<?php
// ======================================================================
//
// AAI LOGIN WITH SHIBBOLETH HANDLING MULTIPLE ORGANIZATIONS
// 
// included functions
//
// License: GNU GPL 3.0
// Source: https://git-repo.iml.unibe.ch/iml-open-source/login-aai
// ======================================================================

// WIP:
// require 'classes/shibd_discofeed.class.php';
// $oD = new shibd_discofeed();
// print_r($oD->getAllIdps());

$SELFURL = isset($_SERVER['SERVER_NAME']) ? "https://" . $_SERVER['SERVER_NAME'] : '';

$url_list = "$SELFURL/Shibboleth.sso/DiscoFeed";
$listcache = "discofeed.json";
$ttlcache = 60 * 10;

// get the user config
if (!file_exists('config.php')) {
    die("ERROR: file config.php does not exist yet.");
}

$aConfig = require 'config.php';

// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------

/**
 * Show a info or error message
 * @param string $sLevel   level: one of "info", "error"
 * @param string $sMessage Message to show
 * @return void
 */
function showMessage(string $sLevel, string $sMessage)
{
    echo "<div class=\"msg $sLevel\">$sMessage</div>";
}

/**
 * Get List if IDPs from cache file if possible or from Shibboleth Disco feed
 * @return array
 */
function getAllIdps(): array
{
    global $listcache, $ttlcache, $url_list, $aConfig;

    if (!file_exists($listcache) || filemtime($listcache) < time() - $ttlcache) {
        // echo "DEBUG: IDP - reading from Shibboleth<br>";
        $aReturn = json_decode(file_get_contents($url_list), 1);

        if ($aReturn && is_array($aReturn)) {
            // echo "DEBUG: IDP - storing cache<br>";
            file_put_contents($listcache, json_encode($aReturn));
        }
    } else {
        // echo "DEBUG: IDP - reading cache<br>";
        $aReturn = json_decode(file_get_contents($listcache), 1);
    }

    return isset($aReturn) && is_array($aReturn) ? $aReturn : [];
}

/**
 * Get list of active IDPs
 * @return mixed
 */
function getIdps()
{
    global $aConfig, $SELFURL;
    $aAllIdps = getAllIdps();

    if (is_array($aAllIdps) && count($aAllIdps)) {
        foreach ($aAllIdps as $aEntry) {
            $sEntityId = $aEntry['entityID'];

            if (in_array($sEntityId, $aConfig['idps'])) {

                $sLabel = $aEntry['DisplayNames'][0]['value'] ?? parse_url($sEntityId, PHP_URL_HOST);
                $sImage = $aEntry['Logos'][1]['value'] ?? ($aEntry['Logos'][0]['value'] ?? '');

                $sUrl = "$SELFURL/Shibboleth.sso/Login?entityID=" . urlencode($sEntityId) . "&target=" . urlencode($SELFURL.$aConfig['return-url']??'');

                $aReturn[] = [
                    'label' => $sLabel,
                    'image' => $sImage,
                    'url' => $sUrl,

                    // for debugging
                    '_entity' => $aEntry
                ];
            }
        }
    }
    return $aReturn;
}

/**
 * Get a list of static links for browsers without javascript
 * @param array $aIdplist
 * @return string
 */
function getStaticlinks($aIdplist){
    $sReturn='';
    foreach ($aIdplist as $aEntry) {
        $sReturn .= '<a href="' . $aEntry['url']. '">' . $aEntry['label'] . '</a><br>' . "\n";
    }
    return $sReturn;

}