Пример #1
0
 /**
  * Update the reference name for this Function.
  *
  * WARNING: NOT IN OSID
  * 
  * @param string $referenceName
  * 
  * @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}, {@link
  *		   org.osid.authorization.AuthorizationException#NULL_ARGUMENT
  *		   NULL_ARGUMENT}
  * 
  * @access public
  */
 function updateReferenceName($referenceName)
 {
     // ** parameter validation
     $stringRule = StringValidatorRule::getRule();
     ArgumentValidator::validate($referenceName, $stringRule, true);
     // ** end of parameter validation
     if ($this->_referenceName == $referenceName) {
         return;
     }
     // nothing to update
     // update the object
     $this->_referenceName = $referenceName;
     // update the database
     $dbHandler = Services::getService("DatabaseManager");
     $query = new UpdateQuery();
     $query->setTable("az_function");
     $query->addWhereEqual("function_id", $this->getId()->getIdString());
     $query->addValue("function_reference_name", $referenceName);
     $queryResult = $dbHandler->query($query, $this->_dbIndex);
     if ($queryResult->getNumberOfRows() == 0) {
         throwError(new Error(AuthorizationExeption::OPERATION_FAILED(), "AuthorizationFunction", true));
     }
     if ($queryResult->getNumberOfRows() > 1) {
         throwError(new Error(AuthorizationExeption::OPERATION_FAILED(), "AuthorizationFunction", true));
     }
 }
Пример #2
0
 /**
  * Update the description for this Hierarchy.
  * 
  * @param string $description
  * 
  * @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}
  * 
  * @access public
  */
 function updateDescription($description)
 {
     // ** parameter validation
     ArgumentValidator::validate($description, StringValidatorRule::getRule(), true);
     // ** end of parameter validation
     if ($this->_description == $description) {
         return;
     }
     // nothing to update
     // update the object
     $this->_description = $description;
     // update the database
     $dbHandler = Services::getService("DatabaseManager");
     $query = new UpdateQuery();
     $query->setTable("az2_hierarchy");
     $query->addWhereEqual('id', $this->getId()->getIdString());
     $query->addValue('description', $description);
     $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex);
     if ($queryResult->getNumberOfRows() == 0) {
         throw new OperationFailedException("No rows updated.");
     }
     if ($queryResult->getNumberOfRows() > 1) {
         throw new OperationFailedException("Too many rows updated, expecting 1.");
     }
 }
Пример #3
0
 /**
  * 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;
 }
Пример #4
0
 /**
  * Given an associative array of old Id strings and new Id strings.
  * Update any of the old Ids that this plugin instance recognizes to their
  * new value.
  * 
  * @param array $idMap An associative array of old id-strings to new id-strings.
  * @return void
  * @access public
  * @since 1/24/08
  */
 public function replaceIds(array $idMap)
 {
     $doc = $this->getVersionXml();
     $this->pluginInstance->replaceIdsInVersion($idMap, $doc);
     $query = new UpdateQuery();
     $query->setTable('segue_plugin_version');
     $query->addWhereEqual('version_id', $this->getVersionId());
     $query->addValue('version_xml', $doc->saveXML());
     $dbc = Services::getService('DBHandler');
     $dbc->query($query, IMPORTER_CONNECTION);
 }
Пример #5
0
 /**
  * Enable a plugin
  * 
  * @param object Type $type
  * @return void
  * @access public
  * @since 8/22/07
  */
 public function enablePlugin(Type $type)
 {
     $db = Services::getService("DBHandler");
     // write the type to the database
     $query = new UpdateQuery();
     $query->setTable('plugin_type');
     $query->addValue("type_enabled", '1');
     $query->addWhereEqual("type_domain", $type->getDomain());
     $query->addWhereEqual("type_Authority", $type->getAuthority());
     $query->addWhereEqual("type_keyword", $type->getKeyword());
     $db->query($query, IMPORTER_CONNECTION);
     $this->addPluginToArray($type, 'enabled');
 }
