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/ 16 # ---- PUBLIC INTERFACE -------------------------------------------------- 29 $this->
Id = intval($ResourceId);
31 # locate resource in database 32 $this->DB->Query(
"SELECT * FROM Resources WHERE ResourceId = ".$this->
Id);
34 # if unable to locate resource 35 $Record = $this->DB->FetchRow();
38 # set status to -1 to indicate that creation failed 39 $this->LastStatus = -1;
43 # load in attributes from database 44 $this->DBFields = $Record;
47 # load our local metadata schema 48 $this->
SchemaId = $this->DBFields[
"SchemaId"];
49 if (!isset(self::$Schemas[$this->
SchemaId]))
51 self::$Schemas[$this->SchemaId] =
55 # set status to 1 to indicate that creation succeeded 56 $this->LastStatus = 1;
66 public static function Create($SchemaId)
68 # clean out any temp resource records more than three days old 70 $RFactory->CleanOutStaleTempItems(60 * 24 * 3);
72 # lock DB tables to prevent next ID from being grabbed 74 $DB->Query(
"LOCK TABLES Resources WRITE");
76 # find next temp resource ID 77 $Id = $RFactory->GetNextTempItemId();
79 # write out new resource record with temp resource ID 80 # Set DateLastModified = NOW() to avoid being pruned as a 81 # stale temp resource. 83 "INSERT INTO Resources 84 SET `ResourceId` = '".intval($Id).
"', 85 `SchemaId` = '".intval($SchemaId).
"', 86 `DateLastModified` = NOW() " );
89 $DB->Query(
"UNLOCK TABLES");
91 # create new Resource object 94 if ($Resource->Status() == -1)
96 throw new Exception(
"Resource creation failed");
99 # set some additional fields for default resources 102 $Resource->Set(
"Added By Id", $GLOBALS[
"G_User"]->
Id());
103 $Resource->Set(
"Last Modified By Id", $GLOBALS[
"G_User"]->
Id());
104 $Resource->Set(
"Date Of Record Creation", date(
"Y-m-d H:i:s"));
105 $Resource->Set(
"Date Last Modified", date(
"Y-m-d H:i:s"));
108 # for each field that can have a default value 115 foreach ($Fields as $Field)
117 # if there is a default value available 118 $DefaultValue = $Field->DefaultValue();
119 if ($DefaultValue !== NULL)
121 # if the default value is an array 122 if (is_array($DefaultValue))
124 # if there are values in the array 125 if (!empty($DefaultValue))
127 # flip values for Set() if necessary 130 $DefaultValue = array_flip($DefaultValue);
134 $Resource->Set($Field, $DefaultValue);
140 $Resource->Set($Field, $DefaultValue);
145 # update timestamps as required 147 foreach ($TimestampFields as $Field)
149 if ($Field->UpdateMethod() ==
152 $Resource->SetByField($Field,
"now");
156 # signal resource creation 157 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_CREATE", array(
158 "Resource" => $Resource,
161 # return new Resource object to caller 173 # signal that resource deletion is about to occur 175 $AF->SignalEvent(
"EVENT_RESOURCE_DELETE", array(
179 # grab list of classifications 182 # delete resource/classification intersections 184 $DB->Query(
"DELETE FROM ResourceClassInts WHERE ResourceId = ".$this->
Id());
186 # for each classification type 187 foreach ($Classifications as $ClassType => $ClassesOfType)
189 # for each classification of that type 190 foreach ($ClassesOfType as $ClassId => $ClassName)
192 # recalculate resource count for classification 194 $Class->RecalcResourceCount();
198 # delete resource references 200 DELETE FROM ReferenceInts 201 WHERE SrcResourceId = '".addslashes($this->
Id()).
"' 202 OR DstResourceId = '".addslashes($this->
Id()).
"'");
204 # delete resource/name intersections 205 $DB->Query(
"DELETE FROM ResourceNameInts WHERE ResourceId = ".$this->
Id());
207 # delete resource/user intersections 208 $DB->Query(
"DELETE FROM ResourceUserInts WHERE ResourceId = ".$this->
Id());
210 # get the list of all images associated with this resource 211 $DB->Query(
"SELECT ImageId FROM ResourceImageInts" 212 .
" WHERE ResourceId = ".intval($this->
Id()));
213 $ImageIds =
$DB->FetchColumn(
"ImageId");
215 # disassociate this resource from all images 216 $DB->Query(
"DELETE FROM ResourceImageInts" 217 .
" WHERE ResourceId = ".intval($this->
Id()));
219 # delete any images that no longer belong to any resources 220 foreach ($ImageIds as $ImageId)
222 $DB->Query(
"SELECT ResourceId FROM ResourceImageInts" 223 .
" WHERE ImageId = ".intval($ImageId) );
224 if (
$DB->NumRowsSelected() == 0)
231 # delete any associated files 233 $Files = $Factory->GetFilesForResource($this->
Id());
234 foreach ($Files as $File)
239 # delete resource record from database 240 $DB->Query(
"DELETE FROM Resources WHERE ResourceId = ".$this->
Id());
242 # drop item from search engine and recommender system 243 if ($SysConfig->SearchDBEnabled())
246 $SearchEngine->DropItem($this->
Id());
248 if ($SysConfig->RecommenderDBEnabled())
251 $Recommender->DropItem($this->
Id());
254 # get the folders containing the resource 256 $Folders = $FolderFactory->GetFoldersContainingItem(
260 # drop the resource from each folder it belongs to 261 foreach ($Folders as $Folder)
263 # mixed item type folder 264 if ($Folder->ContainsItem($this->Id,
"Resource"))
266 $Folder->RemoveItem($this->
Id,
"Resource");
269 # single item type folder 272 $Folder->RemoveItem($this->
Id);
276 # delete any resource comments 277 $DB->Query(
"DELETE FROM Messages WHERE ParentId = ".$this->
Id);
286 return $this->LastStatus;
304 return $this->SchemaId;
313 return self::$Schemas[$this->SchemaId];
324 # if new temp resource setting supplied 325 if (!is_null($NewSetting))
327 # if caller requested to switch 329 if ((($this->
Id() < 0) && ($NewSetting == FALSE))
330 || (($this->
Id() >= 0) && ($NewSetting == TRUE)))
332 # lock DB tables to prevent next ID from being grabbed 333 $DB->Query(
"LOCK TABLES Resources write");
335 # get next resource ID as appropriate 336 $OldResourceId = $this->Id;
338 if ($NewSetting == TRUE)
340 $this->
Id = $Factory->GetNextTempItemId();
344 $this->
Id = $Factory->GetNextItemId();
348 $DB->Query(
"UPDATE Resources SET ResourceId = ".
349 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
352 $DB->Query(
"UNLOCK TABLES");
354 # change associations 355 unset($this->ClassificationCache);
356 $DB->Query(
"UPDATE ResourceClassInts SET ResourceId = ".
357 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
358 unset($this->ControlledNameCache);
359 unset($this->ControlledNameVariantCache);
360 $DB->Query(
"UPDATE ResourceNameInts SET ResourceId = ".
361 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
362 $DB->Query(
"UPDATE Files SET ResourceId = ".
363 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
364 $DB->Query(
"UPDATE ReferenceInts SET SrcResourceId = ".
365 $this->
Id.
" WHERE SrcResourceId = ".$OldResourceId);
366 $DB->Query(
"UPDATE ResourceImageInts SET ResourceId = ".
367 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
368 $DB->Query(
"UPDATE ResourceUserInts SET ResourceId = ".
369 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
371 # signal event as appropriate 372 if ($NewSetting === FALSE)
374 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_ADD", array(
381 # report to caller whether we are a temp resource 382 return ($this->
Id() < 0) ? TRUE : FALSE;
386 # --- Generic Attribute Retrieval Methods ------------------------------- 394 # put our Id into the ViewPage from our schema 397 $this->
Schema()->ViewPage());
399 # return clean url, if one is available 400 return $GLOBALS[
"AF"]->GetCleanUrlForPath($Url);
416 public function Get($Field, $ReturnObject = FALSE, $IncludeVariants = FALSE)
418 # load field object if not already supplied 419 $Field = is_object($Field) ? $Field
420 : (is_numeric($Field) ? $this->
Schema()->GetField($Field)
421 : $this->
Schema()->GetFieldByName($Field));
423 # return no value found if we don't have a valid field 426 if ($Field->SchemaId() != $this->
SchemaId())
428 throw new Exception(
"Attempt to get a value for a field" 429 .
" from a different schema." 430 .
" (Field: ".$Field->Name().
" [".$Field->Id()
431 .
"], Field Schema: ".$Field->SchemaId()
432 .
", Resource Schema: ".$this->
SchemaId()
436 # grab database field name 437 $DBFieldName = $Field->DBFieldName();
439 # format return value based on field type 440 switch ($Field->Type())
445 $ReturnValue = isset($this->DBFields[$DBFieldName])
446 ? (string)$this->DBFields[$DBFieldName] : NULL;
450 $ReturnValue = isset($this->DBFields[$DBFieldName])
451 ? (int)$this->DBFields[$DBFieldName] : NULL;
455 $ReturnValue = isset($this->DBFields[$DBFieldName])
456 ? (bool)$this->DBFields[$DBFieldName] : NULL;
460 $ReturnValue = array(
"X" => (
float)$this->DBFields[$DBFieldName.
"X"],
461 "Y" => (
float)$this->DBFields[$DBFieldName.
"Y"]);
465 $Date =
new Date($this->DBFields[$DBFieldName.
"Begin"],
466 $this->DBFields[$DBFieldName.
"End"],
467 $this->DBFields[$DBFieldName.
"Precision"]);
470 $ReturnValue = $Date;
474 $ReturnValue = $Date->Formatted();
479 $ReturnValue = $this->DBFields[$DBFieldName];
483 # start with empty array 484 $ReturnValue = array();
486 # if classification cache has not been loaded 487 if (!isset($this->ClassificationCache))
489 # load all classifications associated with this resource into cache 490 $this->ClassificationCache = array();
492 "SELECT Classifications.ClassificationId," 493 .
" Classifications.FieldId,ClassificationName" 494 .
" FROM ResourceClassInts, Classifications" 495 .
" WHERE ResourceClassInts.ResourceId = ".$this->
Id 496 .
" AND ResourceClassInts.ClassificationId" 497 .
" = Classifications.ClassificationId");
498 while ($Record = $this->DB->FetchRow())
500 $ClassId = $Record[
"ClassificationId"];
501 $this->ClassificationCache[$ClassId][
"Name"]
502 = $Record[
"ClassificationName"];
503 $this->ClassificationCache[$ClassId][
"FieldId"]
504 = $Record[
"FieldId"];
507 # for each entry in classification cache 508 foreach ($this->ClassificationCache as
509 $ClassificationId => $ClassificationInfo)
511 # if classification ID matches field we are looking for 512 if ($ClassificationInfo[
"FieldId"] == $Field->Id())
514 # add field to result 517 $ReturnValue[$ClassificationId] =
522 $ReturnValue[$ClassificationId] = $ClassificationInfo[
"Name"];
530 # start with empty array 531 $ReturnValue = array();
533 # if controlled name cache has not been loaded 534 if (!isset($this->ControlledNameCache))
536 # load all controlled names associated with this resource into cache 537 $this->ControlledNameCache = array();
539 "SELECT ControlledNames.ControlledNameId," 540 .
" ControlledNames.FieldId,ControlledName" 541 .
" FROM ResourceNameInts, ControlledNames" 542 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 543 .
" AND ResourceNameInts.ControlledNameId" 544 .
" = ControlledNames.ControlledNameId" 545 .
" ORDER BY ControlledNames.ControlledName ASC");
546 while ($Record = $this->DB->FetchRow())
548 $CNameId = $Record[
"ControlledNameId"];
549 $this->ControlledNameCache[$CNameId][
"Name"]
550 = $Record[
"ControlledName"];
551 $this->ControlledNameCache[$CNameId][
"FieldId"]
552 = $Record[
"FieldId"];
556 # if variant names requested and variant name cache has not been loaded 557 if ($IncludeVariants && !isset($this->ControlledNameVariantCache))
559 # load all controlled names associated with this resource into cache 560 $this->ControlledNameVariantCache = array();
561 $this->DB->Query(
"SELECT ControlledNames.ControlledNameId," 562 .
" ControlledNames.FieldId," 563 .
" ControlledName, VariantName" 564 .
" FROM ResourceNameInts, ControlledNames, VariantNames" 565 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 566 .
" AND ResourceNameInts.ControlledNameId" 567 .
" = ControlledNames.ControlledNameId" 568 .
" AND VariantNames.ControlledNameId" 569 .
" = ControlledNames.ControlledNameId");
570 while ($Record = $this->DB->FetchRow())
572 $this->ControlledNameVariantCache[$Record[
"ControlledNameId"]][]
573 = $Record[
"VariantName"];
577 # for each entry in controlled name cache 578 foreach ($this->ControlledNameCache as
579 $CNameId => $ControlledNameInfo)
581 # if controlled name type matches field we are looking for 582 if ($ControlledNameInfo[
"FieldId"] == $Field->Id())
584 # if objects requested 587 $ReturnValue[$CNameId] =
592 # if variant names requested 593 if ($IncludeVariants)
595 # add field to result 596 $ReturnValue[] = $ControlledNameInfo[
"Name"];
598 # add any variant names to result 599 if (isset($this->ControlledNameVariantCache[$CNameId]))
601 $ReturnValue = array_merge(
603 $this->ControlledNameVariantCache[$CNameId]);
608 # add field with index to result 609 $ReturnValue[$CNameId] =
610 $ControlledNameInfo[
"Name"];
618 # start out assuming no associated users 619 $ReturnValue = array();
621 # query the database to get the associated userids 623 "SELECT UserId FROM ResourceUserInts WHERE ".
624 "ResourceId=".intval($this->
Id).
625 " AND FieldId=".intval($Field->Id()));
626 $UserIds = $this->DB->FetchColumn(
"UserId");
628 # convert each userid to either a name or a CWUser object 629 foreach ($UserIds as $UserId)
631 $User =
new CWUser(intval($UserId));
634 $ReturnValue[$UserId] = $User;
638 $ReturnValue[$UserId] = $User->Get(
"UserName");
644 # start out assuming no images will be found 645 $ReturnValue = array();
647 # find all images associated with this resource 648 $this->DB->Query(
"SELECT ImageId FROM ResourceImageInts" 649 .
" WHERE ResourceId = ".intval($this->
Id())
650 .
" AND FieldId = ".intval($Field->Id()));
652 # if images were found 653 if ($this->DB->NumRowsSelected())
655 # if we are to return an object 656 $ImageIds = $this->DB->FetchColumn(
"ImageId");
659 # load array of Image objects for return value 660 foreach ($ImageIds as $ImageId)
662 $ReturnValue[$ImageId] =
new SPTImage($ImageId);
667 # load array of Image ids for return value 668 $ReturnValue = $ImageIds;
674 # retrieve files using factory 677 $this->
Id, $ReturnObject);
681 # query for resource references 683 SELECT * FROM ReferenceInts 684 WHERE FieldId = '".addslashes($Field->Id()).
"' 685 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
687 $ReturnValue = array();
689 # return each reference as a Resource object 692 $FoundErrors = FALSE;
694 while (FALSE !== ($Record = $this->DB->FetchRow()))
696 $ReferenceId = $Record[
"DstResourceId"];
697 $Reference =
new Resource($ReferenceId);
699 # the reference is bad, so flag that there were errors 700 if ($Reference->Status() != 1)
707 $ReturnValue[$ReferenceId] = $Reference;
711 # try to fix the errors by removing any references to 712 # resources that were bad 715 $this->
Set($Field, $ReturnValue);
719 # return each reference as a resource ID 722 while (FALSE !== ($Record = $this->DB->FetchRow()))
724 $ReferenceId = $Record[
"DstResourceId"];
725 $ReturnValue[$ReferenceId] = $ReferenceId;
732 exit(
"<br>SPT - ERROR: attempt to retrieve " 733 .
"unknown resource field type (".$Field->Type().
")<br>\n");
737 # return formatted value to caller 761 $FieldNameOrObject, $ReturnObject = TRUE, $IncludeVariants = FALSE)
763 # normalize metadata field for use by any hooked code 764 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
765 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
768 $Value = $this->
Get($Field, $ReturnObject, $IncludeVariants);
770 # signal event to allowed hooked code to modify value 771 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
772 "EVENT_FIELD_DISPLAY_FILTER", array(
777 # return possibly modified value to caller 778 return $SignalResult[
"Value"];
797 $ReturnObject = FALSE, $IncludeVariants = FALSE)
799 return $this->
Get($FieldNameOrObject, $ReturnObject, $IncludeVariants);
817 $FieldId, $ReturnObject = FALSE, $IncludeVariants = FALSE)
819 return $this->
Get($FieldId, $ReturnObject, $IncludeVariants);
834 public function GetAsArray($IncludeDisabledFields = FALSE, $ReturnObjects = TRUE)
836 # retrieve field info 837 $Fields = $this->
Schema()->GetFields();
840 foreach ($Fields as $Field)
842 # if field is enabled or caller requested disabled fields 843 if ($Field->Enabled() || $IncludeDisabledFields)
845 # retrieve info and add it to the array 846 $FieldStrings[$Field->Name()] = $this->
Get($Field, $ReturnObjects);
848 # if field uses qualifiers 849 if ($Field->UsesQualifiers())
851 # get qualifier attributes and add to the array 852 $FieldStrings[$Field->Name().
" Qualifier"] =
858 # add in internal values 859 $FieldStrings[
"ResourceId"] = $this->
Id();
862 # return array to caller 863 return $FieldStrings;
881 $MappedName, $ReturnObject = FALSE, $IncludeVariants = FALSE)
883 $Schema = $this->
Schema();
884 $FieldId = $Schema->StdNameToFieldMapping($MappedName);
886 ? $this->
Get($FieldId, $ReturnObject, $IncludeVariants)
900 $Field = $this->
Schema()->GetFieldByName($FieldName);
914 $Field = $this->
Schema()->GetField($FieldId);
928 # return NULL if field is invalid 931 # assume no qualifiers if not otherwise determined 934 # if field uses qualifiers 935 if ($Field->UsesQualifiers())
937 # retrieve qualifiers based on field type 938 switch ($Field->Type())
943 # retrieve list of items 946 # if field uses item-level qualifiers 947 if ($Field->HasItemLevelQualifiers())
949 # determine general item name in DB 951 ?
"Classification" :
"ControlledName";
954 foreach (
$Items as $ItemId => $ItemName)
956 # look up qualifier for item 957 $QualId = $this->DB->Query(
958 "SELECT * FROM ".$TableName.
"s" 959 .
" WHERE ".$TableName.
"Id = ".$ItemId,
965 # if object was requested by caller 968 # load qualifier and add to return value array 969 $ReturnValue[$ItemId] =
new Qualifier($QualId);
973 # add qualifier ID to return value array 974 $ReturnValue[$ItemId] = $QualId;
979 # add NULL to return value array for this item 980 $ReturnValue[$ItemId] = NULL;
987 foreach (
$Items as $ItemId => $ItemName)
989 # if object was requested by caller 992 # load default qualifier and add to return value array 994 $Field->DefaultQualifier());
998 # add default qualifier ID to return value array 999 $ReturnValue[$ItemId] = $Field->DefaultQualifier();
1006 # if field uses item-level qualifiers 1007 if ($Field->HasItemLevelQualifiers())
1009 # if qualifier available 1010 if ($this->DBFields[$Field->DBFieldName().
"Qualifier"] > 0)
1012 # if object was requested by caller 1013 $QFieldName = $Field->DBFieldName().
"Qualifier";
1016 # return qualifier for field 1018 $this->DBFields[$QFieldName]);
1022 # return qualifier ID for field 1023 $ReturnValue = $this->DBFields[$QFieldName];
1029 # if default qualifier available 1030 if ($Field->DefaultQualifier() > 0)
1032 # if object was requested by caller 1035 # return default qualifier 1036 $ReturnValue =
new Qualifier($Field->DefaultQualifier());
1040 # return default qualifier ID 1041 $ReturnValue = $Field->DefaultQualifier();
1049 # return qualifier object or ID (or array of same) to caller 1050 return $ReturnValue;
1060 public function FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
1062 # load field object if needed 1063 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1064 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
1066 # return no value found if we don't have a valid field 1070 $Value = $this->
Get($Field);
1072 # checks depend on the field type 1073 switch ($Field->Type())
1079 return isset($Value)
1081 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
1084 return isset($Value)
1088 return isset($Value[
"X"])
1089 && isset($Value[
"Y"])
1090 && strlen(trim($Value[
"X"]))
1091 && strlen(trim($Value[
"Y"]));
1094 return isset($Value)
1095 && strlen(trim($Value))
1096 && $Value !=
"0000-00-00";
1099 return isset($Value)
1100 && strlen(trim($Value))
1101 && $Value !=
"0000-00-00 00:00:00";
1109 return count($Value) > 0;
1113 return isset($Value)
1115 && $Factory->UserNameExists($Value);
1134 # get our target field and extract its values 1135 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1136 : $this->
Schema()->GetField($FieldNameOrObject);
1137 $Images = $this->
Get($Field, TRUE);
1139 # iterate over our images getting URLs for each 1141 foreach ($Images as $Image)
1143 $Result[$Image->Id()] = $Image->GetImageUrlForResource(
1144 $this->
Id(), $Field->Id(), $Index, $ImageSize);
1151 # --- Generic Attribute Setting Methods --------------------------------- 1165 public function Set($Field, $NewValue, $Reset=FALSE)
1167 # load field object if not already supplied 1168 $Field = is_object($Field) ? $Field
1169 : (is_numeric($Field) ? $this->
Schema()->GetField($Field)
1170 : $this->
Schema()->GetFieldByName($Field));
1172 # return if we don't have a valid field 1175 if ($Field->SchemaId() != $this->
SchemaId())
1177 throw new Exception(
"Attempt to set a value for a field " 1178 .
"from a different schema.");
1181 # grab commonly-used values for local use 1183 $ResourceId = $this->Id;
1185 # grab database field name 1186 $DBFieldName = $Field->DBFieldName();
1188 # Flag to deterimine if we've actually changed anything. 1189 $UpdateModTime = FALSE;
1191 # store value in DB based on field type 1192 switch ($Field->Type())
1197 if ($this->DBFields[$DBFieldName] != $NewValue)
1199 # save value directly to DB 1200 $DB->Query(
"UPDATE Resources SET `" 1201 .$DBFieldName.
"` = '".addslashes($NewValue).
"' " 1202 .
"WHERE ResourceId = ".$ResourceId);
1204 # save value locally 1205 $this->DBFields[$DBFieldName] = $NewValue;
1206 $UpdateModTime=TRUE;
1211 if ( $this->DBFields[$DBFieldName] != $NewValue )
1213 # save value directly to DB 1214 if (is_null($NewValue))
1216 $DB->Query(
"UPDATE Resources SET `" 1217 .$DBFieldName.
"` = NULL" 1218 .
" WHERE ResourceId = ".$ResourceId);
1222 $DB->Query(
"UPDATE Resources SET `" 1223 .$DBFieldName.
"` = ".intval($NewValue)
1224 .
" WHERE ResourceId = ".$ResourceId);
1227 # save value locally 1228 $this->DBFields[$DBFieldName] = $NewValue;
1229 $UpdateModTime = TRUE;
1235 if ($this->DBFields[$DBFieldName.
"X"] != $NewValue[
"X"] ||
1236 $this->DBFields[$DBFieldName.
"Y"] != $NewValue[
"Y"] )
1238 if (is_null($NewValue))
1240 $DB->Query(
"UPDATE Resources SET " 1241 .
"`".$DBFieldName.
"X` = NULL, " 1242 .
"`".$DBFieldName.
"Y` = NULL " 1243 .
"WHERE ResourceId = ".$ResourceId);
1244 $this->DBFields[$DBFieldName.
"X"] = NULL;
1245 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1249 $DB->Query(
"UPDATE Resources SET " 1250 .
"`".$DBFieldName.
"X` = " .(strlen($NewValue[
"X"])
1251 ?
"'".$NewValue[
"X"].
"'" :
"NULL").
", " 1252 .
"`".$DBFieldName.
"Y` = ".(strlen($NewValue[
"Y"])
1253 ?
"'".$NewValue[
"Y"].
"'" :
"NULL")
1254 .
" WHERE ResourceId = ".$ResourceId);
1256 $Digits = $Field->PointDecimalDigits();
1258 $this->DBFields[$DBFieldName.
"X"] =
1259 strlen($NewValue[
"X"]) ?
1260 round($NewValue[
"X"], $Digits) : NULL;
1261 $this->DBFields[$DBFieldName.
"Y"] =
1262 strlen($NewValue[
"Y"]) ?
1263 round($NewValue[
"Y"], $Digits) : NULL;
1265 $UpdateModTime = TRUE;
1270 if ($this->DBFields[$DBFieldName] != $NewValue)
1272 # save value directly to DB 1273 if (is_null($NewValue))
1275 $DB->Query(
"UPDATE Resources SET `" 1276 .$DBFieldName.
"` = NULL" 1277 .
" WHERE ResourceId = ".$ResourceId);
1281 $NewValue = $NewValue ?
"1" :
"0";
1282 $DB->Query(
"UPDATE Resources SET `" 1283 .$DBFieldName.
"` = ".$NewValue
1284 .
" WHERE ResourceId = ".$ResourceId);
1287 $this->DBFields[$DBFieldName] = $NewValue;
1289 # recalculate counts for any associated classifications if necessary 1290 if ($DBFieldName ==
"ReleaseFlag")
1292 $DB->Query(
"SELECT ClassificationId FROM ResourceClassInts" 1293 .
" WHERE ResourceId = ".$ResourceId);
1294 while ($ClassId =
$DB->FetchField(
"ClassificationId"))
1297 $Class->RecalcResourceCount();
1300 $UpdateModTime = TRUE;
1305 $OldValue = $this->
Get($Field);
1306 # value comes back as array (UserId => UserName), just get the Ids 1307 $OldValue = array_keys($OldValue);
1309 # input to Set() for these fields is one of 1310 # 1. an int specifying a UserId 1311 if (is_numeric($NewValue))
1313 $NewValue = array($NewValue);
1315 # 2. a CWUser object 1316 elseif ($NewValue instanceof
CWUser)
1318 $NewValue = array($NewValue->Id());
1320 # 3. an array keyed by UserId (don't care about the values) 1321 elseif (is_array($NewValue))
1323 $NewValue = array_keys($NewValue);
1327 throw new Exception(
"Unknown format for NewValue in a User field");
1330 # if this is a unique field, only accept the first of the options given 1331 if ($Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1333 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1336 # sort new and old values so we can directly compare 1340 # if the value has changed 1341 if ($OldValue != $NewValue)
1343 if ($Reset || $Field->AllowMultiple() == FALSE )
1345 $ToRemove = array_diff($OldValue, $NewValue);
1346 $this->RemoveAssociation(
1347 "ResourceUserInts",
"UserId", $ToRemove, $Field);
1350 # associate with resource if not already associated 1351 $this->AddAssociation(
"ResourceUserInts",
1355 $UpdateModTime=TRUE;
1360 # if we were given a date object 1361 if (is_object($NewValue))
1363 # use supplied date object 1368 # create date object 1369 $Date =
new Date($NewValue);
1372 $OldDate =
new Date(
1373 $this->DBFields[$DBFieldName.
"Begin"],
1374 $this->DBFields[$DBFieldName.
"End"]);
1376 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1377 $OldDate->EndDate() != $Date->EndDate() ||
1378 $OldDate->Precision() != $Date->Precision() )
1380 # extract values from date object and store in DB 1381 $BeginDate =
"'".$Date->BeginDate().
"'";
1382 if (strlen($BeginDate) < 3) { $BeginDate =
"NULL"; }
1383 $EndDate =
"'".$Date->EndDate().
"'";
1384 if (strlen($EndDate) < 3) { $EndDate =
"NULL"; }
1386 $DB->Query(
"UPDATE Resources SET " 1387 .$DBFieldName.
"Begin = ".$BeginDate.
", " 1388 .$DBFieldName.
"End = ".$EndDate.
", " 1389 .$DBFieldName.
"Precision = '".$Date->Precision().
"' " 1390 .
"WHERE ResourceId = ".$ResourceId);
1392 # save values locally 1393 $this->DBFields[$DBFieldName.
"Begin"] = $Date->BeginDate();
1394 $this->DBFields[$DBFieldName.
"End"] = $Date->EndDate();
1395 $this->DBFields[$DBFieldName.
"Precision"] = $Date->Precision();
1396 $UpdateModTime=TRUE;
1401 if (is_null($NewValue) || !strlen(trim($NewValue)))
1403 $DateValue = $NewValue;
1405 if (!is_null($this->DBFields[$DBFieldName]))
1407 # save value directly to DB 1408 $DB->Query(
"UPDATE Resources SET " 1409 .
"`".$DBFieldName.
"` = NULL " 1410 .
"WHERE ResourceId = ".$ResourceId);
1411 $UpdateModTime = TRUE;
1416 # assume value is date and use directly 1417 $TimestampValue = strtotime($NewValue);
1419 # use the new value if the date is valid 1420 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1422 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1424 if ($this->DBFields[$DBFieldName] != $DateValue)
1426 # save value directly to DB 1427 $DB->Query(
"UPDATE Resources SET " 1428 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' " 1429 .
"WHERE ResourceId = ".$ResourceId);
1430 $UpdateModTime=TRUE;
1434 # continue using the old value if invalid 1437 $DateValue = $this->
Get($Field);
1441 # save value locally 1442 $this->DBFields[$DBFieldName] = $DateValue;
1446 $OldValue = $this->
Get($Field);
1448 # if incoming value is array 1449 if (is_array($NewValue))
1451 if ($OldValue != $NewValue)
1455 # remove values that were in the old value 1456 # but not the new one 1457 $ToRemove = array_diff(array_keys($OldValue),
1458 array_keys($NewValue));
1459 foreach ($ToRemove as $ClassificationId)
1461 $this->RemoveAssociation(
"ResourceClassInts",
1467 $Class->RecalcResourceCount();
1472 # for each element of array 1473 foreach ($NewValue as
1474 $ClassificationId => $ClassificationName)
1477 if ($Class->FieldId() == $Field->Id())
1481 # associate with resource if not already associated 1482 if ($this->AddAssociation(
"ResourceClassInts",
1484 $ClassificationId) )
1486 $Class->UpdateLastAssigned();
1487 $Class->RecalcResourceCount();
1493 throw new Exception(
1494 "Attempting to store classification from " 1495 .
"Field ".$Class->FieldId().
" into Field " 1501 $UpdateModTime=TRUE;
1506 # associate with resource if not already associated 1507 if (is_object($NewValue))
1510 $NewValue = $Class->Id();
1517 if (!array_key_exists($Class->Id(), $OldValue))
1520 $this->AddAssociation(
"ResourceClassInts",
1523 $Class->UpdateLastAssigned();
1524 $Class->RecalcResourceCount();
1525 $UpdateModTime=TRUE;
1529 # clear our classification cache 1532 unset($this->ClassificationCache);
1538 $OldValue = $this->
Get($Field);
1540 # input to Set() for these fields is one of 1541 # 1. an int specifying a ControlledNameId 1542 # 2. a ControlledName object 1543 # 3. an array with keys giving Ids and values giving ControlledNames 1545 # normalize 1 and 2 into 3 for simplicity of processing 1546 if (is_object($NewValue) || !is_array($NewValue) )
1548 if (!is_object($NewValue))
1553 $TmpValue = array();
1554 $TmpValue[$NewValue->Id()] = $NewValue->Name();
1556 $NewValue = $TmpValue;
1559 # if this is a unique field, only accept the first of the options given 1560 # NB: all ControlledNames implicitly AllowMultiple 1562 $Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1564 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1567 # if the value has changed 1568 if ($OldValue != $NewValue)
1571 && $Field->AllowMultiple() == FALSE ) )
1573 $ToRemove = array_diff(array_keys($OldValue),
1574 array_keys($NewValue));
1575 foreach ($ToRemove as $CNId)
1577 $this->RemoveAssociation(
"ResourceNameInts",
1583 # for each element of array 1584 foreach ($NewValue as $ControlledNameId => $ControlledName)
1586 # associate with resource if not already associated 1587 if ($this->AddAssociation(
"ResourceNameInts",
1594 $this->RemoveAssociation(
"ResourceNameInts",
1595 "ControlledNameId", $ControlledNameId);
1596 throw new InvalidArgumentException(
1597 "Attempt to set controlled name with" 1598 .
" invalid ID (".$ControlledNameId.
").");
1600 $CN->UpdateLastAssigned();
1603 $UpdateModTime = TRUE;
1608 # clear our controlled name cache 1609 unset($this->ControlledNameCache);
1610 unset($this->ControlledNameVariantCache);
1612 # clear visible count cache for any affected resources 1613 $ValueIds = array_keys($OldValue) + array_keys($NewValue);
1615 "DELETE FROM VisibleResourceCounts WHERE " 1616 .
"SchemaId=".intval($this->
SchemaId).
" AND " 1617 .
"ValueId IN (".implode(
",", $ValueIds).
")");
1623 # associate value(s) with resource 1624 $this->AddAssociation(
1625 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1626 # clear cached image mappings 1631 # convert incoming value to array if necessary 1632 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1634 # for each incoming file 1636 foreach ($NewValue as $File)
1639 $NewFile = $Factory->
Copy($File);
1641 # associate copy with this resource and field 1642 $NewFile->ResourceId($this->
Id);
1643 $NewFile->FieldId($Field->Id());
1645 # Since we make a fresh copy of the File whenever Set is called, 1646 # we'll always update the modification time for this field. 1647 $UpdateModTime = TRUE;
1651 # convert incoming value to array to simplify the workflow 1652 if (is_scalar($NewValue) || $NewValue instanceof
Resource)
1654 $NewValue = array($NewValue);
1657 # delete existing resource references 1660 # add each reference 1661 foreach ($NewValue as $ReferenceOrId)
1663 # initially issume it's a reference ID and not an object... 1664 $ReferenceId = $ReferenceOrId;
1666 # ... but get the reference ID if it's an object 1667 if ($ReferenceOrId instanceof
Resource)
1669 $ReferenceId = $ReferenceOrId->Id();
1672 # skip blank reference IDs 1673 if (strlen(trim($ReferenceId)) < 1)
1678 # skip reference IDs that don't look right 1679 if (!is_numeric($ReferenceId))
1684 # skip references to the current resource 1685 if ($ReferenceId == $this->
Id())
1690 # add the reference to the references table 1692 INSERT INTO ReferenceInts ( 1697 ".addslashes($Field->Id()).
", 1698 ".addslashes($this->
Id()).
", 1699 ".addslashes($ReferenceId).
")");
1705 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1711 # update modification timestamps 1713 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1714 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 1715 .
"WHERE ResourceId=".$this->
Id.
" AND " 1716 .
"FieldId=".$Field->Id() );
1717 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 1718 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 1719 .$this->
Id.
",".$Field->Id().
"," 1720 .$UserId.
",NOW())");
1722 # on resource modification, clear the UserPermsCache entry 1723 # so that stale permissions checks are not cached 1724 $DB->Query(
"DELETE FROM UserPermsCache WHERE ResourceId=".$this->
Id);
1737 $this->
Set($Field, $NewValue);
1749 $this->
Set($FieldId, $NewValue);
1759 $Field = $this->
Schema()->GetFieldByName($FieldName);
1770 $Field = $this->
Schema()->GetField($FieldId);
1781 # if field uses qualifiers and uses item-level qualifiers 1782 if ($Field->UsesQualifiers() && $Field->HasItemLevelQualifiers())
1784 # if qualifier object passed in 1785 if (is_object($NewValue))
1787 # grab qualifier ID from object 1788 $QualifierId = $NewValue->Id();
1792 # assume value passed in is qualifier ID 1793 $QualifierId = $NewValue;
1796 # update qualifier value in database 1797 $DBFieldName = $Field->DBFieldName();
1798 $this->DB->Query(
"UPDATE Resources SET " 1799 .$DBFieldName.
"Qualifier = '".$QualifierId.
"' " 1800 .
"WHERE ResourceId = ".$this->Id);
1802 # update local qualifier value 1803 $this->DBFields[$DBFieldName.
"Qualifier"] = $QualifierId;
1815 $Field = $this->
Schema()->GetField($FieldId);
1816 $this->
Clear($Field, $ValueToClear);
1825 public function Clear($Field, $ValueToClear = NULL)
1827 # convert field name to object if necessary 1828 if (!is_object($Field))
1830 $Field = $this->
Schema()->GetFieldByName($Field);
1833 # grab commonly-used values for local use 1835 $ResourceId = $this->Id;
1837 # grab database field name 1838 $DBFieldName = $Field->DBFieldName();
1840 $UpdateModTime=FALSE;
1842 # store value in DB based on field type 1843 switch ($Field->Type())
1851 if (strlen($this->DBFields[$DBFieldName])>0)
1854 $DB->Query(
"UPDATE Resources SET `" 1855 .$DBFieldName.
"` = NULL " 1856 .
"WHERE ResourceId = ".$ResourceId);
1858 # clear value locally 1859 $this->DBFields[$DBFieldName] = NULL;
1860 $UpdateModTime=TRUE;
1865 if (!is_null($this->DBFields[$DBFieldName.
"X"]) ||
1866 !is_null($this->DBFields[$DBFieldName.
"Y"]) )
1869 $DB->Query(
"UPDATE Resources SET " 1870 .
"`".$DBFieldName.
"X` = NULL ," 1871 .
"`".$DBFieldName.
"Y` = NULL " 1872 .
"WHERE ResourceId = ".$ResourceId);
1874 # Clear local values 1875 $this->DBFields[$DBFieldName.
"X"] = NULL;
1876 $this->DBFields[$DBFieldName.
"Y"] = NULL;
1877 $UpdateModTime=TRUE;
1882 if (!is_null($this->DBFields[$DBFieldName.
"Begin"]) ||
1883 !is_null($this->DBFields[$DBFieldName.
"End"]) ||
1884 !is_null($this->DBFields[$DBFieldName.
"Precision"]))
1886 # clear date object values in DB 1887 $DB->Query(
"UPDATE Resources SET " 1888 .$DBFieldName.
"Begin = '', " 1889 .$DBFieldName.
"End = '', " 1890 .$DBFieldName.
"Precision = '' " 1891 .
"WHERE ResourceId = ".$ResourceId);
1893 # clear value locally 1894 $this->DBFields[$DBFieldName.
"Begin"] = NULL;
1895 $this->DBFields[$DBFieldName.
"End"] = NULL;
1896 $this->DBFields[$DBFieldName.
"Precision"] = NULL;
1897 $UpdateModTime=TRUE;
1902 $OldValue = $this->
Get($Field);
1904 # if value to clear supplied 1905 if ($ValueToClear !== NULL)
1907 # if supplied value is array 1908 if (is_array($ValueToClear))
1910 # for each element of array 1911 foreach ($ValueToClear as $ClassificationId => $Dummy)
1913 if (array_key_exists($ClassificationId, $OldValue))
1915 # remove association with resource (if any) 1916 $this->RemoveAssociation(
"ResourceClassInts",
1920 $Class->RecalcResourceCount();
1921 $UpdateModTime=TRUE;
1927 if (array_key_exists($ValueToClear, $OldValue))
1929 # remove association with resource (if any) 1930 $this->RemoveAssociation(
"ResourceClassInts",
1934 $Class->RecalcResourceCount();
1935 $UpdateModTime=TRUE;
1941 if (count($OldValue)>0)
1943 # remove all associations for resource and field 1944 $this->RemoveAllAssociations(
1945 "ResourceClassInts",
"ClassificationId", $Field);
1947 # recompute resource count 1948 $Values = $this->
Get($Field);
1949 foreach ($Values as $ClassificationId => $Dummy)
1952 $Class->RecalcResourceCount();
1954 $UpdateModTime=TRUE;
1958 # clear our classification cache 1961 unset($this->ClassificationCache);
1967 $OldValue = $this->
Get($Field);
1968 # if value to clear supplied 1969 if ($ValueToClear !== NULL)
1971 # if incoming value is array 1972 if (is_array($ValueToClear))
1974 # for each element of array 1975 foreach ($ValueToClear as $ControlledNameId =>
1978 if (array_key_exists($ControlledNameId, $OldValue))
1980 # remove association with resource (if any) 1981 $this->RemoveAssociation(
"ResourceNameInts",
1984 $UpdateModTime=TRUE;
1990 if (array_key_exists($ValueToClear, $OldValue))
1992 # remove association with resource (if any) 1993 $this->RemoveAssociation(
"ResourceNameInts",
1996 $UpdateModTime=TRUE;
2002 if (count($OldValue)>0)
2004 # remove all associations for resource and field 2005 $this->RemoveAllAssociations(
2006 "ResourceNameInts",
"ControlledNameId", $Field);
2007 $UpdateModTime=TRUE;
2013 # clear our controlled name cache 2014 unset($this->ControlledNameCache);
2015 unset($this->ControlledNameVariantCache);
2020 $OldValue = $this->
Get($Field);
2022 # if value to clear supplied 2023 if ($ValueToClear !== NULL)
2025 # if incoming value is array 2026 if (is_array($ValueToClear))
2028 # for each element of array 2029 foreach ($ValueToClear as $UserId => $User)
2031 if (array_key_exists($UserId, $OldValue))
2033 # remove association with resource (if any) 2034 $this->RemoveAssociation(
"ResourceUserInts",
2038 $UpdateModTime=TRUE;
2044 if (array_key_exists($ValueToClear, $OldValue))
2046 # remove association with resource (if any) 2047 $this->RemoveAssociation(
"ResourceUserInts",
2051 $UpdateModTime=TRUE;
2057 if (count($OldValue)>0)
2059 # remove all associations for resource and field 2060 $this->RemoveAllAssociations(
2061 "ResourceUserInts",
"UserId", $Field);
2062 $UpdateModTime=TRUE;
2069 # if value to clear supplied 2070 if ($ValueToClear !== NULL)
2072 # convert value to array if necessary 2073 $Files = $ValueToClear;
2074 if (!is_array($Files)) { $Files = array($Files); }
2076 # convert values to objects if necessary 2077 foreach ($Files as $Index => $File)
2079 if (!is_object($File))
2081 $Files[$Index] =
new File($File);
2087 # use all files associated with resource 2088 $Files = $this->
Get($Field, TRUE);
2092 foreach ($Files as $File) { $File->Delete(); }
2096 # if value to clear supplied 2097 if ($ValueToClear !== NULL)
2099 # convert value to array if necessary 2100 $Images = $ValueToClear;
2101 if (!is_array($Images)) { $Images = array($Images); }
2103 # convert values to objects if necessary 2104 foreach ($Images as $Index => $Image)
2106 if (!is_object($Image))
2108 $Images[$Index] =
new SPTImage($Image);
2114 # use all images associated with resource 2115 $Images = $this->
Get($Field, TRUE);
2118 # delete images if we are the last resource referencing 2119 # a particular image. 2120 foreach ($Images as $Image)
2122 $Cnt = $this->DB->Query(
2123 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
2124 "ImageId=".$Image->Id(),
"Cnt");
2131 # clear cached image mappings 2134 # remove connections to images 2135 $UpdateModTime = $this->RemoveAssociation(
2136 "ResourceImageInts",
"ImageId", $Images, $Field);
2140 # remove references from the references table 2142 DELETE FROM ReferenceInts 2143 WHERE FieldId = '".addslashes($Field->Id()).
"' 2144 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
2149 exit(
"<br>SPT - ERROR: attempt to clear " 2150 .
"unknown resource field type<br>\n");
2156 # update modification timestamps 2158 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
2159 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 2160 .
"WHERE ResourceId=".$this->
Id.
" AND " 2161 .
"FieldId=".$Field->Id() );
2162 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 2163 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 2164 .$this->
Id.
",".$Field->Id().
"," 2165 .$UserId.
",NOW())");
2179 $this->
Clear($Field, $ValueToClear);
2182 # --- Field-Specific or Type-Specific Attribute Retrieval Methods ------- 2193 # start with empty array 2196 # for each controlled name 2197 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, " 2198 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, " 2199 .
"Classifications, MetadataFields " 2200 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" " 2201 .
"AND ResourceClassInts.ClassificationId = " 2202 .
"Classifications.ClassificationId " 2203 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
2204 while ($Record =
$DB->FetchRow())
2207 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
2208 $Record[
"ClassificationName"];
2211 # return array to caller 2216 # --- Ratings Methods --------------------------------------------------- 2224 return $this->CumulativeRating;
2249 # if number of ratings not already set 2252 # obtain number of ratings 2254 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings " 2255 .
"FROM ResourceRatings " 2256 .
"WHERE ResourceId = ".$this->
Id,
2260 # recalculate cumulative rating if it looks erroneous 2263 $this->UpdateCumulativeRating();
2267 # return number of ratings to caller 2268 return $this->NumberOfRatings;
2278 public function Rating($NewRating = NULL, $UserId = NULL)
2282 # if user ID not supplied 2283 if ($UserId == NULL)
2285 # if user is logged in 2287 if ($User->IsLoggedIn())
2289 # use ID of current user 2290 $UserId = $User->Get(
"UserId");
2294 # return NULL to caller 2299 # sanitize $NewRating 2300 if (!is_null($NewRating))
2302 $NewRating = intval($NewRating);
2305 # if there is a rating for resource and user 2306 $DB->Query(
"SELECT Rating FROM ResourceRatings " 2307 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2308 if ($Record =
$DB->FetchRow())
2310 # if new rating was supplied 2311 if ($NewRating != NULL)
2313 # update existing rating 2314 $DB->Query(
"UPDATE ResourceRatings " 2315 .
"SET Rating = ${NewRating}, DateRated = NOW() " 2316 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2318 # update cumulative rating value 2319 $this->UpdateCumulativeRating();
2321 # return value is new rating 2322 $Rating = $NewRating;
2326 # get rating value to return to caller 2327 $Rating = $Record[
"Rating"];
2332 # if new rating was supplied 2333 if ($NewRating != NULL)
2336 $DB->Query(
"INSERT INTO ResourceRatings " 2337 .
"(ResourceId, UserId, DateRated, Rating) " 2344 # update cumulative rating value 2345 $this->UpdateCumulativeRating();
2347 # return value is new rating 2348 $Rating = $NewRating;
2352 # return value is NULL 2357 # return rating value to caller 2362 # --- Resource Comment Methods ------------------------------------------ 2370 # read in comments if not already loaded 2373 $this->DB->Query(
"SELECT MessageId FROM Messages " 2374 .
"WHERE ParentId = ".$this->
Id 2375 .
" AND ParentType = 2 " 2376 .
"ORDER BY DatePosted DESC");
2377 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2383 # return array of comments to caller 2384 return $this->Comments;
2393 # obtain number of comments if not already set 2397 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments " 2399 .
"WHERE ParentId = ".$this->
Id 2400 .
" AND ParentType = 2",
2405 # return number of comments to caller 2406 return $this->NumberOfComments;
2410 # --- Permission Methods ------------------------------------------------- 2423 return $this->CheckSchemaPermissions($User,
"View", $AllowHooksToModify);
2434 return $this->CheckSchemaPermissions($User,
"Edit");
2445 return $this->CheckSchemaPermissions($User,
"Author");
2456 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit");
2457 return $this->$CheckFn($User);
2468 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"View" );
2479 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Edit" );
2490 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2502 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2504 return $this->$CheckFn($User, $FieldOrFieldName);
2507 # --- Utility Methods ---------------------------------------------------- 2517 $SearchEngine->QueueUpdateForItem($this);
2520 $Recommender->QueueUpdateForItem($this);
2531 # if schema IDs are not loaded 2532 if (!isset(self::$SchemaIdCache))
2536 $DB->Query(
"SELECT ResourceId, SchemaId FROM Resources");
2537 self::$SchemaIdCache =
$DB->FetchColumn(
"SchemaId",
"ResourceId");
2540 # if multiple resources specified 2541 if (is_array($ResourceId))
2543 # find schema IDs for specified resources 2544 $SchemaIds = array_intersect_key(self::$SchemaIdCache,
2545 array_flip($ResourceId));
2547 # check that specified resource IDs were all valid 2548 if (count($SchemaIds) < count($ResourceId))
2550 $BadIds = array_diff($ResourceId, array_keys($SchemaIds));
2551 throw new InvalidArgumentException(
"Unknown resource IDs (" 2552 .implode(
", ", $BadIds).
").");
2555 # return schema IDs to caller 2560 # check that specified resource was valid 2561 if (!isset(self::$SchemaIdCache[$ResourceId]))
2563 throw new InvalidArgumentException(
"Unknown resource ID (" 2567 # return schema IDs for specified resource 2568 return self::$SchemaIdCache[$ResourceId];
2573 # ---- PRIVATE INTERFACE ------------------------------------------------- 2577 private $ClassificationCache;
2579 private $ControlledNameCache;
2580 private $ControlledNameVariantCache;
2581 private $CumulativeRating;
2583 private $LastStatus;
2584 private $NumberOfComments;
2585 private $NumberOfRatings;
2586 private $PermissionCache;
2589 static private $Schemas;
2590 static private $SchemaIdCache;
2602 private function CheckSchemaPermissions($User, $CheckType, $AllowHooksToModify=TRUE)
2604 # checks against invalid resources should always fail 2605 if ($this->
Status() !== 1) {
return FALSE; }
2607 # construct a key to use for our permissions cache 2608 $CacheKey =
"UserCan".$CheckType.$User->Id();
2610 # if we don't have a cached value for this perm, compute one 2611 if (!isset($this->PermissionCache[$CacheKey]))
2613 # get privileges for schema 2614 $PermsFn = $CheckType.
"ingPrivileges";
2615 $SchemaPrivs = $this->
Schema()->$PermsFn();
2617 # check passes if user privileges are greater than resource set 2618 $CheckResult = $SchemaPrivs->MeetsRequirements($User, $this);
2620 # save the result of this check in our cache 2621 $this->PermissionCache[$CacheKey] = $CheckResult;
2624 $Value = $this->PermissionCache[$CacheKey];
2626 if ($AllowHooksToModify)
2628 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2629 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2631 "Resource" => $this,
2633 "Can".$CheckType => $Value,
2634 "Schema" => $this->
Schema(), ));
2636 $Value = $SignalResult[
"Can".$CheckType];
2650 private function CheckFieldPermissions($User, $Field, $CheckType)
2652 # checks against invalid resources should always fail 2653 if ($this->
Status() !== 1) {
return FALSE; }
2655 # get field object (if not supplied) 2660 $Field = $this->
Schema()->GetField($Field);
2662 catch (InvalidArgumentException $Exception)
2664 # (user cannot view/author/edit if field was invalid) 2669 # construct a key to use for our permissions cache 2670 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2672 # if we don't have a cahced value, compute one 2673 if (!isset($this->PermissionCache[$CacheKey]))
2675 # if field is enabled and editable, do permission check 2676 if ($Field->Enabled() &&
2677 ($CheckType ==
"View" || $Field->Editable()))
2679 # be sure schema privs allow View/Edit/Author for this resource 2680 $SchemaCheckFn =
"UserCan".$CheckType;
2681 if ($this->$SchemaCheckFn($User))
2683 # get appropriate privilege set for field 2684 $PermsFn = $CheckType.
"ingPrivileges";
2685 $FieldPrivs = $Field->$PermsFn();
2687 # user can View/Edit/Author if privileges are greater than field set 2688 $CheckResult = $FieldPrivs->MeetsRequirements($User, $this);
2692 $CheckResult = FALSE;
2697 $CheckResult = FALSE;
2700 # allow plugins to modify result of permission check 2701 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2702 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2704 "Resource" => $this,
2706 "Can".$CheckType => $CheckResult));
2707 $CheckResult = $SignalResult[
"Can".$CheckType];
2709 # save the result of this check in our cache 2710 $this->PermissionCache[$CacheKey] = $CheckResult;
2713 # return cached permission value 2714 return $this->PermissionCache[$CacheKey];
2720 private function UpdateCumulativeRating()
2722 # grab totals from DB 2723 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, " 2724 .
"SUM(Rating) AS Total FROM ResourceRatings " 2725 .
"WHERE ResourceId = ".$this->
Id);
2726 $Record = $this->DB->FetchRow();
2728 # calculate new cumulative rating 2731 # save new cumulative rating in DB 2732 $this->DB->Query(
"UPDATE Resources " 2734 .
"WHERE ResourceId = ".$this->Id);
2748 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2750 # We should ignore duplicate key errors when doing inserts: 2751 $this->DB->SetQueryErrorsToIgnore( array(
2752 "/INSERT INTO ".$TableName.
"/" =>
2753 "/Duplicate entry '-?[0-9]+-[0-9]+(-[0-9]+)?' for key/"));
2755 # start out assuming no association will be added 2756 $AssociationAdded = FALSE;
2758 # convert new value to array if necessary 2759 $Values = is_array($Value) ? $Value : array($Value);
2761 # for each new value 2762 foreach ($Values as $Value)
2764 # retrieve ID from value if necessary 2765 if (is_object($Value)) { $Value = $Value->Id(); }
2767 # Try to insert a new entry for this association. 2768 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET" 2769 .
" ResourceId = ".intval($this->
Id)
2770 .
", ".$FieldName.
" = ".intval($Value)
2771 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2773 # If the insert ran without a duplicate key error, 2774 # then we added an assocation: 2775 if ($this->DB->IgnoredError() === FALSE)
2777 $AssociationAdded = TRUE;
2781 # Clear ignored errors: 2782 $this->DB->SetQueryErrorsToIgnore( NULL );
2784 # report to caller whether association was added 2785 return $AssociationAdded;
2799 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2801 # start out assuming no association will be removed 2802 $AssociationRemoved = FALSE;
2804 # convert value to array if necessary 2805 $Values = is_array($Value) ? $Value : array($Value);
2808 foreach ($Values as $Value)
2810 # retrieve ID from value if necessary 2811 if (is_object($Value)) { $Value = $Value->Id(); }
2813 # remove any intersections with target ID from DB 2814 $this->DB->Query(
"DELETE FROM ".$TableName
2815 .
" WHERE ResourceId = ".intval($this->
Id)
2816 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2817 .
" AND ".$FieldName.
" = ".intval($Value));
2818 if ($this->DB->NumRowsAffected()) { $AssociationRemoved = TRUE; }
2821 # report to caller whether association was added 2822 return $AssociationRemoved;
2831 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2833 # retrieve list of entries for this field and resource 2834 $Entries = $this->
Get($Field);
2836 # divide them into chunks of not more than 100 2837 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2839 # remove assocations from this chunk 2840 $this->DB->Query(
"DELETE FROM ".$TableName
2841 .
" WHERE ResourceId = ".intval($this->
Id)
2842 .
" AND ".$TargetFieldName.
" IN " 2843 .
"(".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.
GetImageUrls($FieldNameOrObject, $ImageSize=SPTImage::SIZE_FULL)
Get URLs for images, returning CleanURLs when possible and direct paths to image files otherwise...
SetQualifier($FieldName, $NewValue)
Set qualifier using field name.
Abstraction for forum messages and resource comments.
SQL database abstraction object with smart query caching.
UserCanModifyField($User, $FieldOrFieldName)
Check whether user is allowed to modify (Edit for perm resources, Author for temp) specified metadata...
QueueSearchAndRecommenderUpdate()
Update search and recommender system DBs.
GetAsArray($IncludeDisabledFields=FALSE, $ReturnObjects=TRUE)
Retrieve all resource values as an array.
Id()
Retrieve numerical resource ID.
UserCanEditField($User, $FieldOrFieldName)
Check whether user is allowed to edit specified metadata field.
SetQualifierByField($Field, $NewValue)
Set qualifier using field object.
GetViewPageUrl()
Retrieve view page URL for this resource.
Rating($NewRating=NULL, $UserId=NULL)
Get/set rating by a specific user for resource.
Status()
Retrieve result of last operation if available.
NumberOfComments()
Get current number of comments for resource.
NumberOfRatings()
Get current number of ratings for resource.
GetQualifier($FieldName, $ReturnObject=TRUE)
Retrieve qualifier by field name.
Factory object for Folder class, used to retrieve and manage Folders and groups of Folders...
Copy($FileToCopy)
Create copy of File and return to caller.
Schema()
Get MetadataSchema for resource.
Metadata type representing non-hierarchical controlled vocabulary values.
UserCanEdit($User)
Determine if the given user can edit the resource.
GetForDisplay($FieldNameOrObject, $ReturnObject=TRUE, $IncludeVariants=FALSE)
Retrieve value using field name or field object, signaling EVENT_FIELD_DISPLAY_FILTER to allow other ...
Comments()
Get comments for resource.
CWIS-specific user factory class.
Get($Field, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field name or field object.
static GetSchemaForResource($ResourceId)
Get schema ID for specified resource(s).
Factory for manipulating File objects.
GetQualifierByFieldId($FieldId, $ReturnObject=TRUE)
Retrieve qualifier by field ID.
Encapsulates a full-size, preview, and thumbnail image.
UserCanAuthorField($User, $FieldOrFieldName)
Check whether user is allowed to author specified metadata field.
Clear($Field, $ValueToClear=NULL)
Clear field value.
UserCanModify($User)
Check if the user is allowed to modify (Edit for perm resources, Author for temp) a specified resourc...
UserCanAuthor($User)
Determine if the given user can edit the resource.
GetByFieldId($FieldId, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field ID.
IsTempResource($NewSetting=NULL)
Get/set whether resource is a temporary record.
SetByField($Field, $NewValue)
Method replaced by Resource::Set(), preserved for backward compatibility.
const STATUS_OK
Successful execution.
__construct($ResourceId)
Object constructor for loading an existing resource.
GetMapped($MappedName, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using standard (mapped) field name.
Represents a "resource" in CWIS.
GetQualifierByField($Field, $ReturnObject=TRUE)
Retrieve qualifier by Field object.
ClearByFieldId($FieldId, $ValueToClear=NULL)
Clear field value specified by field ID.
const CLASSSTAT_OK
Status code indicating operation completed successfully.
SetQualifierByFieldId($FieldId, $NewValue)
Set qualifier using field ID.
static ClearImageSymlinksForResource($ResourceId, $FieldId)
Remove symlinks used for to cache image mappings.
SchemaId()
Retrieve ID of schema for resource.
ScaledCumulativeRating()
Return cumulative rating scaled to 1/10th.
Set($Field, $NewValue, $Reset=FALSE)
Set value using field name or field object.
static Create($SchemaId)
Create a new resource.
UserCanViewField($User, $FieldOrFieldName)
Check whether user is allowed to view specified metadata field.
Metadata type representing hierarchical ("Tree") controlled vocabulary values.
SetByFieldId($FieldId, $NewValue)
Set field value using field ID.
Classifications()
Get 2D array of classifications associated with resource.
ClearByField($Field, $ValueToClear=NULL)
Clear field value.
Class representing a stored (usually uploaded) file.
Factory for Resource objects.
CWIS-specific user class.
CumulativeRating()
Get cumulative rating (range is usually 0-100)
FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
Determine if the value for a field is set.
Delete()
Remove resource (and accompanying associations) from database and delete any associated files...