コード例 #1
0
ファイル: Schema.php プロジェクト: adrianclay/xbrl
 /**
  * @return Concept[]
  */
 public function getConcepts()
 {
     if ($this->concepts == null) {
         $this->concepts = array();
         $xPath = new \DOMXPath($this->dom);
         $xPath->registerNamespace('xsd', 'http://www.w3.org/2001/XMLSchema');
         $xPath->registerNamespace('link', 'http://www.xbrl.org/2003/linkbase');
         foreach ($xPath->evaluate('//xsd:schema/xsd:element') as $element) {
             $concept = new Concept($this, $element);
             $this->concepts[$concept->getId()] = $concept;
         }
     }
     return $this->concepts;
 }
コード例 #2
0
ファイル: 1323b2TestCase.php プロジェクト: swk/bluebox
 /**
  * setting some polyhierarchical relations
  */
 public function resetData()
 {
     $q = Doctrine_Query::create();
     $q->delete()->from("ConceptRelation")->execute();
     $q = Doctrine_Query::create();
     $q->delete()->from("Concept")->execute();
     $concepts = array("Woodworking", "Metalworking", "Submetalworking 1", "Submetalworking 2", "Subwoodworking 1", "Subwoodworking 2", "Surfaceworking", "drilled", "welded", "turned");
     foreach ($concepts as $concept) {
         $c = new Concept();
         $c->identifier = $concept;
         $c->status = "approved";
         $c->source = "test";
         $c->created = "today";
         $c->creator = "me";
         $c->creationIdentifier = "nothing";
         $c->save();
     }
     $w = Doctrine::getTable("Concept")->findOneByIdentifier("Woodworking");
     $sw1 = Doctrine::getTable("Concept")->findOneByIdentifier("Subwoodworking 1");
     $sw2 = Doctrine::getTable("Concept")->findOneByIdentifier("Subwoodworking 2");
     $m = Doctrine::getTable("Concept")->findOneByIdentifier("Metalworking");
     $sm1 = Doctrine::getTable("Concept")->findOneByIdentifier("Submetalworking 1");
     $sm2 = Doctrine::getTable("Concept")->findOneByIdentifier("Submetalworking 2");
     $d = Doctrine::getTable("Concept")->findOneByIdentifier("drilled");
     $wd = Doctrine::getTable("Concept")->findOneByIdentifier("welded");
     $t = Doctrine::getTable("Concept")->findOneByIdentifier("turned");
     $s = Doctrine::getTable("Concept")->findOneByIdentifier("Surfaceworking");
     $w->narrowerConcepts[] = $sw1;
     $w->narrowerConcepts[] = $sw2;
     $w->save();
     $sw1->narrowerConcepts[] = $s;
     $sw1->narrowerConcepts[] = $d;
     $sw1->narrowerConcepts[] = $t;
     $sw1->save();
     $sw2->narrowerConcepts[] = $d;
     $sw2->save();
     $m->narrowerConcepts[] = $sm1;
     $m->narrowerConcepts[] = $sm2;
     $m->save();
     $sm1->narrowerConcepts[] = $wd;
     $sm1->narrowerConcepts[] = $s;
     $sm1->save();
     $sm2->narrowerConcepts[] = $t;
     $sm2->save();
     $s->narrowerConcepts[] = $t;
     $s->narrowerConcepts[] = $d;
     $s->save();
 }
コード例 #3
0
ファイル: migration.php プロジェクト: florinp/dexonline
function createLexemDefinitionMap()
{
    LexemDefinitionMap::deleteAll();
    $dbResult = db_selectAllConcepts();
    print "Migrating " . mysql_num_rows($dbResult) . " concepts...\n";
    $seen = 0;
    while ($dbRow = mysql_fetch_assoc($dbResult)) {
        $concept = new Concept();
        $concept->populateFromDbRow($dbRow);
        $words = Word::loadByConceptId($concept->id);
        $definitions = Definition::loadByConceptId($concept->id);
        if ($definitions) {
            // Select distinct words
            $distinctWords = array();
            foreach ($words as $word) {
                $distinctWords[$word->name] = 1;
            }
            // For every word, look up all the lexems. Then map each of those lexems
            // to every definition.
            foreach ($distinctWords as $word => $ignored) {
                $lexems = Lexem::loadByUnaccented($word);
                // Create lexem if necessary so that we don't lose any words during the
                // migration
                if (count($lexems) == 0) {
                    $lexem = Lexem::create($word, 'T', 1, '');
                    $lexem->save();
                    $lexem->id = db_getLastInsertedId();
                    $lexems[] = $lexem;
                    $lexem->regenerateParadigm();
                }
                foreach ($lexems as $lexem) {
                    foreach ($definitions as $definition) {
                        $ldm = LexemDefinitionMap::load($lexem->id, $definition->id);
                        if (!$ldm) {
                            $ldm = LexemDefinitionMap::create($lexem->id, $definition->id);
                            $ldm->save();
                        }
                    }
                }
            }
        }
        $seen++;
        if ($seen % 1000 == 0) {
            print "Seen: {$seen};\n";
        }
    }
    print "Seen: {$seen};\n";
}
コード例 #4
0
 private static function saveMutation($operation, $fullRelationSignature, $stableAtom, $stableConcept, $modifiedAtom, $modifiedConcept, $source)
 {
     if (array_key_exists($fullRelationSignature, Config::get('mutationConcepts', 'MutationExtension'))) {
         Notifications::addLog("Save mutation on '{$fullRelationSignature}' (editUpdate)", 'Mutation');
         $mutConcept = Config::get('mutationConcepts', 'MutationExtension')[$fullRelationSignature];
         $database = Database::singleton();
         $database->setTrackAffectedConjuncts(false);
         // Don't track affected conjuncts for Mutation concept and relations;
         // New Mutation
         $mut = $database->addAtomToConcept(Concept::createNewAtom($mutConcept), $mutConcept);
         // Add mut info
         $database->editUpdate('mutRelation', false, $mut, 'Mutation', $fullRelationSignature, 'Relation');
         $database->editUpdate('mutDateTime', false, $mut, 'Mutation', date(DATE_ISO8601), 'DateTime');
         if ($source == 'User') {
             $user = Session::getSessionUserId();
         } else {
             $user = $source;
         }
         $database->editUpdate('mutBy', false, $mut, 'Mutation', $user, 'User');
         $database->editUpdate('mutOp', false, $mut, 'Mutation', $operation, 'Operation');
         // $database->editUpdate('mutReason', false, $mut, 'Mutation', 'zomaar', 'MutationReason'); // TODO: get reason from somewhere
         $database->editUpdate('mutValue', false, $mut, 'Mutation', $modifiedAtom, 'MutationValue');
         $database->editUpdate('mutStable', false, $mut, $mutConcept, $stableAtom, $stableConcept);
         $database->editUpdate('mutPublish', false, $mut, 'Mutation', $mut, 'Mutation');
         $database->setTrackAffectedConjuncts(true);
         // Enable tracking of affected conjuncts again!!
     }
 }
コード例 #5
0
 /**
 * Set defaults
 *
 * @param  Concept $concept
 */
 public function setDefaults($concept)
 {
     $vocabObj = $this->getCurrentVocabulary();
     $vocabId = $vocabObj->getId();
     $concept->setVocabularyId($vocabId);
     $conceptParam = $this->getContext()->getRequest()->getParameter('concept');
     if (!$this->getContext()->getRequest()->getErrors() and !isset($conceptParam['uri'])) {
         $vocabDomain = $vocabObj->getBaseDomain();
         $vocabToken = $vocabObj->getToken();
         //get the next id
         $nextUriId = VocabularyPeer::getNextConceptId($vocabId);
         //URI looks like: agent(base_domain) / vocabulary(token) / vocabulary(next_concept_id) / skos_property_id # concept(next_property_id)
         $vSlash = preg_match('@(/$)@i', $vocabDomain) ? '' : '/';
         $tSlash = preg_match('@(/$)@i', $vocabToken) ? '' : '/';
         //to support hash URIs just a wee bit better...
         $tSlash = preg_match('/#$/', $vocabToken) ? '' : $tSlash;
         $newURI = $vocabDomain . $vSlash . $vocabToken . $tSlash . $nextUriId;
         //registry base domain is http://metadataregistry.org/uri/
         //next_concept_id is always initialized to 100000, allowing for 999,999 concepts
         //vocabulary carries denormalized base_domain from agent
         $concept->setUri($newURI);
         $concept->setprefLabel('');
         //set to the vocabulary defaults
         $concept->setLanguage($vocabObj->getLanguage());
         $concept->setStatusId($vocabObj->getStatusId());
     }
     parent::setDefaults($concept);
 }