Пример #6
0
 /**
  * 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();
 }
Пример #7
0
 /**
  * Execute
  * 
  * @return void
  * @access public
  * @since 3/26/08
  */
 public function execute()
 {
     if (!$this->isAuthorizedToExecute()) {
         throw new PermissionDeniedException('This command can only be run by admins or from the command-line.');
     }
     header("Content-Type: text/plain");
     if (RequestContext::value('help') || RequestContext::value('h') || RequestContext::value('?')) {
         throw new HelpRequestedException($this->usage);
     }
     $outDir = RequestContext::value('d');
     if (empty($outDir)) {
         throw new InvalidArgumentException("An output directory must be specified.\n\n" . $this->usage);
     }
     if (!is_dir($outDir) || !is_writable($outDir)) {
         throw new InvalidArgumentException("The output directory doesn't exist or is not writeable.\n\n" . $this->usage);
     }
     foreach (SlotAbstract::getLocationCategories() as $category) {
         $baseUrl = SiteDispatcher::getBaseUrlForLocationCategory($category);
         if (!preg_match('/^https?:\\/\\/.+/', $baseUrl)) {
             throw new ConfigurationErrorException('Please set a base URL for the \'' . $category . '\' category with SiteDispatcher::setBaseUrlForLocationCategory($category, $url); in config/slots.conf.php');
         }
     }
     while (ob_get_level()) {
         ob_end_flush();
     }
     flush();
     /*********************************************************
      * Check for a running export
      *********************************************************/
     $dbc = Services::getService('DatabaseManager');
     $query = new SelectQuery();
     $query->addColumn('slot');
     $query->addColumn('pid');
     $query->addTable('site_export_queue');
     $query->addWhereNotEqual('pid', 0);
     $result = $dbc->query($query);
     // If we are exporting, check the status of the export process
     if ($result->hasMoreRows()) {
         // Don't start a new export if one is running.
         if ($this->isRunning($result->field('pid'))) {
             print "An export is already running\n";
             exit;
         } else {
             $query = new UpdateQuery();
             $query->setTable('site_export_queue');
             $query->addValue('status', 'DIED');
             $query->addRawValue('pid', 'NULL');
             $query->addValue('info', 'Process ' . $result->field('pid') . ' has died.');
             $query->addWhereEqual('slot', $result->field('slot'));
             $query->addWhereEqual('pid', $result->field('pid'));
             $dbc->query($query);
         }
     }
     /*********************************************************
      * If there aren't any other exports happening, run our export
      *********************************************************/
     // Find the next slot to update
     $query = new SelectQuery();
     $query->addColumn('slot');
     $query->addTable('site_export_queue', NO_JOIN, '', 'q');
     $query->addTable('segue_slot', INNER_JOIN, 'q.slot = s.shortname', 's');
     $query->addWhereNull('pid');
     $query->addWhereNull('status');
     $query->addWhereNull('alias_target');
     $query->addWhereNotEqual('site_id', '');
     $query->addOrderBy('priority', DESCENDING);
     $query->addOrderBy('slot', ASCENDING);
     $result = $dbc->query($query);
     // Exit if there is nothing to do.
     if (!$result->hasMoreRows()) {
         print "The queue is empty\n";
         exit;
     }
     $slot = $result->field('slot');
     $slotMgr = SlotManager::instance();
     $slotObj = $slotMgr->getSlotByShortname($slot);
     $baseUrl = SiteDispatcher::getBaseUrlForLocationCategory($slotObj->getLocationCategory());
     // Mark that we are running
     $query = new UpdateQuery();
     $query->setTable('site_export_queue');
     $query->addValue('pid', strval(getmypid()));
     $query->addWhereEqual('slot', $slot);
     $dbc->query($query);
     // Run the export
     $start = microtime(true);
     try {
         $exportDirname = $slot . "-html";
         $exportDir = $outDir . "/" . $exportDirname;
         $archivePath = $outDir . '/' . $exportDirname . ".zip";
         if (file_exists($exportDir)) {
             $this->deleteRecursive($exportDir);
         }
         mkdir($exportDir);
         if (file_exists($archivePath)) {
             unlink($archivePath);
         }
         // Set the user to be an admin.
         $idMgr = Services::getService("Id");
         $authType = new Type("Authentication", "edu.middlebury.harmoni", "Harmoni DB");
         $_SESSION['__AuthenticatedAgents']['Authentication::edu.middlebury.harmoni::Harmoni DB'] = $idMgr->getId('17008');
         $authZ = Services::getService("AuthZ");
         $isAuthorizedCache = $authZ->getIsAuthorizedCache();
         $isAuthorizedCache->dirtyUser();
         // Close the session. If we don't, a lock on the session file will
         // cause the request initiated via wget to hang.
         session_write_close();
         // Do the export
         $urlParts = parse_url($baseUrl);
         $urlPrefix = rtrim($urlParts['path'], '/');
         $include = array($urlPrefix . '/gui2', $urlPrefix . '/images', $urlPrefix . '/javascript', $urlPrefix . '/polyphony', $urlPrefix . '/repository', $urlPrefix . '/plugin_manager', $urlPrefix . '/rss', $urlPrefix . '/dataport/html/site/' . $slot);
         if (defined('WGET_PATH')) {
             $wget = WGET_PATH;
         } else {
             $wget = 'wget';
         }
         if (defined('WGET_OPTIONS')) {
             $wgetOptions = WGET_OPTIONS;
         } else {
             $wgetOptions = '';
         }
         $command = $wget . " " . $wgetOptions . " -r --page-requisites --html-extension --convert-links --no-directories -e robots=off " . "--directory-prefix=" . escapeshellarg($exportDir . '/content') . " " . "--include=" . escapeshellarg(implode(',', $include)) . " " . "--header=" . escapeshellarg("Cookie: " . session_name() . "=" . session_id()) . " " . escapeshellarg($baseUrl . '/dataport/html/site/' . $slot);
         print "Cookie: " . session_name() . "=" . session_id() . "\n";
         // 			throw new Exception($command);
         exec($command, $output, $exitCode);
         if ($exitCode) {
             throw new Exception('Wget Failed. ' . implode("\n", $output));
         }
         // Copy the main HTML file to index.html
         copy($exportDir . '/content/' . $slot . '.html', $exportDir . '/content/index.html');
         // Copy the index.html file up a level to make it easy to find
         file_put_contents($exportDir . '/index.html', preg_replace('/(src|href)=([\'"])([^\'"\\/]+)([\'"])/', '$1=$2content/$3$4', file_get_contents($exportDir . '/content/index.html')));
         // Zip up the result
         $archive = new ZipArchive();
         if ($archive->open($archivePath, ZIPARCHIVE::CREATE) !== TRUE) {
             throw new Exception("Could not create zip archive.");
         }
         $this->addDirectoryToZip($archive, $exportDir, $exportDirname);
         $archive->close();
         // Remove the directory
         $this->deleteRecursive($exportDir);
         // Mark our success
         $query = new UpdateQuery();
         $query->setTable('site_export_queue');
         $query->addRawValue('pid', 'NULL');
         $query->addValue('status', 'SUCCESS');
         $query->addValue('running_time', strval(round(microtime(true) - $start, 2)));
         $query->addWhereEqual('slot', $slot);
         $dbc->query($query);
     } catch (Exception $e) {
         $this->deleteRecursive($exportDir);
         if (file_exists($archivePath)) {
             unlink($archivePath);
         }
         // Mark our failure
         $query = new UpdateQuery();
         $query->setTable('site_export_queue');
         $query->addRawValue('pid', 'NULL');
         $query->addValue('status', 'EXCEPTION');
         $query->addValue('info', $e->getMessage());
         $query->addValue('running_time', strval(round(microtime(true) - $start, 2)));
         $query->addWhereEqual('slot', $slot);
         $dbc->query($query);
         throw $e;
     }
     exit;
 }
