5 # Part of the Collection Workflow Integration System (CWIS) 6 # Copyright 2011-2016 Edward Almasy and Internet Scout Research Group 7 # http://scout.wisc.edu/cwis/ 16 # ---- PUBLIC INTERFACE -------------------------------------------------- 27 # call parent contstructor to load info from DB 28 parent::__construct($ResourceId);
30 # load local attributes from database value cache 33 # load our local metadata schema 34 $this->
SchemaId = $this->ValueCache[
"SchemaId"];
35 if (!isset(self::$Schemas[$this->
SchemaId]))
37 self::$Schemas[$this->SchemaId] =
48 public static function Create($SchemaId)
50 # clean out any temp resource records more than three days old 52 $RFactory->CleanOutStaleTempItems(60 * 24 * 3);
54 # lock DB tables to prevent next ID from being grabbed 56 $DB->Query(
"LOCK TABLES Resources WRITE");
58 # find next temp resource ID 59 $Id = $RFactory->GetNextTempItemId();
61 # write out new resource record with temp resource ID 62 # Set DateLastModified = NOW() to avoid being pruned as a 63 # stale temp resource. 65 "INSERT INTO Resources 66 SET `ResourceId` = '".intval(
$Id).
"', 67 `SchemaId` = '".intval($SchemaId).
"', 68 `DateLastModified` = NOW() " );
71 $DB->Query(
"UNLOCK TABLES");
73 # create new Resource object 76 # set some additional fields for default resources 79 $Resource->Set(
"Date Of Record Creation", date(
"Y-m-d H:i:s"));
80 $Resource->Set(
"Date Last Modified", date(
"Y-m-d H:i:s"));
81 if ($GLOBALS[
"G_User"]->IsLoggedIn())
83 $Resource->Set(
"Added By Id", $GLOBALS[
"G_User"]->
Id());
84 $Resource->Set(
"Last Modified By Id", $GLOBALS[
"G_User"]->
Id());
88 # for each field that can have a default value 95 foreach ($Fields as $Field)
97 # if there is a default value available 98 $DefaultValue = $Field->DefaultValue();
99 if ($DefaultValue !== NULL)
101 # if the default value is an array 102 if (is_array($DefaultValue))
104 # if there are values in the array 105 if (!empty($DefaultValue))
107 # flip values for Set() if necessary 110 $DefaultValue = array_flip($DefaultValue);
114 $Resource->Set($Field, $DefaultValue);
120 $Resource->Set($Field, $DefaultValue);
125 $Resource->UpdateAutoupdateFields(
129 # signal resource creation 130 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_CREATE", array(
131 "Resource" => $Resource,
134 # return new Resource object to caller 146 # signal that resource deletion is about to occur 148 $AF->SignalEvent(
"EVENT_RESOURCE_DELETE", array(
152 # grab list of classifications 155 # delete resource/classification intersections 157 $DB->Query(
"DELETE FROM ResourceClassInts WHERE ResourceId = ".$this->
Id());
159 # for each classification type 160 foreach ($Classifications as $ClassType => $ClassesOfType)
162 # for each classification of that type 163 foreach ($ClassesOfType as $ClassId => $ClassName)
165 # recalculate resource count for classification 167 $Class->RecalcResourceCount();
171 # delete resource references 173 DELETE FROM ReferenceInts 174 WHERE SrcResourceId = '".addslashes($this->
Id()).
"' 175 OR DstResourceId = '".addslashes($this->
Id()).
"'");
177 # delete resource/name intersections 178 $DB->Query(
"DELETE FROM ResourceNameInts WHERE ResourceId = ".$this->
Id());
180 # delete resource/user intersections 181 $DB->Query(
"DELETE FROM ResourceUserInts WHERE ResourceId = ".$this->
Id());
183 # get the list of all images associated with this resource 184 $DB->Query(
"SELECT ImageId FROM ResourceImageInts" 185 .
" WHERE ResourceId = ".intval($this->
Id()));
186 $ImageIds =
$DB->FetchColumn(
"ImageId");
188 # disassociate this resource from all images 189 $DB->Query(
"DELETE FROM ResourceImageInts" 190 .
" WHERE ResourceId = ".intval($this->
Id()));
192 # delete any images that no longer belong to any resources 193 foreach ($ImageIds as $ImageId)
195 $DB->Query(
"SELECT ResourceId FROM ResourceImageInts" 196 .
" WHERE ImageId = ".intval($ImageId) );
197 if (
$DB->NumRowsSelected() == 0)
204 # delete any associated files 206 $Files = $Factory->GetFilesForResource($this->
Id());
207 foreach ($Files as $File)
212 # delete resource record from database 213 $DB->Query(
"DELETE FROM Resources WHERE ResourceId = ".$this->
Id());
215 # drop item from search engine and recommender system 216 if ($SysConfig->SearchDBEnabled())
219 $SearchEngine->DropItem($this->
Id());
221 if ($SysConfig->RecommenderDBEnabled())
224 $Recommender->DropItem($this->
Id());
227 # get the folders containing the resource 229 $Folders = $FolderFactory->GetFoldersContainingItem(
233 # drop the resource from each folder it belongs to 234 foreach ($Folders as $Folder)
236 # mixed item type folder 237 if ($Folder->ContainsItem($this->Id,
"Resource"))
239 $Folder->RemoveItem($this->
Id,
"Resource");
242 # single item type folder 245 $Folder->RemoveItem($this->
Id);
249 # delete any resource comments 250 $DB->Query(
"DELETE FROM Messages WHERE ParentId = ".$this->
Id);
261 # update all the timestamp fields as required 262 $TimestampFields = $this->
Schema()->GetFields(
264 foreach ($TimestampFields as $Field)
266 if ($Field->UpdateMethod() == $UpdateType)
268 $this->
Set($Field,
"now");
272 # if a user was provided, update the user fields as well 273 if (!is_null($User) && !$User->IsAnonymous())
275 $UserFields = $this->
Schema()->GetFields(
277 foreach ($UserFields as $Field)
279 if ($Field->UpdateMethod() == $UpdateType)
281 $this->
Set($Field, $User);
302 return $this->SchemaId;
311 return self::$Schemas[$this->SchemaId];
322 # if new temp resource setting supplied 323 if (!is_null($NewSetting))
325 # if caller requested to switch 327 if ((($this->
Id() < 0) && ($NewSetting == FALSE))
328 || (($this->
Id() >= 0) && ($NewSetting == TRUE)))
332 # lock DB tables to prevent next ID from being grabbed 333 $DB->Query(
"LOCK TABLES Resources WRITE");
335 # get next resource ID as appropriate 337 if ($NewSetting == TRUE)
339 $this->
Id = $Factory->GetNextTempItemId();
343 $this->
Id = $Factory->GetNextItemId();
347 $DB->Query(
"UPDATE Resources SET ResourceId = ".
348 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
351 $DB->Query(
"UNLOCK TABLES");
353 # change associations 354 unset($this->ClassificationCache);
355 $DB->Query(
"UPDATE ResourceClassInts SET ResourceId = ".
356 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
357 unset($this->ControlledNameCache);
358 unset($this->ControlledNameVariantCache);
359 $DB->Query(
"UPDATE ResourceNameInts SET ResourceId = ".
360 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
361 $DB->Query(
"UPDATE Files SET ResourceId = ".
362 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
363 $DB->Query(
"UPDATE ReferenceInts SET SrcResourceId = ".
364 $this->
Id.
" WHERE SrcResourceId = ".$OldResourceId);
365 $DB->Query(
"UPDATE ResourceImageInts SET ResourceId = ".
366 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
367 $DB->Query(
"UPDATE ResourceUserInts SET ResourceId = ".
368 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
370 # signal event as appropriate 371 if ($NewSetting === FALSE)
373 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_ADD", array(
380 # report to caller whether we are a temp resource 381 return ($this->
Id() < 0) ? TRUE : FALSE;
385 # --- Generic Attribute Retrieval Methods ------------------------------- 393 # put our Id into the ViewPage from our schema 396 $this->
Schema()->ViewPage());
398 # return clean url, if one is available 399 return $GLOBALS[
"AF"]->GetCleanUrlForPath($Url);
415 public function Get($Field, $ReturnObject = FALSE, $IncludeVariants = FALSE)
417 # load field object if not already supplied 418 $Field = is_object($Field) ? $Field : $this->
Schema()->GetField($Field);
420 if ($Field->SchemaId() != $this->
SchemaId())
422 throw new Exception(
"Attempt to get a value for a field" 423 .
" from a different schema." 424 .
" (Field: ".$Field->Name().
" [".$Field->Id()
425 .
"], Field Schema: ".$Field->SchemaId()
426 .
", Resource Schema: ".$this->
SchemaId()
430 # grab database field name 431 $DBFieldName = $Field->DBFieldName();
433 # format return value based on field type 434 switch ($Field->Type())
439 $ReturnValue = isset($this->ValueCache[$DBFieldName])
440 ? (string)$this->ValueCache[$DBFieldName] : NULL;
444 $ReturnValue = isset($this->ValueCache[$DBFieldName])
445 ? (int)$this->ValueCache[$DBFieldName] : NULL;
449 $ReturnValue = isset($this->ValueCache[$DBFieldName])
450 ? (bool)$this->ValueCache[$DBFieldName] : NULL;
454 $ReturnValue = array(
"X" => (
float)$this->ValueCache[$DBFieldName.
"X"],
455 "Y" => (
float)$this->ValueCache[$DBFieldName.
"Y"]);
459 $Date =
new Date($this->ValueCache[$DBFieldName.
"Begin"],
460 $this->ValueCache[$DBFieldName.
"End"],
461 $this->ValueCache[$DBFieldName.
"Precision"]);
464 $ReturnValue = $Date;
468 $ReturnValue = $Date->Formatted();
473 $ReturnValue = $this->ValueCache[$DBFieldName];
477 # start with empty array 478 $ReturnValue = array();
480 # if classification cache has not been loaded 481 if (!isset($this->ClassificationCache))
483 # load all classifications associated with this resource into cache 484 $this->ClassificationCache = array();
486 "SELECT Classifications.ClassificationId," 487 .
" Classifications.FieldId,ClassificationName" 488 .
" FROM ResourceClassInts, Classifications" 489 .
" WHERE ResourceClassInts.ResourceId = ".$this->
Id 490 .
" AND ResourceClassInts.ClassificationId" 491 .
" = Classifications.ClassificationId");
492 while ($Record = $this->DB->FetchRow())
494 $ClassId = $Record[
"ClassificationId"];
495 $this->ClassificationCache[$ClassId][
"Name"]
496 = $Record[
"ClassificationName"];
497 $this->ClassificationCache[$ClassId][
"FieldId"]
498 = $Record[
"FieldId"];
501 # for each entry in classification cache 502 foreach ($this->ClassificationCache as
503 $ClassificationId => $ClassificationInfo)
505 # if classification ID matches field we are looking for 506 if ($ClassificationInfo[
"FieldId"] == $Field->Id())
508 # add field to result 511 $ReturnValue[$ClassificationId] =
516 $ReturnValue[$ClassificationId] = $ClassificationInfo[
"Name"];
524 # start with empty array 525 $ReturnValue = array();
527 # if controlled name cache has not been loaded 528 if (!isset($this->ControlledNameCache))
530 # load all controlled names associated with this resource into cache 531 $this->ControlledNameCache = array();
533 "SELECT ControlledNames.ControlledNameId," 534 .
" ControlledNames.FieldId,ControlledName" 535 .
" FROM ResourceNameInts, ControlledNames" 536 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 537 .
" AND ResourceNameInts.ControlledNameId" 538 .
" = ControlledNames.ControlledNameId" 539 .
" ORDER BY ControlledNames.ControlledName ASC");
540 while ($Record = $this->DB->FetchRow())
542 $CNameId = $Record[
"ControlledNameId"];
543 $this->ControlledNameCache[$CNameId][
"Name"]
544 = $Record[
"ControlledName"];
545 $this->ControlledNameCache[$CNameId][
"FieldId"]
546 = $Record[
"FieldId"];
550 # if variant names requested and variant name cache has not been loaded 551 if ($IncludeVariants && !isset($this->ControlledNameVariantCache))
553 # load all controlled names associated with this resource into cache 554 $this->ControlledNameVariantCache = array();
555 $this->DB->Query(
"SELECT ControlledNames.ControlledNameId," 556 .
" ControlledNames.FieldId," 557 .
" ControlledName, VariantName" 558 .
" FROM ResourceNameInts, ControlledNames, VariantNames" 559 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 560 .
" AND ResourceNameInts.ControlledNameId" 561 .
" = ControlledNames.ControlledNameId" 562 .
" AND VariantNames.ControlledNameId" 563 .
" = ControlledNames.ControlledNameId");
564 while ($Record = $this->DB->FetchRow())
566 $this->ControlledNameVariantCache[$Record[
"ControlledNameId"]][]
567 = $Record[
"VariantName"];
571 # for each entry in controlled name cache 572 foreach ($this->ControlledNameCache as
573 $CNameId => $ControlledNameInfo)
575 # if controlled name type matches field we are looking for 576 if ($ControlledNameInfo[
"FieldId"] == $Field->Id())
578 # if objects requested 581 $ReturnValue[$CNameId] =
586 # if variant names requested 587 if ($IncludeVariants)
589 # add field to result 590 $ReturnValue[] = $ControlledNameInfo[
"Name"];
592 # add any variant names to result 593 if (isset($this->ControlledNameVariantCache[$CNameId]))
595 $ReturnValue = array_merge(
597 $this->ControlledNameVariantCache[$CNameId]);
602 # add field with index to result 603 $ReturnValue[$CNameId] =
604 $ControlledNameInfo[
"Name"];
612 # start out assuming no associated users 613 $ReturnValue = array();
615 # query the database to get the associated userids 617 "SELECT UserId FROM ResourceUserInts WHERE ".
618 "ResourceId=".intval($this->
Id).
619 " AND FieldId=".intval($Field->Id()));
620 $UserIds = $this->DB->FetchColumn(
"UserId");
622 # convert each userid to either a name or a CWUser object 623 foreach ($UserIds as $UserId)
625 $User =
new CWUser(intval($UserId));
628 $ReturnValue[$UserId] = $User;
632 $ReturnValue[$UserId] = $User->Get(
"UserName");
638 # start out assuming no images will be found 639 $ReturnValue = array();
641 # find all images associated with this resource 642 $this->DB->Query(
"SELECT ImageId FROM ResourceImageInts" 643 .
" WHERE ResourceId = ".intval($this->
Id())
644 .
" AND FieldId = ".intval($Field->Id()));
646 # if images were found 647 if ($this->DB->NumRowsSelected())
649 # if we are to return an object 650 $ImageIds = $this->DB->FetchColumn(
"ImageId");
653 # load array of Image objects for return value 654 foreach ($ImageIds as $ImageId)
656 $ReturnValue[$ImageId] =
new SPTImage($ImageId);
661 # load array of Image ids for return value 662 $ReturnValue = $ImageIds;
668 # retrieve files using factory 671 $this->
Id, $ReturnObject);
675 # query for resource references 677 SELECT * FROM ReferenceInts 678 WHERE FieldId = '".addslashes($Field->Id()).
"' 679 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
681 $ReturnValue = array();
683 # return each reference as a Resource object 686 $FoundErrors = FALSE;
688 while (FALSE !== ($Record = $this->DB->FetchRow()))
690 $ReferenceId = $Record[
"DstResourceId"];
691 $Reference =
new Resource($ReferenceId);
692 $ReturnValue[$ReferenceId] = $Reference;
696 # return each reference as a resource ID 699 while (FALSE !== ($Record = $this->DB->FetchRow()))
701 $ReferenceId = $Record[
"DstResourceId"];
702 $ReturnValue[$ReferenceId] = $ReferenceId;
709 exit(
"<br>SPT - ERROR: attempt to retrieve " 710 .
"unknown resource field type (".$Field->Type().
")<br>\n");
714 # return formatted value to caller 738 $FieldNameOrObject, $ReturnObject = TRUE, $IncludeVariants = FALSE)
740 # normalize metadata field for use by any hooked code 741 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
742 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
745 $Value = $this->
Get($Field, $ReturnObject, $IncludeVariants);
747 # signal event to allowed hooked code to modify value 748 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
749 "EVENT_FIELD_DISPLAY_FILTER", array(
754 # return possibly modified value to caller 755 return $SignalResult[
"Value"];
774 $ReturnObject = FALSE, $IncludeVariants = FALSE)
776 return $this->
Get($FieldNameOrObject, $ReturnObject, $IncludeVariants);
794 $FieldId, $ReturnObject = FALSE, $IncludeVariants = FALSE)
796 return $this->
Get($FieldId, $ReturnObject, $IncludeVariants);
811 public function GetAsArray($IncludeDisabledFields = FALSE, $ReturnObjects = TRUE)
813 # retrieve field info 814 $Fields = $this->
Schema()->GetFields();
817 foreach ($Fields as $Field)
819 # if field is enabled or caller requested disabled fields 820 if ($Field->Enabled() || $IncludeDisabledFields)
822 # retrieve info and add it to the array 823 $FieldStrings[$Field->Name()] = $this->
Get($Field, $ReturnObjects);
825 # if field uses qualifiers 826 if ($Field->UsesQualifiers())
828 # get qualifier attributes and add to the array 829 $FieldStrings[$Field->Name().
" Qualifier"] =
835 # add in internal values 836 $FieldStrings[
"ResourceId"] = $this->
Id();
839 # return array to caller 840 return $FieldStrings;
858 $MappedName, $ReturnObject = FALSE, $IncludeVariants = FALSE)
860 $FieldId = $this->
Schema()->StdNameToFieldMapping($MappedName);
862 ? $this->
Get($FieldId, $ReturnObject, $IncludeVariants)
876 $Field = $this->
Schema()->GetFieldByName($FieldName);
890 $Field = $this->
Schema()->GetField($FieldId);
904 # return NULL if field is invalid 907 # assume no qualifiers if not otherwise determined 910 # if field uses qualifiers 911 if ($Field->UsesQualifiers())
913 # retrieve qualifiers based on field type 914 switch ($Field->Type())
919 # retrieve list of items 922 # if field uses item-level qualifiers 923 if ($Field->HasItemLevelQualifiers())
925 # determine general item name in DB 927 ?
"Classification" :
"ControlledName";
930 foreach (
$Items as $ItemId => $ItemName)
932 # look up qualifier for item 933 $QualId = $this->DB->Query(
934 "SELECT * FROM ".$TableName.
"s" 935 .
" WHERE ".$TableName.
"Id = ".$ItemId,
941 # if object was requested by caller 944 # load qualifier and add to return value array 945 $ReturnValue[$ItemId] =
new Qualifier($QualId);
949 # add qualifier ID to return value array 950 $ReturnValue[$ItemId] = $QualId;
955 # add NULL to return value array for this item 956 $ReturnValue[$ItemId] = NULL;
963 foreach (
$Items as $ItemId => $ItemName)
965 # if object was requested by caller 968 # load default qualifier and add to return value array 970 $Field->DefaultQualifier());
974 # add default qualifier ID to return value array 975 $ReturnValue[$ItemId] = $Field->DefaultQualifier();
982 # if field uses item-level qualifiers 983 if ($Field->HasItemLevelQualifiers())
985 # if qualifier available 986 if ($this->ValueCache[$Field->DBFieldName().
"Qualifier"] > 0)
988 # if object was requested by caller 989 $QFieldName = $Field->DBFieldName().
"Qualifier";
992 # return qualifier for field 994 $this->ValueCache[$QFieldName]);
998 # return qualifier ID for field 999 $ReturnValue = $this->ValueCache[$QFieldName];
1005 # if default qualifier available 1006 if ($Field->DefaultQualifier() > 0)
1008 # if object was requested by caller 1011 # return default qualifier 1012 $ReturnValue =
new Qualifier($Field->DefaultQualifier());
1016 # return default qualifier ID 1017 $ReturnValue = $Field->DefaultQualifier();
1025 # return qualifier object or ID (or array of same) to caller 1026 return $ReturnValue;
1036 public function FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
1038 # load field object if needed 1039 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1040 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
1042 # return no value found if we don't have a valid field 1046 $Value = $this->
Get($Field);
1048 # checks depend on the field type 1049 switch ($Field->Type())
1055 return isset($Value)
1057 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
1060 return isset($Value)
1064 return isset($Value[
"X"])
1065 && isset($Value[
"Y"])
1066 && strlen(trim($Value[
"X"]))
1067 && strlen(trim($Value[
"Y"]));
1070 return isset($Value)
1071 && strlen(trim($Value))
1072 && $Value !=
"0000-00-00";
1075 return isset($Value)
1076 && strlen(trim($Value))
1077 && $Value !=
"0000-00-00 00:00:00";
1085 return count($Value) > 0;
1089 return isset($Value)
1091 && $Factory->UserNameExists($Value);
1110 # get our target field and extract its values 1111 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1112 : $this->
Schema()->GetField($FieldNameOrObject);
1113 $Images = $this->
Get($Field, TRUE);
1115 # iterate over our images getting URLs for each 1117 foreach ($Images as $Image)
1119 $Result[$Image->Id()] = $Image->GetImageUrlForResource(
1120 $this->
Id(), $Field->Id(), $Index, $ImageSize);
1127 # --- Generic Attribute Setting Methods --------------------------------- 1141 public function Set($Field, $NewValue, $Reset=FALSE)
1143 # load field object if not already supplied 1144 $Field = is_object($Field) ? $Field
1145 : (is_numeric($Field) ? $this->
Schema()->GetField($Field)
1146 : $this->
Schema()->GetFieldByName($Field));
1148 # return if we don't have a valid field 1151 if ($Field->SchemaId() != $this->
SchemaId())
1153 throw new Exception(
"Attempt to set a value for a field " 1154 .
"from a different schema.");
1157 # grab commonly-used values for local use 1161 # grab database field name 1162 $DBFieldName = $Field->DBFieldName();
1164 # Flag to deterimine if we've actually changed anything. 1165 $UpdateModTime = FALSE;
1167 # store value in DB based on field type 1168 switch ($Field->Type())
1173 if ($this->ValueCache[$DBFieldName] != $NewValue)
1175 # save value directly to DB 1176 $DB->Query(
"UPDATE Resources SET `" 1177 .$DBFieldName.
"` = '".addslashes($NewValue).
"' " 1178 .
"WHERE ResourceId = ".$ResourceId);
1180 # save value locally 1181 $this->ValueCache[$DBFieldName] = $NewValue;
1182 $UpdateModTime=TRUE;
1187 if ( $this->ValueCache[$DBFieldName] != $NewValue )
1189 # save value directly to DB 1190 if (is_null($NewValue))
1192 $DB->Query(
"UPDATE Resources SET `" 1193 .$DBFieldName.
"` = NULL" 1194 .
" WHERE ResourceId = ".$ResourceId);
1198 $DB->Query(
"UPDATE Resources SET `" 1199 .$DBFieldName.
"` = ".intval($NewValue)
1200 .
" WHERE ResourceId = ".$ResourceId);
1203 # save value locally 1204 $this->ValueCache[$DBFieldName] = $NewValue;
1205 $UpdateModTime = TRUE;
1211 if ($this->ValueCache[$DBFieldName.
"X"] != $NewValue[
"X"] ||
1212 $this->ValueCache[$DBFieldName.
"Y"] != $NewValue[
"Y"] )
1214 if (is_null($NewValue))
1216 $DB->Query(
"UPDATE Resources SET " 1217 .
"`".$DBFieldName.
"X` = NULL, " 1218 .
"`".$DBFieldName.
"Y` = NULL " 1219 .
"WHERE ResourceId = ".$ResourceId);
1220 $this->ValueCache[$DBFieldName.
"X"] = NULL;
1221 $this->ValueCache[$DBFieldName.
"Y"] = NULL;
1225 $DB->Query(
"UPDATE Resources SET " 1226 .
"`".$DBFieldName.
"X` = " .(strlen($NewValue[
"X"])
1227 ?
"'".$NewValue[
"X"].
"'" :
"NULL").
", " 1228 .
"`".$DBFieldName.
"Y` = ".(strlen($NewValue[
"Y"])
1229 ?
"'".$NewValue[
"Y"].
"'" :
"NULL")
1230 .
" WHERE ResourceId = ".$ResourceId);
1232 $Digits = $Field->PointDecimalDigits();
1234 $this->ValueCache[$DBFieldName.
"X"] =
1235 strlen($NewValue[
"X"]) ?
1236 round($NewValue[
"X"], $Digits) : NULL;
1237 $this->ValueCache[$DBFieldName.
"Y"] =
1238 strlen($NewValue[
"Y"]) ?
1239 round($NewValue[
"Y"], $Digits) : NULL;
1241 $UpdateModTime = TRUE;
1246 if ($this->ValueCache[$DBFieldName] != $NewValue)
1248 # save value directly to DB 1249 if (is_null($NewValue))
1251 $DB->Query(
"UPDATE Resources SET `" 1252 .$DBFieldName.
"` = NULL" 1253 .
" WHERE ResourceId = ".$ResourceId);
1257 $NewValue = $NewValue ?
"1" :
"0";
1258 $DB->Query(
"UPDATE Resources SET `" 1259 .$DBFieldName.
"` = ".$NewValue
1260 .
" WHERE ResourceId = ".$ResourceId);
1263 $this->ValueCache[$DBFieldName] = $NewValue;
1265 $UpdateModTime = TRUE;
1270 $OldValue = $this->
Get($Field);
1271 # value comes back as array (UserId => UserName), just get the Ids 1272 $OldValue = array_keys($OldValue);
1274 # input to Set() for these fields is one of 1275 # 1. an int specifying a UserId 1276 if (is_numeric($NewValue))
1278 $NewValue = array($NewValue);
1280 # 2. a CWUser object 1281 elseif ($NewValue instanceof
CWUser)
1283 $NewValue = array($NewValue->Id());
1285 # 3. an array keyed by UserId (don't care about the values) 1286 elseif (is_array($NewValue))
1288 $NewValue = array_keys($NewValue);
1292 throw new Exception(
"Unknown format for NewValue in a User field");
1295 # if this is a unique field, only accept the first of the options given 1296 if ($Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1298 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1301 # sort new and old values so we can directly compare 1305 # if the value has changed 1306 if ($OldValue != $NewValue)
1308 if ($Reset || $Field->AllowMultiple() == FALSE )
1310 $ToRemove = array_diff($OldValue, $NewValue);
1311 $this->RemoveAssociation(
1312 "ResourceUserInts",
"UserId", $ToRemove, $Field);
1315 # associate with resource if not already associated 1316 $this->AddAssociation(
"ResourceUserInts",
1320 $UpdateModTime=TRUE;
1325 # if we were given a date object 1326 if (is_object($NewValue))
1328 # use supplied date object 1333 # create date object 1334 $Date =
new Date($NewValue);
1337 $OldDate =
new Date(
1338 $this->ValueCache[$DBFieldName.
"Begin"],
1339 $this->ValueCache[$DBFieldName.
"End"]);
1341 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1342 $OldDate->EndDate() != $Date->EndDate() ||
1343 $OldDate->Precision() != $Date->Precision() )
1345 # extract values from date object and store in DB 1346 $BeginDate =
"'".$Date->BeginDate().
"'";
1347 if (strlen($BeginDate) < 3) { $BeginDate =
"NULL"; }
1348 $EndDate =
"'".$Date->EndDate().
"'";
1349 if (strlen($EndDate) < 3) { $EndDate =
"NULL"; }
1351 $DB->Query(
"UPDATE Resources SET " 1352 .$DBFieldName.
"Begin = ".$BeginDate.
", " 1353 .$DBFieldName.
"End = ".$EndDate.
", " 1354 .$DBFieldName.
"Precision = '".$Date->Precision().
"' " 1355 .
"WHERE ResourceId = ".$ResourceId);
1357 # save values locally 1358 $this->ValueCache[$DBFieldName.
"Begin"] = $Date->BeginDate();
1359 $this->ValueCache[$DBFieldName.
"End"] = $Date->EndDate();
1360 $this->ValueCache[$DBFieldName.
"Precision"] = $Date->Precision();
1361 $UpdateModTime=TRUE;
1366 if (is_null($NewValue) || !strlen(trim($NewValue)))
1368 $DateValue = $NewValue;
1370 if (!is_null($this->ValueCache[$DBFieldName]))
1372 # save value directly to DB 1373 $DB->Query(
"UPDATE Resources SET " 1374 .
"`".$DBFieldName.
"` = NULL " 1375 .
"WHERE ResourceId = ".$ResourceId);
1376 $UpdateModTime = TRUE;
1381 # assume value is date and use directly 1382 $TimestampValue = strtotime($NewValue);
1384 # use the new value if the date is valid 1385 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1387 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1389 if ($this->ValueCache[$DBFieldName] != $DateValue)
1391 # save value directly to DB 1392 $DB->Query(
"UPDATE Resources SET " 1393 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' " 1394 .
"WHERE ResourceId = ".$ResourceId);
1395 $UpdateModTime=TRUE;
1399 # continue using the old value if invalid 1402 $DateValue = $this->
Get($Field);
1406 # save value locally 1407 $this->ValueCache[$DBFieldName] = $DateValue;
1411 $OldValue = $this->
Get($Field);
1413 # if incoming value is array 1414 if (is_array($NewValue))
1416 if ($OldValue != $NewValue)
1420 # remove values that were in the old value 1421 # but not the new one 1422 $ToRemove = array_diff(array_keys($OldValue),
1423 array_keys($NewValue));
1424 foreach ($ToRemove as $ClassificationId)
1426 $this->RemoveAssociation(
"ResourceClassInts",
1430 $Class->RecalcResourceCount();
1434 # for each element of array 1435 foreach ($NewValue as
1436 $ClassificationId => $ClassificationName)
1439 if ($Class->FieldId() == $Field->Id())
1441 # associate with resource if not already associated 1442 if ($this->AddAssociation(
"ResourceClassInts",
1443 "ClassificationId", $ClassificationId))
1445 $Class->UpdateLastAssigned();
1446 $Class->RecalcResourceCount();
1451 throw new Exception(
1452 "Attempting to store classification from " 1453 .
"Field ".$Class->FieldId().
" into Field " 1459 $UpdateModTime=TRUE;
1464 # associate with resource if not already associated 1465 if (is_object($NewValue))
1468 $NewValue = $Class->Id();
1475 if (!array_key_exists($Class->Id(), $OldValue))
1478 $this->AddAssociation(
"ResourceClassInts",
1481 $Class->UpdateLastAssigned();
1482 $Class->RecalcResourceCount();
1483 $UpdateModTime=TRUE;
1487 # clear our classification cache 1490 unset($this->ClassificationCache);
1496 $OldValue = $this->
Get($Field);
1498 # input to Set() for these fields is one of 1499 # 1. an int specifying a ControlledNameId 1500 # 2. a ControlledName object 1501 # 3. an array with keys giving Ids and values giving ControlledNames 1503 # normalize 1 and 2 into 3 for simplicity of processing 1504 if (is_object($NewValue) || !is_array($NewValue) )
1506 if (!is_object($NewValue))
1511 $TmpValue = array();
1512 $TmpValue[$NewValue->Id()] = $NewValue->Name();
1514 $NewValue = $TmpValue;
1517 # if this is a unique field, only accept the first of the options given 1518 # NB: all ControlledNames implicitly AllowMultiple 1520 $Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1522 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1525 # if the value has changed 1526 if ($OldValue != $NewValue)
1529 && $Field->AllowMultiple() == FALSE ) )
1531 $ToRemove = array_diff(array_keys($OldValue),
1532 array_keys($NewValue));
1533 foreach ($ToRemove as $CNId)
1535 $this->RemoveAssociation(
"ResourceNameInts",
1541 # for each element of array 1542 foreach ($NewValue as $ControlledNameId => $ControlledName)
1544 # associate with resource if not already associated 1545 if ($this->AddAssociation(
"ResourceNameInts",
1552 $this->RemoveAssociation(
"ResourceNameInts",
1553 "ControlledNameId", $ControlledNameId);
1554 throw new InvalidArgumentException(
1555 "Attempt to set controlled name with" 1556 .
" invalid ID (".$ControlledNameId.
").");
1558 $CN->UpdateLastAssigned();
1561 $UpdateModTime = TRUE;
1566 # clear our controlled name cache 1567 unset($this->ControlledNameCache);
1568 unset($this->ControlledNameVariantCache);
1570 # clear visible count cache for any affected resources 1571 $ValueIds = array_keys($OldValue) + array_keys($NewValue);
1573 "DELETE FROM VisibleResourceCounts WHERE " 1574 .
"SchemaId=".intval($this->
SchemaId).
" AND " 1575 .
"ValueId IN (".implode(
",", $ValueIds).
")");
1581 # associate value(s) with resource 1582 $this->AddAssociation(
1583 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1584 # clear cached image mappings 1589 # convert incoming value to array if necessary 1590 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1592 # for each incoming file 1594 foreach ($NewValue as $File)
1597 $NewFile = $Factory->
Copy($File);
1599 # associate copy with this resource and field 1600 $NewFile->ResourceId($this->
Id);
1601 $NewFile->FieldId($Field->Id());
1603 # Since we make a fresh copy of the File whenever Set is called, 1604 # we'll always update the modification time for this field. 1605 $UpdateModTime = TRUE;
1609 # convert incoming value to array to simplify the workflow 1610 if (is_scalar($NewValue) || $NewValue instanceof
Resource)
1612 $NewValue = array($NewValue);
1615 # delete existing resource references 1618 # add each reference 1619 foreach ($NewValue as $ReferenceOrId)
1621 # initially issume it's a reference ID and not an object... 1622 $ReferenceId = $ReferenceOrId;
1624 # ... but get the reference ID if it's an object 1625 if ($ReferenceOrId instanceof
Resource)
1627 $ReferenceId = $ReferenceOrId->Id();
1630 # skip blank reference IDs 1631 if (strlen(trim($ReferenceId)) < 1)
1636 # skip reference IDs that don't look right 1637 if (!is_numeric($ReferenceId))
1642 # skip references to the current resource 1643 if ($ReferenceId == $this->
Id())
1648 # add the reference to the references table 1650 INSERT INTO ReferenceInts ( 1655 ".addslashes($Field->Id()).
", 1656 ".addslashes($this->
Id()).
", 1657 ".addslashes($ReferenceId).
")");
1663 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1669 # update modification timestamps 1671 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1672 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 1673 .
"WHERE ResourceId=".$this->
Id.
" AND " 1674 .
"FieldId=".$Field->Id() );
1675 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 1676 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 1677 .$this->
Id.
",".$Field->Id().
"," 1678 .$UserId.
",NOW())");
1680 # on resource modification, clear the UserPermsCache entry 1681 # so that stale permissions checks are not cached 1682 $DB->Query(
"DELETE FROM UserPermsCache WHERE ResourceId=".$this->
Id);
1695 $this->
Set($Field, $NewValue);
1707 $this->
Set($FieldId, $NewValue);
1717 $Field = $this->
Schema()->GetFieldByName($FieldName);
1728 $Field = $this->
Schema()->GetField($FieldId);
1739 # if field uses qualifiers and uses item-level qualifiers 1740 if ($Field->UsesQualifiers() && $Field->HasItemLevelQualifiers())
1742 # if qualifier object passed in 1743 if (is_object($NewValue))
1745 # grab qualifier ID from object 1746 $QualifierId = $NewValue->Id();
1750 # assume value passed in is qualifier ID 1751 $QualifierId = $NewValue;
1754 # update qualifier value in database 1755 $DBFieldName = $Field->DBFieldName();
1756 $this->DB->Query(
"UPDATE Resources SET " 1757 .$DBFieldName.
"Qualifier = '".$QualifierId.
"' " 1758 .
"WHERE ResourceId = ".$this->Id);
1760 # update local qualifier value 1761 $this->ValueCache[$DBFieldName.
"Qualifier"] = $QualifierId;
1773 $Field = $this->
Schema()->GetField($FieldId);
1774 $this->
Clear($Field, $ValueToClear);
1783 public function Clear($Field, $ValueToClear = NULL)
1785 # convert field name to object if necessary 1786 if (!is_object($Field))
1788 $Field = $this->
Schema()->GetFieldByName($Field);
1791 # grab commonly-used values for local use 1795 # grab database field name 1796 $DBFieldName = $Field->DBFieldName();
1798 $UpdateModTime=FALSE;
1800 # store value in DB based on field type 1801 switch ($Field->Type())
1809 if (strlen($this->ValueCache[$DBFieldName])>0)
1812 $DB->Query(
"UPDATE Resources SET `" 1813 .$DBFieldName.
"` = NULL " 1814 .
"WHERE ResourceId = ".$ResourceId);
1816 # clear value locally 1817 $this->ValueCache[$DBFieldName] = NULL;
1818 $UpdateModTime=TRUE;
1823 if (!is_null($this->ValueCache[$DBFieldName.
"X"]) ||
1824 !is_null($this->ValueCache[$DBFieldName.
"Y"]) )
1827 $DB->Query(
"UPDATE Resources SET " 1828 .
"`".$DBFieldName.
"X` = NULL ," 1829 .
"`".$DBFieldName.
"Y` = NULL " 1830 .
"WHERE ResourceId = ".$ResourceId);
1832 # Clear local values 1833 $this->ValueCache[$DBFieldName.
"X"] = NULL;
1834 $this->ValueCache[$DBFieldName.
"Y"] = NULL;
1835 $UpdateModTime=TRUE;
1840 if (!is_null($this->ValueCache[$DBFieldName.
"Begin"]) ||
1841 !is_null($this->ValueCache[$DBFieldName.
"End"]) ||
1842 !is_null($this->ValueCache[$DBFieldName.
"Precision"]))
1844 # clear date object values in DB 1845 $DB->Query(
"UPDATE Resources SET " 1846 .$DBFieldName.
"Begin = '', " 1847 .$DBFieldName.
"End = '', " 1848 .$DBFieldName.
"Precision = '' " 1849 .
"WHERE ResourceId = ".$ResourceId);
1851 # clear value locally 1852 $this->ValueCache[$DBFieldName.
"Begin"] = NULL;
1853 $this->ValueCache[$DBFieldName.
"End"] = NULL;
1854 $this->ValueCache[$DBFieldName.
"Precision"] = NULL;
1855 $UpdateModTime=TRUE;
1860 $OldValue = $this->
Get($Field);
1862 # if value to clear supplied 1863 if ($ValueToClear !== NULL)
1865 # if supplied value is array 1866 if (is_array($ValueToClear))
1868 # for each element of array 1869 foreach ($ValueToClear as $ClassificationId => $Dummy)
1871 if (array_key_exists($ClassificationId, $OldValue))
1873 # remove association with resource (if any) 1874 $this->RemoveAssociation(
"ResourceClassInts",
1878 $Class->RecalcResourceCount();
1879 $UpdateModTime=TRUE;
1885 if (array_key_exists($ValueToClear, $OldValue))
1887 # remove association with resource (if any) 1888 $this->RemoveAssociation(
"ResourceClassInts",
1892 $Class->RecalcResourceCount();
1893 $UpdateModTime=TRUE;
1899 if (count($OldValue)>0)
1901 # remove all associations for resource and field 1902 $this->RemoveAllAssociations(
1903 "ResourceClassInts",
"ClassificationId", $Field);
1905 # recompute resource count 1906 $Values = $this->
Get($Field);
1907 foreach ($Values as $ClassificationId => $Dummy)
1910 $Class->RecalcResourceCount();
1912 $UpdateModTime=TRUE;
1916 # clear our classification cache 1919 unset($this->ClassificationCache);
1925 $OldValue = $this->
Get($Field);
1926 # if value to clear supplied 1927 if ($ValueToClear !== NULL)
1929 # if incoming value is array 1930 if (is_array($ValueToClear))
1932 # for each element of array 1933 foreach ($ValueToClear as $ControlledNameId =>
1936 if (array_key_exists($ControlledNameId, $OldValue))
1938 # remove association with resource (if any) 1939 $this->RemoveAssociation(
"ResourceNameInts",
1942 $UpdateModTime=TRUE;
1948 if (array_key_exists($ValueToClear, $OldValue))
1950 # remove association with resource (if any) 1951 $this->RemoveAssociation(
"ResourceNameInts",
1954 $UpdateModTime=TRUE;
1960 if (count($OldValue)>0)
1962 # remove all associations for resource and field 1963 $this->RemoveAllAssociations(
1964 "ResourceNameInts",
"ControlledNameId", $Field);
1965 $UpdateModTime=TRUE;
1971 # clear our controlled name cache 1972 unset($this->ControlledNameCache);
1973 unset($this->ControlledNameVariantCache);
1978 $OldValue = $this->
Get($Field);
1980 # if value to clear supplied 1981 if ($ValueToClear !== NULL)
1983 # if incoming value is array 1984 if (is_array($ValueToClear))
1986 # for each element of array 1987 foreach ($ValueToClear as $UserId => $User)
1989 if (array_key_exists($UserId, $OldValue))
1991 # remove association with resource (if any) 1992 $this->RemoveAssociation(
"ResourceUserInts",
1996 $UpdateModTime=TRUE;
2002 if (array_key_exists($ValueToClear, $OldValue))
2004 # remove association with resource (if any) 2005 $this->RemoveAssociation(
"ResourceUserInts",
2009 $UpdateModTime=TRUE;
2015 if (count($OldValue)>0)
2017 # remove all associations for resource and field 2018 $this->RemoveAllAssociations(
2019 "ResourceUserInts",
"UserId", $Field);
2020 $UpdateModTime=TRUE;
2027 # if value to clear supplied 2028 if ($ValueToClear !== NULL)
2030 # convert value to array if necessary 2031 $Files = $ValueToClear;
2032 if (!is_array($Files)) { $Files = array($Files); }
2034 # convert values to objects if necessary 2035 foreach ($Files as $Index => $File)
2037 if (!is_object($File))
2039 $Files[$Index] =
new File($File);
2045 # use all files associated with resource 2046 $Files = $this->
Get($Field, TRUE);
2050 foreach ($Files as $File) { $File->Delete(); }
2054 # if value to clear supplied 2055 if ($ValueToClear !== NULL)
2057 # convert value to array if necessary 2058 $Images = $ValueToClear;
2059 if (!is_array($Images)) { $Images = array($Images); }
2061 # convert values to objects if necessary 2062 foreach ($Images as $Index => $Image)
2064 if (!is_object($Image))
2066 $Images[$Index] =
new SPTImage($Image);
2072 # use all images associated with resource 2073 $Images = $this->
Get($Field, TRUE);
2076 # delete images if we are the last resource referencing 2077 # a particular image. 2078 foreach ($Images as $Image)
2080 $Cnt = $this->DB->Query(
2081 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
2082 "ImageId=".$Image->Id(),
"Cnt");
2089 # clear cached image mappings 2092 # remove connections to images 2093 $UpdateModTime = $this->RemoveAssociation(
2094 "ResourceImageInts",
"ImageId", $Images, $Field);
2098 # remove references from the references table 2100 DELETE FROM ReferenceInts 2101 WHERE FieldId = '".addslashes($Field->Id()).
"' 2102 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
2107 exit(
"<br>SPT - ERROR: attempt to clear " 2108 .
"unknown resource field type<br>\n");
2114 # update modification timestamps 2116 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
2117 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 2118 .
"WHERE ResourceId=".$this->
Id.
" AND " 2119 .
"FieldId=".$Field->Id() );
2120 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 2121 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 2122 .$this->
Id.
",".$Field->Id().
"," 2123 .$UserId.
",NOW())");
2137 $this->
Clear($Field, $ValueToClear);
2140 # --- Field-Specific or Type-Specific Attribute Retrieval Methods ------- 2151 # start with empty array 2154 # for each controlled name 2155 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, " 2156 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, " 2157 .
"Classifications, MetadataFields " 2158 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" " 2159 .
"AND ResourceClassInts.ClassificationId = " 2160 .
"Classifications.ClassificationId " 2161 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
2162 while ($Record =
$DB->FetchRow())
2165 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
2166 $Record[
"ClassificationName"];
2169 # return array to caller 2174 # --- Ratings Methods --------------------------------------------------- 2182 return $this->CumulativeRating;
2207 # if number of ratings not already set 2210 # obtain number of ratings 2212 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings " 2213 .
"FROM ResourceRatings " 2214 .
"WHERE ResourceId = ".$this->
Id,
2218 # recalculate cumulative rating if it looks erroneous 2221 $this->UpdateCumulativeRating();
2225 # return number of ratings to caller 2226 return $this->NumberOfRatings;
2236 public function Rating($NewRating = NULL, $UserId = NULL)
2240 # if user ID not supplied 2241 if ($UserId == NULL)
2243 # if user is logged in 2245 if ($User->IsLoggedIn())
2247 # use ID of current user 2248 $UserId = $User->Get(
"UserId");
2252 # return NULL to caller 2257 # sanitize $NewRating 2258 if (!is_null($NewRating))
2260 $NewRating = intval($NewRating);
2263 # if there is a rating for resource and user 2264 $DB->Query(
"SELECT Rating FROM ResourceRatings " 2265 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2266 if ($Record =
$DB->FetchRow())
2268 # if new rating was supplied 2269 if ($NewRating != NULL)
2271 # update existing rating 2272 $DB->Query(
"UPDATE ResourceRatings " 2273 .
"SET Rating = ${NewRating}, DateRated = NOW() " 2274 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2276 # update cumulative rating value 2277 $this->UpdateCumulativeRating();
2279 # return value is new rating 2280 $Rating = $NewRating;
2284 # get rating value to return to caller 2285 $Rating = $Record[
"Rating"];
2290 # if new rating was supplied 2291 if ($NewRating != NULL)
2294 $DB->Query(
"INSERT INTO ResourceRatings " 2295 .
"(ResourceId, UserId, DateRated, Rating) " 2302 # update cumulative rating value 2303 $this->UpdateCumulativeRating();
2305 # return value is new rating 2306 $Rating = $NewRating;
2310 # return value is NULL 2315 # return rating value to caller 2320 # --- Resource Comment Methods ------------------------------------------ 2328 # read in comments if not already loaded 2331 $this->DB->Query(
"SELECT MessageId FROM Messages " 2332 .
"WHERE ParentId = ".$this->
Id 2333 .
" AND ParentType = 2 " 2334 .
"ORDER BY DatePosted DESC");
2335 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2341 # return array of comments to caller 2342 return $this->Comments;
2351 # obtain number of comments if not already set 2355 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments " 2357 .
"WHERE ParentId = ".$this->
Id 2358 .
" AND ParentType = 2",
2363 # return number of comments to caller 2364 return $this->NumberOfComments;
2368 # --- Permission Methods ------------------------------------------------- 2381 return $this->CheckSchemaPermissions($User,
"View", $AllowHooksToModify);
2392 return $this->CheckSchemaPermissions($User,
"Edit");
2403 return $this->CheckSchemaPermissions($User,
"Author");
2414 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit");
2415 return $this->$CheckFn($User);
2426 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"View");
2437 $FieldId = $this->
Schema()->StdNameToFieldMapping($MappedName);
2438 return ($FieldId === NULL) ? FALSE
2439 : $this->CheckFieldPermissions($User, $FieldId,
"View");
2450 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"Edit");
2461 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2473 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2475 return $this->$CheckFn($User, $FieldOrFieldName);
2478 # --- Utility Methods ---------------------------------------------------- 2488 $SearchEngine->QueueUpdateForItem($this);
2491 $Recommender->QueueUpdateForItem($this);
2502 # if schema IDs are not loaded 2503 if (!isset(self::$SchemaIdCache))
2507 $DB->Query(
"SELECT ResourceId, SchemaId FROM Resources");
2508 self::$SchemaIdCache =
$DB->FetchColumn(
"SchemaId",
"ResourceId");
2511 # if multiple resources specified 2512 if (is_array($ResourceId))
2514 # find schema IDs for specified resources 2515 $SchemaIds = array_intersect_key(self::$SchemaIdCache,
2516 array_flip($ResourceId));
2518 # check that specified resource IDs were all valid 2519 if (count($SchemaIds) < count($ResourceId))
2521 $BadIds = array_diff($ResourceId, array_keys($SchemaIds));
2522 throw new InvalidArgumentException(
"Unknown resource IDs (" 2523 .implode(
", ", $BadIds).
").");
2526 # return schema IDs to caller 2531 # check that specified resource was valid 2532 if (!isset(self::$SchemaIdCache[$ResourceId]))
2534 throw new InvalidArgumentException(
"Unknown resource ID (" 2538 # return schema IDs for specified resource 2539 return self::$SchemaIdCache[$ResourceId];
2544 # ---- PRIVATE INTERFACE ------------------------------------------------- 2546 private $ClassificationCache;
2548 private $ControlledNameCache;
2549 private $ControlledNameVariantCache;
2550 private $CumulativeRating;
2551 private $NumberOfComments;
2552 private $NumberOfRatings;
2553 private $PermissionCache;
2556 static private $Schemas;
2557 static private $SchemaIdCache;
2569 private function CheckSchemaPermissions($User, $CheckType, $AllowHooksToModify=TRUE)
2571 # construct a key to use for our permissions cache 2572 $CacheKey =
"UserCan".$CheckType.$User->Id();
2574 # if we don't have a cached value for this perm, compute one 2575 if (!isset($this->PermissionCache[$CacheKey]))
2577 # get privileges for schema 2578 $PermsFn = $CheckType.
"ingPrivileges";
2579 $SchemaPrivs = $this->
Schema()->$PermsFn();
2581 # check passes if user privileges are greater than resource set 2582 $CheckResult = $SchemaPrivs->MeetsRequirements($User, $this);
2584 # save the result of this check in our cache 2585 $this->PermissionCache[$CacheKey] = $CheckResult;
2588 $Value = $this->PermissionCache[$CacheKey];
2590 if ($AllowHooksToModify)
2592 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2593 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2595 "Resource" => $this,
2597 "Can".$CheckType => $Value,
2598 "Schema" => $this->
Schema(), ));
2600 $Value = $SignalResult[
"Can".$CheckType];
2614 private function CheckFieldPermissions($User, $Field, $CheckType)
2616 # get field object (if not supplied) 2621 $Field = $this->
Schema()->GetField($Field);
2623 catch (InvalidArgumentException $Exception)
2625 # (user cannot view/author/edit if field was invalid) 2630 # construct a key to use for our permissions cache 2631 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2633 # if we don't have a cahced value, compute one 2634 if (!isset($this->PermissionCache[$CacheKey]))
2636 # if field is enabled and editable, do permission check 2637 if ($Field->Enabled() &&
2638 ($CheckType ==
"View" || $Field->Editable()))
2640 # be sure schema privs allow View/Edit/Author for this resource 2641 $SchemaCheckFn =
"UserCan".$CheckType;
2642 if ($this->$SchemaCheckFn($User))
2644 # get appropriate privilege set for field 2645 $PermsFn = $CheckType.
"ingPrivileges";
2646 $FieldPrivs = $Field->$PermsFn();
2648 # user can View/Edit/Author if privileges are greater than field set 2649 $CheckResult = $FieldPrivs->MeetsRequirements($User, $this);
2653 $CheckResult = FALSE;
2658 $CheckResult = FALSE;
2661 # allow plugins to modify result of permission check 2662 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2663 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2665 "Resource" => $this,
2667 "Can".$CheckType => $CheckResult));
2668 $CheckResult = $SignalResult[
"Can".$CheckType];
2670 # save the result of this check in our cache 2671 $this->PermissionCache[$CacheKey] = $CheckResult;
2674 # return cached permission value 2675 return $this->PermissionCache[$CacheKey];
2681 private function UpdateCumulativeRating()
2683 # grab totals from DB 2684 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, " 2685 .
"SUM(Rating) AS Total FROM ResourceRatings " 2686 .
"WHERE ResourceId = ".$this->
Id);
2687 $Record = $this->DB->FetchRow();
2689 # calculate new cumulative rating 2692 # save new cumulative rating in DB 2693 $this->DB->Query(
"UPDATE Resources " 2695 .
"WHERE ResourceId = ".$this->Id);
2709 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2711 # We should ignore duplicate key errors when doing inserts: 2712 $this->DB->SetQueryErrorsToIgnore( array(
2713 "/INSERT INTO ".$TableName.
"/" =>
2714 "/Duplicate entry '-?[0-9]+-[0-9]+(-[0-9]+)?' for key/"));
2716 # start out assuming no association will be added 2717 $AssociationAdded = FALSE;
2719 # convert new value to array if necessary 2720 $Values = is_array($Value) ? $Value : array($Value);
2722 # for each new value 2723 foreach ($Values as $Value)
2725 # retrieve ID from value if necessary 2726 if (is_object($Value)) { $Value = $Value->Id(); }
2728 # Try to insert a new entry for this association. 2729 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET" 2730 .
" ResourceId = ".intval($this->
Id)
2731 .
", ".$FieldName.
" = ".intval($Value)
2732 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2734 # If the insert ran without a duplicate key error, 2735 # then we added an assocation: 2736 if ($this->DB->IgnoredError() === FALSE)
2738 $AssociationAdded = TRUE;
2742 # Clear ignored errors: 2743 $this->DB->SetQueryErrorsToIgnore( NULL );
2745 # report to caller whether association was added 2746 return $AssociationAdded;
2760 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2762 # start out assuming no association will be removed 2763 $AssociationRemoved = FALSE;
2765 # convert value to array if necessary 2766 $Values = is_array($Value) ? $Value : array($Value);
2769 foreach ($Values as $Value)
2771 # retrieve ID from value if necessary 2772 if (is_object($Value)) { $Value = $Value->Id(); }
2774 # remove any intersections with target ID from DB 2775 $this->DB->Query(
"DELETE FROM ".$TableName
2776 .
" WHERE ResourceId = ".intval($this->
Id)
2777 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2778 .
" AND ".$FieldName.
" = ".intval($Value));
2779 if ($this->DB->NumRowsAffected()) { $AssociationRemoved = TRUE; }
2782 # report to caller whether association was added 2783 return $AssociationRemoved;
2792 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2794 # retrieve list of entries for this field and resource 2795 $Entries = $this->
Get($Field);
2797 # divide them into chunks of not more than 100 2798 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2800 # remove assocations from this chunk 2801 $this->DB->Query(
"DELETE FROM ".$TableName
2802 .
" WHERE ResourceId = ".intval($this->
Id)
2803 .
" AND ".$TargetFieldName.
" IN " 2804 .
"(".implode(
",", array_keys($Chunk)).
")");
2816 if (!isset(self::$ItemIdColumnNames[$ClassName]))
2818 self::$ItemIdColumnNames[$ClassName] =
"ResourceId";
2819 self::$ItemNameColumnNames[$ClassName] = NULL;
2820 self::$ItemTableNames[$ClassName] =
"Resources";
GetByField($FieldNameOrObject, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Old method for retrieving values, deprecated in favor of Get().
UserCanView(User $User, $AllowHooksToModify=TRUE)
Determine if the given user can view the resource, e.g., on the full record page. ...
GetFilesForResource($ResourceOrResourceId, $ReturnObjects=TRUE)
Retrieve all files (names or objects) for specified resource.
GetImageUrls($FieldNameOrObject, $ImageSize=SPTImage::SIZE_FULL)
Get URLs for images, returning CleanURLs when possible and direct paths to image files otherwise...
SetQualifier($FieldName, $NewValue)
Set qualifier using field name.
UserCanViewMappedField($User, $MappedName)
Check whether user can view specified standard (mapped) metadata field.
Abstraction for forum messages and resource comments.
SQL database abstraction object with smart query caching.
UserCanModifyField($User, $FieldOrFieldName)
Check whether user is allowed to modify (Edit for perm resources, Author for temp) specified metadata...
QueueSearchAndRecommenderUpdate()
Update search and recommender system DBs.
GetAsArray($IncludeDisabledFields=FALSE, $ReturnObjects=TRUE)
Retrieve all resource values as an array.
Id()
Retrieve numerical resource ID.
UserCanEditField($User, $FieldOrFieldName)
Check whether user is allowed to edit specified metadata field.
SetQualifierByField($Field, $NewValue)
Set qualifier using field object.
GetViewPageUrl()
Retrieve view page URL for this resource.
Rating($NewRating=NULL, $UserId=NULL)
Get/set rating by a specific user for resource.
NumberOfComments()
Get current number of comments for resource.
NumberOfRatings()
Get current number of ratings for resource.
GetQualifier($FieldName, $ReturnObject=TRUE)
Retrieve qualifier by field name.
Factory object for Folder class, used to retrieve and manage Folders and groups of Folders...
Copy($FileToCopy)
Create copy of File and return to caller.
Schema()
Get MetadataSchema for resource.
Metadata type representing non-hierarchical controlled vocabulary values.
UserCanEdit($User)
Determine if the given user can edit the resource.
GetForDisplay($FieldNameOrObject, $ReturnObject=TRUE, $IncludeVariants=FALSE)
Retrieve value using field name or field object, signaling EVENT_FIELD_DISPLAY_FILTER to allow other ...
Comments()
Get comments for resource.
UpdateAutoupdateFields($UpdateType, $User=NULL)
Update the auto-updated fields as necessary.
CWIS-specific user factory class.
Get($Field, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field name or field object.
static GetSchemaForResource($ResourceId)
Get schema ID for specified resource(s).
Factory for manipulating File objects.
Common base class for persistent items store in database.
GetQualifierByFieldId($FieldId, $ReturnObject=TRUE)
Retrieve qualifier by field ID.
Encapsulates a full-size, preview, and thumbnail image.
UserCanAuthorField($User, $FieldOrFieldName)
Check whether user is allowed to author specified metadata field.
Clear($Field, $ValueToClear=NULL)
Clear field value.
UserCanModify($User)
Check if the user is allowed to modify (Edit for perm resources, Author for temp) a specified resourc...
UserCanAuthor($User)
Determine if the given user can edit the resource.
GetByFieldId($FieldId, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field ID.
IsTempResource($NewSetting=NULL)
Get/set whether resource is a temporary record.
SetByField($Field, $NewValue)
Method replaced by Resource::Set(), preserved for backward compatibility.
const STATUS_OK
Successful execution.
__construct($ResourceId)
Object constructor for loading an existing resource.
GetMapped($MappedName, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using standard (mapped) field name.
static SetDatabaseAccessValues($ClassName)
Set the database access values (table name, ID column name, name column name) for specified class...
Represents a "resource" in CWIS.
GetQualifierByField($Field, $ReturnObject=TRUE)
Retrieve qualifier by Field object.
ClearByFieldId($FieldId, $ValueToClear=NULL)
Clear field value specified by field ID.
SetQualifierByFieldId($FieldId, $NewValue)
Set qualifier using field ID.
static ClearImageSymlinksForResource($ResourceId, $FieldId)
Remove symlinks used for to cache image mappings.
SchemaId()
Retrieve ID of schema for resource.
ScaledCumulativeRating()
Return cumulative rating scaled to 1/10th.
Set($Field, $NewValue, $Reset=FALSE)
Set value using field name or field object.
static Create($SchemaId)
Create a new resource.
UserCanViewField($User, $FieldOrFieldName)
Check whether user is allowed to view specified metadata field.
Metadata type representing hierarchical ("Tree") controlled vocabulary values.
SetByFieldId($FieldId, $NewValue)
Set field value using field ID.
Classifications()
Get 2D array of classifications associated with resource.
ClearByField($Field, $ValueToClear=NULL)
Clear field value.
Class representing a stored (usually uploaded) file.
Factory for Resource objects.
CWIS-specific user class.
CumulativeRating()
Get cumulative rating (range is usually 0-100)
FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
Determine if the value for a field is set.
Delete()
Remove resource (and accompanying associations) from database and delete any associated files...