/**
  * Load entities that user has access to
  *
  * @return bool True on success and false on error.
  * @since Method available since Release 1.0.0
  * @throws Exception if loading fails
  */
 private function _loadEntities($state = null, $state_exclude = null, $sort = null, $order = null)
 {
     $orderBySQL = ';';
     $queryData = array();
     if ($sort == "created") {
         $sortfield = 'ENTITY.`created` AS `orderfield`';
     } else {
         if ($sort == 'name') {
             $sortfield = 'IFNULL(METADATA.`value`, ENTITY.`entityid`) AS `orderfield`';
         } else {
             $sortfield = 'IFNULL(METADATA.`value`, ENTITY.`entityid`) AS `orderfield`';
         }
     }
     if ($order == "ASC") {
         $orderfield = 'ASC';
     } else {
         if ($order == 'DESC') {
             $orderfield = 'DESC';
         } else {
             $orderfield = 'ASC';
         }
     }
     // Select entity (only last revision)
     $query = "\n            SELECT      DISTINCT ENTITY.eid, \n            " . $sortfield . "\n            FROM        " . self::$prefix . "entity   AS ENTITY";
     $whereClauses[] = "ENTITY.revisionid = (\n                SELECT      MAX(revisionid)\n                FROM        " . self::$prefix . "entity\n                WHERE       eid = ENTITY.eid\n                GROUP BY    eid\n            )";
     // Filter out entities that are not allowed
     $guard = new sspmod_janus_UIguard($this->_config->getArray('access', array()));
     $allowAllEntities = $guard->hasPermission('allentities', null, $this->_user->getType(), TRUE);
     if (!$allowAllEntities) {
         $query .= "\n            INNER JOIN janus__hasEntity AS hasentity\n                ON     hasentity.eid = ENTITY.eid\n                AND    hasentity.uid = :uid\n            ";
         $queryData['uid'] = $this->_user->getUid();
     }
     // Include given state
     if (!is_null($state)) {
         $whereClauses[] = "ENTITY.state = :state ";
         $queryData['state'] = $state;
     }
     // Exclude given state
     if (!is_null($state_exclude)) {
         $whereClauses[] = "ENTITY.`state` <> :state_exclude";
         $queryData['state_exclude'] = $state_exclude;
     }
     // Find default value for sort field so it can be excluded
     $sortFieldName = $this->_config->getString('entity.prettyname', NULL);
     $queryData['default_value'] = '';
     if ($sortFieldDefaultValue = $this->_config->getArray('metadatafields.saml20-idp', FALSE)) {
         if (isset($sortFieldDefaultValue[$sortFieldName])) {
             $queryData['default_value'] = $sortFieldDefaultValue[$sortFieldName]['default'];
         }
     } else {
         if ($sortFieldDefaultValue = $this->_config->getArray('metadatafields.saml20-sp', FALSE)) {
             if (isset($sortFieldDefaultValue[$sortFieldName])) {
                 $queryData['default_value'] = $sortFieldDefaultValue[$sortFieldName]['default'];
             }
         }
     }
     // Try to sort results by pretty name from metadata
     if ($sortFieldName) {
         $query .= "\n            LEFT JOIN   " . self::$prefix . "metadata AS METADATA\n                ON METADATA.key = :metadata_key\n                AND METADATA.eid = ENTITY.eid\n                AND METADATA.revisionid = ENTITY.revisionid\n                AND METADATA.value != :default_value";
         $queryData['metadata_key'] = $sortFieldName;
         $orderBySQL = "\nORDER BY `orderfield` " . $orderfield . ";";
     }
     $query .= " WHERE " . implode("\nAND ", $whereClauses);
     $query .= $orderBySQL;
     $st = $this->execute($query, $queryData);
     if ($st === false) {
         throw new exception('Entities could not be loaded');
     }
     $this->_entities = array();
     $rs = $st->fetchAll(PDO::FETCH_ASSOC);
     foreach ($rs as $row) {
         $entity = new sspmod_janus_Entity($this->_config);
         $entity->setEid($row['eid']);
         if (!is_null($state)) {
             $entity->setWorkflow($state);
         }
         if ($entity->load()) {
             $this->_entities[] = $entity;
         } else {
             SimpleSAML_Logger::error('JANUS:UserController:_loadEntities - Entity could not be
                 loaded: ' . var_export($row, true));
         }
     }
     return true;
 }
}
// Revisin id has been set. Fetch the correct version of the entity
if ($revisionid > -1) {
    if (!($entity = $mcontroller->setEntity($eid, $revisionid))) {
        throw new SimpleSAML_Error_Exception('Error in setEntity');
    }
} else {
    // Revision not set, get latest
    if (!($entity = $mcontroller->setEntity($eid))) {
        throw new SimpleSAML_Error_Exception('Error in setEntity');
    }
}
// load entity
$mcontroller->loadEntity();
// Check if user is allowed to se entity
$guard = new sspmod_janus_UIguard($janus_config->getArray('access', array()));
$allowedUsers = $mcontroller->getUsers();
if (!(array_key_exists($userid, $allowedUsers) || $guard->hasPermission('allentities', null, $user->getType(), TRUE))) {
    SimpleSAML_Utilities::redirect(SimpleSAML_Module::getModuleURL('janus/index.php'));
}
$et = new SimpleSAML_XHTML_Template($config, 'janus:editentity.php', 'janus:editentity');
$language = $et->getLanguage();
$update = FALSE;
$note = '';
if (!empty($_POST)) {
    // Array for collecting addresses to notify
    $addresses = array();
    // Change entityID
    if (isset($_POST['entityid']) && $guard->hasPermission('changeentityid', $entity->getWorkflow(), $user->getType())) {
        if (check_uri($_POST['entityid']) || true) {
            # HACK: For SURFnetGuests : https://espee-test.surfnet.nl/federate/metadata/saml20/SURFnetGuests
 public function testHasPermission()
 {
     $permissionmatrix = array('permission1' => array('default' => FALSE, 'test' => array('role' => array('admin'))));
     $uig = new sspmod_janus_UIguard($permissionmatrix);
     $this->assertTrue($uig->hasPermission('permission1', 'test', array('admin')));
 }
$mcontroller = new sspmod_janus_EntityController($janus_config);
// Get the user
$user = new sspmod_janus_User($janus_config->getValue('store'));
$user->setUserid($userid);
$user->load(sspmod_janus_User::USERID_LOAD);
// Get the correct entity
$eid = $_GET['eid'];
if (!($entity = $mcontroller->setEntity($eid))) {
    throw new SimpleSAML_Error_Exception('Error in setEntity');
}
$workflowstates = $janus_config->getValue('workflowstates');
// load entity
$mcontroller->loadEntity();
// Check if user is allowed to se entity
$allowedUsers = $mcontroller->getUsers();
$uiguard = new sspmod_janus_UIguard($janus_config->getValue('access'));
$output = '';
$wfstate = $entity->getWorkflow();
if ((array_key_exists($userid, $allowedUsers) || $uiguard->hasPermission('allentities', null, $user->getType(), true)) && $uiguard->hasPermission('entityhistory', $wfstate, $user->getType())) {
    $history_size = $mcontroller->getHistorySize();
    $history = $mcontroller->getHistory(10, $history_size);
    foreach ($history as $data) {
        $rid = $data->getRevisionid();
        $rnote = $data->getRevisionnote();
        $output .= '<a href="?eid=' . $data->getEid() . '&revisionid=' . $rid . '">' . $et->t('tab_edit_entity_connection_revision') . ' ' . $rid . '</a>';
        $output .= strlen($rnote) > 80 ? ' - ' . substr($rnote, 0, 79) . '...' : ' - ' . $rnote;
        // Show edit user if present
        $user->setUid($data->getUser());
        if ($user->load()) {
            $output .= ' - ' . $user->getUserid();
        }