Пример #8
0
 /**
  * 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;
 }
Пример #9
0
 /**
  * Set the media library quota
  * 
  * @param object Integer $quota
  * @return void
  * @access public
  * @since 3/20/08
  */
 public function setMediaQuota(Integer $quota)
 {
     $this->mediaQuota = $quota->value();
     $this->recordInDB();
     $query = new UpdateQuery();
     $query->setTable('segue_slot');
     $query->addWhereEqual('shortname', $this->getShortname());
     $query->addValue('media_quota', strval($this->mediaQuota));
     $dbc = Services::getService('DBHandler');
     $dbc->query($query, IMPORTER_CONNECTION);
 }
Пример #10
0
 /**
  * Make the changes to the database required to go from harmoni-0.11.0 to harmoni-0.12.0.
  * 
  * @param integer $dbIndes
  * @return void
  * @access public
  * @since 9/13/07
  */
 public static function harmoni_0_12_0_update($dbIndex)
 {
     $dbc = Services::getService("DBHandler");
     $tables = $dbc->getTableList($dbIndex);
     $changeTables = array('j_node_node', 'node_ancestry');
     $changeTableStatus = array('j_node_node' => false, 'node_ancestry' => false);
     // Check which tables need to be updated and update if needed.
     foreach ($changeTables as $table) {
         if (in_array($table, $tables)) {
             $result = $dbc->query(new GenericSQLQuery("DESCRIBE " . $table), $dbIndex);
             $result = $result->returnAsSelectQueryResult();
             while ($result->hasNext()) {
                 if ($result->field("Field") == 'fk_hierarchy') {
                     $changeTableStatus[$table] = true;
                     break;
                 }
                 $result->advanceRow();
             }
             if (!$changeTableStatus[$table]) {
                 // Alter the table
                 printpre("Adding column fk_hierarchy to {$table}");
                 $dbc->query(new GenericSQLQuery("ALTER TABLE `" . $table . "` ADD `fk_hierarchy` VARCHAR( 170 ) FIRST ;"), $dbIndex);
             }
         }
     }
     // Select the hierarchy ids and update the table
     if (in_array(false, $changeTableStatus)) {
         // Look up which nodes belong to which hierarchy
         $query = new SelectQuery();
         $query->addTable("node");
         $query->addColumn("node_id");
         $query->addColumn("fk_hierarchy");
         $query->addOrderBy("fk_hierarchy");
         $hierarchies = array();
         $result = $dbc->query($query, $dbIndex);
         while ($result->hasMoreRows()) {
             // Create an array to hold the ids of all nodes in the hierarchy
             if (!isset($hierarchies[$result->field('fk_hierarchy')])) {
                 $hierarchies[$result->field('fk_hierarchy')] = array();
             }
             $hierarchies[$result->field('fk_hierarchy')][] = $result->field('node_id');
             $result->advanceRow();
         }
         $result->free();
         // Update each table's fk_hierarchy
         foreach ($hierarchies as $hierarchyId => $nodeIds) {
             if (!$changeTableStatus['j_node_node']) {
                 $query = new UpdateQuery();
                 $query->addValue('fk_hierarchy', $hierarchyId);
                 $query->setTable('j_node_node');
                 $query->addWhere("fk_child IN ('" . implode("', '", $nodeIds) . "')");
                 $result = $dbc->query($query, $dbIndex);
                 printpre("Updated fk_hierarchy on " . $result->getNumberOfRows() . " rows in j_node_node.");
             }
             if (!$changeTableStatus['j_node_node']) {
                 $query = new UpdateQuery();
                 $query->addValue('fk_hierarchy', $hierarchyId);
                 $query->setTable('node_ancestry');
                 $query->addWhere("fk_node IN ('" . implode("', '", $nodeIds) . "')");
                 $result = $dbc->query($query, $dbIndex);
                 printpre("Updated fk_hierarchy on " . $result->getNumberOfRows() . " rows in node_ancestry.");
             }
         }
         // Alter the table to be NOT NULL
         foreach ($changeTables as $table) {
             if (!$changeTableStatus[$table]) {
                 // Alter the table
                 $dbc->query(new GenericSQLQuery("ALTER TABLE `" . $table . "` CHANGE `fk_hierarchy` `fk_hierarchy`  VARCHAR( 170 ) NOT NULL"), $dbIndex);
                 printpre("Altering column fk_hierarchy in {$table} to be NOT NULL.");
             }
         }
     }
     // Alter the names of the Scheduling columns
     if (in_array('sc_item', $tables)) {
         try {
             $dbc->query(new GenericSQLQuery("ALTER TABLE `sc_item` CHANGE `start` `start_date` BIGINT( 20 ) NULL DEFAULT NULL , CHANGE `end` `end_date` BIGINT( 20 ) NULL DEFAULT NULL "), $dbIndex);
             printpre("Renaming columns start and end to start_date and end_date in the sc_item table.");
         } catch (QueryDatabaseException $e) {
         }
     }
 }