コード例 #6
0
 public function __construct($id, $interface = array())
 {
     global $allInterfaceObjects;
     // from Generics.php
     if (empty($interface)) {
         $interface = $allInterfaceObjects[$id];
     }
     // if no $interface is provided, use toplevel interfaces from $allInterfaceObjects
     // Check if interface exists
     if (empty($interface['id'])) {
         throw new Exception("Interface '{$id}' does not exists", 500);
     }
     // Set attributes of interface
     $this->id = $interface['id'];
     $this->label = $interface['label'];
     $this->interfaceRoles = $interface['interfaceRoles'];
     $this->editableConcepts = (array) $interface['editableConcepts'];
     $this->invariantConjuctsIds = $interface['invConjunctIds'];
     // only applicable for Top-level interfaces
     $this->signalConjunctsIds = $interface['sigConjunctIds'];
     // only applicable for Top-level interfaces
     // CRUD rights
     $this->crudC = is_null($interface['crudC']) ? Config::get('defaultCrudC', 'transactions') : $interface['crudC'];
     $this->crudR = is_null($interface['crudR']) ? Config::get('defaultCrudR', 'transactions') : $interface['crudR'];
     $this->crudU = is_null($interface['crudU']) ? Config::get('defaultCrudU', 'transactions') : $interface['crudU'];
     $this->crudD = is_null($interface['crudD']) ? Config::get('defaultCrudD', 'transactions') : $interface['crudD'];
     // Information about the (editable) relation if applicable
     $this->relation = $interface['relation'];
     $this->relationIsFlipped = $interface['relationIsFlipped'];
     $this->editable = empty($interface['relation']) ? false : $interface['relationIsEditable'];
     $this->totaal = $interface['exprIsTot'];
     $this->univalent = $interface['exprIsUni'];
     $this->isProperty = $interface['exprIsProp'];
     $this->isIdent = $interface['exprIsIdent'];
     $this->srcConcept = $interface['srcConcept'];
     $this->tgtConcept = $interface['tgtConcept'];
     isset($interface['viewId']) ? $this->viewId = $interface['viewId'] : null;
     // Determine if tgtConcept is Object (true) or Scalar (false)
     $this->tgtConceptIsObject = Concept::getTypeRepresentation($this->tgtConcept) == "OBJECT" ? true : false;
     // Set attributes
     $this->refInterfaceId = $interface['refSubInterfaceId'];
     $this->isLinkTo = $interface['isLinkTo'];
     $this->boxSubInterfaces = $interface['boxSubInterfaces'];
     $this->expressionSQL = $interface['expressionSQL'];
     // Determine subInterfaces
     foreach ((array) $this->boxSubInterfaces as $subInterface) {
         $this->subInterfaces[] = new InterfaceObject($subInterface['id'], $subInterface);
     }
 }
コード例 #7
0
 public static function isCombination($relationName, $srcConcept, $tgtConcept)
 {
     $allRelations = Relation::getAllRelations();
     foreach ($allRelations as $key => $relationInfo) {
         // Match relationName with relation name as specified in Ampersand script.
         // Includes support for specializations.
         if ($relationInfo['name'] == $relationName && ($relationInfo['srcConcept'] == $srcConcept || in_array($srcConcept, Concept::getSpecializations($relationInfo['srcConcept']))) && ($relationInfo['tgtConcept'] == $tgtConcept || in_array($tgtConcept, Concept::getSpecializations($relationInfo['tgtConcept'])))) {
             return $key;
         }
         // return fullRelationSignature
         // Match relationName with fullRelationSignature (format: 'rel_<relationName>_<srcConcept>_<tgtConcept>')
         if ($key == $relationName && ($relationInfo['srcConcept'] == $srcConcept || in_array($srcConcept, Concept::getSpecializations($relationInfo['srcConcept']))) && ($relationInfo['tgtConcept'] == $tgtConcept || in_array($tgtConcept, Concept::getSpecializations($relationInfo['tgtConcept'])))) {
             return $key;
         }
         // return fullRelationSignature
     }
     // If relation not found in $allRelations
     throw new Exception("Cannot find relation with signature '" . $relationName . "[" . $srcConcept . "*" . $tgtConcept . "]'", 500);
 }
コード例 #8
0
ファイル: Concept.php プロジェクト: luisbrito/Phraseanet
 public static function pruneNarrowConcepts($concepts)
 {
     // Build a map with paths as keys
     $concepts = array_combine(Concept::toPathArray($concepts), $concepts);
     // Paths are sorted in advance to keep search O(n)
     ksort($concepts);
     // With sorting, the first element can't be a child
     $broad = current($concepts);
     next($concepts);
     // Start prunning concepts narrower than current broad one
     while ($concept = current($concepts)) {
         if ($concept->isNarrowerThan($broad)) {
             unset($concepts[key($concepts)]);
         } else {
             // End of prunable childs, beginning of a new concept
             $broad = $concept;
             next($concepts);
         }
     }
     return array_values($concepts);
 }
コード例 #9
0
ファイル: Set.php プロジェクト: adrianclay/xbrl
 /**
  * @param Concept $concept
  * @return Arc[]
  */
 public function getArcsFromConcept(Concept $concept)
 {
     if (is_null($this->arcCache)) {
         $this->arcCache = array();
         foreach ($this->getArcs() as $arc) {
             /** @var $fromConcept NamespaceId */
             foreach ($arc->getFromConcepts() as $fromConcept) {
                 if (!isset($this->arcCache[$fromConcept->namespace])) {
                     $this->arcCache[$fromConcept->namespace] = array();
                 }
                 if (!isset($this->arcCache[$fromConcept->namespace][$fromConcept->id])) {
                     $this->arcCache[$fromConcept->namespace][$fromConcept->id] = array();
                 }
                 $this->arcCache[$fromConcept->namespace][$fromConcept->id][] = $arc;
             }
         }
     }
     $namespaceArcCache = $this->arcCache[$concept->getNamespace()];
     if ($namespaceArcCache) {
         return $namespaceArcCache[$concept->getId()];
     }
     return null;
 }
コード例 #10
0
ファイル: Session.php プロジェクト: 4ZP6Capstone2015/Capstone
 private function __construct()
 {
     try {
         $this->id = session_id();
         $this->database = Database::singleton();
         // AMPERSAND SESSION
         Concept::getConcept('SESSION');
         // Remove expired Ampersand sessions from __SessionTimeout__ and all concept tables and relations where it appears.
         $expiredSessionsAtoms = array_column($this->database->Exe("SELECT SESSION FROM `__SessionTimeout__` WHERE `lastAccess` < " . (time() - Config::get('sessionExpirationTime'))), 'SESSION');
         foreach ($expiredSessionsAtoms as $expiredSessionAtom) {
             $this->destroyAmpersandSession($expiredSessionAtom);
         }
         // Create a new Ampersand session if session_id() is not in SESSION table (browser started a new session or Ampersand session was expired
         $sessionAtom = new Atom($this->id, 'SESSION');
         if (!$sessionAtom->atomExists()) {
             $this->database->addAtomToConcept($this->id, 'SESSION');
             $this->database->commitTransaction();
             //TODO: ook door Database->closeTransaction() laten doen, maar die verwijst terug naar Session class voor de checkrules. Oneindige loop
         }
         $this->database->Exe("INSERT INTO `__SessionTimeout__` (`SESSION`,`lastAccess`) VALUES ('" . $this->id . "', '" . time() . "') ON DUPLICATE KEY UPDATE `lastAccess` = '" . time() . "'");
     } catch (Exception $e) {
         throw $e;
     }
 }
