/** * 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; }
/** * Returns the values of wizard-components. Should return an array if children are involved, * otherwise a whatever type of object is expected. * @access public * @return mixed */ function getAllValues() { if (is_null($this->_value)) { return null; } $obj = DateAndTime::fromString($this->_value); // print "<pre>"; var_dump($this->_value); print "</pre>"; // printpre($obj); return $obj; }
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()); }
/** * 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; }
/** * 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()); }
/** * 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(); }
/** * load the info for this file * * @return null * @access protected * @since 5/15/08 */ protected function loadInfo() { $query = new SelectQuery(); $query->addTable('segue_site_theme_image'); $query->addColumn('size'); $query->addColumn('mime_type'); $query->addColumn('modify_timestamp'); $query->addWhereEqual('fk_theme', $this->themeId); $query->addWhereEqual('path', $this->path); $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."); } $row = $result->next(); $this->size = $row['size']; $this->mimeType = $row['mime_type']; $this->modificationDate = DateAndTime::fromString($row['modify_timestamp']); }
/** * 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; }
/** * Test Converting Methods * */ function test_converting() { // Converting $timespan = Year::startingDuration(DateAndTime::withYearMonthDayHourMinuteSecondOffset(2005, 5, 4, 15, 25, 10, Duration::withHours(-4)), Duration::withDays(10)); // asDate() $temp = $timespan->asDate(); $this->assertTrue($temp->isEqualTo(Date::withYearMonthDay(2005, 5, 4))); // asDateAndTime() $temp = $timespan->asDateAndTime(); $this->assertTrue($temp->isEqualTo(DateAndTime::withYearMonthDayHourMinuteSecond(2005, 5, 4, 00, 00, 00))); // asDuration() $temp = $timespan->asDuration(); $this->assertTrue($temp->isEqualTo(Duration::withDays(365))); // asMonth() $temp = $timespan->asMonth(); $this->assertTrue($temp->isEqualTo(Month::withMonthYear(5, 2005))); // asTime() $temp = $timespan->asTime(); $dateAndTime = DateAndTime::withYearMonthDayHourMinuteSecond(2005, 5, 4, 0, 0, 0); $this->assertTrue($temp->isEqualTo($dateAndTime->asTime())); // asTimeStamp() $temp = $timespan->asTimeStamp(); $this->assertTrue($temp->isEqualTo(TimeStamp::withYearMonthDayHourMinuteSecond(2005, 5, 4, 0, 0, 0))); // asWeek() $temp = $timespan->asWeek(); $this->assertTrue($temp->isEqualTo(Week::starting(Date::withYearMonthDay(2005, 5, 1)))); // asYear() $temp = $timespan->asYear(); $this->assertTrue($temp->isEqualTo(Year::starting(Date::withYearMonthDay(2005, 5, 4)))); // to() $temp = $timespan->to(Date::withYearMonthDay(2005, 10, 1)); $comparison = Timespan::startingEnding(DateAndTime::withYearMonthDayHourMinuteSecond(2005, 5, 4, 0, 0, 0), Date::withYearMonthDay(2005, 10, 1)); $this->assertTrue($temp->isEqualTo($comparison)); }
/** * Answer an array of ThemeHistory items, in reverse chronological order. * * @return array * @access public * @since 5/8/08 */ public function getHistory() { if (!isset($this->info)) { $this->loadInfo(); } if (is_null($this->info)) { return array(); } $xpath = new DOMXPath($this->info); $entryElements = $xpath->query('/ThemeInfo/History/Entry'); $history = array(); $dates = array(); foreach ($entryElements as $entryElement) { $comment = $xpath->query('Comment', $entryElement)->item(0)->nodeValue; $name = $xpath->query('Name', $entryElement)->item(0)->nodeValue; $email = $xpath->query('EMail', $entryElement)->item(0)->nodeValue; $date = DateAndTime::fromString($entryElement->getAttribute('date')); $history[] = new Harmoni_Gui2_HistoryEntry($date, $comment, $name, $email); $dates[] = $date->asString(); } $unique = array_keys($history); array_multisort($dates, SORT_DESC, $unique, $history); return $history; }
/** * Create a new Year * * @param integer $anInteger * @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 Year * @access public * @since 5/4/05 * @static */ static function withYear($anInteger, $class = 'Year') { $start = DateAndTime::withYearMonthDay($anInteger, 1, 1); eval('$result = ' . $class . '::startingDuration( $start, $null = NULL, $class );'); return $result; }
/** * Test some leap years. * */ function test_end() { $datA = DateAndTime::withYearDay(2005, 125); $datB = DateAndTime::withYearDay(2006, 125); $timespan = Schedule::startingDuration(DateAndTime::withYearDay(2005, 125), Duration::withDays(365)); $this->assertEqual($timespan->startYear(), 2005); $this->assertEqual($timespan->dayOfYear(), 125); $duration = $timespan->duration(); $this->assertTrue($duration->isEqualTo(Duration::withDays(365))); $end = $timespan->end(); $this->assertEqual($end->julianDayNumber(), 2453860); $this->assertEqual($end->julianDayNumber() - $datA->julianDayNumber(), 364); $this->assertEqual($end->year(), 2006); $this->assertEqual($end->dayOfYear(), 124); $this->assertTrue($end->isEqualTo(DateAndTime::withYearDayHourMinuteSecond(2006, 124, 23, 59, 59))); }
/** * 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 4/28/05 */ function saveWizard($cacheName) { $harmoni = Harmoni::instance(); $harmoni->request->startNamespace('modify_exhibition'); $harmoni->request->passthrough('exhibition_id'); $wizard = $this->getWizard($cacheName); // Make sure we have a valid Repository $idManager = Services::getService("Id"); $authZ = Services::getService("AuthZ"); $repositoryManager = Services::getService("Repository"); $exhibitionRepositoryId = $idManager->getId("edu.middlebury.concerto.exhibition_repository"); $repository = $repositoryManager->getRepository($exhibitionRepositoryId); $asset = $repository->getAsset($idManager->getId(RequestContext::value('exhibition_id'))); $properties = $wizard->getAllValues(); $assetType = new Type("Asset Types", "edu.middlebury.concerto", "Exhibition", "Exhibition Assets are containers for Slideshows."); $asset->updateDisplayName($properties['namedescstep']['display_name']); $asset->updateDescription($properties['namedescstep']['description']); $assetId = $asset->getId(); $this->_assetId = $assetId; // Update the effective/expiration dates if ($properties['datestep']['effective_date']) { $asset->updateEffectiveDate(DateAndTime::fromString($properties['datestep']['effective_date'])); } if ($properties['datestep']['expiration_date']) { $asset->updateExpirationDate(DateAndTime::fromString($properties['datestep']['expiration_date'])); } // Log the success or failure if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Concerto"); $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("Modify Node", "Exhibition Modified"); $item->addNodeId($asset->getId()); $log->appendLogWithTypes($item, $formatType, $priorityType); } $harmoni->request->endNamespace(); return TRUE; }
/** * Load the information XML file * * @return null * @access protected * @since 5/7/08 */ protected function loadInfo() { $query = new SelectQuery(); $query->addTable('segue_site_theme'); $query->addColumn('display_name'); $query->addColumn('description'); $query->addColumn('modify_timestamp'); $query->addWhereEqual('id', $this->id); $dbMgr = Services::getService("DatabaseManager"); $result = $dbMgr->query($query, $this->databaseIndex); if (!$result->hasNext()) { throw new UnknownIdException("Theme with id '" . $this->id . "' does not exist."); } $row = $result->next(); $result->free(); $this->displayName = $row['display_name']; $this->description = $row['description']; $this->modificationDate = DateAndTime::fromString($row['modify_timestamp']); }
/** * creates appropriate object from given ids * * @param Id $structureId * @param Id $partStructureId * @param String $part * @return object mixed * @access public * @since 7/21/05 */ function getPartObject($structureId, $partStructureId, $part) { $structure = $this->_destinationRepository->getRecordStructure($structureId); $partStructure = $structure->getPartStructure($partStructureId); $type = $partStructure->getType(); $typeString = $type->getKeyword(); switch ($typeString) { case "shortstring": case "string": $obj = String::withValue($part); return $obj; break; case "integer": $obj = Integer::withValue($part); return $obj; break; case "boolean": $obj = Boolean::withValue($part); return $obj; break; case "float": $obj = Float::withValue($part); return $obj; break; case "datetime": $obj = DateAndTime::fromString($part); return $obj; break; case "type": $obj = HarmoniType::fromString($part); return $obj; break; default: $this->addError("Unsupported PartStructure DataType: " . HarmoniType::typeToString($type) . "."); $false = false; return $false; } }
/** * Forcibly set the creation date of this Asset. This is meant to be used when importing * from backups. * * WARNING: NOT IN OSID * * @param object DateAndTime $date * @return void * @access public * @since 1/25/08 */ public function forceSetModificationDate(DateAndTime $date) { $dbHandler = Services::getService("DatabaseManager"); $query = new UpdateQuery(); $query->setTable("dr_asset_info"); $query->addValue("modify_timestamp", $date->asString()); $query->addWhere("asset_id='" . $this->getId()->getIdString() . "'"); $dbHandler->query($query, $this->_dbIndex); $this->_modifyDate = $date; }
/** * Imports the current node's information * * @access public * @since 10/6/05 */ function importNode() { $idManager = Services::getService("Id"); if (!method_exists($this->_parent, "createAsset")) { $this->_stepParent = $this->_parent; $this->_parent = $this->_stepParent->getRepository(); } $this->getNodeInfo(); $hasId = $this->_node->hasAttribute("id"); if ($hasId && (in_array($this->_node->getAttribute("id"), $this->_existingArray) || $this->_type == "update")) { $this->_myId = $idManager->getId($this->_node->getAttribute("id")); $this->_object = $this->_parent->getAsset($this->_myId); $this->update(); } else { $this->_object = $this->_parent->createAsset($this->_info['name'], $this->_info['description'], $this->_info['type']); $this->_myId = $this->_object->getId(); if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Harmoni"); $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("Create Node", "Asset: " . htmlspecialchars($this->_myId->getIdString()) . " created."); $item->addNodeId($this->_myId); $item->addNodeId($this->_parent->getId()); } if (isset($this->_stepParent)) { $this->_stepParent->addAsset($this->_myId); if (isset($item)) { $item->addNodeId($this->_stepParent->getId()); } } if (isset($this->_info['effectivedate'])) { $this->_object->updateEffectiveDate(DateAndTime::fromString($this->_info['effectivedate'])); } if (isset($this->_info['expirationdate'])) { $this->_object->updateExpirationDate(DateAndTime::fromString($this->_info['expirationdate'])); } if (isset($item)) { $log->appendLogWithTypes($item, $formatType, $priorityType); } } if ($this->_node->hasAttribute("maintainOrder") && $this->_node->getAttribute("maintainOrder") == TRUE) { $this->doSets(); } }
/** * Converts a database datetime/timestamp/time value (that has been fetched * from the db) to a DateAndTime object. * * @access public * @param mixed A database datetime/timestamp/time value (that has been fetched * from the db). * @return ref object The DateAndTime object. */ function fromDBDate($value) { /* * NOT SURE HOW TO DO THIS FOR ORACLE */ $obj = DateAndTime::fromString($value); return $obj; }
/** * Print the dateRange form * * @param object DateAndTime $startDate * @param object DateAndTime $endDate * @return void * @access public * @since 3/8/06 */ function printDateRangeForm($startDate, $endDate) { $min = $this->minDate(); $max = DateAndTime::tomorrow(); $harmoni = Harmoni::instance(); print "\n<form action='"; $harmoni->request->forget('startYear'); $harmoni->request->forget('startMonth'); $harmoni->request->forget('startDay'); $harmoni->request->forget('startHour'); $harmoni->request->forget('endYear'); $harmoni->request->forget('endMonth'); $harmoni->request->forget('endDay'); $harmoni->request->forget('endHour'); print $harmoni->request->quickURL('logs', 'browse'); $harmoni->request->passthrough('log', 'priority', 'startYear', 'startMonth', 'startDay', 'startHour', 'endYear', 'endMonth', 'endDay', 'endHour', 'agent_id', 'node_id', 'category'); print "' method='post'>"; print "\n\t<select name='" . RequestContext::name("startMonth") . "'>"; $month = 1; while ($month <= 12) { print "\n\t\t<option value='" . $month . "'"; print $month == $startDate->month() ? " selected='selected'" : ""; print ">" . Month::nameOfMonth($month) . "</option>"; $month++; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("startDay") . "'>"; $day = 1; while ($day <= 31) { print "\n\t\t<option value='" . $day . "'"; print $day == $startDate->dayOfMonth() ? " selected='selected'" : ""; print ">" . $day . "</option>"; $day++; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("startYear") . "'>"; $year = $max->year(); $minYear = $min->year(); while ($year >= $minYear) { print "\n\t\t<option value='" . $year . "'"; print $year == $startDate->year() ? " selected='selected'" : ""; print ">{$year}</option>"; $year--; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("startHour") . "'>"; $hour = 0; while ($hour <= 23) { print "\n\t\t<option value='" . $hour . "'"; print $hour == $startDate->hour() ? " selected='selected'" : ""; print ">" . sprintf("%02d", $hour) . ":00</option>"; $hour++; } print "\n\t</select>"; print "\n\t<strong> to: </strong>"; print "\n\t<select name='" . RequestContext::name("endMonth") . "'>"; $month = 1; while ($month <= 12) { print "\n\t\t<option value='" . $month . "'"; print $month == $endDate->month() ? " selected='selected'" : ""; print ">" . Month::nameOfMonth($month) . "</option>"; $month++; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("endDay") . "'>"; $day = 1; while ($day <= 31) { print "\n\t\t<option value='" . $day . "'"; print $day == $endDate->dayOfMonth() ? " selected='selected'" : ""; print ">" . $day . "</option>"; $day++; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("endYear") . "'>"; $year = $max->year(); $minYear = $min->year(); while ($year >= $minYear) { print "\n\t\t<option value='" . $year . "'"; print $year == $endDate->year() ? " selected='selected'" : ""; print ">{$year}</option>"; $year--; } print "\n\t</select>"; print "\n\t<select name='" . RequestContext::name("endHour") . "'>"; $hour = 0; while ($hour <= 23) { print "\n\t\t<option value='" . $hour . "'"; print $hour == $endDate->hour() ? " selected='selected'" : ""; print ">" . sprintf("%02d", $hour) . ":00</option>"; $hour++; } print "\n\t</select>"; print "\n\t<input type='submit' value='" . _("Set Range") . "'/>"; print "\n\t<a href='"; print $harmoni->request->quickURL('logs', 'browse', array('startYear' => $min->year(), 'startMonth' => $min->month(), 'startDay' => $min->dayOfMonth(), 'startHour' => $min->hour(), 'endYear' => $max->year(), 'endMonth' => $max->month(), 'endDay' => $max->dayOfMonth(), 'endHour' => $max->hour())); print "'>"; print "\n\t\t<input type='button' value='" . _("Clear") . "' />"; print "</a>"; print "\n</form>"; }
/** * Answer a DateAndTime that represents this object * * @return object DateAndTime * @access public * @since 5/4/05 */ function asDateAndTime() { $dateAndTime = DateAndTime::today(); $obj = $dateAndTime->plus($this); return $obj; }
/** * 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; } }
/** * 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(); } }
/** * 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); }
/** * Answer true if the content has modified since the cache was last * updated, false otherwise. * * Based on info from: * Simon Willison - http://simonwillison.net/2003/Apr/23/conditionalGet/ * http://fishbowl.pastiche.org/archives/001132.html * * * @param object DateAndTime $timestamp * @param string $eTag * @return boolean * @access private * @since 5/13/08 */ private function changed(DateAndTime $timestamp, $eTag) { if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $clientTimestamp = DateAndTime::fromString(stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE'])); } if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) { $clientETag = trim($_SERVER['HTTP_IF_NONE_MATCH']); $eTag = trim($eTag); } // Check the HTTP 1.1 ETag/If None Match parts first. if (isset($clientETag) && $clientETag == $eTag) { return false; } // Check the HTTP 1.0 Modification date if (isset($clientTimestamp) && $timestamp->isLessThanOrEqual($clientTimestamp)) { return false; } return true; }
/** * Generate the Monthly Project Report for Selected User * @return View */ public function postUserProjectReport() { //Get the selected UserId $userId = \Input::get('userprojectreportid'); //Get Details of User $user = \User::find($userId); $firstName = $user->first_name; $lastName = $user->last_name; //Get selected Project Id $projectId = \Input::get('projectmonth'); //Get the selected Date for the month $selectedMonth = \Input::get('userprojectdate_submit'); //Generate Month from the date $daysArray = \DateAndTime::getMonthDates($selectedMonth); //Get Data $data = $this->report->generateWeeklyProjectReport($daysArray, $projectId, $userId); //Manipulation for View $tempDates = array(); foreach ($daysArray as $day) { $tempDay = new \ExpressiveDate($day); $tempDates[] = $tempDay->format('jS F, Y'); } //Manipulation for Charts $chartWeek = json_encode($tempDates); $tempDate = new \ExpressiveDate($selectedMonth); $year = $tempDate->getYear(); $month = $tempDate->getMonth(); $totalNoOfDays = (int) $tempDate->getDaysInMonth(); $allmonths = array(1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); $chartWeekData = json_encode($data['dayTime'], JSON_NUMERIC_CHECK); return \View::make('dashboard.reports.monthlyproject')->with('data', $data)->with('name', $firstName . $lastName)->with('totalDays', $totalNoOfDays)->with('dates', $daysArray)->with('year', (int) $year)->with('month', $allmonths[(int) $month])->with('chartWeek', $chartWeek)->with('chartWeekData', $chartWeekData); }
/** * Create a new object starting now, with a given duration. * Override - as each month has a defined duration * * @param object DateAndTime $aDateAndTime * @param object Duration $aDuration * @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 Month * @access public * @since 5/5/05 * @static */ static function startingDuration($aDateAndTime, $aDuration, $class = 'Month') { // Validate our passed class name. if (!(strtolower($class) == strtolower('Month') || is_subclass_of(new $class(), 'Month'))) { die("Class, '{$class}', is not a subclass of 'Month'."); } $start = $aDateAndTime->asDateAndTime(); $adjusted = DateAndTime::withYearMonthDay($start->year(), $start->month(), 1); $days = Month::daysInMonthForYear($adjusted->month(), $adjusted->year()); $month = new $class(); $month->setStart($adjusted); $month->setDuration(Duration::withDays($days)); return $month; }
/** * Answer an TagInfoIterator that lists information on tags attached to an item. * * @param object TaggedItem $item * @return object TagInfoIterator * @access public * @since 4/18/08 */ public function getTagInfoForItem(TaggedItem $item) { $query = new SelectQuery(); $query->addTable('tag'); $query->addColumn('value'); $query->addColumn('user_id'); $query->addColumn('tstamp'); $query->addWhereEqual("fk_item", $item->getDatabaseId()); $dbc = Services::getService("DatabaseManager"); $result = $dbc->query($query, $this->getDatabaseIndex()); $iterator = new HarmoniIterator(array()); $idManager = Services::getService("Id"); while ($result->hasNext()) { $row = $result->next(); $iterator->add(new TagInfo(new Tag($row['value']), $item, $idManager->getId($row['user_id']), DateAndTime::fromString($row['tstamp']))); } return $iterator; }