Пример #11
0
 /**
  * Record a visit in the database
  * 
  * @param string $slotname
  * @param string $timestamp
  * @return void
  * @access protected
  * @since 9/22/08
  */
 protected function _recordPastVisit($slotname, $timestamp)
 {
     $dbc = Services::getService('DatabaseManager');
     // First try running an update query, since most will be updates
     $query = new UpdateQuery();
     $query->setTable('segue_accesslog');
     $query->addValue('tstamp', $timestamp);
     $query->addWhereEqual('agent_id', $this->_getCurrentAgentId());
     $query->addWhereEqual('fk_slotname', $slotname);
     $query->addWhereLessThan('tstamp', $timestamp);
     $result = $dbc->query($query, IMPORTER_CONNECTION);
     // If no rows were updated, insert a new one for this user/slot
     if (!$result->getNumberOfRows()) {
         try {
             $query = new InsertQuery();
             $query->setTable('segue_accesslog');
             $query->addValue('tstamp', $timestamp);
             $query->addValue('agent_id', $this->_getCurrentAgentId());
             $query->addValue('fk_slotname', $slotname);
             $dbc->query($query, IMPORTER_CONNECTION);
             // If the update query failed the more recent time where clause,
             // this insert query will fail. That is fine, just ignore.
         } catch (DuplicateKeyDatabaseException $e) {
         }
     }
 }
