5 # Part of the Collection Workflow Integration System (CWIS) 6 # Copyright 2011-2016 Edward Almasy and Internet Scout Research Group 7 # http://scout.wisc.edu/cwis/ 16 # ---- PUBLIC INTERFACE -------------------------------------------------- 27 # call parent contstructor to load info from DB 28 parent::__construct($ResourceId);
30 # load local attributes from database value cache 33 # load our local metadata schema 34 $this->
SchemaId = $this->ValueCache[
"SchemaId"];
35 if (!isset(self::$Schemas[$this->
SchemaId]))
37 self::$Schemas[$this->SchemaId] =
48 public static function Create($SchemaId)
50 # clean out any temp resource records more than three days old 52 $RFactory->CleanOutStaleTempItems(60 * 24 * 3);
54 # lock DB tables to prevent next ID from being grabbed 56 $DB->Query(
"LOCK TABLES Resources WRITE");
58 # find next temp resource ID 59 $Id = $RFactory->GetNextTempItemId();
61 # write out new resource record with temp resource ID 62 # Set DateLastModified = NOW() to avoid being pruned as a 63 # stale temp resource. 65 "INSERT INTO Resources 66 SET `ResourceId` = '".intval(
$Id).
"', 67 `SchemaId` = '".intval($SchemaId).
"', 68 `DateLastModified` = NOW() " );
71 $DB->Query(
"UNLOCK TABLES");
73 # create new Resource object 76 # set some additional fields for default resources 79 $Resource->Set(
"Date Of Record Creation", date(
"Y-m-d H:i:s"));
80 $Resource->Set(
"Date Last Modified", date(
"Y-m-d H:i:s"));
81 if ($GLOBALS[
"G_User"]->IsLoggedIn())
83 $Resource->Set(
"Added By Id", $GLOBALS[
"G_User"]->
Id());
84 $Resource->Set(
"Last Modified By Id", $GLOBALS[
"G_User"]->
Id());
88 # for each field that can have a default value 95 foreach ($Fields as $Field)
97 # if there is a default value available 98 $DefaultValue = $Field->DefaultValue();
99 if ($DefaultValue !== NULL)
101 # if the default value is an array 102 if (is_array($DefaultValue))
104 # if there are values in the array 105 if (!empty($DefaultValue))
107 # flip values for Set() if necessary 110 $DefaultValue = array_flip($DefaultValue);
114 $Resource->Set($Field, $DefaultValue);
120 $Resource->Set($Field, $DefaultValue);
125 $Resource->UpdateAutoupdateFields(
129 # signal resource creation 130 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_CREATE", array(
131 "Resource" => $Resource,
134 # return new Resource object to caller 146 # signal that resource deletion is about to occur 148 $AF->SignalEvent(
"EVENT_RESOURCE_DELETE", array(
152 # grab list of classifications 155 # delete resource/classification intersections 157 $DB->Query(
"DELETE FROM ResourceClassInts WHERE ResourceId = ".$this->
Id());
159 # for each classification type 160 foreach ($Classifications as $ClassType => $ClassesOfType)
162 # for each classification of that type 163 foreach ($ClassesOfType as $ClassId => $ClassName)
165 # recalculate resource count for classification 167 $Class->RecalcResourceCount();
171 # delete resource references 173 DELETE FROM ReferenceInts 174 WHERE SrcResourceId = '".addslashes($this->
Id()).
"' 175 OR DstResourceId = '".addslashes($this->
Id()).
"'");
177 # delete resource/name intersections 178 $DB->Query(
"DELETE FROM ResourceNameInts WHERE ResourceId = ".$this->
Id());
180 # delete resource/user intersections 181 $DB->Query(
"DELETE FROM ResourceUserInts WHERE ResourceId = ".$this->
Id());
183 # get the list of all images associated with this resource 184 $DB->Query(
"SELECT ImageId FROM ResourceImageInts" 185 .
" WHERE ResourceId = ".intval($this->
Id()));
186 $ImageIds =
$DB->FetchColumn(
"ImageId");
188 # disassociate this resource from all images 189 $DB->Query(
"DELETE FROM ResourceImageInts" 190 .
" WHERE ResourceId = ".intval($this->
Id()));
192 # delete any images that no longer belong to any resources 193 foreach ($ImageIds as $ImageId)
195 $DB->Query(
"SELECT ResourceId FROM ResourceImageInts" 196 .
" WHERE ImageId = ".intval($ImageId) );
197 if (
$DB->NumRowsSelected() == 0)
204 # delete any associated files 206 $Files = $Factory->GetFilesForResource($this->
Id());
207 foreach ($Files as $File)
212 # delete resource record from database 213 $DB->Query(
"DELETE FROM Resources WHERE ResourceId = ".$this->
Id());
215 # drop item from search engine and recommender system 216 if ($SysConfig->SearchDBEnabled())
219 $SearchEngine->DropItem($this->
Id());
221 if ($SysConfig->RecommenderDBEnabled())
224 $Recommender->DropItem($this->
Id());
227 # get the folders containing the resource 229 $Folders = $FolderFactory->GetFoldersContainingItem(
233 # drop the resource from each folder it belongs to 234 foreach ($Folders as $Folder)
236 # mixed item type folder 237 if ($Folder->ContainsItem($this->Id,
"Resource"))
239 $Folder->RemoveItem($this->
Id,
"Resource");
242 # single item type folder 245 $Folder->RemoveItem($this->
Id);
249 # delete any resource comments 250 $DB->Query(
"DELETE FROM Messages WHERE ParentId = ".$this->
Id);
261 # update all the timestamp fields as required 262 $TimestampFields = $this->
Schema()->GetFields(
264 foreach ($TimestampFields as $Field)
266 if ($Field->UpdateMethod() == $UpdateType)
268 $this->
Set($Field,
"now");
272 # if a user was provided, update the user fields as well 273 if (!is_null($User) && !$User->IsAnonymous())
275 $UserFields = $this->
Schema()->GetFields(
277 foreach ($UserFields as $Field)
279 if ($Field->UpdateMethod() == $UpdateType)
281 $this->
Set($Field, $User);
302 return $this->SchemaId;
311 return self::$Schemas[$this->SchemaId];
322 # if new temp resource setting supplied 323 if (!is_null($NewSetting))
325 # if caller requested to switch 327 if ((($this->
Id() < 0) && ($NewSetting == FALSE))
328 || (($this->
Id() >= 0) && ($NewSetting == TRUE)))
332 # lock DB tables to prevent next ID from being grabbed 333 $DB->Query(
"LOCK TABLES Resources WRITE");
335 # get next resource ID as appropriate 337 if ($NewSetting == TRUE)
339 $this->
Id = $Factory->GetNextTempItemId();
343 $this->
Id = $Factory->GetNextItemId();
347 $DB->Query(
"UPDATE Resources SET ResourceId = ".
348 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
351 $DB->Query(
"UNLOCK TABLES");
353 # change associations 354 unset($this->ClassificationCache);
355 $DB->Query(
"UPDATE ResourceClassInts SET ResourceId = ".
356 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
357 unset($this->ControlledNameCache);
358 unset($this->ControlledNameVariantCache);
359 $DB->Query(
"UPDATE ResourceNameInts SET ResourceId = ".
360 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
361 $DB->Query(
"UPDATE Files SET ResourceId = ".
362 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
363 $DB->Query(
"UPDATE ReferenceInts SET SrcResourceId = ".
364 $this->
Id.
" WHERE SrcResourceId = ".$OldResourceId);
365 $DB->Query(
"UPDATE ResourceImageInts SET ResourceId = ".
366 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
367 $DB->Query(
"UPDATE ResourceUserInts SET ResourceId = ".
368 $this->
Id.
" WHERE ResourceId = ".$OldResourceId);
370 # signal event as appropriate 371 if ($NewSetting === FALSE)
373 $GLOBALS[
"AF"]->SignalEvent(
"EVENT_RESOURCE_ADD", array(
380 # report to caller whether we are a temp resource 381 return ($this->
Id() < 0) ? TRUE : FALSE;
385 # --- Generic Attribute Retrieval Methods ------------------------------- 393 # put our Id into the ViewPage from our schema 396 $this->
Schema()->ViewPage());
398 # return clean url, if one is available 399 return $GLOBALS[
"AF"]->GetCleanUrlForPath($Url);
415 public function Get($Field, $ReturnObject = FALSE, $IncludeVariants = FALSE)
417 # load field object if not already supplied 418 $Field = is_object($Field) ? $Field : $this->
Schema()->GetField($Field);
420 if ($Field->SchemaId() != $this->
SchemaId())
422 throw new Exception(
"Attempt to get a value for a field" 423 .
" from a different schema." 424 .
" (Field: ".$Field->Name().
" [".$Field->Id()
425 .
"], Field Schema: ".$Field->SchemaId()
426 .
", Resource Schema: ".$this->
SchemaId()
430 # grab database field name 431 $DBFieldName = $Field->DBFieldName();
433 # format return value based on field type 434 switch ($Field->Type())
439 $ReturnValue = isset($this->ValueCache[$DBFieldName])
440 ? (string)$this->ValueCache[$DBFieldName] : NULL;
444 $ReturnValue = isset($this->ValueCache[$DBFieldName])
445 ? (int)$this->ValueCache[$DBFieldName] : NULL;
449 $ReturnValue = isset($this->ValueCache[$DBFieldName])
450 ? (bool)$this->ValueCache[$DBFieldName] : NULL;
454 $ReturnValue = array(
"X" => (
float)$this->ValueCache[$DBFieldName.
"X"],
455 "Y" => (
float)$this->ValueCache[$DBFieldName.
"Y"]);
459 $Date =
new Date($this->ValueCache[$DBFieldName.
"Begin"],
460 $this->ValueCache[$DBFieldName.
"End"],
461 $this->ValueCache[$DBFieldName.
"Precision"]);
464 $ReturnValue = $Date;
468 $ReturnValue = $Date->Formatted();
473 $ReturnValue = $this->ValueCache[$DBFieldName];
477 # start with empty array 478 $ReturnValue = array();
480 # if classification cache has not been loaded 481 if (!isset($this->ClassificationCache))
483 # load all classifications associated with this resource into cache 484 $this->ClassificationCache = array();
486 "SELECT Classifications.ClassificationId," 487 .
" Classifications.FieldId,ClassificationName" 488 .
" FROM ResourceClassInts, Classifications" 489 .
" WHERE ResourceClassInts.ResourceId = ".$this->
Id 490 .
" AND ResourceClassInts.ClassificationId" 491 .
" = Classifications.ClassificationId");
492 while ($Record = $this->DB->FetchRow())
494 $ClassId = $Record[
"ClassificationId"];
495 $this->ClassificationCache[$ClassId][
"Name"]
496 = $Record[
"ClassificationName"];
497 $this->ClassificationCache[$ClassId][
"FieldId"]
498 = $Record[
"FieldId"];
501 # for each entry in classification cache 502 foreach ($this->ClassificationCache as
503 $ClassificationId => $ClassificationInfo)
505 # if classification ID matches field we are looking for 506 if ($ClassificationInfo[
"FieldId"] == $Field->Id())
508 # add field to result 511 $ReturnValue[$ClassificationId] =
516 $ReturnValue[$ClassificationId] = $ClassificationInfo[
"Name"];
524 # start with empty array 525 $ReturnValue = array();
527 # if controlled name cache has not been loaded 528 if (!isset($this->ControlledNameCache))
530 # load all controlled names associated with this resource into cache 531 $this->ControlledNameCache = array();
533 "SELECT ControlledNames.ControlledNameId," 534 .
" ControlledNames.FieldId,ControlledName" 535 .
" FROM ResourceNameInts, ControlledNames" 536 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 537 .
" AND ResourceNameInts.ControlledNameId" 538 .
" = ControlledNames.ControlledNameId" 539 .
" ORDER BY ControlledNames.ControlledName ASC");
540 while ($Record = $this->DB->FetchRow())
542 $CNameId = $Record[
"ControlledNameId"];
543 $this->ControlledNameCache[$CNameId][
"Name"]
544 = $Record[
"ControlledName"];
545 $this->ControlledNameCache[$CNameId][
"FieldId"]
546 = $Record[
"FieldId"];
550 # if variant names requested and variant name cache has not been loaded 551 if ($IncludeVariants && !isset($this->ControlledNameVariantCache))
553 # load all controlled names associated with this resource into cache 554 $this->ControlledNameVariantCache = array();
555 $this->DB->Query(
"SELECT ControlledNames.ControlledNameId," 556 .
" ControlledNames.FieldId," 557 .
" ControlledName, VariantName" 558 .
" FROM ResourceNameInts, ControlledNames, VariantNames" 559 .
" WHERE ResourceNameInts.ResourceId = ".$this->
Id 560 .
" AND ResourceNameInts.ControlledNameId" 561 .
" = ControlledNames.ControlledNameId" 562 .
" AND VariantNames.ControlledNameId" 563 .
" = ControlledNames.ControlledNameId");
564 while ($Record = $this->DB->FetchRow())
566 $this->ControlledNameVariantCache[$Record[
"ControlledNameId"]][]
567 = $Record[
"VariantName"];
571 # for each entry in controlled name cache 572 foreach ($this->ControlledNameCache as
573 $CNameId => $ControlledNameInfo)
575 # if controlled name type matches field we are looking for 576 if ($ControlledNameInfo[
"FieldId"] == $Field->Id())
578 # if objects requested 581 $ReturnValue[$CNameId] =
586 # if variant names requested 587 if ($IncludeVariants)
589 # add field to result 590 $ReturnValue[] = $ControlledNameInfo[
"Name"];
592 # add any variant names to result 593 if (isset($this->ControlledNameVariantCache[$CNameId]))
595 $ReturnValue = array_merge(
597 $this->ControlledNameVariantCache[$CNameId]);
602 # add field with index to result 603 $ReturnValue[$CNameId] =
604 $ControlledNameInfo[
"Name"];
612 # start out assuming no associated users 613 $ReturnValue = array();
615 # query the database to get the associated userids 617 "SELECT UserId FROM ResourceUserInts WHERE ".
618 "ResourceId=".intval($this->
Id).
619 " AND FieldId=".intval($Field->Id())
620 .
" AND UserId IN (SELECT UserId FROM APUsers)" 622 $UserIds = $this->DB->FetchColumn(
"UserId");
624 # convert each userid to either a name or a CWUser object 625 foreach ($UserIds as $UserId)
627 $User =
new CWUser(intval($UserId));
630 $ReturnValue[$UserId] = $User;
634 $ReturnValue[$UserId] = $User->Get(
"UserName");
640 # start out assuming no images will be found 641 $ReturnValue = array();
643 # find all images associated with this resource 644 $this->DB->Query(
"SELECT ImageId FROM ResourceImageInts" 645 .
" WHERE ResourceId = ".intval($this->
Id())
646 .
" AND FieldId = ".intval($Field->Id()));
648 # if images were found 649 if ($this->DB->NumRowsSelected())
651 # if we are to return an object 652 $ImageIds = $this->DB->FetchColumn(
"ImageId");
655 # load array of Image objects for return value 656 foreach ($ImageIds as $ImageId)
658 $ReturnValue[$ImageId] =
new SPTImage($ImageId);
663 # load array of Image ids for return value 664 $ReturnValue = $ImageIds;
670 # retrieve files using factory 673 $this->
Id, $ReturnObject);
677 # query for resource references 679 SELECT * FROM ReferenceInts 680 WHERE FieldId = '".addslashes($Field->Id()).
"' 681 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
683 $ReturnValue = array();
685 # return each reference as a Resource object 688 $FoundErrors = FALSE;
690 while (FALSE !== ($Record = $this->DB->FetchRow()))
692 $ReferenceId = $Record[
"DstResourceId"];
693 $Reference =
new Resource($ReferenceId);
694 $ReturnValue[$ReferenceId] = $Reference;
698 # return each reference as a resource ID 701 while (FALSE !== ($Record = $this->DB->FetchRow()))
703 $ReferenceId = $Record[
"DstResourceId"];
704 $ReturnValue[$ReferenceId] = $ReferenceId;
711 exit(
"<br>SPT - ERROR: attempt to retrieve " 712 .
"unknown resource field type (".$Field->Type().
")<br>\n");
716 # return formatted value to caller 740 $FieldNameOrObject, $ReturnObject = TRUE, $IncludeVariants = FALSE)
742 # normalize metadata field for use by any hooked code 743 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
744 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
747 $Value = $this->
Get($Field, $ReturnObject, $IncludeVariants);
749 # signal event to allowed hooked code to modify value 750 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
751 "EVENT_FIELD_DISPLAY_FILTER", array(
756 # return possibly modified value to caller 757 return $SignalResult[
"Value"];
776 $ReturnObject = FALSE, $IncludeVariants = FALSE)
778 return $this->
Get($FieldNameOrObject, $ReturnObject, $IncludeVariants);
796 $FieldId, $ReturnObject = FALSE, $IncludeVariants = FALSE)
798 return $this->
Get($FieldId, $ReturnObject, $IncludeVariants);
813 public function GetAsArray($IncludeDisabledFields = FALSE, $ReturnObjects = TRUE)
815 # retrieve field info 816 $Fields = $this->
Schema()->GetFields();
819 foreach ($Fields as $Field)
821 # if field is enabled or caller requested disabled fields 822 if ($Field->Enabled() || $IncludeDisabledFields)
824 # retrieve info and add it to the array 825 $FieldStrings[$Field->Name()] = $this->
Get($Field, $ReturnObjects);
827 # if field uses qualifiers 828 if ($Field->UsesQualifiers())
830 # get qualifier attributes and add to the array 831 $FieldStrings[$Field->Name().
" Qualifier"] =
837 # add in internal values 838 $FieldStrings[
"ResourceId"] = $this->
Id();
841 # return array to caller 842 return $FieldStrings;
860 $MappedName, $ReturnObject = FALSE, $IncludeVariants = FALSE)
862 $FieldId = $this->
Schema()->StdNameToFieldMapping($MappedName);
864 ? $this->
Get($FieldId, $ReturnObject, $IncludeVariants)
878 $Field = $this->
Schema()->GetFieldByName($FieldName);
892 $Field = $this->
Schema()->GetField($FieldId);
906 # return NULL if field is invalid 909 # assume no qualifiers if not otherwise determined 912 # if field uses qualifiers 913 if ($Field->UsesQualifiers())
915 # retrieve qualifiers based on field type 916 switch ($Field->Type())
921 # retrieve list of items 924 # if field uses item-level qualifiers 925 if ($Field->HasItemLevelQualifiers())
927 # determine general item name in DB 929 ?
"Classification" :
"ControlledName";
932 foreach (
$Items as $ItemId => $ItemName)
934 # look up qualifier for item 935 $QualId = $this->DB->Query(
936 "SELECT * FROM ".$TableName.
"s" 937 .
" WHERE ".$TableName.
"Id = ".$ItemId,
943 # if object was requested by caller 946 # load qualifier and add to return value array 947 $ReturnValue[$ItemId] =
new Qualifier($QualId);
951 # add qualifier ID to return value array 952 $ReturnValue[$ItemId] = $QualId;
957 # add NULL to return value array for this item 958 $ReturnValue[$ItemId] = NULL;
965 foreach (
$Items as $ItemId => $ItemName)
967 # if object was requested by caller 970 # load default qualifier and add to return value array 972 $Field->DefaultQualifier());
976 # add default qualifier ID to return value array 977 $ReturnValue[$ItemId] = $Field->DefaultQualifier();
984 # if field uses item-level qualifiers 985 if ($Field->HasItemLevelQualifiers())
987 # if qualifier available 988 if ($this->ValueCache[$Field->DBFieldName().
"Qualifier"] > 0)
990 # if object was requested by caller 991 $QFieldName = $Field->DBFieldName().
"Qualifier";
994 # return qualifier for field 996 $this->ValueCache[$QFieldName]);
1000 # return qualifier ID for field 1001 $ReturnValue = $this->ValueCache[$QFieldName];
1007 # if default qualifier available 1008 if ($Field->DefaultQualifier() > 0)
1010 # if object was requested by caller 1013 # return default qualifier 1014 $ReturnValue =
new Qualifier($Field->DefaultQualifier());
1018 # return default qualifier ID 1019 $ReturnValue = $Field->DefaultQualifier();
1027 # return qualifier object or ID (or array of same) to caller 1028 return $ReturnValue;
1038 public function FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
1040 # load field object if needed 1041 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1042 : $this->
Schema()->GetFieldByName($FieldNameOrObject);
1044 # return no value found if we don't have a valid field 1048 $Value = $this->
Get($Field);
1050 # checks depend on the field type 1051 switch ($Field->Type())
1057 return isset($Value)
1059 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
1062 return isset($Value)
1066 return isset($Value[
"X"])
1067 && isset($Value[
"Y"])
1068 && strlen(trim($Value[
"X"]))
1069 && strlen(trim($Value[
"Y"]));
1072 return isset($Value)
1073 && strlen(trim($Value))
1074 && $Value !=
"0000-00-00";
1077 return isset($Value)
1078 && strlen(trim($Value))
1079 && $Value !=
"0000-00-00 00:00:00";
1087 return count($Value) > 0;
1091 return isset($Value)
1093 && $Factory->UserNameExists($Value);
1112 # get our target field and extract its values 1113 $Field = is_object($FieldNameOrObject) ? $FieldNameOrObject
1114 : $this->
Schema()->GetField($FieldNameOrObject);
1115 $Images = $this->
Get($Field, TRUE);
1117 # iterate over our images getting URLs for each 1119 foreach ($Images as $Image)
1121 $Result[$Image->Id()] = $Image->GetImageUrlForResource(
1122 $this->
Id(), $Field->Id(), $Index, $ImageSize);
1129 # --- Generic Attribute Setting Methods --------------------------------- 1143 public function Set($Field, $NewValue, $Reset=FALSE)
1145 # load field object if not already supplied 1146 $Field = is_object($Field) ? $Field
1147 : (is_numeric($Field) ? $this->
Schema()->GetField($Field)
1148 : $this->
Schema()->GetFieldByName($Field));
1150 # return if we don't have a valid field 1153 if ($Field->SchemaId() != $this->
SchemaId())
1155 throw new Exception(
"Attempt to set a value for a field " 1156 .
"from a different schema.");
1159 # grab commonly-used values for local use 1163 # grab database field name 1164 $DBFieldName = $Field->DBFieldName();
1166 # Flag to deterimine if we've actually changed anything. 1167 $UpdateModTime = FALSE;
1169 # store value in DB based on field type 1170 switch ($Field->Type())
1175 if ($this->ValueCache[$DBFieldName] != $NewValue)
1177 # save value directly to DB 1178 $DB->Query(
"UPDATE Resources SET `" 1179 .$DBFieldName.
"` = '".addslashes($NewValue).
"' " 1180 .
"WHERE ResourceId = ".$ResourceId);
1182 # save value locally 1183 $this->ValueCache[$DBFieldName] = $NewValue;
1184 $UpdateModTime=TRUE;
1189 if ( $this->ValueCache[$DBFieldName] != $NewValue )
1191 # save value directly to DB 1192 if (is_null($NewValue))
1194 $DB->Query(
"UPDATE Resources SET `" 1195 .$DBFieldName.
"` = NULL" 1196 .
" WHERE ResourceId = ".$ResourceId);
1200 $DB->Query(
"UPDATE Resources SET `" 1201 .$DBFieldName.
"` = ".intval($NewValue)
1202 .
" WHERE ResourceId = ".$ResourceId);
1205 # save value locally 1206 $this->ValueCache[$DBFieldName] = $NewValue;
1207 $UpdateModTime = TRUE;
1213 if ($this->ValueCache[$DBFieldName.
"X"] != $NewValue[
"X"] ||
1214 $this->ValueCache[$DBFieldName.
"Y"] != $NewValue[
"Y"] )
1216 if (is_null($NewValue))
1218 $DB->Query(
"UPDATE Resources SET " 1219 .
"`".$DBFieldName.
"X` = NULL, " 1220 .
"`".$DBFieldName.
"Y` = NULL " 1221 .
"WHERE ResourceId = ".$ResourceId);
1222 $this->ValueCache[$DBFieldName.
"X"] = NULL;
1223 $this->ValueCache[$DBFieldName.
"Y"] = NULL;
1227 $DB->Query(
"UPDATE Resources SET " 1228 .
"`".$DBFieldName.
"X` = " .(strlen($NewValue[
"X"])
1229 ?
"'".$NewValue[
"X"].
"'" :
"NULL").
", " 1230 .
"`".$DBFieldName.
"Y` = ".(strlen($NewValue[
"Y"])
1231 ?
"'".$NewValue[
"Y"].
"'" :
"NULL")
1232 .
" WHERE ResourceId = ".$ResourceId);
1234 $Digits = $Field->PointDecimalDigits();
1236 $this->ValueCache[$DBFieldName.
"X"] =
1237 strlen($NewValue[
"X"]) ?
1238 round($NewValue[
"X"], $Digits) : NULL;
1239 $this->ValueCache[$DBFieldName.
"Y"] =
1240 strlen($NewValue[
"Y"]) ?
1241 round($NewValue[
"Y"], $Digits) : NULL;
1243 $UpdateModTime = TRUE;
1248 if ($this->ValueCache[$DBFieldName] != $NewValue)
1250 # save value directly to DB 1251 if (is_null($NewValue))
1253 $DB->Query(
"UPDATE Resources SET `" 1254 .$DBFieldName.
"` = NULL" 1255 .
" WHERE ResourceId = ".$ResourceId);
1259 $NewValue = $NewValue ?
"1" :
"0";
1260 $DB->Query(
"UPDATE Resources SET `" 1261 .$DBFieldName.
"` = ".$NewValue
1262 .
" WHERE ResourceId = ".$ResourceId);
1265 $this->ValueCache[$DBFieldName] = $NewValue;
1267 $UpdateModTime = TRUE;
1272 $OldValue = $this->
Get($Field);
1273 # value comes back as array (UserId => UserName), just get the Ids 1274 $OldValue = array_keys($OldValue);
1276 # input to Set() for these fields is one of 1277 # 1. an int specifying a UserId 1278 if (is_numeric($NewValue))
1280 $NewValue = array($NewValue);
1282 # 2. a CWUser object 1283 elseif ($NewValue instanceof
CWUser)
1285 $NewValue = array($NewValue->Id());
1287 # 3. an array keyed by UserId (don't care about the values) 1288 elseif (is_array($NewValue))
1290 $NewValue = array_keys($NewValue);
1294 throw new Exception(
"Unknown format for NewValue in a User field");
1297 # if this is a unique field, only accept the first of the options given 1298 if ($Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1300 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1303 # sort new and old values so we can directly compare 1307 # if the value has changed 1308 if ($OldValue != $NewValue)
1310 if ($Reset || $Field->AllowMultiple() == FALSE )
1312 $ToRemove = array_diff($OldValue, $NewValue);
1313 $this->RemoveAssociation(
1314 "ResourceUserInts",
"UserId", $ToRemove, $Field);
1317 # associate with resource if not already associated 1318 $this->AddAssociation(
"ResourceUserInts",
1322 $UpdateModTime=TRUE;
1327 # if we were given a date object 1328 if (is_object($NewValue))
1330 # use supplied date object 1335 # create date object 1336 $Date =
new Date($NewValue);
1339 $OldDate =
new Date(
1340 $this->ValueCache[$DBFieldName.
"Begin"],
1341 $this->ValueCache[$DBFieldName.
"End"]);
1343 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1344 $OldDate->EndDate() != $Date->EndDate() ||
1345 $OldDate->Precision() != $Date->Precision() )
1347 # extract values from date object and store in DB 1348 $BeginDate =
"'".$Date->BeginDate().
"'";
1349 if (strlen($BeginDate) < 3) { $BeginDate =
"NULL"; }
1350 $EndDate =
"'".$Date->EndDate().
"'";
1351 if (strlen($EndDate) < 3) { $EndDate =
"NULL"; }
1353 $DB->Query(
"UPDATE Resources SET " 1354 .$DBFieldName.
"Begin = ".$BeginDate.
", " 1355 .$DBFieldName.
"End = ".$EndDate.
", " 1356 .$DBFieldName.
"Precision = '".$Date->Precision().
"' " 1357 .
"WHERE ResourceId = ".$ResourceId);
1359 # save values locally 1360 $this->ValueCache[$DBFieldName.
"Begin"] = $Date->BeginDate();
1361 $this->ValueCache[$DBFieldName.
"End"] = $Date->EndDate();
1362 $this->ValueCache[$DBFieldName.
"Precision"] = $Date->Precision();
1363 $UpdateModTime=TRUE;
1368 if (is_null($NewValue) || !strlen(trim($NewValue)))
1370 $DateValue = $NewValue;
1372 if (!is_null($this->ValueCache[$DBFieldName]))
1374 # save value directly to DB 1375 $DB->Query(
"UPDATE Resources SET " 1376 .
"`".$DBFieldName.
"` = NULL " 1377 .
"WHERE ResourceId = ".$ResourceId);
1378 $UpdateModTime = TRUE;
1383 # assume value is date and use directly 1384 $TimestampValue = strtotime($NewValue);
1386 # use the new value if the date is valid 1387 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1389 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1391 if ($this->ValueCache[$DBFieldName] != $DateValue)
1393 # save value directly to DB 1394 $DB->Query(
"UPDATE Resources SET " 1395 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' " 1396 .
"WHERE ResourceId = ".$ResourceId);
1397 $UpdateModTime=TRUE;
1401 # continue using the old value if invalid 1404 $DateValue = $this->
Get($Field);
1408 # save value locally 1409 $this->ValueCache[$DBFieldName] = $DateValue;
1413 $OldValue = $this->
Get($Field);
1415 # if incoming value is array 1416 if (is_array($NewValue))
1418 if ($OldValue != $NewValue)
1422 # remove values that were in the old value 1423 # but not the new one 1424 $ToRemove = array_diff(array_keys($OldValue),
1425 array_keys($NewValue));
1426 foreach ($ToRemove as $ClassificationId)
1428 $this->RemoveAssociation(
"ResourceClassInts",
1432 $Class->RecalcResourceCount();
1436 # for each element of array 1437 foreach ($NewValue as
1438 $ClassificationId => $ClassificationName)
1441 if ($Class->FieldId() == $Field->Id())
1443 # associate with resource if not already associated 1444 if ($this->AddAssociation(
"ResourceClassInts",
1445 "ClassificationId", $ClassificationId))
1447 $Class->UpdateLastAssigned();
1448 $Class->RecalcResourceCount();
1453 throw new Exception(
1454 "Attempting to store classification from " 1455 .
"Field ".$Class->FieldId().
" into Field " 1461 $UpdateModTime=TRUE;
1466 # associate with resource if not already associated 1467 if (is_object($NewValue))
1470 $NewValue = $Class->Id();
1477 if (!array_key_exists($Class->Id(), $OldValue))
1480 $this->AddAssociation(
"ResourceClassInts",
1483 $Class->UpdateLastAssigned();
1484 $Class->RecalcResourceCount();
1485 $UpdateModTime=TRUE;
1489 # clear our classification cache 1492 unset($this->ClassificationCache);
1498 $OldValue = $this->
Get($Field);
1500 # input to Set() for these fields is one of 1501 # 1. an int specifying a ControlledNameId 1502 # 2. a ControlledName object 1503 # 3. an array with keys giving Ids and values giving ControlledNames 1505 # normalize 1 and 2 into 3 for simplicity of processing 1506 if (is_object($NewValue) || !is_array($NewValue) )
1508 if (!is_object($NewValue))
1513 $TmpValue = array();
1514 $TmpValue[$NewValue->Id()] = $NewValue->Name();
1516 $NewValue = $TmpValue;
1519 # if this is a unique field, only accept the first of the options given 1520 # NB: all ControlledNames implicitly AllowMultiple 1522 $Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1524 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1527 # if the value has changed 1528 if ($OldValue != $NewValue)
1531 && $Field->AllowMultiple() == FALSE ) )
1533 $ToRemove = array_diff(array_keys($OldValue),
1534 array_keys($NewValue));
1535 foreach ($ToRemove as $CNId)
1537 $this->RemoveAssociation(
"ResourceNameInts",
1543 # for each element of array 1544 foreach ($NewValue as $ControlledNameId => $ControlledName)
1546 # associate with resource if not already associated 1547 if ($this->AddAssociation(
"ResourceNameInts",
1554 $this->RemoveAssociation(
"ResourceNameInts",
1555 "ControlledNameId", $ControlledNameId);
1556 throw new InvalidArgumentException(
1557 "Attempt to set controlled name with" 1558 .
" invalid ID (".$ControlledNameId.
").");
1560 $CN->UpdateLastAssigned();
1563 $UpdateModTime = TRUE;
1568 # clear our controlled name cache 1569 unset($this->ControlledNameCache);
1570 unset($this->ControlledNameVariantCache);
1572 # clear visible count cache for any affected resources 1573 $ValueIds = array_keys($OldValue) + array_keys($NewValue);
1575 "DELETE FROM VisibleResourceCounts WHERE " 1576 .
"SchemaId=".intval($this->
SchemaId).
" AND " 1577 .
"ValueId IN (".implode(
",", $ValueIds).
")");
1583 # associate value(s) with resource 1584 $this->AddAssociation(
1585 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1586 # clear cached image mappings 1591 # convert incoming value to array if necessary 1592 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1594 # for each incoming file 1596 foreach ($NewValue as $File)
1599 $NewFile = $Factory->
Copy($File);
1601 # associate copy with this resource and field 1602 $NewFile->ResourceId($this->
Id);
1603 $NewFile->FieldId($Field->Id());
1605 # Since we make a fresh copy of the File whenever Set is called, 1606 # we'll always update the modification time for this field. 1607 $UpdateModTime = TRUE;
1611 # convert incoming value to array to simplify the workflow 1612 if (is_scalar($NewValue) || $NewValue instanceof
Resource)
1614 $NewValue = array($NewValue);
1617 # delete existing resource references 1620 # add each reference 1621 foreach ($NewValue as $ReferenceOrId)
1623 # initially issume it's a reference ID and not an object... 1624 $ReferenceId = $ReferenceOrId;
1626 # ... but get the reference ID if it's an object 1627 if ($ReferenceOrId instanceof
Resource)
1629 $ReferenceId = $ReferenceOrId->Id();
1632 # skip blank reference IDs 1633 if (strlen(trim($ReferenceId)) < 1)
1638 # skip reference IDs that don't look right 1639 if (!is_numeric($ReferenceId))
1644 # skip references to the current resource 1645 if ($ReferenceId == $this->
Id())
1650 # add the reference to the references table 1652 INSERT INTO ReferenceInts ( 1657 ".addslashes($Field->Id()).
", 1658 ".addslashes($this->
Id()).
", 1659 ".addslashes($ReferenceId).
")");
1665 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1671 # update modification timestamps 1673 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1674 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 1675 .
"WHERE ResourceId=".$this->
Id.
" AND " 1676 .
"FieldId=".$Field->Id() );
1677 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 1678 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 1679 .$this->
Id.
",".$Field->Id().
"," 1680 .$UserId.
",NOW())");
1682 # on resource modification, clear the UserPermsCache entry 1683 # so that stale permissions checks are not cached 1684 $DB->Query(
"DELETE FROM UserPermsCache WHERE ResourceId=".$this->
Id);
1697 $this->
Set($Field, $NewValue);
1709 $this->
Set($FieldId, $NewValue);
1719 $Field = $this->
Schema()->GetFieldByName($FieldName);
1730 $Field = $this->
Schema()->GetField($FieldId);
1741 # if field uses qualifiers and uses item-level qualifiers 1742 if ($Field->UsesQualifiers() && $Field->HasItemLevelQualifiers())
1744 # if qualifier object passed in 1745 if (is_object($NewValue))
1747 # grab qualifier ID from object 1748 $QualifierId = $NewValue->Id();
1752 # assume value passed in is qualifier ID 1753 $QualifierId = $NewValue;
1756 # update qualifier value in database 1757 $DBFieldName = $Field->DBFieldName();
1758 $this->DB->Query(
"UPDATE Resources SET " 1759 .$DBFieldName.
"Qualifier = '".$QualifierId.
"' " 1760 .
"WHERE ResourceId = ".$this->Id);
1762 # update local qualifier value 1763 $this->ValueCache[$DBFieldName.
"Qualifier"] = $QualifierId;
1775 $Field = $this->
Schema()->GetField($FieldId);
1776 $this->
Clear($Field, $ValueToClear);
1785 public function Clear($Field, $ValueToClear = NULL)
1787 # convert field name to object if necessary 1788 if (!is_object($Field))
1790 $Field = $this->
Schema()->GetFieldByName($Field);
1793 # grab commonly-used values for local use 1797 # grab database field name 1798 $DBFieldName = $Field->DBFieldName();
1800 $UpdateModTime=FALSE;
1802 # store value in DB based on field type 1803 switch ($Field->Type())
1811 if (strlen($this->ValueCache[$DBFieldName])>0)
1814 $DB->Query(
"UPDATE Resources SET `" 1815 .$DBFieldName.
"` = NULL " 1816 .
"WHERE ResourceId = ".$ResourceId);
1818 # clear value locally 1819 $this->ValueCache[$DBFieldName] = NULL;
1820 $UpdateModTime=TRUE;
1825 if (!is_null($this->ValueCache[$DBFieldName.
"X"]) ||
1826 !is_null($this->ValueCache[$DBFieldName.
"Y"]) )
1829 $DB->Query(
"UPDATE Resources SET " 1830 .
"`".$DBFieldName.
"X` = NULL ," 1831 .
"`".$DBFieldName.
"Y` = NULL " 1832 .
"WHERE ResourceId = ".$ResourceId);
1834 # Clear local values 1835 $this->ValueCache[$DBFieldName.
"X"] = NULL;
1836 $this->ValueCache[$DBFieldName.
"Y"] = NULL;
1837 $UpdateModTime=TRUE;
1842 if (!is_null($this->ValueCache[$DBFieldName.
"Begin"]) ||
1843 !is_null($this->ValueCache[$DBFieldName.
"End"]) ||
1844 !is_null($this->ValueCache[$DBFieldName.
"Precision"]))
1846 # clear date object values in DB 1847 $DB->Query(
"UPDATE Resources SET " 1848 .$DBFieldName.
"Begin = '', " 1849 .$DBFieldName.
"End = '', " 1850 .$DBFieldName.
"Precision = '' " 1851 .
"WHERE ResourceId = ".$ResourceId);
1853 # clear value locally 1854 $this->ValueCache[$DBFieldName.
"Begin"] = NULL;
1855 $this->ValueCache[$DBFieldName.
"End"] = NULL;
1856 $this->ValueCache[$DBFieldName.
"Precision"] = NULL;
1857 $UpdateModTime=TRUE;
1862 $OldValue = $this->
Get($Field);
1864 # if value to clear supplied 1865 if ($ValueToClear !== NULL)
1867 # if supplied value is array 1868 if (is_array($ValueToClear))
1870 # for each element of array 1871 foreach ($ValueToClear as $ClassificationId => $Dummy)
1873 if (array_key_exists($ClassificationId, $OldValue))
1875 # remove association with resource (if any) 1876 $this->RemoveAssociation(
"ResourceClassInts",
1880 $Class->RecalcResourceCount();
1881 $UpdateModTime=TRUE;
1887 if (array_key_exists($ValueToClear, $OldValue))
1889 # remove association with resource (if any) 1890 $this->RemoveAssociation(
"ResourceClassInts",
1894 $Class->RecalcResourceCount();
1895 $UpdateModTime=TRUE;
1901 if (count($OldValue)>0)
1903 # remove all associations for resource and field 1904 $this->RemoveAllAssociations(
1905 "ResourceClassInts",
"ClassificationId", $Field);
1907 # recompute resource count 1908 $Values = $this->
Get($Field);
1909 foreach ($Values as $ClassificationId => $Dummy)
1912 $Class->RecalcResourceCount();
1914 $UpdateModTime=TRUE;
1918 # clear our classification cache 1921 unset($this->ClassificationCache);
1927 $OldValue = $this->
Get($Field);
1928 # if value to clear supplied 1929 if ($ValueToClear !== NULL)
1931 # if incoming value is array 1932 if (is_array($ValueToClear))
1934 # for each element of array 1935 foreach ($ValueToClear as $ControlledNameId =>
1938 if (array_key_exists($ControlledNameId, $OldValue))
1940 # remove association with resource (if any) 1941 $this->RemoveAssociation(
"ResourceNameInts",
1944 $UpdateModTime=TRUE;
1950 if (array_key_exists($ValueToClear, $OldValue))
1952 # remove association with resource (if any) 1953 $this->RemoveAssociation(
"ResourceNameInts",
1956 $UpdateModTime=TRUE;
1962 if (count($OldValue)>0)
1964 # remove all associations for resource and field 1965 $this->RemoveAllAssociations(
1966 "ResourceNameInts",
"ControlledNameId", $Field);
1967 $UpdateModTime=TRUE;
1973 # clear our controlled name cache 1974 unset($this->ControlledNameCache);
1975 unset($this->ControlledNameVariantCache);
1980 $OldValue = $this->
Get($Field);
1982 # if value to clear supplied 1983 if ($ValueToClear !== NULL)
1985 # if incoming value is array 1986 if (is_array($ValueToClear))
1988 # for each element of array 1989 foreach ($ValueToClear as $UserId => $User)
1991 if (array_key_exists($UserId, $OldValue))
1993 # remove association with resource (if any) 1994 $this->RemoveAssociation(
"ResourceUserInts",
1998 $UpdateModTime=TRUE;
2004 if (array_key_exists($ValueToClear, $OldValue))
2006 # remove association with resource (if any) 2007 $this->RemoveAssociation(
"ResourceUserInts",
2011 $UpdateModTime=TRUE;
2017 if (count($OldValue)>0)
2019 # remove all associations for resource and field 2020 $this->RemoveAllAssociations(
2021 "ResourceUserInts",
"UserId", $Field);
2022 $UpdateModTime=TRUE;
2029 # if value to clear supplied 2030 if ($ValueToClear !== NULL)
2032 # convert value to array if necessary 2033 $Files = $ValueToClear;
2034 if (!is_array($Files)) { $Files = array($Files); }
2036 # convert values to objects if necessary 2037 foreach ($Files as $Index => $File)
2039 if (!is_object($File))
2041 $Files[$Index] =
new File($File);
2047 # use all files associated with resource 2048 $Files = $this->
Get($Field, TRUE);
2052 foreach ($Files as $File) { $File->Delete(); }
2056 # if value to clear supplied 2057 if ($ValueToClear !== NULL)
2059 # convert value to array if necessary 2060 $Images = $ValueToClear;
2061 if (!is_array($Images)) { $Images = array($Images); }
2063 # convert values to objects if necessary 2064 foreach ($Images as $Index => $Image)
2066 if (!is_object($Image))
2068 $Images[$Index] =
new SPTImage($Image);
2074 # use all images associated with resource 2075 $Images = $this->
Get($Field, TRUE);
2078 # delete images if we are the last resource referencing 2079 # a particular image. 2080 foreach ($Images as $Image)
2082 $Cnt = $this->DB->Query(
2083 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
2084 "ImageId=".$Image->Id(),
"Cnt");
2091 # clear cached image mappings 2094 # remove connections to images 2095 $UpdateModTime = $this->RemoveAssociation(
2096 "ResourceImageInts",
"ImageId", $Images, $Field);
2100 # remove references from the references table 2102 DELETE FROM ReferenceInts 2103 WHERE FieldId = '".addslashes($Field->Id()).
"' 2104 AND SrcResourceId = '".addslashes($this->
Id()).
"'");
2109 exit(
"<br>SPT - ERROR: attempt to clear " 2110 .
"unknown resource field type<br>\n");
2116 # update modification timestamps 2118 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
2119 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 2120 .
"WHERE ResourceId=".$this->
Id.
" AND " 2121 .
"FieldId=".$Field->Id() );
2122 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 2123 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 2124 .$this->
Id.
",".$Field->Id().
"," 2125 .$UserId.
",NOW())");
2139 $this->
Clear($Field, $ValueToClear);
2142 # --- Field-Specific or Type-Specific Attribute Retrieval Methods ------- 2153 # start with empty array 2156 # for each controlled name 2157 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, " 2158 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, " 2159 .
"Classifications, MetadataFields " 2160 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" " 2161 .
"AND ResourceClassInts.ClassificationId = " 2162 .
"Classifications.ClassificationId " 2163 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
2164 while ($Record =
$DB->FetchRow())
2167 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
2168 $Record[
"ClassificationName"];
2171 # return array to caller 2176 # --- Ratings Methods --------------------------------------------------- 2184 return $this->CumulativeRating;
2209 # if number of ratings not already set 2212 # obtain number of ratings 2214 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings " 2215 .
"FROM ResourceRatings " 2216 .
"WHERE ResourceId = ".$this->
Id,
2220 # recalculate cumulative rating if it looks erroneous 2223 $this->UpdateCumulativeRating();
2227 # return number of ratings to caller 2228 return $this->NumberOfRatings;
2238 public function Rating($NewRating = NULL, $UserId = NULL)
2242 # if user ID not supplied 2243 if ($UserId == NULL)
2245 # if user is logged in 2247 if ($User->IsLoggedIn())
2249 # use ID of current user 2250 $UserId = $User->Get(
"UserId");
2254 # return NULL to caller 2259 # sanitize $NewRating 2260 if (!is_null($NewRating))
2262 $NewRating = intval($NewRating);
2265 # if there is a rating for resource and user 2266 $DB->Query(
"SELECT Rating FROM ResourceRatings " 2267 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2268 if ($Record =
$DB->FetchRow())
2270 # if new rating was supplied 2271 if ($NewRating != NULL)
2273 # update existing rating 2274 $DB->Query(
"UPDATE ResourceRatings " 2275 .
"SET Rating = ${NewRating}, DateRated = NOW() " 2276 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2278 # update cumulative rating value 2279 $this->UpdateCumulativeRating();
2281 # return value is new rating 2282 $Rating = $NewRating;
2286 # get rating value to return to caller 2287 $Rating = $Record[
"Rating"];
2292 # if new rating was supplied 2293 if ($NewRating != NULL)
2296 $DB->Query(
"INSERT INTO ResourceRatings " 2297 .
"(ResourceId, UserId, DateRated, Rating) " 2304 # update cumulative rating value 2305 $this->UpdateCumulativeRating();
2307 # return value is new rating 2308 $Rating = $NewRating;
2312 # return value is NULL 2317 # return rating value to caller 2322 # --- Resource Comment Methods ------------------------------------------ 2330 # read in comments if not already loaded 2333 $this->DB->Query(
"SELECT MessageId FROM Messages " 2334 .
"WHERE ParentId = ".$this->
Id 2335 .
" AND ParentType = 2 " 2336 .
"ORDER BY DatePosted DESC");
2337 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2343 # return array of comments to caller 2344 return $this->Comments;
2353 # obtain number of comments if not already set 2357 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments " 2359 .
"WHERE ParentId = ".$this->
Id 2360 .
" AND ParentType = 2",
2365 # return number of comments to caller 2366 return $this->NumberOfComments;
2370 # --- Permission Methods ------------------------------------------------- 2383 return $this->CheckSchemaPermissions($User,
"View", $AllowHooksToModify);
2394 return $this->CheckSchemaPermissions($User,
"Edit");
2405 return $this->CheckSchemaPermissions($User,
"Author");
2416 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit");
2417 return $this->$CheckFn($User);
2428 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"View");
2439 $FieldId = $this->
Schema()->StdNameToFieldMapping($MappedName);
2440 return ($FieldId === NULL) ? FALSE
2441 : $this->CheckFieldPermissions($User, $FieldId,
"View");
2452 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"Edit");
2463 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2475 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2477 return $this->$CheckFn($User, $FieldOrFieldName);
2480 # --- Utility Methods ---------------------------------------------------- 2490 $SearchEngine->QueueUpdateForItem($this);
2493 $Recommender->QueueUpdateForItem($this);
2504 # if schema IDs are not loaded 2505 if (!isset(self::$SchemaIdCache))
2509 $DB->Query(
"SELECT ResourceId, SchemaId FROM Resources");
2510 self::$SchemaIdCache =
$DB->FetchColumn(
"SchemaId",
"ResourceId");
2513 # if multiple resources specified 2514 if (is_array($ResourceId))
2516 # find schema IDs for specified resources 2517 $SchemaIds = array_intersect_key(self::$SchemaIdCache,
2518 array_flip($ResourceId));
2520 # check that specified resource IDs were all valid 2521 if (count($SchemaIds) < count($ResourceId))
2523 $BadIds = array_diff($ResourceId, array_keys($SchemaIds));
2524 throw new InvalidArgumentException(
"Unknown resource IDs (" 2525 .implode(
", ", $BadIds).
").");
2528 # return schema IDs to caller 2533 # check that specified resource was valid 2534 if (!isset(self::$SchemaIdCache[$ResourceId]))
2536 throw new InvalidArgumentException(
"Unknown resource ID (" 2540 # return schema IDs for specified resource 2541 return self::$SchemaIdCache[$ResourceId];
2546 # ---- PRIVATE INTERFACE ------------------------------------------------- 2548 private $ClassificationCache;
2550 private $ControlledNameCache;
2551 private $ControlledNameVariantCache;
2552 private $CumulativeRating;
2553 private $NumberOfComments;
2554 private $NumberOfRatings;
2555 private $PermissionCache;
2558 static private $Schemas;
2559 static private $SchemaIdCache;
2571 private function CheckSchemaPermissions($User, $CheckType, $AllowHooksToModify=TRUE)
2573 # construct a key to use for our permissions cache 2574 $CacheKey =
"UserCan".$CheckType.$User->Id();
2576 # if we don't have a cached value for this perm, compute one 2577 if (!isset($this->PermissionCache[$CacheKey]))
2579 # get privileges for schema 2580 $PermsFn = $CheckType.
"ingPrivileges";
2581 $SchemaPrivs = $this->
Schema()->$PermsFn();
2583 # check passes if user privileges are greater than resource set 2584 $CheckResult = $SchemaPrivs->MeetsRequirements($User, $this);
2586 # save the result of this check in our cache 2587 $this->PermissionCache[$CacheKey] = $CheckResult;
2590 $Value = $this->PermissionCache[$CacheKey];
2592 if ($AllowHooksToModify)
2594 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2595 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2597 "Resource" => $this,
2599 "Can".$CheckType => $Value,
2600 "Schema" => $this->
Schema(), ));
2602 $Value = $SignalResult[
"Can".$CheckType];
2616 private function CheckFieldPermissions($User, $Field, $CheckType)
2618 # get field object (if not supplied) 2623 $Field = $this->
Schema()->GetField($Field);
2625 catch (InvalidArgumentException $Exception)
2627 # (user cannot view/author/edit if field was invalid) 2632 # construct a key to use for our permissions cache 2633 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2635 # if we don't have a cahced value, compute one 2636 if (!isset($this->PermissionCache[$CacheKey]))
2638 # if field is enabled and editable, do permission check 2639 if ($Field->Enabled() &&
2640 ($CheckType ==
"View" || $Field->Editable()))
2642 # be sure schema privs allow View/Edit/Author for this resource 2643 $SchemaCheckFn =
"UserCan".$CheckType;
2644 if ($this->$SchemaCheckFn($User))
2646 # get appropriate privilege set for field 2647 $PermsFn = $CheckType.
"ingPrivileges";
2648 $FieldPrivs = $Field->$PermsFn();
2650 # user can View/Edit/Author if privileges are greater than field set 2651 $CheckResult = $FieldPrivs->MeetsRequirements($User, $this);
2655 $CheckResult = FALSE;
2660 $CheckResult = FALSE;
2663 # allow plugins to modify result of permission check 2664 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2665 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2667 "Resource" => $this,
2669 "Can".$CheckType => $CheckResult));
2670 $CheckResult = $SignalResult[
"Can".$CheckType];
2672 # save the result of this check in our cache 2673 $this->PermissionCache[$CacheKey] = $CheckResult;
2676 # return cached permission value 2677 return $this->PermissionCache[$CacheKey];
2683 private function UpdateCumulativeRating()
2685 # grab totals from DB 2686 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, " 2687 .
"SUM(Rating) AS Total FROM ResourceRatings " 2688 .
"WHERE ResourceId = ".$this->
Id);
2689 $Record = $this->DB->FetchRow();
2691 # calculate new cumulative rating 2694 # save new cumulative rating in DB 2695 $this->DB->Query(
"UPDATE Resources " 2697 .
"WHERE ResourceId = ".$this->Id);
2711 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2713 # We should ignore duplicate key errors when doing inserts: 2714 $this->DB->SetQueryErrorsToIgnore( array(
2715 "/INSERT INTO ".$TableName.
"/" =>
2716 "/Duplicate entry '-?[0-9]+-[0-9]+(-[0-9]+)?' for key/"));
2718 # start out assuming no association will be added 2719 $AssociationAdded = FALSE;
2721 # convert new value to array if necessary 2722 $Values = is_array($Value) ? $Value : array($Value);
2724 # for each new value 2725 foreach ($Values as $Value)
2727 # retrieve ID from value if necessary 2728 if (is_object($Value)) { $Value = $Value->Id(); }
2730 # Try to insert a new entry for this association. 2731 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET" 2732 .
" ResourceId = ".intval($this->
Id)
2733 .
", ".$FieldName.
" = ".intval($Value)
2734 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2736 # If the insert ran without a duplicate key error, 2737 # then we added an assocation: 2738 if ($this->DB->IgnoredError() === FALSE)
2740 $AssociationAdded = TRUE;
2744 # Clear ignored errors: 2745 $this->DB->SetQueryErrorsToIgnore( NULL );
2747 # report to caller whether association was added 2748 return $AssociationAdded;
2762 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2764 # start out assuming no association will be removed 2765 $AssociationRemoved = FALSE;
2767 # convert value to array if necessary 2768 $Values = is_array($Value) ? $Value : array($Value);
2771 foreach ($Values as $Value)
2773 # retrieve ID from value if necessary 2774 if (is_object($Value)) { $Value = $Value->Id(); }
2776 # remove any intersections with target ID from DB 2777 $this->DB->Query(
"DELETE FROM ".$TableName
2778 .
" WHERE ResourceId = ".intval($this->
Id)
2779 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2780 .
" AND ".$FieldName.
" = ".intval($Value));
2781 if ($this->DB->NumRowsAffected()) { $AssociationRemoved = TRUE; }
2784 # report to caller whether association was added 2785 return $AssociationRemoved;
2794 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2796 # retrieve list of entries for this field and resource 2797 $Entries = $this->
Get($Field);
2799 # divide them into chunks of not more than 100 2800 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2802 # remove assocations from this chunk 2803 $this->DB->Query(
"DELETE FROM ".$TableName
2804 .
" WHERE ResourceId = ".intval($this->
Id)
2805 .
" AND ".$TargetFieldName.
" IN " 2806 .
"(".implode(
",", array_keys($Chunk)).
")");
2818 if (!isset(self::$ItemIdColumnNames[$ClassName]))
2820 self::$ItemIdColumnNames[$ClassName] =
"ResourceId";
2821 self::$ItemNameColumnNames[$ClassName] = NULL;
2822 self::$ItemTableNames[$ClassName] =
"Resources";
GetByField($FieldNameOrObject, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Old method for retrieving values, deprecated in favor of Get().
UserCanView(User $User, $AllowHooksToModify=TRUE)
Determine if the given user can view the resource, e.g., on the full record page. ...
GetFilesForResource($ResourceOrResourceId, $ReturnObjects=TRUE)
Retrieve all files (names or objects) for specified resource.
GetImageUrls($FieldNameOrObject, $ImageSize=SPTImage::SIZE_FULL)
Get URLs for images, returning CleanURLs when possible and direct paths to image files otherwise...
SetQualifier($FieldName, $NewValue)
Set qualifier using field name.
UserCanViewMappedField($User, $MappedName)
Check whether user can view specified standard (mapped) metadata field.
Abstraction for forum messages and resource comments.
SQL database abstraction object with smart query caching.
UserCanModifyField($User, $FieldOrFieldName)
Check whether user is allowed to modify (Edit for perm resources, Author for temp) specified metadata...
QueueSearchAndRecommenderUpdate()
Update search and recommender system DBs.
GetAsArray($IncludeDisabledFields=FALSE, $ReturnObjects=TRUE)
Retrieve all resource values as an array.
Id()
Retrieve numerical resource ID.
UserCanEditField($User, $FieldOrFieldName)
Check whether user is allowed to edit specified metadata field.
SetQualifierByField($Field, $NewValue)
Set qualifier using field object.
GetViewPageUrl()
Retrieve view page URL for this resource.
Rating($NewRating=NULL, $UserId=NULL)
Get/set rating by a specific user for resource.
NumberOfComments()
Get current number of comments for resource.
NumberOfRatings()
Get current number of ratings for resource.
GetQualifier($FieldName, $ReturnObject=TRUE)
Retrieve qualifier by field name.
Factory object for Folder class, used to retrieve and manage Folders and groups of Folders...
Copy($FileToCopy)
Create copy of File and return to caller.
Schema()
Get MetadataSchema for resource.
Metadata type representing non-hierarchical controlled vocabulary values.
UserCanEdit($User)
Determine if the given user can edit the resource.
GetForDisplay($FieldNameOrObject, $ReturnObject=TRUE, $IncludeVariants=FALSE)
Retrieve value using field name or field object, signaling EVENT_FIELD_DISPLAY_FILTER to allow other ...
Comments()
Get comments for resource.
UpdateAutoupdateFields($UpdateType, $User=NULL)
Update the auto-updated fields as necessary.
CWIS-specific user factory class.
Get($Field, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field name or field object.
static GetSchemaForResource($ResourceId)
Get schema ID for specified resource(s).
Factory for manipulating File objects.
Common base class for persistent items store in database.
GetQualifierByFieldId($FieldId, $ReturnObject=TRUE)
Retrieve qualifier by field ID.
Encapsulates a full-size, preview, and thumbnail image.
UserCanAuthorField($User, $FieldOrFieldName)
Check whether user is allowed to author specified metadata field.
Clear($Field, $ValueToClear=NULL)
Clear field value.
UserCanModify($User)
Check if the user is allowed to modify (Edit for perm resources, Author for temp) a specified resourc...
UserCanAuthor($User)
Determine if the given user can edit the resource.
GetByFieldId($FieldId, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using field ID.
IsTempResource($NewSetting=NULL)
Get/set whether resource is a temporary record.
SetByField($Field, $NewValue)
Method replaced by Resource::Set(), preserved for backward compatibility.
const STATUS_OK
Successful execution.
__construct($ResourceId)
Object constructor for loading an existing resource.
GetMapped($MappedName, $ReturnObject=FALSE, $IncludeVariants=FALSE)
Retrieve value using standard (mapped) field name.
static SetDatabaseAccessValues($ClassName)
Set the database access values (table name, ID column name, name column name) for specified class...
Represents a "resource" in CWIS.
GetQualifierByField($Field, $ReturnObject=TRUE)
Retrieve qualifier by Field object.
ClearByFieldId($FieldId, $ValueToClear=NULL)
Clear field value specified by field ID.
SetQualifierByFieldId($FieldId, $NewValue)
Set qualifier using field ID.
static ClearImageSymlinksForResource($ResourceId, $FieldId)
Remove symlinks used for to cache image mappings.
SchemaId()
Retrieve ID of schema for resource.
ScaledCumulativeRating()
Return cumulative rating scaled to 1/10th.
Set($Field, $NewValue, $Reset=FALSE)
Set value using field name or field object.
static Create($SchemaId)
Create a new resource.
UserCanViewField($User, $FieldOrFieldName)
Check whether user is allowed to view specified metadata field.
Metadata type representing hierarchical ("Tree") controlled vocabulary values.
SetByFieldId($FieldId, $NewValue)
Set field value using field ID.
Classifications()
Get 2D array of classifications associated with resource.
ClearByField($Field, $ValueToClear=NULL)
Clear field value.
Class representing a stored (usually uploaded) file.
Factory for Resource objects.
CWIS-specific user class.
CumulativeRating()
Get cumulative rating (range is usually 0-100)
FieldIsSet($FieldNameOrObject, $IgnorePadding=FALSE)
Determine if the value for a field is set.
Delete()
Remove resource (and accompanying associations) from database and delete any associated files...