protected function _loadEntityMetadata($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     $this->_entityMetadata = $entityController->getMetaArray();
 }
 protected function _loadEntity($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     $this->_entityController = $entityController;
     return $entityController ? true : false;
 }
 protected function _loadEntityCertificate($entityId)
 {
     $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
     $entityController = new sspmod_janus_EntityController($janusConfig);
     $entityController->setEntity($entityId);
     $entityController->loadEntity();
     try {
         $certificate = $entityController->getCertificate();
     } catch (Exception $e) {
         $this->_response->Errors[] = "Certificate data invalid!";
         return false;
     }
     if (!$certificate) {
         $this->_response->Warnings[] = "No certificate data for this entity";
         return false;
     }
     $this->_certificate = $certificate;
     return true;
 }
 $entityid = $entity->item(0)->getAttribute('entityID');
 $query = '/md:EntityDescriptor/md:SPSSODescriptor';
 $sp = $xpath->query($query);
 if ($sp->length > 0) {
     $type = 'saml20-sp';
 }
 $query = '/md:EntityDescriptor/md:IDPSSODescriptor';
 $idp = $xpath->query($query);
 if ($idp->length > 0) {
     $type = 'saml20-idp';
 }
 $msg = $mcontrol->createNewEntity($entityid, $type);
 if (is_int($msg)) {
     $econtroller = new sspmod_janus_EntityController($janus_config);
     $econtroller->setEntity((string) $msg);
     $econtroller->loadEntity();
     $pm->subscribe($user->getUid(), 'ENTITYUPDATE-' . $msg);
     $directlink = SimpleSAML_Module::getModuleURL('janus/editentity.php', array('eid' => $msg));
     $pm->post('New entity created', 'Permalink: <a href="' . $directlink . '">' . $directlink . '</a><br /><br />A new entity has been created.<br />Entityid: ' . $_POST['entityid'] . '<br />Entity type: ' . $_POST['entitytype'], 'ENTITYCREATE', $user->getUid());
     $msg = 'text_entity_created';
     if ($type == 'saml20-sp') {
         $msg = $econtroller->importMetadata20SP($_POST['metadata_xml'], $update);
     } else {
         if ($type == 'saml20-idp') {
             $msg = $econtroller->importMetadata20IdP($_POST['metadata_xml'], $update);
         } else {
             $msg = 'error_metadata_not_import';
         }
     }
     $econtroller->saveEntity();
     SimpleSAML_Utilities::redirect(SimpleSAML_Utilities::selfURLNoQuery(), array('selectedtab' => $selectedtab));
$session = SimpleSAML_Session::getInstance();
$janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
$authSource = $janusConfig->getValue('auth', 'login-admin');
// Validate user
if (!$session->isValid($authSource)) {
    SimpleSAML_Utilities::redirect(SimpleSAML_Module::getModuleURL('janus/index.php', array('selectedtab' => "'federation'")));
}
$entities = array();
$util = new sspmod_janus_AdminUtil();
$userController = new sspmod_janus_UserController($janusConfig);
$entities = array_merge($userController->searchEntitiesByType('saml20-idp'), $userController->searchEntitiesByType('saml20-sp'));
foreach ($entities as $entity) {
    /**
     * @var sspmod_janus_Entity $entity
     */
    $entityId = $entity->getEid();
    $entityController = new sspmod_janus_EntityController($janusConfig);
    $entityController->setEntity($entityId);
    $entityController->loadEntity();
    $controllerEntity = $entityController->getEntity();
    $entityType = $controllerEntity->getType();
    if (!isset($entities[$entityType])) {
        $entities[$entityType] = array();
    }
    $entities_info[$entityType][] = array('Id' => $controllerEntity->getEntityid(), 'Name' => $controllerEntity->getPrettyname(), 'WorkflowStatus' => $controllerEntity->getWorkflow(), 'MetadataUrl' => $controllerEntity->getMetadataURL(), 'Eid' => $controllerEntity->getEid());
}
ksort($entities_info);
$template = new SimpleSAML_XHTML_Template(SimpleSAML_Configuration::getInstance(), 'janus:show-entities-validation.php', 'janus:show-entities-validation');
$template->data['header'] = "Service Registry JANUS entities validation";
$template->data['entities'] = $entities_info;
$template->show();
 public function runForCronTag($cronTag)
 {
     if (!$this->_isExecuteRequired($cronTag)) {
         return array("Not doing metadata_refresh");
     }
     $cronLogger = new sspmod_janus_Cron_Logger();
     try {
         $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $util = new sspmod_janus_AdminUtil();
         $entities = $util->getEntities();
         foreach ($entities as $partialEntity) {
             $entityController = new sspmod_janus_EntityController($janusConfig);
             $eid = $partialEntity['eid'];
             if (!$entityController->setEntity($eid)) {
                 $cronLogger->with($eid)->error("Failed import of entity. Wrong eid '{$eid}'.");
                 continue;
             }
             $entityController->loadEntity();
             $entity = $entityController->getEntity();
             $entityId = $entity->getEntityId();
             $metadataUrl = $entity->getMetadataURL();
             $metadataCachingInfo = $entityController->getMetadataCaching();
             if (empty($metadataUrl)) {
                 $cronLogger->with($entityId)->warn("No metadata url.");
                 continue;
             }
             $nextRun = time();
             switch ($cronTag) {
                 case 'hourly':
                     $nextRun += 3600;
                     break;
                 case 'daily':
                     $nextRun += 24 * 60 * 60;
                     break;
                 case 'frequent':
                     $nextRun += 0;
                     // How often is frequent?
                     break;
                 default:
                     throw new Exception("Unknown cron tag '{$cronTag}'");
             }
             if ($metadataCachingInfo['validUntil'] > $nextRun && $metadataCachingInfo['cacheUntil'] > $nextRun) {
                 $cronLogger->with($entityId)->notice("Should not update, cache still valid.");
                 continue;
             }
             $xml = @file_get_contents($metadataUrl);
             if (!$xml) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Bad URL '{$metadataUrl}'? ");
                 continue;
             }
             $document = new DOMDocument();
             if (!@$document->loadXML($xml)) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Invalid XML at '{$metadataUrl}'?");
                 continue;
             }
             $query = new DOMXPath($document);
             $nsFound = false;
             foreach ($query->query('namespace::*') as $node) {
                 if ($node->nodeValue === "urn:oasis:names:tc:SAML:2.0:metadata") {
                     $nsFound = true;
                     break;
                 }
             }
             if (!$nsFound) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Metadata at '{$metadataUrl}' does not contain SAML2 Metadata namespace?");
                 continue;
             }
             $query->registerNamespace('md', "urn:oasis:names:tc:SAML:2.0:metadata");
             $entityDescriptorDomElement = $query->query("//md:EntityDescriptor[@entityID=\"{$entityId}\"]");
             if ($entityDescriptorDomElement->length === 0) {
                 $cronLogger->with($entityId)->error("Failed import of entity. Metadata at '{$metadataUrl}' does not contain an EntityDescriptor with entityId '{$entityId}'?");
                 continue;
             }
             $updated = false;
             if ($entity->getType() == 'saml20-sp') {
                 $statusCode = $entityController->importMetadata20SP($xml, $updated);
                 if ($statusCode !== 'status_metadata_parsed_ok') {
                     $cronLogger->with($entityId)->error("Entity not updated");
                 }
             } else {
                 if ($entity->getType() == 'saml20-idp') {
                     $statusCode = $entityController->importMetadata20IdP($xml, $updated);
                     if ($statusCode !== 'status_metadata_parsed_ok') {
                         $cronLogger->with($entityId)->error("Entity not updated");
                     }
                 } else {
                     $cronLogger->with($entityId)->error("Failed import of entity. Wrong type");
                 }
             }
             if ($updated) {
                 $this->_mailUpdatedMetaData($entity, $xml);
                 $cronLogger->with($entityId)->notice("Entity updated");
                 $metadataCachingInfo = $this->_getMetaDataCachingInfo($xml, $entityId);
                 $entityController->setMetadataCaching($metadataCachingInfo['validUntil'], $metadataCachingInfo['cacheUntil']);
             } else {
                 $cronLogger->with($entityId)->notice("Entity not updated, no changes required");
                 // Update metadata caching info (validUntil )
                 $metadataCachingInfo = $this->_getMetaDataCachingInfo($xml, $entityId);
                 $entityController->setMetadataCaching($metadataCachingInfo['validUntil'], $metadataCachingInfo['cacheUntil']);
             }
         }
     } catch (Exception $e) {
         $cronLogger->error($e->getMessage());
     }
     if ($cronLogger->hasErrors()) {
         $this->_mailTechnicalContact($cronTag, $cronLogger);
     }
     return $cronLogger->getSummaryLines();
 }
 public function runForCronTag($cronTag)
 {
     if (!$this->_isExecuteRequired($cronTag)) {
         return array();
     }
     $cronLogger = new sspmod_janus_Cron_Logger();
     try {
         $janusConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $srConfig = SimpleSAML_Configuration::getConfig('module_janus.php');
         $rootCertificatesFile = $srConfig->getString('ca_bundle_file');
         $util = new sspmod_janus_AdminUtil();
         $entities = $util->getEntities();
         foreach ($entities as $partialEntity) {
             try {
                 $entityController = new sspmod_janus_EntityController($janusConfig);
                 $eid = $partialEntity['eid'];
                 if (!$entityController->setEntity($eid)) {
                     $cronLogger->with($eid)->error("Failed import of entity. Wrong eid '{$eid}'.");
                     continue;
                 }
                 $entityController->loadEntity();
                 $entityId = $entityController->getEntity()->getEntityid();
                 $entityType = $entityController->getEntity()->getType();
                 try {
                     try {
                         $certificate = $entityController->getCertificate();
                         // @workaround
                         // Since getCertificate() returns false when certificate does not exist following check is required to skip validation
                         if (empty($certificate)) {
                             throw new Exception('No certificate found');
                         }
                     } catch (Exception $e) {
                         if ($entityType === 'saml20-sp') {
                             $cronLogger->with($entityId)->notice("SP does not have a certificate");
                         } else {
                             if ($entityType === 'saml20-idp') {
                                 $cronLogger->with($entityId)->warn("Unable to create certificate object, certData missing?");
                             }
                         }
                         continue;
                     }
                     $validator = new sspmod_janus_OpenSsl_Certificate_Validator($certificate);
                     $validator->setIgnoreSelfSigned(true);
                     $validator->validate();
                     $validatorWarnings = $validator->getWarnings();
                     $validatorErrors = $validator->getErrors();
                     foreach ($validatorWarnings as $warning) {
                         $cronLogger->with($entityId)->warn($warning);
                     }
                     foreach ($validatorErrors as $error) {
                         $cronLogger->with($entityId)->error($error);
                     }
                     sspmod_janus_OpenSsl_Certificate_Chain_Factory::loadRootCertificatesFromFile($rootCertificatesFile);
                     $chain = sspmod_janus_OpenSsl_Certificate_Chain_Factory::createFromCertificateIssuerUrl($certificate);
                     $validator = new sspmod_janus_OpenSsl_Certificate_Chain_Validator($chain);
                     $validator->setIgnoreSelfSigned(true);
                     $validator->setTrustedRootCertificateAuthorityFile($rootCertificatesFile);
                     $validator->validate();
                     $validatorWarnings = $validator->getWarnings();
                     $validatorErrors = $validator->getErrors();
                     foreach ($validatorWarnings as $warning) {
                         $cronLogger->with($entityId)->warn($warning);
                     }
                     foreach ($validatorErrors as $error) {
                         $cronLogger->with($entityId)->error($error);
                     }
                 } catch (Exception $e) {
                     $cronLogger->with($entityId)->error($e->getMessage());
                 }
             } catch (Exception $e) {
                 $cronLogger->error($e->getMessage() . $e->getTraceAsString());
             }
         }
     } catch (Exception $e) {
         $cronLogger->error($e->getMessage() . $e->getTraceAsString());
     }
     if ($cronLogger->hasErrors()) {
         $this->_mailTechnicalContact($cronTag, $cronLogger);
     }
     return $cronLogger->getSummaryLines();
 }
 /**
  * Delete the ARP identified by the aid.
  *
  * @return PDOStatement|false The statement or false on error.
  */
 public function delete()
 {
     if (empty($this->_aid)) {
         SimpleSAML_Logger::error('JANUS:ARP:delete - aid needs to be set.');
         return false;
     }
     $deleteStatement = $this->execute('UPDATE ' . self::$prefix . 'arp SET
         `deleted` = ?
         WHERE `aid` = ?;', array(date('c'), $this->_aid));
     if ($deleteStatement === false) {
         return false;
     }
     // Get all entities with the just removed ARP
     $st = $this->execute('SELECT eid
         FROM ' . self::$prefix . 'entity
         WHERE `arp` = ?;', array($this->_aid));
     if (!$st) {
         return $deleteStatement;
     }
     $janus_config = SimpleSAML_Configuration::getConfig('module_janus.php');
     $controller = new sspmod_janus_EntityController($janus_config);
     // Remove the ARP from all entities
     $entity_rows = $st->fetchAll();
     foreach ($entity_rows as $entity_row) {
         $controller->setEntity($entity_row['eid']);
         $controller->loadEntity();
         $controller->setArp('0');
         $controller->saveEntity();
     }
     return $deleteStatement;
 }
 /** 
  * Retrieve all entity metadata for all entities of a certain type.
  * @param String $type Supported types: "saml20-idp" or "saml20-sp"
  * @param Array $keys optional list of metadata keys to retrieve. Retrieves all if blank
  * @param String $allowedEntityId if passed, returns only those entities that are 
  *                         whitelisted against the given entity
  * @return Array Associative array of all metadata. The key of the array is the identifier
  */
 protected static function _getEntities($type, $keys = array(), $allowedEntityId = NULL)
 {
     $econtroller = new sspmod_janus_EntityController(SimpleSAML_Configuration::getConfig('module_janus.php'));
     $ucontroller = new sspmod_janus_UserController(SimpleSAML_Configuration::getConfig('module_janus.php'));
     $entities = array();
     if (isset($allowedEntityId)) {
         $econtroller->setEntity($allowedEntityId);
         $econtroller->loadEntity();
         if ($econtroller->getEntity()->getAllowedAll() == "yes") {
             $entities = $ucontroller->searchEntitiesByType($type);
         } else {
             $allowedEntities = $econtroller->getAllowedEntities();
             // Check the whitelist
             if (count($allowedEntities)) {
                 foreach ($allowedEntities as $entityid => $data) {
                     $entities[] = $data["remoteentityid"];
                 }
             } else {
                 // Check the blacklist
                 $blockedEntities = $econtroller->getBlockedEntities();
                 if (count($blockedEntities)) {
                     $blockedEntityIds = array();
                     foreach ($blockedEntities as $entityid => $data) {
                         $blockedEntityIds[] = $data["remoteentityid"];
                     }
                     $all = $ucontroller->searchEntitiesByType($type);
                     $list = array();
                     foreach ($all as $entity) {
                         $list[] = $entity->getEntityId();
                     }
                     // Return all entities that are not in the blacklist
                     $entities = array_diff($list, $blockedEntityIds);
                 }
             }
         }
     } else {
         $entities = $ucontroller->searchEntitiesByType($type);
     }
     $result = array();
     foreach ($entities as $entity) {
         $data = self::_getMetadataForEntity($entity, NULL, $keys);
         // Add workflow state info for optional filtering at client side
         $data['workflowState'] = $entity->getWorkflow();
         if (is_object($entity)) {
             $entityId = $entity->getEntityId();
         } else {
             $entityId = $entity;
         }
         $result[$entityId] = $data;
     }
     return $result;
 }
        throw new SimpleSAML_Error_Exception('eid and revisionid parameter must be set');
    }
}
// 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())) {