/** * 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; }
/** * Constructor. Creates a HarmoniId with id = $id or a new unique id if $id is NULL. * @param string $id The desired id. If NULL, a new unique id is used. * */ function __construct($id) { // ** parameter validation ArgumentValidator::validate($id, OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), IntegerValidatorRule::getRule()), true); // ** end of parameter validation // if (preg_match('/^#.+$/', $id)) $this->_id = strval($id); // else // $this->_id = '#'.md5($id); }
/** * Adds the given menu item to this container. The only difference from the * familiar <code>add()</code> method of the Container class is that now * explicit checking is performed to make sure that the given component * is indeed a <code>menuItem</code> and not just any component. * <br /><br /> * Warning: The <code>add()</code> method allows the user to add the same * instance of an object multiple times. With menus, this is extremely unadvised because * the menu might end up with multiple selected menu items at the same time. * @access public * @param ref object menuItem The menuItem to add. If it is selected, then the * old selected menu item will be automatically deselected. * @param string width The available width for the added menuItem. If null, will be ignored. * @param string height The available height for the added menuItem. If null, will be ignored. * @param integer alignmentX The horizontal alignment for the added menuItem. Allowed values are * <code>LEFT</code>, <code>CENTER</code>, and <code>RIGHT</code>. * If null, will be ignored. * @param integer alignmentY The vertical alignment for the added menuItem. Allowed values are * <code>TOP</code>, <code>CENTER</code>, and <code>BOTTOM</code>. * If null, will be ignored. * @return ref object The menuItem that was just added. **/ function add($menuItem, $width = null, $height = null, $alignmentX = null, $alignmentY = null) { // ** parameter validation // some weird class checking here - would have been much simpler if PHP // supported multiple inheritance $rule1 = ExtendsValidatorRule::getRule("MenuItemLink"); $rule2 = ExtendsValidatorRule::getRule("MenuItemHeading"); $rule3 = ExtendsValidatorRule::getRule("MenuItem"); $rule4 = ExtendsValidatorRule::getRule("SubMenu"); ArgumentValidator::validate($menuItem, OrValidatorRule::getRule(OrValidatorRule::getRule(OrValidatorRule::getRule($rule1, $rule2), $rule3), $rule4), true); // ** end of parameter validation parent::add($menuItem, $width, $height, $alignmentX, $alignmentY); // if the given menuItem is selected, then select it if ($menuItem instanceof MenuItemLink) { if ($menuItem->isSelected()) { $id = $this->getComponentsCount(); $this->select($id); } } return $menuItem; }
/** * 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; }
/** * Attempts to delete the specified node in the database. Only leaf nodes can * be deleted. * @access public * @param mixed idValue The string id of the node to delete. * @return void **/ function deleteNode($idValue) { // ** parameter validation ArgumentValidator::validate($idValue, OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), IntegerValidatorRule::getRule()), true); // ** end of parameter validation // get the node $node = $this->getNode($idValue); // if not a leaf, cannot delete if (!$node->isLeaf()) { // "Can not delete non-leaf nodes."; throw new OperationFailedException("Cannont delete non-leaf nodes."); } // clear the cache and update the _tree structure // detach the node from each of its parents and update the join table $parents = $node->getParents(); while ($parents->hasNext()) { $parent = $parents->next(); $node->removeParent($parent->getId()); } // now delete the tree node $treeNode = $this->_tree->getNode($idValue); $this->_tree->deleteNode($treeNode); // ----------------- // remove from cache unset($this->_cache[$idValue]); $node = null; // now remove from database $dbHandler = Services::getService("DatabaseManager"); // 1. Get the id of the type associated with the node $query = new SelectQuery(); $query->addTable("az2_node"); $query->addColumn("fk_type", "type_id", "az2_node"); $query->addWhereEqual("id", $idValue); $queryResult = $dbHandler->query($query, $this->_dbIndex); if (!$queryResult->hasNext()) { $queryResult->free(); throw new OperationFailedException("No type found for node, '{$idValue}'."); } $typeIdValue = $queryResult->field("type_id"); $queryResult->free(); // 2. Now delete the node $query = new DeleteQuery(); $query->setTable("az2_node"); $query->addWhereEqual("id", $idValue); $queryResult = $dbHandler->query($query, $this->_dbIndex); // 3. Now see if any other nodes have the same type $query = new SelectQuery(); $query->addTable("az2_node"); // count the number of nodes using the same type $query->addColumn("COUNT(fk_type)", "num"); $query->addWhereEqual("fk_type", $typeIdValue); $queryResult = $dbHandler->query($query, $this->_dbIndex); $num = $queryResult->field("num"); $queryResult->free(); if ($num == 0) { // if no other nodes use this type, then delete the type $query = new DeleteQuery(); $query->setTable("az2_node_type"); $query->addWhereEqual("id", $typeIdValue); $queryResult = $dbHandler->query($query, $this->_dbIndex); } // Delete the node's ancestory from the Ancestory table $this->clearNodeAncestory($idValue); }
/** * Answer the first image Record of the Asset, if none is availible, answer * the first file of any time. If none are availible, answer FALSE. * * @param object Id $assetId * @return mixed * @access public * @since 8/19/05 * @static */ static function getFirstImageOrFileRecordForAsset($assetOrId) { ArgumentValidator::validate($assetOrId, OrValidatorRule::getRule(ExtendsValidatorRule::getRule("Id"), ExtendsValidatorRule::getRule("Asset"))); $rule = ExtendsValidatorRule::getRule("Id"); if ($rule->check($assetOrId)) { $repositoryManager = Services::getService("RepositoryManager"); $asset = $repositoryManager->getAsset($assetOrId); } else { $asset = $assetOrId; } $idManager = Services::getService("IdManager"); $assetId = $asset->getId(); // Check the cache if (!isset($GLOBALS['__RepositoryThumbRecordCache'])) { $GLOBALS['__RepositoryThumbRecordCache'] = array(); } if (!isset($GLOBALS['__RepositoryThumbRecordCache'][$assetId->getIdString()])) { $imageProcessor = Services::getService("ImageProcessor"); $fileRecords = new MultiIteratorIterator(); try { $fileRecords->addIterator($asset->getRecordsByRecordStructure($idManager->getId("FILE"))); } catch (UnknownIdException $e) { } try { $fileRecords->addIterator($asset->getRecordsByRecordStructure($idManager->getId("REMOTE_FILE"))); } catch (UnknownIdException $e) { } while ($fileRecords->hasNext()) { $record = $fileRecords->next(); if (!isset($fileRecord)) { $fileRecord = $record; } $mimeTypeParts = $record->getPartsByPartStructure($idManager->getId("MIME_TYPE")); $mimeTypePart = $mimeTypeParts->next(); $mimeType = $mimeTypePart->getValue(); // If this record is supported by the image processor, then use it // to generate a thumbnail instead of the default icons. if ($imageProcessor->isFormatSupported($mimeType)) { $fileRecord = $record; break; } } if (!isset($fileRecord)) { $GLOBALS['__RepositoryThumbRecordCache'][$assetId->getIdString()] = FALSE; } else { $GLOBALS['__RepositoryThumbRecordCache'][$assetId->getIdString()] = $fileRecord; } } return $GLOBALS['__RepositoryThumbRecordCache'][$assetId->getIdString()]; }
/** * Answer the slot that matches the given site id * * @param string $siteId * @return object Slot * @access public * @since 8/16/07 */ public function getSlotBySiteId($siteId) { ArgumentValidator::validate($siteId, OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), ExtendsValidatorRule::getRule('Id'))); if (is_object($siteId)) { $tmp = $siteId; unset($siteId); $siteId = $tmp->getIdString(); } // Check our cache foreach ($this->slots as $slot) { if ($slot->getSiteId() == $siteId && !$slot->isAlias()) { return $slot; } } // Look up the slot in the database; try { $result = $this->getSlotByIdResult_Harmoni_Db($siteId); } catch (UnknownIdException $e) { $result = $this->getSlotByIdResult($siteId); } if ($result->getNumberOfRows()) { $slots = $this->getSlotsFromQueryResult($result); if (count($slots) !== 1) { throw new Exception("Mismached number of slots."); } $slot = current($slots); $this->slots[$slot->getShortname()] = $slot; } else { throw new UnknownIdException("No Slot Found for site id, '{$siteId}'"); } return $slot; }
/** * Get the unique Id with this String representation or create a new unique * Id with this representation. * * @param string $idString * * @return object Id * * @throws object IdException An exception with one of the following * messages defined in org.osid.id.IdException: {@link * org.osid.id.IdException#OPERATION_FAILED OPERATION_FAILED}, * {@link org.osid.id.IdException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.id.IdException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.id.IdException#UNIMPLEMENTED UNIMPLEMENTED}, {@link * org.osid.id.IdException#NULL_ARGUMENT NULL_ARGUMENT} * * @access public */ function getId($idString) { // if (isset($this->_ids[$idString])) { // print "id:". $idString." and ".$this->_ids[$idString]->getIdString()."<br/>"; // return $this->_ids[$idString]; // } ArgumentValidator::validate($idString, OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), NumericValidatorRule::getRule())); $id = new HarmoniId($idString); // cache the id // $this->_ids[$idString] = $id; return $id; }
/** * Sets the value of this text field. * @param string $value * @access public * @return void */ function setValue($value) { ArgumentValidator::validate($value, OrValidatorRule::getRule(StringValidatorRule::getRule(), NumericValidatorRule::getRule())); $this->_value = $value; }
/** * Returns <code>true</code> if the node with the specified id (string) exists. * @access public * @param mixed id The id of the node. * @return boolean <code>true</code> if the node with the specified id is in the tree; else <code>false</code>. */ function nodeExists($id) { // ** parameter validation ArgumentValidator::validate($id, OrValidatorRule::getRule(NonzeroLengthStringValidatorRule::getRule(), IntegerValidatorRule::getRule()), true); // ** end of parameter validation return isset($this->_nodes[$id]); }
/** * Unbinds the field that has been bound by <code>bindField()</code>. * @access public * @param string field The field to unbind. This could be either * a string value that would correspond to the field as returned by * <code>getFieldNames()</code>, or an integer (less than <code>getNumberOfFields()</code>) * corresponding to the index of the field. **/ function unbindField($field) { // ** parameter validation $orRule = OrValidatorRule::getRule(IntegerValidatorRule::getRule(), StringValidatorRule::getRule()); ArgumentValidator::validate($field, $orRule, true); // ** end of parameter validation if (isset($this->_boundVars[$field])) { $this->_boundVars[$field] = null; unset($this->_boundVars[$field]); } }
/** * Answer all of the comments attached to an asset * * @param object $assetOrId An Asset object or an Id object * @param string $order The constant ASC or DESC for ascending time (oldest * first) or decending time (recent first). * @return object Iterator * @access public * @since 7/3/07 */ function getAllComments($assetOrId, $order = ASC) { ArgumentValidator::validate($assetOrId, OrValidatorRule::getRule(ExtendsValidatorRule::getRule('Asset'), ExtendsValidatorRule::getRule('Id'))); if (method_exists($assetOrId, 'getId')) { $asset = $assetOrId; $assetId = $asset->getId(); } else { $repositoryManager = Services::getService("Repository"); $idManager = Services::getService("Id"); $repository = $repositoryManager->getRepository($idManager->getId("edu.middlebury.segue.sites_repository")); $asset = $repository->getAsset($assetOrId); $assetId = $assetOrId; } // Load the replies, their creation times into arrays for caching and // easy sorting. $assetIdString = $assetId->getIdString(); if (!isset($this->_allComments[$assetIdString])) { $this->_allComments[$assetIdString] = array(); $this->_allComments[$assetIdString]['ids'] = array(); $this->_allComments[$assetIdString]['times'] = array(); $rootComments = $this->getRootComments($asset); $allComments = new MultiIteratorIterator(); while ($rootComments->hasNext()) { $allComments->addIterator($this->_getDescendentComments($rootComments->next())); } while ($allComments->hasNext()) { $comment = $allComments->next(); $dateTime = $comment->getCreationDate(); $this->_allComments[$assetIdString]['ids'][] = $comment->getId(); $this->_allComments[$assetIdString]['times'][] = $dateTime->asSeconds(); } } // Sort the comment Ids based on time. array_multisort($this->_allComments[$assetIdString]['times'], SORT_NUMERIC, $order == ASC ? SORT_ASC : SORT_DESC, $this->_allComments[$assetIdString]['ids']); $null = null; $comments = new HarmoniIterator($null); foreach ($this->_allComments[$assetIdString]['ids'] as $id) { $comments->add($this->getComment($id)); } return $comments; }