Skip to content
Snippets Groups Projects
inc_functions.php 16.39 KiB
<?php

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

  IML DEPLOYMENT

  included functions for the act_*.php files

  ---------------------------------------------------------------------
  2013-11-08  Axel <axel.hahn@iml.unibe.ch>
  ...
  2024-09-03  Axel <axel.hahn@unibe.ch>  php8 only; added variable types; short array syntax
  ###################################################################### */

global $aParams;
$aParams = [];


// 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 (["id"] as $sKey) {
      if (array_key_exists($sKey, $aParams)) {
      $aParams[$sKey]=(int)$aParams[$sKey];
      }
      }
     */

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

/**
 * Get home link as button
 * 
 * @global object $oHtml
 * 
 * @param string $sClass css class for the button; default: "btn btn-default"
 * @return string
 */
function aHome(string $sClass = "btn btn-default"): string
{
    global $oHtml;
    // if (!array_key_exists("prj", $aParams)) return false;
    return $oHtml->getLinkButton([
        'href' => '/deployment/?',
        'icon' => 'overview',
        'class' => $sClass,
        'label' => t("menu-overview"),
    ]);
}

/**
 * Get project Home link as button.
 * It returns false if no project is selected (GET param "prj" is missing)
 * 
 * @global object $oHtml
 * @global array $aParams
 * 
 * @param string $sClass css class for the button; default: "btn btn-default"
 * @return bool|string
 */
function aPrjHome(string $sClass = "btn btn-default"): bool|string
{
    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([
        'href' => '/deployment/' . $aParams["prj"] . '/',
        'icon' => 'project',
        'class' => $sClass,
        'label' => $oPrj->getLabel(),
    ]);
}

/**
 * Get go back link as button
 * 
 * @global object $oHtml
 * 
 * @param string $sClass css class for the button; default: "btn btn-default"
 * @return string
 */
function aGoback(string $sClass = "btn btn-default"): string
{
    global $oHtml;
    return $oHtml->getLinkButton([
        'href' => '#',
        'onclick' => 'history.back();',
        'title' => t("back"),
        'icon' => 'back',
        'class' => $sClass,
        'label' => t("back")
    ]);
}
/**
 * Get go top link as button
 * 
 * @global object $oHtml
 * 
 * @param string $sClass css class for the button; default: "scroll-link btn btn-default"
 * @return string
 */
function aGotop($sClass = "scroll-link btn btn-default"): string
{
    global $oHtml;
    return $oHtml->getLinkButton([
        'href' => '#top',
        'class' => $sClass,
        'title' => t("gotop"),
        'icon' => 'gotop',
        'label' => ' '
    ]);
}

/**
 * Get array for top left navigation.
 * It is an empty array if no authenticated user was found.
 * 
 * @global object $oHtml
 * @global array $aParams
 * 
 * @return array
 */
