/** * Add a new Id to the set. * @param object Id $id The Id to add. * @access public * @return void */ function addItem($id) { parent::addItem($id); $position = $this->getPosition($id); // Add the item to the database $query = new InsertQuery(); $query->setTable("sets"); $columns = array("id", "item_id", "item_order"); $values = array("'" . addslashes($this->_setId->getIdString()) . "'", "'" . addslashes($id->getIdString()) . "'", "'" . $position . "'"); $query->setColumns($columns); $query->setValues($values); $dbHandler = Services::getService("DatabaseManager"); $dbHandler->query($query, $this->_dbIndex); }
/** * Inserts a new row into the Database with the data contained in the object. * @param integer $dbID The {@link DBHandler} database ID to query. * @access public * @return integer Returns the new ID of the data stored. */ function insert($dbID) { $idManager = Services::getService("Id"); $newID = $idManager->createId(); $query = new InsertQuery(); $query->setTable($this->_table); $query->setColumns(array("id", "data")); $query->addRowOfValues(array("'" . addslashes($newID->getIdString()) . "'", "'" . addslashes($this->asString()) . "'")); $dbHandler = Services::getService("DatabaseManager"); $result = $dbHandler->query($query, $dbID); if (!$result || $result->getNumberOfRows() != 1) { throwError(new UnknownDBError("StorableString")); return false; } return $newID->getIdString(); }
/** * Takes a {@link DMRecord} and an optional date and creates a {@link RecordTag} in the database based * on the current active versions of values within the {@link DMRecord}. * @param ref object $record The {@link DMRecord} to be tagged. * @param optional object $date An optional {@link DateAndTime} object to attach to the tag instead of the current date/time. * @return int The new tag's ID in the database. * @access public */ function tagRecord($record, $date = null) { // if the dataset is not versionControlled, there's no point in tagging if (!$record->isVersionControlled()) { return null; } $id = $record->getID(); if (!$date) { $date = DateAndTime::now(); } // spider through the record and get the IDs of the active versions. $ids = array(); $schema = $record->getSchema(); foreach ($schema->getAllIDs() as $id) { $values = $record->getRecordFieldValues($id); foreach (array_keys($values) as $key) { if ($values[$key]->hasActiveValue()) { $actVer = $values[$key]->getActiveVersion(); $ids[] = $actVer->getID(); } } } // now let's dump it all to the DB $query = new InsertQuery(); $query->setTable("dm_tag"); $query->setColumns(array("id", "fk_record", "date")); $idManager = Services::getService("Id"); $dbHandler = Services::getService("DBHandler"); $newID = $idManager->createId(); $query->addRowOfValues(array($newID->getIdString(), $id, $dbHandler->toDBDate($date, DATAMANAGER_DBID))); $query2 = new InsertQuery(); $query2->setTable("dm_tag_map"); $query2->setColumns(array("fk_tag", "fk_record_field")); foreach ($ids as $id) { $query2->addRowOfValues(array("'" . addslashes($newID->getIdString()) . "'", $id)); } $result = $dbHandler->query($query, DATAMANAGER_DBID); $result2 = $dbHandler->query($query2, DATAMANAGER_DBID); if (!$result || !$result2) { throwError(new UnknownDBError("RecordTagManager")); } // we're done. return $newID->getIdString(); }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { ArgumentValidator::validate($value, StringValidatorRule::getRule()); // Store the size in the object in case its asked for again. try { $size = ByteSize::fromString($value); } catch (InvalidArgumentException $e) { $size = ByteSize::withValue(0); } $this->_size = $size->value(); // then write it to the database. $dbHandler = Services::getService("DatabaseManager"); // Check to see if the name is in the database $query = new SelectQuery(); $query->addTable("dr_file"); $query->addColumn("COUNT(*) as count"); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it already exists, use an update query. if ($result->field("count") > 0) { $query = new UpdateQuery(); $query->setTable("dr_file"); $query->setColumns(array("size")); $query->setValues(array("'" . addslashes($this->_size) . "'")); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); } else { $query = new InsertQuery(); $query->setTable("dr_file"); $query->setColumns(array("id", "size")); $query->setValues(array("'" . $this->_recordId->getIdString() . "'", "'" . addslashes($this->_size) . "'")); } $result->free(); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Tests the generateSQLQuery() without WHERE clause. */ function test() { // insert one row $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->addRowOfValues(array("'Spaceboy'")); $query->setAutoIncrementColumn("id", "test1_id_seq"); $result = $this->db->query($query); $lastId = $result->getLastAutoIncrementValue(); // insert it again, the id must have increased by one $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $this->assertIdentical($result->getLastAutoIncrementValue(), $lastId + 1); // add several rows at the same time $query->addRowOfValues(array("'Astrogirl'")); $result = $this->db->query($query); $this->assertIdentical($result->getLastAutoIncrementValue(), $lastId + 3); // now insert in the other test table $query = new InsertQuery(); $query->setTable("test"); $query->setColumns(array("FK", "value")); $query->addRowOfValues(array($lastId, "'Ziggy'")); $query->addRowOfValues(array($lastId + 1, "'Lost in the Stars'")); $query->addRowOfValues(array($lastId + 2, "'Headstar'")); $query->addRowOfValues(array($lastId + 3, "'Stardust'")); $query->setAutoIncrementColumn("id", "test1_id_seq"); $result = $this->db->query($query); // join the inserted rows $query = new SelectQuery(); $query->addTable("test1"); $query->addTable("test", INNER_JOIN, "test.FK = test1.id"); $query->addColumn("id", "dm86_id", "test"); $query->addColumn("FK", "dm86_fk", "test"); $query->addColumn("value", "dm86_value", "test"); $query->addColumn("id", "dm98_id", "test1"); $query->addColumn("value", "dm98_value", "test1"); $query->addWhere("test1.id >= " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 4); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId); $this->assertIdentical($result->field("dm86_value"), "Ziggy"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 1); $this->assertIdentical($result->field("dm86_value"), "Lost in the Stars"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 1); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 2); $this->assertIdentical($result->field("dm86_value"), "Headstar"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 2); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 3); $this->assertIdentical($result->field("dm86_value"), "Stardust"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 3); $this->assertIdentical($result->field("dm98_value"), "Astrogirl"); $result->free(); $query = new UpdateQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->setValues(array("'I changed you MF!'")); $query->addWhere("id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $query = new SelectQuery(); $query->addTable("test1"); $query->addColumn("value"); $query->addWhere("test1.id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $this->assertIdentical($result->field("value"), "I changed you MF!"); $result->free(); $query = new DeleteQuery(); $query->setTable("test1"); $query->addWhere("id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $query = new SelectQuery(); $query->addTable("test1"); $query->addColumn("value"); $query->addWhere("test1.id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 0); $result->free(); }
/** * Attempts to commit our {@link DMRecord}s to the database and update our mapping. * @param boolean optional $ignoreMandatory If true, doesn't fail if mandatory * fields don't have values. * @return void */ function commit($ignoreMandatory = false) { $ids = array(); if (count($this->_records)) { for ($i = 0; $i < count($this->_records); $i++) { $this->_records[$i]->commit($ignoreMandatory); $ids[] = $this->_records[$i]->getID(); } $this->_records = array(); $this->_fetchMode = -1; } if ($this->_dirty) { // syncrhonize the database $ids = array_merge($ids, $this->_storedRecordIDs); // Make sure that we only have one ID for each record. $ids = array_unique($ids); $dbHandler = Services::getService("DatabaseManager"); // first delete all the old mappings $query = new DeleteQuery(); $query->setTable("dm_record_set"); $query->setWhere("dm_record_set.id='" . addslashes($this->_myID) . "'"); // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); $dbHandler->query($query, DATAMANAGER_DBID); if (count($ids)) { // next insert all our mappings back in. $query = new InsertQuery(); $query->setTable("dm_record_set"); $query->setColumns(array("id", "fk_record")); foreach ($ids as $id) { $query->addRowOfValues(array("'" . addslashes($this->_myID) . "'", "'" . addslashes($id) . "'")); if (!in_array($id, $this->_storedRecordIDs)) { $this->_storedRecordIDs[] = $id; } } // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); $dbHandler->query($query, DATAMANAGER_DBID); // done! } } }
/** * A public function for getting a type id (and ensuring that it exists * in the database). One might consider implementing a Type manager for * stuff like this that has no proper home. * * @param object Type $type * * @return integer * * @access public * * @since 11/18/04 */ function getTypeId($type) { $dbc = Services::getService("DBHandler"); // Check to see if the type already exists in the DB $query = new SelectQuery(); $query->addColumn("type_id"); $query->addTable("type"); $query->addWhere("type_domain='" . addslashes($type->getDomain()) . "'"); $query->addWhere("type_authority='" . addslashes($type->getAuthority()) . "'", _AND); $query->addWhere("type_keyword='" . addslashes($type->getKeyword()) . "'", _AND); $result = $dbc->query($query, $this->_dbIndex); // If we have a type id already, use that if ($result->getNumberOfRows()) { $typeId = $result->field("type_id"); $result->free(); } else { $result->free(); $query = new InsertQuery(); $query->setTable("type"); $query->setAutoIncrementColumn("type_id", "type_type_id_seq"); $query->setColumns(array("type_domain", "type_authority", "type_keyword", "type_description")); $query->setValues(array("'" . addslashes($type->getDomain()) . "'", "'" . addslashes($type->getAuthority()) . "'", "'" . addslashes($type->getKeyword()) . "'", "'" . addslashes($type->getDescription()) . "'")); $result = $dbc->query($query, $this->_dbIndex); $typeId = $result->getLastAutoIncrementValue(); } return $typeId; }
/** * Update a record table for a set of harvesters and repositories * * @param string $table * @param array $allowedRepositoryIdStrings * @param array $authGroupIdStrings The ids of the groups to check view authorization for, * May be one of the following or another group Id string: * edu.middlebury.agents.everyone * edu.middlebury.agents.all_agents * If empty, all assets in the specified repositories will be added regardless of * their visibility. * * @return void * @access public * @since 3/9/07 */ function updateTable($table, $allowedRepositoryIdStrings, $authGroupIdStrings) { ArgumentValidator::validate($table, StringValidatorRule::getRule()); ArgumentValidator::validate($allowedRepositoryIdStrings, ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); ArgumentValidator::validate($authGroupIdStrings, ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); $harmoni = Harmoni::instance(); $config = $harmoni->getAttachedData('OAI_CONFIG'); $repositoryManager = Services::getService('Repository'); $authorizationManager = Services::getService('AuthZ'); $idManager = Services::getService("IdManager"); $dbc = Services::getService("DatabaseManager"); $authGroupIds = array(); foreach ($authGroupIdStrings as $id) { $authGroupIds[] = $idManager->getId($id); } $baseCheckQuery = new SelectQuery(); $baseCheckQuery->addTable('oai_' . $table); $baseCheckQuery->addColumn('datestamp'); $baseCheckQuery->addColumn('deleted'); $baseUpdateQuery = new UpdateQuery(); $baseUpdateQuery->setTable('oai_' . $table); $baseUpdateColumns = array('datestamp', 'deleted', 'oai_set', 'dc_title', 'dc_description'); $dcUpdateColumns = array('datestamp', 'deleted', 'oai_set', 'dc_title', 'dc_description', 'dc_creator', 'dc_subject', 'dc_contributor', 'dc_publisher', 'dc_date', 'dc_type', 'dc_format', 'dc_identifier', 'dc_source', 'dc_language', 'dc_relation', 'dc_coverage', 'dc_rights'); $baseInsertQuery = new InsertQuery(); $baseInsertQuery->setTable('oai_' . $table); $baseInsertColumns = array('datestamp', 'oai_identifier', 'deleted', 'oai_set', 'dc_title', 'dc_description'); $dcInsertColumns = array('datestamp', 'oai_identifier', 'deleted', 'oai_set', 'dc_title', 'dc_description', 'dc_creator', 'dc_subject', 'dc_contributor', 'dc_publisher', 'dc_date', 'dc_type', 'dc_format', 'dc_identifier', 'dc_source', 'dc_language', 'dc_relation', 'dc_coverage', 'dc_rights'); $baseDeleteQuery = new UpdateQuery(); $baseDeleteQuery->setTable('oai_' . $table); $baseDeleteQuery->addValue('deleted', 'true'); $baseDeleteQuery->addRawValue('datestamp', 'NOW()'); $baseUndeleteQuery = new UpdateQuery(); $baseUndeleteQuery->setTable('oai_' . $table); $baseUndeleteQuery->addValue('deleted', 'false'); $baseUndeleteQuery->addRawValue('datestamp', 'NOW()'); $forceUpdate = false; $repositories = $repositoryManager->getRepositories(); $r = 0; if (count($allowedRepositoryIdStrings)) { $numR = count($allowedRepositoryIdStrings); } else { $numR = $repositories->count(); } $numUpdates = 0; $numDeleted = 0; $message = _('Updating OAI records for repository (%1 of %2) : '); $message = str_replace('%2', $numR, $message); $instituteId = $idManager->getId('edu.middlebury.agents.users'); $viewId = $idManager->getId('edu.middlebury.authorization.view'); require_once HARMONI . "/utilities/Timer.class.php"; $timer = new Timer(); $timer->start(); $existingRepositoryIds = array(); while ($repositories->hasNext()) { $updatesInRepository = 0; $repository = $repositories->next(); $repositoryId = $repository->getId(); // Only work with allowed repositories if (count($allowedRepositoryIdStrings) && !in_array($repositoryId->getIdString(), $allowedRepositoryIdStrings)) { continue; } $r++; $existingRepositoryIds[] = $repositoryId->getIdString(); $assets = $repository->getAssets(); $status = new CLIStatusStars(str_replace('%1', $r, $message) . $repository->getDisplayName()); $status->initializeStatistics($assets->count()); $existingAssetIds = array(); while ($assets->hasNext()) { $asset = $assets->next(); $assetId = $asset->getId(); $existingAssetIds[] = $assetId->getIdString(); try { $modificationDate = $asset->getModificationDate(); } catch (UnimplementedException $e) { $modificationDate = DateAndTime::now(); } $query = $baseCheckQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if (!$result->getNumberOfRows()) { // printpre("Doesn't exist:\t".$asset->getDisplayName().""); $query = $baseInsertQuery->copy(); $query->addValue('oai_set', $repositoryId->getIdString()); $query->addValue('oai_identifier', $assetId->getIdString()); } else { // printpre("Exists:\t".$asset->getDisplayName().""); if ($modificationDate->isGreaterThan(DateAndTime::fromString($result->field('datestamp'))) || $forceUpdate) { // printpre("\tUpdating:\t".$asset->getDisplayName()); $query = $baseUpdateQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); } else { $query = null; } } if ($query) { $query->addRawValue('datestamp', 'NOW()'); } $isCurrentlyDeleted = $result->getNumberOfRows() && $result->field('deleted') == 'true' ? true : false; $result->free(); if (!count($authGroupIds)) { $isVisible = true; } else { $isVisible = false; try { foreach ($authGroupIds as $id) { if ($authorizationManager->isAuthorized($id, $viewId, $assetId)) { $isVisible = true; break; } } } catch (UnknownIdException $e) { $isVisible = true; } } if ($query) { //Add the data fields // Deleted if ($isVisible) { $query->addValue('deleted', 'false'); } else { $query->addValue('deleted', 'true'); } $query->addValue('dc_title', $asset->getDisplayName()); $query->addValue('dc_description', $asset->getDescription()); $this->addDublinCoreValues($asset, $query); $dbc->query($query, $config->getProperty('OAI_DBID')); $updatesInRepository++; $numUpdates++; } else { if ($isCurrentlyDeleted && $isVisible) { $query = $baseUndeleteQuery->copy(); } else { if (!$isCurrentlyDeleted && !$isVisible) { $query = $baseDeleteQuery->copy(); } else { $query = null; } } if ($query) { $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); $dbc->query($query, $config->getProperty('OAI_DBID')); $updatesInRepository++; $numUpdates++; } } $status->updateStatistics(); } // Update any missing assets as deleted $query = $baseDeleteQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); if (count($existingAssetIds)) { $query->addWhereEqual("deleted", "false"); $query->addWhereNotIn("oai_identifier", $existingAssetIds); } $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if ($result->getNumberOfRows()) { $updatesInRepository = $updatesInRepository + $result->getNumberOfRows(); $numUpdates = $numUpdates + $result->getNumberOfRows(); } print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Elapsed Time:\t"; $timer->end(); printf("%1.2f", $timer->printTime()); print " seconds"; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : ""; print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Updates: " . $updatesInRepository; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : "\n"; } // Update any missing repositories as deleted $query = $baseDeleteQuery->copy(); $query->addWhereEqual("deleted", "false"); if (count($existingRepositoryIds)) { $query->addWhereNotIn("oai_set", $existingRepositoryIds); } $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if ($result->getNumberOfRows()) { $updatesInRepository = $updatesInRepository + $result->getNumberOfRows(); $numUpdates = $numUpdates + $result->getNumberOfRows(); } print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Total Updates:\t" . $numUpdates; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : "\n"; }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { // ArgumentValidator::validate($value, StringValidatorRule::getRule()); $dbHandler = Services::getService("DatabaseManager"); // Delete the row if we are setting the value to null if (is_null($value)) { $query = new DeleteQuery(); $query->setTable("dr_file_data"); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); return; } // Store the data in the object in case its asked for again. // $this->_data = $value; // Make sure that the dr_file row is inserted. $query = new InsertQuery(); $query->setTable("dr_file"); $query->addValue("id", $this->_recordId->getIdString()); try { $dbHandler->query($query, $this->_configuration->getProperty("database_index")); } catch (QueryDatabaseException $e) { // If an error is thrown inserting (because the file already exists) // ignore it. } $dbHandler->beginTransaction($this->_configuration->getProperty("database_index")); // Base64 encode the data to preserve it, // then write it to the database. // Check to see if the data is in the database $query = new SelectQuery(); $query->addTable("dr_file_data"); $query->addColumn("COUNT(*) as count"); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it already exists, use an update query. if ($result->field("count") > 0) { $query = new UpdateQuery(); $query->setTable("dr_file_data"); $query->setColumns(array("data")); $query->setValues(array("'" . base64_encode($value) . "'")); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); } else { $query = new InsertQuery(); $query->setTable("dr_file_data"); $query->setColumns(array("fk_file", "data")); $query->setValues(array("'" . $this->_recordId->getIdString() . "'", "'" . base64_encode($value) . "'")); } $result->free(); // printpre($query); // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // Update the size row. $query = new UpdateQuery(); $query->setTable("dr_file"); $query->addValue("size", strval(strlen($value))); $query->addWhereEqual("id", $this->_recordId->getIdString()); $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $dbHandler->commitTransaction($this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Save an XML string to the feed cache * * @param string $url * @param string $feedXml * @return void * @access protected * @since 7/8/08 */ protected function cacheXmlString($url, $feedXml) { $dbc = Services::getService("DatabaseManager"); $query = new DeleteQuery(); $query->setTable('segue_plugins_rssfeed_cache'); $query->addWhereEqual('url', $url); $query->addWhereRawLessThan('cache_time', $dbc->toDBDate(DateAndTime::now()->minus(Duration::withSeconds(600)), IMPORTER_CONNECTION), _OR); try { $result = $dbc->query($query, IMPORTER_CONNECTION); } catch (NoSuchTableDatabaseException $e) { $this->createCacheTable(); } $query = new InsertQuery(); $query->setTable('segue_plugins_rssfeed_cache'); $query->addValue('url', $url); $query->addValue('feed_data', $feedXml); $dbc->query($query, IMPORTER_CONNECTION); }
/** * Store a mapping between Segue1 ids and Segue2 ids * * @return void * @access protected * @since 3/20/08 */ protected function storeSegue1IdMapping() { if (!isset($this->origenSlotname)) { throw new OperationFailedException("Origen slot not set. Call " . get_class($this) . "->setOrigenSlotname('xxxxx')."); } if (!isset($this->destSlotname)) { throw new OperationFailedException("Destination slot not set. Call " . get_class($this) . "->setDestinationSlotname('xxxxx')."); } $dbc = Services::getService('DatabaseManager'); $map = $this->filterNonAccessible($this->getIdMap()); // printpre(htmlentities($this->doc->saveXMLWithWhitespace())); // printpre($map); // throw new Exception('test'); // Delete any old mappings $query = new DeleteQuery(); $query->setTable('segue1_id_map'); $query->addWhereIn('segue1_id', array_keys($map)); $dbc->query($query, IMPORTER_CONNECTION); // Add new mappings $query = new InsertQuery(); $query->setTable('segue1_id_map'); foreach ($map as $segue1Id => $segue2Id) { $query->createRow(); $query->addValue('segue1_slot_name', $this->origenSlotname); $query->addValue('segue1_id', $segue1Id); $query->addValue('segue2_slot_name', $this->destSlotname); $query->addValue('segue2_id', $segue2Id); } $dbc->query($query, IMPORTER_CONNECTION); }
/** * Answer the mime type key * * @param string $mimeType * @return integer * @access public * @since 2/13/06 */ function getMimeKey() { // If we have a key, make sure it exists. if ($this->_mimeType && $this->_mimeType != "NULL") { $dbc = Services::getService('DatabaseManager'); // Check to see if the type is in the database $query = new SelectQuery(); $query->addTable("dr_mime_type"); $query->addColumn("id"); $query->addWhere("type = '" . $this->_mimeType . "'"); $result = $dbc->query($query, $this->getDBIndex()); // If it doesn't exist, insert it. if (!$result->getNumberOfRows()) { $query = new InsertQuery(); $query->setTable("dr_mime_type"); $query->setAutoIncrementColumn("id", "dr_mime_type_id_seq"); $query->setColumns(array("type")); $query->setValues(array("'" . addslashes($this->_mimeType) . "'")); $result2 = $dbc->query($query, $this->getDBIndex()); $mimeId = "'" . $result2->getLastAutoIncrementValue() . "'"; } else { $mimeId = "'" . $result->field("id") . "'"; } $result->free(); } else { $mimeId = "NULL"; } return $mimeId; }
/** * Add a student to the roster and assign the specified Enrollment Status * Type. * * @param object Id $agentId * @param object Type $enrollmentStatusType * * @throws object CourseManagementException An exception * with one of the following messages defined in * org.osid.coursemanagement.CourseManagementException may be * thrown: {@link * org.osid.coursemanagement.CourseManagementException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.coursemanagement.CourseManagementException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.coursemanagement.CourseManagementException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.coursemanagement.CourseManagementException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.coursemanagement.CourseManagementException#NULL_ARGUMENT * NULL_ARGUMENT}, {@link * org.osid.coursemanagement.CourseManagementException#UNKNOWN_TYPE * UNKNOWN_TYPE}, {@link * org.osid.coursemanagement.CourseManagementException#ALREADY_ADDED * ALREADY_ADDED} * * @access public */ function addStudent(Id $agentId, Type $enrollmentStatusType) { $dbManager = Services::getService("DatabaseManager"); $query = new SelectQuery(); $query->addTable('cm_enroll'); $query->addWhere("fk_cm_section='" . addslashes($this->_id->getIdString()) . "'"); $query->addWhere("fk_student_id='" . addslashes($agentId->getIdString()) . "'"); //I don't need Id, but I need to select something for the query to work $query->addColumn('id'); $res = $dbManager->query($query); if ($res->getNumberOfRows() == 0) { $typeIndex = $this->_typeToIndex('enroll_stat', $enrollmentStatusType); $query = new InsertQuery(); $query->setTable('cm_enroll'); $values[] = "'" . addslashes($agentId->getIdString()) . "'"; $values[] = "'" . addslashes($typeIndex) . "'"; $values[] = "'" . addslashes($this->_id->getIdString()) . "'"; $query->setColumns(array('fk_student_id', 'fk_cm_enroll_stat_type', 'fk_cm_section')); $query->addRowOfValues($values); $query->setAutoIncrementColumn('id', 'id_sequence'); $dbManager->query($query); } else { print "<b>Warning!</b> Student with id " . $agentId->getIdString() . " is already enrolled in section " . $this->getDisplayName() . "."; } }
/** * Add tokens to the system. * * @param object AuthNTokens $authNTokens * @return void * @access public * @since 3/1/05 */ function addTokens($authNTokens) { /********************************************************* * Check validity *********************************************************/ ArgumentValidator::validate($authNTokens, ExtendsValidatorRule::getRule("AuthNTokens")); if ($this->tokensExist($authNTokens)) { throw new OperationFailedException("Cannot create tokens: '" . $authNTokens->getUsername() . "' already exists."); } $email = $authNTokens->getUsername(); // Check that the email is in a whitelisted domain if a whitelist is set. if (is_array($this->_configuration->getProperty('domain_whitelist'))) { $allowed = false; foreach ($this->_configuration->getProperty('domain_whitelist') as $domain) { if (preg_match('/' . str_replace('.', '\\.', $domain) . '$/i', $email)) { $allowed = true; break; } } if (!$allowed) { preg_match('/@([^@]+)$/', $email, $matches); throw new OperationFailedException("Cannot create visitor registrations from " . $matches[1] . ". Not in list of allowed domains."); } } // Check that the email is not in a blacklisted domain if a blacklist is set. if (is_array($this->_configuration->getProperty('domain_blacklist'))) { foreach ($this->_configuration->getProperty('domain_blacklist') as $domain) { if (preg_match('/' . str_replace('.', '\\.', $domain) . '$/i', $email)) { throw new OperationFailedException("Cannot create visitor registration from {$domain}. Domain is black-listed."); } } } // Check that the email is not for someone with an account already in the // system through another authentication method. $methodMgr = Services::getService("AuthNMethodManager"); $types = $methodMgr->getAuthNTypes(); while ($types->hasNext()) { $method = $methodMgr->getAuthNMethodForType($types->next()); $matching = $method->getTokensBySearch($email); while ($matching->hasNext()) { $properties = $method->getPropertiesForTokens($matching->next()); if ($properties->getProperty('email') && strtolower($email) == strtolower($properties->getProperty('email'))) { $message = dgettext("polyphony", "Cannot create visitor registration for %1. An account already exists in the %2 system. Please log in with your %2 username and password."); $message = str_replace("%1", $email, $message); $message = str_replace("%2", $method->getType()->getKeyword(), $message); throw new OperationFailedException($message); } } } /********************************************************* * Add the tokens *********************************************************/ $dbc = Services::getService("DatabaseManager"); $dbId = $this->_configuration->getProperty('database_id'); $authenticationTable = $this->_configuration->getProperty('authentication_table'); $usernameField = $this->_configuration->getProperty('username_field'); $passwordField = $this->_configuration->getProperty('password_field'); $query = new InsertQuery(); $query->setTable($authenticationTable); $query->addValue($usernameField, $authNTokens->getUsername()); $query->addValue($passwordField, $authNTokens->getPassword()); $query->addValue('display_name', $authNTokens->getUsername()); $query->addValue('email_confirmed', '0'); $query->addValue('confirmation_code', md5(rand())); $result = $dbc->query($query, $dbId); // Log the success if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Authentication"); $formatType = new Type("logging", "edu.middlebury", "AgentsAndNodes", "A format in which the acting Agent[s] and the target nodes affected are specified."); $priorityType = new Type("logging", "edu.middlebury", "Event_Notice", "Normal events."); $properties = $this->getPropertiesForTokens($authNTokens); $item = new AgentNodeEntryItem("Visitor Registration", "Visitor Registration entered: <br/> Email: " . htmlspecialchars($authNTokens->getIdentifier()) . " <br/>Still need to confirm email."); $log->appendLogWithTypes($item, $formatType, $priorityType); } }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { if (!is_null($value)) { ArgumentValidator::validate($value, NonzeroLengthStringValidatorRule::getRule()); } // Store the name in the object in case its asked for again. $this->_type = $value; // then write it to the database. $dbHandler = Services::getService("DatabaseManager"); // If we have a key, make sure it exists. if ($this->_type && $this->_type != "NULL") { // Check to see if the type is in the database $query = new SelectQuery(); $query->addTable("dr_mime_type"); $query->addColumn("id"); $query->addWhere("type = '" . $this->_type . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it doesn't exist, insert it. if (!$result->getNumberOfRows()) { $query = new InsertQuery(); $query->setTable("dr_mime_type"); $query->setAutoIncrementColumn("id", "dr_mime_type_id_seq"); $query->setColumns(array("type")); $query->setValues(array("'" . addslashes($this->_type) . "'")); $result2 = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $mimeId = "'" . $result2->getLastAutoIncrementValue() . "'"; } else { $mimeId = "'" . $result->field("id") . "'"; } $result->free(); } else { $mimeId = "NULL"; } // add its id to the file. $query = new UpdateQuery(); $query->setTable("dr_file"); $query->setColumns(array("fk_mime_type")); $query->setValues(array($mimeId)); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Commits any changes that have been made to the database. If neither update() nor prune() have been * called, even if changes have been made, they will not be reflected in the database. * @return bool * @access public */ function commit() { $dbHandler = Services::getService("DatabaseManager"); if ($this->_update) { // let's re-cast our primitive to a storablePrimitive $this->recastAsStorable(); // first we need to commit the actual Primitive value // so that we can get its ID if (!$this->_dataID) { $this->_dataID = $this->_primitive->insert(DATAMANAGER_DBID); } else { $this->_primitive->update(DATAMANAGER_DBID, $this->_dataID); } $this->_date = DateAndTime::now(); if ($this->_myID) { // we're already in the DB. just update the entry $query = new UpdateQuery(); $query->setWhere("id='" . addslashes($this->_myID) . "'"); $query->setColumns(array("value_index", "active", "modified")); $query->setValues(array($this->_parent->getIndex(), $this->_active ? 1 : 0, $dbHandler->toDBDate($this->_date, DATAMANAGER_DBID))); } else { // we have to insert a new one $query = new InsertQuery(); $idManager = Services::getService("Id"); $newID = $idManager->createId(); $this->_myID = $newID->getIdString(); $query->setColumns(array("id", "fk_record", "fk_schema_field", "value_index", "fk_data", "active", "modified")); $schema = $this->_parent->_parent->_parent->getSchema(); $schemaField = $this->_parent->_parent->getSchemaField(); $query->addRowOfValues(array("'" . addslashes($this->_myID) . "'", "'" . addslashes($this->_parent->_parent->_parent->getID()) . "'", "'" . addslashes($schemaField->getID()) . "'", $this->_parent->getIndex(), "'" . addslashes($this->_dataID) . "'", $this->_active ? 1 : 0, $dbHandler->toDBDate($this->_date, DATAMANAGER_DBID))); } $query->setTable("dm_record_field"); $result = $dbHandler->query($query, DATAMANAGER_DBID); if (!$result) { throwError(new UnknownDBError("DMRecord")); return false; } } if ($this->_prune && $this->_dataID) { if ($id = $this->getID()) { // ok, let's get rid of ourselves... completely! $query = new DeleteQuery(); $query->setTable("dm_record_field"); $query->setWhere("id='" . addslashes($id) . "'"); $res = $dbHandler->query($query, DATAMANAGER_DBID); if (!$res) { throwError(new UnknownDBError("DMRecord")); } // now tell the data object to prune itself $this->recastAsStorable(); $this->_primitive->prune(DATAMANAGER_DBID, $this->_dataID); // and we have to get rid of any tag mappings where we are included. $query = new DeleteQuery(); $query->setTable("dm_tag_map"); $query->setWhere("fk_record_field='" . addslashes($id) . "'"); $res = $dbHandler->query($query, DATAMANAGER_DBID); if (!$res) { throwError(new UnknownDBError("DMRecord")); } } } // reset the prune flag $this->_prune = false; // reset the update flag $this->_update = false; return true; }
/** * Create a Hierarchy. * * @param string $displayName * @param object Type[] $nodeTypes * @param string $description * @param boolean $allowsMultipleParents * @param boolean $allowsRecursion * @param optional object Id $id WARNING: NOT IN OSID * * @return object Hierarchy * * @throws object HierarchyException An exception with one of * the following messages defined in * org.osid.hierarchy.HierarchyException may be thrown: {@link * org.osid.hierarchy.HierarchyException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.hierarchy.HierarchyException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.hierarchy.HierarchyException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.hierarchy.HierarchyException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.hierarchy.HierarchyException#NULL_ARGUMENT * NULL_ARGUMENT}, {@link * org.osid.hierarchy.HierarchyException#UNSUPPORTED_CREATION * UNSUPPORTED_CREATION} * * @access public */ function createHierarchy($displayName, array $nodeTypes, $description, $allowsMultipleParents, $allowsRecursion, Id $id = NULL) { // ** parameter validation ArgumentValidator::validate($description, StringValidatorRule::getRule(), true); ArgumentValidator::validate($displayName, StringValidatorRule::getRule(), true); ArgumentValidator::validate($allowsMultipleParents, BooleanValidatorRule::getRule(), true); ArgumentValidator::validate($allowsRecursion, BooleanValidatorRule::getRule(), true); ArgumentValidator::validate($id, OptionalRule::getRule(ExtendsValidatorRule::getRule("Id")), true); // ** end of parameter validation // check for supported hierarchies if ($allowsRecursion) { throw new OperationFailedException("Unsuported creation. Does not support recursion."); } $dbHandler = Services::getService("DatabaseManager"); // Create an Id for the Hierarchy if (!is_object($id)) { $idManager = Services::getService("Id"); $id = $idManager->createId(); } $idValue = $id->getIdString(); $query = new InsertQuery(); $query->setTable("az2_hierarchy"); $query->addValue("id", $idValue); $query->addValue("display_name", $displayName); $query->addValue("description", $description); $query->addValue("multiparent", $allowsMultipleParents ? '1' : '0'); $queryResult = $dbHandler->query($query, $this->_dbIndex); // Create a new hierarchy and insert it into the database $cache = new AuthZ2_HierarchyCache($idValue, $allowsMultipleParents, $this->_dbIndex, isset($this->harmoni_db) ? $this->harmoni_db : null); $cache->setAuthorizationManager($this->getAuthorizationManager()); $hierarchy = new AuthZ2_Hierarchy($id, $displayName, $description, $cache); // then cache it $this->_hierarchies[$idValue] = $hierarchy; return $hierarchy; }
/** * Record an entry for the slot in the local database * * @return void * @access private * @since 8/14/07 */ private function recordInDB() { if (!$this->isInDB) { $dbc = Services::getService('DBHandler'); try { // Add a row to the slot table $query = new InsertQuery(); $query->setTable('segue_slot'); $query->addValue('shortname', $this->getShortname()); if ($this->siteId) { $query->addValue('site_id', $this->siteId->getIdString()); } $query->addValue('type', $this->getType()); $query->addValue('location_category', $this->getLocationCategory()); if ($this->mediaQuota == self::$defaultMediaQuota) { $query->addRawValue('media_quota', 'null'); } else { $query->addValue('media_quota', $this->mediaQuota); } $dbc->query($query, IMPORTER_CONNECTION); } catch (DuplicateKeyDatabaseException $e) { // Update row to the slot table $query = new UpdateQuery(); $query->setTable('segue_slot'); $query->addWhereEqual('shortname', $this->getShortname()); if ($this->siteId) { $query->addValue('site_id', $this->siteId->getIdString()); } $query->addValue('type', $this->getType()); $query->addValue('location_category', $this->getLocationCategory()); if ($this->mediaQuota == self::$defaultMediaQuota) { $query->addRawValue('media_quota', 'null'); } else { $query->addValue('media_quota', $this->mediaQuota); } $dbc->query($query, IMPORTER_CONNECTION); } // Add existing owners to the slot_owner table // Adam 2007-08-16: Not sure if we actually need to do this... if (count($this->getOwners())) { $query = new InsertQuery(); $query->setTable('segue_slot_owner'); foreach ($this->getOwners() as $ownerId) { $query->addValue('shortname', $this->getShortname()); $query->addValue('owner_id', $ownerId->getIdString()); try { $dbc->query($query, IMPORTER_CONNECTION); } catch (DuplicateKeyDatabaseException $e) { // If already there, just skip. } } } $this->isInDB = true; } }
/** * Store the effective and expiration Dates. getEffectiveDate or getExpirationDate * should be called first to set the datesInDB flag. * * @return void * @access public * @since 8/10/04 */ function _storeDates() { $dbHandler = Services::getService("DatabaseManager"); $id = $this->_node->getId(); // If we have stored dates for this asset set them if ($this->_datesInDB) { $query = new UpdateQuery(); $query->addWhereEqual("asset_id", $id->getIdString()); } else { $query = new InsertQuery(); $query->addValue("asset_id", $id->getIdString()); $query->addRawValue("create_timestamp", "NOW()"); // Add the creator $agentId = $this->_getCurrentAgent(); $query->addValue("creator", $agentId->getIdString()); } if (is_object($this->_effectiveDate)) { $query->addValue("effective_date", $dbHandler->toDBDate($this->_effectiveDate, $this->_dbIndex)); } else { $query->addRawValue("effective_date", "NULL"); } if (is_object($this->_expirationDate)) { $query->addValue("expiration_date", $dbHandler->toDBDate($this->_expirationDate, $this->_dbIndex)); } else { $query->addRawValue("expiration_date", "NULL"); } $query->addRawValue("modify_timestamp", "NOW()"); $query->setTable("dr_asset_info"); $result = $dbHandler->query($query, $this->_dbIndex); }
/** * Find the index for our Type of type $type in its table. If it is not there, * put it into the table and return the index. * * @param string $typename the type of Type that is passed in. * @param object Type $type the Type itself * * @return object Type * * @access private */ function _typeToIndex($typename, $type) { //the appropriate table names and fields must be given names according to the pattern indicated below //validate the Type ArgumentValidator::validate($type, ExtendsValidatorRule::getRule("Type"), true); //query to see if it exists $dbHandler = Services::getService("DBHandler"); $query = new SelectQuery(); $query->addTable('cm_' . $typename . "_type"); $query->addWhere("domain='" . $type->getDomain() . "'"); $query->addWhere("authority='" . $type->getAuthority() . "'"); $query->addWhere("keyword='" . $type->getKeyword() . "'"); $query->addColumn('id'); $res = $dbHandler->query($query); if ($res->getNumberOfRows() == 0) { //if not query to create it $query = new InsertQuery(); $query->setTable('cm_' . $typename . '_type'); $values[] = "'" . addslashes($type->getDomain()) . "'"; $values[] = "'" . addslashes($type->getAuthority()) . "'"; $values[] = "'" . addslashes($type->getKeyword()) . "'"; if (is_null($type->getDescription())) { $query->setColumns(array('domain', 'authority', 'keyword')); } else { $query->setColumns(array('domain', 'authority', 'keyword', 'description')); $values[] = "'" . addslashes($type->getDescription()) . "'"; } $query->addRowOfValues($values); $query->setAutoIncrementColumn('id', 'cm_' . $typename . '_type_id_seq'); $result = $dbHandler->query($query); return $result->getLastAutoIncrementValue(); } elseif ($res->getNumberOfRows() == 1) { //if it does exist, create it $row = $res->getCurrentRow(); $the_index = $row['id']; return $the_index; } else { //print a warning if there is more than one such type. Should never happen. print "\n<b>Warning!<\\b> The Type with domain " . $type->getDomain() . ", authority " . $type->getAuthority() . ", and keyword " . $type->getKeyword() . " is not unique--there are " . $res->getNumberOfRows() . " copies.\n"; //return either one anyway. $row = $res->getCurrentRow(); $the_index = $row['id']; return $the_index; } }
/** * Add an External group to a Hierarchy-based group. * * @param object Id $hierarchyParentId * @param object Id $externalChildId * @return void * @access public * @since 11/6/07 */ public function addExternalChildGroup(Id $hierarchyParentId, Id $externalChildId) { // Check to see that it hasn't been added. $children = $this->getExternalChildGroupIds($hierarchyParentId); foreach ($children as $child) { if ($externalChildId->isEqual($child)) { throw new HarmoniException("Child group '" . $externalChildId->getIdString() . "' has already been added to group '" . $hierarchyParentId->getIdString() . "'."); } } // Insert the row. $query = new InsertQuery(); $query->setTable('agent_external_children'); $query->addValue('fk_parent', $hierarchyParentId->getIdString()); $query->addValue('fk_child', $externalChildId->getIdString()); $dbc = Services::getService("DBHandler"); $dbc->query($query, $this->_configuration->getProperty('database_index')); }
/** * Installs a plugin * * @param object HarmoniType $type gives us the location of plugin to be * installed * @access public * @since 3/6/06 */ function installPlugin($type) { // @todo deal with new plugin readiness structure, and database tables $authZ = Services::getService("AuthZ"); // if ($authZ->isUserAuthorized("edu.middlebury.authorization.add_children", ??)) { $dr = Services::getService("Repository"); $dm = Services::getService("DataTypeManager"); $db = Services::getService("DBHandler"); $id = Services::getService("Id"); // a few things we need $site_rep = $dr->getRepository($id->getId("edu.middlebury.segue.sites_repository")); $pluginDir = $this->getConfiguration('plugin_dir'); $types = $dm->getRegisteredTypes(); // for partstructures // use the plugin type to get through the filesystem $domain = $type->getDomain(); $authority = $type->getAuthority(); $keyword = $type->getKeyword(); $description = "The type for a {$domain} {$authority} {$keyword} plugin."; // write the type to the database $query = new InsertQuery(); $query->setTable('plugin_type'); $query->setColumns(array("type_domain", "type_authority", "type_keyword", "type_description", "type_enabled")); $query->addRowOfValues(array("'" . addslashes($domain) . "'", "'" . addslashes($authority) . "'", "'" . addslashes($keyword) . "'", "'" . addslashes($description) . "'", '0')); $db->query($query, IMPORTER_CONNECTION); // grab the xml file $xmlFile = $pluginDir . "/" . $domain . "/" . $authority . "/" . $keyword . "/" . $authority . $keyword . "Plugin.xml"; // if there is no file then the plugin has no data structures if (is_file($xmlFile)) { $document = new DOMDocument(); $document->loadXML($xmlFile); $recordStructures = $document->documentElement->childNodes; // first create the recordstructure(s) foreach ($recordStructures as $rs) { if ($rs->hasAttribute("name")) { $rsName = $rs->getAttribute("name"); $plugStruct = $site_rep->createRecordStructure($rsName, "This is the {$rsName} structure for holding data of the {$domain} {$authority} {$keyword} plugin", "", ""); $pSId = $plugStruct->getId(); $partStructures = $rs->childNodes; // now create the partstructure(s) foreach ($partStructures as $ps) { if ($ps->hasAttribute("name") && $ps->hasAttribute("type")) { $psName = $ps->getAttribute("name"); $psType = $ps->getAttribute("type"); if (in_array($psType, $types)) { $plugStruct->createPartStructure($psName, "This is the {$psName} structure for holding data of the {$domain} {$authority} {$keyword} plugin", new Type("Repository", "edu.middlebury.segue", $psType), false, true, false); } } } // write to the DB the plugin and its structures $typeId = null; $query2 = new SelectQuery(); $query2->addTable("plugin_type"); $query2->addColumn("*"); $query2->addWhere("type_domain = '" . addslashes($domain) . "'"); $query2->addWhere("type_authority = '" . addslashes($authority) . "'"); $query2->addWhere("type_keyword = '" . addslashes($keyword) . "'"); $results = $db->query($query2, IMPORTER_CONNECTION); if ($results->getNumberOfRows() == 1) { $result = $results->next(); $typeId = $result['type_id']; $results->free(); $query3 = new InsertQuery(); $query3->setTable("plugin_manager"); $query3->setColumns(array("fk_plugin_type", "fk_schema")); $query3->addRowOfValues(array("'" . addslashes($typeId) . "'", "'" . addslashes($pSId->getIdString()) . "'")); $db->query($query3, IMPORTER_CONNECTION); } else { $results->free(); throwError(new Error("PluginType not found", "Plugins", false)); } } } } if (!in_array($type->asString(), array_keys($this->getInstalledPlugins()))) { $this->addPluginToArray($type); } // } }
/** * Add this tag to an Item for a particular agent * * @param object TaggedItem $item * @param object Id $agentId * @param optional object DateAndTime $date An optional timestamp, used for importing historical tags. * @return object The item * @access public * @since 11/6/06 */ function tagItemForAgent(TaggedItem $item, Id $agentId, DateAndTime $date = null) { // Make sure the item is not already tagged if ($this->isItemTagged($item)) { return $item; } // Make sure the tag has a non-zero length if (!$this->getValue()) { return $item; } $query = new InsertQuery(); $query->setTable('tag'); $query->addValue('value', $this->getValue()); $query->addValue('user_id', $agentId->getIdString()); $query->addValue('fk_item', $item->getDatabaseId()); //printpre("'".addslashes($item->getDatabaseId())."'")) if (!is_null($date)) { $query->addValue('tstamp', $date->asString()); } $dbc = Services::getService("DatabaseManager"); $result = $dbc->query($query, $this->getDatabaseIndex()); return $item; }
/** * Import a historical version, for instance from a backup system. * * @param object DOMDocument $versionXml The version markup. * @param object Id $agentId The agent id that created the version. * @param object DateAndTime $timestamp The time the version was created. * @param string $comment A comment associated with the version. * @return void * @access public * @since 1/23/08 */ public function importVersion(DOMDocument $versionXml, Id $agentId, DateAndTime $timestamp, $comment) { $query = new InsertQuery(); $query->setTable('segue_plugin_version'); $query->addValue('node_id', $this->getId()); $query->addValue('tstamp', $timestamp->asString()); $query->addValue('agent_id', $agentId->getIdString()); $query->addValue('comment', $comment); $query->addValue('version_xml', $versionXml->saveXML()); $dbc = Services::getService('DBHandler'); $dbc->query($query, IMPORTER_CONNECTION); unset($this->versions); }
/** * Get the key of the type. * * @param object Type $type * @return integer * @access private * @since 3/9/05 */ function _getTypeKey(Type $type) { $dbc = Services::getService("DatabaseManager"); // Check if the type exists and return its key if found. $query = new SelectQuery(); $query->addTable($this->_typeTable); $query->addColumn('id'); $query->addWhere("domain='" . addslashes($type->getDomain()) . "'"); $query->addWhere("authority='" . addslashes($type->getAuthority()) . "'", _AND); $query->addWhere("keyword='" . addslashes($type->getKeyword()) . "'", _AND); $result = $dbc->query($query, $this->_dbId); if ($result->getNumberOfRows() == 1) { return $result->field('id'); } else { $result->free(); $query = new InsertQuery(); $query->setTable($this->_typeTable); $query->setAutoIncrementColumn("id", $this->_typeTable . "_id_seq"); $query->setColumns(array('domain', 'authority', 'keyword', 'description')); $query->setValues(array("'" . addslashes($type->getDomain()) . "'", "'" . addslashes($type->getAuthority()) . "'", "'" . addslashes($type->getKeyword()) . "'", "'" . addslashes($type->getDescription()) . "'")); $result = $dbc->query($query, $this->_dbId); return $result->getLastAutoIncrementValue(); } }
/** * Build the ancestory rows for a given node * * @param object Id $id * @return void * @access public * @since 11/4/05 */ function rebuildNodeAncestory(Id $id) { if (isset($this->harmoni_db)) { return $this->rebuildNodeAncestory_Harmoni_Db($id); } // print "<hr/><hr/>"; // print "<strong>"; printpre($id); print "</strong>"; $idString = $id->getIdString(); $dbHandler = Services::getService("DatabaseManager"); // Delete the old ancestory rows $this->clearNodeAncestory($idString); // Make sure we have traversed the authoratative parent/child hierarchy // To determine the new ancestory of the nodes if (!$this->_isCachedUp($idString, -1)) { $this->_traverseUp($idString, -1); } // now that all nodes are cached, add their ids to the ancestor table for // easy future searching. $query = new InsertQuery(); $query->setTable("az2_node_ancestry"); $query->setColumns(array("fk_hierarchy", "fk_node", "fk_ancestor", "level", "fk_ancestors_child")); $treeNode = $this->_tree->getNode($idString); $treeNodes = $this->_tree->traverse($treeNode, false, -1); if (count($treeNodes) > 1) { foreach (array_keys($treeNodes) as $i => $key) { $node = $this->_cache[$key][0]; // If the node was deleted, but the cache still has a key for it, // continue. if (!is_object($node)) { continue; } $nodeId = $node->getId(); // printpre($nodeId->getIdString()); if (!$nodeId->isEqual($id)) { foreach ($treeNodes[$key]['children'] as $ancestorChildId) { $query->addRowOfValues(array("'" . addslashes($this->_hierarchyId) . "'", "'" . addslashes($idString) . "'", "'" . addslashes($nodeId->getIdString()) . "'", "'" . addslashes($treeNodes[$key][1]) . "'", "'" . addslashes($ancestorChildId) . "'")); } } else { $query->addRowOfValues(array("'" . addslashes($this->_hierarchyId) . "'", "'" . addslashes($idString) . "'", "NULL", "'0'", "NULL")); } } $queryResult = $dbHandler->query($query, $this->_dbIndex); // $queryResult->free(); } }
/** * Set the contents of the file * * @param string $contents * @return null * @access public * @since 5/15/08 */ public function setContents($contents) { try { $this->getContents(); $query = new UpdateQuery(); $query->addWhereEqual('fk_theme', $this->themeId); $query->addWhereEqual('path', $this->path); } catch (UnknownIdException $e) { $query = new InsertQuery(); $query->addValue('fk_theme', $this->themeId); $query->addValue('path', $this->path); $mime = Services::getService("MIME"); $query->addValue('mime_type', $mime->getMIMETypeForFileName($this->getBaseName())); } $query->setTable('segue_site_theme_image'); $query->addValue('data', base64_encode($contents)); $query->addValue('size', strlen($contents)); $dbMgr = Services::getService("DatabaseManager"); $result = $dbMgr->query($query, $this->databaseIndex); if (!$result->hasNext()) { throw new UnknownIdException("Theme image '" . $this->path . "' for theme '" . $this->themeId . "' does not exist."); } return $result->field('data'); }
function test_All_Queries() { $value = "'Depeche Mode rocks!'"; $this->dbhandler->connect(); // create a new queue of queries to execuete $queryQueue = new Queue(); $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->addRowOfValues(array($value)); $queryQueue->add($query); $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array(id, value)); $query->addRowOfValues(array("3000000", $value)); $queryQueue->add($query); $query = new DeleteQuery(); $query->setTable("test1"); $query->setWhere("id = 3000000"); $queryQueue->add($query); $query = new UpdateQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->setValues(array($value)); $query->setWhere("id > 1000 AND id < 1006"); $queryQueue->add($query); $resultQueue = $this->dbhandler->queryQueue($queryQueue); $this->assertEqual($this->dbhandler->getTotalNumberOfQueries(), 4); $this->assertEqual($this->dbhandler->getTotalNumberOfSuccessfulQueries(), 4); $this->assertEqual($this->dbhandler->getTotalNumberOfFailedQueries(), 0); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $this->assertNotNull($result->getLastAutoIncrementValue()); $id = $result->getLastAutoIncrementValue(); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $this->assertNotNull($result->getLastAutoIncrementValue()); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $result = $resultQueue->next(); $query = new SelectQuery(); $query->setColumns(array("value")); $query->addTable("test1"); $query->setWhere("id = {$id}"); $result = $this->dbhandler->query($query); $this->assertEqual($this->dbhandler->getTotalNumberOfQueries(), 5); $this->assertEqual($this->dbhandler->getTotalNumberOfSuccessfulQueries(), 5); $this->assertEqual($this->dbhandler->getTotalNumberOfFailedQueries(), 0); $this->assertEqual("'" . $result->field("value") . "'", $value); $result->free(); }
/** * Add a new image at the path specified. * * @param object Harmoni_Filing_FileInterface $image * @param string $filename * @param string $prefixPath * @return null * @access public * @since 5/15/08 */ public function addImage(Harmoni_Filing_FileInterface $image, $filename, $prefixPath = '') { if (!$this->canModify()) { throw new PermissionDeniedException(); } ArgumentValidator::validate($filename, NonzeroLengthStringValidatorRule::getRule()); $path = trim($prefixPath, '/'); if (strlen($path)) { $path = $path . '/' . $filename; } else { $path = $filename; } // Delete the old image $query = new DeleteQuery(); $query->setTable('segue_site_theme_image'); $query->addWhereEqual('fk_theme', $this->id); $query->addWhereEqual('path', $path); $dbc = Services::getService('DatabaseManager'); $dbc->query($query, $this->databaseIndex); $query = new InsertQuery(); $query->setTable('segue_site_theme_image'); $query->addValue('fk_theme', $this->id); $query->addValue('mime_type', $image->getMimeType()); $query->addValue('path', $path); $query->addValue('size', $image->getSize()); $query->addValue('data', base64_encode($image->getContents())); $dbc = Services::getService('DatabaseManager'); $dbc->query($query, $this->databaseIndex); }
/** * Convert a slot to another type. The object passed on will no longer be valid. * * @param object Slot $slot * @param string $type * @return object Slot * @access public * @since 1/4/08 */ public function convertSlotToType(Slot $slot, $type) { if (!isset($this->slotTypes[$type])) { throw new Exception("Unknown SlotType, '{$type}'. Should be one of (" . implode(", ", array_keys($this->slotTypes)) . ")."); } $shortname = $slot->getShortname(); $dbc = Services::getService("DatabaseManager"); try { // Add a row to the slot table $query = new InsertQuery(); $query->setTable('segue_slot'); $query->addValue('shortname', $shortname); if ($slot->getSiteId()) { $query->addValue('site_id', $slot->getSiteId()->getIdString()); } if ($slot->isAlias()) { $query->addValue('alias_target', $slot->getAliasTarget()->getShortname()); } $query->addValue('type', $type); $query->addValue('location_category', $slot->getLocationCategory()); if (!$slot->usesDefaultMediaQuota()) { $query->addValue('media_quota', $slot->getMediaQuota()); } $dbc->query($query, IMPORTER_CONNECTION); } catch (DuplicateKeyDatabaseException $e) { // Update row to the slot table $query = new UpdateQuery(); $query->setTable('segue_slot'); $query->addWhereEqual('shortname', $shortname); $query->addValue('type', $type); $dbc->query($query, IMPORTER_CONNECTION); } // Clear our cache unset($this->slots[$shortname]); $slot = $this->getSlotByShortname($shortname); return $slot; }