Пример #12
0
 /**
  * Update the name of this Node. Node name changes are permitted since the
  * Hierarchy's integrity is based on the Node's unique Id.
  * 
  * @param string $displayName
  * 
  * @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}
  * 
  * @access public
  */
 function updateDisplayName($displayName)
 {
     // ** parameter validation
     $stringRule = StringValidatorRule::getRule();
     ArgumentValidator::validate($displayName, $stringRule, true);
     // ** end of parameter validation
     if ($this->_displayName == $displayName) {
         return;
     }
     // nothing to update
     // update the object
     $this->_displayName = $displayName;
     // update the database
     $dbHandler = Services::getService("DatabaseManager");
     $query = new UpdateQuery();
     $query->setTable("az2_node");
     $query->addWhereEqual("id", $this->getId()->getIdString());
     $query->addValue("display_name", $displayName);
     $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex);
     if ($queryResult->getNumberOfRows() == 0) {
         throw new OperationFailedException("No rows updated.");
     }
     if ($queryResult->getNumberOfRows() > 1) {
         throw new OperationFailedException("Too many rows updated, expecting 1.");
     }
 }
Пример #13
0
 /**
  * Update the description for this Hierarchy.
  * 
  * @param string $description
  * 
  * @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}
  * 
  * @access public
  */
 function updateDescription($description)
 {
     // ** parameter validation
     ArgumentValidator::validate($description, StringValidatorRule::getRule(), true);
     // ** end of parameter validation
     if ($this->_description == $description) {
         return;
     }
     // nothing to update
     // update the object
     $this->_description = $description;
     // update the database
     $dbHandler = Services::getService("DatabaseManager");
     $query = new UpdateQuery();
     $query->setTable("hierarchy");
     $query->addWhereEqual('hierarchy_id', $this->getId()->getIdString());
     $query->addValue('hierarchy_description', $description);
     $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex);
     if ($queryResult->getNumberOfRows() == 0) {
         throwError(new Error(HierarchyException::OPERATION_FAILED(), "Hierarchy", true));
     }
     if ($queryResult->getNumberOfRows() > 1) {
         throwError(new Error(HierarchyException::OPERATION_FAILED(), "Hierarchy", true));
     }
 }
