Exemple #1
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     API::userClear(self::$config['userID']);
     // Create test data
     $key = API::createItem("book", array("title" => "Title", "creators" => array(array("creatorType" => "author", "firstName" => "First", "lastName" => "Last"))), null, 'key');
     self::$items[$key] = '<content xmlns:zapi="http://zotero.org/ns/api" type="application/xml"><zapi:subcontent zapi:type="bib"><div xmlns="http://www.w3.org/1999/xhtml" class="csl-bib-body" style="line-height: 1.35; padding-left: 2em; text-indent:-2em;"><div class="csl-entry">Last, First. <i>Title</i>, n.d.</div></div></zapi:subcontent><zapi:subcontent zapi:type="json">' . \Zotero_Utilities::formatJSON(json_decode('{"itemKey":"","itemVersion":0,"itemType":"book","title":"Title","creators":[{"creatorType":"author","firstName":"First","lastName":"Last"}],"abstractNote":"","series":"","seriesNumber":"","volume":"","numberOfVolumes":"","edition":"","place":"","publisher":"","date":"","numPages":"","language":"","ISBN":"","shortTitle":"","url":"","accessDate":"","archive":"","archiveLocation":"","libraryCatalog":"","callNumber":"","rights":"","extra":"","tags":[],"collections":[],"relations":{}}')) . '</zapi:subcontent></content>';
     $key = API::createItem("book", array("title" => "Title 2", "creators" => array(array("creatorType" => "author", "firstName" => "First", "lastName" => "Last"), array("creatorType" => "editor", "firstName" => "Ed", "lastName" => "McEditor"))), null, 'key');
     self::$items[$key] = '<content xmlns:zapi="http://zotero.org/ns/api" type="application/xml"><zapi:subcontent zapi:type="bib"><div xmlns="http://www.w3.org/1999/xhtml" class="csl-bib-body" style="line-height: 1.35; padding-left: 2em; text-indent:-2em;"><div class="csl-entry">Last, First. <i>Title 2</i>. Edited by Ed McEditor, n.d.</div></div></zapi:subcontent><zapi:subcontent zapi:type="json">' . \Zotero_Utilities::formatJSON(json_decode('{"itemKey":"","itemVersion":0,"itemType":"book","title":"Title 2","creators":[{"creatorType":"author","firstName":"First","lastName":"Last"},{"creatorType":"editor","firstName":"Ed","lastName":"McEditor"}],"abstractNote":"","series":"","seriesNumber":"","volume":"","numberOfVolumes":"","edition":"","place":"","publisher":"","date":"","numPages":"","language":"","ISBN":"","shortTitle":"","url":"","accessDate":"","archive":"","archiveLocation":"","libraryCatalog":"","callNumber":"","rights":"","extra":"","tags":[],"collections":[],"relations":{}}')) . '</zapi:subcontent></content>';
 }
 public function deleted()
 {
     if ($this->apiVersion < 2) {
         $this->e404();
     }
     $this->allowMethods(array('GET'));
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
     // TEMP: sync transition
     if ($this->queryParams['sincetime'] !== null) {
         $deleted = array("collections" => Zotero_Collections::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['sincetime'], true), "items" => Zotero_Items::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['sincetime'], true), "searches" => Zotero_Searches::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['sincetime'], true), "tags" => Zotero_Tags::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['sincetime'], true), "settings" => Zotero_Settings::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['sincetime'], true));
         echo Zotero_Utilities::formatJSON($deleted);
         $this->end();
     }
     if ($this->queryParams['since'] === null) {
         $this->e400("'since' parameter must be provided");
     }
     $deleted = array("collections" => Zotero_Collections::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['since']), "items" => Zotero_Items::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['since']), "searches" => Zotero_Searches::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['since']), "tags" => Zotero_Tags::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['since']), "settings" => Zotero_Settings::getDeleteLogKeys($this->objectLibraryID, $this->queryParams['since']));
     echo Zotero_Utilities::formatJSON($deleted);
     $this->end();
 }
 public function itemContent()
 {
     $this->allowMethods(array('GET', 'PUT'));
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if (!$this->singleObject) {
         $this->e404();
     }
     if ($this->isWriteMethod()) {
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
     if (!$item) {
         $this->e404();
     }
     // If no access to the note, don't show that it exists
     if ($item->isNote() && !$this->permissions->canAccess($this->objectLibraryID, 'notes')) {
         $this->e404();
     }
     if (!$item->isAttachment() || Zotero_Attachments::linkModeNumberToName($item->attachmentLinkMode) == 'LINKED_URL') {
         $this->e404();
     }
     if ($this->isWriteMethod()) {
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         if ($this->method == 'PUT') {
             $this->requireContentType("application/json");
             $json = json_decode($this->body, true);
             if (!$json) {
                 $this->e400("PUT data is not valid JSON");
             }
             $stats = [];
             foreach (Zotero_FullText::$metadata as $prop) {
                 if (isset($json[$prop])) {
                     $stats[$prop] = $json[$prop];
                 }
             }
             Zotero_FullText::indexItem($item, $json['content'], $stats);
             $this->e204();
         } else {
             $this->e405();
         }
     }
     $data = Zotero_FullText::getItemData($item->libraryID, $item->key);
     if (!$data) {
         $this->e404();
     }
     $this->libraryVersion = $data['version'];
     $json = ["content" => $data['content']];
     foreach (Zotero_FullText::$metadata as $prop) {
         if (!empty($data[$prop])) {
             $json[$prop] = $data[$prop];
         }
     }
     echo Zotero_Utilities::formatJSON($json);
     $this->end();
 }
Exemple #4
0
 /**
  * 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 collections()
 {
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     $collectionIDs = array();
     $collectionKeys = array();
     $results = array();
     // Single collection
     if ($this->singleObject) {
         $this->allowMethods(['HEAD', 'GET', 'PUT', 'PATCH', 'DELETE']);
         if (!Zotero_ID::isValidKey($this->objectKey)) {
             $this->e404();
         }
         $collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if ($this->isWriteMethod()) {
             $collection = $this->handleObjectWrite('collection', $collection ? $collection : null);
             $this->queryParams['content'] = ['json'];
         }
         if (!$collection) {
             $this->e404("Collection not found");
         }
         $this->libraryVersion = $collection->version;
         if ($this->method == 'HEAD') {
             $this->end();
         }
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_Collections::convertCollectionToAtom($collection, $this->queryParams);
                 break;
             case 'json':
                 $json = $collection->toResponseJSON($this->queryParams, $this->permissions);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     } else {
         $this->allowMethods(['HEAD', 'GET', 'POST', 'DELETE']);
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         if ($this->scopeObject) {
             $this->allowMethods(array('GET'));
             switch ($this->scopeObject) {
                 case 'collections':
                     $collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
                     if (!$collection) {
                         $this->e404("Collection not found");
                     }
                     $title = "Child Collections of ‘{$collection->name}'’";
                     $collectionIDs = $collection->getChildCollections();
                     break;
                 default:
                     throw new Exception("Invalid collections scope object '{$this->scopeObject}'");
             }
         } else {
             // Top-level items
             if ($this->subset == 'top') {
                 $this->allowMethods(array('GET'));
                 $title = "Top-Level Collections";
                 $results = Zotero_Collections::search($this->objectLibraryID, true, $this->queryParams);
             } else {
                 // Create a collection
                 if ($this->method == 'POST') {
                     $this->queryParams['format'] = 'writereport';
                     $obj = $this->jsonDecode($this->body);
                     $results = Zotero_Collections::updateMultipleFromJSON($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $libraryTimestampChecked ? 0 : 1, null);
                     if ($cacheKey = $this->getWriteTokenCacheKey()) {
                         Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                     }
                     if ($this->apiVersion < 2) {
                         $uri = Zotero_API::getCollectionsURI($this->objectLibraryID);
                         $keys = array_merge(get_object_vars($results['success']), get_object_vars($results['unchanged']));
                         $queryString = "collectionKey=" . urlencode(implode(",", $keys)) . "&format=atom&content=json&order=collectionKeyList&sort=asc";
                         if ($this->apiKey) {
                             $queryString .= "&key=" . $this->apiKey;
                         }
                         $uri .= "?" . $queryString;
                         $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, true, $this->apiVersion);
                         $title = "Collections";
                         $results = Zotero_Collections::search($this->objectLibraryID, false, $this->queryParams);
                     }
                 } else {
                     if ($this->method == 'DELETE') {
                         Zotero_DB::beginTransaction();
                         foreach ($this->queryParams['collectionKey'] as $collectionKey) {
                             Zotero_Collections::delete($this->objectLibraryID, $collectionKey);
                         }
                         Zotero_DB::commit();
                         $this->e204();
                     } else {
                         $title = "Collections";
                         $results = Zotero_Collections::search($this->objectLibraryID, false, $this->queryParams);
                     }
                 }
             }
         }
         if ($collectionIDs) {
             $this->queryParams['collectionIDs'] = $collectionIDs;
             $results = Zotero_Collections::search($this->objectLibraryID, false, $this->queryParams);
         }
         $options = ['action' => $this->action, 'uri' => $this->uri, 'results' => $results, 'requestParams' => $this->queryParams, 'permissions' => $this->permissions, 'head' => $this->method == 'HEAD'];
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_API::multiResponse(array_merge($options, ['title' => $this->getFeedNamePrefix($this->objectLibraryID) . $title]));
                 break;
             case 'json':
             case 'keys':
             case 'versions':
             case 'writereport':
                 Zotero_API::multiResponse($options);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     }
     $this->end();
 }
Exemple #6
0
 public function toAtom($queryParams)
 {
     if (!empty($queryParams['content'])) {
         $content = $queryParams['content'];
     } else {
         $content = array('none');
     }
     // TEMP: multi-format support
     $content = $content[0];
     if (!$this->loaded) {
         $this->load();
     }
     $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" ' . 'xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '" ' . 'xmlns:zxfer="' . Zotero_Atom::$nsZoteroTransfer . '"/>');
     $title = $this->name ? $this->name : '[Untitled]';
     $xml->title = $title;
     $author = $xml->addChild('author');
     $ownerLibraryID = Zotero_Users::getLibraryIDFromUserID($this->ownerUserID);
     $author->name = Zotero_Users::getUsername($this->ownerUserID);
     $author->uri = Zotero_URI::getLibraryURI($ownerLibraryID);
     $xml->id = Zotero_URI::getGroupURI($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::getGroupURI($this);
     $link = $xml->addChild('link');
     $link['rel'] = 'alternate';
     $link['type'] = 'text/html';
     $link['href'] = Zotero_URI::getGroupURI($this);
     $xml->addChild('zapi:groupID', $this->id, Zotero_Atom::$nsZoteroAPI);
     $xml->addChild('zapi:numItems', $this->numItems(), Zotero_Atom::$nsZoteroAPI);
     if ($content == 'html') {
         $xml->content['type'] = 'html';
         $htmlXML = $this->toHTML();
         $xml->content->div = '';
         $xml->content->div['xmlns'] = Zotero_Atom::$nsXHTML;
         $fNode = dom_import_simplexml($xml->content->div);
         $subNode = dom_import_simplexml($htmlXML);
         $importedNode = $fNode->ownerDocument->importNode($subNode, true);
         $fNode->appendChild($importedNode);
     } else {
         if ($content == 'json') {
             $xml->content['type'] = 'application/json';
             $xml->content['etag'] = $this->etag;
             // Deprecated
             if ($queryParams['v'] < 2) {
                 $xml->content->addAttribute("zapi:etag", $this->etag, Zotero_Atom::$nsZoteroAPI);
             }
             $xml->content = Zotero_Utilities::formatJSON($this->toJSON($queryParams, true));
         } else {
             if ($content == 'full') {
                 $xml->content['type'] = 'application/xml';
                 $fullXML = $this->toXML();
                 $fNode = dom_import_simplexml($xml->content);
                 $subNode = dom_import_simplexml($fullXML);
                 $importedNode = $fNode->ownerDocument->importNode($subNode, true);
                 $fNode->appendChild($importedNode);
             }
         }
     }
     return $xml;
 }
Exemple #7
0
 public function toJSON($asArray = false)
 {
     if (!$this->loaded) {
         $this->load();
     }
     $arr = array();
     $arr['subject'] = $this->subject;
     $arr['predicate'] = $this->predicate;
     $arr['object'] = $this->object;
     if ($asArray) {
         return $arr;
     }
     return Zotero_Utilities::formatJSON($arr);
 }
Exemple #8
0
 /**
  * Converts a Zotero_Item object to a SimpleXMLElement Atom object
  *
  * Note: Increment Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY when changing
  * the response.
  *
  * @param	object				$item		Zotero_Item object
  * @param	string				$content
  * @return	SimpleXMLElement					Item data as SimpleXML element
  */
 public static function convertItemToAtom(Zotero_Item $item, $queryParams, $permissions, $sharedData = null)
 {
     $t = microtime(true);
     // Uncached stuff or parts of the cache key
     $version = $item->version;
     $parent = $item->getSource();
     $isRegularItem = !$parent && $item->isRegularItem();
     $downloadDetails = $permissions->canAccess($item->libraryID, 'files') ? Zotero_Storage::getDownloadDetails($item) : false;
     if ($isRegularItem) {
         $numChildren = $permissions->canAccess($item->libraryID, 'notes') ? $item->numChildren() : $item->numAttachments();
     }
     // <id> changes based on group visibility in v1
     if ($queryParams['v'] < 2) {
         $id = Zotero_URI::getItemURI($item, false, true);
     } else {
         $id = Zotero_URI::getItemURI($item);
     }
     $libraryType = Zotero_Libraries::getType($item->libraryID);
     // Any query parameters that have an effect on the output
     // need to be added here
     $allowedParams = array('content', 'style', 'css', 'linkwrap');
     $cachedParams = Z_Array::filterKeys($queryParams, $allowedParams);
     $cacheVersion = 2;
     $cacheKey = "atomEntry_" . $item->libraryID . "/" . $item->id . "_" . md5($version . json_encode($cachedParams) . ($downloadDetails ? 'hasFile' : '') . ($libraryType == 'group' ? 'id' . $id : '')) . "_" . $queryParams['v'] . "_" . $cacheVersion . (isset(Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY) ? "_" . Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY : "") . (in_array('bib', $queryParams['content']) && isset(Z_CONFIG::$CACHE_VERSION_BIB) ? "_" . Z_CONFIG::$CACHE_VERSION_BIB : "");
     $xmlstr = Z_Core::$MC->get($cacheKey);
     if ($xmlstr) {
         try {
             // TEMP: Strip control characters
             $xmlstr = Zotero_Utilities::cleanString($xmlstr, true);
             $doc = new DOMDocument();
             $doc->loadXML($xmlstr);
             $xpath = new DOMXpath($doc);
             $xpath->registerNamespace('atom', Zotero_Atom::$nsAtom);
             $xpath->registerNamespace('zapi', Zotero_Atom::$nsZoteroAPI);
             $xpath->registerNamespace('xhtml', Zotero_Atom::$nsXHTML);
             // Make sure numChildren reflects the current permissions
             if ($isRegularItem) {
                 $xpath->query('/atom:entry/zapi:numChildren')->item(0)->nodeValue = $numChildren;
             }
             // To prevent PHP from messing with namespace declarations,
             // we have to extract, remove, and then add back <content>
             // subelements. Otherwise the subelements become, say,
             // <default:span xmlns="http://www.w3.org/1999/xhtml"> instead
             // of just <span xmlns="http://www.w3.org/1999/xhtml">, and
             // xmlns:default="http://www.w3.org/1999/xhtml" gets added to
             // the parent <entry>. While you might reasonably think that
             //
             // echo $xml->saveXML();
             //
             // and
             //
             // $xml = new SimpleXMLElement($xml->saveXML());
             // echo $xml->saveXML();
             //
             // would be identical, you would be wrong.
             $multiFormat = !!$xpath->query('/atom:entry/atom:content/zapi:subcontent')->length;
             $contentNodes = array();
             if ($multiFormat) {
                 $contentNodes = $xpath->query('/atom:entry/atom:content/zapi:subcontent');
             } else {
                 $contentNodes = $xpath->query('/atom:entry/atom:content');
             }
             foreach ($contentNodes as $contentNode) {
                 $contentParts = array();
                 while ($contentNode->hasChildNodes()) {
                     $contentParts[] = $doc->saveXML($contentNode->firstChild);
                     $contentNode->removeChild($contentNode->firstChild);
                 }
                 foreach ($contentParts as $part) {
                     if (!trim($part)) {
                         continue;
                     }
                     // Strip the namespace and add it back via SimpleXMLElement,
                     // which keeps it from being changed later
                     if (preg_match('%^<[^>]+xmlns="http://www.w3.org/1999/xhtml"%', $part)) {
                         $part = preg_replace('%^(<[^>]+)xmlns="http://www.w3.org/1999/xhtml"%', '$1', $part);
                         $html = new SimpleXMLElement($part);
                         $html['xmlns'] = "http://www.w3.org/1999/xhtml";
                         $subNode = dom_import_simplexml($html);
                         $importedNode = $doc->importNode($subNode, true);
                         $contentNode->appendChild($importedNode);
                     } else {
                         if (preg_match('%^<[^>]+xmlns="http://zotero.org/ns/transfer"%', $part)) {
                             $part = preg_replace('%^(<[^>]+)xmlns="http://zotero.org/ns/transfer"%', '$1', $part);
                             $html = new SimpleXMLElement($part);
                             $html['xmlns'] = "http://zotero.org/ns/transfer";
                             $subNode = dom_import_simplexml($html);
                             $importedNode = $doc->importNode($subNode, true);
                             $contentNode->appendChild($importedNode);
                         } else {
                             $docFrag = $doc->createDocumentFragment();
                             $docFrag->appendXML($part);
                             $contentNode->appendChild($docFrag);
                         }
                     }
                 }
             }
             $xml = simplexml_import_dom($doc);
             StatsD::timing("api.items.itemToAtom.cached", (microtime(true) - $t) * 1000);
             StatsD::increment("memcached.items.itemToAtom.hit");
             // Skip the cache every 10 times for now, to ensure cache sanity
             if (Z_Core::probability(10)) {
                 $xmlstr = $xml->saveXML();
             } else {
                 return $xml;
             }
         } catch (Exception $e) {
             error_log($xmlstr);
             error_log("WARNING: " . $e);
         }
     }
     $content = $queryParams['content'];
     $contentIsHTML = sizeOf($content) == 1 && $content[0] == 'html';
     $contentParamString = urlencode(implode(',', $content));
     $style = $queryParams['style'];
     $entry = '<?xml version="1.0" encoding="UTF-8"?>' . '<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;
     $lastModifiedByUserID = null;
     switch (Zotero_Libraries::getType($item->libraryID)) {
         case 'group':
             $createdByUserID = $item->createdByUserID;
             // Used for zapi:lastModifiedByUser below
             $lastModifiedByUserID = $item->lastModifiedByUserID;
             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);
     }
     $xml->id = $id;
     $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";
     $href = Zotero_API::getItemURI($item);
     if (!$contentIsHTML) {
         $href .= "?content={$contentParamString}";
     }
     $link['href'] = $href;
     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_API::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, true);
     // If appropriate permissions and the file is stored in ZFS, get file request link
     if ($downloadDetails) {
         $details = $downloadDetails;
         $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 (isset($details['size'])) {
             $link['length'] = $details['size'];
         }
     }
     $xml->addChild('zapi:key', $item->key, Zotero_Atom::$nsZoteroAPI);
     $xml->addChild('zapi:version', $item->version, Zotero_Atom::$nsZoteroAPI);
     if ($lastModifiedByUserID) {
         $xml->addChild('zapi:lastModifiedByUser', Zotero_Users::getUsername($lastModifiedByUserID), Zotero_Atom::$nsZoteroAPI);
     }
     $xml->addChild('zapi:itemType', Zotero_ItemTypes::getName($item->itemTypeID), Zotero_Atom::$nsZoteroAPI);
     if ($isRegularItem) {
         $val = $item->creatorSummary;
         if ($val !== '') {
             $xml->addChild('zapi:creatorSummary', htmlspecialchars($val), Zotero_Atom::$nsZoteroAPI);
         }
         $val = $item->getField('date', true, true, true);
         if ($val !== '') {
             if ($queryParams['v'] < 3) {
                 $val = substr($val, 0, 4);
                 if ($val !== '0000') {
                     $xml->addChild('zapi:year', $val, Zotero_Atom::$nsZoteroAPI);
                 }
             } else {
                 $sqlDate = Zotero_Date::multipartToSQL($val);
                 if (substr($sqlDate, 0, 4) !== '0000') {
                     $xml->addChild('zapi:parsedDate', Zotero_Date::sqlToISO8601($sqlDate), Zotero_Atom::$nsZoteroAPI);
                 }
             }
         }
         $xml->addChild('zapi:numChildren', $numChildren, Zotero_Atom::$nsZoteroAPI);
     }
     if ($queryParams['v'] < 3) {
         $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->createElementNS(Zotero_Atom::$nsXHTML, 'div');
             $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, $queryParams);
                 }
                 $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), $queryParams);
                     }
                     $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') {
                         if ($queryParams['v'] < 2) {
                             $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:etag", $item->etag);
                         }
                         $textNode = $domDoc->createTextNode($item->toJSON(false, $queryParams, true));
                         $target->appendChild($textNode);
                     } else {
                         if ($type == 'csljson') {
                             $arr = $item->toCSLItem();
                             $json = Zotero_Utilities::formatJSON($arr);
                             $textNode = $domDoc->createTextNode($json);
                             $target->appendChild($textNode);
                         } 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);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // TEMP
     if ($xmlstr) {
         $uncached = $xml->saveXML();
         if ($xmlstr != $uncached) {
             $uncached = str_replace('<zapi:year></zapi:year>', '<zapi:year/>', $uncached);
             $uncached = str_replace('<content zapi:type="none"></content>', '<content zapi:type="none"/>', $uncached);
             $uncached = str_replace('<zapi:subcontent zapi:type="coins" type="text/html"></zapi:subcontent>', '<zapi:subcontent zapi:type="coins" type="text/html"/>', $uncached);
             $uncached = str_replace('<title></title>', '<title/>', $uncached);
             $uncached = str_replace('<note></note>', '<note/>', $uncached);
             $uncached = str_replace('<path></path>', '<path/>', $uncached);
             $uncached = str_replace('<td></td>', '<td/>', $uncached);
             if ($xmlstr != $uncached) {
                 error_log("Cached Atom item entry does not match");
                 error_log("  Cached: " . $xmlstr);
                 error_log("Uncached: " . $uncached);
                 Z_Core::$MC->set($cacheKey, $uncached, 3600);
                 // 1 hour for now
             }
         }
     } else {
         $xmlstr = $xml->saveXML();
         Z_Core::$MC->set($cacheKey, $xmlstr, 3600);
         // 1 hour for now
         StatsD::timing("api.items.itemToAtom.uncached", (microtime(true) - $t) * 1000);
         StatsD::increment("memcached.items.itemToAtom.miss");
     }
     return $xml;
 }
 /**
  * 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;
 }
Exemple #10
0
 /**
  * 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;
 }
Exemple #11
0
 public function items()
 {
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         // We don't update the library version in file mode, because currently
         // to avoid conflicts in the client the timestamp can't change
         // when the client updates file metadata
         if (!$this->fileMode) {
             Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
         }
     }
     $itemIDs = array();
     $itemKeys = array();
     $results = array();
     $title = "";
     //
     // Single item
     //
     if ($this->singleObject) {
         if ($this->fileMode) {
             if ($this->fileView) {
                 $this->allowMethods(array('HEAD', 'GET', 'POST'));
             } else {
                 $this->allowMethods(array('HEAD', 'GET', 'PUT', 'POST', 'PATCH'));
             }
         } else {
             $this->allowMethods(array('HEAD', 'GET', 'PUT', 'PATCH', 'DELETE'));
         }
         if (!$this->objectLibraryID || !Zotero_ID::isValidKey($this->objectKey)) {
             $this->e404();
         }
         $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if ($item) {
             // If no access to the note, don't show that it exists
             if ($item->isNote() && !$this->permissions->canAccess($this->objectLibraryID, 'notes')) {
                 $this->e404();
             }
             // Make sure URL libraryID matches item libraryID
             if ($this->objectLibraryID != $item->libraryID) {
                 $this->e404("Item does not exist");
             }
             // File access mode
             if ($this->fileMode) {
                 $this->_handleFileRequest($item);
             }
             if ($this->scopeObject) {
                 switch ($this->scopeObject) {
                     // Remove item from collection
                     case 'collections':
                         $this->allowMethods(array('DELETE'));
                         $collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
                         if (!$collection) {
                             $this->e404("Collection not found");
                         }
                         if (!$collection->hasItem($item->id)) {
                             $this->e404("Item not found in collection");
                         }
                         $collection->removeItem($item->id);
                         $this->e204();
                     default:
                         $this->e400();
                 }
             }
         } else {
             // Possibly temporary workaround to block unnecessary full syncs
             if ($this->fileMode && $this->httpAuth && $this->method == 'POST') {
                 // If > 2 requests for missing file, trigger a full sync via 404
                 $cacheKey = "apiMissingFile_" . $this->objectLibraryID . "_" . $this->objectKey;
                 $set = Z_Core::$MC->get($cacheKey);
                 if (!$set) {
                     Z_Core::$MC->set($cacheKey, 1, 86400);
                 } else {
                     if ($set < 2) {
                         Z_Core::$MC->increment($cacheKey);
                     } else {
                         Z_Core::$MC->delete($cacheKey);
                         $this->e404("A file sync error occurred. Please sync again.");
                     }
                 }
                 $this->e500("A file sync error occurred. Please sync again.");
             }
         }
         if ($this->isWriteMethod()) {
             $item = $this->handleObjectWrite('item', $item ? $item : null);
             if ($this->apiVersion < 2 && ($this->method == 'PUT' || $this->method == 'PATCH')) {
                 $this->queryParams['format'] = 'atom';
                 $this->queryParams['content'] = ['json'];
             }
         }
         if (!$item) {
             $this->e404("Item does not exist");
         }
         $this->libraryVersion = $item->version;
         if ($this->method == 'HEAD') {
             $this->end();
         }
         // Display item
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_Items::convertItemToAtom($item, $this->queryParams, $this->permissions);
                 break;
             case 'bib':
                 echo Zotero_Cite::getBibliographyFromCitationServer(array($item), $this->queryParams);
                 break;
             case 'csljson':
                 $json = Zotero_Cite::getJSONFromItems(array($item), true);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             case 'json':
                 $json = $item->toResponseJSON($this->queryParams, $this->permissions);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             default:
                 $export = Zotero_Translate::doExport(array($item), $this->queryParams['format']);
                 $this->queryParams['format'] = null;
                 header("Content-Type: " . $export['mimeType']);
                 echo $export['body'];
                 break;
         }
     } else {
         $this->allowMethods(array('HEAD', 'GET', 'POST', 'DELETE'));
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         $includeTrashed = $this->queryParams['includeTrashed'];
         if ($this->scopeObject) {
             $this->allowMethods(array('GET', 'POST'));
             switch ($this->scopeObject) {
                 case 'collections':
                     // TEMP
                     if (Zotero_ID::isValidKey($this->scopeObjectKey)) {
                         $collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
                     } else {
                         $collection = false;
                     }
                     if (!$collection) {
                         // If old collectionID, redirect
                         if ($this->method == 'GET' && Zotero_Utilities::isPosInt($this->scopeObjectKey)) {
                             $collection = Zotero_Collections::get($this->objectLibraryID, $this->scopeObjectKey);
                             if ($collection) {
                                 $qs = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
                                 $base = Zotero_API::getCollectionURI($collection);
                                 $this->redirect($base . "/items" . $qs, 301);
                             }
                         }
                         $this->e404("Collection not found");
                     }
                     // Add items to collection
                     if ($this->method == 'POST') {
                         $itemKeys = explode(' ', $this->body);
                         $itemIDs = array();
                         foreach ($itemKeys as $key) {
                             try {
                                 $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $key);
                             } catch (Exception $e) {
                                 if ($e->getCode() == Z_ERROR_OBJECT_LIBRARY_MISMATCH) {
                                     $item = false;
                                 } else {
                                     throw $e;
                                 }
                             }
                             if (!$item) {
                                 throw new Exception("Item '{$key}' not found in library", Z_ERROR_INVALID_INPUT);
                             }
                             if ($item->getSource()) {
                                 throw new Exception("Child items cannot be added to collections directly", Z_ERROR_INVALID_INPUT);
                             }
                             $itemIDs[] = $item->id;
                         }
                         $collection->addItems($itemIDs);
                         $this->e204();
                     }
                     if ($this->subset == 'top' || $this->apiVersion < 2) {
                         $title = "Top-Level Items in Collection ‘" . $collection->name . "’";
                         $itemIDs = $collection->getItems();
                     } else {
                         $title = "Items in Collection ‘" . $collection->name . "’";
                         $itemIDs = $collection->getItems(true);
                     }
                     break;
                 case 'tags':
                     if ($this->apiVersion >= 2) {
                         $this->e404();
                     }
                     $this->allowMethods(array('GET'));
                     $tagIDs = Zotero_Tags::getIDs($this->objectLibraryID, $this->scopeObjectName);
                     if (!$tagIDs) {
                         $this->e404("Tag not found");
                     }
                     foreach ($tagIDs as $tagID) {
                         $tag = new Zotero_Tag();
                         $tag->libraryID = $this->objectLibraryID;
                         $tag->id = $tagID;
                         // Use a real tag name, in case case differs
                         if (!$title) {
                             $title = "Items of Tag ‘" . $tag->name . "’";
                         }
                         $itemKeys = array_merge($itemKeys, $tag->getLinkedItems(true));
                     }
                     $itemKeys = array_unique($itemKeys);
                     break;
                 default:
                     $this->e404();
             }
         } else {
             // Top-level items
             if ($this->subset == 'top') {
                 $this->allowMethods(array('GET'));
                 $title = "Top-Level Items";
                 $results = Zotero_Items::search($this->objectLibraryID, true, $this->queryParams, $includeTrashed, $this->permissions);
             } else {
                 if ($this->subset == 'trash') {
                     $this->allowMethods(array('GET'));
                     $title = "Deleted Items";
                     $this->queryParams['trashedItemsOnly'] = true;
                     $includeTrashed = true;
                     $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
                 } else {
                     if ($this->subset == 'children') {
                         $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
                         if (!$item) {
                             $this->e404("Item not found");
                         }
                         if ($item->isAttachment()) {
                             $this->e400("/children cannot be called on attachment items");
                         }
                         if ($item->isNote()) {
                             $this->e400("/children cannot be called on note items");
                         }
                         if ($item->getSource()) {
                             $this->e400("/children cannot be called on child items");
                         }
                         // Create new child items
                         if ($this->method == 'POST') {
                             if ($this->apiVersion >= 2) {
                                 $this->allowMethods(array('GET'));
                             }
                             Zotero_DB::beginTransaction();
                             $obj = $this->jsonDecode($this->body);
                             $results = Zotero_Items::updateMultipleFromJSON($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $libraryTimestampChecked ? 0 : 1, $item);
                             Zotero_DB::commit();
                             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                             }
                             $uri = Zotero_API::getItemsURI($this->objectLibraryID);
                             $keys = array_merge(get_object_vars($results['success']), get_object_vars($results['unchanged']));
                             $queryString = "itemKey=" . urlencode(implode(",", $keys)) . "&format=atom&content=json&order=itemKeyList&sort=asc";
                             if ($this->apiKey) {
                                 $queryString .= "&key=" . $this->apiKey;
                             }
                             $uri .= "?" . $queryString;
                             $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
                             $this->responseCode = 201;
                             $title = "Items";
                             $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
                         } else {
                             $title = "Child Items of ‘" . $item->getDisplayTitle() . "’";
                             $notes = $item->getNotes();
                             $attachments = $item->getAttachments();
                             $itemIDs = array_merge($notes, $attachments);
                         }
                     } else {
                         // Create new items
                         if ($this->method == 'POST') {
                             $this->queryParams['format'] = 'writereport';
                             $obj = $this->jsonDecode($this->body);
                             // Server-side translation
                             if (isset($obj->url)) {
                                 if ($this->apiVersion == 1) {
                                     Zotero_DB::beginTransaction();
                                 }
                                 $token = $this->getTranslationToken($obj);
                                 $results = Zotero_Items::addFromURL($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $token);
                                 if ($this->apiVersion == 1) {
                                     Zotero_DB::commit();
                                 }
                                 // Multiple choices
                                 if ($results instanceof stdClass) {
                                     $this->queryParams['format'] = null;
                                     header("Content-Type: application/json");
                                     if ($this->queryParams['v'] >= 2) {
                                         echo Zotero_Utilities::formatJSON(['url' => $obj->url, 'token' => $token, 'items' => $results->select]);
                                     } else {
                                         echo Zotero_Utilities::formatJSON($results->select);
                                     }
                                     $this->e300();
                                 } else {
                                     if (is_int($results)) {
                                         switch ($results) {
                                             case 501:
                                                 $this->e501("No translators found for URL");
                                                 break;
                                             default:
                                                 $this->e500("Error translating URL");
                                         }
                                     } else {
                                         if ($this->apiVersion == 1) {
                                             $uri = Zotero_API::getItemsURI($this->objectLibraryID);
                                             $keys = array_merge(get_object_vars($results['success']), get_object_vars($results['unchanged']));
                                             $queryString = "itemKey=" . urlencode(implode(",", $keys)) . "&format=atom&content=json&order=itemKeyList&sort=asc";
                                             if ($this->apiKey) {
                                                 $queryString .= "&key=" . $this->apiKey;
                                             }
                                             $uri .= "?" . $queryString;
                                             $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
                                             $this->responseCode = 201;
                                             $title = "Items";
                                             $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
                                         }
                                     }
                                 }
                                 // Otherwise return write status report
                             } else {
                                 if ($this->apiVersion < 2) {
                                     Zotero_DB::beginTransaction();
                                 }
                                 $results = Zotero_Items::updateMultipleFromJSON($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $libraryTimestampChecked ? 0 : 1, null);
                                 if ($this->apiVersion < 2) {
                                     Zotero_DB::commit();
                                     $uri = Zotero_API::getItemsURI($this->objectLibraryID);
                                     $keys = array_merge(get_object_vars($results['success']), get_object_vars($results['unchanged']));
                                     $queryString = "itemKey=" . urlencode(implode(",", $keys)) . "&format=atom&content=json&order=itemKeyList&sort=asc";
                                     if ($this->apiKey) {
                                         $queryString .= "&key=" . $this->apiKey;
                                     }
                                     $uri .= "?" . $queryString;
                                     $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
                                     $this->responseCode = 201;
                                     $title = "Items";
                                     $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
                                 }
                             }
                             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                             }
                         } else {
                             if ($this->method == 'DELETE') {
                                 Zotero_DB::beginTransaction();
                                 foreach ($this->queryParams['itemKey'] as $itemKey) {
                                     Zotero_Items::delete($this->objectLibraryID, $itemKey);
                                 }
                                 Zotero_DB::commit();
                                 $this->e204();
                             } else {
                                 $title = "Items";
                                 $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
                             }
                         }
                     }
                 }
             }
         }
         if ($itemIDs || $itemKeys) {
             if ($itemIDs) {
                 $this->queryParams['itemIDs'] = $itemIDs;
             }
             if ($itemKeys) {
                 $this->queryParams['itemKey'] = $itemKeys;
             }
             $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $this->permissions);
         }
         if ($this->queryParams['format'] == 'bib') {
             $maxBibItems = Zotero_API::MAX_BIBLIOGRAPHY_ITEMS;
             if ($results['total'] > $maxBibItems) {
                 $this->e413("Cannot generate bibliography with more than {$maxBibItems} items");
             }
         }
         $this->generateMultiResponse($results, $title);
     }
     $this->end();
 }
Exemple #12
0
 public function toJSON($asArray = false, $requestParams = array())
 {
     if (!$this->loaded) {
         $this->load();
     }
     $arr = array('value' => $this->value, 'version' => $this->version);
     if ($asArray) {
         return $arr;
     }
     return Zotero_Utilities::formatJSON($arr);
 }
 public function groups()
 {
     $groupID = $this->objectGroupID;
     //
     // Add a group
     //
     if ($this->method == 'POST') {
         if (!$this->permissions->isSuper()) {
             $this->e403();
         }
         if ($groupID) {
             $this->e400("POST requests cannot end with a groupID (did you mean PUT?)");
         }
         try {
             $group = @new SimpleXMLElement($this->body);
         } catch (Exception $e) {
             $this->e400("{$this->method} data is not valid XML");
         }
         if ((int) $group['id']) {
             $this->e400("POST requests cannot contain a groupID in '" . $this->body . "'");
         }
         $fields = $this->getFieldsFromGroupXML($group);
         Zotero_DB::beginTransaction();
         try {
             $group = new Zotero_Group();
             foreach ($fields as $field => $val) {
                 $group->{$field} = $val;
             }
             $group->save();
         } catch (Exception $e) {
             if (strpos($e->getMessage(), "Invalid") === 0) {
                 $this->e400($e->getMessage() . " in " . $this->body . "'");
             }
             switch ($e->getCode()) {
                 case Z_ERROR_GROUP_NAME_UNAVAILABLE:
                     $this->e400($e->getMessage());
                 default:
                     $this->handleException($e);
             }
         }
         $this->queryParams['content'] = array('full');
         $this->responseXML = $group->toAtom($this->queryParams);
         Zotero_DB::commit();
         $url = Zotero_API::getGroupURI($group);
         $this->responseCode = 201;
         header("Location: " . $url, false, 201);
         $this->end();
     }
     //
     // Update a group
     //
     if ($this->method == 'PUT') {
         if (!$this->permissions->isSuper()) {
             $this->e403();
         }
         if (!$groupID) {
             $this->e400("PUT requests must end with a groupID (did you mean POST?)");
         }
         try {
             $group = @new SimpleXMLElement($this->body);
         } catch (Exception $e) {
             $this->e400("{$this->method} data is not valid XML");
         }
         $fields = $this->getFieldsFromGroupXML($group);
         // Group id is optional, but, if it's there, make sure it matches
         $id = (string) $group['id'];
         if ($id && $id != $groupID) {
             $this->e400("Group ID {$id} does not match group ID {$groupID} from URI");
         }
         Zotero_DB::beginTransaction();
         try {
             $group = Zotero_Groups::get($groupID);
             if (!$group) {
                 $this->e404("Group {$groupID} does not exist");
             }
             foreach ($fields as $field => $val) {
                 $group->{$field} = $val;
             }
             if ($this->ifUnmodifiedSince && strtotime($group->dateModified) > $this->ifUnmodifiedSince) {
                 $this->e412();
             }
             $group->save();
         } catch (Exception $e) {
             if (strpos($e->getMessage(), "Invalid") === 0) {
                 $this->e400($e->getMessage() . " in " . $this->body . "'");
             } else {
                 if ($e->getCode() == Z_ERROR_GROUP_DESCRIPTION_TOO_LONG) {
                     $this->e400($e->getMessage());
                 }
             }
             $this->handleException($e);
         }
         $this->queryParams['content'] = array('full');
         $this->responseXML = $group->toAtom($this->queryParams);
         Zotero_DB::commit();
         $this->end();
     }
     //
     // Delete a group
     //
     if ($this->method == 'DELETE') {
         if (!$this->permissions->isSuper()) {
             $this->e403();
         }
         if (!$groupID) {
             $this->e400("DELETE requests must end with a groupID");
         }
         Zotero_DB::beginTransaction();
         $group = Zotero_Groups::get($groupID);
         if (!$group) {
             $this->e404("Group {$groupID} does not exist");
         }
         $group->erase();
         Zotero_DB::commit();
         header("HTTP/1.1 204 No Content");
         exit;
     }
     //
     // View one or more groups
     //
     // Single group
     if ($groupID) {
         $group = Zotero_Groups::get($groupID);
         if (!$this->permissions->canAccess($this->objectLibraryID)) {
             $this->e403();
         }
         if (!$group) {
             $this->e404("Group not found");
         }
         if ($this->apiVersion >= 3) {
             $this->libraryVersion = $group->version;
         } else {
             header("ETag: " . $group->etag);
         }
         if ($this->method == 'HEAD') {
             $this->end();
         }
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = $group->toAtom($this->queryParams);
                 break;
             case 'json':
                 $json = $group->toResponseJSON($this->queryParams);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     } else {
         if ($this->objectUserID) {
             $title = Zotero_Users::getUsername($this->objectUserID) . "’s Groups";
         } else {
             // For now, only root can do unrestricted group searches
             if (!$this->permissions->isSuper()) {
                 $this->e403();
             }
             $title = "Groups";
         }
         try {
             $results = Zotero_Groups::getAllAdvanced($this->objectUserID, $this->queryParams, $this->permissions);
         } catch (Exception $e) {
             switch ($e->getCode()) {
                 case Z_ERROR_INVALID_GROUP_TYPE:
                     $this->e400($e->getMessage());
             }
             throw $e;
         }
         $options = ['action' => $this->action, 'uri' => $this->uri, 'results' => $results, 'requestParams' => $this->queryParams, 'permissions' => $this->permissions, 'head' => $this->method == 'HEAD'];
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_API::multiResponse(array_merge($options, ['title' => $title]));
                 break;
             case 'json':
                 Zotero_API::multiResponse($options);
                 break;
             case 'etags':
             case 'versions':
                 $prop = substr($this->queryParams['format'], 0, -1);
                 // remove 's'
                 $newResults = [];
                 foreach ($results['results'] as $group) {
                     $newResults[$group->id] = $group->{$prop};
                 }
                 $options['results']['results'] = $newResults;
                 Zotero_API::multiResponse($options, 'versions');
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     }
     $this->end();
 }
Exemple #14
0
 public function keys()
 {
     $userID = $this->objectUserID;
     $key = $this->objectName;
     $this->allowMethods(['GET', 'POST', 'PUT', 'DELETE']);
     if ($this->method == 'GET') {
         // Single key
         if ($key) {
             $keyObj = Zotero_Keys::getByKey($key);
             if (!$keyObj) {
                 $this->e404("Key not found");
             }
             // /users/<userID>/keys/<keyID> (deprecated)
             if ($userID) {
                 // If we have a userID, make sure it matches
                 if ($keyObj->userID != $userID) {
                     $this->e404("Key not found");
                 }
             } else {
                 if ($this->apiVersion < 3) {
                     $this->e404();
                 }
             }
             if ($this->apiVersion >= 3) {
                 $json = $keyObj->toJSON();
                 // If not super-user, don't include name or recent IP addresses
                 if (!$this->permissions->isSuper()) {
                     unset($json['dateAdded']);
                     unset($json['lastUsed']);
                     unset($json['name']);
                     unset($json['recentIPs']);
                 }
                 header('application/json');
                 echo Zotero_Utilities::formatJSON($json);
             } else {
                 $this->responseXML = $keyObj->toXML();
                 // If not super-user, don't include name or recent IP addresses
                 if (!$this->permissions->isSuper()) {
                     unset($this->responseXML['dateAdded']);
                     unset($this->responseXML['lastUsed']);
                     unset($this->responseXML->name);
                     unset($this->responseXML->recentIPs);
                 }
             }
         } else {
             if (!$this->permissions->isSuper()) {
                 $this->e403();
             }
             $keyObjs = Zotero_Keys::getUserKeys($userID);
             if ($keyObjs) {
                 if ($this->apiVersion >= 3) {
                     $json = [];
                     foreach ($keyObjs as $keyObj) {
                         $json[] = $keyObj->toJSON();
                     }
                     echo Zotero_Utilities::formatJSON($json);
                 } else {
                     $xml = new SimpleXMLElement('<keys/>');
                     $domXML = dom_import_simplexml($xml);
                     foreach ($keyObjs as $keyObj) {
                         $keyXML = $keyObj->toXML();
                         $domKeyXML = dom_import_simplexml($keyXML);
                         $node = $domXML->ownerDocument->importNode($domKeyXML, true);
                         $domXML->appendChild($node);
                     }
                     $this->responseXML = $xml;
                 }
             }
         }
     } else {
         if ($this->method == 'DELETE') {
             if (!$key) {
                 $this->e400("DELETE requests must end with a key");
             }
             Zotero_DB::beginTransaction();
             $keyObj = Zotero_Keys::getByKey($key);
             if (!$keyObj) {
                 $this->e404("Key '{$key}' does not exist");
             }
             $keyObj->erase();
             Zotero_DB::commit();
             header("HTTP/1.1 204 No Content");
             exit;
         } else {
             // Require super-user for modifications
             if (!$this->permissions->isSuper()) {
                 $this->e403();
             }
             if ($this->method == 'POST') {
                 if ($key) {
                     $this->e400("POST requests cannot end with a key (did you mean PUT?)");
                 }
                 if ($this->apiVersion >= 3) {
                     $json = json_decode($this->body, true);
                     if (!$json) {
                         $this->e400("{$this->method} data is not valid JSON");
                     }
                     if (!empty($json['key'])) {
                         $this->e400("POST requests cannot contain a key in '" . $this->body . "'");
                     }
                     $fields = $this->getFieldsFromJSON($json);
                 } else {
                     try {
                         $keyXML = @new SimpleXMLElement($this->body);
                     } catch (Exception $e) {
                         $this->e400("{$this->method} data is not valid XML");
                     }
                     if (!empty($key['key'])) {
                         $this->e400("POST requests cannot contain a key in '" . $this->body . "'");
                     }
                     $fields = $this->getFieldsFromKeyXML($keyXML);
                 }
                 Zotero_DB::beginTransaction();
                 try {
                     $keyObj = new Zotero_Key();
                     $keyObj->userID = $userID;
                     foreach ($fields as $field => $val) {
                         if ($field == 'access') {
                             foreach ($val as $access) {
                                 $this->setKeyPermissions($keyObj, $access);
                             }
                         } else {
                             $keyObj->{$field} = $val;
                         }
                     }
                     $keyObj->save();
                 } catch (Exception $e) {
                     if ($e->getCode() == Z_ERROR_KEY_NAME_TOO_LONG) {
                         $this->e400($e->getMessage());
                     }
                     $this->handleException($e);
                 }
                 if ($this->apiVersion >= 3) {
                     header('application/json');
                     echo Zotero_Utilities::formatJSON($keyObj->toJSON());
                 } else {
                     $this->responseXML = $keyObj->toXML();
                 }
                 Zotero_DB::commit();
                 $url = Zotero_API::getKeyURI($keyObj);
                 $this->responseCode = 201;
                 header("Location: " . $url, false, 201);
             } else {
                 if ($this->method == 'PUT') {
                     if (!$key) {
                         $this->e400("PUT requests must end with a key (did you mean POST?)");
                     }
                     if ($this->apiVersion >= 3) {
                         $json = json_decode($this->body, true);
                         if (!$json) {
                             $this->e400("{$this->method} data is not valid JSON");
                         }
                         $fields = $this->getFieldsFromJSON($json);
                     } else {
                         try {
                             $keyXML = @new SimpleXMLElement($this->body);
                         } catch (Exception $e) {
                             $this->e400("{$this->method} data is not valid XML");
                         }
                         $fields = $this->getFieldsFromKeyXML($keyXML);
                     }
                     // Key attribute is optional, but, if it's there, make sure it matches
                     if (isset($fields['key']) && $fields['key'] != $key) {
                         $this->e400("Key '{$fields['key']}' does not match key '{$key}' from URI");
                     }
                     Zotero_DB::beginTransaction();
                     try {
                         $keyObj = Zotero_Keys::getByKey($key);
                         if (!$keyObj) {
                             $this->e404("Key '{$key}' does not exist");
                         }
                         foreach ($fields as $field => $val) {
                             if ($field == 'access') {
                                 foreach ($val as $access) {
                                     $this->setKeyPermissions($keyObj, $access);
                                 }
                             } else {
                                 $keyObj->{$field} = $val;
                             }
                         }
                         $keyObj->save();
                     } catch (Exception $e) {
                         if ($e->getCode() == Z_ERROR_KEY_NAME_TOO_LONG) {
                             $this->e400($e->getMessage());
                         }
                         $this->handleException($e);
                     }
                     if ($this->apiVersion >= 3) {
                         echo Zotero_Utilities::formatJSON($keyObj->toJSON());
                     } else {
                         $this->responseXML = $keyObj->toXML();
                     }
                     Zotero_DB::commit();
                 }
             }
         }
     }
     if ($this->apiVersion >= 3) {
         $this->end();
     } else {
         header('Content-Type: application/xml');
         $xmlstr = $this->responseXML->asXML();
         $doc = new DOMDocument('1.0');
         $doc->loadXML($xmlstr);
         $doc->formatOutput = true;
         echo $doc->saveXML();
         exit;
     }
 }
 public function settings()
 {
     if ($this->apiVersion < 2) {
         $this->e404();
     }
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         Zotero_DB::beginTransaction();
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     // Single setting
     if ($this->singleObject) {
         $this->allowMethods(array('GET', 'PUT', 'DELETE'));
         $setting = Zotero_Settings::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if (!$setting) {
             if ($this->method == 'PUT') {
                 $setting = new Zotero_Setting();
                 $setting->libraryID = $this->objectLibraryID;
                 $setting->name = $this->objectKey;
             } else {
                 $this->e404("Setting not found");
             }
         }
         if ($this->isWriteMethod()) {
             if ($this->method == 'PUT') {
                 $json = $this->jsonDecode($this->body);
                 $objectVersionValidated = $this->checkSingleObjectWriteVersion('setting', $setting, $json);
             }
             $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
             // Update setting
             if ($this->method == 'PUT') {
                 $changed = Zotero_Settings::updateFromJSON($setting, $json, $this->queryParams, $this->userID, $objectVersionValidated ? 0 : 2);
                 // If not updated, return the original library version
                 if (!$changed) {
                     $this->libraryVersion = Zotero_Libraries::getOriginalVersion($this->objectLibraryID);
                     Zotero_DB::rollback();
                     $this->e204();
                 }
             } else {
                 if ($this->method == 'DELETE') {
                     Zotero_Settings::delete($this->objectLibraryID, $this->objectKey);
                 } else {
                     throw new Exception("Unexpected method {$this->method}");
                 }
             }
             Zotero_DB::commit();
             $this->e204();
         } else {
             $this->libraryVersion = $setting->version;
             $json = $setting->toJSON(true, $this->queryParams);
             echo Zotero_Utilities::formatJSON($json);
         }
     } else {
         $this->allowMethods(array('GET', 'POST'));
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         // Create a setting
         if ($this->method == 'POST') {
             $obj = $this->jsonDecode($this->body);
             $changed = Zotero_Settings::updateMultipleFromJSON($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $libraryTimestampChecked ? 0 : 1, null);
             // If not updated, return the original library version
             if (!$changed) {
                 $this->libraryVersion = Zotero_Libraries::getOriginalVersion($this->objectLibraryID);
             }
             Zotero_DB::commit();
             $this->e204();
         } else {
             $settings = Zotero_Settings::search($this->objectLibraryID, $this->queryParams);
             $json = new stdClass();
             foreach ($settings as $setting) {
                 $json->{$setting->name} = $setting->toJSON(true, $this->queryParams);
             }
             echo Zotero_Utilities::formatJSON($json);
         }
     }
     $this->end();
 }
Exemple #16
0
	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 searches()
 {
     if ($this->apiVersion < 2) {
         $this->e404();
     }
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     $results = array();
     // Single search
     if ($this->singleObject) {
         $this->allowMethods(['HEAD', 'GET', 'PUT', 'PATCH', 'DELETE']);
         $search = Zotero_Searches::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if ($this->isWriteMethod()) {
             $search = $this->handleObjectWrite('search', $search ? $search : null);
             $this->e204();
         }
         if (!$search) {
             $this->e404("Search not found");
         }
         $this->libraryVersion = $search->version;
         if ($this->method == 'HEAD') {
             $this->end();
         }
         // Display search
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = $search->toAtom($this->queryParams);
                 break;
             case 'json':
                 $json = $search->toResponseJSON($this->queryParams, $this->permissions);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     } else {
         $this->allowMethods(['HEAD', 'GET', 'POST', 'DELETE']);
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         // Create a search
         if ($this->method == 'POST') {
             $this->queryParams['format'] = 'writereport';
             $obj = $this->jsonDecode($this->body);
             $results = Zotero_Searches::updateMultipleFromJSON($obj, $this->objectLibraryID, $this->queryParams, $this->userID, $libraryTimestampChecked ? 0 : 1, null);
             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
             }
         } else {
             if ($this->method == 'DELETE') {
                 Zotero_DB::beginTransaction();
                 foreach ($this->queryParams['searchKey'] as $searchKey) {
                     Zotero_Searches::delete($this->objectLibraryID, $searchKey);
                 }
                 Zotero_DB::commit();
                 $this->e204();
             } else {
                 $title = "Searches";
                 $results = Zotero_Searches::search($this->objectLibraryID, $this->queryParams);
             }
         }
         $options = ['action' => $this->action, 'uri' => $this->uri, 'results' => $results, 'requestParams' => $this->queryParams, 'permissions' => $this->permissions, 'head' => $this->method == 'HEAD'];
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_API::multiResponse(array_merge($options, ['title' => $this->getFeedNamePrefix($this->objectLibraryID) . $title]));
                 break;
             case 'json':
             case 'keys':
             case 'versions':
             case 'writereport':
                 Zotero_API::multiResponse($options);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     }
     $this->end();
 }
Exemple #18
0
 public static function createJSONResponse($entries, array $queryParams, Zotero_Permissions $permissions = null)
 {
     $json = [];
     foreach ($entries as $entry) {
         $json[] = $entry->toResponseJSON($queryParams, $permissions);
     }
     return Zotero_Utilities::formatJSON($json);
 }
 public function newItem()
 {
     if (empty($_GET['itemType'])) {
         $this->e400("'itemType' not provided");
     }
     $itemType = $_GET['itemType'];
     if ($itemType == 'attachment') {
         if (empty($_GET['linkMode'])) {
             $this->e400("linkMode required for itemType=attachment");
         }
         $linkModeName = $_GET['linkMode'];
         try {
             $linkMode = Zotero_Attachments::linkModeNameToNumber(strtoupper($linkModeName));
         } catch (Exception $e) {
             $this->e400("Invalid linkMode '{$linkModeName}'");
         }
     }
     $itemTypeID = Zotero_ItemTypes::getID($itemType);
     if (!$itemTypeID) {
         $this->e400("Invalid item type '{$itemType}'");
     }
     // TODO: check If-Modified-Since and return 304 if not changed
     $cacheVersion = 1;
     $cacheKey = "newItemJSON" . "_" . $this->apiVersion . "_" . $itemTypeID . "_" . $cacheVersion;
     if ($itemType == 'attachment') {
         $cacheKey .= "_" . $linkMode;
     }
     $cacheKey .= '_' . $this->apiVersion;
     $ttl = 60;
     $json = Z_Core::$MC->get($cacheKey);
     if ($json) {
         header("Content-Type: application/json");
         echo $json;
         exit;
     }
     // Generate template
     $json = array('itemType' => $itemType);
     if ($itemType == 'attachment') {
         $json['linkMode'] = $linkModeName;
     }
     $fieldIDs = Zotero_ItemFields::getItemTypeFields($itemTypeID);
     $first = true;
     foreach ($fieldIDs as $fieldID) {
         $fieldName = Zotero_ItemFields::getName($fieldID);
         // Before v3, computerProgram's 'versionNumber' was just 'version'
         if ($this->apiVersion < 3 && $fieldID == 81) {
             $fieldName = 'version';
         }
         if ($itemType == 'attachment' && $fieldName == 'url' && !preg_match('/_url$/', $linkModeName)) {
             continue;
         }
         $json[$fieldName] = "";
         if ($first && $itemType != 'note' && $itemType != 'attachment') {
             $creatorTypeID = Zotero_CreatorTypes::getPrimaryIDForType($itemTypeID);
             $creatorTypeName = Zotero_CreatorTypes::getName($creatorTypeID);
             $json['creators'] = array(array('creatorType' => $creatorTypeName, 'firstName' => '', 'lastName' => ''));
             $first = false;
         }
     }
     if ($itemType == 'note' || $itemType == 'attachment') {
         $json['note'] = '';
     }
     $json['tags'] = array();
     if ($this->apiVersion >= 2) {
         $json['collections'] = array();
         $json['relations'] = new stdClass();
     }
     if ($this->apiVersion == 1) {
         if ($itemType != 'note' && $itemType != 'attachment') {
             $json['attachments'] = array();
             $json['notes'] = array();
         }
     }
     if ($itemType == 'attachment') {
         $json['contentType'] = '';
         $json['charset'] = '';
         if (preg_match('/^imported_/', $linkModeName)) {
             $json['filename'] = '';
             $json['md5'] = null;
             $json['mtime'] = null;
             //$json['zip'] = false;
         }
     }
     header("Content-Type: application/json");
     $json = Zotero_Utilities::formatJSON($json);
     Z_Core::$MC->set($cacheKey, $json, $ttl);
     echo $json;
     exit;
 }