5 # Part of the Collection Workflow Integration System (CWIS)
6 # Copyright 2011-2013 Edward Almasy and Internet Scout Research Group
7 # http://scout.wisc.edu/cwis/
15 # ---- PUBLIC INTERFACE --------------------------------------------------
28 $this->
Id = intval($ResourceId);
30 # locate resource in database
31 $this->DB->Query(
"SELECT * FROM Resources WHERE ResourceId = ".$this->
Id);
33 # if unable to locate resource
34 $Record = $this->DB->FetchRow();
37 # set status to -1 to indicate that creation failed
38 $this->LastStatus = -1;
42 # load in attributes from database
43 $this->DBFields = $Record;
46 # load our local metadata schema
49 # set status to 1 to indicate that creation succeeded
50 $this->LastStatus = 1;
61 # clean out any temp resource records more than three days old
63 $RFactory->CleanOutStaleTempItems(60 * 24 * 3);
65 # lock DB tables to prevent next ID from being grabbed
67 $DB->Query(
"LOCK TABLES Resources WRITE");
69 # find next temp resource ID
70 $Id = $RFactory->GetNextTempItemId();
72 # write out new resource record with temp resource ID
73 # Set DateLastModified = NOW() to avoid being pruned as a
74 # stale temp resource.
76 "INSERT INTO Resources
77 SET `ResourceId` = '".intval($Id).
"',
78 `SchemaId` = '".intval($SchemaId).
"',
79 `DateLastModified` = NOW() " );
82 $DB->Query(
"UNLOCK TABLES");
84 # create new Resource object
87 # set some additional fields for default resources
90 $Resource->Set(
"Added By Id", $GLOBALS[
"G_User"]->
Id());
91 $Resource->Set(
"Last Modified By Id", $GLOBALS[
"G_User"]->
Id());
92 $Resource->Set(
"Date Of Record Creation", date(
"Y-m-d H:i:s"));
93 $Resource->Set(
"Date Last Modified", date(
"Y-m-d H:i:s"));
96 # set any default values
103 foreach ($Fields as $Field)
105 $DefaultValue = $Field->DefaultValue();
107 # flip option default values to get into the form that
108 # Resource::Set() expects
110 && is_array($DefaultValue))
112 $DefaultValue = array_flip($DefaultValue);
115 if (!empty($DefaultValue))
116 $Resource->SetByField($Field, $DefaultValue);
119 # update timestamps as required
121 foreach ($TimestampFields as $Field)
123 if ($Field->UpdateMethod() ==
126 $Resource->SetByField($Field,
"now");
130 # signal resource creation
131 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_CREATE", array(
132 "Resource" => $Resource,
135 # return new Resource object to caller
147 # signal that resource deletion is about to occur
149 $AF->SignalEvent(
"EVENT_RESOURCE_DELETE", array(
153 # grab list of classifications
156 # delete resource/classification intersections
158 $DB->Query(
"DELETE FROM ResourceClassInts WHERE ResourceId = ".$this->
Id());
160 # for each classification type
161 foreach ($Classifications as $ClassType => $ClassesOfType)
163 # for each classification of that type
164 foreach ($ClassesOfType as $ClassId => $ClassName)
166 # recalculate resource count for classification
168 $Class->RecalcResourceCount();
172 # delete resource references
174 DELETE FROM ReferenceInts
175 WHERE SrcResourceId = '".addslashes($this->
Id()).
"'
176 OR DstResourceId = '".addslashes($this->
Id()).
"'");
178 # delete resource/name intersections
179 $DB->Query(
"DELETE FROM ResourceNameInts WHERE ResourceId = ".$this->
Id());
181 # delete any associated images not in use by other resources
182 $DB->Query(
"SELECT ImageId FROM ResourceImageInts"
183 .
" WHERE ResourceId = ".intval($this->
Id()));
184 $ImageIds = $DB->FetchColumn(
"ImageId");
185 foreach ($ImageIds as $ImageId)
187 $DB->Query(
"SELECT ResourceId FROM ResourceImageInts"
188 .
" WHERE ImageId = ".intval($ImageId)
189 .
" AND ResourceId != ".intval($this->
Id()));
190 if ($DB->NumRowsSelected() == 0)
197 # delete any associated files
199 $Files = $Factory->GetFilesForResource($this->
Id());
200 foreach ($Files as $File)
205 # delete resource record from database
206 $DB->Query(
"DELETE FROM Resources WHERE ResourceId = ".$this->
Id());
208 # drop item from search engine and recommender system
209 if ($SysConfig->SearchDBEnabled())
212 $SearchEngine->DropItem($this->
Id());
214 if ($SysConfig->RecommenderDBEnabled())
217 $Recommender->DropItem($this->
Id());
220 # get the folders containing the resource
222 $Folders = $FolderFactory->GetFoldersContainingItem(
226 # drop the resource from each folder it belongs to
227 foreach ($Folders as $Folder)
229 # mixed item type folder
230 if ($Folder->ContainsItem($this->Id,
"Resource"))
232 $Folder->RemoveItem($this->
Id,
"Resource");
235 # single item type folder
238 $Folder->RemoveItem($this->
Id);
242 # delete any resource comments
243 $DB->Query(
"DELETE FROM Messages WHERE ParentId = ".$this->
Id);
250 function Status() {
return $this->LastStatus; }
256 function Id() {
return $this->Id; }
262 function SchemaId() {
return $this->DBFields[
"SchemaId"]; }
272 # if new temp resource setting supplied
273 if (!is_null($NewSetting))
275 # if caller requested to switch
277 if ((($this->
Id() < 0) && ($NewSetting == FALSE))
278 || (($this->
Id() >= 0) && ($NewSetting == TRUE)))
280 # lock DB tables to prevent next ID from being grabbed
281 $DB->Query(
"LOCK TABLES Resources write");
283 # get next resource ID as appropriate
284 $OldResourceId = $this->Id;
286 if ($NewSetting == TRUE)
288 $this->
Id = $Factory->GetNextTempItemId();
292 $this->
Id = $Factory->GetNextItemId();
296 $DB->Query(
"UPDATE Resources SET ResourceId = ".
297 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
300 $DB->Query(
"UNLOCK TABLES");
302 # change associations
303 unset($this->ClassificationCache);
304 $DB->Query(
"UPDATE ResourceClassInts SET ResourceId = ".
305 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
306 unset($this->ControlledNameCache);
307 unset($this->ControlledNameVariantCache);
308 $DB->Query(
"UPDATE ResourceNameInts SET ResourceId = ".
309 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
310 $DB->Query(
"UPDATE Files SET ResourceId = ".
311 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
312 $DB->Query(
"UPDATE ReferenceInts SET SrcResourceId = ".
313 $this->
Id.
" WHERE SrcResourceId = ".$OldResourceId);
314 $DB->Query(
"UPDATE ResourceImageInts SET ResourceId = ".
315 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
317 # signal event as appropriate
318 if ($NewSetting === FALSE)
320 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_ADD", array(
327 # report to caller whether we are a temp resource
328 return ($this->
Id() < 0) ? TRUE : FALSE;
332 # --- Generic Attribute Retrieval Methods -------------------------------
348 function Get($FieldNameOrObject, $ReturnObject = FALSE, $IncludeVariants = FALSE)
350 # load field object if needed
351 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
352 : $this->Schema->GetFieldByName($FieldNameOrObject);
354 # return no value found if we don't have a valid field
357 # grab database field name
358 $DBFieldName = $Field->DBFieldName();
360 # format return value based on field type
361 switch ($Field->Type())
366 $ReturnValue = isset($this->DBFields[$DBFieldName])
367 ? (string)$this->DBFields[$DBFieldName] : NULL;
371 $ReturnValue = isset($this->DBFields[$DBFieldName])
372 ? (int)$this->DBFields[$DBFieldName] : NULL;
376 $ReturnValue = isset($this->DBFields[$DBFieldName])
377 ? (bool)$this->DBFields[$DBFieldName] : NULL;
381 $ReturnValue = array(
"X" => (
float)$this->DBFields[$DBFieldName.
"X"],
382 "Y" => (
float)$this->DBFields[$DBFieldName.
"Y"]);
386 $Date =
new Date($this->DBFields[$DBFieldName.
"Begin"],
387 $this->DBFields[$DBFieldName.
"End"],
388 $this->DBFields[$DBFieldName.
"Precision"]);
391 $ReturnValue = $Date;
395 $ReturnValue = $Date->Formatted();
400 $ReturnValue = $this->DBFields[$DBFieldName];
404 # start with empty array
405 $ReturnValue = array();
407 # if classification cache has not been loaded
408 if (!isset($this->ClassificationCache))
410 # load all classifications associated with this resource into cache
411 $this->ClassificationCache = array();
413 "SELECT Classifications.ClassificationId,"
414 .
" Classifications.FieldId,ClassificationName"
415 .
" FROM ResourceClassInts, Classifications"
416 .
" WHERE ResourceClassInts.ResourceId = ".$this->
Id
417 .
" AND ResourceClassInts.ClassificationId"
418 .
" = Classifications.ClassificationId");
419 while ($Record = $this->DB->FetchRow())
421 $this->ClassificationCache[$Record[
"ClassificationId"]][
"Name"] =
422 $Record[
"ClassificationName"];
423 $this->ClassificationCache[$Record[
"ClassificationId"]][
"FieldId"] =
428 # for each entry in classification cache
429 foreach ($this->ClassificationCache as $ClassificationId => $ClassificationInfo)
431 # if classification ID matches field we are looking for
432 if ($ClassificationInfo[
"FieldId"] == $Field->Id())
434 # add field to result
437 $ReturnValue[$ClassificationId] =
new Classification($ClassificationId);
441 $ReturnValue[$ClassificationId] = $ClassificationInfo[
"Name"];
449 # start with empty array
450 $ReturnValue = array();
452 # if controlled name cache has not been loaded
453 if (!isset($this->ControlledNameCache))
455 # load all controlled names associated with this resource into cache
456 $this->ControlledNameCache = array();
458 "SELECT ControlledNames.ControlledNameId,"
459 .
" ControlledNames.FieldId,ControlledName"
460 .
" FROM ResourceNameInts, ControlledNames"
461 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id
462 .
" AND ResourceNameInts.ControlledNameId"
463 .
" = ControlledNames.ControlledNameId"
464 .
" ORDER BY ControlledNames.ControlledName ASC");
465 while ($Record = $this->DB->FetchRow())
467 $this->ControlledNameCache[$Record[
"ControlledNameId"]][
"Name"] = $Record[
"ControlledName"];
468 $this->ControlledNameCache[$Record[
"ControlledNameId"]][
"FieldId"] = $Record[
"FieldId"];
472 # if variant names requested and variant name cache has not been loaded
473 if ($IncludeVariants && !isset($this->ControlledNameVariantCache))
475 # load all controlled names associated with this resource into cache
476 $this->ControlledNameVariantCache = array();
477 $this->DB->Query(
"SELECT ControlledNames.ControlledNameId,"
478 .
" ControlledNames.FieldId,"
479 .
" ControlledName, VariantName"
480 .
" FROM ResourceNameInts, ControlledNames, VariantNames"
481 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id
482 .
" AND ResourceNameInts.ControlledNameId"
483 .
" = ControlledNames.ControlledNameId"
484 .
" AND VariantNames.ControlledNameId"
485 .
" = ControlledNames.ControlledNameId");
486 while ($Record = $this->DB->FetchRow())
488 $this->ControlledNameVariantCache[$Record[
"ControlledNameId"]][]
489 = $Record[
"VariantName"];
493 # for each entry in controlled name cache
494 foreach ($this->ControlledNameCache as $ControlledNameId => $ControlledNameInfo)
496 # if controlled name type matches field we are looking for
497 if ($ControlledNameInfo[
"FieldId"] == $Field->Id())
499 # if objects requested
502 $ReturnValue[$ControlledNameId] =
507 # if variant names requested
508 if ($IncludeVariants)
510 # add field to result
511 $ReturnValue[] = $ControlledNameInfo[
"Name"];
513 # add any variant names to result
514 if (isset($this->ControlledNameVariantCache[$ControlledNameId]))
516 $ReturnValue = array_merge(
518 $this->ControlledNameVariantCache[$ControlledNameId]);
523 # add field with index to result
524 $ReturnValue[$ControlledNameId] =
525 $ControlledNameInfo[
"Name"];
533 $User =
new CWUser(intval($this->DBFields[$DBFieldName]));
536 $ReturnValue = $User;
540 $ReturnValue = $User->Get(
"UserName");
545 # start out assuming no images will be found
546 $ReturnValue = array();
548 # find all images associated with this resource
549 $this->DB->Query(
"SELECT ImageId FROM ResourceImageInts"
550 .
" WHERE ResourceId = ".intval($this->
Id())
551 .
" AND FieldId = ".intval($Field->Id()));
553 # if images were found
554 if ($this->DB->NumRowsSelected())
556 # if we are to return an object
557 $ImageIds = $this->DB->FetchColumn(
"ImageId");
560 # load array of Image objects for return value
561 foreach ($ImageIds as $ImageId)
563 $ReturnValue[$ImageId] =
new SPTImage($ImageId);
568 # load array of Image ids for return value
569 $ReturnValue = $ImageIds;
575 # retrieve files using factory
578 $this->
Id, $ReturnObject);
582 # query for resource references
584 SELECT * FROM ReferenceInts
585 WHERE FieldId = '".addslashes($Field->Id()).
"'
586 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
588 $ReturnValue = array();
590 # return each reference as a Resource object
593 $FoundErrors = FALSE;
595 while (FALSE !== ($Record = $this->DB->FetchRow()))
597 $ReferenceId = $Record[
"DstResourceId"];
598 $Reference =
new Resource($ReferenceId);
600 # the reference is bad, so flag that there were errors
601 if ($Reference->Status() != 1)
608 $ReturnValue[$ReferenceId] = $Reference;
612 # try to fix the errors by removing any references to
613 # resources that were bad
616 $this->
Set($Field, $ReturnValue);
620 # return each reference as a resource ID
623 while (FALSE !== ($Record = $this->DB->FetchRow()))
625 $ReferenceId = $Record[
"DstResourceId"];
626 $ReturnValue[$ReferenceId] = $ReferenceId;
633 exit(
"<br>SPT - ERROR: attempt to retrieve unknown resource field type (".$Field->Type().
")<br>\n");
637 # return formatted value to caller
645 $ReturnObject = FALSE, $IncludeVariants = FALSE)
646 {
return $this->
Get($FieldNameOrObject, $ReturnObject, $IncludeVariants); }
661 function GetByFieldId($FieldId, $ReturnObject = FALSE, $IncludeVariants = FALSE)
663 $Field = $this->Schema->GetField($FieldId);
664 return ($Field) ? $this->
Get($Field, $ReturnObject, $IncludeVariants) : NULL;
679 function GetAsArray($IncludeDisabledFields = FALSE, $ReturnObjects = TRUE)
681 # retrieve field info
682 $Fields = $this->Schema->GetFields();
685 foreach ($Fields as $Field)
687 # if field is enabled or caller requested disabled fields
688 if ($Field->Enabled() || $IncludeDisabledFields)
690 # retrieve info and add it to the array
691 $FieldStrings[$Field->Name()] = $this->
Get($Field, $ReturnObjects);
693 # if field uses qualifiers
694 if ($Field->UsesQualifiers())
696 # get qualifier attributes and add to the array
697 $FieldStrings[$Field->Name().
" Qualifier"] =
703 # add in internal values
704 $FieldStrings[
"ResourceId"] = $this->
Id();
707 # return array to caller
708 return $FieldStrings;
725 function GetMapped($MappedName, $ReturnObject = FALSE, $IncludeVariants = FALSE)
727 return $this->Schema->StdNameToFieldMapping($MappedName)
728 ? $this->
GetByFieldId($this->Schema->StdNameToFieldMapping($MappedName),
729 $ReturnObject, $IncludeVariants)
743 $Field = $this->Schema->GetFieldByName($FieldName);
757 $Field = $this->Schema->GetField($FieldId);
771 # return NULL if field is invalid
774 # assume no qualifiers if not otherwise determined
777 # if field uses qualifiers
778 if ($Field->UsesQualifiers())
780 # retrieve qualifiers based on field type
781 switch ($Field->Type())
786 # retrieve list of items
789 # if field uses item-level qualifiers
790 if ($Field->HasItemLevelQualifiers())
792 # determine general item name in DB
794 ?
"Classification" :
"ControlledName";
797 foreach (
$Items as $ItemId => $ItemName)
799 # look up qualifier for item
800 $QualId = $this->DB->Query(
801 "SELECT * FROM ".$TableName.
"s"
802 .
" WHERE ".$TableName.
"Id = ".$ItemId,
808 # if object was requested by caller
811 # load qualifier and add to return value array
812 $ReturnValue[$ItemId] =
new Qualifier($QualId);
816 # add qualifier ID to return value array
817 $ReturnValue[$ItemId] = $QualId;
822 # add NULL to return value array for this item
823 $ReturnValue[$ItemId] = NULL;
830 foreach (
$Items as $ItemId => $ItemName)
832 # if object was requested by caller
835 # load default qualifier and add to return value array
836 $ReturnValue[$ItemId] =
new Qualifier($Field->DefaultQualifier());
840 # add default qualifier ID to return value array
841 $ReturnValue[$ItemId] = $Field->DefaultQualifier();
848 # if field uses item-level qualifiers
849 if ($Field->HasItemLevelQualifiers())
851 # if qualifier available
852 if ($this->DBFields[$Field->DBFieldName().
"Qualifier"] > 0)
854 # if object was requested by caller
857 # return qualifier for field
858 $ReturnValue =
new Qualifier($this->DBFields[$Field->DBFieldName().
"Qualifier"]);
862 # return qualifier ID for field
863 $ReturnValue = $this->DBFields[$Field->DBFieldName().
"Qualifier"];
869 # if default qualifier available
870 if ($Field->DefaultQualifier() > 0)
872 # if object was requested by caller
875 # return default qualifier
876 $ReturnValue =
new Qualifier($Field->DefaultQualifier());
880 # return default qualifier ID
881 $ReturnValue = $Field->DefaultQualifier();
889 # return qualifier object or ID (or array of same) to caller
900 function FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
902 # load field object if needed
903 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
904 : $this->Schema->GetFieldByName($FieldNameOrObject);
906 # return no value found if we don't have a valid field
910 $Value = $this->
Get($Field);
912 # checks depend on the field type
913 switch ($Field->Type())
921 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
928 return isset($Value[
"X"])
929 && isset($Value[
"Y"])
930 && strlen(trim($Value[
"X"]))
931 && strlen(trim($Value[
"Y"]));
935 && strlen(trim($Value))
936 && $Value !=
"0000-00-00";
940 && strlen(trim($Value))
941 && $Value !=
"0000-00-00 00:00:00";
949 return count($Value) > 0;
955 && $Factory->UserNameExists($Value);
962 # --- Generic Attribute Setting Methods ---------------------------------
972 function Set($FieldNameOrObject, $NewValue, $Reset=FALSE)
974 # load field object if needed
975 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
976 : $this->Schema->GetFieldByName($FieldNameOrObject);
978 # return if we don't have a valid field
981 # grab commonly-used values for local use
983 $ResourceId = $this->Id;
985 # grab database field name
986 $DBFieldName = $Field->DBFieldName();
988 # Flag to deterimine if we've actually changed anything.
989 $UpdateModTime = FALSE;
991 # store value in DB based on field type
992 switch ($Field->Type())
997 if ($this->DBFields[$DBFieldName] != $NewValue)
999 # save value directly to DB
1000 $DB->Query(
"UPDATE Resources SET `"
1001 .$DBFieldName.
"` = '".addslashes($NewValue).
"' "
1002 .
"WHERE ResourceId = ".$ResourceId);
1004 # save value locally
1005 $this->DBFields[$DBFieldName] = $NewValue;
1006 $UpdateModTime=TRUE;
1011 if ( $this->DBFields[$DBFieldName] != $NewValue )
1013 # save value directly to DB
1014 if (is_null($NewValue))
1016 $DB->Query(
"UPDATE Resources SET `"
1017 .$DBFieldName.
"` = NULL"
1018 .
" WHERE ResourceId = ".$ResourceId);
1022 $DB->Query(
"UPDATE Resources SET `"
1023 .$DBFieldName.
"` = ".intval($NewValue)
1024 .
" WHERE ResourceId = ".$ResourceId);
1027 # save value locally
1028 $this->DBFields[$DBFieldName] = $NewValue;
1029 $UpdateModTime = TRUE;
1035 if ($this->DBFields[$DBFieldName.
"X"] != $NewValue[
"X"] ||
1036 $this->DBFields[$DBFieldName.
"Y"] != $NewValue[
"Y"] )
1038 if (is_null($NewValue))
1040 $DB->Query(
"UPDATE Resources SET "
1041 .
"`".$DBFieldName.
"X` = NULL, "
1042 .
"`".$DBFieldName.
"Y` = NULL "
1043 .
"WHERE ResourceId = ".$ResourceId);
1044 $this->DBFields[$DBFieldName.
"X"] = NULL;
1045 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1049 $DB->Query(
"UPDATE Resources SET "
1050 .
"`".$DBFieldName.
"X` = ".(strlen($NewValue[
"X"])
1051 ?
"'".$NewValue[
"X"].
"'" :
"NULL").
", "
1052 .
"`".$DBFieldName.
"Y` = ".(strlen($NewValue[
"Y"])
1053 ?
"'".$NewValue[
"Y"].
"'" :
"NULL")
1054 .
" WHERE ResourceId = ".$ResourceId);
1056 $Digits = $Field->PointDecimalDigits();
1058 $this->DBFields[$DBFieldName.
"X"] =
1059 strlen($NewValue[
"X"]) ? round($NewValue[
"X"], $Digits) : NULL;
1060 $this->DBFields[$DBFieldName.
"Y"] =
1061 strlen($NewValue[
"Y"]) ? round($NewValue[
"Y"], $Digits) : NULL;
1063 $UpdateModTime = TRUE;
1068 if ($this->DBFields[$DBFieldName] != $NewValue)
1070 # save value directly to DB
1071 if (is_null($NewValue))
1073 $DB->Query(
"UPDATE Resources SET `"
1074 .$DBFieldName.
"` = NULL"
1075 .
" WHERE ResourceId = ".$ResourceId);
1079 $NewValue = $NewValue ?
"1" :
"0";
1080 $DB->Query(
"UPDATE Resources SET `"
1081 .$DBFieldName.
"` = ".$NewValue
1082 .
" WHERE ResourceId = ".$ResourceId);
1085 $this->DBFields[$DBFieldName] = $NewValue;
1087 # recalculate counts for any associated classifications if necessary
1088 if ($DBFieldName ==
"ReleaseFlag")
1090 $DB->Query(
"SELECT ClassificationId FROM ResourceClassInts"
1091 .
" WHERE ResourceId = ".$ResourceId);
1092 while ($ClassId = $DB->FetchField(
"ClassificationId"))
1095 $Class->RecalcResourceCount();
1098 $UpdateModTime = TRUE;
1103 # if value passed in was object
1104 if (is_object($NewValue))
1106 # retrieve user ID from object
1107 $UserId = $NewValue->Get(
"UserId");
1109 # else if value passed in was user name
1110 elseif (is_string($NewValue) && strlen($NewValue))
1112 # create user object and retrieve user ID from there
1113 $User =
new CWUser($NewValue);
1114 $UserId = $User->Get(
"UserId");
1118 # assume value is user ID and use value directly
1119 $UserId = $NewValue;
1122 if ($this->DBFields[$DBFieldName] != $UserId)
1124 # save value directly to DB
1125 $DB->Query(
"UPDATE Resources SET `"
1126 .$DBFieldName.
"` = '".$UserId.
"' "
1127 .
"WHERE ResourceId = ".$ResourceId);
1129 # save value locally
1130 $this->DBFields[$DBFieldName] = $UserId;
1131 $UpdateModTime = TRUE;
1136 # if we were given a date object
1137 if (is_object($NewValue))
1139 # use supplied date object
1144 # create date object
1145 $Date =
new Date($NewValue);
1148 $OldDate =
new Date(
1149 $this->DBFields[$DBFieldName.
"Begin"],
1150 $this->DBFields[$DBFieldName.
"End"]);
1152 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1153 $OldDate->EndDate() != $Date->EndDate() ||
1154 $OldDate->Precision() != $Date->Precision() )
1156 # extract values from date object and store in DB
1157 $BeginDate =
"'".$Date->BeginDate().
"'";
1158 if (strlen($BeginDate) < 3) { $BeginDate =
"NULL"; }
1159 $EndDate =
"'".$Date->EndDate().
"'";
1160 if (strlen($EndDate) < 3) { $EndDate =
"NULL"; }
1162 $DB->Query(
"UPDATE Resources SET "
1163 .$DBFieldName.
"Begin = ".$BeginDate.
", "
1164 .$DBFieldName.
"End = ".$EndDate.
", "
1165 .$DBFieldName.
"Precision = '".$Date->Precision().
"' "
1166 .
"WHERE ResourceId = ".$ResourceId);
1168 # save values locally
1169 $this->DBFields[$DBFieldName.
"Begin"] = $Date->BeginDate();
1170 $this->DBFields[$DBFieldName.
"End"] = $Date->EndDate();
1171 $this->DBFields[$DBFieldName.
"Precision"] = $Date->Precision();
1172 $UpdateModTime=TRUE;
1177 if (is_null($NewValue) || !strlen(trim($NewValue)))
1179 $DateValue = $NewValue;
1181 if (!is_null($this->DBFields[$DBFieldName]))
1183 # save value directly to DB
1184 $DB->Query(
"UPDATE Resources SET "
1185 .
"`".$DBFieldName.
"` = NULL "
1186 .
"WHERE ResourceId = ".$ResourceId);
1187 $UpdateModTime = TRUE;
1192 # assume value is date and use directly
1193 $TimestampValue = strtotime($NewValue);
1195 # use the new value if the date is valid
1196 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1198 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1200 if ($this->DBFields[$DBFieldName] != $DateValue)
1202 # save value directly to DB
1203 $DB->Query(
"UPDATE Resources SET "
1204 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' "
1205 .
"WHERE ResourceId = ".$ResourceId);
1206 $UpdateModTime=TRUE;
1210 # continue using the old value if invalid
1213 $DateValue = $this->
Get($Field);
1217 # save value locally
1218 $this->DBFields[$DBFieldName] = $DateValue;
1222 $OldValue = $this->
Get($Field);
1224 # if incoming value is array
1225 if (is_array($NewValue))
1227 if ($OldValue != $NewValue)
1231 # Remove values that were in the old value, but not the new one:
1232 $ToRemove = array_diff(array_keys($OldValue), array_keys($NewValue));
1233 foreach ($ToRemove as $ClassificationId)
1235 $this->RemoveAssociation(
"ResourceClassInts",
1240 $Class->RecalcResourceCount();
1244 # for each element of array
1245 foreach ($NewValue as
1246 $ClassificationId => $ClassificationName)
1251 # associate with resource if not already associated
1252 if ($this->AddAssociation(
"ResourceClassInts",
1254 $ClassificationId) )
1256 $Class->UpdateLastAssigned();
1257 $Class->RecalcResourceCount();
1262 $UpdateModTime=TRUE;
1267 # associate with resource if not already associated
1268 if (is_object($NewValue))
1271 $NewValue = $Class->Id();
1278 if (!array_key_exists($Class->Id(), $OldValue))
1281 $this->AddAssociation(
"ResourceClassInts",
1284 $Class->UpdateLastAssigned();
1285 $Class->RecalcResourceCount();
1286 $UpdateModTime=TRUE;
1290 # clear our classification cache
1293 unset($this->ClassificationCache);
1299 $OldValue = $this->
Get($Field);
1301 # Clear other values if this field expects unique options
1302 if ($Field->AllowMultiple() === FALSE)
1304 # If we're fed an array for a unique option,
1305 # just use the last element of the array
1306 if (is_array($NewValue)){
1307 $NewValue = array_pop($NewValue);
1310 if (!array_key_exists($NewValue, $OldValue))
1313 $this->RemoveAllAssociations(
"ResourceNameInts",
1316 $UpdateModTime=TRUE;
1320 # if incoming value is array
1321 if (is_array($NewValue) && ($Field->AllowMultiple() !== FALSE) )
1323 if ($OldValue != $NewValue)
1327 $ToRemove = array_diff(array_keys($OldValue), array_keys($NewValue));
1328 foreach ($ToRemove as $CNId)
1330 $this->RemoveAssociation(
"ResourceNameInts",
1336 # for each element of array
1337 foreach ($NewValue as $ControlledNameId => $ControlledName)
1339 # associate with resource if not already associated
1340 if ($this->AddAssociation(
"ResourceNameInts",
1345 $CN->UpdateLastAssigned();
1348 $UpdateModTime=TRUE;
1353 # associate with resource if not already associated
1354 if (is_object($NewValue)) { $NewValue = $NewValue->Id(); }
1355 if (!array_key_exists($NewValue, $OldValue))
1357 $this->AddAssociation(
"ResourceNameInts",
1360 $UpdateModTime=TRUE;
1366 # clear our controlled name cache
1367 unset($this->ControlledNameCache);
1368 unset($this->ControlledNameVariantCache);
1374 # associate value(s) with resource
1375 $this->AddAssociation(
1376 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1380 # convert incoming value to array if necessary
1381 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1383 # for each incoming file
1385 foreach ($NewValue as $File)
1388 $NewFile = $Factory->
Copy($File);
1390 # associate copy with this resource and field
1391 $NewFile->ResourceId($this->
Id);
1392 $NewFile->FieldId($Field->Id());
1394 # Since we make a fresh copy of the File whenever Set is called,
1395 # we'll always update the modification time for this field.
1396 $UpdateModTime = TRUE;
1400 # convert incoming value to array to simplify the workflow
1401 if (is_scalar($NewValue) || $NewValue instanceof
Resource)
1403 $NewValue = array($NewValue);
1406 # delete existing resource references
1409 # add each reference
1410 foreach ($NewValue as $ReferenceOrId)
1412 # initially issume it's a reference ID and not an object...
1413 $ReferenceId = $ReferenceOrId;
1415 # ... but get the reference ID if it's an object
1416 if ($ReferenceOrId instanceof
Resource)
1418 $ReferenceId = $ReferenceOrId->Id();
1421 # skip blank reference IDs
1422 if (strlen(trim($ReferenceId)) < 1)
1427 # skip reference IDs that don't look right
1428 if (!is_numeric($ReferenceId))
1433 # skip references to the current resource
1434 if ($ReferenceId == $this->
Id())
1439 # add the reference to the references table
1441 INSERT INTO ReferenceInts (
1446 ".addslashes($Field->Id()).
",
1447 ".addslashes($this->
Id()).
",
1448 ".addslashes($ReferenceId).
")");
1454 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1460 # update modification timestamps
1462 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1463 $DB->Query(
"DELETE FROM ResourceFieldTimestamps "
1464 .
"WHERE ResourceId=".$this->
Id.
" AND "
1465 .
"FieldId=".$Field->Id() );
1466 $DB->Query(
"INSERT INTO ResourceFieldTimestamps "
1467 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES ("
1468 .$this->
Id.
",".$Field->Id().
","
1469 .$UserId.
",NOW())");
1478 # set value by field ID
1481 $Field = $this->Schema->GetField($FieldId);
1482 $this->
Set($Field, $NewValue);
1485 # set qualifier by field name
1488 $Field = $this->Schema->GetFieldByName($FieldName);
1492 # set qualifier by field ID
1495 $Field = $this->Schema->GetField($FieldId);
1499 # set qualifier using field object
1502 # if field uses qualifiers and uses item-level qualifiers
1503 if ($Field->UsesQualifiers() && $Field->HasItemLevelQualifiers())
1505 # if qualifier object passed in
1506 if (is_object($NewValue))
1508 # grab qualifier ID from object
1509 $QualifierId = $NewValue->Id();
1513 # assume value passed in is qualifier ID
1514 $QualifierId = $NewValue;
1517 # update qualifier value in database
1518 $DBFieldName = $Field->DBFieldName();
1519 $this->DB->Query(
"UPDATE Resources SET "
1520 .$DBFieldName.
"Qualifier = '".$QualifierId.
"' "
1521 .
"WHERE ResourceId = ".$this->Id);
1523 # update local qualifier value
1524 $this->DBFields[$DBFieldName.
"Qualifier"] = $QualifierId;
1528 # clear value by field ID
1531 $Field = $this->Schema->GetField($FieldId);
1535 # clear value using field object
1536 function Clear($Field, $ValueToClear = NULL)
1538 # convert field name to object if necessary
1539 if (!is_object($Field))
1541 $Field = $this->Schema->GetFieldByName($Field);
1544 # grab commonly-used values for local use
1546 $ResourceId = $this->Id;
1548 # grab database field name
1549 $DBFieldName = $Field->DBFieldName();
1551 $UpdateModTime=FALSE;
1553 # store value in DB based on field type
1554 switch ($Field->Type())
1563 if (strlen($this->DBFields[$DBFieldName])>0)
1566 $DB->Query(
"UPDATE Resources SET `"
1567 .$DBFieldName.
"` = NULL "
1568 .
"WHERE ResourceId = ".$ResourceId);
1570 # clear value locally
1571 $this->DBFields[$DBFieldName] = NULL;
1572 $UpdateModTime=TRUE;
1577 if (!is_null($this->DBFields[$DBFieldName.
"X"]) ||
1578 !is_null($this->DBFields[$DBFieldName.
"Y"]) )
1581 $DB->Query(
"UPDATE Resources SET "
1582 .
"`".$DBFieldName.
"X` = NULL ,"
1583 .
"`".$DBFieldName.
"Y` = NULL "
1584 .
"WHERE ResourceId = ".$ResourceId);
1586 # Clear local values
1587 $this->DBFields[$DBFieldName.
"X"] = NULL;
1588 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1589 $UpdateModTime=TRUE;
1594 if (!is_null($this->DBFields[$DBFieldName.
"Begin"]) ||
1595 !is_null($this->DBFields[$DBFieldName.
"End"]) ||
1596 !is_null($this->DBFields[$DBFieldName.
"Precision"]))
1598 # clear date object values in DB
1599 $DB->Query(
"UPDATE Resources SET "
1600 .$DBFieldName.
"Begin = '', "
1601 .$DBFieldName.
"End = '', "
1602 .$DBFieldName.
"Precision = '' "
1603 .
"WHERE ResourceId = ".$ResourceId);
1605 # clear value locally
1606 $this->DBFields[$DBFieldName.
"Begin"] = NULL;
1607 $this->DBFields[$DBFieldName.
"End"] = NULL;
1608 $this->DBFields[$DBFieldName.
"Precision"] = NULL;
1609 $UpdateModTime=TRUE;
1614 $OldValue = $this->
Get($Field);
1616 # if value to clear supplied
1617 if ($ValueToClear !== NULL)
1619 # if supplied value is array
1620 if (is_array($ValueToClear))
1622 # for each element of array
1623 foreach ($ValueToClear as $ClassificationId => $Dummy)
1625 if (array_key_exists($ClassificationId, $OldValue))
1627 # remove association with resource (if any)
1628 $this->RemoveAssociation(
"ResourceClassInts",
1632 $Class->RecalcResourceCount();
1633 $UpdateModTime=TRUE;
1639 if (array_key_exists($ValueToClear, $OldValue))
1641 # remove association with resource (if any)
1642 $this->RemoveAssociation(
"ResourceClassInts",
1646 $Class->RecalcResourceCount();
1647 $UpdateModTime=TRUE;
1653 if (count($OldValue)>0)
1655 # remove all associations for resource and field
1656 $this->RemoveAllAssociations(
"ResourceClassInts",
"ClassificationId", $Field);
1658 # recompute resource count
1659 $Values = $this->
Get($Field);
1660 foreach ($Values as $ClassificationId => $Dummy)
1663 $Class->RecalcResourceCount();
1665 $UpdateModTime=TRUE;
1669 # clear our classification cache
1672 unset($this->ClassificationCache);
1678 $OldValue = $this->
Get($Field);
1679 # if value to clear supplied
1680 if ($ValueToClear !== NULL)
1682 # if incoming value is array
1683 if (is_array($ValueToClear))
1685 # for each element of array
1686 foreach ($ValueToClear as $ControlledNameId =>
1689 if (array_key_exists($ControlledNameId, $OldValue))
1691 # remove association with resource (if any)
1692 $this->RemoveAssociation(
"ResourceNameInts",
1695 $UpdateModTime=TRUE;
1701 if (array_key_exists($ValueToClear, $OldValue))
1703 # remove association with resource (if any)
1704 $this->RemoveAssociation(
"ResourceNameInts",
1707 $UpdateModTime=TRUE;
1713 if (count($OldValue)>0)
1715 # remove all associations for resource and field
1716 $this->RemoveAllAssociations(
"ResourceNameInts",
"ControlledNameId", $Field);
1717 $UpdateModTime=TRUE;
1723 # clear our controlled name cache
1724 unset($this->ControlledNameCache);
1725 unset($this->ControlledNameVariantCache);
1730 # if value to clear supplied
1731 if ($ValueToClear !== NULL)
1733 # convert value to array if necessary
1734 $Files = $ValueToClear;
1735 if (!is_array($Files)) { $Files = array($Files); }
1737 # convert values to objects if necessary
1738 foreach ($Files as $Index => $File)
1740 if (!is_object($File))
1742 $Files[$Index] =
new File($File);
1748 # use all files associated with resource
1749 $Files = $this->
Get($Field, TRUE);
1753 foreach ($Files as $File) { $File->Delete(); }
1757 # if value to clear supplied
1758 if ($ValueToClear !== NULL)
1760 # convert value to array if necessary
1761 $Images = $ValueToClear;
1762 if (!is_array($Images)) { $Images = array($Images); }
1764 # convert values to objects if necessary
1765 foreach ($Images as $Index => $Image)
1767 if (!is_object($Image))
1769 $Images[$Index] =
new SPTImage($Image);
1775 # use all images associated with resource
1776 $Images = $this->
Get($Field, TRUE);
1779 # delete images if we are the last resource referencing
1780 # a particular image.
1781 foreach ($Images as $Image) {
1782 $Cnt = $this->DB->Query(
1783 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
1784 "ImageId=".$Image->Id(),
"Cnt");
1789 # remove connections to images
1790 $UpdateModTime = $this->RemoveAssociation(
1791 "ResourceImageInts",
"ImageId", $Images, $Field);
1795 # remove references from the references table
1797 DELETE FROM ReferenceInts
1798 WHERE FieldId = '".addslashes($Field->Id()).
"'
1799 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
1804 exit(
"<br>SPT - ERROR: attempt to clear unknown resource field type<br>\n");
1810 # update modification timestamps
1812 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1813 $DB->Query(
"DELETE FROM ResourceFieldTimestamps "
1814 .
"WHERE ResourceId=".$this->
Id.
" AND "
1815 .
"FieldId=".$Field->Id() );
1816 $DB->Query(
"INSERT INTO ResourceFieldTimestamps "
1817 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES ("
1818 .$this->
Id.
",".$Field->Id().
","
1819 .$UserId.
",NOW())");
1823 { $this->
Clear($Field, $ValueToClear); }
1826 # --- Field-Specific or Type-Specific Attribute Retrieval Methods -------
1828 # return 2D array of classifications associated with resource
1829 # (first index is classification (field) name, second index is classification ID)
1834 # start with empty array
1837 # for each controlled name
1838 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, "
1839 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, "
1840 .
"Classifications, MetadataFields "
1841 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" "
1842 .
"AND ResourceClassInts.ClassificationId = Classifications.ClassificationId "
1843 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
1844 while ($Record = $DB->FetchRow())
1847 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
1848 $Record[
"ClassificationName"];
1851 # return array to caller
1856 # --- Ratings Methods ---------------------------------------------------
1858 # return cumulative rating (range is usually 0-100)
1861 # return cumulative rating scaled to 1/10th (range is usually 0-10)
1874 # return current number of ratings for resource
1877 # if number of ratings not already set
1880 # obtain number of ratings
1882 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings "
1883 .
"FROM ResourceRatings "
1884 .
"WHERE ResourceId = ".$this->
Id,
1888 # recalculate cumulative rating if it looks erroneous
1891 $this->UpdateCumulativeRating();
1895 # return number of ratings to caller
1896 return $this->NumberOfRatings;
1899 # update individual rating for resource
1900 function Rating($NewRating = NULL, $UserId = NULL)
1904 # if user ID not supplied
1905 if ($UserId == NULL)
1907 # if user is logged in
1909 if ($User->IsLoggedIn())
1911 # use ID of current user
1912 $UserId = $User->Get(
"UserId");
1916 # return NULL to caller
1921 # sanitize $NewRating
1922 if (!is_null($NewRating))
1924 $NewRating = intval($NewRating);
1927 # if there is a rating for resource and user
1928 $DB->Query(
"SELECT Rating FROM ResourceRatings "
1929 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
1930 if ($Record = $DB->FetchRow())
1932 # if new rating was supplied
1933 if ($NewRating != NULL)
1935 # update existing rating
1936 $DB->Query(
"UPDATE ResourceRatings "
1937 .
"SET Rating = ${NewRating}, DateRated = NOW() "
1938 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
1940 # update cumulative rating value
1941 $this->UpdateCumulativeRating();
1943 # return value is new rating
1944 $Rating = $NewRating;
1948 # get rating value to return to caller
1949 $Rating = $Record[
"Rating"];
1954 # if new rating was supplied
1955 if ($NewRating != NULL)
1958 $DB->Query(
"INSERT INTO ResourceRatings "
1959 .
"(ResourceId, UserId, DateRated, Rating) "
1966 # update cumulative rating value
1967 $this->UpdateCumulativeRating();
1969 # return value is new rating
1970 $Rating = $NewRating;
1974 # return value is NULL
1979 # return rating value to caller
1984 # --- Resource Comment Methods ------------------------------------------
1986 # return comments as array of Message objects
1989 # read in comments if not already loaded
1992 $this->DB->Query(
"SELECT MessageId FROM Messages "
1993 .
"WHERE ParentId = ".$this->
Id
1994 .
" AND ParentType = 2 "
1995 .
"ORDER BY DatePosted DESC");
1996 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2002 # return array of comments to caller
2003 return $this->Comments;
2006 # return current number of comments
2009 # obtain number of comments if not already set
2013 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments "
2015 .
"WHERE ParentId = ".$this->
Id
2016 .
" AND ParentType = 2",
2021 # return number of comments to caller
2022 return $this->NumberOfComments;
2026 # --- Permission Methods -------------------------------------------------
2037 return $this->CheckSchemaPermissions($User,
"View" );
2048 return $this->CheckSchemaPermissions($User,
"Edit");
2059 return $this->CheckSchemaPermissions($User,
"Author");
2070 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"View" );
2081 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Edit" );
2092 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2104 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2106 return $this->$CheckFn($User, $FieldOrFieldName);
2109 # ---- PRIVATE INTERFACE -------------------------------------------------
2115 private $NumberOfRatings;
2116 private $CumulativeRating;
2117 private $NumberOfComments;
2119 private $LastStatus;
2120 private $ControlledNameCache;
2121 private $ControlledNameVariantCache;
2122 private $ClassificationCache;
2123 private $PermissionCache;
2131 private function CheckSchemaPermissions($User, $CheckType)
2133 # checks against invalid reosurces should always fail
2134 if ($this->
Status() !== 1) {
return FALSE; }
2136 # construct a key to use for our permissions cache
2137 $CacheKey =
"UserCan".$CheckType.$User->Id();
2139 # if we don't have a cached value for this perm, compute one
2140 if (!isset($this->PermissionCache[$CacheKey]))
2142 # get privilege set for user
2143 $UserPrivs = $User->Privileges();
2145 # get privileges for schema
2146 $PermsFn = $CheckType.
"ingPrivileges";
2147 $SchemaPrivs = $this->Schema->$PermsFn();
2149 # check passes if user privileges are greater than resource set
2150 $CheckResult = $UserPrivs->IsGreaterThan($SchemaPrivs, $this);
2152 # allow plugins to modify result of permission check
2153 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2154 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2156 "Resource" => $this,
2158 "Can".$CheckType => $CheckResult));
2159 $CheckResult = $SignalResult[
"Can".$CheckType];
2161 # save the result of this check in our cache
2162 $this->PermissionCache[$CacheKey] = $CheckResult;
2165 # return the cached value
2166 return $this->PermissionCache[$CacheKey];
2176 private function CheckFieldPermissions($User, $FieldOrFieldName, $CheckType)
2178 # checks against invalid resources should always fail
2179 if ($this->
Status() !== 1) {
return FALSE; }
2181 # get field object (if not supplied)
2182 $Field = is_object($FieldOrFieldName) ? $FieldOrFieldName
2183 : $this->Schema->GetFieldByName($FieldOrFieldName);
2185 # checks against invalid fields should also fail
2188 # construct a key to use for our permissions cache
2189 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2191 # if we don't have a cahced value, compute one
2192 if (!isset($this->PermissionCache[$CacheKey]))
2194 # checks for disabled fields should not pass
2195 if (!$Field->Enabled())
2197 $CheckResult = FALSE;
2201 # be sure schema privs allow View/Edit/Author for this resource
2202 $SchemaCheckFn =
"UserCan".$CheckType;
2203 if ($this->$SchemaCheckFn($User))
2205 # get appropriate privilege set for field
2206 $PermsFn = $CheckType.
"ingPrivileges";
2207 $FieldPrivs = $Field->$PermsFn();
2209 # get privilege set for user
2210 $UserPrivs = $User->Privileges();
2212 # user can View/Edit/Author if privileges are greater than field set
2213 $CheckResult = $UserPrivs->IsGreaterThan($FieldPrivs, $this);
2217 $CheckResult = FALSE;
2221 # allow plugins to modify result of permission check
2222 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2223 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2225 "Resource" => $this,
2227 "Can".$CheckType => $CheckResult));
2228 $CheckResult = $SignalResult[
"Can".$CheckType];
2230 # save the result of this check in our cache
2231 $this->PermissionCache[$CacheKey] = $CheckResult;
2234 # return cached permission value
2235 return $this->PermissionCache[$CacheKey];
2238 # recalculate and save cumulative rating value for resource
2239 private function UpdateCumulativeRating()
2241 # grab totals from DB
2242 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, "
2243 .
"SUM(Rating) AS Total FROM ResourceRatings "
2244 .
"WHERE ResourceId = ".$this->
Id);
2245 $Record = $this->DB->FetchRow();
2247 # calculate new cumulative rating
2250 # save new cumulative rating in DB
2251 $this->DB->Query(
"UPDATE Resources "
2253 .
"WHERE ResourceId = ".$this->Id);
2266 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2268 # We should ignore duplicate key errors when doing inserts:
2269 $this->DB->SetQueryErrorsToIgnore( array(
2270 "/INSERT INTO ".$TableName.
"/" =>
2271 "/Duplicate entry '[0-9]+-[0-9]+' for key/"));
2273 # start out assuming no association will be added
2274 $AssociationAdded = FALSE;
2276 # convert new value to array if necessary
2277 $Values = is_array($Value) ? $Value : array($Value);
2279 # for each new value
2280 foreach ($Values as $Value)
2282 # retrieve ID from value if necessary
2283 if (is_object($Value)) { $Value = $Value->Id(); }
2285 # Try to insert a new entry for this association.
2286 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET"
2287 .
" ResourceId = ".intval($this->
Id)
2288 .
", ".$FieldName.
" = ".intval($Value)
2289 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2291 # If the insert ran without a duplicate key error,
2292 # then we added an assocation:
2293 if ($this->DB->IgnoredError() === FALSE)
2294 $AssociationAdded = TRUE;
2297 # Clear ignored errors:
2298 $this->DB->SetQueryErrorsToIgnore( NULL );
2300 # report to caller whether association was added
2301 return $AssociationAdded;
2314 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2316 # start out assuming no association will be removed
2317 $AssociationRemoved = FALSE;
2319 # convert value to array if necessary
2320 $Values = is_array($Value) ? $Value : array($Value);
2323 foreach ($Values as $Value)
2325 # retrieve ID from value if necessary
2326 if (is_object($Value)) { $Value = $Value->Id(); }
2328 # remove any intersections with target ID from DB
2329 $this->DB->Query(
"DELETE FROM ".$TableName
2330 .
" WHERE ResourceId = ".intval($this->
Id)
2331 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2332 .
" AND ".$FieldName.
" = ".intval($Value));
2335 # report to caller whether association was added
2336 return $AssociationRemoved;
2339 # remove all intersections for resource and field (if any)
2340 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2342 # retrieve list of entries for this field and resource
2343 $Entries = $this->
Get($Field);
2345 # Divide them into chunks of not more than 50:
2346 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2348 # Construct a query that will remove assocations in this chunk:
2349 $this->DB->Query(
"DELETE FROM ".$TableName
2350 .
" WHERE ResourceId = ".intval($this->
Id)
2351 .
" AND ".$TargetFieldName.
" IN "
2352 .
"(".implode(
",", array_keys($Chunk)).
")");
GetByField($FieldNameOrObject, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Old method for retrieving values, deprecated in favor of Get().
GetFilesForResource($ResourceOrResourceId, $ReturnObjects=TRUE)
Retrieve all files (names or objects) for specified resource.
SetQualifier($FieldName, $NewValue)
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...
GetAsArray($IncludeDisabledFields=FALSE, $ReturnObjects=TRUE)
Retrieve all resource values as an array.
Set($FieldNameOrObject, $NewValue, $Reset=FALSE)
Set value using field name or field object.
Id()
Retrieve numerical resource ID.
UserCanEditField($User, $FieldOrFieldName)
Check whether user is allowed to edit specified metadata field.
SetQualifierByField($Field, $NewValue)
Rating($NewRating=NULL, $UserId=NULL)
Status()
Retrieve result of last operation if available.
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.
Metadata type representing non-hierarchical controlled vocabulary values.
UserCanEdit($User)
Determine if the given user can edit the resource.
CWIS-specific user factory class.
Factory for manipulating File objects.
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.
UserCanView(User $User)
Determine if the given user can view the resource, e.g., on the full record page. ...
Clear($Field, $ValueToClear=NULL)
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.
Get($FieldNameOrObject, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field name or field object.
SetByField($Field, $NewValue)
Method replaced by Resource::Set(), preserved for backward compatibility.
__construct($ResourceId)
Object constructor for loading an existing resource.
GetMapped($MappedName, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using standard (mapped) field name.
Represents a "resource" in CWIS.
GetQualifierByField($Field, $ReturnObject=TRUE)
Retrieve qualifier by Field object.
ClearByFieldId($FieldId, $ValueToClear=NULL)
const CLASSSTAT_OK
Status code indicating operation completed successfully.
SetQualifierByFieldId($FieldId, $NewValue)
SchemaId()
Retrieve ID of schema for resource.
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)
ClearByField($Field, $ValueToClear=NULL)
Class representing a stored (usually uploaded) file.
Factory for Resource objects.
CWIS-specific user class.
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...