コード例 #1
0
 public function run()
 {
     $ext = common_ext_ExtensionsManager::singleton()->getExtensionById('ltiProvider');
     if ($ext->isInstalled()) {
         common_Logger::t('Uninstall ltiProvider');
         $db = core_kernel_classes_DbWrapper::singleton();
         $sql = "DELETE from extensions where id ='ltiProvider';";
         $db->exec($sql);
         tao_helpers_File::delTree($ext->getConstant('BASE_PATH'));
         $newExt = common_ext_ExtensionsManager::singleton()->getExtensionById('taoLti');
         taoUpdate_models_classes_DataMigrationService::singleton()->installExtension($newExt);
     }
 }
コード例 #2
0
ファイル: CardinalityTest.php プロジェクト: nagyist/tao-core
 /**
  * Test the service factory: dynamical instantiation and single instance serving
  */
 public function testMultiple()
 {
     $propClass = new core_kernel_classes_Class(RDF_PROPERTY);
     $q = "SELECT subject, count(object)\n                FROM statements\n                    WHERE predicate = ?\n                    GROUP BY subject\n                    HAVING (count(object) > 1)";
     foreach ($propClass->getInstances(true) as $property) {
         $property = new core_kernel_classes_Property($property);
         if (!$property->isMultiple() && !$property->isLgDependent()) {
             // bypass generis
             $result = core_kernel_classes_DbWrapper::singleton()->query($q, array($property->getUri()));
             while ($statement = $result->fetch()) {
                 $this->fail($property->getUri() . ' has multiple values but is not multiple.');
             }
         }
     }
 }
コード例 #3
0
 /**
  * Generates a URI based on a serial stored in the database.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return string
  * @throws common_UriProviderException
  */
 public function provide()
 {
     $returnValue = (string) '';
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     try {
         $sth = $this->getPersistence()->query($this->getPersistence()->getPlatForm()->getSqlFunction("generis_sequence_uri_provider"), array($this->getOption(self::OPTION_NAMESPACE)));
         if ($sth !== false) {
             $row = $sth->fetch();
             $returnValue = current($row);
             $sth->closeCursor();
         } else {
             throw new common_uri_UriProviderException("An error occured while calling the stored procedure for persistence " . $this->getOption(self::OPTION_PERSISTENCE) . ".");
         }
     } catch (Exception $e) {
         throw new common_uri_UriProviderException("An error occured while calling the stored ': " . $e->getMessage() . ".");
     }
     return (string) $returnValue;
 }
コード例 #4
0
 private function add($data)
 {
     $subject = new core_kernel_classes_Resource($data['s']);
     $property = new core_kernel_classes_Property($data['p']);
     $object = $data['o'];
     $lg = is_null($data['l']) ? '' : $data['l'];
     if (!$this->exists($subject, $property, $object, $lg)) {
         $nsPrefix = substr($data['s'], 0, strpos($data['s'], '#') + 1);
         $ns = isset($this->namespaceCache[$nsPrefix]) ? $this->namespaceCache[$nsPrefix]->getModelId() : common_ext_NamespaceManager::singleton()->getLocalNamespace()->getModelId();
         if (!core_kernel_classes_DbWrapper::singleton()->query($this->updateQuery, array($ns, $subject->getUri(), $property->getUri(), $object, $lg))) {
             $this->err('Add query failed');
         }
         if (!$this->exists($subject, $property, $object, $lg)) {
             $this->err('Did not add ' . $subject->getUri() . ':' . $property->getUri() . ':"' . $object . '"@' . $lg);
         }
     } else {
         $this->out('Already existed ' . $subject->getUri() . ':' . $property->getUri() . ':"' . $object . '"@' . $lg);
     }
 }
コード例 #5
0
 private function getRdfTriples(\core_kernel_classes_Resource $resource, $usingRestrictionOn = "object")
 {
     $returnValue = null;
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $query = 'SELECT * FROM "statements" WHERE "' . $usingRestrictionOn . '" = ? order by modelid ';
     $result = $dbWrapper->query($query, array($resource->getUri()));
     $returnValue = new \core_kernel_classes_ContainerCollection(new \common_Object(__METHOD__));
     while ($statement = $result->fetch()) {
         $triple = new \core_kernel_classes_Triple();
         $triple->modelid = $statement["modelid"];
         $triple->subject = $statement["subject"];
         $triple->predicate = $statement["predicate"];
         $triple->object = $statement["object"];
         $triple->id = $statement["id"];
         $triple->lg = $statement["l_language"];
         $triple->author = $statement["author"];
         $returnValue->add($triple);
     }
     return $returnValue;
 }