Пример #14
0
 /**
  * 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, StringValidatorRule::getRule());
     }
     // Store the name in the object in case its asked for again.
     if (is_null($value)) {
         $this->_name = '';
     } else {
         $this->_name = $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");
         if (is_null($value)) {
             $query->addRawValue("filename", "NULL");
         } else {
             $query->addValue("filename", $this->_name);
         }
         $query->addWhere("id = '" . $this->_recordId->getIdString() . "'");
     } else {
         $query = new InsertQuery();
         $query->setTable("dr_file");
         $query->addValue("id", $this->_recordId->getIdString());
         if (is_null($value)) {
             $query->addRawValue("filename", "NULL");
         } else {
             $query->addValue("filename", $this->_name);
         }
     }
     $result->free();
     // run the query
     $dbHandler->query($query, $this->_configuration->getProperty("database_index"));
     $this->_asset->updateModificationDate();
 }
Пример #15
0
 /**
  * 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";
 }
 /**
  * Confirm an email address
  * 
  * @param object AuthNTokens $email
  * @param string $confirmationCode
  * @return boolean True on success
  * @access public
  * @since 6/4/08
  */
 public function confirmEmail(AuthNTokens $authNTokens, $confirmationCode)
 {
     $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 UpdateQuery();
     $query->setTable($authenticationTable);
     $query->addValue("email_confirmed", "1");
     $query->addWhereEqual($usernameField, $authNTokens->getUsername());
     $query->addWhereEqual('confirmation_code', $confirmationCode);
     $result = $dbc->query($query, $dbId);
     if ($result->getNumberOfRows()) {
         $confirmed = TRUE;
     } else {
         $confirmed = FALSE;
     }
     // Log the success or failure
     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);
         if ($confirmed) {
             $item = new AgentNodeEntryItem("Visitor Registration Confirmed", "Visitor Registration Confirmed: <br/>&nbsp;&nbsp;&nbsp;&nbsp;Name: " . htmlspecialchars($properties->getProperty('name')) . " <br/>&nbsp;&nbsp;&nbsp;&nbsp;Email: " . htmlspecialchars($authNTokens->getIdentifier()));
         } else {
             $priorityType = new Type("logging", "edu.middlebury", "User_Error", "Events that indicate errors in user supplied data.");
             $item = new AgentNodeEntryItem("Visitor Registration Failed", "Visitor Registration email confirmation failed. Confirmation code/email mis-match: <br/>&nbsp;&nbsp;&nbsp;&nbsp;Name: " . htmlspecialchars($properties->getProperty('name')) . " <br/>&nbsp;&nbsp;&nbsp;&nbsp;Email: " . htmlspecialchars($authNTokens->getIdentifier()));
         }
         $log->appendLogWithTypes($item, $formatType, $priorityType);
     }
     return $confirmed;
 }
Пример #17
0
 /**
  * [Re]Set a full path to the file, including the file name.
  * 
  * @param string $path
  * @return null
  * @access public
  * @since 5/6/08
  */
 public function setPath($path)
 {
     $query = new UpdateQuery();
     $query->setTable('segue_site_theme_image');
     $query->addValue('path', $path);
     $query->addWhereEqual('fk_theme', $this->themeId);
     $query->addWhereEqual('path', $this->path);
     $dbMgr = Services::getService("DatabaseManager");
     $result = $dbMgr->query($query, $this->databaseIndex);
     $this->path = $path;
 }
