<?php

/* ######################################################################

  IML DEPLOYMENT

  included functions for the act_*.php files

  ---------------------------------------------------------------------
  2013-11-08  Axel <axel.hahn@iml.unibe.ch>
  ###################################################################### */

global $aParams;
$aParams = array();


// ----------------------------------------------------------------------
// verifiy config
// ----------------------------------------------------------------------
    $aErrors=array();
    if (!isset($aConfig) || !is_array($aConfig)) {
        $aErrors[]="* \$aConfig does not exist. The config was not included before including " . __FILE__ . " in the request/ script.\n";
    } else {

        foreach (array(
            'appRootDir', 
            'configDir', 
            'workDir',
            'dataDir',
            'buildDir',
            'buildDefaultsDir',
            'packageDir',
            'archiveDir',
            ) as $sKey){
            if (!is_dir($aConfig[$sKey])){
                $aErrors[]="* \$aConfig['$sKey'] points to a non existing directory (".$aConfig[$sKey].").\n";
            } else {
                if (!is_writable($aConfig[$sKey])){
                    $aErrors[]="* \$aConfig['$sKey'] = ".$aConfig[$sKey]." is NOT writable.\n";
                }
            }
        }
    }
    foreach (array(
        $aConfig['dataDir'].'/database', 
        $aConfig['dataDir'].'/projects', 
        $aConfig['dataDir'].'/sshkeys', 
        ) as $sDir2Check){
        if (!is_dir($sDir2Check)){
            $aErrors[]="* directory not found: $sDir2Check\n";
        } else {
            if (!is_writable($sDir2Check)){
                $aErrors[]="* $sDir2Check is NOT writable.\n";
            }
        }
    }

    // check required keys in the config
    foreach (array(
        'auth',
        'hooks',
        'installPackages',
        'lang',
        'phases',
        'projects',
    ) as $sKey){
        if (!array_key_exists($sKey, $aConfig)){
            $aErrors[]="* missing key directory [$sKey] in config\n";
        }
    }

    if (count($aErrors)){
        die("FATAL ERROR on config.<br>" . implode("<br>\n", $aErrors));
    }


// remark: $_SERVER does not exist in CLI
if (isset($_SERVER) && is_array($_SERVER) && array_key_exists("REQUEST_URI", $_SERVER)) {
    /*
      print_r($_GET);
      print_r($_POST);
      print_r($aParams);
      print_r($_SERVER);
      echo $_SERVER["REQUEST_URI"];
     */
    $aTmp = preg_split("#/#", $_SERVER["REQUEST_URI"]);
    if (count($aTmp) > 1 && $aTmp[1] == "deployment" && $aTmp[2] != "?") {
        array_shift($aTmp);
        array_shift($aTmp);
        if (
                count($aTmp) && $aTmp[count($aTmp) - 1] && $aTmp[count($aTmp) - 1][0] == "?"
        ) {
            array_pop($aTmp);
        }
        if (count($aTmp) && $aTmp[0])
            $aParams["prj"] = $aTmp[0];
        if (count($aTmp) > 1 && $aTmp[1])
            $aParams["action"] = $aTmp[1];
        if (count($aTmp) > 2 && $aTmp[2])
            $aParams["par3"] = $aTmp[2];
        if (count($aTmp) > 3 && $aTmp[3])
            $aParams["par4"] = $aTmp[3];
    }
    if (count($_GET))
        foreach ($_GET as $key => $value)
            $aParams[$key] = $value;
    if (count($_POST))
        foreach ($_POST as $key => $value)
            $aParams[$key] = $value;

    /* force integer params
      foreach (array("id") as $sKey) {
      if (array_key_exists($sKey, $aParams)) {
      $aParams[$sKey]=(int)$aParams[$sKey];
      }
      }
     */

    foreach (array_keys($aParams) as $sKey) {
        $aParams[$sKey] = str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $aParams[$sKey]);
    }
}

/**
 * get home link as button
 * @return string
 */
function aHome($sClass = "btn btn-default") {
    global $oHtml;
    // if (!array_key_exists("prj", $aParams)) return false;
    return $oHtml->getLinkButton(array(
        'href'=>'/deployment/?',
        'icon'=>'overview',
        'label'=>t("menu-overview"),
    ));
}

/**
 * get project Home link as button
 * @return string
 */
function aPrjHome($sClass = "btn btn-default") {
    global $aParams, $oHtml;
    if (!array_key_exists("prj", $aParams)){
        return false;
    }
    if ($aParams["prj"] == "all"){
        return aHome($sClass);
    }
    // if (!array_key_exists("action", $aParams)) return false;

    require_once("./classes/project.class.php");
    $oPrj = new project($aParams["prj"]);
    return $oHtml->getLinkButton(array(
        'href'=>'/deployment/' . $aParams["prj"] . '/',
        'icon'=>'project-home',
        'label'=>$oPrj->getLabel(),
    ));
}