コード例 #6
0
 public function run()
 {
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $sth = $dbWrapper->prepare('SELECT DISTINCT "author" FROM statements');
     $result = $sth->execute();
     $updateQuery = $dbWrapper->prepare('UPDATE statements SET "author" = ? WHERE "author" = ?;');
     foreach ($sth->fetchAll() as $data) {
         if (!empty($data['author'])) {
             $login = $data['author'];
             $user = core_kernel_users_Service::singleton()->getOneUser($login);
             if (is_null($user)) {
                 $this->out('User with login ' . $login . ' not found, skipping');
             } else {
                 if (!$updateQuery->execute(array($user->getUri(), $login))) {
                     $this->err('Unable to replace ' . $login . ' with ' . $user->getUri());
                 }
             }
         }
     }
 }
コード例 #7
0
 /**
  * Generates a URI based on the value of PHP microtime() and rand().
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return string
  */
 public function provide()
 {
     $returnValue = (string) '';
     $modelUri = common_ext_NamespaceManager::singleton()->getLocalNamespace()->getUri();
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $uriExist = false;
     do {
         list($usec, $sec) = explode(" ", microtime());
         $uri = $modelUri . 'i' . str_replace(".", "", $sec . "" . $usec) . rand(0, 1000);
         $sqlResult = $dbWrapper->query("SELECT COUNT(subject) AS num FROM statements WHERE subject = '" . $uri . "'");
         if ($row = $sqlResult->fetch()) {
             $found = (int) $row['num'];
             if ($found > 0) {
                 $uriExist = true;
             }
             $sqlResult->closeCursor();
         }
     } while ($uriExist);
     $returnValue = $uri;
     return (string) $returnValue;
 }
コード例 #8
0
ファイル: RdfExportTest.php プロジェクト: nagyist/generis
 public function testFullExport()
 {
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $result = $dbWrapper->query('SELECT count(*) FROM (SELECT DISTINCT subject, predicate, object, l_language FROM statements) as supercount')->fetch();
     $triples = $result[0];
     $result = $dbWrapper->query('SELECT modelid FROM "models"');
     $modelIds = array();
     while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
         $modelIds[] = $row['modelid'];
     }
     $xml = core_kernel_api_ModelExporter::exportModels($modelIds);
     $doc = new DOMDocument();
     $doc->loadXML($xml);
     $count = 0;
     $descriptions = $doc->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Description');
     foreach ($descriptions as $description) {
         foreach ($description->childNodes as $child) {
             if ($child instanceof DOMElement) {
                 $count++;
             }
         }
     }
     $this->assertEquals($triples, $count);
 }
コード例 #9
0
ファイル: FileModel.php プロジェクト: nagyist/generis
 /**
  * @param string $file
  * @throws common_exception_Error
  */
 public static function getModelIdFromXml($file)
 {
     $xml = simplexml_load_file($file);
     $attrs = $xml->attributes('xml', true);
     if (!isset($attrs['base']) || empty($attrs['base'])) {
         throw new common_exception_Error('The namespace of ' . $file . ' has to be defined with the "xml:base" attribute of the ROOT node');
     }
     $namespaceUri = (string) $attrs['base'];
     $modelId = null;
     foreach (common_ext_NamespaceManager::singleton()->getAllNamespaces() as $namespace) {
         if ($namespace->getUri() == $namespaceUri) {
             $modelId = $namespace->getModelId();
         }
     }
     if (is_null($modelId)) {
         \common_Logger::d('modelId not found, need to add namespace ' . $namespaceUri);
         //TODO bad way, need to find better
         $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
         $results = $dbWrapper->insert('models', array('modeluri' => $namespaceUri));
         $modelId = $dbWrapper->lastInsertId('models');
         common_ext_NamespaceManager::singleton()->reset();
     }
     return $modelId;
 }
コード例 #10
0
ファイル: class.Profiler.php プロジェクト: nagyist/generis
 protected function logMysqlProfiles()
 {
     $this->initMysqlProfiler();
     //get sql profile data
     $profiles = array();
     $profile = array();
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $sqlProfilesResult = $dbWrapper->query('SHOW PROFILES');
     while ($row = $sqlProfilesResult->fetch()) {
         $id = $row['Query_ID'];
         $sqlDataResult = $dbWrapper->query('SHOW PROFILE FOR QUERY ' . $id);
         $profileData = array();
         while ($r = $sqlDataResult->fetch()) {
             $profileData[$r[0]] = $r;
         }
         $profiles[$id] = $profileData;
         $profiles[$id]['duration'] = $row['Duration'];
         $profiles[$id]['query'] = $row['Query'];
     }
     $sqlResult = $dbWrapper->query('SHOW PROFILE');
     while ($row = $sqlResult->fetch()) {
         $profile[$row[0]] = $row;
     }
     $report = array('queriesCount' => $dbWrapper->getNrOfQueries(), 'profile' => $profile, 'profiles' => $profiles);
     $this->log(json_encode($report));
 }
