예제 #1
0
 private static function validateJSONItem($json, $libraryID, Zotero_Item $item = null, $isChild, $requestParams, $partialUpdate = false)
 {
     $isNew = !$item || !$item->version;
     if (!is_object($json)) {
         throw new Exception("Invalid item object (found " . gettype($json) . " '" . $json . "')", Z_ERROR_INVALID_INPUT);
     }
     if (isset($json->items) && is_array($json->items)) {
         throw new Exception("An 'items' array is not valid for single-item updates", Z_ERROR_INVALID_INPUT);
     }
     $apiVersion = $requestParams['v'];
     if ($partialUpdate) {
         $requiredProps = [];
     } else {
         if (isset($json->itemType) && $json->itemType == "attachment") {
             $requiredProps = array('linkMode', 'tags');
         } else {
             if (isset($json->itemType) && $json->itemType == "attachment") {
                 $requiredProps = array('tags');
             } else {
                 if ($isNew) {
                     $requiredProps = array('itemType');
                 } else {
                     if ($apiVersion < 2) {
                         $requiredProps = array('itemType', 'tags');
                     } else {
                         $requiredProps = array('itemType', 'tags', 'relations');
                         if (!$isChild) {
                             $requiredProps[] = 'collections';
                         }
                     }
                 }
             }
         }
     }
     foreach ($requiredProps as $prop) {
         if (!isset($json->{$prop})) {
             throw new Exception("'{$prop}' property not provided", Z_ERROR_INVALID_INPUT);
         }
     }
     // For partial updates where item type isn't provided, use the existing item type
     if (!isset($json->itemType) && $partialUpdate) {
         $itemType = Zotero_ItemTypes::getName($item->itemTypeID);
     } else {
         $itemType = $json->itemType;
     }
     foreach ($json as $key => $val) {
         switch ($key) {
             // Handled by Zotero_API::checkJSONObjectVersion()
             case 'key':
             case 'version':
                 if ($apiVersion < 3) {
                     throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'itemKey':
             case 'itemVersion':
                 if ($apiVersion != 2) {
                     throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'parentItem':
                 if ($apiVersion < 2) {
                     throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 if (!Zotero_ID::isValidKey($val) && $val !== false) {
                     throw new Exception("'{$key}' must be a valid item key", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'itemType':
                 if (!is_string($val)) {
                     throw new Exception("'itemType' must be a string", Z_ERROR_INVALID_INPUT);
                 }
                 if ($isChild || !empty($json->parentItem)) {
                     switch ($val) {
                         case 'note':
                         case 'attachment':
                             break;
                         default:
                             throw new Exception("Child item must be note or attachment", Z_ERROR_INVALID_INPUT);
                     }
                 } else {
                     if ($val == 'attachment' && (!$item || !$item->getSource())) {
                         if ($json->linkMode == 'linked_url' || $json->linkMode == 'imported_url' && (empty($json->contentType) || $json->contentType != 'application/pdf')) {
                             throw new Exception("Only file attachments and PDFs can be top-level items", Z_ERROR_INVALID_INPUT);
                         }
                     }
                 }
                 if (!Zotero_ItemTypes::getID($val)) {
                     throw new Exception("'{$val}' is not a valid itemType", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'tags':
                 if (!is_array($val)) {
                     throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT);
                 }
                 foreach ($val as $tag) {
                     $empty = true;
                     if (is_string($tag)) {
                         if ($tag === "") {
                             throw new Exception("Tag cannot be empty", Z_ERROR_INVALID_INPUT);
                         }
                         continue;
                     }
                     if (!is_object($tag)) {
                         throw new Exception("Tag must be an object", Z_ERROR_INVALID_INPUT);
                     }
                     foreach ($tag as $k => $v) {
                         switch ($k) {
                             case 'tag':
                                 if (!is_scalar($v)) {
                                     throw new Exception("Invalid tag name", Z_ERROR_INVALID_INPUT);
                                 }
                                 if ($v === "") {
                                     throw new Exception("Tag cannot be empty", Z_ERROR_INVALID_INPUT);
                                 }
                                 break;
                             case 'type':
                                 if (!is_numeric($v)) {
                                     throw new Exception("Invalid tag type '{$v}'", Z_ERROR_INVALID_INPUT);
                                 }
                                 break;
                             default:
                                 throw new Exception("Invalid tag property '{$k}'", Z_ERROR_INVALID_INPUT);
                         }
                         $empty = false;
                     }
                     if ($empty) {
                         throw new Exception("Tag object is empty", Z_ERROR_INVALID_INPUT);
                     }
                 }
                 break;
             case 'collections':
                 if (!is_array($val)) {
                     throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT);
                 }
                 if ($isChild && $val) {
                     throw new Exception("Child items cannot be assigned to collections", Z_ERROR_INVALID_INPUT);
                 }
                 foreach ($val as $k) {
                     if (!Zotero_ID::isValidKey($k)) {
                         throw new Exception("'{$k}' is not a valid collection key", Z_ERROR_INVALID_INPUT);
                     }
                 }
                 break;
             case 'relations':
                 if ($apiVersion < 2) {
                     throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 if (!is_object($val) && !(is_array($val) && empty($val))) {
                     throw new Exception("'{$key}' property must be an object", Z_ERROR_INVALID_INPUT);
                 }
                 foreach ($val as $predicate => $object) {
                     switch ($predicate) {
                         case 'owl:sameAs':
                         case 'dc:replaces':
                         case 'dc:relation':
                             break;
                         default:
                             throw new Exception("Unsupported predicate '{$predicate}'", Z_ERROR_INVALID_INPUT);
                     }
                     $arr = is_string($object) ? [$object] : $object;
                     foreach ($arr as $uri) {
                         if (!preg_match('/^http:\\/\\/zotero.org\\/(users|groups)\\/[0-9]+\\/(publications\\/)?items\\/[A-Z0-9]{8}$/', $uri)) {
                             throw new Exception("'{$key}' values currently must be Zotero item URIs", Z_ERROR_INVALID_INPUT);
                         }
                     }
                 }
                 break;
             case 'creators':
                 if (!is_array($val)) {
                     throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT);
                 }
                 foreach ($val as $creator) {
                     $empty = true;
                     if (!isset($creator->creatorType)) {
                         throw new Exception("creator object must contain 'creatorType'", Z_ERROR_INVALID_INPUT);
                     }
                     if ((!isset($creator->name) || trim($creator->name) == "") && (!isset($creator->firstName) || trim($creator->firstName) == "") && (!isset($creator->lastName) || trim($creator->lastName) == "")) {
                         // On item creation, ignore single nameless creator,
                         // because that's in the item template that the API returns
                         if (sizeOf($val) == 1 && $isNew) {
                             continue;
                         } else {
                             throw new Exception("creator object must contain 'firstName'/'lastName' or 'name'", Z_ERROR_INVALID_INPUT);
                         }
                     }
                     foreach ($creator as $k => $v) {
                         switch ($k) {
                             case 'creatorType':
                                 $creatorTypeID = Zotero_CreatorTypes::getID($v);
                                 if (!$creatorTypeID) {
                                     throw new Exception("'{$v}' is not a valid creator type", Z_ERROR_INVALID_INPUT);
                                 }
                                 $itemTypeID = Zotero_ItemTypes::getID($itemType);
                                 if (!Zotero_CreatorTypes::isValidForItemType($creatorTypeID, $itemTypeID)) {
                                     // Allow 'author' in all item types, but reject other invalid creator types
                                     if ($creatorTypeID != Zotero_CreatorTypes::getID('author')) {
                                         throw new Exception("'{$v}' is not a valid creator type for item type '{$itemType}'", Z_ERROR_INVALID_INPUT);
                                     }
                                 }
                                 break;
                             case 'firstName':
                                 if (!isset($creator->lastName)) {
                                     throw new Exception("'lastName' creator field must be set if 'firstName' is set", Z_ERROR_INVALID_INPUT);
                                 }
                                 if (isset($creator->name)) {
                                     throw new Exception("'firstName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT);
                                 }
                                 break;
                             case 'lastName':
                                 if (!isset($creator->firstName)) {
                                     throw new Exception("'firstName' creator field must be set if 'lastName' is set", Z_ERROR_INVALID_INPUT);
                                 }
                                 if (isset($creator->name)) {
                                     throw new Exception("'lastName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT);
                                 }
                                 break;
                             case 'name':
                                 if (isset($creator->firstName)) {
                                     throw new Exception("'firstName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT);
                                 }
                                 if (isset($creator->lastName)) {
                                     throw new Exception("'lastName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT);
                                 }
                                 break;
                             default:
                                 throw new Exception("Invalid creator property '{$k}'", Z_ERROR_INVALID_INPUT);
                         }
                         $empty = false;
                     }
                     if ($empty) {
                         throw new Exception("Creator object is empty", Z_ERROR_INVALID_INPUT);
                     }
                 }
                 break;
             case 'note':
                 switch ($itemType) {
                     case 'note':
                     case 'attachment':
                         break;
                     default:
                         throw new Exception("'note' property is valid only for note and attachment items", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'attachments':
             case 'notes':
                 if ($apiVersion > 1) {
                     throw new Exception("'{$key}' property is no longer supported", Z_ERROR_INVALID_INPUT);
                 }
                 if (!$isNew) {
                     throw new Exception("'{$key}' property is valid only for new items", Z_ERROR_INVALID_INPUT);
                 }
                 if (!is_array($val)) {
                     throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT);
                 }
                 foreach ($val as $child) {
                     // Check child item type ('attachment' or 'note')
                     $t = substr($key, 0, -1);
                     if (isset($child->itemType) && $child->itemType != $t) {
                         throw new Exception("Child {$t} must be of itemType '{$t}'", Z_ERROR_INVALID_INPUT);
                     }
                     if ($key == 'note') {
                         if (!isset($child->note)) {
                             throw new Exception("'note' property not provided for child note", Z_ERROR_INVALID_INPUT);
                         }
                     }
                 }
                 break;
             case 'deleted':
                 break;
                 // Attachment properties
             // Attachment properties
             case 'linkMode':
                 try {
                     $linkMode = Zotero_Attachments::linkModeNameToNumber($val, true);
                 } catch (Exception $e) {
                     throw new Exception("'{$val}' is not a valid linkMode", Z_ERROR_INVALID_INPUT);
                 }
                 // Don't allow changing of linkMode
                 if (!$isNew && $linkMode != $item->attachmentLinkMode) {
                     throw new Exception("Cannot change attachment linkMode", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'contentType':
             case 'charset':
             case 'filename':
             case 'md5':
             case 'mtime':
                 if ($itemType != 'attachment') {
                     throw new Exception("'{$key}' is valid only for attachment items", Z_ERROR_INVALID_INPUT);
                 }
                 switch ($key) {
                     case 'filename':
                     case 'md5':
                     case 'mtime':
                         $lm = isset($json->linkMode) ? $json->linkMode : Zotero_Attachments::linkModeNumberToName($item->attachmentLinkMode);
                         if (strpos(strtolower($lm), 'imported_') !== 0) {
                             throw new Exception("'{$key}' is valid only for imported attachment items", Z_ERROR_INVALID_INPUT);
                         }
                         break;
                 }
                 switch ($key) {
                     case 'contentType':
                     case 'charset':
                     case 'filename':
                         $propName = 'attachment' . ucwords($key);
                         break;
                     case 'md5':
                         $propName = 'attachmentStorageHash';
                         break;
                     case 'mtime':
                         $propName = 'attachmentStorageModTime';
                         break;
                 }
                 if (Zotero_Libraries::getType($libraryID) == 'group') {
                     if ($item && $item->{$propName} !== $val || !$item && $val !== null && $val !== "") {
                         throw new Exception("Cannot change '{$key}' directly in group library", Z_ERROR_INVALID_INPUT);
                     }
                 } else {
                     if ($key == 'md5') {
                         if ($val && !preg_match("/^[a-f0-9]{32}\$/", $val)) {
                             throw new Exception("'{$val}' is not a valid MD5 hash", Z_ERROR_INVALID_INPUT);
                         }
                     }
                 }
                 break;
             case 'accessDate':
                 if ($apiVersion >= 3 && $val !== '' && $val != 'CURRENT_TIMESTAMP' && !Zotero_Date::isSQLDate($val) && !Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) {
                     throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD[ hh-mm-dd]' format or 'CURRENT_TIMESTAMP' ({$val})", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             case 'dateAdded':
                 if (!Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) {
                     throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD hh-mm-dd' format", Z_ERROR_INVALID_INPUT);
                 }
                 if (!$isNew) {
                     // Convert ISO date to SQL date for equality comparison
                     if (Zotero_Date::isISO8601($val)) {
                         $val = Zotero_Date::iso8601ToSQL($val);
                     }
                     if ($val != $item->{$key}) {
                         throw new Exception("'{$key}' cannot be modified for existing items", Z_ERROR_INVALID_INPUT);
                     }
                 }
                 break;
             case 'dateModified':
                 if (!Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) {
                     throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD hh-mm-dd' format ({$val})", Z_ERROR_INVALID_INPUT);
                 }
                 break;
             default:
                 if (!Zotero_ItemFields::getID($key)) {
                     throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 if (is_array($val)) {
                     throw new Exception("Unexpected array for property '{$key}'", Z_ERROR_INVALID_INPUT);
                 }
                 break;
         }
     }
     // Publications libraries have additional restrictions
     if (Zotero_Libraries::getType($libraryID) == 'publications') {
         Zotero_Publications::validateJSONItem($json);
     }
 }
예제 #2
0
	/**
	 * @param 	string|int	$field				Field name or ID
	 * @param	mixed		$value				Field value
	 * @param	bool		$loadIn				Populate the data fields without marking as changed
	 */
	public function setField($field, $value, $loadIn=false) {
		if (is_string($value)) {
			$value = trim($value);
		}
		
		if (empty($field)) {
			throw new Exception("Field not specified");
		}
		
		if ($field == 'id' || $field == 'libraryID' || $field == 'key') {
			return $this->setIdentifier($field, $value);
		}
		
		if (($this->_id || $this->_key) && !$this->loaded['primaryData']) {
			$this->loadPrimaryData();
		}
		
		// Primary field
		if (Zotero_Items::isPrimaryField($field)) {
			if ($loadIn) {
				throw new Exception("Cannot set primary field $field in loadIn mode");
			}
			
			switch ($field) {
			case 'itemTypeID':
				break;
				
			case 'dateAdded':
			case 'dateModified':
				if (Zotero_Date::isISO8601($value)) {
					$value = Zotero_Date::iso8601ToSQL($value);
				}
				break;
			
			case 'version':
				$value = (int) $value;
				break;
			
			case 'synced':
				$value = !!$value;
			
			default:
				throw new Exception("Primary field $field cannot be changed");
			}
			
			if ($this->{"_$field"} === $value) {
				Z_Core::debug("Field '$field' has not changed", 4);
				return false;
			}
			
			Z_Core::debug("Field $field has changed from " . $this->{"_$field"} . " to $value", 4);
			
			if ($field == 'itemTypeID') {
				$this->setType($value, $loadIn);
			}
			else {
				$this->{"_$field"} = $value;
				$this->changed['primaryData'][$field] = true;
			}
			return true;
		}
		
		//
		// itemData field
		//
		
		if ($field == 'accessDate' && Zotero_Date::isISO8601($value)) {
			$value = Zotero_Date::iso8601ToSQL($value);
		}
		
		if (!$this->_itemTypeID) {
			trigger_error('Item type must be set before setting field data', E_USER_ERROR);
		}
		
		// If existing item, load field data first unless we're already in
		// the middle of a load
		if ($this->_id) {
			if (!$loadIn && !$this->loaded['itemData']) {
				$this->loadItemData();
			}
		}
		else {
			$this->loaded['itemData'] = true;
		}
		
		$fieldID = Zotero_ItemFields::getID($field);
		
		if (!$fieldID) {
			throw new Exception("'$field' is not a valid itemData field.", Z_ERROR_INVALID_INPUT);
		}
		
		if ($value === "") {
			$value = false;
		}
		
		if ($value !== false && !Zotero_ItemFields::isValidForType($fieldID, $this->_itemTypeID)) {
			throw new Exception("'$field' is not a valid field for type '"
				. Zotero_ItemTypes::getName($this->_itemTypeID) . "'", Z_ERROR_INVALID_INPUT);
		}
		
		if (!$loadIn) {
			// Save date field as multipart date
			if (Zotero_ItemFields::isFieldOfBase($fieldID, 'date') &&
					!Zotero_Date::isMultipart($value)) {
				$value = Zotero_Date::strToMultipart($value);
				if ($value === "") {
					$value = false;
				}
			}
			// Validate access date
			else if ($fieldID == Zotero_ItemFields::getID('accessDate')) {
				if ($value && (!Zotero_Date::isSQLDate($value) &&
						!Zotero_Date::isSQLDateTime($value) &&
						$value != 'CURRENT_TIMESTAMP')) {
					Z_Core::debug("Discarding invalid accessDate '" . $value . "'");
					return false;
				}
			}
			
			// If existing value, make sure it's actually changing
			if ((!isset($this->itemData[$fieldID]) && $value === false) ||
					(isset($this->itemData[$fieldID]) && $this->itemData[$fieldID] === $value)) {
				return false;
			}
			
			//Z_Core::debug("Field $field has changed from {$this->itemData[$fieldID]} to $value", 4);
			
			// TODO: Save a copy of the object before modifying?
		}
		
		$this->itemData[$fieldID] = $value;
		
		if (!$loadIn) {
			if (!isset($changed['itemData'])) {
				$changed['itemData'] = [];
			}
			$this->changed['itemData'][$fieldID] = true;
		}
		return true;
	}
예제 #3
0
 /**
  * @param 	string|int	$field				Field name or ID
  * @param	mixed		$value				Field value
  * @param	bool		$loadIn				Populate the data fields without marking as changed
  */
 public function setField($field, $value, $loadIn = false)
 {
     if (empty($field)) {
         throw new Exception("Field not specified");
     }
     // Set id, libraryID, and key without loading data first
     switch ($field) {
         case 'id':
         case 'libraryID':
         case 'key':
             // Allow libraryID to be set if empty, even if primary data is loaded,
             // which happens if an item type is set in the constructor
             if ($field == 'libraryID' && !$this->{$field}) {
             } else {
                 if ($this->loaded['primaryData']) {
                     throw new Exception("Cannot set {$field} after item is already loaded");
                 }
             }
             //this._checkValue(field, val);
             $this->{$field} = $value;
             return;
     }
     if ($this->id || $this->key) {
         if (!$this->loaded['primaryData']) {
             $this->loadPrimaryData(true);
         }
     } else {
         $this->loaded['primaryData'] = true;
     }
     if ($field == 'dateAdded' || $field == 'dateModified' || $field == 'accessDate') {
         if (Zotero_Date::isISO8601($value)) {
             $value = Zotero_Date::iso8601ToSQL($value);
         }
     }
     // Primary field
     if (isset(Zotero_Items::$primaryFields[$field])) {
         if ($loadIn) {
             throw new Exception("Cannot set primary field {$field} in loadIn mode");
         }
         switch ($field) {
             case 'id':
             case 'version':
                 trigger_error("Primary field '{$field}' cannot be changed through setField()", E_USER_ERROR);
         }
         if (!Zotero_ItemFields::validate($field, $value)) {
             trigger_error("Value '{$value}' of type " . gettype($value) . " does not validate for field '{$field}'", E_USER_ERROR);
         }
         if ($this->{$field} == $value) {
             return false;
         }
         Z_Core::debug("Field {$field} has changed from {$this->{$field}} to {$value}", 4);
         if ($field == 'itemTypeID') {
             $this->setType($value, $loadIn);
         } else {
             $this->{$field} = $value;
             $this->changed['primaryData'][$field] = true;
         }
         return true;
     }
     //
     // itemData field
     //
     if (!$this->itemTypeID) {
         trigger_error('Item type must be set before setting field data', E_USER_ERROR);
     }
     // If existing item, load field data first unless we're already in
     // the middle of a load
     if ($this->id) {
         if (!$loadIn && !$this->loaded['itemData']) {
             $this->loadItemData();
         }
     } else {
         $this->loaded['itemData'] = true;
     }
     $fieldID = Zotero_ItemFields::getID($field);
     if (!$fieldID) {
         throw new Exception("'{$field}' is not a valid itemData field.", Z_ERROR_INVALID_INPUT);
     }
     if ($value === "") {
         $value = false;
     }
     if ($value !== false && !Zotero_ItemFields::isValidForType($fieldID, $this->itemTypeID)) {
         throw new Exception("'{$field}' is not a valid field for type '" . Zotero_ItemTypes::getName($this->itemTypeID) . "'", Z_ERROR_INVALID_INPUT);
     }
     if (!$loadIn) {
         // Save date field as multipart date
         if (Zotero_ItemFields::isFieldOfBase($fieldID, 'date') && !Zotero_Date::isMultipart($value)) {
             $value = Zotero_Date::strToMultipart($value);
             if ($value === "") {
                 $value = false;
             }
         } else {
             if ($fieldID == Zotero_ItemFields::getID('accessDate')) {
                 if ($value && (!Zotero_Date::isSQLDate($value) && !Zotero_Date::isSQLDateTime($value) && $value != 'CURRENT_TIMESTAMP')) {
                     Z_Core::debug("Discarding invalid accessDate '" . $value . "'");
                     return false;
                 }
             }
         }
         // If existing value, make sure it's actually changing
         if (!isset($this->itemData[$fieldID]) && $value === false || isset($this->itemData[$fieldID]) && $this->itemData[$fieldID] === $value) {
             return false;
         }
         //Z_Core::debug("Field $field has changed from {$this->itemData[$fieldID]} to $value", 4);
         // TODO: Save a copy of the object before modifying?
     }
     $this->itemData[$fieldID] = $value;
     if (!$loadIn) {
         $this->changed['itemData'][$fieldID] = true;
     }
     return true;
 }
예제 #4
0
 public function toSolrDocument()
 {
     $doc = new SolrInputDocument();
     $uri = Zotero_Solr::getItemURI($this->libraryID, $this->key);
     $doc->addField("uri", $uri);
     // Primary fields
     foreach (Zotero_Items::$primaryFields as $field) {
         switch ($field) {
             case 'itemID':
             case 'numAttachments':
             case 'numNotes':
                 continue 2;
             case 'itemTypeID':
                 $xmlField = 'itemType';
                 $xmlValue = Zotero_ItemTypes::getName($this->{$field});
                 break;
             case 'dateAdded':
             case 'dateModified':
             case 'serverDateModified':
                 $xmlField = $field;
                 $xmlValue = Zotero_Date::sqlToISO8601($this->{$field});
                 break;
             default:
                 $xmlField = $field;
                 $xmlValue = $this->{$field};
         }
         $doc->addField($xmlField, $xmlValue);
     }
     // Title for sorting
     $title = $this->getDisplayTitle(true);
     $title = $title ? $title : '';
     // Strip HTML from note titles
     if ($this->isNote()) {
         // Clean and strip HTML, giving us an HTML-encoded plaintext string
         $title = strip_tags($GLOBALS['HTMLPurifier']->purify($title));
         // Unencode plaintext string
         $title = html_entity_decode($title);
     }
     // Strip some characters
     $sortTitle = preg_replace("/^[\\[\\'\"]*(.*)[\\]\\'\"]*\$/", "\$1", $title);
     if ($sortTitle) {
         $doc->addField('titleSort', $sortTitle);
     }
     // Item data
     $fieldIDs = $this->getUsedFields();
     foreach ($fieldIDs as $fieldID) {
         $val = $this->getField($fieldID);
         if ($val == '') {
             continue;
         }
         $fieldName = Zotero_ItemFields::getName($fieldID);
         switch ($fieldName) {
             // As is
             case 'title':
                 $val = $title;
                 break;
                 // Date fields
             // Date fields
             case 'date':
                 // Add user part as text
                 $doc->addField($fieldName . "_t", Zotero_Date::multipartToStr($val));
                 // Add as proper date, if there is one
                 $sqlDate = Zotero_Date::multipartToSQL($val);
                 if (!$sqlDate || $sqlDate == '0000-00-00') {
                     continue 2;
                 }
                 $fieldName .= "_tdt";
                 $val = Zotero_Date::sqlToISO8601($sqlDate);
                 break;
             case 'accessDate':
                 if (!Zotero_Date::isSQLDateTime($val)) {
                     continue 2;
                 }
                 $fieldName .= "_tdt";
                 $val = Zotero_Date::sqlToISO8601($val);
                 break;
             default:
                 $fieldName .= "_t";
         }
         $doc->addField($fieldName, $val);
     }
     // Deleted item flag
     if ($this->getDeleted()) {
         $doc->addField('deleted', true);
     }
     if ($this->isNote() || $this->isAttachment()) {
         $sourceItemID = $this->getSource();
         if ($sourceItemID) {
             $sourceItem = Zotero_Items::get($this->libraryID, $sourceItemID);
             if (!$sourceItem) {
                 throw new Exception("Source item {$sourceItemID} not found");
             }
             $doc->addField('sourceItem', $sourceItem->key);
         }
     }
     // Group modification info
     $createdByUserID = null;
     $lastModifiedByUserID = null;
     switch (Zotero_Libraries::getType($this->libraryID)) {
         case 'group':
             $createdByUserID = $this->createdByUserID;
             $lastModifiedByUserID = $this->lastModifiedByUserID;
             break;
     }
     if ($createdByUserID) {
         $doc->addField('createdByUserID', $createdByUserID);
     }
     if ($lastModifiedByUserID) {
         $doc->addField('lastModifiedByUserID', $lastModifiedByUserID);
     }
     // Note
     if ($this->isNote()) {
         $doc->addField('note', $this->getNote());
     }
     if ($this->isAttachment()) {
         $doc->addField('linkMode', $this->attachmentLinkMode);
         $doc->addField('mimeType', $this->attachmentMIMEType);
         if ($this->attachmentCharset) {
             $doc->addField('charset', $this->attachmentCharset);
         }
         // TODO: get from a constant
         if ($this->attachmentLinkMode != 3) {
             $doc->addField('path', $this->attachmentPath);
         }
         $note = $this->getNote();
         if ($note) {
             $doc->addField('note', $note);
         }
     }
     // Creators
     $creators = $this->getCreators();
     if ($creators) {
         foreach ($creators as $index => $creator) {
             $c = $creator['ref'];
             $doc->addField('creatorKey', $c->key);
             if ($c->fieldMode == 0) {
                 $doc->addField('creatorFirstName', $c->firstName);
             }
             $doc->addField('creatorLastName', $c->lastName);
             $doc->addField('creatorType', Zotero_CreatorTypes::getName($creator['creatorTypeID']));
             $doc->addField('creatorIndex', $index);
         }
     }
     // Tags
     $tags = $this->getTags();
     if ($tags) {
         foreach ($tags as $tag) {
             $doc->addField('tagKey', $tag->key);
             $doc->addField('tag', $tag->name);
             $doc->addField('tagType', $tag->type);
         }
     }
     // Related items
     /*$related = $this->relatedItems;
     		if ($related) {
     			$related = Zotero_Items::get($this->libraryID, $related);
     			$keys = array();
     			foreach ($related as $item) {
     				$doc->addField('relatedItem', $item->key);
     			}
     		}*/
     return $doc;
 }
예제 #5
0
 public static function retrieveItem($zoteroItem)
 {
     if (!$zoteroItem) {
         throw new Exception("Zotero item not provided");
     }
     // don't return URL or accessed information for journal articles if a
     // pages field exists
     $itemType = Zotero_ItemTypes::getName($zoteroItem->itemTypeID);
     $cslType = isset(self::$zoteroTypeMap[$itemType]) ? self::$zoteroTypeMap[$itemType] : false;
     if (!$cslType) {
         $cslType = "article";
     }
     $ignoreURL = ($zoteroItem->getField("accessDate", true, true, true) || $zoteroItem->getField("url", true, true, true)) && in_array($itemType, array("journalArticle", "newspaperArticle", "magazineArticle")) && $zoteroItem->getField("pages", false, false, true) && self::$citePaperJournalArticleURL;
     $cslItem = array('id' => $zoteroItem->libraryID . "/" . $zoteroItem->key, 'type' => $cslType);
     // get all text variables (there must be a better way)
     // TODO: does citeproc-js permit short forms?
     foreach (self::$zoteroFieldMap as $variable => $fields) {
         if ($variable == "URL" && $ignoreURL) {
             continue;
         }
         foreach ($fields as $field) {
             $value = $zoteroItem->getField($field, false, true, true);
             if ($value !== "") {
                 // Strip enclosing quotes
                 if (preg_match(self::$quotedRegexp, $value)) {
                     $value = substr($value, 1, strlen($value) - 2);
                 }
                 $cslItem[$variable] = $value;
                 break;
             }
         }
     }
     // separate name variables
     $authorID = Zotero_CreatorTypes::getPrimaryIDForType($zoteroItem->itemTypeID);
     $creators = $zoteroItem->getCreators();
     foreach ($creators as $creator) {
         if ($creator['creatorTypeID'] == $authorID) {
             $creatorType = "author";
         } else {
             $creatorType = Zotero_CreatorTypes::getName($creator['creatorTypeID']);
         }
         $creatorType = isset(self::$zoteroNameMap[$creatorType]) ? self::$zoteroNameMap[$creatorType] : false;
         if (!$creatorType) {
             continue;
         }
         $nameObj = array('family' => $creator['ref']->lastName, 'given' => $creator['ref']->firstName);
         if (isset($cslItem[$creatorType])) {
             $cslItem[$creatorType][] = $nameObj;
         } else {
             $cslItem[$creatorType] = array($nameObj);
         }
     }
     // get date variables
     foreach (self::$zoteroDateMap as $key => $val) {
         $date = $zoteroItem->getField($val, false, true, true);
         if ($date) {
             if (Zotero_Date::isSQLDateTime($date)) {
                 $date = substr($date, 0, 10);
             }
             $cslItem[$key] = array("raw" => $date);
             continue;
             $date = Zotero_Date::strToDate($date);
             if (!empty($date['part']) && !$date['month']) {
                 // if there's a part but no month, interpret literally
                 $cslItem[$variable] = array("literal" => $date['part']);
             } else {
                 // otherwise, use date-parts
                 $dateParts = array();
                 if ($date['year']) {
                     $dateParts[] = $date['year'];
                     if ($date['month']) {
                         $dateParts[] = $date['month'] + 1;
                         // Mimics JS
                         if ($date['day']) {
                             $dateParts[] = $date['day'];
                         }
                     }
                 }
                 $cslItem[$key] = array("date-parts" => array($dateParts));
             }
         }
     }
     return $cslItem;
 }