コード例 #11
0
 private function ParseLines($data)
 {
     $relation = $concept = $atom = array();
     foreach ($data as $linenr => $values) {
         $totalcolumns = count($values);
         if ($linenr == 0) {
             // Relations:
             for ($col = 0; $col < $totalcolumns; $col++) {
                 $relation[$col] = $values[$col];
             }
         } elseif ($linenr == 1) {
             // Concepts:
             for ($col = 0; $col < $totalcolumns; $col++) {
                 $concept[$col] = $values[$col];
             }
         } else {
             // Atoms:
             for ($col = 0; $col < $totalcolumns; $col++) {
                 $atom[$col] = $values[$col];
             }
             // Don't process lines that start with an empty first cell
             if ($atom[0] == '' or empty($atom[0])) {
                 continue;
             }
             // Check if this is an atom-create line, syntax = &atomname
             if (strpos('&', $atom[0]) === 0) {
                 $atom[0] = Concept::createNewAtom($concept[0]);
                 // Create a unique atom name
             }
             // Insert $atom[0] into the DB if it does not yet exist
             $this->addAtomToConcept($atom[0], $concept[0]);
             for ($col = 1; $col < $totalcolumns; $col++) {
                 // Now we transform the data info function calls:
                 if ($atom[$col] == '') {
                     continue;
                 }
                 // Empty cells are allowed but shouldn't do anything
                 if ($concept[$col] == '' or empty($concept[$col])) {
                     continue;
                 }
                 // if no concept is specified, the contents of the cell should be ignored.
                 if ($relation[$col] == '' or empty($relation[$col])) {
                     continue;
                 }
                 // if no relation is specified, the contents of the cell should be ignored.
                 if (strpos('&', $atom[$col]) === 0) {
                     // Check if this is an atom-create line, syntax = &atomname
                     $atom[$col] = $atom[0];
                     // '&' copies the atom-value; useful for property-relations.
                 }
                 $this->insertRel($relation[$col], $atom[0], $atom[$col], $concept[0], $concept[$col]);
             }
             $atom = array();
         }
     }
 }
