/** * Stores the configuration. Calls the parent configuration first, * then does additional operations. * * @param object Properties $configuration * @return object * @access public * @since 3/24/05 */ function assignConfiguration(Properties $configuration) { // Set the configuration values to our custom values. $configuration->addProperty('authentication_table', 'auth_visitor'); $configuration->addProperty('username_field', 'email'); $configuration->addProperty('password_field', 'password'); $propertiesFields = array('name' => 'display_name', 'email' => 'email'); $configuration->addProperty('properties_fields', $propertiesFields); try { ArgumentValidator::validate($configuration->getProperty('email_from_name'), NonzeroLengthStringValidatorRule::getRule()); } catch (InvalidArgumentException $e) { throw new ConfigurationErrorException("'email_from_name' must be a string. " . $e->getMessage()); } try { ArgumentValidator::validate($configuration->getProperty('email_from_address'), RegexValidatorRule::getRule('/^.+@.+$/')); } catch (InvalidArgumentException $e) { throw new ConfigurationErrorException("'email_from_address' must be an email address. " . $e->getMessage()); } try { ArgumentValidator::validate($configuration->getProperty('domain_blacklist'), OptionalRule::getRule(ArrayValidatorRuleWithRule::getRule(NonzeroLengthStringValidatorRule::getRule()))); ArgumentValidator::validate($configuration->getProperty('domain_whitelist'), OptionalRule::getRule(ArrayValidatorRuleWithRule::getRule(NonzeroLengthStringValidatorRule::getRule()))); } catch (InvalidArgumentException $e) { throw new ConfigurationErrorException("'domain_blacklist' and 'domain_whitelist' if specified must be arrays of domain name strings. " . $e->getMessage()); } parent::assignConfiguration($configuration); }
/** * Add a user agent string and an array of matching codes. If the user agent * matches the string and the code or exception class is in the list, the exception * will not be logged. This can be used to prevent misbehaving bots and web * crawlers from filling the logs with repeated invalid requests. * * @param string $userAgent * @param optional array $codesOrExceptionClasses If empty, no matches to the user agent will be logged. * @return void * @access public * @since 2/26/08 */ public function addUserAgentFilter($userAgent, $codesOrExceptionClasses = array()) { $userAgent = trim($userAgent); ArgumentValidator::validate($userAgent, NonzeroLengthStringValidatorRule::getRule()); ArgumentValidator::validate($codesOrExceptionClasses, ArrayValidatorRuleWithRule::getRule(OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), IntegerValidatorRule::getRule()))); $this->userAgentFilters[$userAgent] = $codesOrExceptionClasses; }
/** * Stores the configuration. Calls the parent configuration first, * then does additional operations. * * @param object Properties $configuration * @return object * @access public * @since 3/24/05 */ function assignConfiguration(Properties $configuration) { parent::assignConfiguration($configuration); $this->_connector = new LDAPConnector($configuration); $this->_configuration->addProperty('connector', $this->_connector); // Validate the configuration options we use: ArgumentValidator::validate($this->_configuration->getProperty('properties_fields'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); }
/** * Constructor, Adds some additional functionality to that of the parent's * constructor * * @param object Properties $configuration * @return object * @access public * @since 3/4/05 */ function LDAPAuthNTokens($configuration) { $par = get_parent_class($this); parent::$par($configuration); $this->_connector = $configuration->getProperty('connector'); // Validate the configuration options we use: ArgumentValidator::validate($this->_configuration->getProperty('login_fields'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); }
/** * Stores the configuration. Calls the parent configuration first, * then does additional operations. * * @param object Properties $configuration * @return object * @access public * @since 3/24/05 */ function assignConfiguration(Properties $configuration) { parent::assignConfiguration($configuration); // Validate the configuration options we use: ArgumentValidator::validate($this->_configuration->getProperty('properties_fields'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); ArgumentValidator::validate($this->_configuration->getProperty('database_id'), IntegerValidatorRule::getRule()); ArgumentValidator::validate($this->_configuration->getProperty('authentication_table'), StringValidatorRule::getRule()); ArgumentValidator::validate($this->_configuration->getProperty('username_field'), StringValidatorRule::getRule()); ArgumentValidator::validate($this->_configuration->getProperty('password_field'), StringValidatorRule::getRule()); ArgumentValidator::validate($this->_configuration->getProperty('allow_token_addition'), OptionalRule::getRule(BooleanValidatorRule::getRule())); ArgumentValidator::validate($this->_configuration->getProperty('allow_token_deletion'), OptionalRule::getRule(BooleanValidatorRule::getRule())); ArgumentValidator::validate($this->_configuration->getProperty('allow_token_updates'), OptionalRule::getRule(BooleanValidatorRule::getRule())); ArgumentValidator::validate($this->_configuration->getProperty('allow_property_updates'), OptionalRule::getRule(BooleanValidatorRule::getRule())); }
/** * Create wizard steps for editing the values of the specified Record and * add them to the wizard. * * @param object $record * @param object $wizard The wizard to add the steps to. * @param array $partStructures An ordered array of the partStructures to include. * @return void * @access public * @since 10/19/04 */ function createWizardStepsForPartStructures(Record $record, Wizard $wizard, array $partStructures) { ArgumentValidator::validate($partStructures, ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule("PartStructure"))); $recordStructure = $record->getRecordStructure(); $recordStructureId = $recordStructure->getId(); /* build an interface for editing this record! */ $m = ''; $step = $wizard->addStep("record", new WizardStep()); $step->setDisplayName(dgettext("polyphony", "Edit Record")); // Go through each of the PartStructures and create a component for it foreach (array_keys($partStructures) as $key) { $partStructure = $partStructures[$key]; $m .= $this->_addComponentForPartStructure($step, $record, $partStructure); $m .= "<br/>"; } $step->setContent($m); }
/** * Constructor */ function HarmoniAsset(RepositoryManager $manager, Hierarchy $hierarchy, Repository $repository, Id $id, ConfigurationProperties $configuration) { // Get the node coresponding to our id $this->manager = $manager; $this->_hierarchy = $hierarchy; $this->_node = $this->_hierarchy->getNode($id); $this->_repository = $repository; $this->_recordIDs = array(); $this->_createdRecords = array(); $this->_createdRecordStructures = array(); // Store our configuration $this->_configuration = $configuration; $this->_versionControlAll = $configuration->getProperty('version_control_all') ? TRUE : FALSE; if (is_array($configuration->getProperty('version_control_types'))) { ArgumentValidator::validate($configuration->getProperty('version_control_types'), ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule("Type"))); $this->_versionControlTypes = $configuration->getProperty('version_control_types'); } else { $this->_versionControlTypes = array(); } $this->_dbIndex = $configuration->getProperty('database_index'); }
/** * Constructor * * @param object $iterator The iterator to print. * @param integer $numColumns The number of result columns to print on each page. * @param integer $numResultsPerPage The number of iterator items to print on a page. * @param mixed $callbackFunction The name of the function that will be called to * to print each result. If null, the first parameter is assumed to be an * array of gui components that can be rendered without further processing. * @param optional mixed $callbackArgs Any additional arguements will be stored * and passed on to the callback function. * @access public * @date 8/5/04 */ function ArrayResultPrinter($array, $numColumns, $numResultsPerPage, $callbackFunction = NULL) { ArgumentValidator::validate($array, ArrayValidatorRule::getRule()); ArgumentValidator::validate($numColumns, IntegerValidatorRule::getRule()); ArgumentValidator::validate($numResultsPerPage, IntegerValidatorRule::getRule()); // ArgumentValidator::validate($callbackFunction, StringValidatorRule::getRule()); if (is_null($callbackFunction)) { ArgumentValidator::validate($array, ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule("ComponentInterface"))); } $this->_array = $array; $this->_numColumns = $numColumns; $this->_pageSize = $numResultsPerPage; $this->_callbackFunction = $callbackFunction; $this->_callbackParams = array(); $args = func_get_args(); for ($i = 4; $i < count($args); $i++) { $this->_callbackParams[] = $args[$i]; } $this->_resultLayout = new TableLayout($this->_numColumns); $this->_resultLayout->printEmptyCells = false; $this->_linksStyleCollection = new StyleCollection("*.result_page_links", "result_page_links", "Result Page Links", "Links to other pages of results."); // $this->_linksStyleCollection->addSP(new MarginTopSP("10px")); }
/** * Assign the configuration of this Manager. Valid configuration options are as * follows: * * thumbnail_format string (ex: 'image/jpeg') * * use_gd boolean I * gd_formats array of strings (ex: array('image/jpeg', 'image/png')) * An empty array indicates any/all supported formats. * * use_imagemagick boolean * * imagemagick_path string (ex: 'usr/bin' OR '/usr/X11R6/bin') * * imagemagick_temp_dir string (ex: '/tmp') * * imagemagick_formats array of strings (ex: array('image/jpeg', 'image/png')) * An empty array indicates any/all supported formats. * * @param object Properties $configuration (original type: java.util.Properties) * * @throws object OsidException An exception with one of the following * messages defined in org.osid.OsidException: {@link * org.osid.OsidException#OPERATION_FAILED OPERATION_FAILED}, * {@link org.osid.OsidException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.OsidException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.OsidException#UNIMPLEMENTED UNIMPLEMENTED}, {@link * org.osid.OsidException#NULL_ARGUMENT NULL_ARGUMENT} * * @access public */ function assignConfiguration(Properties $configuration) { $this->_configuration = $configuration; ArgumentValidator::validate($configuration->getProperty('thumbnail_format'), StringValidatorRule::getRule()); ArgumentValidator::validate($configuration->getProperty('use_gd'), BooleanValidatorRule::getRule()); ArgumentValidator::validate($configuration->getProperty('gd_formats'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); ArgumentValidator::validate($configuration->getProperty('use_imagemagick'), BooleanValidatorRule::getRule()); ArgumentValidator::validate($configuration->getProperty('imagemagick_path'), StringValidatorRule::getRule()); ArgumentValidator::validate($configuration->getProperty('imagemagick_temp_dir'), StringValidatorRule::getRule()); ArgumentValidator::validate($configuration->getProperty('imagemagick_formats'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); $this->_thumbnailFormat = $configuration->getProperty('thumbnail_format'); $this->_useGD = $configuration->getProperty('use_gd'); $this->_gdFormats = $configuration->getProperty('gd_formats'); $this->_useImageMagick = $configuration->getProperty('use_imagemagick'); $this->_ImageMagickPath = $configuration->getProperty('imagemagick_path'); $this->_ImageMagickTempDir = $configuration->getProperty('imagemagick_temp_dir'); $this->_ImageMagickFormats = $configuration->getProperty('imagemagick_formats'); if ($this->_useGD) { $this->_gdProcessor = new GDProcessor($configuration->getProperty('thumbnail_format')); } if ($this->_useImageMagick) { $this->_ImageMagickProcessor = new ImageMagickProcessor($configuration->getProperty('thumbnail_format'), $this->_ImageMagickPath, $this->_ImageMagickTempDir); } }
/** * Constructor -- sets up the allowed fields for this kind of {@link DataContainer} * * @see DataContainer * @access public * @return void */ function HarmoniConfig() { // initialize the data container $this->init(); // add the fields we want to allow $message = "HarmoniConfig - the option 'defaultAction' must be set to a string value!"; $type = "Harmoni"; $this->add("defaultAction", StringValidatorRule::getRule(), $message, $type); $this->add("defaultAction", FieldRequiredValidatorRule::getRule(), $message, $type); unset($message, $type); $message = "HarmoniConfig - the option 'defaultModule' must be set to a string value!"; $type = "Harmoni"; $this->add("defaultModule", StringValidatorRule::getRule(), $message, $type); $this->add("defaultModule", FieldRequiredValidatorRule::getRule(), $message, $type); $message = "HarmoniConfig - if specified, the option 'defaultParams' must be set to a an array of string values!"; $this->add("defaultParams", OptionalRule::getRule(ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())), $message, $type); $this->add("programTitle", StringValidatorRule::getRule(), $message, $type); $this->add("sessionName", FieldRequiredValidatorRule::getRule()); $this->set("sessionName", "Harmoni"); $this->add("sessionUseCookies", BooleanValidatorRule::getRule()); $this->set("sessionUseCookies", true); $this->add("sessionUseOnlyCookies", BooleanValidatorRule::getRule()); $this->set("sessionUseOnlyCookies", true); $this->add("sessionCookiePath", FieldRequiredValidatorRule::getRule()); $this->set("sessionCookiePath", "/"); $this->add("sessionCookieDomain", StringValidatorRule::getRule(), "HarmoniConfig - You must set the 'sessionDomain' to the DNS domain you would like your session cookie sent to! (eg, '.mydomain.com')", "Harmoni"); $this->set("sessionCookieDomain", ""); // default // An array of module.action in which session ids are allowed to be passed in the // url $this->add("sessionInUrlActions", OptionalRule::getRule(ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())), $message, $type); $this->add("sessionCookiesSecure", BooleanValidatorRule::getRule()); $this->set("sessionCookiesSecure", false); $this->add("sessionCookiesHttpOnly", BooleanValidatorRule::getRule()); $this->set("sessionCookiesHttpOnly", true); }
/** * Set a list of disabled templates * * @param array $orderedIdStrings * @return void * @access public * @since 6/12/08 */ public function setDisabled(array $idStrings) { ArgumentValidator::validate($idStrings, ArrayValidatorRuleWithRule::getRule(NonzeroLengthStringValidatorRule::getRule())); $this->disabled = $idStrings; }
/** * 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"; }
/** * Fetches and returns an array of DMRecord IDs from the database in one Query. * @return ref array Indexed by DMRecord ID, values are {@link DMRecord}s. * @param array $IDs * @param optional int $mode Specifies the mode the record should be fetched. * @param optional object $limitResults NOT YET IMPLEMENTED * criteria. If not specified, will fetch all IDs. */ function fetchRecords($IDs, $mode = RECORD_CURRENT, $limitResults = null) { ArgumentValidator::validate($IDs, ArrayValidatorRuleWithRule::getRule(OrValidatorRule::getRule(StringValidatorRule::getRule(), IntegerValidatorRule::getRule()))); ArgumentValidator::validate($mode, IntegerValidatorRule::getRule()); $IDs = array_unique($IDs); // let's weed out those IDs that we can take from cache $fromCacheIDs = array(); $fromDBIDs = array(); if (count($this->_recordCache)) { foreach ($IDs as $id) { // only take from the cache if we have it cached, AND // what is cached is fetched at a higher/equal data-mode than what's requested if (isset($this->_recordCache[$id]) && $this->_recordCache[$id]->getFetchMode() >= $mode) { $fromCacheIDs[] = $id; } else { $fromDBIDs[] = $id; } } } else { $fromDBIDs = $IDs; } $records = array(); // put all the records from the cache into the array foreach ($IDs as $id) { if (isset($this->_recordCache[$id])) { $records[$id] = $this->_recordCache[$id]; } } if (count($fromDBIDs)) { // first, make the new query $query = new SelectQuery(); $this->_setupSelectQuery($query, $mode); // and now, go through the records we already have cached but are fetching more information for, // and make sure that we don't fetch information for fields that are already fetched. $alreadyFetchedFields = array(); // and, build the WHERE clause while we're at it. $t = array(); foreach ($fromDBIDs as $id) { $t[] = "dm_record.id='" . addslashes($id) . "'"; if (isset($this->_recordCache[$id])) { $alreadyFetchedFields = array_unique(array_merge($alreadyFetchedFields, $this->_recordCache[$id]->getFetchedFieldIDs())); } } $query->addWhere("(" . implode(" OR ", $t) . ")"); if (count($alreadyFetchedFields)) { $temp = array(); foreach ($alreadyFetchedFields as $id) { $temp[] = "dm_record_field.id != '" . addslashes($id) . "'"; } $query->addWhere('(' . implode(" AND ", $temp) . ')'); } $dbHandler = Services::getService("DatabaseManager"); // print "<PRE>" . MySQL_SQLGenerator::generateSQLQuery($query)."</PRE>"; $result = $dbHandler->query($query, DATAMANAGER_DBID); if (!$result) { throwError(new UnknownDBError("RecordManager")); } // now, we need to parse things out and distribute the lines accordingly while ($result->hasMoreRows()) { $a = $result->getCurrentRow(); $result->advanceRow(); $id = $a['record_id']; $type = $a['fk_schema']; $vcontrol = $a['record_ver_control']; if (!isset($records[$id])) { $schemaManager = Services::getService("SchemaManager"); $schema = $schemaManager->getSchemaByID($type); $schema->load(); $records[$id] = new DMRecord($schema, $vcontrol ? true : false, $mode); if ($this->_cacheMode) { $this->_recordCache[$id] = $records[$id]; } } $records[$id]->takeRow($a); unset($a); } $result->free(); } // make sure we found the data sets $rule = ExtendsValidatorRule::getRule("DMRecord"); foreach ($IDs as $id) { if (!isset($records[$id]) || !$rule->check($records[$id])) { throw new UnknownIdException("DMRecord {$id} was requested, but not found."); } // and set the fetch mode. $records[$id]->setFetchMode($mode); // print "<pre>";print_r($records[$id]);print "</pre>"; } return $records; }
/** * Answer all the items with this tag that match a particular list * * @param array $items An array of TaggedItem objects * @return object TaggedItemIterator * @access public * @since 4/9/08 */ public function getItemsInList(array $items) { ArgumentValidator::validate($items, ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule('TaggedItem'))); if (!count($items)) { return new HarmoniIterator(array()); } $id = array(); $system = $items[0]->getSystem(); foreach ($items as $item) { if ($system != $item->getSystem()) { throw new Exception("getItemsInList() currently only supports items from the same system. If needed, this method should be updated."); } $ids[] = $item->getId(); } return new HarmoniIterator($ids); }
/** * Auxilliary private function that returns Authorizations according to a * criteria. Null values are interpreted as wildmarks. Warning: $returnExplicitOnly = false * will increase the running time significantly - USE SPARINGLY! * @access public * @param string aId The string id of an agent. * @param string fId The string id of a function. * @param string qId The string id of a qualifier. This parameter can not be null * and used as a wildmark. * @param object fType The type of a function. * @param boolean returnExplicitOnly If True, only explicit Authorizations * will be returned. * @param boolean isActiveNow If True, only active Authorizations will be returned. * @return array **/ function getAZs($aId, $fId, $qId, $fType, $returnExplicitOnly, $isActiveNow, $groupIds = array()) { // printpre (func_get_args()); // ** parameter validation $rule = StringValidatorRule::getRule(); ArgumentValidator::validate($groupIds, ArrayValidatorRuleWithRule::getRule(OptionalRule::getRule($rule)), true); ArgumentValidator::validate($aId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($fId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($qId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($fType, OptionalRule::getRule(ExtendsValidatorRule::getRule("Type")), true); ArgumentValidator::validate($returnExplicitOnly, BooleanValidatorRule::getRule(), true); ArgumentValidator::validate($isActiveNow, BooleanValidatorRule::getRule(), true); // ** end of parameter validation $idManager = Services::getService("Id"); // the parameter that influences the result most is $returnExplicitOnly // 1) If $returnExplicitOnly is TRUE, then we only need to check for Authorizations // that have been explicitly created, i.e. no need to look for inherited // authorizations // 2) If $returnExplicitOnly is FALSE, then we need to include inherited Authorizations // as well. // Agents/Groups if (isset($aId)) { $agentIds = array($aId); } else { $agentIds = array(); } $allAgentIds = array_merge($agentIds, $groupIds); $explicitQueryResult = $this->getExplicitAZQueryResult($allAgentIds, $fId, $qId, $fType, $isActiveNow); if ($returnExplicitOnly) { return $this->getAuthorizationsFromQueryResult($explicitQueryResult, $aId, $qId, $returnExplicitOnly); } else { $implicitQueryResult = $this->getImplicitAZQueryResult($allAgentIds, $fId, $qId, $fType, $isActiveNow); return array_merge($this->getAuthorizationsFromQueryResult($explicitQueryResult, $aId, $qId, $returnExplicitOnly), $this->getAuthorizationsFromQueryResult($implicitQueryResult, $aId, $qId, $returnExplicitOnly)); } }
/** * Sets the action to call after the browser-requested action has executed but before the output from that action is processed. The result from the previous action can be accessed as Harmoni::result. * @param string $action A dotted-pair action (module.action) to use for post processing. * @param optional array $ignore An array of dotted-pair actions for which we will NOT execute the post-process action. * @access public * @return void */ function setPostProcessAction($action, $ignore = null) { $rule1 = DottedPairValidatorRule::getRule(); $rule2 = ArrayValidatorRuleWithRule::getRule($rule1); ArgumentValidator::validate($action, $rule1); if ($ignore) { ArgumentValidator::validate($ignore, $rule2); } $this->_postProcessIgnoreList = $ignore ? $ignore : array(); $this->_postProcessAction = $action; }
/** * Set a list of actions that require request tokens to prevent Cross-Site Request Forgery * attacks. All actions that could potentially change data should require this. * * Actions in this list will not be able to be loaded directly. * * @param array $actions An array of module.action strings. '*' wildcards are allowed. * @return void * @access public * @since 8/14/08 */ public function addRequestTokenRequiredActions($actions) { ArgumentValidator::validate($actions, ArrayValidatorRuleWithRule::getRule(DottedPairValidatorRule::getRule())); $this->_tokenRequiredActions = array_merge($this->_tokenRequiredActions, $actions); }
/** * Assign the configuration of this Manager. Valid configuration options are as * follows: * token_collectors (array) An array in which the keys are the serialized * Type objects that correspond to * AuthenticationTypes and the values are the * TokenCollector objects to be used fot that * AuthenticationType. * * @param object Properties $configuration (original type: java.util.Properties) * * @throws object OsidException An exception with one of the following * messages defined in org.osid.OsidException: {@link * org.osid.OsidException#OPERATION_FAILED OPERATION_FAILED}, * {@link org.osid.OsidException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.OsidException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.OsidException#UNIMPLEMENTED UNIMPLEMENTED}, {@link * org.osid.OsidException#NULL_ARGUMENT NULL_ARGUMENT} * * @access public */ function assignConfiguration(Properties $configuration) { $this->_configuration = $configuration; $configKeys = $this->_configuration->getKeys(); while ($configKeys->hasNextObject()) { $key = $configKeys->nextObject(); if ($key == 'token_collectors') { $tokenCollectors = $this->_configuration->getProperty('token_collectors'); ArgumentValidator::validate($tokenCollectors, ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule("TokenCollector"))); foreach (array_keys($tokenCollectors) as $key) { $authType = unserialize($key); $authTypeString = $this->_getTypeString($authType); $this->_tokenCollectors[$authTypeString] = $tokenCollectors[$key]; } } } }
/** * Ask the role to store a list of agent Ids which caused the role to exist. * This should be used only by the SegueRoleManager. It is intended to be a * temparary store which may or may not be populated when roles are returned. * * @param array $agentIds * @return void * @access public * @since 11/28/07 */ public function setAgentsCausing(array $agentIds) { ArgumentValidator::validate($agentIds, ArrayValidatorRuleWithRule::getRule(ExtendsValidatorRule::getRule("Id"))); $idStrings = array(); $this->agentsCausing = array(); foreach ($agentIds as $id) { if (!in_array($id->getIdString(), $idStrings)) { $this->agentsCausing[] = $id; $idStrings[] = $id->getIdString(); } } }
/** * Answer an XHTML 'diff' that compares two arrays of strings. * Normal usage would be to explode blocks of text on "\n" to allow a line-by-line * comparison. * * @param array $oldStrings * @param array $newStrings * @return string * @access public * @since 1/7/08 */ public function getDiff($oldStrings, $newStrings) { $rule = ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule()); ArgumentValidator::validate($oldStrings, $rule); ArgumentValidator::validate($newStrings, $rule); $formatter = new SegueTableDiffFormatter(); $diff = new Diff($oldStrings, $newStrings); return $formatter->format($diff); }
/** * Auxilliary private function that returns Authorizations according to a * criteria. Null values are interpreted as wildmarks. Warning: $returnExplicitOnly = false * will increase the running time significantly - USE SPARINGLY! * @access public * @param string aId The string id of an agent. * @param string fId The string id of a function. * @param string qId The string id of a qualifier. This parameter can not be null * and used as a wildmark. * @param object fType The type of a function. * @param boolean returnExplicitOnly If True, only explicit Authorizations * will be returned. * @param boolean searchUp If true, the ancester nodes of the qualifier will * be checked as well * @param boolean isActiveNow If True, only active Authorizations will be returned. * @return ref object An AuthorizationIterator. **/ function getAZs($aId, $fId, $qId, $fType, $returnExplicitOnly, $searchUp, $isActiveNow, $groupIds = array()) { // printpre (func_get_args()); // ** parameter validation $rule = StringValidatorRule::getRule(); ArgumentValidator::validate($groupIds, ArrayValidatorRuleWithRule::getRule(OptionalRule::getRule($rule)), true); ArgumentValidator::validate($aId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($fId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($qId, OptionalRule::getRule($rule), true); ArgumentValidator::validate($fType, OptionalRule::getRule(ExtendsValidatorRule::getRule("Type")), true); ArgumentValidator::validate($returnExplicitOnly, BooleanValidatorRule::getRule(), true); ArgumentValidator::validate($isActiveNow, BooleanValidatorRule::getRule(), true); // ** end of parameter validation $idManager = Services::getService("Id"); // the parameter that influences the result most is $returnExplicitOnly // 1) If $returnExplicitOnly is TRUE, then we only need to check for Authorizations // that have been explicitly created, i.e. no need to look for inherited // authorizations // 2) If $returnExplicitOnly is FALSE, then we need to include inherited Authorizations // as well. // this array will store the ids of all qualifiers to be checked for authorizations $qualifiers = array(); // check all ancestors of given qualifier $hierarchyManager = Services::getService("Hierarchy"); if (isset($qId)) { $qualifierId = $idManager->getId($qId); $node = $hierarchyManager->getNode($qualifierId); $hierarchy = $hierarchyManager->getHierarchyForNode($node); if ($searchUp) { // these are the ancestor nodes $nodes = $hierarchy->traverse($qualifierId, Hierarchy::TRAVERSE_MODE_DEPTH_FIRST, Hierarchy::TRAVERSE_DIRECTION_UP, Hierarchy::TRAVERSE_LEVELS_ALL); // now get the id of each node and store in array while ($nodes->hasNext()) { $info = $nodes->next(); $id = $info->getNodeId(); $qualifiers[] = $id->getIdString(); } } else { $qualifiers = array($qId); } } // print_r($qualifiers); // setup the query $dbHandler = Services::getService("DatabaseManager"); $query = new SelectQuery(); $query->addColumn("authorization_id", "id"); $query->addColumn("fk_agent", "aid"); $query->addColumn("fk_function", "fid"); $query->addColumn("fk_qualifier", "qid"); $query->addColumn("authorization_effective_date", "eff_date"); $query->addColumn("authorization_expiration_date", "exp_date"); $query->addTable("az_authorization"); // now include criteria // the qualifiers criteria if (isset($qualifiers) && count($qualifiers)) { $query->addWhereIn('az_authorization.fk_qualifier', $qualifiers); } // Agents/Groups if (isset($aId)) { $agentIds = array($aId); } else { $agentIds = array(); } $allAgentIds = array_merge($agentIds, $groupIds); // the agent criteria if (count($allAgentIds)) { $query->addWhereIn('az_authorization.fk_agent', $allAgentIds); } // the function criteria if (isset($fId)) { $joinc = "az_authorization.fk_function = az_function.function_id"; $query->addTable("az_function", INNER_JOIN, $joinc); $query->addWhereEqual("az_authorization.fk_function", $fId); } // the function type criteria if (isset($fType)) { // do not join with az_function if we did already if (!isset($fId)) { $joinc = "az_authorization.fk_function = az_function.function_id"; $query->addTable("az_function", INNER_JOIN, $joinc); } // now join with type $joinc = "az_function.fk_type = type.type_id"; $query->addTable("type", INNER_JOIN, $joinc); $query->addWhereEqual("type.type_domain", $fType->getDomain()); $query->addWhereEqual("type.type_authority", $fType->getAuthority()); $query->addWhereEqual("type.type_keyword", $fType->getKeyword()); } // the isActiveNow criteria if ($isActiveNow) { $where = "(authorization_effective_date IS NULL OR (NOW() >= authorization_effective_date))"; $query->addWhere($where); $where = "(authorization_expiration_date IS NULL OR (NOW() < authorization_expiration_date))"; $query->addWhere($where); } $query->addOrderBy("authorization_id"); // echo "<pre>\n"; // echo MySQL_SQLGenerator::generateSQLQuery($query); // echo "</pre>\n"; $queryResult = $dbHandler->query($query, $this->_dbIndex); // this array will store the authorizations that will be returned $authorizations = array(); // we only want to create one implicitAZ for a given Agent/Function/Qualifier // combo, so maintain a list of already created ones to skip $createdImplicitAZs = array(); $i = 0; // process all rows and create the explicit authorizations while ($queryResult->hasMoreRows()) { $row = $queryResult->getCurrentRow(); // printpre($row); $idValue = $row['id']; $id = $idManager->getId($idValue); if (isset($this->_authorizations[$idValue])) { $authorization = $this->_authorizations[$idValue]; } else { $agentId = $idManager->getId($row['aid']); $functionId = $idManager->getId($row['fid']); $explicitQualifierId = $idManager->getId($row['qid']); $effectiveDate = $dbHandler->fromDBDate($row['eff_date'], $this->_dbIndex); $expirationDate = $dbHandler->fromDBDate($row['exp_date'], $this->_dbIndex); // create the explicit authorization (each explicit authorization // has a corresponding row in the authorization db table) $authorization = new HarmoniAuthorization($idValue, $agentId, $functionId, $explicitQualifierId, true, $this, $effectiveDate, $expirationDate); $this->_authorizations[$idValue] = $authorization; } // Explicit AZ for ancestor qualifiers and groups should have // corresponding implicit AZs // in decendents, but not appear in their AZs directly. // Therefore, only add the explicit AZ if it is for the requested // qualifier and agent if we are fetching more than just the explicitAZs. if ($row['qid'] == $qId && $row['aid'] == $aId || $returnExplicitOnly) { $authorizations[] = $authorization; } // now create the implicit authorizations // the implicit authorizations will be created for all nodes // on the hierarchy path(s) between the node with the explicit authorization // and the node on which getAZs() was called. // If the row's qualifier and agent are what we asked for however, // then the AZ is explicit and doesn't need an implicit AZ as well. if ((!$returnExplicitOnly || $searchUp) && ($row['qid'] != $qId || $aId && $row['aid'] != $aId)) { // printpre("Building Implicit AZs..."); // var_dump($returnExplicitOnly); // var_dump($searchUp); // if this is an AZ that is implicit because of a group instead // of because of the hierarchy, create it. if ($row['qid'] == $qId && $row['aid'] != $aId) { // printpre("In first clause (AuthorizationCache)"); $qualifierId = $idManager->getId($qId); // If we are getting implicit AZs for a given agent, make sure // that the implicit AZ has their Id. if ($aId) { $agentId = $idManager->getId($aId); } else { $agentId = $authorization->getAgentId(); } $function = $authorization->getFunction(); $functionId = $function->getId(); $effectiveDate = $authorization->getEffectiveDate(); $expirationDate = $authorization->getExpirationDate(); $implicit = new HarmoniAuthorization(null, $agentId, $functionId, $qualifierId, false, $this, $effectiveDate, $expirationDate); $azHash = $agentId->getIdString() . "::" . $functionId->getIdString() . "::" . $qualifierId->getIdString(); if (!in_array($azHash, $createdImplicitAZs)) { $authorizations[] = $implicit; $createdImplicitAZs[] = $azHash; } } else { if (!$returnExplicitOnly && $qId) { // printpre("In second clause (AuthorizationCache)"); // If we are getting implicit AZs for a given agent, make sure // that the implicit AZ has their Id. if ($aId) { $agentId = $idManager->getId($aId); } else { $agentId = $authorization->getAgentId(); } $function = $authorization->getFunction(); $functionId = $function->getId(); $effectiveDate = $authorization->getEffectiveDate(); $expirationDate = $authorization->getExpirationDate(); $implicitQualifierId = $idManager->getId($qId); $implicit = new HarmoniAuthorization(null, $agentId, $functionId, $implicitQualifierId, false, $this, $effectiveDate, $expirationDate); $azHash = $agentId->getIdString() . "::" . $functionId->getIdString() . "::" . $implicitQualifierId->getIdString(); if (!in_array($azHash, $createdImplicitAZs)) { $authorizations[] = $implicit; $createdImplicitAZs[] = $azHash; } } else { if (!$returnExplicitOnly) { printpre($row); printpre("In third clause (AuthorizationCache)"); $explicitQualifier = $authorization->getQualifier(); $explicitQualifierId = $explicitQualifier->getId(); // If we are getting implicit AZs for a given agent, make sure // that the implicit AZ has their Id. if ($aId) { $agentId = $idManager->getId($aId); } else { $agentId = $authorization->getAgentId(); } $function = $authorization->getFunction(); $functionId = $function->getId(); $effectiveDate = $authorization->getEffectiveDate(); $expirationDate = $authorization->getExpirationDate(); // this is set 2 $authZManager = Services::getService("AuthZ"); $hierarchies = $authZManager->getQualifierHierarchies(); while ($hierarchies->hasNext()) { $hierarchyId = $hierarchies->next(); $hierarchy = $hierarchyManager->getHierarchy($hierarchyId); $timer = new Timer(); $timer->start(); $nodes = $hierarchy->traverse($explicitQualifierId, Hierarchy::TRAVERSE_MODE_DEPTH_FIRST, Hierarchy::TRAVERSE_DIRECTION_DOWN, Hierarchy::TRAVERSE_LEVELS_ALL); $timer->end(); printf("LoadAZTime: %1.6f <br/>", $timer->printTime()); // now get the id of each node and store in array $set2 = array(); // skip the first node $nodes->next(); while ($nodes->hasNext()) { $info = $nodes->next(); $nodeId = $info->getNodeId(); $implicit = new HarmoniAuthorization(null, $agentId, $functionId, $nodeId, false, $this, $effectiveDate, $expirationDate); $azHash = $agentId->getIdString() . "::" . $functionId->getIdString() . "::" . $nodeId->getIdString(); // printpre($azHash); // Weird bugs were happening, with $createdImplicitAZs // but I can't figure out what is going on. if (!in_array($azHash, $createdImplicitAZs)) { $authorizations[] = $implicit; // $createdImplicitAZs[] = $azHash; } } } } } } } $queryResult->advanceRow(); } $queryResult->free(); return $authorizations; }
/** * Stores the configuration. Calls the parent configuration first, * then does additional operations. * * @param object Properties $configuration * @return object * @access public * @since 3/24/05 */ function assignConfiguration(Properties $configuration) { parent::assignConfiguration($configuration); $format = $configuration->getProperty('DISPLAY_NAME_FORMAT'); ArgumentValidator::validate($format, RegexValidatorRule::getRule('/\\[\\[([^]]+)\\]\\]/')); $this->displayNameFormat = $format; if ($debug = $configuration->getProperty('CAS_DEBUG_PATH')) { ArgumentValidator::validate($debug, StringValidatorRule::getRule()); phpCAS::setDebug($debug); } $host = $configuration->getProperty('CAS_HOST'); ArgumentValidator::validate($host, RegexValidatorRule::getRule('/^[a-z0-9]+\\.[a-z0-9]+.[a-z]+$/')); $port = $configuration->getProperty('CAS_PORT'); ArgumentValidator::validate($port, RegexValidatorRule::getRule('/^[0-9]+$/')); $path = $configuration->getProperty('CAS_PATH'); ArgumentValidator::validate($path, RegexValidatorRule::getRule('/^\\/.*$/')); phpCAS::client(CAS_VERSION_2_0, $host, intval($port), $path, false); if ($cert = $configuration->getProperty('CAS_CERT')) { phpCAS::setCasServerCACert($cert); } else { phpCAS::setNoCasServerValidation(); } // Allow group lookup via a CASDirectory: // https://mediawiki.middlebury.edu/wiki/LIS/CAS_Directory $dirUrl = $configuration->getProperty('CASDIRECTORY_BASE_URL'); ArgumentValidator::validate($dirUrl, StringValidatorRule::getRule()); $this->directoryUrl = $dirUrl; // set the callback URL for the PGT to be sent to. This must be an https url // whose certificate is trusted by CAS. // $callbackUrl = $configuration->getProperty('CALLBACK_URL'); // ArgumentValidator::validate($callbackUrl, RegexValidatorRule::getRule('/^https:\/\/.*$/')); // phpCAS::setFixedCallbackURL($callbackUrl); $adminAccess = $configuration->getProperty('CASDIRECTORY_ADMIN_ACCESS'); ArgumentValidator::validate($adminAccess, StringValidatorRule::getRule()); $this->adminAccess = $adminAccess; $classRoot = $configuration->getProperty('CASDIRECTORY_CLASS_ROOT'); if ($classRoot) { ArgumentValidator::validate($classRoot, StringValidatorRule::getRule()); $this->classRoot = $classRoot; } else { $this->classRoot = null; } $groupIdRegex = $configuration->getProperty('CASDIRECTORY_GROUP_ID_REGEX'); if ($groupIdRegex) { ArgumentValidator::validate($groupIdRegex, StringValidatorRule::getRule()); $this->groupIdRegex = $groupIdRegex; } else { $this->groupIdRegex = null; } // Root Groups to expose ArgumentValidator::validate($configuration->getProperty('ROOT_GROUPS'), ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); $this->rootGroups = array_unique($configuration->getProperty('ROOT_GROUPS')); }