コード例 #11
0
 /**
  * Short description of method removeType
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  Resource resource
  * @param  Class class
  * @return boolean
  */
 public function removeType(\core_kernel_classes_Resource $resource, \core_kernel_classes_Class $class)
 {
     $returnValue = (bool) false;
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $referencer = ResourceReferencer::singleton();
     if ($resource->hasType($class)) {
         $resourceId = intval(Utils::getResourceToTableId($resource));
         $classInfo = Utils::getClassInfo($class);
         $triples = $resource->getRdfTriples();
         if (!empty($resourceId)) {
             $resource->delete(false);
             $referencer->unReferenceResource($resource);
             $query = 'INSERT INTO "statements" ("modelid", "subject", "predicate", "object", "l_language") VALUES  (?, ?, ?, ?, ?);';
             foreach ($triples as $t) {
                 $dbWrapper->exec($query, array(99999, $t->subject, $t->predicate, $t->object, $t->lg));
             }
         }
     }
     $returnValue = true;
     return (bool) $returnValue;
 }
コード例 #12
0
 public static function getClassInfo(\core_kernel_classes_Class $class)
 {
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $sql = 'SELECT "id", "table" FROM "class_to_table" WHERE "uri" = ?';
     $result = $dbWrapper->query($sql, array($class->getUri()));
     $returnValue = false;
     while ($row = $result->fetch()) {
         $returnValue = array('id' => $row['id'], 'table' => $row['table']);
         $result->closeCursor();
         return $returnValue;
     }
     return $returnValue;
 }
コード例 #13
0
 /**
  * Entry point.
  * Enables you to retrieve staticly the DbWrapper instance.
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @throws core_kernel_persistence_Exception
  * @return core_kernel_classes_DbWrapper
  */
 public static function singleton()
 {
     $returnValue = null;
     if (!isset(self::$instance)) {
         $c = __CLASS__;
         self::$instance = new $c();
     }
     $returnValue = self::$instance;
     return $returnValue;
 }
コード例 #14
0
 /**
  * (non-PHPdoc)
  * @see core_kernel_persistence_ClassInterface::createInstanceWithProperties()
  */
 public function createInstanceWithProperties(\core_kernel_classes_Class $type, $properties)
 {
     $returnValue = null;
     if (isset($properties[RDF_TYPE])) {
         throw new \core_kernel_persistence_Exception('Additional types in createInstanceWithProperties not permited');
     }
     $uri = \common_Utils::getNewUri();
     $table = '_' . HardapiUtils::getShortName($type);
     // prepare properties
     $hardPropertyNames = array("uri" => $uri);
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     if (is_array($properties)) {
         if (count($properties) > 0) {
             // Get the table name
             $referencer = ResourceReferencer::singleton();
             $queryProps = array();
             foreach ($properties as $propertyUri => $value) {
                 $property = new \core_kernel_classes_Property($propertyUri);
                 $propertyLocation = $referencer->propertyLocation($property);
                 if (in_array("{$table}props", $propertyLocation) || !$referencer->isPropertyReferenced($property)) {
                     $propertyRange = $property->getRange();
                     $lang = $property->isLgDependent() ? \common_session_SessionManager::getSession()->getDataLanguage() : '';
                     $formatedValues = array();
                     if ($value instanceof \core_kernel_classes_Resource) {
                         $formatedValues[] = $dbWrapper->quote($value->getUri());
                     } else {
                         if (is_array($value)) {
                             foreach ($value as $val) {
                                 if ($val instanceof \core_kernel_classes_Resource) {
                                     $formatedValues[] = $dbWrapper->quote($val->getUri());
                                 } else {
                                     $formatedValues[] = $dbWrapper->quote($val);
                                 }
                             }
                         } else {
                             $formatedValues[] = $dbWrapper->quote($value);
                         }
                     }
                     if (is_null($propertyRange) || $propertyRange->getUri() == RDFS_LITERAL) {
                         foreach ($formatedValues as $formatedValue) {
                             $queryProps[] = "'{$property->getUri()}', {$formatedValue}, null, '{$lang}'";
                         }
                     } else {
                         foreach ($formatedValues as $formatedValue) {
                             $queryProps[] = "'{$property->getUri()}', null, {$formatedValue}, '{$lang}'";
                         }
                     }
                 } else {
                     $propertyName = HardapiUtils::getShortName($property);
                     if (is_array($value)) {
                         if (count($value) > 1) {
                             throw new Exception("try setting multivalue for the non multiple property {$property->getLabel()} ({$property->getUri()})");
                         } else {
                             $value = count($value) == 0 ? null : reset($value);
                             // take the only element
                         }
                     }
                     if ($value instanceof \core_kernel_classes_Resource) {
                         $value = $value->getUri();
                     }
                     $hardPropertyNames[$propertyName] = $value;
                 }
             }
         }
     }
     // spawn
     $returnValue = new \core_kernel_classes_Resource($uri, __METHOD__);
     $varnames = '"' . implode('","', array_keys($hardPropertyNames)) . '"';
     try {
         $query = 'INSERT INTO "' . $table . '" (' . $varnames . ') VALUES (' . implode(',', array_fill(0, count($hardPropertyNames), '?')) . ')';
         $result = $dbWrapper->exec($query, array_values($hardPropertyNames));
         // reference the newly created instance
         ResourceReferencer::singleton()->referenceResource($returnValue, $table, array($type), true);
         // @todo this shoould be retrievable without an aditional query
         $instanceId = Utils::getInstanceId($returnValue);
         // @todo Merge into a single query
         if (!empty($queryProps)) {
             $prefixed = array();
             foreach ($queryProps as $row) {
                 $prefixed[] = ' (' . $instanceId . ', ' . $row . ')';
             }
             try {
                 $query = 'INSERT INTO "' . $table . 'props" ("instance_id", "property_uri", "property_value", "property_foreign_uri", "l_language") VALUES ' . implode(',', $prefixed);
                 $result = $dbWrapper->exec($query);
             } catch (\PDOException $e) {
                 throw new Exception("Unable to set properties (multiple) Value for the instance {$returnValue->getUri()} in {$tableName} : " . $e->getMessage());
             }
         }
     } catch (\PDOException $e) {
         throw new Exception("Unable to create instance for the class {$type->getUri()} in the table {$table} : " . $e->getMessage());
     }
     return $returnValue;
 }