function getTopNavLeft(): array
{
    global $aParams, $oHtml;
    $aReturn = [];
    require_once("./classes/project.class.php");
    require_once("./classes/user.class.php");
    $oUser = new user();
    $sBaseUrl = '/deployment/';

    $sBaseUrl = '/deployment/';
    $sCurrentProject = (array_key_exists("prj", $aParams) && $aParams["prj"] <> "all") ? $aParams["prj"] : false;
    $sCurrentAction = (array_key_exists("action", $aParams) && $aParams["action"]) ? $aParams["action"] : false;
    $sCurrentPar3 = (array_key_exists("par3", $aParams) && $aParams["par3"]) ? $aParams["par3"] : false;

    // $aReturn[]=['label'=>'=' ];
    $aReturn[] = ['href' => $sBaseUrl . '', 'label' => '&nbsp;Deployment UI <small class="badge bg-info"><nobr>v' . APP_VERSION . '</nobr></small>',    'icon' => '', 'class' => 'imllogo topbrand'];

    if ($oUser->getUsername()) {
        $oPrj1 = new project();
        $aPrjItems = [];
        foreach ($oPrj1->getProjects("label") as $aProject) {
            $aPrjItems[] = [
                'href' => $sBaseUrl . $aProject['id'] . '/',
                'label' => $aProject['label'],
                'class' => $sCurrentProject === $aProject['id'] ? 'active' : '',
                'icon' => $oHtml->getIconClass('project'),
            ];
        }
        /* to test a scrolling menu
        $aPrjItems=array_merge(
            $aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,
            $aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,
            $aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,$aPrjItems,
        );
        */

        $aReturn[] = [
            'href' => $sBaseUrl, 'label' => t("menu"),
            'icon' => $oHtml->getIconClass('menu'),
            'class' => ($sCurrentAction === 'setup' || $sCurrentAction === 'valuestore' ? 'active' : ''),
            'children' => [
                ['href' => $sBaseUrl . 'all/setup/new/',       'label' => t("menu-new-project"), 'icon' => $oHtml->getIconClass('new'),          'class' => ($sCurrentPar3   === 'new'        ? 'active' : ''),],
                ['href' => $sBaseUrl . 'all/setup/actionlog/', 'label' => t("menu-logs"),        'icon' => $oHtml->getIconClass('actionlog'),    'class' => ($sCurrentPar3   === 'actionlog'  ? 'active' : ''),],
                ['href' => $sBaseUrl . 'all/valuestore/',      'label' => t("menu-valuestore"),  'icon' => $oHtml->getIconClass('valuestore'),   'class' => ($sCurrentAction === 'valuestore' ? 'active' : ''),],
                ['href' => $sBaseUrl . 'all/setup/checklang/', 'label' => t("menu-checklang"),   'icon' => $oHtml->getIconClass('comment'),      'class' => ($sCurrentPar3   === 'checklang'  ? 'active' : ''),],
                ['label' => '-'],
                ['href' => $sBaseUrl . 'all/setup/',           'label' => t("menu-settings"),    'icon' => $oHtml->getIconClass('setup')],
            ]
        ];
        if (count($aPrjItems)) {
            $aReturn[] = [
                'href' => '#', 'label' => t("menu-projects"), 'icon' => $oHtml->getIconClass('projects'),
                'children' => $aPrjItems
            ];
        }
        if ($sCurrentProject) {
            $oPrj = new project($aParams["prj"]);
            $aPrjChildren = [
                ['href' => $sBaseUrl . $sCurrentProject . '/', 'label' => t("project-home"), 'icon' => $oHtml->getIconClass('project-home'), 'class' => ($sCurrentAction == '' ? 'active' : '')],
                ['label' => '-'],
            ];
            $aPhases = $oPrj->getActivePhases();
            if (count($aPhases)) {
                $aPrjChildren[] = ['href' => $sBaseUrl . $sCurrentProject . '/build/', 'label' => t("build"), 'icon' => $oHtml->getIconClass('build'), 'class' => ($sCurrentAction === 'build' ? 'active' : '')];
                $aPrjChildren[] = ['label' => '-'];

                foreach ($aPhases as $sPhase) {
                    $aPrjChildren[] = ['href' => $sBaseUrl . $sCurrentProject . '/phase/' . $sPhase . '/', 'label' => $sPhase, 'icon' => $oHtml->getIconClass('phase'), 'class' => (isset($aParams['par3']) && $aParams['par3'] === $sPhase ? 'active' : '')];
                }
                $aPrjChildren[] = ['label' => '-'];
            }
            $aPrjChildren[] = ['href' => $sBaseUrl . $sCurrentProject . '/setup/',   'label' => t("menu-project-settings"), 'icon' => $oHtml->getIconClass('setup'),  'class' => ($sCurrentAction === 'setup'   ? 'active' : '')];
            $aPrjChildren[] = ['label'=> '-'];
            $aPrjChildren[] = ['href' => $sBaseUrl . $sCurrentProject . '/cleanup/', 'label' => t("menu-project-cleanup"),  'icon' => $oHtml->getIconClass('cleanup'), 'class' => ($sCurrentAction === 'cleanup' ? 'active' : '')];
            $aPrjChildren[] = ['href' => $sBaseUrl . $sCurrentProject . '/delete/',  'label' => t("menu-project-delete"),   'icon' => $oHtml->getIconClass('delete'),  'class' => ($sCurrentAction === 'delete'  ? 'active' : '')];

            $aReturn[] = [
                'href' => '#', 'label' => $oPrj->getLabel(), 'icon' => $oHtml->getIconClass('project'), 'class' => 'active',
                'children' => $aPrjChildren
            ];
        }
    }
    // echo '<pre>'.print_r($aReturn, 1); die(__FUNCTION__);
    return $aReturn;
}

/**
 * Get array for top right navigation.
 * 
 * @global object $oHtml
 * @global array $aParams
 * 
 * @return array
 */