/**
 * get go back link as button
 * @return string
 */
function aGoback($sClass = "btn btn-default") {
    global $oHtml;
    return $oHtml->getLinkButton(array(
        'href'=>'#',
        'onclick'=>'history.back();',
        'title'=>t("back"),
        'icon'=>'back',
        'label'=>t("back")
    ));
}
/**
 * get go top link as button
 * @return string
 */
function aGotop($sClass = "scroll-link btn btn-default") {
    global $oHtml;
    return $oHtml->getLinkButton(array(
        'href'=>'#top',
        'class'=>$sClass,
        'title'=>t("gotop"),
        'icon'=>'glyphicon-eject',
        'label'=>' '
    ));
}

/**
 * auto generate upper part of the page with header and navigation 
 * @global type $aParams
 * @return type
 */
function getTopArea() {
    global $aParams, $oHtml;
    $sReturn = '';
    require_once("./classes/project.class.php");
    require_once("./classes/user.class.php");
    $oUser = new user();

    $sMyPhase = "[phase]";
    $sMyRev = " [no rev] ";
    // bug#1511 json file was moved 1 level up
    $sJsonfile = __DIR__ . "/../../ci-webgui.json";
    if (file_exists($sJsonfile)) {
        $aJson = json_decode(file_get_contents($sJsonfile), true);
        if (array_key_exists("date", $aJson))
            $sMyRev = $aJson["date"];
    }

    $sBaseUrl = '/deployment/';
    $sWikiBaseUrl = 'https://intranet.iml.unibe.ch/wiki/doku.php';
    $sReturn = '
        <span id="top"></span>
        <nav class="navbar navbar-inverse" role="navigation">
          <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class=" glyphicon glyphicon-bar"></span>
                <span class=" glyphicon glyphicon-bar"></span>
                <span class=" glyphicon glyphicon-bar"></span>
              </button>
              <nobr>
                <a class="navbar-brand" href="' . $sBaseUrl . '"><span class="imllogo"></span> '.t("menu-brand").'</a>
                <span class="badge"></span>
              </nobr>
              &nbsp;&nbsp;&nbsp;
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            ';
    if($oUser->getUsername()){
        $sReturn.='
              <ul class="nav navbar-nav">
              
                <li class="dropdown';
                if (array_key_exists("prj", $aParams) && $aParams['prj']==='all'){
                    $sReturn.=' active';
                }
                $sReturn.='">'
                        . $oHtml->getLink(array(
                            'href'=>$sBaseUrl,
                            'class'=>'dropdown-toggle',
                            'data-toggle'=>'dropdown',
                            'role'=>'button',
                            'aria-expanded'=>'false',
                            'icon'=>'menu',
                            'label'=>t("menu").' <span class="caret"></span>',
                        ))
                  .'<ul class="dropdown-menu" role="menu">
                    <li>'.$oHtml->getLink(array(
                            'href'=>$sBaseUrl . 'all/setup/new/',
                            'icon'=>'new',
                            'label'=>t("menu-new-project"),
                        )).'</li>
                    <li>'.$oHtml->getLink(array(
                            'href'=>$sBaseUrl . 'all/setup/actionlog/',
                            'icon'=>'actionlog',
                            'label'=>t("menu-logs"),
                        )).'</li>
                    <li>'.$oHtml->getLink(array(
                            'href'=>$sBaseUrl . 'all/setup/checklang/',
                            'icon'=>'checklang',
                            'label'=>t("menu-checklang"),
                        )).'</li>
                    <li>'.$oHtml->getLink(array(
                            'href'=>$sBaseUrl . 'all/setup/',
                            'icon'=>'setup',
                            'label'=>t("menu-settings"),
                        )).'</li>
                  </ul>
                </li>
                

                <li class="dropdown">'
                    . $oHtml->getLink(array(
                        'href'=>'#',
                        'class'=>'dropdown-toggle',
                        'data-toggle'=>'dropdown',
                        'role'=>'button',
                        'aria-expanded'=>'false',
                        'icon'=>'projects',
                        'label'=>t("menu-projects") . ' <span class="caret"></span>',
                    ))
                    .'<ul class="dropdown-menu" role="menu">'
                    ;
                
                    $oPrj1 = new project();
                    foreach ($oPrj1->getProjects() as $sPrj) {
                        $oPrj = new project($sPrj);
                        $sReturn.='<li>'
                                . $oHtml->getLink(array(
                                    'href'=>$sBaseUrl . $sPrj .'/',
                                    'icon'=>'project',
                                    'label'=>$oPrj->getLabel(),
                                ))
                                . '</li>';
                    }
                    $sReturn.='
                  </ul>
                </li>
              ';

                if (array_key_exists("prj", $aParams) && $aParams["prj"] <> "all") {
                    $oPrj = new project($aParams["prj"]);
                    $sReturn.='
                    <li class="dropdown active">'
                        .$oHtml->getLink(array(
                            'href'=>'#',
                            'class'=>'dropdown-toggle',
                            'data-toggle'=>'dropdown',
                            'role'=>'button',
                            'aria-expanded'=>'false',
                            'icon'=>'project',
                            'label'=>$oPrj->getLabel() .' <span class="caret"></span>',
                        ))
                        .'
                        <ul class="dropdown-menu" role="menu">
                            <li>'
                            . $oHtml->getLink(array(
                                'href'=>$sBaseUrl . $sPrj .'/',
                                'icon'=>'project-home',
                                'label'=>t("project-home"),
                            ))
                            .'</li>
                        ';
                        $aPhases = $oPrj->getActivePhases();
                        if (count($aPhases)) {
                            $sReturn.='<li role="separator" class="divider"></li>
                                    <li>'
                                    .$oHtml->getLink(array(
                                        'href'=>$sBaseUrl . $aParams["prj"] . '/build/',
                                        'icon'=>'build',
                                        'label'=>t("build"),
                                    ))
                                    .'</li> 
                                    <li role="separator" class="divider"></li>
                                    <li class="dropdown-header">'.t("menu-project-phases").'</li>';
                            foreach ($aPhases as $sPhase) {
                                $sReturn.='<li><a href="' . $sBaseUrl . $aParams["prj"] . '/phase/' . $sPhase . '/">' . $oHtml->getIcon('phase').$sPhase . '</a></li>';
                            }
                        }
                        $sReturn.='
                            <li role="separator" class="divider"></li>
                            <li>'
                            .$oHtml->getLink(array(
                                'href'=>$sBaseUrl . $aParams["prj"] . '/setup/',
                                'icon'=>'setup',
                                'label'=>t("menu-project-settings"),
                            ))
                            .'</li> 
                            <li>'
                            .$oHtml->getLink(array(
                                'href'=>$sBaseUrl . $aParams["prj"] . '/cleanup/',
                                'icon'=>'cleanup',
                                'label'=>t("menu-project-cleanup"),
                            ))
                            .'</li> 
                            <li>'
                            .$oHtml->getLink(array(
                                'href'=>$sBaseUrl . $aParams["prj"] . '/delete/',
                                'icon'=>'delete',
                                'label'=>t("menu-project-delete"),
                            ))
                            .'</li> 
                        </ul></li>';
                }
    }
                    
            $sReturn.='
              </ul>
            
            <ul class="nav navbar-nav navbar-right">'
                . ($oUser->getUsername() 
                    ? '
                    <!-- userdata -->
                    <li class="dropdown">'
                        .$oHtml->getLink(array(
                            'href'=>'#',
                            'class'=>'dropdown-toggle',
                            'data-toggle'=>'dropdown',
                            'role'=>'button',
                            'aria-expanded'=>'false',
                            'icon'=>'user',
                            'label'=>$oUser->getUsername() .' <span class="caret"></span>',
                        ))
                        .'<ul class="dropdown-menu" role="menu">
                            <li>'
                            .$oHtml->getLink(array(
                                'href'=>$sBaseUrl . 'all/login/',
                                'icon'=>'login',
                                'label'=>t("menu-login"),
                            ))
                            .'</li> 
                        </ul>
                    </li>'
                        
                    : '<li>'
                        .$oHtml->getLink(array(
                            'href'=>$sBaseUrl . 'all/login/',
                            'icon'=>'login',
                            'label'=>t("login"),
                        ))
                      .'</li>'
                )
                .'<li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
                        ><span class="glyphicon glyphicon-question-sign"></span> ' . t("menu-help") . ' <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="' . $sWikiBaseUrl . '/it/entwicklung/continuous_deployment">WIKI: Übersicht Continous Deployment</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/entwicklung/continuous_deployment#konventionen">WIKI: Konventionen für Entwickler</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/infrastruktur/dienste/puppet/snippets#iml-deployment">WIKI (Admin): Puppet-Snippets für den Sysadmin</a></li>
                            <li><a href="' . $sWikiBaseUrl . '/it/infrastruktur/dienste/imldeployment">WIKI (Admin): Verzeichnisse und Dateien</a></li>
                            <li><a href="/deployment/all/doc/">' . t("menu-help-classes") . '</a></li>
                        </ul>
                    </li>
            </ul>
            </div><!-- /.navbar-collapse -->
          </div><!-- /.container-fluid -->
        </nav>    
         
          <span id="swversion">' . $sMyRev . ' @ ' . php_uname("n") . '</span>
        </div><div id="header2">';

    if (!array_key_exists("prj", $aParams)) {
        $sReturn.='<h1>' . t("overview-label") . '</h1><span class="description">' . t("overview-hint") . '</span>';
    } else {
        if ($aParams["prj"] <> "all") {
            $oPrj = new project($aParams["prj"]);
            $sReturn.='<h1>' . $oPrj->getLabel() . '</h1>'
                    . '<span class="description">' . $oPrj->getDescription() . '</span>';
            if (array_key_exists("action", $aParams)) {
                // $sReturn.='<h2>Aktion: '.$aParams["action"].'</h2>';
            }
        }
    }
    $sReturn.='</div>';

    return $sReturn;
}