コード例 #15
0
 /**
  * Removes an existing column from the table.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @param  string name The name of the column to remove from the table.
  * @return boolean
  */
 public function removeColumn($name)
 {
     $returnValue = (bool) false;
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     if (!empty($name)) {
         $tblname = $this->getName();
         $sql = 'ALTER TABLE "' . $tblname . '" DROP COLUMN ' . $dbWrapper->quoteIdentifier($name);
         try {
             $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
             $dbWrapper->exec($sql);
             $returnValue = true;
         } catch (\PDOException $e) {
             throw new Exception("An error occured while removing column '{$name}' from table '{$tblname}': " . $e->getMessage());
         }
     } else {
         throw new InvalidArgumentException("Empty column name provided.");
     }
     return (bool) $returnValue;
 }
コード例 #16
0
 /**
  * Adds a statement to the ontology if it does not exist yet
  * 
  * @author "Joel Bout, <*****@*****.**>"
  * @param int $modelId
  * @param string $subject
  * @param string $predicate
  * @param string $object
  * @param string $lang
  */
 private function addStatement($modelId, $subject, $predicate, $object, $lang = null)
 {
     $result = core_kernel_classes_DbWrapper::singleton()->query('SELECT count(*) FROM statements WHERE modelid = ? AND subject = ? AND predicate = ? AND object = ? AND l_language = ?', array($modelId, $subject, $predicate, $object, is_null($lang) ? '' : $lang));
     if (intval($result->fetchColumn()) === 0) {
         $dbWrapper = core_kernel_classes_DbWrapper::singleton();
         $date = $dbWrapper->getPlatForm()->getNowExpression();
         $dbWrapper->insert('statements', array('modelid' => $modelId, 'subject' => $subject, 'predicate' => $predicate, 'object' => $object, 'l_language' => is_null($lang) ? '' : $lang, 'author' => 'http://www.tao.lu/Ontologies/TAO.rdf#installator', 'epoch' => $date));
     }
 }
コード例 #17
0
ファイル: class.ApiModelOO.php プロジェクト: nagyist/generis
 /**
  * Short description of method getObject
  *
  * @access public
  * @author firstname and lastname of author, <*****@*****.**>
  * @param  string subject
  * @param  string predicate
  * @return core_kernel_classes_ContainerCollection
  */
 public function getObject($subject, $predicate)
 {
     $returnValue = null;
     $sqlQuery = "SELECT object FROM statements WHERE subject = ? AND predicate = ?";
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $sqlResult = $dbWrapper->query($sqlQuery, array($subject, $predicate));
     $returnValue = new core_kernel_classes_ContainerCollection(new common_Object(__METHOD__));
     while ($row = $sqlResult->fetch()) {
         $value = $row['object'];
         if (!common_Utils::isUri($value)) {
             $container = new core_kernel_classes_Literal($value);
         } else {
             $container = new core_kernel_classes_Resource($value);
         }
         $container->debug = __METHOD__;
         $returnValue->add($container);
     }
     return $returnValue;
 }
