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 ($G_SysConfig->SearchDBEnabled())
219 $SearchEngine->DropItem($this->
Id());
221 if ($G_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 throw new Exception(
"Attempt to retrieve " 712 .
"unknown field type (".$Field->Type().
")");
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 !is_null($Value)
1059 && (!$IgnorePadding || ($IgnorePadding && strlen(trim($Value))));
1062 return !is_null($Value)
1066 return !is_null($Value[
"X"])
1067 && !is_null($Value[
"Y"])
1068 && strlen(trim($Value[
"X"]))
1069 && strlen(trim($Value[
"Y"]));
1072 return !is_null($Value)
1073 && strlen(trim($Value))
1074 && $Value !=
"0000-00-00";
1077 return !is_null($Value)
1078 && strlen(trim($Value))
1079 && $Value !=
"0000-00-00 00:00:00";
1087 return count($Value) > 0;
1091 return !is_null($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 (is_null($NewValue))
1329 if (!is_null($this->ValueCache[$DBFieldName.
"Begin"]) ||
1330 !is_null($this->ValueCache[$DBFieldName.
"End"]) ||
1331 !is_null($this->ValueCache[$DBFieldName.
"Precision"]))
1333 # clear date object values in DB 1334 $DB->Query(
"UPDATE Resources SET " 1335 .$DBFieldName.
"Begin = '', " 1336 .$DBFieldName.
"End = '', " 1337 .$DBFieldName.
"Precision = '' " 1338 .
"WHERE ResourceId = ".$ResourceId);
1340 # clear value locally 1341 $this->ValueCache[$DBFieldName.
"Begin"] = NULL;
1342 $this->ValueCache[$DBFieldName.
"End"] = NULL;
1343 $this->ValueCache[$DBFieldName.
"Precision"] = NULL;
1344 $UpdateModTime=TRUE;
1350 # if we were given a date object 1351 if (is_object($NewValue))
1353 # use supplied date object 1358 # create date object 1359 $Date =
new Date($NewValue);
1362 $OldDate =
new Date(
1363 $this->ValueCache[$DBFieldName.
"Begin"],
1364 $this->ValueCache[$DBFieldName.
"End"],
1365 $this->ValueCache[$DBFieldName.
"Precision"]);
1367 if ($OldDate->BeginDate() != $Date->BeginDate() ||
1368 $OldDate->EndDate() != $Date->EndDate() ||
1369 $OldDate->Precision() != $Date->Precision() )
1371 # extract values from date object and store in DB 1372 $BeginDate = !is_null($Date->BeginDate()) ?
1373 "'".$Date->BeginDate().
"'" :
"NULL" ;
1374 $EndDate = !is_null($Date->EndDate()) ?
1375 "'".$Date->EndDate().
"'" :
"NULL" ;
1377 $DB->Query(
"UPDATE Resources SET " 1378 .$DBFieldName.
"Begin = ".$BeginDate.
", " 1379 .$DBFieldName.
"End = ".$EndDate.
", " 1380 .$DBFieldName.
"Precision = '".$Date->Precision().
"' " 1381 .
"WHERE ResourceId = ".$ResourceId);
1383 # save values locally 1384 $this->ValueCache[$DBFieldName.
"Begin"] = $Date->BeginDate();
1385 $this->ValueCache[$DBFieldName.
"End"] = $Date->EndDate();
1386 $this->ValueCache[$DBFieldName.
"Precision"] = $Date->Precision();
1387 $UpdateModTime=TRUE;
1393 if (is_null($NewValue) || !strlen(trim($NewValue)))
1395 $DateValue = $NewValue;
1397 if (!is_null($this->ValueCache[$DBFieldName]))
1399 # save value directly to DB 1400 $DB->Query(
"UPDATE Resources SET " 1401 .
"`".$DBFieldName.
"` = NULL " 1402 .
"WHERE ResourceId = ".$ResourceId);
1403 $UpdateModTime = TRUE;
1408 # assume value is date and use directly 1409 $TimestampValue = strtotime($NewValue);
1411 # use the new value if the date is valid 1412 if ($TimestampValue !== FALSE && $TimestampValue >= 0)
1414 $DateValue = date(
"Y-m-d H:i:s", $TimestampValue);
1416 if ($this->ValueCache[$DBFieldName] != $DateValue)
1418 # save value directly to DB 1419 $DB->Query(
"UPDATE Resources SET " 1420 .
"`".$DBFieldName.
"` = '".addslashes($DateValue).
"' " 1421 .
"WHERE ResourceId = ".$ResourceId);
1422 $UpdateModTime=TRUE;
1426 # continue using the old value if invalid 1429 $DateValue = $this->
Get($Field);
1433 # save value locally 1434 $this->ValueCache[$DBFieldName] = $DateValue;
1438 $OldValue = $this->
Get($Field);
1440 # if incoming value is array 1441 if (is_array($NewValue))
1443 if ($OldValue != $NewValue)
1447 # remove values that were in the old value 1448 # but not the new one 1449 $ToRemove = array_diff(array_keys($OldValue),
1450 array_keys($NewValue));
1451 foreach ($ToRemove as $ClassificationId)
1453 $this->RemoveAssociation(
"ResourceClassInts",
1457 $Class->RecalcResourceCount();
1461 # for each element of array 1462 foreach ($NewValue as
1463 $ClassificationId => $ClassificationName)
1466 if ($Class->FieldId() == $Field->Id())
1468 # associate with resource if not already associated 1469 if ($this->AddAssociation(
"ResourceClassInts",
1470 "ClassificationId", $ClassificationId))
1472 $Class->UpdateLastAssigned();
1473 $Class->RecalcResourceCount();
1478 throw new Exception(
1479 "Attempting to store classification from " 1480 .
"Field ".$Class->FieldId().
" into Field " 1486 $UpdateModTime=TRUE;
1491 # associate with resource if not already associated 1492 if (is_object($NewValue))
1495 $NewValue = $Class->Id();
1502 if (!array_key_exists($Class->Id(), $OldValue))
1505 $this->AddAssociation(
"ResourceClassInts",
1508 $Class->UpdateLastAssigned();
1509 $Class->RecalcResourceCount();
1510 $UpdateModTime=TRUE;
1514 # clear our classification cache 1517 unset($this->ClassificationCache);
1523 $OldValue = $this->
Get($Field);
1525 # input to Set() for these fields is one of 1526 # 1. an int specifying a ControlledNameId 1527 # 2. a ControlledName object 1528 # 3. an array with keys giving Ids and values giving ControlledNames 1530 # normalize 1 and 2 into 3 for simplicity of processing 1531 if (is_object($NewValue) || !is_array($NewValue) )
1533 if (!is_object($NewValue))
1538 $TmpValue = array();
1539 $TmpValue[$NewValue->Id()] = $NewValue->Name();
1541 $NewValue = $TmpValue;
1544 # if this is a unique field, only accept the first of the options given 1545 # NB: all ControlledNames implicitly AllowMultiple 1547 $Field->AllowMultiple() == FALSE && count($NewValue) > 1)
1549 $NewValue = array_slice($NewValue, 0, 1, TRUE);
1552 # if the value has changed 1553 if ($OldValue != $NewValue)
1556 && $Field->AllowMultiple() == FALSE ) )
1558 $ToRemove = array_diff(array_keys($OldValue),
1559 array_keys($NewValue));
1560 foreach ($ToRemove as $CNId)
1562 $this->RemoveAssociation(
"ResourceNameInts",
1568 # for each element of array 1569 foreach ($NewValue as $ControlledNameId => $ControlledName)
1571 # associate with resource if not already associated 1572 if ($this->AddAssociation(
"ResourceNameInts",
1580 $CN->UpdateLastAssigned();
1584 $this->RemoveAssociation(
"ResourceNameInts",
1585 "ControlledNameId", $ControlledNameId);
1586 throw new InvalidArgumentException(
1587 "Attempt to set controlled name with" 1588 .
" invalid ID (".$ControlledNameId.
").");
1592 $UpdateModTime = TRUE;
1597 # clear our controlled name cache 1598 unset($this->ControlledNameCache);
1599 unset($this->ControlledNameVariantCache);
1601 # clear visible count cache for any affected CNames 1603 $RFactory->ClearVisibleResourceCountForValues(
1604 array_keys($OldValue + $NewValue) );
1610 # associate value(s) with resource 1611 $this->AddAssociation(
1612 "ResourceImageInts",
"ImageId", $NewValue, $Field);
1613 # clear cached image mappings 1618 # convert incoming value to array if necessary 1619 if (!is_array($NewValue)) { $NewValue = array($NewValue); }
1621 # for each incoming file 1623 foreach ($NewValue as $File)
1626 $NewFile = $Factory->
Copy($File);
1628 # associate copy with this resource and field 1629 $NewFile->ResourceId($this->
Id);
1630 $NewFile->FieldId($Field->Id());
1632 # Since we make a fresh copy of the File whenever Set is called, 1633 # we'll always update the modification time for this field. 1634 $UpdateModTime = TRUE;
1638 # convert incoming value to array to simplify the workflow 1639 if (!is_array($NewValue))
1641 $NewValue = [$NewValue];
1644 # delete existing resource references 1646 "DELETE FROM ReferenceInts " 1647 .
"WHERE FieldId = '".addslashes($Field->Id()).
"' " 1648 .
"AND SrcResourceId = '".addslashes($this->
Id()).
"'");
1650 # add each reference 1651 foreach ($NewValue as $ReferenceId)
1653 if ($ReferenceId instanceof
Resource)
1655 $ReferenceId = $ReferenceId->Id();
1658 # skip blank reference IDs 1659 if (strlen(trim($ReferenceId)) < 1)
1664 # skip reference IDs that don't look right 1665 if (!is_numeric($ReferenceId))
1670 # skip references to the current resource 1671 if ($ReferenceId == $this->
Id())
1676 # add the reference to the references table 1678 "INSERT INTO ReferenceInts (" 1683 .addslashes($Field->Id()).
"," 1684 .addslashes($this->
Id()).
"," 1685 .addslashes($ReferenceId).
")");
1691 exit(
"<br>SPT - ERROR: attempt to set unknown resource field type<br>\n");
1697 # update modification timestamps 1699 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1700 $DB->Query(
"DELETE FROM ResourceFieldTimestamps " 1701 .
"WHERE ResourceId=".$this->
Id.
" AND " 1702 .
"FieldId=".$Field->Id() );
1703 $DB->Query(
"INSERT INTO ResourceFieldTimestamps " 1704 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 1705 .$this->
Id.
",".$Field->Id().
"," 1706 .$UserId.
",NOW())");
1708 # on resource modification, clear the UserPermsCache entry 1709 # so that stale permissions checks are not cached 1710 $DB->Query(
"DELETE FROM UserPermsCache WHERE ResourceId=".$this->
Id);
1712 # if this field is not an option or a cname, but it is 1713 # checked for visibility, then we need to clear resource 1714 # visibility cache (for example, if this is AddedById and 1715 # our schema allows users to view resources where they are 1717 if (!in_array($Field->Type(),
1720 $this->
Schema()->ViewingPrivileges()->ChecksField($Field->Id()))
1723 $RFactory->ClearVisibleResourceCount($this);
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->ValueCache[$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 $UpdateModTime = FALSE;
1835 # store value in DB based on field type 1836 switch ($Field->Type())
1846 $this->
Set($Field, NULL);
1853 # if value to clear supplied 1854 if ($ValueToClear !== NULL)
1856 $Value = $this->
Get($Field);
1858 if (!is_array($ValueToClear))
1860 $ValueToClear = [$ValueToClear =>
"Dummy"];
1863 # for each element of array 1864 foreach ($ValueToClear as
$Id => $Dummy)
1866 if (array_key_exists(
$Id, $Value))
1872 $this->
Set($Field, $Value, TRUE);
1876 $this->
Set($Field, [], TRUE);
1882 # if value to clear supplied 1883 if ($ValueToClear !== NULL)
1885 # convert value to array if necessary 1886 $Files = $ValueToClear;
1887 if (!is_array($Files)) { $Files = array($Files); }
1889 # convert values to objects if necessary 1890 foreach ($Files as $Index => $File)
1892 if (!is_object($File))
1894 $Files[$Index] =
new File($File);
1900 # use all files associated with resource 1901 $Files = $this->
Get($Field, TRUE);
1905 foreach ($Files as $File) { $File->Delete(); }
1909 # if value to clear supplied 1910 if ($ValueToClear !== NULL)
1912 # convert value to array if necessary 1913 $Images = $ValueToClear;
1914 if (!is_array($Images)) { $Images = array($Images); }
1916 # convert values to objects if necessary 1917 foreach ($Images as $Index => $Image)
1919 if (!is_object($Image))
1921 $Images[$Index] =
new SPTImage($Image);
1927 # use all images associated with resource 1928 $Images = $this->
Get($Field, TRUE);
1931 # delete images if we are the last resource referencing 1932 # a particular image. 1933 foreach ($Images as $Image)
1935 $Cnt = $this->DB->Query(
1936 "SELECT COUNT(*) AS Cnt FROM ResourceImageInts WHERE ".
1937 "ImageId=".$Image->Id(),
"Cnt");
1944 # clear cached image mappings 1947 # remove connections to images 1948 $UpdateModTime = $this->RemoveAssociation(
1949 "ResourceImageInts",
"ImageId", $Images, $Field);
1953 $this->
Set($Field, []);
1958 exit(
"<br>SPT - ERROR: attempt to clear " 1959 .
"unknown resource field type<br>\n");
1965 # update modification timestamps 1967 $UserId = $G_User->IsLoggedIn() ? $G_User->Get(
"UserId") : -1;
1968 $this->DB->Query(
"DELETE FROM ResourceFieldTimestamps " 1969 .
"WHERE ResourceId=".$this->
Id.
" AND " 1970 .
"FieldId=".$Field->Id() );
1971 $this->DB->Query(
"INSERT INTO ResourceFieldTimestamps " 1972 .
"(ResourceId,FieldId,ModifiedBy,Timestamp) VALUES (" 1973 .$this->
Id.
",".$Field->Id().
"," 1974 .$UserId.
",NOW())");
1988 $this->
Clear($Field, $ValueToClear);
1991 # --- Field-Specific or Type-Specific Attribute Retrieval Methods ------- 2002 # start with empty array 2005 # for each controlled name 2006 $DB->Query(
"SELECT ClassificationName, MetadataFields.FieldName, " 2007 .
"ResourceClassInts.ClassificationId FROM ResourceClassInts, " 2008 .
"Classifications, MetadataFields " 2009 .
"WHERE ResourceClassInts.ResourceId = ".$this->
Id.
" " 2010 .
"AND ResourceClassInts.ClassificationId = " 2011 .
"Classifications.ClassificationId " 2012 .
"AND Classifications.FieldId = MetadataFields.FieldId ");
2013 while ($Record =
$DB->FetchRow())
2016 $Names[$Record[
"FieldName"]][$Record[
"ClassificationId"]] =
2017 $Record[
"ClassificationName"];
2020 # return array to caller 2025 # --- Ratings Methods --------------------------------------------------- 2033 return $this->CumulativeRating;
2058 # if number of ratings not already set 2061 # obtain number of ratings 2063 $this->DB->Query(
"SELECT Count(*) AS NumberOfRatings " 2064 .
"FROM ResourceRatings " 2065 .
"WHERE ResourceId = ".$this->
Id,
2069 # recalculate cumulative rating if it looks erroneous 2072 $this->UpdateCumulativeRating();
2076 # return number of ratings to caller 2077 return $this->NumberOfRatings;
2087 public function Rating($NewRating = NULL, $UserId = NULL)
2091 # if user ID not supplied 2092 if ($UserId == NULL)
2094 # if user is logged in 2096 if ($G_User->IsLoggedIn())
2098 # use ID of current user 2099 $UserId = $G_User->Get(
"UserId");
2103 # return NULL to caller 2108 # sanitize $NewRating 2109 if (!is_null($NewRating))
2111 $NewRating = intval($NewRating);
2114 # if there is a rating for resource and user 2115 $DB->Query(
"SELECT Rating FROM ResourceRatings " 2116 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2117 if ($Record =
$DB->FetchRow())
2119 # if new rating was supplied 2120 if ($NewRating != NULL)
2122 # update existing rating 2123 $DB->Query(
"UPDATE ResourceRatings " 2124 .
"SET Rating = ${NewRating}, DateRated = NOW() " 2125 .
"WHERE UserId = ${UserId} AND ResourceId = ".$this->
Id);
2127 # update cumulative rating value 2128 $this->UpdateCumulativeRating();
2130 # return value is new rating 2131 $Rating = $NewRating;
2135 # get rating value to return to caller 2136 $Rating = $Record[
"Rating"];
2141 # if new rating was supplied 2142 if ($NewRating != NULL)
2145 $DB->Query(
"INSERT INTO ResourceRatings " 2146 .
"(ResourceId, UserId, DateRated, Rating) " 2153 # update cumulative rating value 2154 $this->UpdateCumulativeRating();
2156 # return value is new rating 2157 $Rating = $NewRating;
2161 # return value is NULL 2166 # return rating value to caller 2171 # --- Resource Comment Methods ------------------------------------------ 2179 # read in comments if not already loaded 2182 $this->DB->Query(
"SELECT MessageId FROM Messages " 2183 .
"WHERE ParentId = ".$this->
Id 2184 .
" AND ParentType = 2 " 2185 .
"ORDER BY DatePosted DESC");
2186 while ($MessageId = $this->DB->FetchField(
"MessageId"))
2192 # return array of comments to caller 2193 return $this->Comments;
2202 # obtain number of comments if not already set 2206 $this->DB->Query(
"SELECT Count(*) AS NumberOfComments " 2208 .
"WHERE ParentId = ".$this->
Id 2209 .
" AND ParentType = 2",
2214 # return number of comments to caller 2215 return $this->NumberOfComments;
2219 # --- Permission Methods ------------------------------------------------- 2232 return $this->CheckSchemaPermissions($User,
"View", $AllowHooksToModify);
2243 return $this->CheckSchemaPermissions($User,
"Edit");
2254 return $this->CheckSchemaPermissions($User,
"Author");
2265 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit");
2266 return $this->$CheckFn($User);
2277 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"View");
2288 $FieldId = $this->
Schema()->StdNameToFieldMapping($MappedName);
2289 return ($FieldId === NULL) ? FALSE
2290 : $this->CheckFieldPermissions($User, $FieldId,
"View");
2301 return $this->CheckFieldPermissions($User, $FieldOrFieldName,
"Edit");
2312 return $this->CheckFieldPermissions( $User, $FieldOrFieldName,
"Author" );
2324 $CheckFn =
"UserCan".(($this->Id()<0) ?
"Author" :
"Edit").
"Field";
2326 return $this->$CheckFn($User, $FieldOrFieldName);
2329 # --- Utility Methods ---------------------------------------------------- 2339 $SearchEngine->QueueUpdateForItem($this);
2342 $Recommender->QueueUpdateForItem($this);
2353 # if schema IDs are not loaded 2354 if (!isset(self::$SchemaIdCache))
2358 $DB->Query(
"SELECT ResourceId, SchemaId FROM Resources");
2359 self::$SchemaIdCache =
$DB->FetchColumn(
"SchemaId",
"ResourceId");
2362 # if multiple resources specified 2363 if (is_array($ResourceId))
2365 # find schema IDs for specified resources 2366 $SchemaIds = array_intersect_key(self::$SchemaIdCache,
2367 array_flip($ResourceId));
2369 # check that specified resource IDs were all valid 2370 if (count($SchemaIds) < count($ResourceId))
2372 $BadIds = array_diff($ResourceId, array_keys($SchemaIds));
2373 throw new InvalidArgumentException(
"Unknown resource IDs (" 2374 .implode(
", ", $BadIds).
").");
2377 # return schema IDs to caller 2382 # check that specified resource was valid 2383 if (!isset(self::$SchemaIdCache[$ResourceId]))
2385 throw new InvalidArgumentException(
"Unknown resource ID (" 2389 # return schema IDs for specified resource 2390 return self::$SchemaIdCache[$ResourceId];
2395 # ---- PRIVATE INTERFACE ------------------------------------------------- 2397 private $ClassificationCache;
2399 private $ControlledNameCache;
2400 private $ControlledNameVariantCache;
2401 private $CumulativeRating;
2402 private $NumberOfComments;
2403 private $NumberOfRatings;
2404 private $PermissionCache;
2407 static private $Schemas;
2408 static private $SchemaIdCache;
2420 private function CheckSchemaPermissions($User, $CheckType, $AllowHooksToModify=TRUE)
2422 # construct a key to use for our permissions cache 2423 $CacheKey =
"UserCan".$CheckType.$User->Id();
2425 # if we don't have a cached value for this perm, compute one 2426 if (!isset($this->PermissionCache[$CacheKey]))
2428 # get privileges for schema 2429 $PermsFn = $CheckType.
"ingPrivileges";
2430 $SchemaPrivs = $this->
Schema()->$PermsFn();
2432 # check passes if user privileges are greater than resource set 2433 $CheckResult = $SchemaPrivs->MeetsRequirements($User, $this);
2435 # save the result of this check in our cache 2436 $this->PermissionCache[$CacheKey] = $CheckResult;
2439 $Value = $this->PermissionCache[$CacheKey];
2441 if ($AllowHooksToModify)
2443 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2444 "EVENT_RESOURCE_".strtoupper($CheckType).
"_PERMISSION_CHECK",
2446 "Resource" => $this,
2448 "Can".$CheckType => $Value,
2449 "Schema" => $this->
Schema(), ));
2451 $Value = $SignalResult[
"Can".$CheckType];
2465 private function CheckFieldPermissions($User, $Field, $CheckType)
2467 # get field object (if not supplied) 2472 $Field = $this->
Schema()->GetField($Field);
2474 catch (InvalidArgumentException $Exception)
2476 # (user cannot view/author/edit if field was invalid) 2481 # construct a key to use for our permissions cache 2482 $CacheKey =
"UserCan".$CheckType.
"Field".$Field->Id().
"-".$User->Id();
2484 # if we don't have a cahced value, compute one 2485 if (!isset($this->PermissionCache[$CacheKey]))
2487 # if field is enabled and editable, do permission check 2488 if ($Field->Enabled() &&
2489 ($CheckType ==
"View" || $Field->Editable()))
2491 # be sure schema privs allow View/Edit/Author for this resource 2492 $SchemaCheckFn =
"UserCan".$CheckType;
2493 if ($this->$SchemaCheckFn($User))
2495 # get appropriate privilege set for field 2496 $PermsFn = $CheckType.
"ingPrivileges";
2497 $FieldPrivs = $Field->$PermsFn();
2499 # user can View/Edit/Author if privileges are greater than field set 2500 $CheckResult = $FieldPrivs->MeetsRequirements($User, $this);
2504 $CheckResult = FALSE;
2509 $CheckResult = FALSE;
2512 # allow plugins to modify result of permission check 2513 $SignalResult = $GLOBALS[
"AF"]->SignalEvent(
2514 "EVENT_FIELD_".strtoupper($CheckType).
"_PERMISSION_CHECK", array(
2516 "Resource" => $this,
2518 "Can".$CheckType => $CheckResult));
2519 $CheckResult = $SignalResult[
"Can".$CheckType];
2521 # save the result of this check in our cache 2522 $this->PermissionCache[$CacheKey] = $CheckResult;
2525 # return cached permission value 2526 return $this->PermissionCache[$CacheKey];
2532 private function UpdateCumulativeRating()
2534 # grab totals from DB 2535 $this->DB->Query(
"SELECT COUNT(Rating) AS Count, " 2536 .
"SUM(Rating) AS Total FROM ResourceRatings " 2537 .
"WHERE ResourceId = ".$this->
Id);
2538 $Record = $this->DB->FetchRow();
2540 # calculate new cumulative rating 2543 # save new cumulative rating in DB 2544 $this->DB->Query(
"UPDATE Resources " 2546 .
"WHERE ResourceId = ".$this->Id);
2560 private function AddAssociation($TableName, $FieldName, $Value, $Field = NULL)
2562 # We should ignore duplicate key errors when doing inserts: 2563 $this->DB->SetQueryErrorsToIgnore( array(
2564 "/INSERT INTO ".$TableName.
"/" =>
2565 "/Duplicate entry '-?[0-9]+-[0-9]+(-[0-9]+)?' for key/"));
2567 # start out assuming no association will be added 2568 $AssociationAdded = FALSE;
2570 # convert new value to array if necessary 2571 $Values = is_array($Value) ? $Value : array($Value);
2573 # for each new value 2574 foreach ($Values as $Value)
2576 # retrieve ID from value if necessary 2577 if (is_object($Value)) { $Value = $Value->Id(); }
2579 # Try to insert a new entry for this association. 2580 $this->DB->Query(
"INSERT INTO ".$TableName.
" SET" 2581 .
" ResourceId = ".intval($this->
Id)
2582 .
", ".$FieldName.
" = ".intval($Value)
2583 .($Field ?
", FieldId = ".intval($Field->Id()) :
""));
2585 # If the insert ran without a duplicate key error, 2586 # then we added an assocation: 2587 if ($this->DB->IgnoredError() === FALSE)
2589 $AssociationAdded = TRUE;
2593 # Clear ignored errors: 2594 $this->DB->SetQueryErrorsToIgnore( NULL );
2596 # report to caller whether association was added 2597 return $AssociationAdded;
2611 private function RemoveAssociation($TableName, $FieldName, $Value, $Field = NULL)
2613 # start out assuming no association will be removed 2614 $AssociationRemoved = FALSE;
2616 # convert value to array if necessary 2617 $Values = is_array($Value) ? $Value : array($Value);
2620 foreach ($Values as $Value)
2622 # retrieve ID from value if necessary 2623 if (is_object($Value)) { $Value = $Value->Id(); }
2625 # remove any intersections with target ID from DB 2626 $this->DB->Query(
"DELETE FROM ".$TableName
2627 .
" WHERE ResourceId = ".intval($this->
Id)
2628 .($Field ?
" AND FieldId = ".intval($Field->Id()) :
"")
2629 .
" AND ".$FieldName.
" = ".intval($Value));
2630 if ($this->DB->NumRowsAffected()) { $AssociationRemoved = TRUE; }
2633 # report to caller whether association was added 2634 return $AssociationRemoved;
2643 private function RemoveAllAssociations($TableName, $TargetFieldName, $Field)
2645 # retrieve list of entries for this field and resource 2646 $Entries = $this->
Get($Field);
2648 # divide them into chunks of not more than 100 2649 foreach (array_chunk($Entries, 100, TRUE) as $Chunk)
2651 # remove assocations from this chunk 2652 $this->DB->Query(
"DELETE FROM ".$TableName
2653 .
" WHERE ResourceId = ".intval($this->
Id)
2654 .
" AND ".$TargetFieldName.
" IN " 2655 .
"(".implode(
",", array_keys($Chunk)).
")");
2667 if (!isset(self::$ItemIdColumnNames[$ClassName]))
2669 self::$ItemIdColumnNames[$ClassName] =
"ResourceId";
2670 self::$ItemNameColumnNames[$ClassName] = NULL;
2671 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.
__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.
static ItemExists($Id)
Check whether an item exists with the specified ID.
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...