/**
 * get h2 headline with action
 * @global type $aParams
 * @return string
 */
function getAction() {
    global $aParams, $oHtml;
    $sReturn = '';
    $sNav = '';
    $sLabel = '';
    // $sDelim=$oHtml->getIcon('fa-chevron-right');
    $sDelim=' / ';
    if (array_key_exists("action", $aParams)) {
        $sLabel .= $oHtml->getIcon($aParams["action"]).t($aParams["action"]);
        $sNav .= aHome();
        if ($aParams['prj']==='all'){
            // $sNav .= ' ' . $oHtml->getIcon('fa-chevron-right') . '[ci-GUI]';
        } else {
            $sNav .= ' ' . $sDelim . aPrjHome();
        }
        $sClass='action '.$aParams["action"];
        if (array_key_exists("par3", $aParams)) {
            $sLabel.=' :: ' . $oHtml->getIcon($aParams["par3"]). $aParams["par3"];
            $sClass='action ' . $aParams["action"];
        }
        // $sReturn.='<h2 class="action ' . $aParams["action"] . '">' . $sLabel . '</h2>';
    } else if (array_key_exists("prj", $aParams)) {
        $sNav .= aHome();
        $sClass='action prjhome';
        $sLabel.=$oHtml->getIcon('project-home').t('project-home');
        // $sReturn.='<h2 class="action prjhome"> Projekt-Home</h2>';
    }
    $sReturn.=($sNav ? '<div id="navtop">' . $sNav .  ' ' . $sDelim . ' <span class="current">'.$sLabel.'</span></div>':'')
        // .'<h2 class="'.$sClass.'"> '.$sLabel.'</h2>'
        ;
    return $sReturn;
}