コード例 #18
0
 /**
  * Change a multi-valued property to a single-valued one.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @param  Resource property The property to modifiy.
  * @param  int batchSize Data must be transfered from the properties table to a given column. This parameter indicates the size of each pack of data transfered from the properties table to the column.
  * @return void
  */
 public static function multipleToScalar(\core_kernel_classes_Resource $property, $batchSize = 100)
 {
     $referencer = ResourceReferencer::singleton();
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $propertyDescription = self::propertyDescriptor($property);
     $propertyLocations = $referencer->propertyLocation($property);
     $propName = $propertyDescription['name'];
     $propUri = $property->getUri();
     $propRanges = array();
     foreach ($propertyDescription['range'] as $range) {
         // If no range provided, we assume it is a Literal.
         $propRanges[] = !empty($range) ? $range->getUri() : RDFS_LITERAL;
     }
     $offset = 0;
     foreach ($propertyLocations as $tblname) {
         $tblmgr = new TableManager($tblname);
         if ($tblmgr->exists()) {
             // Reset offset.
             $offset = 0;
             try {
                 // We go from multiple to single.
                 $toDelete = array();
                 // will contain ids of rows to delete in the 'properties table' after data transfer.
                 // Add a column to the base table to receive single value.
                 $baseTableName = str_replace('props', '', $tblname);
                 $tblmgr->setName($baseTableName);
                 $shortName = self::getShortName($property);
                 $columnAdded = $tblmgr->addColumn(array('name' => $shortName, 'multi' => false));
                 if ($columnAdded == true) {
                     // Now get the values in the props table. Group by instance ID in order to get only
                     // one value to put in the target column.
                     do {
                         $hasResult = false;
                         $retrievePropertyValue = empty($propRanges) || in_array(RDFS_LITERAL, $propRanges) ? true : false;
                         $sql = 'SELECT "a"."id", "a"."instance_id", "a"."property_value", "a"."property_foreign_uri" FROM "' . $tblname . '" "a" ';
                         $sql .= 'RIGHT JOIN (SELECT "instance_id", MIN("id") AS "id" FROM "' . $tblname . '" WHERE "property_uri" = ? ';
                         $sql .= 'GROUP BY "instance_id") AS "b" ON ("a"."id" = "b"."id")';
                         $sql = $dbWrapper->limitStatement($sql, $batchSize, $offset);
                         $result = $dbWrapper->query($sql, array($propUri));
                         // prepare the update statement.
                         $sql = 'UPDATE "' . $baseTableName . '" SET "' . $shortName . '" = ? WHERE "id" = ?';
                         while ($row = $result->fetch()) {
                             // Transfer to the 'base table'.
                             $hasResult = true;
                             $propertyValue = $retrievePropertyValue == true ? $row['property_value'] : $row['property_foreign_uri'];
                             $dbWrapper->exec($sql, array($propertyValue, $row['instance_id']));
                             $toDelete[] = $row['id'];
                         }
                         $offset += $batchSize;
                     } while ($hasResult === true);
                     $inData = implode(',', $toDelete);
                     $sql = 'DELETE FROM "' . $tblname . '" WHERE "id" IN (' . $inData . ')';
                     if ($dbWrapper->exec($sql) == 0) {
                         // If an error occured or no rows removed, we
                         // have a problem.
                         $msg = "Cannot set multiplicity of Property '{$propUri}' because data transfered to the 'base table' could not be deleted";
                         throw new Exception($msg);
                     }
                 } else {
                     $msg = "Cannot set multiplicity of Property '{$propUri}' because the corresponding 'base table' column could not be created.";
                     throw new Exception($msg);
                 }
             } catch (\PDOException $e) {
                 $msg = "Cannot set multiplicity of Property '{$propUri}': " . $e->getMessage();
                 throw new Exception($msg);
             }
         } else {
             $msg = "Cannot set multiplicity of Property '{$propUri}' because the corresponding database location '{$tblname}' does not exist.";
             throw new Exception($msg);
         }
     }
     $referencer->clearCaches();
 }
