public function getPrettyname()
 {
     if (isset($this->_prettyname)) {
         return $this->_prettyname;
     }
     $fieldname = $this->_config->getString('entity.prettyname', NULL);
     $mb = new sspmod_janus_MetadatafieldBuilder($this->_config->getArray('metadatafields.' . $this->_type));
     $metadatafields = $mb->getMetadatafields();
     if (!is_null($fieldname)) {
         $st = $this->execute('
             SELECT t1.value AS value
             FROM ' . self::$prefix . 'metadata AS t1
             WHERE t1.eid = ? AND t1.key = ? AND t1.revisionid = ?;', array($this->_eid, $fieldname, $this->_revisionid));
         if ($st === false) {
             return false;
         }
         $rows = $st->fetchAll(PDO::FETCH_ASSOC);
         if (empty($rows)) {
             $this->_prettyname = $this->_entityid;
         } else {
             if (isset($metadatafields[$fieldname]->default) && $metadatafields[$fieldname]->default == $rows[0]['value']) {
                 $this->_prettyname = $this->_entityid;
             } else {
                 $this->_prettyname = $rows[0]['value'];
             }
         }
     } else {
         $this->_prettyname = $this->_entityid;
     }
     return $this->_prettyname;
 }
 /**
  * Add metadata.
  *
  * Add a new matadata entry to the entity.
  *
  * @param string $key   The metadata key
  * @param string $value The metadata value
  *
  * @return sspmod_janus_Metadata The metadata.
  * @todo Make independent of type (make generic, support for more types than 
  * sp and idp)
  */
 public function addMetadata($key, $value)
 {
     assert('is_string($key);');
     //assert('is_string($value);');
     assert('$this->_entity instanceof Sspmod_Janus_Entity');
     $allowedfields = array();
     $mb = new sspmod_janus_MetadatafieldBuilder($this->_config->getArray('metadatafields.' . $this->_entity->getType()));
     $allowedfields = $mb->getMetadatafields();
     // Check if metadata is allowed
     if (!array_key_exists($key, $allowedfields)) {
         SimpleSAML_Logger::info('JANUS:EntityController:addMetadata - Metadata key \'' . $key . ' not allowed');
         return false;
     }
     if (empty($this->_metadata)) {
         if (!$this->loadEntity()) {
             return false;
         }
     }
     $st = $this->execute('SELECT count(*) AS count 
         FROM ' . self::$prefix . 'metadata 
         WHERE `eid` = ? AND `revisionid` = ? AND `key` = ?;', array($this->_entity->getEid(), $this->_entity->getRevisionid(), $key));
     if ($st === false) {
         SimpleSAML_Logger::error('JANUS:EntityController:addMetadata - Count check failed');
         return false;
     }
     $row = $st->fetchAll(PDO::FETCH_ASSOC);
     if ($row[0]['count'] > 0) {
         SimpleSAML_Logger::error('JANUS:EntityController:addMetadata - Metadata already exists');
         return false;
     }
     if ($allowedfields[$key]->type == 'select') {
         $allowedselectvalues = $allowedfields[$key]->select_values;
         if (!in_array($value, $allowedselectvalues)) {
             SimpleSAML_Logger::error('JANUS:EntityController:addMetadata - Value: ' . $value . ' not allowed for field ' . $key);
             return false;
         }
     }
     $metadata = new sspmod_janus_Metadata($this->_config->getValue('store'));
     $metadata->setEid($this->_entity->getEid());
     // Revision id is not set, since it is not save to the db and hence it
     // do not have a reversionid
     $metadata->setKey($key);
     $metadata->setValue($value);
     $this->_metadata[] = $metadata;
     $this->_modified = true;
     // The metadata is not saved, since it is not part of the current
     // entity with current revision id
     return $metadata;
 }
 private static function getMetadata($eid, $revision, $type = null, array $option = null)
 {
     assert('ctype_digit($eid)');
     assert('ctype_digit($revision)');
     $janus_config = SimpleSAML_Configuration::getConfig('module_janus.php');
     $econtroller = new sspmod_janus_EntityController($janus_config);
     if (!($entity = $econtroller->setEntity($eid, $revision))) {
         self::$_error = array('Entity could not be loaded - Eid: ' . $eid . ' Revisionid: ' . $revisionid);
         return false;
     }
     $metadata_raw = $econtroller->getMetadata();
     // Get metadata fields
     $nm_mb = new sspmod_janus_MetadatafieldBuilder($janus_config->getArray('metadatafields.' . $entity->getType()));
     $metadatafields_required = $nm_mb->getMetadatafields();
     // Get required metadata fields
     $required = array();
     foreach ($metadatafields_required as $mf) {
         if (isset($mf->required) && $mf->required === true) {
             $required[] = $mf->name;
         }
     }
     // Get metadata to me tested
     $metadata = array();
     foreach ($metadata_raw as $k => $v) {
         // Metadata field not defined
         if (!isset($metadatafields_required[$v->getKey()])) {
             continue;
         }
         // Value not set for metadata
         if (is_string($v->getValue()) && $v->getValue() == '') {
             continue;
         }
         // Compute is the default values is allowed
         $default_allow = false;
         if (isset($metadatafield_required[$v->getKey()]->default_allow) && is_bool($metadata_required[$v->getKey()]->default_allow)) {
             $default_allow = $metadata_required[$v->getKey()]->default_allow;
         }
         /*
          * Do not include metadata if value is set to default and default
          * is not allowed.
          */
         if (!$default_allow && (isset($metadata_required[$v->getKey()]->default) && $v->getValue() == $metadata_required[$v->getKey()]->default)) {
             continue;
         }
         $metadata[] = $v->getKey();
     }
     // Compute missing metadata that is required
     $missing_required = array_diff($required, $metadata);
     $entityid = $entity->getEntityid();
     if (empty($missing_required)) {
         try {
             $metaArray = $econtroller->getMetaArray();
             $metaArray['eid'] = $eid;
             $blocked_entities = $econtroller->getBlockedEntities();
             $allowed_entities = $econtroller->getAllowedEntities();
             $disable_consent = $econtroller->getDisableConsent();
             $metaflat = '// Revision: ' . $entity->getRevisionid() . "\n";
             $metaflat .= var_export($entityid, TRUE) . ' => ' . var_export($metaArray, TRUE) . ',';
             // Add authproc filter to block blocked entities
             if (!empty($blocked_entities) || !empty($allowed_entities)) {
                 $metaflat = substr($metaflat, 0, -2);
                 if (!empty($blocked_entities)) {
                     $metaflat .= "  'blocked' => array(\n";
                     foreach ($blocked_entities as $bentity => $value) {
                         $metaflat .= "    '" . $bentity . "',\n";
                     }
                     $metaflat .= "  ),\n";
                 }
                 if (!empty($allowed_entities)) {
                     $metaflat .= "  'allowed' => array(\n";
                     foreach ($allowed_entities as $aentity => $value) {
                         $metaflat .= "      '" . $aentity . "',\n";
                     }
                     $metaflat .= "  ),\n";
                 }
                 $metaflat .= '),';
             }
             // Add disable consent
             if (!empty($disable_consent)) {
                 $metaflat = substr($metaflat, 0, -2);
                 $metaflat .= "  'consent.disable' => array(\n";
                 foreach ($disable_consent as $key => $value) {
                     $metaflat .= "    '" . $key . "',\n";
                 }
                 $metaflat .= "  ),\n";
                 $metaflat .= '),';
             }
             $maxCache = isset($option['maxCache']) ? $option['maxCache'] : null;
             $maxDuration = isset($option['maxDuration']) ? $option['maxDuration'] : null;
             try {
                 $metaBuilder = new SimpleSAML_Metadata_SAMLBuilder($entityid, $maxCache, $maxDuration);
                 $metaBuilder->addMetadata($metaArray['metadata-set'], $metaArray);
             } catch (Exception $e) {
                 SimpleSAML_Logger::error('JANUS - Entity_id:' . $entityid . ' - Error generating XML metadata - ' . var_export($e, true));
                 self::$_error = array('Error generating XML metadata - ' . $e->getMessage());
                 return false;
             }
             // Add organization info
             if (!empty($metaArray['OrganizationName']) && !empty($metaArray['OrganizationDisplayName']) && !empty($metaArray['OrganizationURL'])) {
                 $metaBuilder->addOrganizationInfo(array('OrganizationName' => $metaArray['OrganizationName'], 'OrganizationDisplayName' => $metaArray['OrganizationDisplayName'], 'OrganizationURL' => $metaArray['OrganizationURL']));
             }
             // Add contact info
             if (!empty($metaArray['contact'])) {
                 $metaBuilder->addContact('technical', $metaArray['contact']);
             }
             switch ($type) {
                 case self::XML:
                     return $metaBuilder->getEntityDescriptor();
                 case self::XMLREADABLE:
                     return $metaBuilder->getEntityDescriptorText();
                 case self::PHPARRAY:
                     return $metaArray;
                 case self::FLATFILE:
                 default:
                     return $metaflat;
             }
         } catch (Exception $exception) {
             $session = SimpleSAML_Session::getInstance();
             SimpleSAML_Utilities::fatalError($session->getTrackID(), 'JANUS - Metadatageneration', $exception);
         }
     } else {
         SimpleSAML_Logger::error('JANUS - Missing required metadata fields. Entity_id:' . $entityid);
         self::$_error = $missing_required;
         return false;
     }
 }
 /**
  * Create new entity with parsed entityid
  *
  * Create a new entity and give the user access to the entity.
  *
  * @param string $entityid Entity id for the new entity
  * @param string $type     Entity type
  *
  * @return sspmod_janus_Entity|bool Returns the entity or false on error.
  * @since Method available since Release 1.0.0
  */
 public function createNewEntity($entityid, $type)
 {
     assert('is_string($entityid)');
     assert('is_string($type)');
     if ($this->isEntityIdInUse($entityid, $errorMessage)) {
         return $errorMessage;
     }
     if ($this->hasEntityIdBeenUsed($entityid, $errorMessage)) {
         return $errorMessage;
     }
     $startstate = $this->_config->getString('workflowstate.default');
     // Get the default ARP
     $default_arp = '0';
     $st = $this->execute("SELECT aid FROM " . self::$prefix . "arp WHERE is_default = TRUE AND deleted = ''");
     if ($st) {
         $rows = $st->fetchAll();
         if (count($rows) === 1) {
             $default_arp = $rows[0]['aid'];
         }
     }
     // Instantiate a new entity
     $entity = new sspmod_janus_Entity($this->_config, true);
     $entity->setEntityid($entityid);
     $entity->setWorkflow($startstate);
     $entity->setType($type);
     $entity->setArp($default_arp);
     $entity->setUser($this->_user->getUid());
     $entity->setRevisionnote('Entity created.');
     $entity->save();
     $st = $this->execute('INSERT INTO ' . self::$prefix . 'hasEntity 
         (`uid`, `eid`, `created`, `ip`) 
         VALUES 
         (?, ?, ?, ?);', array($this->_user->getUid(), $entity->getEid(), date('c'), $_SERVER['REMOTE_ADDR']));
     if ($st === false) {
         return 'error_db';
     }
     $ec = new sspmod_janus_EntityController($this->_config);
     $ec->setEntity($entity);
     $update = false;
     // Get metadatafields for new type
     $nm_mb = new sspmod_janus_MetadatafieldBuilder($this->_config->getArray('metadatafields.' . $type));
     $metadatafields = $nm_mb->getMetadatafields();
     // Add all required fileds
     foreach ($metadatafields as $mf) {
         if (isset($mf->required) && $mf->required === true) {
             $ec->addMetadata($mf->name, $mf->default);
             $update = true;
         }
     }
     if ($update === true) {
         $ec->saveEntity();
     }
     // Reset list of entities
     $this->_entities = null;
     $this->_loadEntities();
     return $entity->getEid();
 }
} else {
    if ($entity->getType() == 'saml20-idp') {
        $loaded_entities = array_merge($autil->getEntitiesByStateType(null, 'saml20-sp'), $autil->getEntitiesByStateType(null, 'shib13-sp'));
    } else {
        if ($entity->getType() == 'shib13-sp') {
            $loaded_entities = array_merge($autil->getEntitiesByStateType(null, 'saml20-idp'), $autil->getEntitiesByStateType(null, 'shib13-idp'));
        } else {
            if ($entity->getType() == 'shib13-idp') {
                $loaded_entities = array_merge($autil->getEntitiesByStateType(null, 'saml20-sp'), $autil->getEntitiesByStateType(null, 'shib13-sp'));
            }
        }
    }
}
// Get metadatafields
$mfc = $janus_config->getArray('metadatafields.' . $entity->getType());
$mb = new sspmod_janus_MetadatafieldBuilder($mfc);
$et->data['metadatafields'] = $mb->getMetadatafields();
$remote_entities = array();
// Only parse name and description in current language
foreach ($loaded_entities as $entityRow) {
    $instance = new sspmod_janus_Entity($janus_config);
    $instance->setEid($entityRow["eid"]);
    $instance->setRevisionid($entityRow["revisionid"]);
    $instance->load();
    $value = array("name" => $instance->getPrettyName(), "description" => $instance->getEntityId());
    $key = $instance->getEntityId();
    unset($value2);
    if (isset($value['name'])) {
        if (is_array($value['name'])) {
            if (array_key_exists($language, $value['name'])) {
                $value2['name'][$language] = $value['name'][$language];