public function test_strToDate_yearRange() { $pattern = "1983-84"; $parts = Zotero_Date::strToDate($pattern); $this->assertEquals(1983, $parts['year']); $this->assertFalse(isset($parts['month'])); $this->assertFalse(isset($parts['day'])); $this->assertEquals("84", $parts['part']); $pattern = "1983-1984"; $parts = Zotero_Date::strToDate($pattern); $this->assertEquals(1983, $parts['year']); $this->assertFalse(isset($parts['month'])); $this->assertFalse(isset($parts['day'])); $this->assertEquals("1984", $parts['part']); }
public function toJSON($asArray=false, $requestParams=array(), $includeEmpty=false, $unformattedFields=false) { if ($this->id || $this->key) { if (!$this->loaded['primaryData']) { $this->loadPrimaryData(); } if (!$this->loaded['itemData']) { $this->loadItemData(); } } if (!isset($requestParams['v'])) { $requestParams['v'] = 3; } $regularItem = $this->isRegularItem(); $arr = array(); if ($requestParams['v'] >= 2) { if ($requestParams['v'] >= 3) { $arr['key'] = $this->key; $arr['version'] = $this->version; } else { $arr['itemKey'] = $this->key; $arr['itemVersion'] = $this->version; } $key = $this->getSourceKey(); if ($key) { $arr['parentItem'] = $key; } } $arr['itemType'] = Zotero_ItemTypes::getName($this->itemTypeID); if ($this->isAttachment()) { $val = $this->attachmentLinkMode; $arr['linkMode'] = strtolower(Zotero_Attachments::linkModeNumberToName($val)); } // For regular items, show title and creators first if ($regularItem) { // Get 'title' or the equivalent base-mapped field $titleFieldID = Zotero_ItemFields::getFieldIDFromTypeAndBase($this->itemTypeID, 'title'); $titleFieldName = Zotero_ItemFields::getName($titleFieldID); if ($includeEmpty || $this->itemData[$titleFieldID] !== false) { $arr[$titleFieldName] = $this->itemData[$titleFieldID] !== false ? $this->itemData[$titleFieldID] : ""; } // Creators $arr['creators'] = array(); $creators = $this->getCreators(); foreach ($creators as $creator) { $c = array(); $c['creatorType'] = Zotero_CreatorTypes::getName($creator['creatorTypeID']); // Single-field mode if ($creator['ref']->fieldMode == 1) { $c['name'] = $creator['ref']->lastName; } // Two-field mode else { $c['firstName'] = $creator['ref']->firstName; $c['lastName'] = $creator['ref']->lastName; } $arr['creators'][] = $c; } if (!$arr['creators'] && !$includeEmpty) { unset($arr['creators']); } } else { $titleFieldID = false; } // Item metadata $fields = array_keys($this->itemData); foreach ($fields as $field) { if ($field == $titleFieldID) { continue; } if ($unformattedFields) { $value = $this->itemData[$field]; } else { $value = $this->getField($field); } if (!$includeEmpty && ($value === false || $value === "")) { continue; } $fieldName = Zotero_ItemFields::getName($field); // TEMP if ($fieldName == 'versionNumber') { if ($requestParams['v'] < 3) { $fieldName = 'version'; } } else if ($fieldName == 'accessDate') { if ($requestParams['v'] >= 3 && $value !== false && $value !== "") { $value = Zotero_Date::sqlToISO8601($value); } } $arr[$fieldName] = ($value !== false && $value !== "") ? $value : ""; } if ($requestParams['v'] >= 3) { $arr['dateAdded'] = Zotero_Date::sqlToISO8601($this->dateAdded); $arr['dateModified'] = Zotero_Date::sqlToISO8601($this->dateModified); } // Embedded note for notes and attachments if (!$regularItem) { // Use sanitized version $arr['note'] = $this->getNote(true); } if ($this->isAttachment()) { $val = $this->attachmentLinkMode; $arr['linkMode'] = strtolower(Zotero_Attachments::linkModeNumberToName($val)); $val = $this->attachmentMIMEType; if ($includeEmpty || ($val !== false && $val !== "")) { $arr['contentType'] = $val; } $val = $this->attachmentCharset; if ($includeEmpty || ($val !== false && $val !== "")) { $arr['charset'] = $val; } if ($this->isImportedAttachment()) { $arr['filename'] = $this->attachmentFilename; $val = $this->attachmentStorageHash; if ($includeEmpty || $val) { $arr['md5'] = $val; } $val = $this->attachmentStorageModTime; if ($includeEmpty || $val) { $arr['mtime'] = $val; } } } if ($this->getDeleted()) { $arr['deleted'] = 1; } // Tags $arr['tags'] = array(); $tags = $this->getTags(); if ($tags) { foreach ($tags as $tag) { $t = array( 'tag' => $tag->name ); if ($tag->type != 0) { $t['type'] = $tag->type; } $arr['tags'][] = $t; } } if ($requestParams['v'] >= 2) { if ($this->isTopLevelItem()) { $collections = $this->getCollections(true); $arr['collections'] = $collections; } $arr['relations'] = $this->getRelations(); } if ($asArray) { return $arr; } // Before v3, additional characters were escaped in the JSON, for unclear reasons $escapeAll = $requestParams['v'] <= 2; return Zotero_Utilities::formatJSON($arr, $escapeAll); }
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; }
/** * Converts a Zotero_Tag object to a SimpleXMLElement Atom object * * @param object $tag Zotero_Tag object * @param string $content * @return SimpleXMLElement Tag data as SimpleXML element */ public function toAtom($content = array('none'), $apiVersion = null, $fixedValues = null) { // TEMP: multi-format support $content = $content[0]; $xml = new SimpleXMLElement('<entry xmlns="' . Zotero_Atom::$nsAtom . '" ' . 'xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '" ' . 'xmlns:zxfer="' . Zotero_Atom::$nsZoteroTransfer . '"/>'); $xml->title = $this->name; $author = $xml->addChild('author'); $author->name = Zotero_Libraries::getName($this->libraryID); $author->uri = Zotero_URI::getLibraryURI($this->libraryID); $xml->id = Zotero_URI::getTagURI($this); $xml->published = Zotero_Date::sqlToISO8601($this->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($this->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_Atom::getTagURI($this); $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getTagURI($this); // Count user's linked items if (isset($fixedValues['numItems'])) { $numItems = $fixedValues['numItems']; } else { $itemIDs = $this->getLinkedItems(); $numItems = sizeOf($itemIDs); } $xml->addChild('zapi:numItems', $numItems, Zotero_Atom::$nsZoteroAPI); if ($content == 'html') { $xml->content['type'] = 'xhtml'; //$fullXML = Zotero_Tags::convertTagToXML($tag); $fullStr = "<div/>"; $fullXML = new SimpleXMLElement($fullStr); $fullXML->addAttribute("xmlns", Zotero_Atom::$nsXHTML); $fNode = dom_import_simplexml($xml->content); $subNode = dom_import_simplexml($fullXML); $importedNode = $fNode->ownerDocument->importNode($subNode, true); $fNode->appendChild($importedNode); //$arr = $tag->serialize(); //require_once("views/zotero/tags.php") } else { if ($content == 'full') { $xml->content['type'] = 'application/xml'; $fullXML = $this->toXML(); $fullXML->addAttribute("xmlns", Zotero_Atom::$nsZoteroTransfer); $fNode = dom_import_simplexml($xml->content); $subNode = dom_import_simplexml($fullXML); $importedNode = $fNode->ownerDocument->importNode($subNode, true); $fNode->appendChild($importedNode); } } return $xml; }
/** * Generate a SimpleXMLElement Atom object for the search * * @param array $queryParams * @return SimpleXMLElement */ public function toAtom($queryParams) { if (!$this->loaded) { $this->load(); } // TEMP: multi-format support if (!empty($queryParams['content'])) { $content = $queryParams['content']; } else { $content = array('none'); } $content = $content[0]; $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'); $xml->title = $this->name ? $this->name : '[Untitled]'; $author = $xml->addChild('author'); // TODO: group item creator $author->name = Zotero_Libraries::getName($this->libraryID); $author->uri = Zotero_URI::getLibraryURI($this->libraryID, true); $xml->id = Zotero_URI::getSearchURI($this); $xml->published = Zotero_Date::sqlToISO8601($this->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($this->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_API::getSearchURI($this); $xml->addChild('zapi:key', $this->key, Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:version', $this->version, Zotero_Atom::$nsZoteroAPI); if ($content == 'json') { $xml->content['type'] = 'application/json'; $xml->content = Zotero_Utilities::formatJSON($this->toJSON($queryParams)); } return $xml; }
public function itemToAtom($itemID) { if (!is_int($itemID)) { throw new Exception("itemID must be an integer (was " . gettype($itemID) . ")"); } if (!$this->loaded) { $this->load(); } //$groupUserData = $this->getUserData($itemID); $item = Zotero_Items::get($this->libraryID, $itemID); if (!$item) { throw new Exception("Item {$itemID} doesn't exist"); } $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" ' . 'xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '" ' . 'xmlns:xfer="' . Zotero_Atom::$nsZoteroTransfer . '"/>'); $title = $item->getDisplayTitle(true); $title = $title ? $title : '[Untitled]'; // Strip HTML from note titles if ($item->isNote()) { // Clean and strip HTML, giving us an HTML-encoded plaintext string $title = strip_tags(Zotero_Notes::sanitize($title)); // Unencode plaintext string $title = html_entity_decode($title); } $xml->title = $title; $author = $xml->addChild('author'); $author->name = Zotero_Libraries::getName($item->libraryID); $author->uri = Zotero_URI::getLibraryURI($item->libraryID); $xml->id = Zotero_URI::getItemURI($item); $xml->published = Zotero_Date::sqlToISO8601($item->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($item->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_API::getItemURI($item); $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getItemURI($item, true); $xml->content['type'] = 'application/xml'; $itemXML = new SimpleXMLElement('<item xmlns="' . Zotero_Atom::$nsZoteroTransfer . '"/>'); // This method of adding the element seems to be necessary to get the // namespace prefix to show up $fNode = dom_import_simplexml($xml->content); $subNode = dom_import_simplexml($itemXML); $importedNode = $fNode->ownerDocument->importNode($subNode, true); $fNode->appendChild($importedNode); $xml->content->item['id'] = $itemID; return $xml; }
/** * Converts a Zotero_Item object to a SimpleXMLElement Atom object * * @param object $item Zotero_Item object * @param string $content * @return SimpleXMLElement Item data as SimpleXML element */ public static function convertItemToAtom(Zotero_Item $item, $queryParams, $apiVersion = null, $permissions = null, $sharedData = null) { $content = $queryParams['content']; $contentIsHTML = sizeOf($content) == 1 && $content[0] == 'html'; $contentParamString = urlencode(implode(',', $content)); $style = $queryParams['style']; $entry = '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'; $xml = new SimpleXMLElement($entry); $title = $item->getDisplayTitle(true); $title = $title ? $title : '[Untitled]'; $xml->title = $title; $author = $xml->addChild('author'); $createdByUserID = null; switch (Zotero_Libraries::getType($item->libraryID)) { case 'group': $createdByUserID = $item->createdByUserID; break; } if ($createdByUserID) { $author->name = Zotero_Users::getUsername($createdByUserID); $author->uri = Zotero_URI::getUserURI($createdByUserID); } else { $author->name = Zotero_Libraries::getName($item->libraryID); $author->uri = Zotero_URI::getLibraryURI($item->libraryID); } $id = Zotero_URI::getItemURI($item); /*if (!$contentIsHTML) { $id .= "?content=$content"; }*/ $xml->id = $id; $xml->published = Zotero_Date::sqlToISO8601($item->getField('dateAdded')); $xml->updated = Zotero_Date::sqlToISO8601($item->getField('dateModified')); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $href = Zotero_Atom::getItemURI($item); if (!$contentIsHTML) { $href .= "?content={$contentParamString}"; } $link['href'] = $href; $parent = $item->getSource(); if ($parent) { // TODO: handle group items? $parentItem = Zotero_Items::get($item->libraryID, $parent); $link = $xml->addChild("link"); $link['rel'] = "up"; $link['type'] = "application/atom+xml"; $href = Zotero_Atom::getItemURI($parentItem); if (!$contentIsHTML) { $href .= "?content={$contentParamString}"; } $link['href'] = $href; } $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getItemURI($item); // If appropriate permissions and the file is stored in ZFS, get file request link if ($permissions && $permissions->canAccess($item->libraryID, 'files')) { $details = Zotero_S3::getDownloadDetails($item); if ($details) { $link = $xml->addChild('link'); $link['rel'] = 'enclosure'; $type = $item->attachmentMIMEType; if ($type) { $link['type'] = $type; } $link['href'] = $details['url']; if (!empty($details['filename'])) { $link['title'] = $details['filename']; } if (!empty($details['size'])) { $link['length'] = $details['size']; } } } $xml->addChild('zapi:key', $item->key, Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:itemType', Zotero_ItemTypes::getName($item->itemTypeID), Zotero_Atom::$nsZoteroAPI); if ($item->isRegularItem()) { $val = $item->creatorSummary; if ($val !== '') { $xml->addChild('zapi:creatorSummary', htmlspecialchars($val), Zotero_Atom::$nsZoteroAPI); } $val = substr($item->getField('date', true, true, true), 0, 4); if ($val !== '' && $val !== '0000') { $xml->addChild('zapi:year', $val, Zotero_Atom::$nsZoteroAPI); } } if (!$parent && $item->isRegularItem()) { if ($permissions && !$permissions->canAccess($item->libraryID, 'notes')) { $numChildren = $item->numAttachments(); } else { $numChildren = $item->numChildren(); } $xml->addChild('zapi:numChildren', $numChildren, Zotero_Atom::$nsZoteroAPI); } $xml->addChild('zapi:numTags', $item->numTags(), Zotero_Atom::$nsZoteroAPI); $xml->content = ''; // // DOM XML from here on out // $contentNode = dom_import_simplexml($xml->content); $domDoc = $contentNode->ownerDocument; $multiFormat = sizeOf($content) > 1; // Create a root XML document for multi-format responses if ($multiFormat) { $contentNode->setAttribute('type', 'application/xml'); /*$multicontent = $domDoc->createElementNS( Zotero_Atom::$nsZoteroAPI, 'multicontent' ); $contentNode->appendChild($multicontent);*/ } foreach ($content as $type) { // Set the target to either the main <content> // or a <multicontent> <content> if (!$multiFormat) { $target = $contentNode; } else { $target = $domDoc->createElementNS(Zotero_Atom::$nsZoteroAPI, 'subcontent'); $contentNode->appendChild($target); } $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:type", $type); if ($type == 'html') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } $div = $domDoc->createElement('div'); $div->setAttribute('xmlns', Zotero_Atom::$nsXHTML); $target->appendChild($div); $html = $item->toHTML(true); $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $div->appendChild($importedNode); } else { if ($type == 'citation') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) { $html = $sharedData[$type][$item->libraryID . "/" . $item->key]; } else { if ($sharedData !== null) { error_log("Citation not found in sharedData -- retrieving individually"); } $html = Zotero_Cite::getCitationFromCiteServer($item, $style); } $html = new SimpleXMLElement($html); $html['xmlns'] = Zotero_Atom::$nsXHTML; $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $target->appendChild($importedNode); } else { if ($type == 'bib') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) { $html = $sharedData[$type][$item->libraryID . "/" . $item->key]; } else { if ($sharedData !== null) { error_log("Bibliography not found in sharedData -- retrieving individually"); } $html = Zotero_Cite::getBibliographyFromCitationServer(array($item), $style); } $html = new SimpleXMLElement($html); $html['xmlns'] = Zotero_Atom::$nsXHTML; $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $target->appendChild($importedNode); } else { if ($type == 'json') { $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:etag", $item->etag); $textNode = $domDoc->createTextNode($item->toJSON(false, $queryParams['pprint'], true)); $target->appendChild($textNode); } else { if ($type == 'csljson') { $arr = $item->toCSLItem(); $mask = JSON_HEX_TAG | JSON_HEX_AMP; if ($queryParams['pprint']) { $json = Zotero_Utilities::json_encode_pretty($arr, $mask); } else { $json = json_encode($arr, $mask); } // Until JSON_UNESCAPED_SLASHES is available $json = str_replace('\\/', '/', $json); $textNode = $domDoc->createTextNode($json); $target->appendChild($textNode); } else { if ($type == 'full') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } $fullXML = Zotero_Items::convertItemToXML($item, array(), $apiVersion); $fullXML->addAttribute("xmlns", Zotero_Atom::$nsZoteroTransfer); $subNode = dom_import_simplexml($fullXML); $importedNode = $domDoc->importNode($subNode, true); $target->appendChild($importedNode); } else { if (in_array($type, Zotero_Translate::$exportFormats)) { $export = Zotero_Translate::doExport(array($item), $type); $target->setAttribute('type', $export['mimeType']); // Insert XML into document if (preg_match('/\\+xml$/', $export['mimeType'])) { // Strip prolog $body = preg_replace('/^<\\?xml.+\\n/', "", $export['body']); $subNode = $domDoc->createDocumentFragment(); $subNode->appendXML($body); $target->appendChild($subNode); } else { $textNode = $domDoc->createTextNode($export['body']); $target->appendChild($textNode); } } } } } } } } } return $xml; }
public static function createAtomFeed($title, $url, $entries, $totalResults = null, $queryParams = null, $apiVersion = null, $permissions = null, $fixedValues = array()) { if ($queryParams) { $nonDefaultParams = Zotero_API::getNonDefaultQueryParams($queryParams); // Convert 'content' array to sorted comma-separated string if (isset($nonDefaultParams['content'])) { $nonDefaultParams['content'] = implode(',', $nonDefaultParams['content']); } } else { $nonDefaultParams = array(); } $feed = '<feed xmlns="' . Zotero_Atom::$nsAtom . '" ' . 'xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"'; if ($queryParams && $queryParams['content'][0] == 'full') { $feed .= ' xmlns:zxfer="' . Zotero_Atom::$nsZoteroTransfer . '"'; } $feed .= '/>'; $xml = new SimpleXMLElement($feed); $xml->title = $title; $path = parse_url($url, PHP_URL_PATH); // Generate canonical URI $zoteroURI = Zotero_URI::getBaseURI() . substr($path, 1); if ($nonDefaultParams) { $zoteroURI .= "?" . http_build_query($nonDefaultParams); } $atomURI = Zotero_Atom::getBaseURI() . substr($path, 1); // // Generate URIs for 'self', 'first', 'next' and 'last' links // // 'self' $atomSelfURI = $atomURI; if ($nonDefaultParams) { $atomSelfURI .= "?" . http_build_query($nonDefaultParams); } // 'first' $atomFirstURI = $atomURI; if ($nonDefaultParams) { $p = $nonDefaultParams; unset($p['start']); if ($first = http_build_query($p)) { $atomFirstURI .= "?" . $first; } } // 'last' if (!$queryParams['start'] && $queryParams['limit'] >= $totalResults) { $atomLastURI = $atomSelfURI; } else { // 'start' past results if ($queryParams['start'] >= $totalResults) { $lastStart = $totalResults - $queryParams['limit']; } else { $lastStart = $totalResults - $totalResults % $queryParams['limit']; if ($lastStart == $totalResults) { $lastStart = $totalResults - $queryParams['limit']; } } $p = $nonDefaultParams; if ($lastStart > 0) { $p['start'] = $lastStart; } else { unset($p['start']); } $atomLastURI = $atomURI; if ($last = http_build_query($p)) { $atomLastURI .= "?" . $last; } // 'next' $nextStart = $queryParams['start'] + $queryParams['limit']; if ($nextStart < $totalResults) { $p = $nonDefaultParams; $p['start'] = $nextStart; $atomNextURI = $atomURI . "?" . http_build_query($p); } } $xml->id = $zoteroURI; $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = $atomSelfURI; $link = $xml->addChild("link"); $link['rel'] = "first"; $link['type'] = "application/atom+xml"; $link['href'] = $atomFirstURI; if (isset($atomNextURI)) { $link = $xml->addChild("link"); $link['rel'] = "next"; $link['type'] = "application/atom+xml"; $link['href'] = $atomNextURI; } $link = $xml->addChild("link"); $link['rel'] = "last"; $link['type'] = "application/atom+xml"; $link['href'] = $atomLastURI; // Generate alternate URI $alternateURI = Zotero_URI::getBaseURI() . substr($path, 1); if ($nonDefaultParams) { $p = $nonDefaultParams; if (isset($p['content'])) { unset($p['content']); } if ($p) { $alternateURI .= "?" . http_build_query($p); } } $link = $xml->addChild("link"); $link['rel'] = "alternate"; $link['type'] = "text/html"; $link['href'] = $alternateURI; $xml->addChild("zapi:totalResults", is_numeric($totalResults) ? $totalResults : sizeOf($entries), self::$nsZoteroAPI); $xml->addChild("zapi:apiVersion", $apiVersion, self::$nsZoteroAPI); $latestUpdated = ''; // Get bib data using parallel requests $sharedData = array(); if ($entries && $entries[0] instanceof Zotero_Item) { if (in_array('citation', $queryParams['content'])) { $sharedData["citation"] = Zotero_Cite::multiGetFromCiteServer("citation", $entries, $queryParams['style']); } if (in_array('bib', $queryParams['content'])) { $sharedData["bib"] = Zotero_Cite::multiGetFromCiteServer("bib", $entries, $queryParams['style']); } } $xmlEntries = array(); foreach ($entries as $entry) { if ($entry->dateModified > $latestUpdated) { $latestUpdated = $entry->dateModified; } if ($entry instanceof SimpleXMLElement) { $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Collection) { $entry = Zotero_Collections::convertCollectionToAtom($entry, $queryParams['content'], $apiVersion); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Creator) { $entry = Zotero_Creators::convertCreatorToAtom($entry, $queryParams['content'], $apiVersion); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Item) { $entry = Zotero_Items::convertItemToAtom($entry, $queryParams, $apiVersion, $permissions, $sharedData); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Search) { $entry = Zotero_Searches::convertSearchToAtom($entry, $queryParams['content'], $apiVersion); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Tag) { $xmlEntries[] = $entry->toAtom($queryParams['content'], $apiVersion, isset($fixedValues[$entry->id]) ? $fixedValues[$entry->id] : null); } else { if ($entry instanceof Zotero_Group) { $entry = $entry->toAtom($queryParams['content'], $apiVersion); $xmlEntries[] = $entry; } } } } } } } } if ($latestUpdated) { $xml->updated = Zotero_Date::sqlToISO8601($latestUpdated); } else { $xml->updated = str_replace("+00:00", "Z", date('c')); } // Import object XML nodes into document $doc = dom_import_simplexml($xml); foreach ($xmlEntries as $xmlEntry) { $subNode = dom_import_simplexml($xmlEntry); $importedNode = $doc->ownerDocument->importNode($subNode, true); $doc->appendChild($importedNode); } return $xml; }
/** * Converts a Zotero_Tag object to a SimpleXMLElement Atom object * * @return SimpleXMLElement Tag data as SimpleXML element */ public function toAtom($queryParams, $fixedValues = null) { if (!empty($queryParams['content'])) { $content = $queryParams['content']; } else { $content = array('none'); } // TEMP: multi-format support $content = $content[0]; $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'); $xml->title = $this->name; $author = $xml->addChild('author'); $author->name = Zotero_Libraries::getName($this->libraryID); $author->uri = Zotero_URI::getLibraryURI($this->libraryID, true); $xml->id = Zotero_URI::getTagURI($this); $xml->published = Zotero_Date::sqlToISO8601($this->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($this->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_API::getTagURI($this); $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getTagURI($this, true); // Count user's linked items if (isset($fixedValues['numItems'])) { $numItems = $fixedValues['numItems']; } else { $numItems = sizeOf($this->getLinkedItems(true)); } $xml->addChild('zapi:numItems', $numItems, Zotero_Atom::$nsZoteroAPI); if ($content == 'html') { $xml->content['type'] = 'xhtml'; $contentXML = new SimpleXMLElement("<div/>"); $contentXML->addAttribute("xmlns", Zotero_Atom::$nsXHTML); $fNode = dom_import_simplexml($xml->content); $subNode = dom_import_simplexml($contentXML); $importedNode = $fNode->ownerDocument->importNode($subNode, true); $fNode->appendChild($importedNode); } else { if ($content == 'json') { $xml->content['type'] = 'application/json'; $xml->content = Zotero_Utilities::formatJSON($this->toJSON()); } } return $xml; }
public static function createAtomFeed($action, $title, $url, $entries, $totalResults = null, $queryParams = [], Zotero_Permissions $permissions = null, $fixedValues = array()) { if ($queryParams) { $nonDefaultParams = Zotero_API::getNonDefaultParams($action, $queryParams); } else { $nonDefaultParams = []; } $feed = '<?xml version="1.0" encoding="UTF-8"?>' . '<feed xmlns="' . Zotero_Atom::$nsAtom . '" ' . 'xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'; $xml = new SimpleXMLElement($feed); $xml->title = $title; $path = parse_url($url, PHP_URL_PATH); // Generate canonical URI $zoteroURI = Zotero_URI::getBaseURI() . substr($path, 1) . Zotero_API::buildQueryString($queryParams['v'], $action, $nonDefaultParams, ['v']); $baseURI = Zotero_API::getBaseURI() . substr($path, 1); // API version isn't included in URLs (as with the API key) // // It could alternatively be made a private parameter so that it didn't appear // in the Link header either, but for now it's still there. $excludeParams = ['v']; $links = Zotero_API::buildLinks($action, $path, $totalResults, $queryParams, $nonDefaultParams, $excludeParams); $xml->id = $zoteroURI; $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = $links['self']; $link = $xml->addChild("link"); $link['rel'] = "first"; $link['type'] = "application/atom+xml"; $link['href'] = $links['first']; if (isset($links['next'])) { $link = $xml->addChild("link"); $link['rel'] = "next"; $link['type'] = "application/atom+xml"; $link['href'] = $links['next']; } $link = $xml->addChild("link"); $link['rel'] = "last"; $link['type'] = "application/atom+xml"; $link['href'] = $links['last']; // Generate alternate URI $link = $xml->addChild("link"); $link['rel'] = "alternate"; $link['type'] = "text/html"; $link['href'] = $links['alternate']; if ($queryParams['v'] < 3) { $xml->addChild("zapi:totalResults", is_numeric($totalResults) ? $totalResults : sizeOf($entries), self::$nsZoteroAPI); } if ($queryParams['v'] < 2) { $xml->addChild("zapi:apiVersion", 1, self::$nsZoteroAPI); } $latestUpdated = ''; // Check memcached for bib data $sharedData = array(); if ($entries && $entries[0] instanceof Zotero_Item) { if (in_array('citation', $queryParams['content'])) { $sharedData["citation"] = Zotero_Cite::multiGetFromMemcached("citation", $entries, $queryParams); } if (in_array('bib', $queryParams['content'])) { $sharedData["bib"] = Zotero_Cite::multiGetFromMemcached("bib", $entries, $queryParams); } } $xmlEntries = array(); foreach ($entries as $entry) { if ($entry->dateModified > $latestUpdated) { $latestUpdated = $entry->dateModified; } if ($entry instanceof SimpleXMLElement) { $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Collection) { $entry = Zotero_Collections::convertCollectionToAtom($entry, $queryParams); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Item) { $entry = Zotero_Items::convertItemToAtom($entry, $queryParams, $permissions, $sharedData); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Search) { $entry = $entry->toAtom($queryParams); $xmlEntries[] = $entry; } else { if ($entry instanceof Zotero_Tag) { $xmlEntries[] = $entry->toAtom($queryParams, isset($fixedValues[$entry->id]) ? $fixedValues[$entry->id] : null); } else { if ($entry instanceof Zotero_Group) { $entry = $entry->toAtom($queryParams); $xmlEntries[] = $entry; } } } } } } } if ($latestUpdated) { $xml->updated = Zotero_Date::sqlToISO8601($latestUpdated); } else { $xml->updated = str_replace("+00:00", "Z", date('c')); } // Import object XML nodes into document $doc = dom_import_simplexml($xml); foreach ($xmlEntries as $xmlEntry) { $subNode = dom_import_simplexml($xmlEntry); $importedNode = $doc->ownerDocument->importNode($subNode, true); $doc->appendChild($importedNode); } return $xml; }
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) { $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; }
public function toJSON() { if (($this->id || $this->key) && !$this->loaded) { $this->load(); } $json = []; $json['key'] = $this->key; $json['userID'] = $this->userID; $json['username'] = Zotero_Users::getUsername($this->userID); $json['name'] = $this->name; if ($this->permissions) { $json['access'] = ['user' => [], 'groups' => []]; foreach ($this->permissions as $libraryID => $p) { // group="all" is stored as libraryID 0 if ($libraryID === 0) { $json['access']['groups']['all']['library'] = true; $json['access']['groups']['all']['write'] = !empty($p['write']); } else { $type = Zotero_Libraries::getType($libraryID); switch ($type) { case 'user': $json['access']['user']['library'] = true; foreach ($p as $permission => $granted) { if ($permission == 'library') { continue; } $json['access']['user'][$permission] = (bool) $granted; } break; case 'group': $groupID = Zotero_Groups::getGroupIDFromLibraryID($libraryID); $json['access']['groups'][$groupID]['library'] = true; $json['access']['groups'][$groupID]['write'] = !empty($p['write']); break; } } } if (sizeOf($json['access']['user']) === 0) { unset($json['access']['user']); } if (sizeOf($json['access']['groups']) === 0) { unset($json['access']['groups']); } } $json['dateAdded'] = Zotero_Date::sqlToISO8601($this->dateAdded); if ($this->lastUsed != '0000-00-00 00:00:00') { $json['lastUsed'] = Zotero_Date::sqlToISO8601($this->lastUsed); } $ips = $this->getRecentIPs(); if ($ips) { $json['recentIPs'] = $ips; } return $json; }
/** * Converts a Zotero_Collection object to a SimpleXMLElement Atom object * * @param object $item Zotero_Collection object * @param string $content * @return SimpleXMLElement Collection data as SimpleXML element */ public static function convertCollectionToAtom(Zotero_Collection $collection, $content = array('none')) { // TEMP: multi-format support $content = $content[0]; $xml = new SimpleXMLElement('<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'); $title = $collection->name ? $collection->name : '[Untitled]'; $xml->title = $title; $author = $xml->addChild('author'); // TODO: group item creator $author->name = Zotero_Libraries::getName($collection->libraryID); $author->uri = Zotero_URI::getLibraryURI($collection->libraryID); $xml->id = Zotero_URI::getCollectionURI($collection); $xml->published = Zotero_Date::sqlToISO8601($collection->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($collection->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_Atom::getCollectionURI($collection); $parent = $collection->parent; if ($parent) { $parentCol = self::get($collection->libraryID, $parent); $link = $xml->addChild("link"); $link['rel'] = "up"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_Atom::getCollectionURI($parentCol); } $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getCollectionURI($collection); $xml->addChild('zapi:key', $collection->key, Zotero_Atom::$nsZoteroAPI); $collections = $collection->getChildCollections(); $xml->addChild('zapi:numCollections', sizeOf($collections), Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:numItems', $collection->numItems(), Zotero_Atom::$nsZoteroAPI); if ($content == 'json') { $xml->content['type'] = 'application/json'; $xml->content->addAttribute('zapi:etag', $collection->etag, Zotero_Atom::$nsZoteroAPI); // TODO: remove non-namespaced attribute $xml->content['etag'] = $collection->etag; $xml->content = $collection->toJSON(); } else { if ($content == 'full') { $xml->content['type'] = 'application/xml'; $fullXML = Zotero_Collections::convertCollectionToXML($collection); $fullXML->addAttribute("xmlns", Zotero_Atom::$nsZoteroTransfer); $fNode = dom_import_simplexml($xml->content); $subNode = dom_import_simplexml($fullXML); $importedNode = $fNode->ownerDocument->importNode($subNode, true); $fNode->appendChild($importedNode); } } return $xml; }
public static function strToDate($string) { // Parse 'yesterday'/'today'/'tomorrow' $lc = strtolower($string); if ($lc == 'yesterday' || $lc == self::getString('date.yesterday')) { $string = date("Y-m-d", strtotime('yesterday')); } else { if ($lc == 'today' || $lc == self::getString('date.today')) { $string = date("Y-m-d"); } else { if ($lc == 'tomorrow' || $lc == self::getString('date.tomorrow')) { $string = date("Y-m-d", strtotime('tomorrow')); } } } $date = array(); // skip empty things if (!$string) { return $date; } $string = preg_replace(array("/^\\s+/", "/\\s+\$/", "/\\s+/"), array("", "", " "), $string); // first, directly inspect the string preg_match(self::$slashRE, $string, $m); if ($m && (empty($m[5]) || $m[3] == $m[5] || $m[3] == "年" && $m[5] == "月") && (!empty($m[2]) && !empty($m[4]) && !empty($m[6]) || empty($m[1]) && empty($m[7]))) { // require that either all parts are found, // or else this is the entire date field // figure out date based on parts if (mb_strlen($m[2]) == 3 || mb_strlen($m[2]) == 4 || $m[3] == "年") { // ISO 8601 style date (big endian) $date['year'] = $m[2]; $date['month'] = $m[4]; $date['day'] = $m[6]; } else { // local style date (middle or little endian) $date['year'] = $m[6]; $country = substr(self::$locale, 3); if ($country == "US" || $country == "FM" || $country == "PW" || $country == "PH") { // The Philippines $date['month'] = $m[2]; $date['day'] = $m[4]; } else { $date['month'] = $m[4]; $date['day'] = $m[2]; } } if ($date['year']) { $date['year'] = (int) $date['year']; } if ($date['day']) { $date['day'] = (int) $date['day']; } if ($date['month']) { $date['month'] = (int) $date['month']; if ($date['month'] > 12) { // swap day and month $tmp = $date['day']; $date['day'] = $date['month']; $date['month'] = $tmp; } } if ((empty($date['month']) || $date['month'] <= 12) && (empty($date['day']) || $date['day'] <= 31)) { if (!empty($date['year']) && $date['year'] < 100) { // for two digit years, determine proper $year = date('Y'); $twoDigitYear = date('y'); $century = $year - $twoDigitYear; if ($date['year'] <= $twoDigitYear) { // assume this date is from our century $date['year'] = $century + $date['year']; } else { // assume this date is from the previous century $date['year'] = $century - 100 + $date['year']; } } Z_Core::debug("DATE: retrieved with algorithms: " . json_encode($date)); $date['part'] = $m[1] . $m[7]; } else { // give up; we failed the sanity check Z_Core::debug("DATE: algorithms failed sanity check"); $date = array("part" => $string); } } else { //Zotero.debug("DATE: could not apply algorithms"); $date['part'] = $string; } // couldn't find something with the algorithms; use regexp // YEAR if (empty($date['year'])) { if (preg_match(self::$yearRE, $date['part'], $m)) { $date['year'] = $m[2]; $date['part'] = $m[1] . $m[3]; Z_Core::debug("DATE: got year (" . $date['year'] . ", " . $date['part'] . ")"); } } // MONTH if (empty($date['month'])) { // compile month regular expression $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); // If using a non-English bibliography locale, try those too if (self::$locale != 'en-US') { throw new Exception("Unimplemented"); //$months = array_merge($months, .concat(Zotero.$date['month']s.short); } if (!self::$monthRE) { self::$monthRE = "/^(.*)\\b(" . implode("|", $months) . ")[^ ]*(?: (.*)\$|\$)/iu"; } if (preg_match(self::$monthRE, $date['part'], $m)) { // Modulo 12 in case we have multiple languages $date['month'] = array_search(ucwords(strtolower($m[2])), $months) % 12 + 1; $date['part'] = $m[1] . (isset($m[3]) ? $m[3] : ''); Z_Core::debug("DATE: got month (" . $date['month'] . ", " . $date['part'] . ")"); } } // DAY if (empty($date['day'])) { // compile day regular expression if (!self::$dayRE) { $daySuffixes = preg_replace("/, ?/", "|", self::getString("date.daySuffixes")); self::$dayRE = "/\\b([0-9]{1,2})(?:" . $daySuffixes . ")?\\b(.*)/iu"; } if (preg_match(self::$dayRE, $date['part'], $m, PREG_OFFSET_CAPTURE)) { $day = (int) $m[1][0]; // Sanity check if ($day <= 31) { $date['day'] = $day; if ($m[0][1] > 0) { $date['part'] = substr($date['part'], 0, $m[0][1]); if ($m[2][0]) { $date['part'] .= " " . $m[2][0]; } } else { $date['part'] = $m[2][0]; } Z_Core::debug("DATE: got day (" . $date['day'] . ", " . $date['part'] . ")"); } } } // clean up date part if ($date['part']) { $date['part'] = preg_replace(array("/^[^A-Za-z0-9]+/", "/[^A-Za-z0-9]+\$/"), "", $date['part']); } if ($date['part'] === "" || !isset($date['part'])) { unset($date['part']); } return $date; }
/** * Converts a Zotero_Collection object to a SimpleXMLElement Atom object * * @param Zotero_Collection $collection Zotero_Collection object * @param array $requestParams * @return SimpleXMLElement Collection data as SimpleXML element */ public static function convertCollectionToAtom(Zotero_Collection $collection, $requestParams) { // TEMP: multi-format support if (!empty($requestParams['content'])) { $content = $requestParams['content']; } else { $content = array('none'); } $content = $content[0]; $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'); $title = $collection->name ? $collection->name : '[Untitled]'; $xml->title = $title; $author = $xml->addChild('author'); // TODO: group item creator $author->name = Zotero_Libraries::getName($collection->libraryID); $author->uri = Zotero_URI::getLibraryURI($collection->libraryID, true); $xml->id = Zotero_URI::getCollectionURI($collection); $xml->published = Zotero_Date::sqlToISO8601($collection->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($collection->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_API::getCollectionURI($collection); $parent = $collection->parent; if ($parent) { $parentCol = self::get($collection->libraryID, $parent); $link = $xml->addChild("link"); $link['rel'] = "up"; $link['type'] = "application/atom+xml"; $link['href'] = Zotero_API::getCollectionURI($parentCol); } $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getCollectionURI($collection, true); $xml->addChild('zapi:key', $collection->key, Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:version', $collection->version, Zotero_Atom::$nsZoteroAPI); $collections = $collection->getChildCollections(); $xml->addChild('zapi:numCollections', sizeOf($collections), Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:numItems', $collection->numItems(), Zotero_Atom::$nsZoteroAPI); if ($content == 'json') { $xml->content['type'] = 'application/json'; // Deprecated if ($requestParams['v'] < 2) { $xml->content->addAttribute('zapi:etag', $collection->etag, Zotero_Atom::$nsZoteroAPI); $xml->content['etag'] = $collection->etag; } $xml->content = Zotero_Utilities::formatJSON($collection->toJSON($requestParams)); } return $xml; }
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); } }
protected function assertISO8601Date($date) { $this->assertTrue(\Zotero_Date::isISO8601($date)); }