コード例 #19
0
 public function testHardPropertyModifications()
 {
     $this->hardify();
     $this->createData();
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $movieClass = $this->targetMovieClass;
     $workClass = $this->targetWorkClass;
     $authorProperty = $this->targetAuthorProperty;
     $producerProperty = $this->targetProducerProperty;
     $actorsProperty = $this->targetActorsProperty;
     $labelProperty = new core_kernel_classes_Property(RDFS_LABEL);
     $referencer = ResourceReferencer::singleton();
     $propertyProxy = PropertyProxy::singleton();
     // Retrieve interesting resources.
     $instances = $workClass->searchInstances(array($authorProperty->getUri() => 'Leonardo da Vinci'), array('like' => false, 'recursive' => false));
     $monaLisa = current($instances);
     $instances = $movieClass->searchInstances(array($labelProperty->getUri() => 'The Lord of the Rings'), array('like' => false, 'recursive' => false));
     $lordOfTheRings = current($instances);
     $instances = $movieClass->searchInstances(array($labelProperty->getUri() => 'The Hobbit'), array('like' => true, 'recursive' => false));
     $theHobbit = current($instances);
     if (empty($monaLisa) || empty($lordOfTheRings) || empty($theHobbit)) {
         $this->fail("Unable to retrieve instances that will be used in the following tests.");
     } else {
         // Try to create a new scalar property after hardification.
         $testProperty = $movieClass->createProperty('after hardify property');
         $testPropertyShortName = Utils::getShortName($testProperty);
         $testPropertyLocations = $referencer->propertyLocation($testProperty);
         $movieClassLocations = $referencer->classLocations($movieClass);
         $movieClassTable = $movieClassLocations[0]['table'];
         $movieClassTableColumns = array();
         foreach ($dbWrapper->getColumnNames($movieClassTable) as $col) {
             $movieClassTableColumns[] = $col->getName();
         }
         $workClassLocations = $referencer->classLocations($workClass);
         $workClassTable = $movieClassLocations[0]['table'];
         $workClassTableColumns = $dbWrapper->getColumnNames($workClassTable);
         $testPropertyShortName = Utils::getShortName($testProperty);
         $authorPropertyShortName = Utils::getShortName($authorProperty);
         // test delegation and presence of the column.
         $this->assertFalse($testProperty->isMultiple());
         $this->assertTrue(in_array($testPropertyShortName, $movieClassTableColumns));
         $this->assertIsA($propertyProxy->getImpToDelegateTo($testProperty), 'oat\\generisHard\\models\\hardsql\\Property');
         // set language dependency of the test property to true.
         $testProperty->setLgDependent(true);
         $this->assertTrue($testProperty->isLgDependent());
         $movieClassTableColumns = array();
         foreach ($dbWrapper->getColumnNames($movieClassTable) as $col) {
             $movieClassTableColumns[] = $col->getName();
         }
         $this->assertFalse(in_array($testPropertyShortName, $movieClassTableColumns));
         // create some property values for the test property.
         $testMovie = $movieClass->createInstance('A Test Movie');
         $testMovie->setPropertyValue($testProperty, 'EN-TestPropertyValue-1');
         $testMovie->setPropertyValueByLg($testProperty, 'EN-TestPropertyValue-2', DEFAULT_LANG);
         $testMovie->setPropertyValueByLg($testProperty, 'FR-TestPropertyValue-1', 'FR');
         $testPropertyValues = $testMovie->getPropertyValues($testProperty);
         $this->assertEquals(count($testPropertyValues), 2);
         // Only EN values will come back.
         $testPropertyValues = $testMovie->getPropertyValuesByLg($testProperty, DEFAULT_LANG);
         $this->assertEquals(count($testPropertyValues->sequence), 2);
         $testPropertyValues = $testMovie->getPropertyValuesByLg($testProperty, 'FR');
         $this->assertEquals(count($testPropertyValues->sequence), 1);
         // set back the language dependency of the test property to false.
         $testProperty->setLgDependent(false);
         $this->assertFalse($testProperty->isLgDependent());
         $movieClassTableColumns = array();
         foreach ($dbWrapper->getColumnNames($movieClassTable) as $col) {
             $movieClassTableColumns[] = $col->getName();
         }
         $this->assertTrue(in_array($testPropertyShortName, $movieClassTableColumns));
         $testPropertyValues = $testMovie->getPropertyValues($testProperty);
         $this->assertEquals(count($testPropertyValues), 1);
         // set the author property to multiple.
         $this->assertTrue(in_array($authorPropertyShortName, $movieClassTableColumns));
         $this->assertFalse($authorProperty->isMultiple());
         $authorProperty->setMultiple(true);
         $this->assertTrue($authorProperty->isMultiple());
         $movieClassTableColumns = array();
         foreach ($dbWrapper->getColumnNames($movieClassTable) as $col) {
             $movieClassTableColumns[] = $col->getName();
         }
         $this->assertFalse(in_array($authorPropertyShortName, $movieClassTableColumns));
         // Add a fake value to make it multi valued
         $theHobbit->setPropertyValue($authorProperty, 'The Clone of Peter Jackson');
         $authors = $theHobbit->getPropertyValues($authorProperty);
         $this->assertEquals(count($authors), 2);
         $this->assertEquals(current($authors), 'Peter Jackson');
         next($authors);
         $this->assertEquals(current($authors), 'The Clone of Peter Jackson');
         $authors = $monaLisa->getPropertyValues($authorProperty);
         $this->assertEquals(count($authors), 1);
         $this->assertEquals(current($authors), 'Leonardo da Vinci');
         // reset the author property to scalar.
         $authorProperty->setMultiple(false);
         $this->assertFalse($authorProperty->isMultiple());
         $movieClassTableColumns = array();
         foreach ($dbWrapper->getColumnNames($movieClassTable) as $col) {
             $movieClassTableColumns[] = $col->getName();
         }
         $this->assertTrue(in_array($authorPropertyShortName, $movieClassTableColumns));
         $authors = $theHobbit->getPropertyValues($authorProperty);
         $this->assertEquals(count($authors), 1);
         $this->assertEquals(current($authors), 'Peter Jackson');
     }
 }