Пример #18
0
 /**
  * the date when this Authorization stops being effective.
  * 
  * @param object DateAndTime $effectiveDate
  * 
  * @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}, {@link
  *		   org.osid.authorization.AuthorizationException#NULL_ARGUMENT
  *		   NULL_ARGUMENT}, {@link
  *		   org.osid.authorization.AuthorizationException#EFFECTIVE_PRECEDE_EXPIRATION}
  * 
  * @access public
  */
 function updateEffectiveDate($effectiveDate)
 {
     if (!$this->isExplicit()) {
         // "Cannot modify an implicit Authorization."
         throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true));
     }
     // ** parameter validation
     ArgumentValidator::validate($effectiveDate, HasMethodsValidatorRule::getRule("asDateAndTime"), true);
     // ** end of parameter validation
     // make sure effective date is before expiration date
     if ($effectiveDate->isGreaterThan($this->_expirationDate)) {
         throwError(new Error(AuthorizationException::EFFECTIVE_PRECEDE_EXPIRATION(), "Authorization", true));
     }
     if ($this->_effectiveDate->isEqualTo($effectiveDate)) {
         return;
     }
     // nothing to update
     // update the object
     $this->_effectiveDate = $effectiveDate;
     // update the database
     $dbHandler = Services::getService("DatabaseManager");
     $query = new UpdateQuery();
     $query->setTable("az2_explicit_az");
     $query->addWhereEqual("id", $this->_id);
     $timestamp = $dbHandler->toDBDate($effectiveDate, $this->_cache->_dbIndex);
     $query->addValue("effective_date", $timestamp);
     $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex);
     if ($queryResult->getNumberOfRows() == 0) {
         throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true));
     }
     if ($queryResult->getNumberOfRows() > 1) {
         throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true));
     }
 }
Пример #19
0
 /**
  * Update the description
  * 
  * @param string $description
  * @return null
  * @access public
  * @since 5/15/08
  */
 public function updateDescription($description)
 {
     if (!$this->canModify()) {
         throw new PermissionDeniedException();
     }
     $this->description = $description;
     $query = new UpdateQuery();
     $query->setTable('segue_site_theme');
     $query->addValue('description', $description);
     $query->addWhereEqual('id', $this->id);
     $dbc = Services::getService('DatabaseManager');
     $dbc->query($query, $this->databaseIndex);
 }
Пример #20
0
 /**
  * Persistantly store a user preference
  * 
  * @param string $key
  * @param string $val
  * @return void
  * @access protected
  * @since 9/16/08
  */
 protected function _storePref($key, $val)
 {
     // Do not persist preferences for anonymous.
     if ($this->_getCurrentAgentId() == 'edu.middlebury.agents.anonymous') {
         return;
     }
     if ($this->_fetchPref($key) == $val) {
         return;
     }
     if (is_null($this->_fetchPref($key))) {
         $query = new InsertQuery();
         $query->addValue('agent_id', $this->_getCurrentAgentId());
         $query->addValue('pref_key', $key);
     } else {
         $query = new UpdateQuery();
         $query->addWhereEqual('agent_id', $this->_getCurrentAgentId());
         $query->addWhereEqual('pref_key', $key);
     }
     $query->setTable('user_prefs');
     $query->addValue('pref_val', $val);
     $dbc = Services::getService('DatabaseManager');
     try {
         $dbc->query($query);
     } catch (DuplicateKeyDatabaseException $e) {
         // If we have another window open that alreay changed the preference,
         // try again.
         unset($_SESSION['harmoni_user_prefs_persistant']);
         $this->_storePref($key, $val);
     }
     $_SESSION['harmoni_user_prefs_persistant'][$key] = $val;
 }