コード例 #12
0
 /**
  * True if this search term object matches the passed Concept; false otherwise.
  * @param Concept $c
  * @param mixed $search_term_type One of the MCL_SEARCH_TERM_TYPE_* constants. Use to force a specific type of comparison
  * @return bool
  */
 public function isMatch(Concept $c, $search_term_type = null)
 {
     // Prepare the search term type for comparison
     if (is_null($search_term_type)) {
         $search_term_type = $this->term_type;
     }
     // Now do the comparison
     if ($search_term_type == MCL_SEARCH_TERM_TYPE_ALL) {
         return true;
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_CONCEPT_ID) {
         if ($this->needle == $c->concept_id) {
             return true;
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_CONCEPT_ID_RANGE) {
         list($min, $max) = explode('-', $this->needle);
         if ($c->concept_id >= $min && $c->concept_id <= $max) {
             return true;
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_MAP_CODE) {
         foreach ($c->getConceptMappingIds() as $mapcode_id) {
             $subject = $c->getConceptMapping($mapcode_id)->source_code;
             if (preg_match('/\\b' . addslashes($this->needle) . '/i', $subject)) {
                 return true;
             }
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_MAP_CODE_RANGE) {
         // TODO: MCL_SEARCH_TERM_TYPE_MAP_CODE_RANGE
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_TEXT) {
         foreach ($c->getConceptNameIds() as $name_id) {
             $subject = $c->getConceptName($name_id)->name;
             if (preg_match('/\\b' . addslashes($this->needle) . '/i', $subject)) {
                 return true;
             }
         }
         foreach ($c->getConceptDescriptionIds() as $desc_id) {
             $subject = $c->getConceptDescription($desc_id)->description;
             if (preg_match('/\\b' . addslashes($this->needle) . '/i', $subject)) {
                 return true;
             }
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_CONCEPT_NAME) {
         foreach ($c->getConceptNameIds() as $name_id) {
             $subject = $c->getConceptName($name_id)->name;
             if (preg_match('/\\b' . addslashes($this->needle) . '/i', $subject)) {
                 return true;
             }
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_CONCEPT_DESCRIPTION) {
         foreach ($c->getConceptDescriptionIds() as $desc_id) {
             $subject = $c->getConceptDescription($desc_id)->description;
             if (preg_match('/\\b' . addslashes($this->needle) . '/i', $subject)) {
                 return true;
             }
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_UUID) {
         if (strtolower($this->needle) == strtolower(substr($c->uuid, 0, strlen($this->needle)))) {
             return true;
         }
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_LIST) {
         // TODO: MCL_SEARCH_TERM_TYPE_LIST
     } elseif ($search_term_type == MCL_SEARCH_TERM_TYPE_MAP_SOURCE) {
         // TODO: MCL_SEARCH_TERM_TYPE_MAP_SOURCE
     }
     return false;
 }
コード例 #13
0
 /**
  * Method called to associate a Concept object to this object
  * through the Concept foreign key attribute
  *
  * @param      Concept $l Concept
  * @return     void
  * @throws     PropelException
  */
 public function addConcept(Concept $l)
 {
     $this->collConcepts[] = $l;
     $l->setConceptProperty($this);
 }
コード例 #14
0
function run_import_marc_vocabulary($task, $args)
{


    //check the argument counts
    if (count($args) < 1) {
        throw new Exception('You must provide a vocabulary type.');
    }

    if (count($args) < 2) {
        throw new Exception('You must provide a file name.');
    }

    if (count($args) < 3) {
        throw new Exception('You must provide a vocabulary id.');
    }

    //set the arguments
    $type          = strtolower($args[0]);
    $filePath      = $args[1];
    $id            = $args[2];
    $deleteMissing = (isset($args[3]) && ("-d" == $args[3]));

    //do some basic validity checks

    if (! in_array($type, array("schema", "vocab", "vocabulary"))) {
        throw new Exception('You must import into a schema or a vocab');
    }

    if ("vocabulary" == $type) {
        $type = "vocab";
    }

    if (! is_numeric($id)) {
        throw new Exception('You must provide a valid ID');
    }

    //does the file exist?
    if (! file_exists($filePath)) {
        throw new Exception('You must supply a valid file to import: ' . $filePath);
    }

    //is the file a valid type?
    if (preg_match('/^.+\.([[:alpha:]]{2,4})$/', $filePath, $matches)) {
        if (! in_array(strtolower($matches[1]), array("json", "rdf", "csv", "xml"))) {
            throw new Exception('You must provide a valid file type based on the extension');
        }
    } else {
        throw new Exception("File type cannot be determined from the file extension");
    }

    $fileType = $matches[1];

    //is the object a valid object?
    if ('vocab' == $type) {
        $vocabObj = VocabularyPeer::retrieveByPK($id);
        if (is_null($vocabObj)) {
            throw new Exception('Invalid vocabulary ID');
        }

        //set some defaults
        $baseDomain = $vocabObj->getBaseDomain();
        $language   = $vocabObj->getLanguage();
        $statusId   = $vocabObj->getStatusId();

        //get a skos property id map
        $skosMap = SkosPropertyPeer::getPropertyNames();

        //there has to be a hash or a slash
        $tSlash = preg_match('@(/$)@i', $vocabObj->getUri()) ? '' : '/';
        $tSlash = preg_match('/#$/', $vocabObj->getUri()) ? '' : $tSlash;
    } else {
        $schemaObj = SchemaPeer::retrieveByPK($id);
        if (is_null($schemaObj)) {
            throw new Exception('Invalid schema ID');
        }

        //set some defaults
        $baseDomain = $schemaObj->getUri();
        $language   = $schemaObj->getLanguage();
        $statusId   = $schemaObj->getStatusId();

        //get a element set property id map
        $profileId  = 1;
        $profile    = ProfilePeer::retrieveByPK($profileId);
        $elementMap = $profile->getAllProperties();

        //there has to be a hash or a slash
        $tSlash = preg_match('@(/$)@i', $baseDomain) ? '' : '/';
        $tSlash = preg_match('/#$/', $baseDomain) ? '' : $tSlash;
    }

    //     insert jon's user id
    $userId = 36;

    /* From here on the process is the same regardless of UI */

    //execute
    //     parse file to get the fields/columns and data
    $file = fopen($filePath, "r");
    if (! $file) {
        throw new Exception("Can't read supplied file");
    }

    //     check to see if file has been uploaded before
    //          check import history for file name
    $importHistory = FileImportHistoryPeer::retrieveByLastFilePath($filePath);
    //          if reimport
    //               get last import history for filename
    //               unserialize column map
    //               match column names to AP based on map
    //     look for matches in unmatched field/column names to AP (ideal)
    //     csv table of data --
    //          row1: parsed field names/column headers
    //          row2: select dropdown with available fields from object AP (pre-select known matches)
    //                each select identified by column number
    //          row3: display datatype of selected field (updated dynamically when field selected)
    //          row4-13: first 10 rows of parsed data from file
    //     require a column that can match to 'URI' (maybe we'll allow an algorithm later)
    //     require columns that are required by AP
    //     on reimport there should be a flag to 'delete missing properties' from the current data
    //     note: at some point there will be a reimport process that allows URI changing
    //          this will require that there be an OMR identifier embedded in the incoming data

    switch ($fileType) {
        case "csv":
            try {
                $reader = new aCsvReader($filePath);
            } catch(Exception $e) {
                throw new Exception("Not a happy CSV file!");
            }

            if ('vocab' == $type) {
                // Get array of heading names found
                $headings = $reader->getHeadings();
                $fields   = ConceptPeer::getFieldNames();

                //set the map
                //      $map[] = array("property" => "Uri", "column" => "URILocal");
                //      $map[] = array("property" => "prefLabel", "column" => "skos:prefLabel");
                //      $map[] = array("property" => "definition", "column" => "skos:definition");
                //      $map[] = array("property" => "notation", "column" => "skos:notation");
                //      $map[] = array("property" => "scopeNote", "column" => "skos:scopeNote");

                $map = array(
                  "uri"        => "URILocal",
                  "prefLabel"  => "skos:prefLabel",
                  "definition" => "skos:definition",
                  "notation"   => "skos:notation",
                  "scopeNote"  => "skos:scopeNote"
                );

                $rows = 0;

                //executeImport:

                //    serialize the column map
                try {
                    while ($row = $reader->getRow()) {
                        $rows ++;
                        //        lookup the URI (or the OMR ID if available) for a match
                        $uri        = $baseDomain . $row[$map["uri"]];
                        $concept    = ConceptPeer::getConceptByUri($uri);
                        $updateTime = time();
                        $language   = (isset($map['language'])) ? $row[$map['language']] : $vocabObj->getLanguage();

                        if (! $concept) {
                            //          create a new concept or element
                            $concept = new Concept();
                            $concept->setVocabulary($vocabObj);
                            $concept->setUri($uri);
                            /**
                             * @todo Need to handle updates for topconcept here, just like language
                             **/
                            $concept->setIsTopConcept(false);
                            $concept->updateFromRequest(
                                    $userId,
                                      fixMarcEncoding(rtrim($row[$map['prefLabel']])),
                                      $language,
                                      $statusId
                            );
                        } //don't update the concept if the preflabel matches
                        else if ($row[$map['prefLabel']] != $concept->getPrefLabel()) {
                            $concept->updateFromRequest($userId, fixMarcEncoding(rtrim($row[$map['prefLabel']])));
                        }

                        //there needs to be a language to lookup the properties unless it's an objectProperty
                        $rowLanguage = (isset($map['language'])) ? $row[$map['language']] : $concept->getLanguage();

                        foreach ($map as $key => $value) {
                            //we skip because we already did them
                            if (! in_array($key, array('uri', 'prefLabel', 'language'))) {
                                $skosId = $skosMap[$key];
                                //check to see if the property already exists
                                $property =
                                  ConceptPropertyPeer::lookupProperty($concept->getId(), $skosId, $rowLanguage);

                                //create a new property for each unmatched column
                                if (! empty($row[$value])) {
                                    if (! $property) {
                                        $property = new ConceptProperty();
                                        $property->setCreatedUserId($userId);
                                        $property->setConceptId($concept->getId());
                                        $property->setCreatedAt($updateTime);
                                        $property->setSkosPropertyId($skosId);
                                    }

                                    if (($row[$value] != $property->getObject()) ||
                                        ($rowLanguage != $property->getLanguage())
                                    ) {
                                        /**
                                         * @todo We need a check here for skos objectproperties and handle differently
                                         **/
                                        if ($rowLanguage != $property->getLanguage()) {
                                            $property->setLanguage($rowLanguage);
                                        }
                                        if ($row[$value] != $property->getObject()) {
                                            $property->setObject(fixMarcEncoding(rtrim($row[$value])));
                                        }
                                        $property->setUpdatedUserId($userId);
                                        $property->setUpdatedAt($updateTime);
                                        $property->save();
                                    }
                                } //the row value is empty
                                else if ($deleteMissing && $property) {
                                    $property->delete();
                                }
                            }
                        }

                        //          else
                        //               lookup and update concept or element
                        //               lookup and update each property
                        //          update the history for each property, action is 'import', should be a single timestamp for all (this should be automatic)
                        //          if 'delete missing properties' is true
                        //               delete each existing, non-required property that wasn't updated by the import
                    }
                } catch(Exception $e) {
                    //          catch
                    //            if there's an error of any kind, write to error log and continue
                    echo "Error on row: " . $rows . ", " . $uri . "\n" . $e . "\n";
                    continue;
                }
                $objects = $vocabObj->countConcepts();
            } else //it's an element set
            {
                $map  = array(
                  "uri"        => "uriLocalPart",
                  "name"       => "reg:name",
                  "definition" => "skos:definition",
                  "label"      => "rdfs:label",
                  "note"       => array("tag" => "tagCap", "ind1" => "ind1Cap", "ind2" => "ind2Cap", "sub" => "subCap")
                );
                $rows = 0;

                //executeImport:
                //    serialize the column map
                try {
                    while ($row = $reader->getRow()) {
                        //        lookup the URI (or the OMR ID if available) for a match

                        //There always has to be a URI on either update or create
                        if (! isset($row[$map["uri"]])) {
                            throw new Exception('Missing URI for row: ' . $reader->getRowCount());
                            continue;
                        }

                        $rows ++;
                        $uri         = $baseDomain . $tSlash . $row[$map["uri"]];
                        $property    = SchemaPropertyPeer::retrieveByUri($uri);
                        $updateTime  = time();
                        $rowLanguage = (isset($map['language'])) ? $row[$map['language']] : $language;
                        $rowStatusId = (isset($map['status'])) ? $row[$map['status']] : $statusId;

                        if (! $property) {
                            //          create a new property
                            /** @var SchemaProperty * */
                            $property = new SchemaProperty();
                            $property->setSchema($schemaObj);
                            $property->setUri($uri);
                            $property->setCreatedUserId($userId);
                            $property->setCreatedAt($updateTime);
                        }

                        $property->setLanguage($rowLanguage);
                        $property->setStatusId($rowStatusId);
                        $property->setUpdatedUserId($userId);
                        $property->setUpdatedAt($updateTime);

                        if (isset($row[$map["label"]])) {
                            $property->setLabel($row[$map["label"]]);
                        }

                        if (isset($row[$map["name"]])) {
                            $property->setName($row[$map["name"]]);
                        }

                        if (isset($row[$map["definition"]])) {
                            $property->setDefinition($row[$map["definition"]]);
                        }

                        if (is_array($map["note"])) {
                            $note = '';
                            foreach ($map["note"] as $key => $value) {
                                $caption = ! empty($row[$value]) ? " (" . $row[$value] . ")" : ' (no caption)';
                                $note .= ! empty($row[$key]) ? $key . ": " . $row[$key] . $caption . "<br />" : "";
                            }
                            $property->setNote($note);
                        } else {
                            if (isset($row[$map["note"]])) {
                                $property->setNote($row[$map["note"]]);
                            }
                        }
                        $property->saveSchemaProperty($userId);

                        /**
                         * @todo Need to handle domain and range
                         **/

                        foreach ($map as $key => $value) {
                            //we skip because we already did them
                            if (! in_array(
                              $key,
                              array('uri', 'status', 'language', 'label', 'name', 'definition', 'comment', 'note')
                            )
                            ) {
                                $elementId = $elementMap[$key];
                                //check to see if the property already exists
                                //note that this also checks the object value as well, so there's no way to update or delete an existing triple
                                //the sheet would have to conatin the identifier for the triple
                                $element = SchemaPropertyElementPeer::lookupElement(
                                                                    $schemaObj->getId(),
                                                                      $elementId,
                                                                      $map[$value]
                                );

                                //create a new property for each unmatched column
                                if (! empty($row[$value])) {
                                    if (! $element) {
                                        $element = new SchemaPropertyElement();
                                        $element->setCreatedUserId($userId);
                                        $element->setCreatedAt($updateTime);
                                        $element->setProfilePropertyId($elementId);
                                    }

                                    if (($row[$value] != $element->getObject()) ||
                                        ($rowLanguage != $element->getLanguage())
                                    ) {
                                        /**
                                         * @todo We need a check here for objectproperties and handle differently
                                         **/
                                        if ($rowLanguage != $element->getLanguage()) {
                                            $element->setLanguage($rowLanguage);
                                        }
                                        if ($row[$value] != $element->getObject()) {
                                            $element->setObject($row[$value]);
                                        }
                                        $element->setUpdatedUserId($userId);
                                        $element->setUpdatedAt($updateTime);
                                        $element->save();
                                    }
                                } //the row value is empty
                                else if ($deleteMissing && $element) {
                                    $element->delete();
                                }
                            }
                        }

                        //          else
                        //               lookup and update concept or element
                        //               lookup and update each property
                        //          update the history for each property, action is 'import', should be a single timestamp for all (this should be automatic)
                        //          if 'delete missing properties' is true
                        //               delete each existing, non-required property that wasn't updated by the import
                    }
                } catch(Exception $e) {
                    //          catch
                    //            if there's an error of any kind, write to error log and continue
                    echo "Error on row: " . $rows . ", " . $uri . "\n" . $e . "\n";
                    continue;
                }
                $objects = $schemaObj->countSchemaPropertys();
            }
            //     save the import history file (match timestamp to history entries)
            break;
        case "json":
            break;
        case "rdf":
            break;
        case "xml":
            break;
        default:
    }

    /* output to stdout*/
    //          number of objects imported (link to history, filtered on timestamp of import)
    echo "File:" . $filePath . ";\n     Objects imported: " . $objects . "; Rows read: " . $rows . "\n";
    //          number of errors (link to error log)

}
コード例 #15
0
 /**
  * Declares an association between this object and a Concept object.
  *
  * @param      Concept $v
  * @return     void
  * @throws     PropelException
  */
 public function setConceptRelatedByRelatedConceptId($v)
 {
     if ($v === null) {
         $this->setRelatedConceptId(NULL);
     } else {
         $this->setRelatedConceptId($v->getId());
     }
     $this->aConceptRelatedByRelatedConceptId = $v;
 }
コード例 #16
0
 private function callback($code, $idp)
 {
     try {
         $identityProviders = Config::get('identityProviders', 'OAuthLogin');
         if (empty($code)) {
             throw new Exception("Oops. Someting went wrong during login. Please try again", 401);
         }
         $session = Session::singleton();
         $db = Database::singleton();
         if (!isset($identityProviders[$idp])) {
             throw new Exception("Unknown identity provider", 500);
         }
         $client_id = $identityProviders[$idp]['clientId'];
         $client_secret = $identityProviders[$idp]['clientSecret'];
         $redirect_uri = $identityProviders[$idp]['redirectUrl'];
         $token_url = $identityProviders[$idp]['tokenUrl'];
         $api_url = $identityProviders[$idp]['apiUrl'];
         $emailField = $identityProviders[$idp]['emailField'];
         // instantiate authController
         $authController = new OAuthLoginController($client_id, $client_secret, $redirect_uri, $token_url);
         // request token
         if ($authController->requestToken($code)) {
             // request data
             if ($authController->requestData($api_url)) {
                 // Verify email/role here
                 $email = $authController->getData()->{$emailField};
                 // Get user with $email
                 // Set sessionUser
                 $interface = new InterfaceObject('EmailUser');
                 $atom = new Atom($email, 'Email');
                 $users = array_keys((array) $atom->getContent($interface, true));
                 // create new user
                 if (empty($users)) {
                     $newUser = Concept::createNewAtom('User');
                     $db->addAtomToConcept($newUser, 'User');
                     $db->editUpdate('userEmail', false, $newUser, 'User', $email, 'Email');
                     // add to Organization
                     $domain = explode('@', $email)[1];
                     $interface = new InterfaceObject('DomainOrgs');
                     $atom = new Atom($domain, 'Domain');
                     $orgs = array_keys((array) $atom->getContent($interface, true));
                     foreach ($orgs as $org) {
                         $db->editUpdate('userOrganization', false, $newUser, 'User', $org, 'Organization');
                     }
                     $users[] = $newUser;
                 }
                 if (count($users) > 1) {
                     throw new Exception("Multiple users registered with email {$email}", 401);
                 }
                 foreach ($users as $userId) {
                     // Set sessionUser
                     $db->editUpdate('sessionUser', false, session_id(), 'SESSION', $userId, 'User');
                     // Timestamps
                     $db->editUpdate('userLastLoginTimeStamp', false, $userId, 'User', date(DATE_ISO8601), 'DateTime');
                     $db->editUpdate('userLoginTimeStamp', false, $userId, 'User', date(DATE_ISO8601), 'DateTime');
                 }
                 $db->closeTransaction('Login successfull', false, true, false);
             }
         }
         header('Location: ' . Config::get('serverURL'));
         exit;
     } catch (Exception $e) {
         throw new RestException($e->getCode(), $e->getMessage());
     }
 }
コード例 #17
0
 public static function getAffectedInvConjuncts($concept)
 {
     $conceptInfo = Concept::getConcept($concept);
     return (array) $conceptInfo['affectedInvConjunctIds'];
 }
コード例 #18
0
/**
 * @param $task
 * @param $args
 *
 * Arg[0] is one of "schema" (element set), "vocab" or "vocabulary"
 * arg[1] is the vocabulary name.
 *        The file type is determined by the extension and must be one of "json", "rdf", "csv", "xml"
 * arg[2] is the vocabulary id
 * arg[3] is the batch id
 * arg[4] [optional] is -d
 *
 * @throws Exception
 */
function run_import_vocabulary($task, $args)
{
    //xdebug_break();

    //check the argument counts
    if (count($args) < 1) {
        throw new Exception('You must provide a vocabulary type.');
    }

    if (count($args) < 2) {
        throw new Exception('You must provide a file name.');
    }

    if (count($args) < 3) {
        throw new Exception('You must provide a vocabulary id.');
    }

    //set the arguments
    $type          = strtolower($args[0]);
    $filePath      = $args[1];
    $vocabId       = $args[2];
    $batchId       = isset($args[3]) ? $args[3] : "";
    $deleteMissing = (isset($args[4]) && ("-d" == $args[4]));

    //do some basic validity checks

    if (! in_array(
      $type,
      array(
        "schema",
        "vocab",
        "vocabulary"
      )
    )
    ) {
        throw new Exception('You must import into a schema or a vocab');
    }

    if ("vocabulary" == $type) {
        $type = "vocab";
    }

    if (! is_numeric($vocabId)) {
        throw new Exception('You must provide a valid ID');
    }

    //does the file exist?
    if (! file_exists($filePath)) {
        //default to the site upload path
        $filePath = $GLOBALS['uploadPath'] . $filePath;
        if (! file_exists($filePath)) {
        throw new Exception('You must supply a valid file to import: ' . $filePath);
        }
    }

    //is the file a valid type?
    if (preg_match('/^.+\.([[:alpha:]]{2,4})$/', $filePath, $matches)) {
        if (! in_array(
          strtolower($matches[1]),
          array(
            "json",
            "rdf",
            "csv",
            "xml"
          )
        )
        ) {
            throw new Exception('You must provide a valid file type based on the extension');
        }
    } else {
        throw new Exception("File type cannot be determined from the file extension");
    }

    $fileType = $matches[1];

    //is the object a valid object?
    if ('vocab' == $type) {
        $vocabObj = VocabularyPeer::retrieveByPK($vocabId);
        if (is_null($vocabObj)) {
            throw new Exception('Invalid vocabulary ID');
        }

        //set some defaults
        $baseDomain = $vocabObj->getBaseDomain();
        $language   = $vocabObj->getLanguage();
        $statusId   = $vocabObj->getStatusId();
        $userId     = $vocabObj->getCreatedUserId();
        $agentId    = $vocabObj->getAgentId();

        //get a skos property id map
        $skosMap = SkosPropertyPeer::getPropertyNames();

        //there has to be a hash or a slash
        $tSlash = preg_match('@(/$)@i', $vocabObj->getUri()) ? '' : '/';
        $tSlash = preg_match('/#$/', $vocabObj->getUri()) ? '' : $tSlash;
    } else {
        $import               = new ImportVocab($type, $filePath, $vocabId);
    }

    /* From here on the process is the same regardless of UI */
    //     check to see if file has been uploaded before
    //          check import history for file name
    $importHistory = FileImportHistoryPeer::retrieveByLastFilePath($filePath);
    //          if reimport
    //               get last import history for filename
    //               unserialize column map
    //               match column names to AP based on map
    //     look for matches in unmatched field/column names to AP (ideal)
    //     csv table of data --
    //          row1: parsed field names/column headers
    //          row2: select dropdown with available fields from object AP (pre-select known matches)
    //                each select identified by column number
    //          row3: display datatype of selected field (updated dynamically when field selected)
    //          row4-13: first 10 rows of parsed data from file
    //     require a column that can match to 'URI' (maybe we'll allow an algorithm later)
    //     require columns that are required by AP
    //     on reimport there should be a flag to 'delete missing properties' from the current data
    //     note: at some point there will be a reimport process that allows URI changing
    //          this will require that there be an OMR identifier embedded in the incoming data

    switch ($fileType) {
        case "csv":
            if ('vocab' == $type) {
                // Get array of heading names found
                $headings = $reader->getHeadings();
                $fields   = ConceptPeer::getFieldNames();

                //set the map
                //      $map[] = array("property" => "Uri", "column" => "URILocal");
                //      $map[] = array("property" => "prefLabel", "column" => "skos:prefLabel");
                //      $map[] = array("property" => "definition", "column" => "skos:definition");
                //      $map[] = array("property" => "notation", "column" => "skos:notation");
                //      $map[] = array("property" => "scopeNote", "column" => "skos:scopeNote");

                $map = array(
                  "uri"        => "URILocal",
                  "prefLabel"  => "skos:prefLabel",
                  "definition" => "skos:definition",
                  "notation"   => "skos:notation",
                  "scopeNote"  => "skos:scopeNote"
                );

                $rows = 0;

                //executeImport:

                //    serialize the column map
                try {
                    while ($row = $reader->getRow()) {
                        $rows ++;
                        //        lookup the URI (or the OMR ID if available) for a match
                        $uri        = $baseDomain . $row[$map["uri"]];
                        $concept    = ConceptPeer::getConceptByUri($uri);
                        $updateTime = time();
                        $language   = (isset($map['language'])) ? $row[$map['language']] : $vocabObj->getLanguage();

                        if (! $concept) {
                            //          create a new concept or element
                            $concept = new Concept();
                            $concept->setVocabulary($vocabObj);
                            $concept->setUri($uri);
                            /**
                             * @todo Need to handle updates for topconcept here, just like language
                             **/
                            $concept->setIsTopConcept(false);
                            $concept->updateFromRequest(
                                    $userId,
                                      fixEncoding(rtrim($row[$map['prefLabel']])),
                                      $language,
                                      $statusId
                            );
                        } //don't update the concept if the preflabel matches
                        else if ($row[$map['prefLabel']] != $concept->getPrefLabel()) {
                            $concept->updateFromRequest($userId, fixEncoding(rtrim($row[$map['prefLabel']])));
                        }

                        //there needs to be a language to lookup the properties unless it's an objectProperty
                        $rowLanguage = (isset($map['language'])) ? $row[$map['language']] : $concept->getLanguage();

                        foreach ($map as $key => $value) {
                            //we skip because we already did them
                            if (! in_array(
                              $key,
                              array(
                                'uri',
                                'prefLabel',
                                'language'
                              )
                            )
                            ) {
                                $skosId = $skosMap[$key];
                                //check to see if the property already exists
                                $property =
                                  ConceptPropertyPeer::lookupProperty($concept->getId(), $skosId, $rowLanguage);

                                //create a new property for each unmatched column
                                if (! empty($row[$value])) {
                                    if (! $property) {
                                        $property = new ConceptProperty();
                                        $property->setCreatedUserId($userId);
                                        $property->setConceptId($concept->getId());
                                        $property->setCreatedAt($updateTime);
                                        $property->setSkosPropertyId($skosId);
                                    }

                                    if (($row[$value] != $property->getObject()) ||
                                        ($rowLanguage != $property->getLanguage())
                                    ) {
                                        /**
                                         * @todo We need a check here for skos objectproperties and handle differently
                                         **/
                                        if ($rowLanguage != $property->getLanguage()) {
                                            $property->setLanguage($rowLanguage);
                                        }
                                        if ($row[$value] != $property->getObject()) {
                                            $property->setObject(fixEncoding(rtrim($row[$value])));
                                        }
                                        $property->setUpdatedUserId($userId);
                                        $property->setUpdatedAt($updateTime);
                                        $property->save();
                                    }
                                } //the row value is empty
                                else if ($deleteMissing && $property) {
                                    $property->delete();
                                }
                            }
                        }

                        //          else
                        //               lookup and update concept or element
                        //               lookup and update each property
                        //          update the history for each property, action is 'import', should be a single timestamp for all (this should be automatic)
                        //          if 'delete missing properties' is true
                        //               delete each existing, non-required property that wasn't updated by the import
                    }
                } catch(Exception $e) {
                    //          catch
                    //            if there's an error of any kind, write to error log and continue
                    echo "Error on row: " . $rows . ", " . $uri . "\n" . $e . "\n";
                    continue;
                }
                $objects = $vocabObj->countConcepts();
            } else //it's an element set
            {
                $import->setCsvReader($import->file);
                $import->processProlog();
                $import->getDataColumnIds();
                $import->processData();
                //todo: $results should be a class
                $results[$vocabId] = $import->results;
                $bacthId = $import->saveResults($batchId);
            }
            break;
        case "json":
            break;
        case "rdf":
            break;
        case "xml":
            break;
        default:
    }

    /* output to stdout*/
    //          number of objects imported (link to history, filtered on timestamp of import)
    echo " Rows imported: " . count($results[$vocabId]['success']['rows']) . "\n From File:" . $filePath . "\nUse this ID for more in this batch: " . $bacthId;
    //          number of errors (link to error log)

}
コード例 #19
0
function delConcept($id)
{
    $tobeDeleted = new Concept($id);
    if ($tobeDeleted->isNew()) {
        return true;
    }
    // item never existed in the first place
    if ($tobeDeleted->del()) {
        return true;
    } else {
        return $tobeDeleted;
    }
}
コード例 #20
0
    /**
     * @param \ConceptProperty | \ConceptProperty[] $dbElement
     * @param \Concept                              $concept
     *
     * @return int
     * @throws \PropelException
     */
    private function deleteConceptProperty(&$dbElement, &$concept)
    {
        if ( ! is_array($dbElement)) {
            //we don't delete derived properties at this stage
//      if (in_array($dbElement->getProfilePropertyId(),[6,9]))
//      {
//        return 0;
//      }
            $profileProperty = $this->profileProperties[$dbElement->getProfileProperty()->getId()];
            if ($profileProperty->getIsInForm() and $concept->getLanguage() == $dbElement->getLanguage()) {
                $this->setConceptValue('',
                                       $concept,
                                       $profileProperty->getName(), ! $profileProperty->getIsObjectProp());
            }
            $dbElement->setUpdatedUserId($this->userId);
            $dbElement->importId = $this->importId;

            //$affectedRows = $dbElement->save();
            return $dbElement->delete();
        } else {
            $affectedRows = 0;
            /** @var \ConceptProperty $element */
            foreach ($dbElement as &$element) {
                $affectedRows += $this->deleteConceptProperty($element, $concept);
            }

            return $affectedRows;
        }
    }
コード例 #21
0
 public function getInterfacesToReadConcept($concept)
 {
     $interfaces = array();
     foreach ($this->accessibleInterfaces as $interface) {
         if ($interface->srcConcept == $concept || in_array($concept, Concept::getSpecializations($interface->srcConcept)) && $interface->crudR) {
             $interfaces[] = $interface;
         }
     }
     return $interfaces;
 }
コード例 #22
0
ファイル: Api.php プロジェクト: 4ZP6Capstone2015/ampersand
 /**
  * @url GET resource/{concept}
  * @param string $concept
  * @param array $roleIds
  */
 public function getConceptAtoms($concept, $roleIds = null)
 {
     try {
         $session = Session::singleton();
         $session->activateRoles($roleIds);
         if (!in_array($concept, $session->getEditableConcepts())) {
             throw new Exception("You do not have access for this call", 403);
         }
         return Concept::getAllAtomObjects($concept);
         // "Return list of all atoms for $concept"
     } catch (Exception $e) {
         throw new RestException($e->getCode(), $e->getMessage());
     }
 }
コード例 #23
0
 public static function getAffectedInvConjuncts($affectedConcepts, $affectedRelations)
 {
     $affectedConjuncts = array();
     foreach ($affectedConcepts as $concept) {
         $affectedConjuncts = array_merge($affectedConjuncts, (array) Concept::getAffectedInvConjuncts($concept));
     }
     foreach ($affectedRelations as $fullRelationSignature) {
         $affectedConjuncts = array_merge($affectedConjuncts, (array) Relation::getAffectedInvConjunctIds($fullRelationSignature));
     }
     return array_unique($affectedConjuncts);
     // remove duplicate entries.
 }
コード例 #24
0
 public static function getConceptPropertyArray(\Concept $concept, $collapse = true)
 {
     $properties = $concept->getConceptPropertysRelatedByConceptIdJoinProfilePropertyRelatedBySkosPropertyId();
     /** @var array $properties */
     $properties = $properties ?: [];
     $array['@id'] = $concept->getUri();
     $array['@type'] = 'Concept';
     $array['api'] = 'http://api.metadataregistry.org/concepts/' . $concept->getId();
     $array['inScheme'] = $concept->getVocabulary()->getUri();
     $array['status'] = $concept->getStatus()->getDisplayName();
     if ($properties) {
         foreach ($properties as $property) {
             if (!$property->getDeletedAt()) {
                 /** @var \ProfileProperty $profile */
                 $profile = $property->getProfileProperty();
                 if ($profile->getHasLanguage()) {
                     if ($profile->getIsSingleton()) {
                         $array[$profile->getName()][$property->getLanguage()] = $property->getObject();
                     } else {
                         $array[$profile->getName()][$property->getLanguage()][] = $property->getObject();
                     }
                 } else {
                     if ($profile->getIsSingleton()) {
                         $array[$profile->getName()] = $property->getObject();
                     } else {
                         $array[$profile->getName()][] = $property->getObject();
                     }
                 }
             }
         }
     }
     if ($collapse) {
         $collapsedArray = [];
         foreach ($array as $key => $element) {
             if (is_array($element)) {
                 foreach ($element as $index => $item) {
                     if (is_array($item) && count($item) == 1) {
                         $collapsedArray[$key][$index] = $item[0];
                     } else {
                         $collapsedArray[$key][$index] = $item;
                     }
                 }
             } else {
                 $collapsedArray[$key] = $element;
             }
         }
         return $collapsedArray;
     }
     return $array;
 }
コード例 #25
0
 /**
  * Render the definitions column
  */
 protected function _renderColumn_Definitions(ConceptSearchResultsGroup $csrg, Concept $c, $group_i, $i)
 {
     echo "\n<td class=\"col_4\">\n\t";
     // Get the search terms
     $arr_term_type = array(MCL_SEARCH_TERM_TYPE_TEXT, MCL_SEARCH_TERM_TYPE_CONCEPT_DESCRIPTION);
     $arr_search_term = $csrg->csg->getSearchTermCollection()->getSearchTerms($arr_term_type, null, true);
     // Definitions
     foreach ($c->getConceptDescriptionIds() as $_desc_i) {
         $cd = $c->getConceptDescription($_desc_i);
         $desc = htmlentities($cd->description);
         foreach ($arr_search_term as $search_term) {
             $desc = preg_replace('/\\b(' . addslashes($search_term->needle) . ')/i', '<span class="h">$1</span>', $desc);
         }
         echo '<div class="concept_def"><span class="concept_def_header">[' . $cd->locale . ']</span> ' . $desc . "</div>";
     }
     /**
      * Answers - Only the first CSRR::num_display_qa_results answers are visible; set to zero to make 
      * all visible by default.
      */
     if ($c->hasAnswers()) {
         echo "<div style=\"margin-bottom:15px;\">This concept is a question with the following answer(s):\n";
         echo '<ul class="qa_set" style="margin-bottom:0;padding-bottom:0;">';
         $_i = 0;
         $num_results = $c->getNumberAnswers();
         foreach ($c->getAnswerIds() as $_answer_id) {
             $ca = $this->cc->getConcept($_answer_id, $c->css_dict);
             echo '<li>' . htmlentities($ca->getPreferredName()) . ' (<a href="' . $this->getSearchUrl('id:' . $_answer_id, array('source' => $c->css_dict->dict_db)) . '">' . $_answer_id . '</a>)</li>';
             $_i++;
             if ($_i == $this->num_display_qa_results && $num_results > $this->num_display_qa_results) {
                 $ul_toggle_id = 'ul_answer_toggle_' . $c->css_dict->dict_id . '_' . $group_i . '_' . $c->concept_id;
                 $ul_more_id = 'ul_answer_more_' . $c->css_dict->dict_id . '_' . $group_i . '_' . $c->concept_id;
                 $num_more_results = $num_results - $this->num_display_qa_results;
                 echo "</ul>\n" . '<ul id="' . $ul_toggle_id . '" style="padding-left:24px;margin-top:6px;padding-top:0;list-style-type:none;">' . '<li><a href="javascript:toggleElementVisibility(\'' . $ul_toggle_id . '\');toggleElementVisibility(\'' . $ul_more_id . '\');">' . 'See ' . $num_more_results . ' more...</a></li></ul>' . "\n";
                 echo '<ul class="qa_set" id="' . $ul_more_id . '" style="display:none;margin-top:0;padding-top:0;margin-bottom:0;padding-bottom:0;">';
             }
         }
         echo '</ul></div>';
     }
     /**
      * Questions - Only the first CSRR::num_display_qa_results questions are visible; 
      * set to zero to make all visible by default.
      */
     if ($c->hasQuestions()) {
         echo "<div style=\"margin-bottom:15px;\">This concept is an answer for the following question(s):\n";
         echo '<ul class="qa_set" style="margin-bottom:0;padding-bottom:0;">';
         $_i = 0;
         $num_results = $c->getNumberQuestions();
         foreach ($c->getQuestionIds() as $_question_id) {
             $cq = $this->cc->getConcept($_question_id, $c->css_dict);
             echo '<li>' . htmlentities($cq->getPreferredName()) . ' (<a href="' . $this->getSearchUrl('id:' . $_question_id, array('source' => $c->css_dict->dict_db)) . '">' . $_question_id . '</a>)</li>';
             $_i++;
             if ($_i == $this->num_display_qa_results && $num_results > $this->num_display_qa_results) {
                 echo "</ul>\n";
                 $ul_toggle_id = 'ul_question_toggle_' . $c->css_dict->dict_id . '_' . $c->concept_id;
                 $ul_more_id = 'ul_question_more_' . $c->css_dict->dict_id . '_' . $c->concept_id;
                 $num_more_results = $num_results - $this->num_display_qa_results;
                 echo '<ul id="' . $ul_toggle_id . '" style="padding-left:24px;margin-top:6px;padding-top:0;list-style-type:none;">' . '<li><a href="javascript:toggleElementVisibility(\'' . $ul_toggle_id . '\');toggleElementVisibility(\'' . $ul_more_id . '\');">' . 'See ' . $num_more_results . ' more...</a></li></ul>' . "\n";
                 echo '<ul class="qa_set" id="' . $ul_more_id . '" style="display:none;margin-top:0;padding-top:0;margin-bottom:0;padding-bottom:0;">';
             }
         }
         echo '</ul></div>';
     }
     // End of column 3
     echo '</td>';
 }
コード例 #26
0
ファイル: Role.php プロジェクト: 4ZP6Capstone2015/Capstone
 private function getInterfacesForConcept($concept)
 {
     $interfaces = array();
     foreach ($this->getSessionInterfaces() as $interface) {
         if ($interface->srcConcept == $concept || in_array($concept, Concept::getSpecializations($interface->srcConcept))) {
             $interfaces[] = $interface;
         }
     }
     return $interfaces;
 }
コード例 #27
0
 public function typeConversion($value, $concept)
 {
     switch (Concept::getTypeRepresentation($concept)) {
         case "DATE":
             $datetime = new DateTime($value);
             return $datetime->format('Y-m-d');
             // format to store in database
         // format to store in database
         case "DATETIME":
             $datetime = new DateTime($value);
             // $value can include timezone, e.g. 2005-08-15T15:52:01+00:00 (DATE_ATOM format)
             $datetime->setTimezone(new DateTimeZone('UTC'));
             // convert to UTC to store in database
             return $datetime->format('Y-m-d H:i:s');
             // format to store in database (UTC)
         // format to store in database (UTC)
         case "INTEGER":
             return (int) $value;
         case "BOOLEAN":
             return (bool) $value;
         case "DECIMAL":
             return (double) $value;
         default:
             return $value;
     }
 }
コード例 #28
0
ファイル: conceptos.php プロジェクト: ricardocasares/Cobros
 function eliminar($id)
 {
     $a = Concept::find($id);
     $a->delete();
     $this->session->set_flashdata('msg', '<div class="success">El Concepto fué eliminado correctamente.</div>');
     redirect('conceptos');
 }
コード例 #29
0
 /**
  * Return a ConceptCollection containing the concepts that match the search
  * criteria described in the passed ConceptSearch object. It iterates through 
  * each search group. This function only returns fields from the concept table. 
  * It is intended to be followed by other functions to retrieve additional 
  * concept info.
  * @param ConceptSearch $cs
  * @access private
  */
 private function _loadConcepts(ConceptSearch $cs)
 {
     $cc = new ConceptCollection();
     $csrg = null;
     $group_i = 0;
     // Iterate through ConceptSearchGroup objects, perform base query and
     // create the concepts for each
     foreach (array_keys($cs->arr_search_group) as $group_key) {
         $group_i++;
         $csg = $cs->arr_search_group[$group_key];
         $csrg = new ConceptSearchResultsGroup($csg);
         $ctsc = $csg->getSearchTermCollection();
         $cc->addGroup($csrg);
         // Get sql statements for this search group
         $coll_csg_sql = $this->_buildSqlFromConceptSearchGroup($cs, $csg);
         $csrg->coll_sql_obj = $coll_csg_sql;
         // Debug info for the search group
         if ($this->debug || $this->verbose) {
             echo '<p><b>Concept Search Group ' . $group_i . ':</b> ' . $csg->query . '<br><ul>';
         }
         // Iterate through the sql collection and execute
         foreach ($coll_csg_sql->getKeys() as $key) {
             $sql_obj = $coll_csg_sql->Get($key);
             // Debug info for sql statements
             if ($this->debug || $this->verbose) {
                 echo '</li><strong>' . $sql_obj->source->getKey();
                 if ($sql_obj->css_sub_list_dict) {
                     echo ' - ' . $sql_obj->css_sub_list_dict->getKey();
                 }
                 echo ' : </strong> ';
                 if ($sql_obj->sql) {
                     echo htmlentities($sql_obj->sql);
                 } else {
                     echo '<em>[[ EMPTY SEARCH QUERY ]]</em></li>';
                 }
             }
             // Skip if no sql
             if (!$sql_obj->sql) {
                 continue;
             }
             // Get the connection and execute
             $css_dict = $sql_obj->getDictionarySource();
             $conn = $css_dict->getConnection();
             $rsc_search = mysql_query($sql_obj->sql, $conn);
             if (!$rsc_search) {
                 trigger_error("could not query db in ConceptSearchFactory::_loadConcepts: " . mysql_error());
             }
             // Create/get the concepts and add to the collection
             while ($row = mysql_fetch_assoc($rsc_search)) {
                 // Create the concept if it does not already exist
                 $c = null;
                 if (!($c = $cc->getConcept($row['concept_id'], $css_dict))) {
                     $c = new Concept($row['concept_id'], $row['retired'], $row['is_set'], $row['class_id'], $row['class_name'], $row['datatype_id'], $row['datatype_name']);
                     $c->uuid = $row['uuid'];
                     // keeping this separate to add version compatibility later
                     if ($row['date_created']) {
                         $c->setAttribute('Date created', $row['date_created']);
                     }
                     if ($row['retired_by']) {
                         $c->setAttribute('Date Retired', $row['retired_by']);
                     }
                     if ($row['date_retired']) {
                         $c->setAttribute('Retired by', $row['date_retired']);
                     }
                     if ($row['retire_reason']) {
                         $c->setAttribute('Retire reason', $row['retire_reason']);
                     }
                     $c->css_dict = $css_dict;
                     $cc->addConcept($c);
                 }
                 // Relevancy - assign Fulltext Search relevancy only for now
                 $relevancy = null;
                 if (isset($row['relevancy'])) {
                     $relevancy = $row['relevancy'];
                 }
                 // Add to the search results group
                 $csrg->addConcept($c, $relevancy);
             }
             // Debug/verbose info
             if ($this->debug || $this->verbose) {
                 echo '<ul><li><strong>' . $csrg->getCount($css_dict) . ' concept(s) returned:</strong> ' . implode(', ', $csrg->getConceptIds($css_dict));
                 echo '</li></ul></li>';
             }
         }
         // end ConceptSearchSqlCollection loop
         // End debug output
         if ($this->debug || $this->verbose) {
             echo '</ul></p>';
         }
     }
     // end ConceptSearchGroup loop
     return $cc;
 }
コード例 #30
0
ファイル: Atom.php プロジェクト: 4ZP6Capstone2015/Capstone
 public function typeConversion($value, $concept)
 {
     switch (Concept::getTypeRepresentation($concept)) {
         case "DATE":
             $datetime = new DateTime($value);
             return $datetime->format('Y-m-d');
             // format in ISO-8601 standard
         // format in ISO-8601 standard
         case "DATETIME":
             $datetime = new DateTime($value, new DateTimeZone('UTC'));
             // datetimes are stored in UTC in database
             $datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
             // convert back to systemtime
             return $datetime->format(DateTime::ATOM);
             // format in ISO-8601 standard, i.e. 2005-08-15T15:52:01+00:00 (DateTime::ATOM)
         // format in ISO-8601 standard, i.e. 2005-08-15T15:52:01+00:00 (DateTime::ATOM)
         case "INTEGER":
             return (int) $value;
         case "BOOLEAN":
             return (bool) $value;
         case "DECIMAL":
             return (double) $value;
         default:
             return $value;
     }
 }