Example #1
0
	/**
	 * @param {Integer} $itemTypeID  itemTypeID to change to
	 * @param {Boolean} [$loadIn=false]  Internal call, so don't flag field as changed
	 */
	private function setType($itemTypeID, $loadIn=false) {
		if ($itemTypeID == $this->_itemTypeID) {
			return true;
		}
		
		// TODO: block switching to/from note or attachment
		
		if (!Zotero_ItemTypes::getID($itemTypeID)) {
			throw new Exception("Invalid itemTypeID", Z_ERROR_INVALID_INPUT);
		}
		
		$copiedFields = array();
		
		$oldItemTypeID = $this->_itemTypeID;
		
		if ($oldItemTypeID) {
			if ($loadIn) {
				throw new Exception('Cannot change type in loadIn mode');
			}
			if (!$this->loaded['itemData'] && $this->id) {
				$this->loadItemData();
			}
			
			$obsoleteFields = $this->getFieldsNotInType($itemTypeID);
			if ($obsoleteFields) {
				foreach($obsoleteFields as $oldFieldID) {
					// Try to get a base type for this field
					$baseFieldID =
						Zotero_ItemFields::getBaseIDFromTypeAndField($this->_itemTypeID, $oldFieldID);
					
					if ($baseFieldID) {
						$newFieldID =
							Zotero_ItemFields::getFieldIDFromTypeAndBase($itemTypeID, $baseFieldID);
						
						// If so, save value to copy to new field
						if ($newFieldID) {
							$copiedFields[] = array($newFieldID, $this->getField($oldFieldID));
						}
					}
					
					// Clear old field
					$this->setField($oldFieldID, false);
				}
			}
			
			foreach ($this->itemData as $fieldID => $value) {
				if (!is_null($this->itemData[$fieldID]) &&
						(!$obsoleteFields || !in_array($fieldID, $obsoleteFields))) {
					$copiedFields[] = array($fieldID, $this->getField($fieldID));
				}
			}
		}
		
		$this->_itemTypeID = $itemTypeID;
		
		if ($oldItemTypeID) {
			// Reset custom creator types to the default
			$creators = $this->getCreators();
			if ($creators) {
				foreach ($creators as $orderIndex=>$creator) {
					if (Zotero_CreatorTypes::isCustomType($creator['creatorTypeID'])) {
						continue;
					}
					if (!Zotero_CreatorTypes::isValidForItemType($creator['creatorTypeID'], $itemTypeID)) {
						// TODO: port
						
						// Reset to contributor (creatorTypeID 2), which exists in all
						$this->setCreator($orderIndex, $creator['ref'], 2);
					}
				}
			}
			
		}
		
		// If not custom item type, initialize $this->itemData with type-specific fields
		$this->itemData = array();
		if (!Zotero_ItemTypes::isCustomType($itemTypeID)) {
			$fields = Zotero_ItemFields::getItemTypeFields($itemTypeID);
			foreach($fields as $fieldID) {
				$this->itemData[$fieldID] = null;
			}
		}
		
		if ($copiedFields) {
			foreach($copiedFields as $copiedField) {
				$this->setField($copiedField[0], $copiedField[1]);
			}
		}
		
		if ($loadIn) {
			$this->loaded['itemData'] = false;
		}
		else {
			$this->changed['primaryData']['itemTypeID'] = true;
		}
		
		return true;
	}