コード例 #20
0
ファイル: DbWrapperTest.php プロジェクト: nagyist/generis
 protected function tearDown()
 {
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     //TODO need to connect to a dbWrapper a function dropTable that currently not exists
     $dbWrapper->exec('DROP TABLE "dbTestCase";');
 }
コード例 #21
0
 /**
  * Short description of method getForeignIds
  *
  * @access protected
  * @author Bertrand Chevrier, <*****@*****.**>
  * @param  array rows
  * @return array
  */
 protected function getForeignIds($rows)
 {
     $returnValue = array();
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $foreigns = array();
     foreach ($this->columns as $column) {
         if (isset($column['foreign']) && !empty($column['foreign'])) {
             $uriList = '';
             foreach ($rows as $row) {
                 $foreignResource = $row[$column['name']];
                 if ($foreignResource != null) {
                     if ($foreignResource instanceof \core_kernel_classes_Resource) {
                         $uriList .= "'{$foreignResource->getUri()}',";
                     }
                 }
             }
             if (!empty($uriList)) {
                 $uriList = substr($uriList, 0, strlen($uriList) - 1);
                 $query = 'SELECT "id", "uri" FROM "' . $column['foreign'] . '" WHERE uri IN (' . $uriList . ')';
                 $result = $dbWrapper->query($query);
                 $foreign = array();
                 while ($r = $result->fetch()) {
                     if (!isset($column['multi']) || $column['multi'] === false) {
                         $foreign[$r['uri']] = $r['id'];
                     } else {
                         $key = $r['uri'];
                         if (array_key_exists($key, $foreign)) {
                             $foreign[$r['uri']][] = $r['id'];
                         } else {
                             $foreign[$r['uri']] = array($r['id']);
                         }
                     }
                 }
                 $foreigns[$column['foreign']] = $foreign;
             }
         }
     }
     $returnValue = $foreigns;
     return (array) $returnValue;
 }
コード例 #22
0
 public function getVariableFile($variableUri)
 {
     //distinguish QTI file from other "file" base type
     $baseType = $this->getVariableBaseType($variableUri);
     // https://bugs.php.net/bug.php?id=52623 ;
     // if the constant for max buffering, mysqlnd or similar driver
     // is being used without need to adapt buffer size as it is atutomatically adapted for all the data.
     if (core_kernel_classes_DbWrapper::singleton()->getPlatForm()->getName() == 'mysql') {
         if (defined("PDO::MYSQL_ATTR_MAX_BUFFER_SIZE")) {
             $maxBuffer = is_int(ini_get('upload_max_filesize')) ? ini_get('upload_max_filesize') * 1.5 : 10485760;
             core_kernel_classes_DbWrapper::singleton()->getSchemaManager()->setAttribute(PDO::MYSQL_ATTR_MAX_BUFFER_SIZE, $maxBuffer);
         }
     }
     switch ($baseType) {
         case "file":
             $value = base64_decode($this->getVariableValue($variableUri));
             common_Logger::i(var_export(strlen($value), true));
             $decodedFile = taoResults_helpers_Datatypes::decodeFile($value);
             common_Logger::i("FileName:");
             common_Logger::i(var_export($decodedFile["name"], true));
             common_Logger::i("Mime Type:");
             common_Logger::i(var_export($decodedFile["mime"], true));
             $file = array("data" => $decodedFile["data"], "mimetype" => "Content-type: " . $decodedFile["mime"], "filename" => $decodedFile["name"]);
             break;
         default:
             //legacy files
             $file = array("data" => base64_decode($this->getVariableValue($variableUri)), "mimetype" => "Content-type: text/xml", "filename" => "trace.xml");
     }
     return $file;
 }
コード例 #23
0
 /**
  * Get the list of all module's namespaces
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return array
  */
 public function getAllNamespaces()
 {
     $returnValue = array();
     if (count($this->namespaces) == 0) {
         $db = core_kernel_classes_DbWrapper::singleton();
         $query = 'SELECT modelid, modeluri FROM models';
         $result = $db->query($query);
         while ($row = $result->fetch()) {
             $id = $row['modelid'];
             $uri = $row['modeluri'];
             $this->namespaces[$id] = $uri;
         }
     }
     foreach ($this->namespaces as $id => $uri) {
         $returnValue[$uri] = new common_ext_Namespace($id, $uri);
     }
     return (array) $returnValue;
 }
