/** * Constructor * @param mixed $schema Either a {@link Schema} object or a string ID of the schema to use. * @param optional boolean $verControl If set to TRUE this DMRecord will use version-control. * @param optional int $fetchMode USED INTERNALLY */ function DMRecord($schema, $verControl = false, $fetchMode = RECORD_FULL) { ArgumentValidator::validate($verControl, BooleanValidatorRule::getRule()); // ArgumentValidator::validate($schema, ExtendsValidatorRule::getRule("Schema")); if (is_object($schema)) { $schemaID = $schema->getID(); } else { $schemaID = $schema; } // it's a string (we hope) $schemaManager = Services::getService("SchemaManager"); $schema = $schemaManager->getSchemaByID($schemaID); $schema->load(); $this->_schema = $schema; $this->_fields = array(); $this->_versionControlled = $verControl; $this->_fetchMode = $fetchMode; $this->_fetchedValueIDs = array(); $this->_creationDate = DateAndTime::now(); $this->_myID = null; $this->_delete = false; // set up the individual fields foreach ($schema->getAllIDs(true) as $label) { $def = $schema->getField($label); $this->_fields[$label] = new RecordField($def, $this); unset($def); } $this->_idManager = Services::getService("Id"); }
/** * Do the conversion for a source document * * @param object DOMDocument $sourceDoc * @param string $sourceFilePath * @return DOMDocument The output document * @access public * @since 2/4/08 */ public function convert(DOMDocument $sourceDoc, $sourceFilePath) { $this->sourceDoc = $sourceDoc; $this->sourceXPath = new DOMXPath($this->sourceDoc); if (!is_dir($sourceFilePath)) { throw new Exception("'{$sourceFilePath}' does not exist for conversion."); } if (!is_readable($sourceFilePath)) { throw new Exception("'{$sourceFilePath}' is not readable for conversion."); } $this->sourceFilePath = $sourceFilePath; // Set up the output document $this->doc = new Harmoni_DOMDocument(); $this->doc->appendChild($this->doc->createElement('Segue2')); $this->doc->documentElement->setAttribute('export_date', DateAndTime::now()->asString()); $this->doc->documentElement->setAttribute('segue_version', displayAction::getSegueVersion()); $this->doc->documentElement->setAttribute('segue_export_version', '2.0'); $this->agents = $this->doc->documentElement->appendChild($this->doc->createElement('agents')); $this->xpath = new DOMXPath($this->doc); $this->rootAdded = false; // print "<pre>"; // foreach ($this->sourceXPath->query('/site/media/media_file/filename') as $filename) // print $filename->nodeValue."\n"; // print "</pre>"; $this->addSite(); return $this->doc; }
/** * Mark a slot as being accessed. * This method should be called every time a page for a site is visited. * * @param string $slotname * @return void * @access public * @since 9/22/08 */ public function touch($slotname) { ArgumentValidator::validate($slotname, NonzeroLengthStringValidatorRule::getRule()); if ($this->_storePersistently()) { $this->_recordVisit($slotname); } else { $_SESSION['segue_access_log'][$slotname] = DateAndTime::now()->asString(); } }
function test_updates() { $dateTime = DateAndTime::now(); $this->authorization->updateExpirationDate($dateTime); $this->assertReference($dateTime, $this->authorization->getExpirationDate()); $this->assertFalse($this->authorization->isActiveNow()); $dateTime = DateAndTime::now(); $this->authorization->updateEffectiveDate($dateTime); $this->authorization->updateExpirationDate(DateAndTime::withYearMonthDay(2030, 10, 10)); $this->assertReference($dateTime, $this->authorization->getEffectiveDate()); $this->assertTrue($this->authorization->isActiveNow()); }
/** * Test the methods. */ function test_now() { $parser = new KeywordStringParser('now'); $this->assertTrue($parser->canHandle()); $dateAndTime = DateAndTime::now(); $offset = $dateAndTime->offset(); $this->assertEqual($parser->year(), $dateAndTime->year()); $this->assertEqual($parser->month(), $dateAndTime->month()); $this->assertEqual($parser->day(), $dateAndTime->dayOfMonth()); $this->assertEqual($parser->hour(), $dateAndTime->hour()); $this->assertEqual($parser->minute(), $dateAndTime->minute()); $this->assertEqual($parser->second(), $dateAndTime->second()); $this->assertEqual($parser->offsetHour(), $offset->hours()); $this->assertEqual($parser->offsetMinute(), $offset->minutes()); $this->assertEqual($parser->offsetSecond(), $offset->seconds()); }
/** * Initializes the export by creating a dir in the tmp dir * * @param string * @access public * @since 10/31/05 * @static */ static function withCompression($compression, $class = 'XMLExporter') { if (!(strtolower($class) == strtolower('XMLExporter') || is_subclass_of(new $class(), 'XMLExporter'))) { die("Class, '{$class}', is not a subclass of 'XMLExporter'."); } $exporter = new $class(); $now = DateAndTime::now(); $exporter->_tmpDir = self::getTmpDir() . "/export_" . str_replace(':', '-', $now->asString()); while (file_exists($exporter->_tmpDir)) { $now = DateAndTime::now(); $exporter->_tmpDir = self::getTmpDir() . "/export_" . str_replace(':', '-', $now->asString()); } mkdir($exporter->_tmpDir); $exporter->_compression = $compression; return $exporter; }
/** * Execute the action * * @return mixed * @access public * @since 1/17/08 */ public function execute() { $harmoni = Harmoni::instance(); $component = SiteDispatcher::getCurrentNode(); $site = SiteDispatcher::getCurrentRootNode(); $slotMgr = SlotManager::instance(); $slot = $slotMgr->getSlotBySiteId($site->getId()); $exportDir = DATAPORT_TMP_DIR . "/" . $slot->getShortname() . "-" . str_replace(':', '_', DateAndTime::now()->asString()); mkdir($exportDir); try { // Do the export $visitor = new DomExportSiteVisitor($exportDir); $component->acceptVisitor($visitor); // Validate the result // printpre(htmlentities($visitor->doc->saveXMLWithWhitespace())); // $tmp = new Harmoni_DomDocument; // $tmp->loadXML($visitor->doc->saveXMLWithWhitespace()); // $tmp->schemaValidateWithException(MYDIR."/doc/raw/dtds/segue2-site.xsd"); $visitor->doc->schemaValidateWithException(MYDIR . "/doc/raw/dtds/segue2-site.xsd"); // Write out the XML $visitor->doc->saveWithWhitespace($exportDir . "/site.xml"); $archive = new Archive_Tar($exportDir . ".tar.gz"); $archive->createModify($exportDir, '', DATAPORT_TMP_DIR); // Remove the directory $this->deleteRecursive($exportDir); header("Content-Type: application/x-gzip;"); header('Content-Disposition: attachment; filename="' . basename($exportDir . ".tar.gz") . '"'); print file_get_contents($exportDir . ".tar.gz"); // Clean up the archive unlink($exportDir . ".tar.gz"); } catch (PermissionDeniedException $e) { $this->deleteRecursive($exportDir); if (file_exists($exportDir . ".tar.gz")) { unlink($exportDir . ".tar.gz"); } return new Block(_("You are not authorized to export this component."), ALERT_BLOCK); } catch (Exception $e) { $this->deleteRecursive($exportDir); if (file_exists($exportDir . ".tar.gz")) { unlink($exportDir . ".tar.gz"); } throw $e; } error_reporting(0); exit; }
/** * 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(); }
/** * Test conversion to the PHP built-in DateTime * * @return void * @access public * @since 11/21/08 */ public function test_php_datetime() { print "<h3>conversion to PHP DateTime</h3>"; $ref = new ReflectionClass('DateTimeZone'); printpre($ref->getMethods()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(2005, 6, 4, 15, 25, 10, Duration::withHours(-5)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(2005, 2, 4, 15, 25, 10, Duration::withHours(-4)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(1423, 2, 4, 15, 25, 10, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(732, 6, 3, 8, 0, 0, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(2, 6, 3, 8, 0, 0, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(0, 6, 3, 8, 0, 0, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(-460, 6, 3, 8, 0, 0, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecondOffset(-8460, 6, 3, 8, 0, 0, Duration::withHours(0)); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); $dateAndTime = DateAndTime::now(); $this->checkEquality($dateAndTime, $dateAndTime->asDateTime()); }
/** * 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"; }
/** * Save our results. Tearing down and unsetting the Wizard is handled by * in {@link runWizard()} and does not need to be implemented here. * * @param string $cacheName * @return boolean TRUE if save was successful and tear-down/cleanup of the * Wizard should ensue. * @access public * @since 7/27/05 */ function saveWizard($cacheName) { $harmoni = Harmoni::instance(); $idManager = Services::getService("Id"); $repositoryManager = Services::getService("Repository"); $wizard = $this->getWizard($cacheName); $properties = $wizard->getAllValues(); $centerPane = $this->getActionRows(); ob_start(); $path = $properties['filename']['tmp_name']; $filename = $properties['filename']['name']; if ($properties['filename']['name'] == "") { print "Please choose a file to upload!"; $centerPane->add(new Block(ob_get_contents(), 1)); ob_end_clean(); return FALSE; } $newName = $this->moveArchive($path, $filename); //===== THIS ARRAY DEFINES THINGS THAT SHOULD NOT BE IMPORTED =====// $this->_ignore = array("REMOTE_FILE", "FILE_URL", "FILE", "FILE_DATA", "FILE_NAME", "MIME_TYPE", "THUMBNAIL_DATA", "THUMBNAIL_MIME_TYPE", "FILE_SIZE", "DIMENSIONS", "THUMBNAIL_DIMENSIONS", "edu.middlebury.harmoni.repository.asset_content", "edu.middlebury.harmoni.repository.asset_content.Content"); $repository = $repositoryManager->getRepository($idManager->getId($harmoni->request->get('collection_id'))); $startTime = DateAndTime::now(); $this->_hasErrors = false; //===== Exif and Tab-Delim Importers are special =====// if ($properties['file_type'] == "Tab-Delimited") { $importer = new TabRepositoryImporter($newName, $repository->getId(), false); } else { if ($properties['file_type'] == "Exif") { $importer = new ExifRepositoryImporter($newName, $repository->getId(), false); } else { if ($properties['file_type'] == "FilesOnly") { $importer = new FilesOnlyRepositoryImporter($newName, $repository->getId(), false); } } } if (isset($importer)) { if ($properties['parent']) { $importer->setParent($repository->getAsset($idManager->getId($properties['parent']))); } $importer->import($properties['is_archived']); // something happened so tell the end user if ($importer->hasErrors()) { $importer->printErrorMessages(); $this->_hasErrors = true; } } //===== Done with special "RepositoryImporters" =====// if ($properties['file_type'] == "XML") { if ($properties['is_archived'] == TRUE) { // define an empty importer for decompression $importer = new XMLImporter($this->_ignore); $directory = $importer->decompress($newName); unset($importer); $this->_repository = $repository; $this->_importType = $properties['import_type']; if ($properties['parent']) { $parent = $repository->getAsset($idManager->getId($properties['parent'])); } else { $parent = null; } $this->importDirectoriesDown($directory, $parent); } else { // not compressed, only one xml file $importer = XMLRepositoryImporter::withObject($this->_ignore, $repositoryManager->getRepository($idManager->getId($harmoni->request->get('collection_id'))), $newName, $properties['import_type']); if ($properties['parent']) { $importer->setParent($repository->getAsset($idManager->getId($properties['parent']))); } $importer->parseAndImportBelow("asset", 100); // something happened so tell the end user if ($importer->hasErrors()) { $importer->printErrorMessages(); $this->_hasErrors = true; } unset($importer); } } // Unlink the directory if (isset($directory) && $directory) { $this->deleteRecursive($directory); } if (file_exists($newName)) { unlink($newName); } if ($this->_hasErrors) { $centerPane->add(new Block(ob_get_contents(), 1)); ob_end_clean(); return FALSE; } // Update any newly modified assets' tags $searchProperties = new HarmoniProperties(new Type("repository", "harmoni", "order")); $searchProperties->addProperty("order", $order = "ModificationDate"); $searchProperties->addProperty("direction", $direction = "DESC"); $assets = $repository->getAssetsBySearch($criteria = '*', new Type("Repository", "edu.middlebury.harmoni", "DisplayName"), $searchProperties); $systemAgentId = $idManager->getId('system:concerto'); $tagGenerator = StructuredMetaDataTagGenerator::instance(); while ($assets->hasNext()) { $asset = $assets->next(); if ($startTime->isGreaterThan($asset->getModificationDate())) { break; } $tagGenerator->regenerateTagsForAsset($asset, $systemAgentId, 'concerto', $repository->getId()); } // clean and clear $centerPane->add(new Block(ob_get_contents(), 1)); ob_end_clean(); return TRUE; }
/** * 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); }
/** * Update the modification date and set the creation date if needed. * * WARNING: NOT IN OSID * * @return void * @access public * @since 5/4/06 */ function updateModificationDate() { // Only update our modification time if we will be adding more than a // minute (to save on many repeated updates while changing lots of values // at once). if (isset($this->_modifyDate) && is_object($this->_modifyDate)) { $now = DateAndTime::now(); $minute = Duration::withSeconds(60); if ($minute->isGreaterThan($now->minus($this->_modifyDate))) { return; } } $this->_loadDates(); $this->_storeDates(); }
/** * Answer the current time. * * @param optional string $class DO NOT USE OUTSIDE OF PACKAGE. * This parameter is used to get around the limitations of not being * able to find the class of the object that recieved the initial * method call. * @return object StorableTime * @access public * @since 5/12/05 * @static */ static function now($class = 'StorableTime') { return parent::now($class); }
/** * Return true if this Authorization is effective; false otherise; * * @return boolean * * @throws object AuthorizationException An exception with * one of the following messages defined in * org.osid.authorization.AuthorizationException may be thrown: * {@link * org.osid.authorization.AuthorizationException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.authorization.AuthorizationException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.authorization.AuthorizationException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.authorization.AuthorizationException#UNIMPLEMENTED * UNIMPLEMENTED} * * @access public */ function isActiveNow() { if (!is_object($this->_effectiveDate) || !is_object($this->_expirationDate)) { // a non-dated Authorization is always active return true; } // if current time is after the effective date and before the expiration // date, then the Authorization is active. if ($this->_effectiveDate->isLessThanOrEqualTo(DateAndTime::now()) && $this->_expirationDate->isGreaterThan(DateAndTime::now())) { return true; } else { return false; } }
/** * Execute this action. * * @return void * @access public * @since 7/28/08 */ public function execute() { if (!$this->isAuthorizedToExecute()) { throw new PermissionDeniedException(_("Your are not authorized to copy this site here.")); } $srcSlot = $this->getSourceSlot(); $srcSiteAsset = $this->getSourceSiteAsset(); $director = SiteDispatcher::getSiteDirector(); $srcComponent = $director->getSiteComponentFromAsset($srcSiteAsset); $destSlot = $this->getDestSlot(); if (RequestContext::value('command') == 'copy') { try { /********************************************************* * Export the Site *********************************************************/ $exportDir = DATAPORT_TMP_DIR . "/" . $srcSlot->getShortname() . "-" . str_replace(':', '_', DateAndTime::now()->asString()); mkdir($exportDir); // Do the export $visitor = new DomExportSiteVisitor($exportDir); $visitor->enableStatusOutput(_("Exporting from original location.")); $srcComponent->acceptVisitor($visitor); $doc = $visitor->doc; // Validate the result // printpre(htmlentities($doc->saveXMLWithWhitespace())); // $tmp = new Harmoni_DomDocument; // $tmp->loadXML($doc->saveXMLWithWhitespace()); // $tmp->schemaValidateWithException(MYDIR."/doc/raw/dtds/segue2-site.xsd"); $doc->schemaValidateWithException(MYDIR . "/doc/raw/dtds/segue2-site.xsd"); // printpre($this->listDir($exportDir)); // throw new Exception('test'); /********************************************************* * Import the site *********************************************************/ $importer = new DomImportSiteVisitor($doc, $exportDir, $director); if (RequestContext::value('copy_permissions') == 'true') { $importer->enableRoleImport(); } if (RequestContext::value('copy_discussions') != 'true') { $importer->disableCommentImport(); } // if (isset($values['owners'])) { // $idMgr = Services::getService('Id'); // foreach($values['owners']['admins'] as $adminIdString) // $importer->addSiteAdministrator($idMgr->getId($adminIdString)); // } $importer->enableStatusOutput(_("Importing into new location")); $importer->makeUserSiteAdministrator(); $site = $importer->importAtSlot($destSlot->getShortname()); // Delete the decompressed Archive $this->deleteRecursive($exportDir); /********************************************************* * Log the success *********************************************************/ if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Segue"); $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."); $item = new AgentNodeEntryItem("Copy Site", "Site copied from placeholder, '" . $srcSlot->getShortname() . "' to '" . $destSlot->getShortname() . "'."); $item->addNodeId($site->getQualifierId()); $log->appendLogWithTypes($item, $formatType, $priorityType); } } catch (Exception $e) { $this->deleteRecursive($exportDir); if (file_exists($exportDir . ".tar.gz")) { unlink($exportDir . ".tar.gz"); } throw $e; } } else { // Detach the site from the source slot. $srcSlot->deleteSiteId(); // Attach the site to the dest slot. $destSlot->setSiteId($srcSiteAsset->getId()); // Make the source an alias of the destination so that links still work. $srcSlot->makeAlias($destSlot); /********************************************************* * Log the success *********************************************************/ if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Segue"); $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."); $item = new AgentNodeEntryItem("Move Site", "Site moved from placeholder, '" . $srcSlot->getShortname() . "' to '" . $destSlot->getShortname() . "'."); $item->addNodeId($destSlot->getSiteId()); $log->appendLogWithTypes($item, $formatType, $priorityType); } } // Remove from selection? if (RequestContext::value('remove_after_use') == 'remove') { $selection = Segue_Selection::instance(); $selection->removeSiteComponent($srcComponent); } print "\n" . _("Done"); exit; }
/** * Answer a Plugin history comment for an element. Extensions of this * class may wish to override this method to modify the comment and/or store * the import date/user instead of that listed in the history. * * @param object DOMElement $element * @return object DateAndTime * @access protected * @since 1/25/08 */ protected function getPluginHistoryTimestamp(DOMElement $element) { return DateAndTime::now(); }
/** * "Sets" the value of this specific index to $value. If the DMRecord is version controlled, a new * version is added. Otherwise, the current active version is modified. * @return bool * @param ref object $value A {@link SObject} object. */ function setValueFromPrimitive($value) { // if we're version controlled, we're adding a new version // otherwise, we're just setting the existing (or only active) one. if ($this->_parent->_parent->isVersionControlled()) { // @todo This is referencing another object's private variables. Bad!! Fix this! // we're going to add a new version // which means, we add a new RecordFieldValue with a *replicate* // of the primitive, so that it gets added to the DB. $newVer = $this->newRecordFieldData(); $clone = $value->copy(); $newVer->setValueFromPrimitive($clone); // all done (we hope) return true; } // let's just set the value of the existing one. // if we have an active version, set that one. if (!$this->hasActiveValue()) { $this->undelete(); } $actVer = $this->getActiveVersion(); $actVal = $actVer->getPrimitive(); if ($actVal && $actVal->isEqual($value)) { return true; } $actVer->takeValueFromPrimitive($value); $actVer->setDate(DateAndTime::now()); // now tell actVer to update the DB on commit() $actVer->update(); return true; }
/** * Sychronize the cache. Remove any nodes from the cache whose AZs may have * changed. * * @return void * @access public * @since 12/20/05 */ function _synchronizeCache() { $dbHandler = Services::getService("DBHandler"); foreach (array_keys($_SESSION['__isAuthorizedCacheAgents']) as $agentIdString) { // Select the nodeIds who's authorization situation may have changed // since the cache was last synchronized. Clear these Ids from the cache. $query = new SelectQuery(); $query->addTable("az2_node"); $query->setColumns(array("id")); $dbDate = $dbHandler->toDBDate($_SESSION['__isAuthorizedCacheTime'][$agentIdString], $this->_configuration->getProperty('database_index')); $query->addWhere("last_changed > " . $dbDate); // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); $result = $dbHandler->query($query, $this->_configuration->getProperty('database_index')); while ($result->hasMoreRows()) { unset($_SESSION['__isAuthorizedCache'][$agentIdString][$result->field("id")]); $result->advanceRow(); } $result->free(); $_SESSION['__isAuthorizedCacheTime'][$agentIdString] = DateAndTime::now(); } }
/** * Answer true if this class is in the past * * @return boolean * @access public * @since 8/21/07 */ public function isPast() { try { if ($this->getEndDate()->isLessThan(DateAndTime::now())) { return true; } else { return false; } } catch (Exception $e) { return false; } }
/** * Copy a component. * * @param object SiteComponent * @return void * @access protected * @since 8/4/08 */ protected function copyComponent(SiteComponent $siteComponent) { $authZ = Services::getService("AuthZ"); $idMgr = Services::getService("Id"); if (!$authZ->isUserAuthorized($idMgr->getId('edu.middlebury.authorization.modify'), $siteComponent->getQualifierId())) { throw new PermissionDeniedException("You are not authorized to copy this node from its original location."); } try { /********************************************************* * Export the Component *********************************************************/ $exportDir = DATAPORT_TMP_DIR . "/" . $siteComponent->getId() . "-" . str_replace(':', '_', DateAndTime::now()->asString()); mkdir($exportDir); // Do the export $visitor = new DomExportSiteVisitor($exportDir); $visitor->enableStatusOutput(_("Exporting from original location.")); $siteComponent->acceptVisitor($visitor); $doc = $visitor->doc; // Validate the result // printpre(htmlentities($doc->saveXMLWithWhitespace())); $doc->schemaValidateWithException(MYDIR . "/doc/raw/dtds/segue2-subtree.xsd"); // printpre($this->listDir($exportDir)); // throw new Exception('test'); /********************************************************* * Import the Component *********************************************************/ $importer = new DomImportSiteVisitor($doc, $exportDir, SiteDispatcher::getSiteDirector()); if (RequestContext::value('copy_permissions') == 'true') { $importer->enableRoleImport(); } if (RequestContext::value('copy_discussions') == 'false') { $importer->disableCommentImport(); } $importer->enableStatusOutput(_("Importing into new location")); $newComponent = $importer->importSubtreeUnderOrganizer($this->getDestinationComponent()); // Delete the decompressed Archive $this->deleteRecursive($exportDir); return $newComponent; } catch (Exception $e) { $this->deleteRecursive($exportDir); if (file_exists($exportDir . ".tar.gz")) { unlink($exportDir . ".tar.gz"); } throw $e; } }
/** * Answer the current time. * * @param optional string $class DO NOT USE OUTSIDE OF PACKAGE. * This parameter is used to get around the limitations of not being * able to find the class of the object that recieved the initial * method call. * @return object TimeStamp * @access public * @since 5/12/05 * @static */ static function now($class = 'TimeStamp') { $obj = parent::now($class); return $obj; }
/** * Answer the later of the modified date and time and the user-login. * * @return object DateAndTime * @access private * @since 5/13/08 */ private function getLastModifiedTime() { $authN = Services::getService('AuthN'); $userId = $authN->getFirstUserId(); if (!isset($_SESSION['COND_GET_USER']) || !$userId->isEqual($_SESSION['COND_GET_USER']['userId'])) { $_SESSION['COND_GET_USER'] = array('userId' => $userId, 'login_time' => DateAndTime::now()); } // Get the time from the call back and validate it. $lastModified = call_user_func($this->getModifiedTimeCallback); ArgumentValidator::validate($lastModified, ExtendsValidatorRule::getRule('DateAndTime')); $lastModified = $lastModified->max($_SESSION['COND_GET_USER']['login_time']); // Ensure that it isn't in the future if ($lastModified->isGreaterThan(DateAndTime::now())) { return DateAndTime::now(); } else { return $lastModified; } }
/** * 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; }