/**
 * translate function
 * @global type $aConfig
 * @staticvar array $aLang
 * @param string $s text
 * @return string
 */
function t($s) {
    global $aConfig;
    static $aLang = array();

    if (!is_array($aConfig) || !array_key_exists("lang", $aConfig)) {
        die("ERROR: \$aConfig[\"lang\"] does not exist.\n");
    }
    if (!count($aLang)) {
        $sLangfile = __DIR__ . "/../../config/lang/" . $aConfig["lang"] . ".json";
        if (!file_exists($sLangfile)) {
            die("language file was not found: $sLangfile");
        }
        $aLang = json_decode(file_get_contents($sLangfile), true);
    }

    if (!array_key_exists($s, $aLang)) {
        return '<span class="warning">' . $s . '</span>';
    }
    // return $aLang[$s].' ('.$s.')';
    return $aLang[$s];
}

/**
 * enter user and comment 
 * @global type $aParams
 * @return string
 */
function enterDeployinfos() {
    global $aParams;
    $sIdUser = "inputUser";
    $sIdComment = "inputComment";
    $sUser = (array_key_exists($sIdUser, $aParams)) ? $aParams[$sIdUser] : "";
    $sComment = (array_key_exists($sIdComment, $aParams)) ? $aParams[$sIdComment] : "";

    $sOut = '
        <div class="control-group">
            <label class="control-label" for="inputUser">Benutzername</label>
            <div class="controls">
                <input type="text" id="inputUser" name="inputUser" placeholder="Benutzername" value="' . $sUser . '">
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="inputComment">Kommentar zum Deployment</label>
            <div class="controls">
                <textarea id= rows="3" id="inputComment" name="inputComment" placeholder="Kommentar">' . $sComment . '</textarea>
            </div>
        </div>
        ';

    return $sOut;
}