コード例 #24
0
 private function countStatements()
 {
     return core_kernel_classes_DbWrapper::singleton()->getRowCount('statements');
 }
コード例 #25
0
 /**
  * Get additional properties used during class' compilation.
  * This function is usefull specially during unhardening
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param  Class clazz
  * @return array
  */
 public function getAdditionalProperties(\core_kernel_classes_Class $clazz)
 {
     $returnValue = array();
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     $query = "SELECT property_uri \n\t\t\tFROM class_additional_properties, class_to_table \n\t\t\tWHERE class_additional_properties.class_id = class_to_table.id\n\t\t\tAND class_to_table.uri = ?";
     $result = $dbWrapper->query($query, array($clazz->getUri()));
     while ($row = $result->fetch()) {
         $returnValue[] = new \core_kernel_classes_Property($row['property_uri']);
     }
     return (array) $returnValue;
 }
コード例 #26
0
 public function __construct()
 {
     $this->dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $this->getTables();
     $this->generate();
 }
コード例 #27
0
 /**
  * Export a model by URI
  * 
  * @param array $modelUri
  * @return string
  */
 public static function exportModelByUri($modelUri)
 {
     $dbWrapper = core_kernel_classes_DbWrapper::singleton();
     $result = $dbWrapper->query('SELECT modelid FROM "models"  WHERE "modeluri" = ?', array($modelUri))->fetch(PDO::FETCH_ASSOC);
     self::exportModels($result['modelid']);
 }
コード例 #28
0
 /**
  * Will create an Index (in the RDBMS) for all the promperties passed as
  * a parameter. This may increase the performance of the system.
  * 
  * @static
  * @access public
  * @param array $indexProperties
  * @throws Exception
  * @return boolean If it succeeds, false otherwise.
  */
 public static function createIndex($indexProperties = array())
 {
     $referencer = ResourceReferencer::singleton();
     $dbWrapper = \core_kernel_classes_DbWrapper::singleton();
     foreach ($indexProperties as $indexProperty) {
         $property = new \core_kernel_classes_Property($indexProperty);
         $propertyAlias = Utils::getShortName($property);
         foreach ($referencer->propertyLocation($property) as $table) {
             if (!preg_match("/props\$/", $table) && preg_match("/^_[0-9]{2,}/", $table)) {
                 try {
                     $indexName = 'idx_' . $table . '_' . $propertyAlias;
                     if (strlen($indexName) > 64) {
                         $md5 = md5($indexName);
                         $indexName = substr($indexName, 0, 30) . $md5;
                     }
                     $dbWrapper->createIndex($indexName, $dbWrapper->quoteIdentifier($table), array($dbWrapper->quoteIdentifier($propertyAlias) => 255));
                 } catch (\Exception $e) {
                     if ($e->getCode() != $dbWrapper->getIndexAlreadyExistsErrorCode() && $e->getCode() != '00000') {
                         throw new Exception("Unable to create index 'idx_{$propertyAlias}' for property alias '{$propertyAlias}' on table '{$table}': {$e->getMessage()}");
                     } else {
                         \common_Logger::e('something go wrong when creating index idx_' . $propertyAlias . ' on table ' . $table . ' : ' . $e->getMessage());
                     }
                 }
             }
         }
     }
     return true;
 }
コード例 #29
0
<?php

/**  
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; under version 2
 * of the License (non-upgradable).
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
 *               
 * 
 */
require_once dirname(__FILE__) . '/../includes/raw_start.php';
$dbWrapper = core_kernel_classes_DbWrapper::singleton();
$statement = $dbWrapper->query('SELECT DISTINCT "subject" FROM "statements" WHERE "predicate" in (\'' . RDFS_LABEL . '\',\'' . RDFS_COMMENT . '\')');
while ($r = $statement->fetch()) {
    $subject = new core_kernel_classes_Resource($r['subject']);
    if (!$subject->exists() && !$subject->isClass()) {
        echo $subject->getUri() . ' has corpses' . PHP_EOL;
    }
}
コード例 #30
0
ファイル: class.Namespace.php プロジェクト: nagyist/generis
 /**
  * Remove a namespace from the ontology. All triples bound to the model will
  * be removed.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return boolean
  */
 public function remove()
 {
     $returnValue = (bool) false;
     $db = core_kernel_classes_DbWrapper::singleton();
     if (false === $db->exec("DELETE FROM statements WHERE modelid = ?", array($this->getModelId()))) {
         $returnValue = false;
     } else {
         if (false === $db->exec("DELETE FROM models WHERE modelid = ?", array($this->getModelId()))) {
             $returnValue = false;
         } else {
             $returnValue = true;
         }
     }
     return (bool) $returnValue;
 }