function getTopNavRight(): array
{
    global $aParams, $oHtml;
    $aReturn = [];
    require_once("./classes/project.class.php");
    require_once("./classes/user.class.php");
    $oUser = new user();

    $sBaseUrl = '/deployment/';
    $sWikiBaseUrl = 'https://intranet.iml.unibe.ch/wiki/doku.php';
    $sCurrentAction = (array_key_exists("action", $aParams) && $aParams["action"]) ? $aParams["action"] : false;

    if ($oUser->getUsername()) {
        $aReturn = [
            [
                'href' => '#', 'label' => $oUser->getUsername(),    'icon' => $oHtml->getIconClass('user'),
                'class' => ($sCurrentAction == 'login' ? 'active' : ''),
                'children' => [
                    ['href' => $sBaseUrl . 'all/login/',           'label' => t("menu-userprofile"),            'icon' => $oHtml->getIconClass('user-profile'), 'class' => ($sCurrentAction == 'login' ? 'active' : '')],
                ]
            ]
        ];
    } else {
        $aReturn[] = ['href' => $sBaseUrl . 'all/login/',           'label' => t("login"),            'icon' => $oHtml->getIconClass('login'), 'class' => ($sCurrentAction == 'login' ? 'active' : '')];
    }
    $aReturn[] = [
        'href' => '#', 'label' => t('menu-help'), 'icon' => $oHtml->getIconClass('help'), 'class' => '',
        'children' => [
            ['href' => $sWikiBaseUrl . '/it/entwicklung/continuous_deployment',                'target' => '_help', 'label' => 'WIKI: Übersicht Continous Deployment',    'icon' => $oHtml->getIconClass('link-extern')],
            ['href' => $sWikiBaseUrl . '/it/entwicklung/continuous_deployment#konventionen',   'target' => '_help', 'label' => 'WIKI: Konventionen für Entwickler',       'icon' => $oHtml->getIconClass('link-extern')],
            ['href' => $sWikiBaseUrl . '/it/infrastruktur/se/snippets/iml.deployment_profile', 'target' => '_help', 'label' => 'WIKI (Admin): Snippets für den Sysadmin', 'icon' => $oHtml->getIconClass('link-extern')],
            ['href' => $sWikiBaseUrl . '/it/infrastruktur/dienste/imldeployment',              'target' => '_help', 'label' => 'WIKI (Admin): Verzeichnisse und Dateien', 'icon' => $oHtml->getIconClass('link-extern')],
            ['href' => $sBaseUrl . 'all/doc',                                                                       'label' => t('menu-help-classes'),                    'icon' => $oHtml->getIconClass('help')],
            ['label' => '-'],
            ['href' => $sBaseUrl . 'all/about',                                                                     'label' => t('about'),                    'icon' => $oHtml->getIconClass('sign-info')],
        ]
    ];

    // echo '<pre>'.print_r($aReturn, 1); die(__FUNCTION__);
    return $aReturn;
}

/**
 * Gett h2 headline with action
 * 
 * @global array $aParams
 * 
 * @param  string  $sLinkClass  classname for links; default: "" (adds class="btn btn-default")
 * @return string
 */
function getBreadcrumb(string $sLinkClass = ""): string
{
    global $aParams, $oHtml;
    $sReturn = '';
    $sNav = '';
    $sLabel = '';

    $sDelim = '&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;';
    if (array_key_exists("action", $aParams)) {
        $sLabel .= $oHtml->getIcon($aParams["action"]) . t($aParams["action"]);
        $sNav .= aHome($sLinkClass);
        if ($aParams['prj'] === 'all') {
        } else {
            $sNav .= ' ' . $sDelim . aPrjHome($sLinkClass);
        }
        if (array_key_exists("par3", $aParams)) {
            $sLabel = $oHtml->getIcon($aParams["par3"]) . $aParams["par3"];
        }
        // $sReturn.='<h2 class="action ' . $aParams["action"] . '">' . $sLabel . '</h2>';
    } else if (array_key_exists("prj", $aParams)) {
        $sNav .= aHome($sLinkClass);
        $sLabel .= aPrjHome($sLinkClass);
    }
    $sReturn .= ($sNav ? '' . $sNav .  ' ' . $sDelim . ' <span class="current">' . $sLabel . '</span>' : '');
    if ($sLinkClass) {
        $sReturn = str_replace(['btn-default ', 'btn '], ['', ''], $sReturn);
    }
    return $sReturn;
}

/**
 * Get version info by detecting a json file in approot 
 * @return string
 */
function getVersioninfo(): string
{
    $sMyRev = "";

    $aFiles = glob(dirname(dirname(__DIR__)) . "/*.json");
    if (isset($aFiles[0])) {
        $aJson = json_decode(file_get_contents($aFiles[0]), true);
        $sMyRev = (isset($aJson["branch"]) ? $aJson["branch"] . ' - ' : '')
            . (isset($aJson["date"]) ? $aJson["date"] : '');
    }
    return ($sMyRev  ? $sMyRev . ' @ ' : '') . php_uname("n");
}

/**
 * translate function. Get translated text by given key.
 * 
 * @global array $aConfig
 * @staticvar array $aLang
 * 
 * @param string $s text
 * @return string
 */
function t(string $s): string
{
    global $aConfig;
    static $aLang = [];

    if (!isset($aConfig["lang"])) {
        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];
}

/**
 * Get html code for a form to enter user and comment 
 * 
 * @global array $aParams
 * 
 * @return string The HTML code
 */
function enterDeployinfos(): string
{
    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;
}