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;
62 # clean out any temp resource records more than three days old
64 $RFactory->CleanOutStaleTempItems(60 * 24 * 3);
66 # lock DB tables to prevent next ID from being grabbed
68 $DB->Query(
"LOCK TABLES Resources WRITE");
70 # find next temp resource ID
71 $Id = $RFactory->GetNextTempItemId();
73 # write out new resource record with temp resource ID
74 # Set DateLastModified = NOW() to avoid being pruned as a
75 # stale temp resource.
77 "INSERT INTO Resources
78 SET `ResourceId` = '".intval($Id).
"',
79 `SchemaId` = '".intval($SchemaId).
"',
80 `DateLastModified` = NOW() " );
83 $DB->Query(
"UNLOCK TABLES");
85 # create new Resource object
88 if ($Resource->Status() == -1)
90 throw new Exception(
"Resource creation failed");
93 # set some additional fields for default resources
96 $Resource->Set(
"Added By Id", $GLOBALS[
"G_User"]->
Id());
97 $Resource->Set(
"Last Modified By Id", $GLOBALS[
"G_User"]->
Id());
98 $Resource->Set(
"Date Of Record Creation", date(
"Y-m-d H:i:s"));
99 $Resource->Set(
"Date Last Modified", date(
"Y-m-d H:i:s"));
102 # set any default values
109 foreach ($Fields as $Field)
111 $DefaultValue = $Field->DefaultValue();
113 # flip option default values to get into the form that
114 # Resource::Set() expects
116 && is_array($DefaultValue))
118 $DefaultValue = array_flip($DefaultValue);
121 # there is no default value when DefaultValue is null,
122 # or when it is an empty array
123 if ( !($DefaultValue === NULL ||
124 (is_array($DefaultValue) && empty($DefaultValue)) ))
126 $Resource->SetByField($Field, $DefaultValue);
130 # update timestamps as required
132 foreach ($TimestampFields as $Field)
134 if ($Field->UpdateMethod() ==
137 $Resource->SetByField($Field,
"now");
141 # signal resource creation
142 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_CREATE", array(
143 "Resource" => $Resource,
146 # return new Resource object to caller
158 # signal that resource deletion is about to occur
160 $AF->SignalEvent(
"EVENT_RESOURCE_DELETE", array(
164 # grab list of classifications
167 # delete resource/classification intersections
169 $DB->Query(
"DELETE FROM ResourceClassInts WHERE ResourceId = ".$this->
Id());
171 # for each classification type
172 foreach ($Classifications as $ClassType => $ClassesOfType)
174 # for each classification of that type
175 foreach ($ClassesOfType as $ClassId => $ClassName)
177 # recalculate resource count for classification
179 $Class->RecalcResourceCount();
183 # delete resource references
185 DELETE FROM ReferenceInts
186 WHERE SrcResourceId = '".addslashes($this->
Id()).
"'
187 OR DstResourceId = '".addslashes($this->
Id()).
"'");
189 # delete resource/name intersections
190 $DB->Query(
"DELETE FROM ResourceNameInts WHERE ResourceId = ".$this->
Id());
192 # get the list of all images associated with this resource
193 $DB->Query(
"SELECT ImageId FROM ResourceImageInts"
194 .
" WHERE ResourceId = ".intval($this->
Id()));
195 $ImageIds =
$DB->FetchColumn(
"ImageId");
197 # disassociate this resource from all images
198 $DB->Query(
"DELETE FROM ResourceImageInts"
199 .
" WHERE ResourceId = ".intval($this->
Id()));
201 # delete any images that no longer belong to any resources
202 foreach ($ImageIds as $ImageId)
204 $DB->Query(
"SELECT ResourceId FROM ResourceImageInts"
205 .
" WHERE ImageId = ".intval($ImageId) );
206 if (
$DB->NumRowsSelected() == 0)
213 # delete any associated files
215 $Files = $Factory->GetFilesForResource($this->
Id());
216 foreach ($Files as $File)
221 # delete resource record from database
222 $DB->Query(
"DELETE FROM Resources WHERE ResourceId = ".$this->
Id());
224 # drop item from search engine and recommender system
225 if ($SysConfig->SearchDBEnabled())
228 $SearchEngine->DropItem($this->
Id());
230 if ($SysConfig->RecommenderDBEnabled())
233 $Recommender->DropItem($this->
Id());
236 # get the folders containing the resource
238 $Folders = $FolderFactory->GetFoldersContainingItem(
242 # drop the resource from each folder it belongs to
243 foreach ($Folders as $Folder)
245 # mixed item type folder
246 if ($Folder->ContainsItem($this->Id,
"Resource"))
248 $Folder->RemoveItem($this->
Id,
"Resource");
251 # single item type folder
254 $Folder->RemoveItem($this->
Id);
258 # delete any resource comments
259 $DB->Query(
"DELETE FROM Messages WHERE ParentId = ".$this->
Id);
268 return $this->LastStatus;
286 return $this->DBFields[
"SchemaId"];
297 # if new temp resource setting supplied
298 if (!is_null($NewSetting))
300 # if caller requested to switch
302 if ((($this->
Id() < 0) && ($NewSetting == FALSE))
303 || (($this->
Id() >= 0) && ($NewSetting == TRUE)))
305 # lock DB tables to prevent next ID from being grabbed
306 $DB->Query(
"LOCK TABLES Resources write");
308 # get next resource ID as appropriate
309 $OldResourceId = $this->Id;
311 if ($NewSetting == TRUE)
313 $this->
Id = $Factory->GetNextTempItemId();
317 $this->
Id = $Factory->GetNextItemId();
321 $DB->Query(
"UPDATE Resources SET ResourceId = ".
322 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
325 $DB->Query(
"UNLOCK TABLES");
327 # change associations
328 unset($this->ClassificationCache);
329 $DB->Query(
"UPDATE ResourceClassInts SET ResourceId = ".
330 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
331 unset($this->ControlledNameCache);
332 unset($this->ControlledNameVariantCache);
333 $DB->Query(
"UPDATE ResourceNameInts SET ResourceId = ".
334 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
335 $DB->Query(
"UPDATE Files SET ResourceId = ".
336 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
337 $DB->Query(
"UPDATE ReferenceInts SET SrcResourceId = ".
338 $this->
Id.
" WHERE SrcResourceId = ".$OldResourceId);
339 $DB->Query(
"UPDATE ResourceImageInts SET ResourceId = ".
340 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
342 # signal event as appropriate
343 if ($NewSetting === FALSE)
345 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_ADD", array(
352 # report to caller whether we are a temp resource
353 return ($this->
Id() < 0) ? TRUE : FALSE;
357 # --- Generic Attribute Retrieval Methods -------------------------------
373 function Get($FieldNameOrObject, $ReturnObject = FALSE, $IncludeVariants = FALSE)
375 # load field object if needed
376 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
377 : $this->Schema->GetFieldByName($FieldNameOrObject);
379 # return no value found if we don't have a valid field
382 # grab database field name
383 $DBFieldName = $Field->DBFieldName();
385 # format return value based on field type
386 switch ($Field->Type())
391 $ReturnValue = isset($this->DBFields[$DBFieldName])
392 ? (string)$this->DBFields[$DBFieldName] : NULL;
396 $ReturnValue = isset($this->DBFields[$DBFieldName])
397 ? (int)$this->DBFields[$DBFieldName] : NULL;
401 $ReturnValue = isset($this->DBFields[$DBFieldName])
402 ? (bool)$this->DBFields[$DBFieldName] : NULL;
406 $ReturnValue = array(
"X" => (
float)$this->DBFields[$DBFieldName.
"X"],
407 "Y" => (
float)$this->DBFields[$DBFieldName.
"Y"]);
411 $Date =
new Date($this->DBFields[$DBFieldName.
"Begin"],
412 $this->DBFields[$DBFieldName.
"End"],
413 $this->DBFields[$DBFieldName.
"Precision"]);
416 $ReturnValue = $Date;
420 $ReturnValue = $Date->Formatted();
425 $ReturnValue = $this->DBFields[$DBFieldName];
429 # start with empty array
430 $ReturnValue = array();
432 # if classification cache has not been loaded
433 if (!isset($this->ClassificationCache))
435 # load all classifications associated with this resource into cache
436 $this->ClassificationCache = array();
438 "SELECT Classifications.ClassificationId,"
439 .
" Classifications.FieldId,ClassificationName"
440 .
" FROM ResourceClassInts, Classifications"
441 .
" WHERE ResourceClassInts.ResourceId = ".$this->
Id
442 .
" AND ResourceClassInts.ClassificationId"
443 .
" = Classifications.ClassificationId");
444 while ($Record = $this->DB->FetchRow())
446 $ClassId = $Record[
"ClassificationId"];
447 $this->ClassificationCache[$ClassId][
"Name"]
448 = $Record[
"ClassificationName"];
449 $this->ClassificationCache[$ClassId][
"FieldId"]
450 = $Record[
"FieldId"];
454 # for each entry in classification cache
455 foreach ($this->ClassificationCache as
456 $ClassificationId => $ClassificationInfo)
458 # if classification ID matches field we are looking for
459 if ($ClassificationInfo[
"FieldId"] == $Field->Id())
461 # add field to result
464 $ReturnValue[$ClassificationId] =
469 $ReturnValue[$ClassificationId] = $ClassificationInfo[
"Name"];
477 # start with empty array
478 $ReturnValue = array();
480 # if controlled name cache has not been loaded
481 if (!isset($this->ControlledNameCache))
483 # load all controlled names associated with this resource into cache
484 $this->ControlledNameCache = array();
486 "SELECT ControlledNames.ControlledNameId,"
487 .
" ControlledNames.FieldId,ControlledName"
488 .
" FROM ResourceNameInts, ControlledNames"
489 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id
490 .
" AND ResourceNameInts.ControlledNameId"
491 .
" = ControlledNames.ControlledNameId"
492 .
" ORDER BY ControlledNames.ControlledName ASC");
493 while ($Record = $this->DB->FetchRow())
495 $CNameId = $Record[
"ControlledNameId"];
496 $this->ControlledNameCache[$CNameId][
"Name"]
497 = $Record[
"ControlledName"];
498 $this->ControlledNameCache[$CNameId][
"FieldId"]
499 = $Record[
"FieldId"];
503 # if variant names requested and variant name cache has not been loaded
504 if ($IncludeVariants && !isset($this->ControlledNameVariantCache))
506 # load all controlled names associated with this resource into cache
507 $this->ControlledNameVariantCache = array();
508 $this->DB->Query(
"SELECT ControlledNames.ControlledNameId,"
509 .
" ControlledNames.FieldId,"
510 .
" ControlledName, VariantName"
511 .
" FROM ResourceNameInts, ControlledNames, VariantNames"
512 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id
513 .
" AND ResourceNameInts.ControlledNameId"
514 .
" = ControlledNames.ControlledNameId"
515 .
" AND VariantNames.ControlledNameId"
516 .
" = ControlledNames.ControlledNameId");
517 while ($Record = $this->DB->FetchRow())
519 $this->ControlledNameVariantCache[$Record[
"ControlledNameId"]][]
520 = $Record[
"VariantName"];
524 # for each entry in controlled name cache
525 foreach ($this->ControlledNameCache as
526 $CNameId => $ControlledNameInfo)
528 # if controlled name type matches field we are looking for
529 if ($ControlledNameInfo[
"FieldId"] == $Field->Id())
531 # if objects requested
534 $ReturnValue[$CNameId] =
539 # if variant names requested
540 if ($IncludeVariants)
542 # add field to result
543 $ReturnValue[] = $ControlledNameInfo[
"Name"];
545 # add any variant names to result
546 if (isset($this->ControlledNameVariantCache[$CNameId]))
548 $ReturnValue = array_merge(
550 $this->ControlledNameVariantCache[$CNameId]);
555 # add field with index to result
556 $ReturnValue[$CNameId] =
557 $ControlledNameInfo[
"Name"];
565 $User =
new CWUser(intval($this->DBFields[$DBFieldName]));
568 $ReturnValue = $User;
572 $ReturnValue = $User->Get(
"UserName");
577 # start out assuming no images will be found
578 $ReturnValue = array();
580 # find all images associated with this resource
581 $this->DB->Query(
"SELECT ImageId FROM ResourceImageInts"
582 .
" WHERE ResourceId = ".intval($this->
Id())
583 .
" AND FieldId = ".intval($Field->Id()));
585 # if images were found
586 if ($this->DB->NumRowsSelected())
588 # if we are to return an object
589 $ImageIds = $this->DB->FetchColumn(
"ImageId");
592 # load array of Image objects for return value
593 foreach ($ImageIds as $ImageId)
595 $ReturnValue[$ImageId] =
new SPTImage($ImageId);
600 # load array of Image ids for return value
601 $ReturnValue = $ImageIds;
607 # retrieve files using factory
610 $this->
Id, $ReturnObject);
614 # query for resource references
616 SELECT * FROM ReferenceInts
617 WHERE FieldId = '".addslashes($Field->Id()).
"'
618 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
620 $ReturnValue = array();
622 # return each reference as a Resource object
625 $FoundErrors = FALSE;
627 while (FALSE !== ($Record = $this->DB->FetchRow()))
629 $ReferenceId = $Record[
"DstResourceId"];
630 $Reference =
new Resource($ReferenceId);
632 # the reference is bad, so flag that there were errors
633 if ($Reference->Status() != 1)
640 $ReturnValue[$ReferenceId] = $Reference;
644 # try to fix the errors by removing any references to
645 # resources that were bad
648 $this->
Set($Field, $ReturnValue);
652 # return each reference as a resource ID
655 while (FALSE !== ($Record = $this->DB->FetchRow()))
657 $ReferenceId = $Record[
"DstResourceId"];
658 $ReturnValue[$ReferenceId] = $ReferenceId;
665 exit(
"<br>SPT - ERROR: attempt to retrieve "
666 .
"unknown resource field type (".$Field->Type().
")<br>\n");
670 # return formatted value to caller
678 $ReturnObject = FALSE, $IncludeVariants = FALSE)
679 {
return $this->
Get($FieldNameOrObject, $ReturnObject, $IncludeVariants); }
694 function GetByFieldId($FieldId, $ReturnObject = FALSE, $IncludeVariants = FALSE)
696 $Field = $this->Schema->GetField($FieldId);
697 return ($Field) ? $this->
Get($Field, $ReturnObject, $IncludeVariants) : NULL;
712 function GetAsArray($IncludeDisabledFields = FALSE, $ReturnObjects = TRUE)
714 # retrieve field info
715 $Fields = $this->Schema->GetFields();
718 foreach ($Fields as $Field)
720 # if field is enabled or caller requested disabled fields
721 if ($Field->Enabled() || $IncludeDisabledFields)
723 # retrieve info and add it to the array
724 $FieldStrings[$Field->Name()] = $this->
Get($Field, $ReturnObjects);
726 # if field uses qualifiers
727 if ($Field->UsesQualifiers())
729 # get qualifier attributes and add to the array
730 $FieldStrings[$Field->Name().
" Qualifier"] =
736 # add in internal values
737 $FieldStrings[
"ResourceId"] = $this->
Id();
740 # return array to caller
741 return $FieldStrings;
758 function GetMapped($MappedName, $ReturnObject = FALSE, $IncludeVariants = FALSE)
760 return $this->Schema->StdNameToFieldMapping($MappedName)
761 ? $this->
GetByFieldId($this->Schema->StdNameToFieldMapping($MappedName),
762 $ReturnObject, $IncludeVariants)
776 $Field = $this->Schema->GetFieldByName($FieldName);
790 $Field = $this->Schema->GetField($FieldId);
804 # return NULL if field is invalid
807 # assume no qualifiers if not otherwise determined
810 # if field uses qualifiers
811 if ($Field->UsesQualifiers())
813 # retrieve qualifiers based on field type
814 switch ($Field->Type())
819 # retrieve list of items
822 # if field uses item-level qualifiers
823 if ($Field->HasItemLevelQualifiers())
825 # determine general item name in DB
827 ?
"Classification" :
"ControlledName";
830 foreach (
$Items as $ItemId => $ItemName)
832 # look up qualifier for item
833 $QualId = $this->DB->Query(
834 "SELECT * FROM ".$TableName.
"s"
835 .
" WHERE ".$TableName.
"Id = ".$ItemId,
841 # if object was requested by caller
844 # load qualifier and add to return value array
845 $ReturnValue[$ItemId] =
new Qualifier($QualId);
849 # add qualifier ID to return value array
850 $ReturnValue[$ItemId] = $QualId;
855 # add NULL to return value array for this item
856 $ReturnValue[$ItemId] = NULL;
863 foreach (
$Items as $ItemId => $ItemName)
865 # if object was requested by caller
868 # load default qualifier and add to return value array
870 $Field->DefaultQualifier());
874 # add default qualifier ID to return value array
875 $ReturnValue[$ItemId] = $Field->DefaultQualifier();
882 # if field uses item-level qualifiers
883 if ($Field->HasItemLevelQualifiers())
885 # if qualifier available
886 if ($this->DBFields[$Field->DBFieldName().
"Qualifier"] > 0)
888 # if object was requested by caller
889 $QFieldName = $Field->DBFieldName().
"Qualifier";
892 # return qualifier for field
894 $this->DBFields[$QFieldName]);
898 # return qualifier ID for field
899 $ReturnValue = $this->DBFields[$QFieldName];
905 # if default qualifier available
906 if ($Field->DefaultQualifier() > 0)
908 # if object was requested by caller
911 # return default qualifier
912 $ReturnValue =
new Qualifier($Field->DefaultQualifier());
916 # return default qualifier ID
917 $ReturnValue = $Field->DefaultQualifier();
925 # return qualifier object or ID (or array of same) to caller
936 function FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
938 # load field object if needed
939 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
940 : $this->Schema->GetFieldByName($FieldNameOrObject);
942 # return no value found if we don't have a valid field
946 $Value = $this->
Get($Field);
948 # checks depend on the field type
949 switch ($Field->Type())
957 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
964 return isset($Value[
"X"])
965 && isset($Value[
"Y"])
966 && strlen(trim($Value[
"X"]))
967 && strlen(trim($Value[
"Y"]));
971 && strlen(trim($Value))
972 && $Value !=
"0000-00-00";
976 && strlen(trim($Value))
977 && $Value !=
"0000-00-00 00:00:00";
985 return count($Value) > 0;
991 && $Factory->UserNameExists($Value);
998 # --- Generic Attribute Setting Methods ---------------------------------
1008 function Set($FieldNameOrObject, $NewValue, $Reset=FALSE)
1010 # load field object if needed
1011 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1012 : $this->Schema->GetFieldByName($FieldNameOrObject);
1014 # return if we don't have a valid field
1017 # grab commonly-used values for local use
1019 $ResourceId = $this->Id;
1021 # grab database field name
1022 $DBFieldName = $Field->DBFieldName();
1024 # Flag to deterimine if we've actually changed anything.
1025 $UpdateModTime = FALSE;
1027 # store value in DB based on field type
1028 switch ($Field->Type())
1033 if ($this->DBFields[$DBFieldName] != $NewValue)
1035 # save value directly to DB
1036 $DB->Query(
"UPDATE Resources SET `"
1037 .$DBFieldName.
"` = '".addslashes($NewValue).
"' "
1038 .
"WHERE ResourceId = ".$ResourceId);
1040 # save value locally
1041 $this->DBFields[$DBFieldName] = $NewValue;
1042 $UpdateModTime=TRUE;
1047 if ( $this->DBFields[$DBFieldName] != $NewValue )
1049 # save value directly to DB
1050 if (is_null($NewValue))
1052 $DB->Query(
"UPDATE Resources SET `"
1053 .$DBFieldName.
"` = NULL"
1054 .
" WHERE ResourceId = ".$ResourceId);
1058 $DB->Query(
"UPDATE Resources SET `"
1059 .$DBFieldName.
"` = ".intval($NewValue)
1060 .
" WHERE ResourceId = ".$ResourceId);
1063 # save value locally
1064 $this->DBFields[$DBFieldName] = $NewValue;
1065 $UpdateModTime = TRUE;
1071 if ($this->DBFields[$DBFieldName.
"X"] != $NewValue[
"X"] ||
1072 $this->DBFields[$DBFieldName.
"Y"] != $NewValue[
"Y"] )
1074 if (is_null($NewValue))
1076 $DB->Query(
"UPDATE Resources SET "
1077 .
"`".$DBFieldName.
"X` = NULL, "
1078 .
"`".$DBFieldName.
"Y` = NULL "
1079 .
"WHERE ResourceId = ".$ResourceId);
1080 $this->DBFields[$DBFieldName.
"X"] = NULL;
1081 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1085 $DB->Query(
"UPDATE Resources SET "
1086 .
"`".$DBFieldName.
"X` = " .(strlen($NewValue[
"X"])
1087 ?
"'".$NewValue[
"X"].
"'" :
"NULL").
", "
1088 .
"`".$DBFieldName.
"Y` = ".(strlen($NewValue[
"Y"])
1089 ?
"'".$NewValue[
"Y"].
"'" :
"NULL")
1090 .
" WHERE ResourceId = ".$ResourceId);
1092 $Digits = $Field->PointDecimalDigits();
1094 $this->DBFields[$DBFieldName.
"X"] =
1095 strlen($NewValue[
"X"]) ?
1096 round($NewValue[
"X"], $Digits) : NULL;
1097 $this->DBFields[$DBFieldName.
"Y"] =
1098 strlen($NewValue[
"Y"]) ?
1099 round($NewValue[
"Y"], $Digits) : NULL;
1101 $UpdateModTime = TRUE;
1106 if ($this->DBFields[$DBFieldName] != $NewValue)
1108 # save value directly to DB
1109 if (is_null($NewValue))
1111 $DB->Query(
"UPDATE Resources SET `"
1112 .$DBFieldName.
"` = NULL"
1113 .
" WHERE ResourceId = ".$ResourceId);
1117 $NewValue = $NewValue ?
"1" :
"0";
1118 $DB->Query(
"UPDATE Resources SET `"
1119 .$DBFieldName.
"` = ".$NewValue
1120 .
" WHERE ResourceId = ".$ResourceId);
1123 $this->DBFields[$DBFieldName] = $NewValue;
1125 # recalculate counts for any associated classifications if necessary
1126 if ($DBFieldName ==
"ReleaseFlag")
1128 $DB->Query(
"SELECT ClassificationId FROM ResourceClassInts"
1129 .
" WHERE ResourceId = ".$ResourceId);
1130 while ($ClassId =
$DB->FetchField(
"ClassificationId"))
1133 $Class->RecalcResourceCount();
1136 $UpdateModTime = TRUE;
1141 # if value passed in was object
1142 if (is_object($NewValue))
1144 # retrieve user ID from object
1145 $UserId = $NewValue->Get(
"UserId");
1147 # else if value passed in was user name
1148 elseif (is_string($NewValue) && strlen($NewValue))
1150 # create user object and retrieve user ID from there
1151 $User =
new CWUser($NewValue);
1152 $UserId = $User->Get(
"UserId");
1156 # assume value is user ID and use value directly
1157 $UserId = $NewValue;
1160 if ($this->DBFields[$DBFieldName] != $UserId)
1162 # save value directly to DB
1163 $DB->Query(
"UPDATE Resources SET `"
1164 .$DBFieldName.
"` = '".$UserId.
"' "
1165 .
"WHERE ResourceId = ".$ResourceId);
1167 # save value locally
1168 $this->DBFields[$DBFieldName] = $UserId;
1169 $UpdateModTime = TRUE;
1174 # if we were given a date object
1175 if (is_object($NewValue))
1177 # use supplied date object
1182 # create date object
1183 $Date =
new Date($NewValue);
1186 $OldDate =
new Date(
1187 $this->DBFields[$DBFieldName.
"Begin"],
1188 $this->DBFields[$DBFieldName.
"End"]);
1190 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1191 $OldDate->EndDate() != $Date->EndDate() ||
1192 $OldDate->Precision() != $Date->Precision() )
1194 # extract values from date object and store in DB
1195 $BeginDate =
"'".$Date->BeginDate().
"'";
1196 if (strlen($BeginDate) < 3) { $BeginDate =
"NULL"; }
1197 $EndDate =
"'".$Date->EndDate().
"'";
1198 if (strlen($EndDate) < 3) { $EndDate =
"NULL"; }
1200 $DB->Query(
"UPDATE Resources SET "
1201 .$DBFieldName.
"Begin = ".$BeginDate.
", "
1202 .$DBFieldName.
"End = ".$EndDate.
", "
1203 .$DBFieldName.
"Precision = '".$Date->Precision().
"' "
1204 .
"WHERE ResourceId = ".$ResourceId);
1206 # save values locally
1207 $this->DBFields[$DBFieldName.
"Begin"] = $Date->BeginDate();
1208 $this->DBFields[$DBFieldName.
"End"] = $Date->EndDate();
1209 $this->DBFields[$DBFieldName.
"Precision"] = $Date->Precision();
1210 $UpdateModTime=TRUE;
1215 if (is_null($NewValue) || !strlen(trim($NewValue)))
1217 $DateValue = $NewValue;
1219 if (!is_null($this->DBFields[$DBFieldName]))
1221 # save value directly to DB
1222 $DB->Query(
"UPDATE Resources SET "
1223 .
"`".$DBFieldName.
"` = NULL "
1224 .
"WHERE ResourceId = ".$ResourceId);
1225 $UpdateModTime = TRUE;
1230 # assume value is date and use directly
1231 $TimestampValue = strtotime($NewValue);
1233 # use the new value if the date is valid
1234 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1236 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1238 if ($this->DBFields[$DBFieldName] != $DateValue)
1240 # save value directly to DB
1241 $DB->Query(
"UPDATE Resources SET "
1242 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' "
1243 .
"WHERE ResourceId = ".$ResourceId);
1244 $UpdateModTime=TRUE;
1248 # continue using the old value if invalid
1251 $DateValue = $this->
Get($Field);
1255 # save value locally
1256 $this->DBFields[$DBFieldName] = $DateValue;
1260 $OldValue = $this->
Get($Field);
1262 # if incoming value is array
1263 if (is_array($NewValue))
1265 if ($OldValue != $NewValue)
1269 # remove values that were in the old value
1270 # but not the new one
1271 $ToRemove = array_diff(array_keys($OldValue),
1272 array_keys($NewValue));
1273 foreach ($ToRemove as $ClassificationId)
1275 $this->RemoveAssociation(
"ResourceClassInts",
1281 $Class->RecalcResourceCount();
1286 # for each element of array
1287 foreach ($NewValue as
1288 $ClassificationId => $ClassificationName)
1293 # associate with resource if not already associated
1294 if ($this->AddAssociation(
"ResourceClassInts",
1296 $ClassificationId) )
1298 $Class->UpdateLastAssigned();
1299 $Class->RecalcResourceCount();
1304 $UpdateModTime=TRUE;
1309 # associate with resource if not already associated
1310 if (is_object($NewValue))
1313 $NewValue = $Class->Id();
1320 if (!array_key_exists($Class->Id(), $OldValue))
1323 $this->AddAssociation(
"ResourceClassInts",
1326 $Class->UpdateLastAssigned();
1327 $Class->RecalcResourceCount();
1328 $UpdateModTime=TRUE;
1332 # clear our classification cache
1335 unset($this->ClassificationCache);
1341 $OldValue = $this->
Get($Field);
1343 # input to Set() for these fields is one of
1344 # 1. an int specifying a ControlledNameId
1345 # 2. a ControlledName object
1346 # 3. an array with keys giving Ids and values giving ControlledNames
1348 # normalize 1 and 2 into 3 for simplicity of processing
1349 if (is_object($NewValue) || !is_array($NewValue) )
1351 if (!is_object($NewValue))
1356 $TmpValue = array();
1357 $TmpValue[$NewValue->Id()] = $NewValue->Name();
1359 $NewValue = $TmpValue;
1362 # if this is a unique field, only accept the first of the options given
1363 # NB: all ControlledNames implicitly AllowMultiple
1365 $Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1367 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1370 # if the value has changed
1371 if ($OldValue != $NewValue)
1374 && $Field->AllowMultiple() == FALSE ) )
1376 $ToRemove = array_diff(array_keys($OldValue),
1377 array_keys($NewValue));
1378 foreach ($ToRemove as $CNId)
1380 $this->RemoveAssociation(
"ResourceNameInts",
1386 # for each element of array
1387 foreach ($NewValue as $ControlledNameId => $ControlledName)
1389 # associate with resource if not already associated
1390 if ($this->AddAssociation(
"ResourceNameInts",
1395 $CN->UpdateLastAssigned();
1398 $UpdateModTime=TRUE;
1403 # clear our controlled name cache
1404 unset($this->ControlledNameCache);
1405 unset($this->ControlledNameVariantCache);
1411 # associate value(s) with resource
1412 $this->AddAssociation(
1413 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1417 # convert incoming value to array if necessary
1418 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1420 # for each incoming file
1422 foreach ($NewValue as $File)
1425 $NewFile = $Factory->
Copy($File);
1427 # associate copy with this resource and field
1428 $NewFile->ResourceId($this->
Id);
1429 $NewFile->FieldId($Field->Id());
1431 # Since we make a fresh copy of the File whenever Set is called,
1432 # we'll always update the modification time for this field.
1433 $UpdateModTime = TRUE;
1437 # convert incoming value to array to simplify the workflow
1438 if (is_scalar($NewValue) || $NewValue instanceof
Resource)
1440 $NewValue = array($NewValue);
1443 # delete existing resource references
1446 # add each reference
1447 foreach ($NewValue as $ReferenceOrId)
1449 # initially issume it's a reference ID and not an object...
1450 $ReferenceId = $ReferenceOrId;
1452 # ... but get the reference ID if it's an object
1453 if ($ReferenceOrId instanceof
Resource)
1455 $ReferenceId = $ReferenceOrId->Id();
1458 # skip blank reference IDs
1459 if (strlen(trim($ReferenceId)) < 1)
1464 # skip reference IDs that don't look right
1465 if (!is_numeric($ReferenceId))
1470 # skip references to the current resource
1471 if ($ReferenceId == $this->
Id())
1476 # add the reference to the references table
1478 INSERT INTO ReferenceInts (
1483 ".addslashes($Field->Id()).
",
1484 ".addslashes($this->
Id()).
",
1485 ".addslashes($ReferenceId).
")");
1491 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1497 # update modification timestamps
1499 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1500 $DB->Query(
"DELETE FROM ResourceFieldTimestamps "
1501 .
"WHERE ResourceId=".$this->
Id.
" AND "
1502 .
"FieldId=".$Field->Id() );
1503 $DB->Query(
"INSERT INTO ResourceFieldTimestamps "
1504 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES ("
1505 .$this->
Id.
",".$Field->Id().
","
1506 .$UserId.
",NOW())");
1508 # on resource modification, clear the UserPermsCache entry
1509 # so that stale permissions checks are not cached
1510 $DB->Query(
"DELETE FROM UserPermsCache WHERE ResourceId=".$this->
Id);
1519 $this->
Set($Field, $NewValue);
1522 # set value by field ID
1525 $Field = $this->Schema->GetField($FieldId);
1526 $this->
Set($Field, $NewValue);
1529 # set qualifier by field name
1532 $Field = $this->Schema->GetFieldByName($FieldName);
1536 # set qualifier by field ID
1539 $Field = $this->Schema->GetField($FieldId);
1543 # set qualifier using field object
1546 # if field uses qualifiers and uses item-level qualifiers
1547 if ($Field->UsesQualifiers() && $Field->HasItemLevelQualifiers())
1549 # if qualifier object passed in
1550 if (is_object($NewValue))
1552 # grab qualifier ID from object
1553 $QualifierId = $NewValue->Id();
1557 # assume value passed in is qualifier ID
1558 $QualifierId = $NewValue;
1561 # update qualifier value in database
1562 $DBFieldName = $Field->DBFieldName();
1563 $this->DB->Query(
"UPDATE Resources SET "
1564 .$DBFieldName.
"Qualifier = '".$QualifierId.
"' "
1565 .
"WHERE ResourceId = ".$this->Id);
1567 # update local qualifier value
1568 $this->DBFields[$DBFieldName.
"Qualifier"] = $QualifierId;
1572 # clear value by field ID
1575 $Field = $this->Schema->GetField($FieldId);
1579 # clear value using field object
1580 function Clear($Field, $ValueToClear = NULL)
1582 # convert field name to object if necessary
1583 if (!is_object($Field))
1585 $Field = $this->Schema->GetFieldByName($Field);
1588 # grab commonly-used values for local use
1590 $ResourceId = $this->Id;
1592 # grab database field name
1593 $DBFieldName = $Field->DBFieldName();
1595 $UpdateModTime=FALSE;
1597 # store value in DB based on field type
1598 switch ($Field->Type())
1607 if (strlen($this->DBFields[$DBFieldName])>0)
1610 $DB->Query(
"UPDATE Resources SET `"
1611 .$DBFieldName.
"` = NULL "
1612 .
"WHERE ResourceId = ".$ResourceId);
1614 # clear value locally
1615 $this->DBFields[$DBFieldName] = NULL;
1616 $UpdateModTime=TRUE;
1621 if (!is_null($this->DBFields[$DBFieldName.
"X"]) ||
1622 !is_null($this->DBFields[$DBFieldName.
"Y"]) )
1625 $DB->Query(
"UPDATE Resources SET "
1626 .
"`".$DBFieldName.
"X` = NULL ,"
1627 .
"`".$DBFieldName.
"Y` = NULL "
1628 .
"WHERE ResourceId = ".$ResourceId);
1630 # Clear local values
1631 $this->DBFields[$DBFieldName.
"X"] = NULL;
1632 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1633 $UpdateModTime=TRUE;
1638 if (!is_null($this->DBFields[$DBFieldName.
"Begin"]) ||
1639 !is_null($this->DBFields[$DBFieldName.
"End"]) ||
1640 !is_null($this->DBFields[$DBFieldName.
"Precision"]))
1642 # clear date object values in DB
1643 $DB->Query(
"UPDATE Resources SET "
1644 .$DBFieldName.
"Begin = '', "
1645 .$DBFieldName.
"End = '', "
1646 .$DBFieldName.
"Precision = '' "
1647 .
"WHERE ResourceId = ".$ResourceId);
1649 # clear value locally
1650 $this->DBFields[$DBFieldName.
"Begin"] = NULL;
1651 $this->DBFields[$DBFieldName.
"End"] = NULL;
1652 $this->DBFields[$DBFieldName.
"Precision"] = NULL;
1653 $UpdateModTime=TRUE;
1658 $OldValue = $this->
Get($Field);
1660 # if value to clear supplied
1661 if ($ValueToClear !== NULL)
1663 # if supplied value is array
1664 if (is_array($ValueToClear))
1666 # for each element of array
1667 foreach ($ValueToClear as $ClassificationId => $Dummy)
1669 if (array_key_exists($ClassificationId, $OldValue))
1671 # remove association with resource (if any)
1672 $this->RemoveAssociation(
"ResourceClassInts",
1676 $Class->RecalcResourceCount();
1677 $UpdateModTime=TRUE;
1683 if (array_key_exists($ValueToClear, $OldValue))
1685 # remove association with resource (if any)
1686 $this->RemoveAssociation(
"ResourceClassInts",
1690 $Class->RecalcResourceCount();
1691 $UpdateModTime=TRUE;
1697 if (count($OldValue)>0)
1699 # remove all associations for resource and field
1700 $this->RemoveAllAssociations(
1701 "ResourceClassInts",
"ClassificationId", $Field);
1703 # recompute resource count
1704 $Values = $this->
Get($Field);
1705 foreach ($Values as $ClassificationId => $Dummy)
1708 $Class->RecalcResourceCount();
1710 $UpdateModTime=TRUE;
1714 # clear our classification cache
1717 unset($this->ClassificationCache);
1723 $OldValue = $this->
Get($Field);
1724 # if value to clear supplied
1725 if ($ValueToClear !== NULL)
1727 # if incoming value is array
1728 if (is_array($ValueToClear))
1730 # for each element of array
1731 foreach ($ValueToClear as $ControlledNameId =>
1734 if (array_key_exists($ControlledNameId, $OldValue))
1736 # remove association with resource (if any)
1737 $this->RemoveAssociation(
"ResourceNameInts",
1740 $UpdateModTime=TRUE;
1746 if (array_key_exists($ValueToClear, $OldValue))
1748 # remove association with resource (if any)
1749 $this->RemoveAssociation(
"ResourceNameInts",
1752 $UpdateModTime=TRUE;
1758 if (count($OldValue)>0)
1760 # remove all associations for resource and field
1761 $this->RemoveAllAssociations(
1762 "ResourceNameInts",
"ControlledNameId", $Field);
1763 $UpdateModTime=TRUE;
1769 # clear our controlled name cache
1770 unset($this->ControlledNameCache);
1771 unset($this->ControlledNameVariantCache);
1776 # if value to clear supplied
1777 if ($ValueToClear !== NULL)
1779 # convert value to array if necessary
1780 $Files = $ValueToClear;
1781 if (!is_array($Files)) { $Files = array($Files); }
1783 # convert values to objects if necessary
1784 foreach ($Files as $Index => $File)
1786 if (!is_object($File))
1788 $Files[$Index] =
new File($File);
1794 # use all files associated with resource
1795 $Files = $this->
Get($Field, TRUE);
1799 foreach ($Files as $File) { $File->Delete(); }
1803 # if value to clear supplied
1804 if ($ValueToClear !== NULL)
1806 # convert value to array if necessary
1807 $Images = $ValueToClear;
1808 if (!is_array($Images)) { $Images = array($Images); }
1810 # convert values to objects if necessary
1811 foreach ($Images as $Index => $Image)
1813 if (!is_object($Image))
1815 $Images[$Index] =
new SPTImage($Image);
1821 # use all images associated with resource
1822 $Images = $this->
Get($Field, TRUE);
1825 # delete images if we are the last resource referencing
1826 # a particular image.
1827 foreach ($Images as $Image) {
1828 $Cnt = $this->DB->Query(
1829 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
1830 "ImageId=".$Image->Id(),
"Cnt");
1837 # remove connections to images
1838 $UpdateModTime = $this->RemoveAssociation(
1839 "ResourceImageInts",
"ImageId", $Images, $Field);
1843 # remove references from the references table
1845 DELETE FROM ReferenceInts
1846 WHERE FieldId = '".addslashes($Field->Id()).
"'
1847 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
1852 exit(
"<br>SPT - ERROR: attempt to clear "
1853 .
"unknown resource field type<br>\n");
1859 # update modification timestamps
1861 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1862 $DB->Query(
"DELETE FROM ResourceFieldTimestamps "
1863 .
"WHERE ResourceId=".$this->
Id.
" AND "
1864 .
"FieldId=".$Field->Id() );
1865 $DB->Query(
"INSERT INTO ResourceFieldTimestamps "
1866 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES ("
1867 .$this->
Id.
",".$Field->Id().
","
1868 .$UserId.
",NOW())");
1874 $this->
Clear($Field, $ValueToClear);
1877 # --- Field-Specific or Type-Specific Attribute Retrieval Methods -------
1879 # return 2D array of classifications associated with resource
1880 # (first index is classification (field) name, second index is classification ID)
1885 # start with empty array
1888 # for each controlled name
1889 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, "
1890 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, "
1891 .
"Classifications, MetadataFields "
1892 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" "
1893 .
"AND ResourceClassInts.ClassificationId = "
1894 .
"Classifications.ClassificationId "
1895 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
1896 while ($Record =
$DB->FetchRow())
1899 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
1900 $Record[
"ClassificationName"];
1903 # return array to caller
1908 # --- Ratings Methods ---------------------------------------------------
1910 # return cumulative rating (range is usually 0-100)
1913 return $this->CumulativeRating;
1916 # return cumulative rating scaled to 1/10th (range is usually 0-10)
1929 # return current number of ratings for resource
1932 # if number of ratings not already set
1935 # obtain number of ratings
1937 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings "
1938 .
"FROM ResourceRatings "
1939 .
"WHERE ResourceId = ".$this->
Id,
1943 # recalculate cumulative rating if it looks erroneous
1946 $this->UpdateCumulativeRating();
1950 # return number of ratings to caller
1951 return $this->NumberOfRatings;
1954 # update individual rating for resource
1955 function Rating($NewRating = NULL, $UserId = NULL)
1959 # if user ID not supplied
1960 if ($UserId == NULL)
1962 # if user is logged in
1964 if ($User->IsLoggedIn())
1966 # use ID of current user
1967 $UserId = $User->Get(
"UserId");
1971 # return NULL to caller
1976 # sanitize $NewRating
1977 if (!is_null($NewRating))
1979 $NewRating = intval($NewRating);
1982 # if there is a rating for resource and user
1983 $DB->Query(
"SELECT Rating FROM ResourceRatings "
1984 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
1985 if ($Record =
$DB->FetchRow())
1987 # if new rating was supplied
1988 if ($NewRating != NULL)
1990 # update existing rating
1991 $DB->Query(
"UPDATE ResourceRatings "
1992 .
"SET Rating = ${NewRating}, DateRated = NOW() "
1993 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
1995 # update cumulative rating value
1996 $this->UpdateCumulativeRating();
1998 # return value is new rating
1999 $Rating = $NewRating;
2003 # get rating value to return to caller
2004 $Rating = $Record[
"Rating"];
2009 # if new rating was supplied
2010 if ($NewRating != NULL)
2013 $DB->Query(
"INSERT INTO ResourceRatings "
2014 .
"(ResourceId, UserId, DateRated, Rating) "
2021 # update cumulative rating value
2022 $this->UpdateCumulativeRating();
2024 # return value is new rating
2025 $Rating = $NewRating;
2029 # return value is NULL
2034 # return rating value to caller
2039 # --- Resource Comment Methods ------------------------------------------
2041 # return comments as array of Message objects
2044 # read in comments if not already loaded
2047 $this->DB->Query(
"SELECT MessageId FROM Messages "
2048 .
"WHERE ParentId = ".$this->
Id
2049 .
" AND ParentType = 2 "
2050 .
"ORDER BY DatePosted DESC");
2051 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2057 # return array of comments to caller
2058 return $this->Comments;
2061 # return current number of comments
2064 # obtain number of comments if not already set
2068 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments "
2070 .
"WHERE ParentId = ".$this->
Id
2071 .
" AND ParentType = 2",
2076 # return number of comments to caller
2077 return $this->NumberOfComments;
2081 # --- Permission Methods -------------------------------------------------
2094 return $this->CheckSchemaPermissions($User,
"View", $AllowHooksToModify);
2105 return $this->CheckSchemaPermissions($User,
"Edit");
2116 return $this->CheckSchemaPermissions($User,
"Author");
2127 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"View" );
2138 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Edit" );
2149 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2161 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2163 return $this->$CheckFn($User, $FieldOrFieldName);
2166 # ---- PRIVATE INTERFACE -------------------------------------------------
2172 private $NumberOfRatings;
2173 private $CumulativeRating;
2174 private $NumberOfComments;
2176 private $LastStatus;
2177 private $ControlledNameCache;
2178 private $ControlledNameVariantCache;
2179 private $ClassificationCache;
2180 private $PermissionCache;
2191 private function CheckSchemaPermissions($User, $CheckType, $AllowHooksToModify=TRUE)
2193 # checks against invalid reosurces should always fail
2194 if ($this->
Status() !== 1) {
return FALSE; }
2196 # construct a key to use for our permissions cache
2197 $CacheKey =
"UserCan".$CheckType.$User->Id();
2199 # if we don't have a cached value for this perm, compute one
2200 if (!isset($this->PermissionCache[$CacheKey]))
2202 # get privileges for schema
2203 $PermsFn = $CheckType.
"ingPrivileges";
2204 $SchemaPrivs = $this->Schema->$PermsFn();
2206 # check passes if user privileges are greater than resource set
2207 $CheckResult = $SchemaPrivs->MeetsRequirements($User, $this);
2209 # save the result of this check in our cache
2210 $this->PermissionCache[$CacheKey] = $CheckResult;
2213 $Value = $this->PermissionCache[$CacheKey];
2215 if ($AllowHooksToModify)
2217 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2218 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2220 "Resource" => $this,
2222 "Can".$CheckType => $Value));
2224 $Value = $SignalResult[
"Can".$CheckType];
2238 private function CheckFieldPermissions($User, $FieldOrFieldName, $CheckType)
2240 # checks against invalid resources should always fail
2241 if ($this->
Status() !== 1) {
return FALSE; }
2243 # get field object (if not supplied)
2244 $Field = is_object($FieldOrFieldName) ? $FieldOrFieldName
2245 : $this->Schema->GetFieldByName($FieldOrFieldName);
2247 # checks against invalid fields should also fail
2250 # construct a key to use for our permissions cache
2251 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2253 # if we don't have a cahced value, compute one
2254 if (!isset($this->PermissionCache[$CacheKey]))
2256 # checks for disabled fields should not pass
2257 if (!$Field->Enabled())
2259 $CheckResult = FALSE;
2263 # be sure schema privs allow View/Edit/Author for this resource
2264 $SchemaCheckFn =
"UserCan".$CheckType;
2265 if ($this->$SchemaCheckFn($User))
2267 # get appropriate privilege set for field
2268 $PermsFn = $CheckType.
"ingPrivileges";
2269 $FieldPrivs = $Field->$PermsFn();
2271 # user can View/Edit/Author if privileges are greater than field set
2272 $CheckResult = $FieldPrivs->MeetsRequirements($User, $this);
2276 $CheckResult = FALSE;
2280 # allow plugins to modify result of permission check
2281 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2282 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2284 "Resource" => $this,
2286 "Can".$CheckType => $CheckResult));
2287 $CheckResult = $SignalResult[
"Can".$CheckType];
2289 # save the result of this check in our cache
2290 $this->PermissionCache[$CacheKey] = $CheckResult;
2293 # return cached permission value
2294 return $this->PermissionCache[$CacheKey];
2297 # recalculate and save cumulative rating value for resource
2298 private function UpdateCumulativeRating()
2300 # grab totals from DB
2301 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, "
2302 .
"SUM(Rating) AS Total FROM ResourceRatings "
2303 .
"WHERE ResourceId = ".$this->
Id);
2304 $Record = $this->DB->FetchRow();
2306 # calculate new cumulative rating
2309 # save new cumulative rating in DB
2310 $this->DB->Query(
"UPDATE Resources "
2312 .
"WHERE ResourceId = ".$this->Id);
2325 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2327 # We should ignore duplicate key errors when doing inserts:
2328 $this->DB->SetQueryErrorsToIgnore( array(
2329 "/INSERT INTO ".$TableName.
"/" =>
2330 "/Duplicate entry '[0-9]+-[0-9]+' for key/"));
2332 # start out assuming no association will be added
2333 $AssociationAdded = FALSE;
2335 # convert new value to array if necessary
2336 $Values = is_array($Value) ? $Value : array($Value);
2338 # for each new value
2339 foreach ($Values as $Value)
2341 # retrieve ID from value if necessary
2342 if (is_object($Value)) { $Value = $Value->Id(); }
2344 # Try to insert a new entry for this association.
2345 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET"
2346 .
" ResourceId = ".intval($this->
Id)
2347 .
", ".$FieldName.
" = ".intval($Value)
2348 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2350 # If the insert ran without a duplicate key error,
2351 # then we added an assocation:
2352 if ($this->DB->IgnoredError() === FALSE)
2354 $AssociationAdded = TRUE;
2358 # Clear ignored errors:
2359 $this->DB->SetQueryErrorsToIgnore( NULL );
2361 # report to caller whether association was added
2362 return $AssociationAdded;
2375 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2377 # start out assuming no association will be removed
2378 $AssociationRemoved = FALSE;
2380 # convert value to array if necessary
2381 $Values = is_array($Value) ? $Value : array($Value);
2384 foreach ($Values as $Value)
2386 # retrieve ID from value if necessary
2387 if (is_object($Value)) { $Value = $Value->Id(); }
2389 # remove any intersections with target ID from DB
2390 $this->DB->Query(
"DELETE FROM ".$TableName
2391 .
" WHERE ResourceId = ".intval($this->
Id)
2392 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2393 .
" AND ".$FieldName.
" = ".intval($Value));
2394 if ($this->DB->NumRowsAffected()) { $AssociationRemoved = TRUE; }
2397 # report to caller whether association was added
2398 return $AssociationRemoved;
2401 # remove all intersections for resource and field (if any)
2402 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2404 # retrieve list of entries for this field and resource
2405 $Entries = $this->
Get($Field);
2407 # Divide them into chunks of not more than 50:
2408 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2410 # Construct a query that will remove assocations in this chunk:
2411 $this->DB->Query(
"DELETE FROM ".$TableName
2412 .
" WHERE ResourceId = ".intval($this->
Id)
2413 .
" AND ".$TargetFieldName.
" IN "
2414 .
"(".implode(
",", array_keys($Chunk)).
")");
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.
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.
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...