Пример #1
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;
 }
Пример #2
0
	public function toResponseJSON($requestParams=[], Zotero_Permissions $permissions, $sharedData=null) {
		$t = microtime(true);
		
		if (!$this->loaded['primaryData']) {
			$this->loadPrimaryData();
		}
		if (!$this->loaded['itemData']) {
			$this->loadItemData();
		}
		
		// Uncached stuff or parts of the cache key
		$version = $this->version;
		$parent = $this->getSource();
		$isRegularItem = !$parent && $this->isRegularItem();
		$downloadDetails = $permissions->canAccess($this->libraryID, 'files')
								? Zotero_Storage::getDownloadDetails($this)
								: false;
		if ($isRegularItem) {
			$numChildren = $permissions->canAccess($this->libraryID, 'notes')
								? $this->numChildren()
								: $this->numAttachments();
		}
		$libraryType = Zotero_Libraries::getType($this->libraryID);
		
		// Any query parameters that have an effect on the output
		// need to be added here
		$allowedParams = [
			'include',
			'style',
			'css',
			'linkwrap'
		];
		$cachedParams = Z_Array::filterKeys($requestParams, $allowedParams);
		
		$cacheVersion = 1;
		$cacheKey = "jsonEntry_" . $this->libraryID . "/" . $this->id . "_"
			. md5(
				$version
				. json_encode($cachedParams)
				. ($downloadDetails ? 'hasFile' : '')
				// For groups, include the group WWW URL, which can change
				. ($libraryType == 'group' ? Zotero_URI::getItemURI($this, true) : '')
			)
			. "_" . $requestParams['v']
			// For code-based changes
			. "_" . $cacheVersion
			// For data-based changes
			. (isset(Z_CONFIG::$CACHE_VERSION_RESPONSE_JSON_ITEM)
				? "_" . Z_CONFIG::$CACHE_VERSION_RESPONSE_JSON_ITEM
				: "")
			// If there's bib content, include the bib cache version
			. ((in_array('bib', $requestParams['include'])
					&& isset(Z_CONFIG::$CACHE_VERSION_BIB))
				? "_" . Z_CONFIG::$CACHE_VERSION_BIB
				: "");
		
		$cached = Z_Core::$MC->get($cacheKey);
		if (false && $cached) {
			// Make sure numChildren reflects the current permissions
			if ($isRegularItem) {
				$json = json_decode($cached);
				$json['numChildren'] = $numChildren;
				$cached = json_encode($json);
			}
			
			//StatsD::timing("api.items.itemToResponseJSON.cached", (microtime(true) - $t) * 1000);
			//StatsD::increment("memcached.items.itemToResponseJSON.hit");
			
			// Skip the cache every 10 times for now, to ensure cache sanity
			if (!Z_Core::probability(10)) {
				return $cached;
			}
		}
		
		
		$json = [
			'key' => $this->key,
			'version' => $version,
			'library' => Zotero_Libraries::toJSON($this->libraryID)
		];
		
		$json['links'] = [
			'self' => [
				'href' => Zotero_API::getItemURI($this),
				'type' => 'application/json'
			],
			'alternate' => [
				'href' => Zotero_URI::getItemURI($this, true),
				'type' => 'text/html'
			]
		];
		
		if ($parent) {
			$parentItem = Zotero_Items::get($this->libraryID, $parent);
			$json['links']['up'] = [
				'href' => Zotero_API::getItemURI($parentItem),
				'type' => 'application/json'
			];
		}
		
		// If appropriate permissions and the file is stored in ZFS, get file request link
		if ($downloadDetails) {
			$details = $downloadDetails;
			$type = $this->attachmentMIMEType;
			if ($type) {
				$json['links']['enclosure'] = [
					'type' => $type
				];
			}
			$json['links']['enclosure']['href'] = $details['url'];
			if (!empty($details['filename'])) {
				$json['links']['enclosure']['title'] = $details['filename'];
			}
			if (isset($details['size'])) {
				$json['links']['enclosure']['length'] = $details['size'];
			}
		}
		
		// 'meta'
		$json['meta'] = new stdClass;
		
		if (Zotero_Libraries::getType($this->libraryID) == 'group') {
			$createdByUserID = $this->createdByUserID;
			$lastModifiedByUserID = $this->lastModifiedByUserID;
			
			if ($createdByUserID) {
				$json['meta']->createdByUser = Zotero_Users::toJSON($createdByUserID);
			}
			
			if ($lastModifiedByUserID && $lastModifiedByUserID != $createdByUserID) {
				$json['meta']->lastModifiedByUser = Zotero_Users::toJSON($lastModifiedByUserID);
			}
		}
		
		if ($isRegularItem) {
			$val = $this->getCreatorSummary();
			if ($val !== '') {
				$json['meta']->creatorSummary = $val;
			}
			
			$val = $this->getField('date', true, true, true);
			if ($val !== '') {
				$sqlDate = Zotero_Date::multipartToSQL($val);
				if (substr($sqlDate, 0, 4) !== '0000') {
					$json['meta']->parsedDate = Zotero_Date::sqlToISO8601($sqlDate);
				}
			}
			
			$json['meta']->numChildren = $numChildren;
		}
		
		// 'include'
		$include = $requestParams['include'];
		
		foreach ($include as $type) {
			if ($type == 'html') {
				$json[$type] = trim($this->toHTML());
			}
			else if ($type == 'citation') {
				if (isset($sharedData[$type][$this->libraryID . "/" . $this->key])) {
					$html = $sharedData[$type][$this->libraryID . "/" . $this->key];
				}
				else {
					if ($sharedData !== null) {
						//error_log("Citation not found in sharedData -- retrieving individually");
					}
					$html = Zotero_Cite::getCitationFromCiteServer($this, $requestParams);
				}
				$json[$type] = $html;
			}
			else if ($type == 'bib') {
				if (isset($sharedData[$type][$this->libraryID . "/" . $this->key])) {
					$html = $sharedData[$type][$this->libraryID . "/" . $this->key];
				}
				else {
					if ($sharedData !== null) {
						//error_log("Bibliography not found in sharedData -- retrieving individually");
					}
					$html = Zotero_Cite::getBibliographyFromCitationServer([$this], $requestParams);
					
					// Strip prolog
					$html = preg_replace('/^<\?xml.+\n/', "", $html);
					$html = trim($html);
				}
				$json[$type] = $html;
			}
			else if ($type == 'data') {
				$json[$type] = $this->toJSON(true, $requestParams, true);
			}
			else if ($type == 'csljson') {
				$json[$type] = $this->toCSLItem();
			}
			else if (in_array($type, Zotero_Translate::$exportFormats)) {
				$export = Zotero_Translate::doExport([$this], $type);
				$json[$type] = $export['body'];
				unset($export);
			}
		}
		

		// TEMP
		if ($cached) {
			$uncached = Zotero_Utilities::formatJSON($json);
			if ($cached != $uncached) {
				error_log("Cached JSON item entry does not match");
				error_log("  Cached: " . $cached);
				error_log("Uncached: " . $uncached);
				
				//Z_Core::$MC->set($cacheKey, $uncached, 3600); // 1 hour for now
			}
		}
		else {
			/*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 $json;
	}
Пример #3
0
 /**
  * Converts a Zotero_Item object to a SimpleXMLElement Atom object
  *
  * @param	object				$item		Zotero_Item object
  * @param	string				$content
  * @return	SimpleXMLElement					Item data as SimpleXML element
  */
 public static function convertItemToAtom(Zotero_Item $item, $queryParams, $apiVersion = null, $permissions = null, $sharedData = null)
 {
     $content = $queryParams['content'];
     $contentIsHTML = sizeOf($content) == 1 && $content[0] == 'html';
     $contentParamString = urlencode(implode(',', $content));
     $style = $queryParams['style'];
     $entry = '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>';
     $xml = new SimpleXMLElement($entry);
     $title = $item->getDisplayTitle(true);
     $title = $title ? $title : '[Untitled]';
     $xml->title = $title;
     $author = $xml->addChild('author');
     $createdByUserID = null;
     switch (Zotero_Libraries::getType($item->libraryID)) {
         case 'group':
             $createdByUserID = $item->createdByUserID;
             break;
     }
     if ($createdByUserID) {
         $author->name = Zotero_Users::getUsername($createdByUserID);
         $author->uri = Zotero_URI::getUserURI($createdByUserID);
     } else {
         $author->name = Zotero_Libraries::getName($item->libraryID);
         $author->uri = Zotero_URI::getLibraryURI($item->libraryID);
     }
     $id = Zotero_URI::getItemURI($item);
     /*if (!$contentIsHTML) {
     			$id .= "?content=$content";
     		}*/
     $xml->id = $id;
     $xml->published = Zotero_Date::sqlToISO8601($item->getField('dateAdded'));
     $xml->updated = Zotero_Date::sqlToISO8601($item->getField('dateModified'));
     $link = $xml->addChild("link");
     $link['rel'] = "self";
     $link['type'] = "application/atom+xml";
     $href = Zotero_Atom::getItemURI($item);
     if (!$contentIsHTML) {
         $href .= "?content={$contentParamString}";
     }
     $link['href'] = $href;
     $parent = $item->getSource();
     if ($parent) {
         // TODO: handle group items?
         $parentItem = Zotero_Items::get($item->libraryID, $parent);
         $link = $xml->addChild("link");
         $link['rel'] = "up";
         $link['type'] = "application/atom+xml";
         $href = Zotero_Atom::getItemURI($parentItem);
         if (!$contentIsHTML) {
             $href .= "?content={$contentParamString}";
         }
         $link['href'] = $href;
     }
     $link = $xml->addChild('link');
     $link['rel'] = 'alternate';
     $link['type'] = 'text/html';
     $link['href'] = Zotero_URI::getItemURI($item);
     // If appropriate permissions and the file is stored in ZFS, get file request link
     if ($permissions && $permissions->canAccess($item->libraryID, 'files')) {
         $details = Zotero_S3::getDownloadDetails($item);
         if ($details) {
             $link = $xml->addChild('link');
             $link['rel'] = 'enclosure';
             $type = $item->attachmentMIMEType;
             if ($type) {
                 $link['type'] = $type;
             }
             $link['href'] = $details['url'];
             if (!empty($details['filename'])) {
                 $link['title'] = $details['filename'];
             }
             if (!empty($details['size'])) {
                 $link['length'] = $details['size'];
             }
         }
     }
     $xml->addChild('zapi:key', $item->key, Zotero_Atom::$nsZoteroAPI);
     $xml->addChild('zapi:itemType', Zotero_ItemTypes::getName($item->itemTypeID), Zotero_Atom::$nsZoteroAPI);
     if ($item->isRegularItem()) {
         $val = $item->creatorSummary;
         if ($val !== '') {
             $xml->addChild('zapi:creatorSummary', htmlspecialchars($val), Zotero_Atom::$nsZoteroAPI);
         }
         $val = substr($item->getField('date', true, true, true), 0, 4);
         if ($val !== '' && $val !== '0000') {
             $xml->addChild('zapi:year', $val, Zotero_Atom::$nsZoteroAPI);
         }
     }
     if (!$parent && $item->isRegularItem()) {
         if ($permissions && !$permissions->canAccess($item->libraryID, 'notes')) {
             $numChildren = $item->numAttachments();
         } else {
             $numChildren = $item->numChildren();
         }
         $xml->addChild('zapi:numChildren', $numChildren, Zotero_Atom::$nsZoteroAPI);
     }
     $xml->addChild('zapi:numTags', $item->numTags(), Zotero_Atom::$nsZoteroAPI);
     $xml->content = '';
     //
     // DOM XML from here on out
     //
     $contentNode = dom_import_simplexml($xml->content);
     $domDoc = $contentNode->ownerDocument;
     $multiFormat = sizeOf($content) > 1;
     // Create a root XML document for multi-format responses
     if ($multiFormat) {
         $contentNode->setAttribute('type', 'application/xml');
         /*$multicontent = $domDoc->createElementNS(
         			Zotero_Atom::$nsZoteroAPI, 'multicontent'
         		);
         		$contentNode->appendChild($multicontent);*/
     }
     foreach ($content as $type) {
         // Set the target to either the main <content>
         // or a <multicontent> <content>
         if (!$multiFormat) {
             $target = $contentNode;
         } else {
             $target = $domDoc->createElementNS(Zotero_Atom::$nsZoteroAPI, 'subcontent');
             $contentNode->appendChild($target);
         }
         $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:type", $type);
         if ($type == 'html') {
             if (!$multiFormat) {
                 $target->setAttribute('type', 'xhtml');
             }
             $div = $domDoc->createElement('div');
             $div->setAttribute('xmlns', Zotero_Atom::$nsXHTML);
             $target->appendChild($div);
             $html = $item->toHTML(true);
             $subNode = dom_import_simplexml($html);
             $importedNode = $domDoc->importNode($subNode, true);
             $div->appendChild($importedNode);
         } else {
             if ($type == 'citation') {
                 if (!$multiFormat) {
                     $target->setAttribute('type', 'xhtml');
                 }
                 if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) {
                     $html = $sharedData[$type][$item->libraryID . "/" . $item->key];
                 } else {
                     if ($sharedData !== null) {
                         error_log("Citation not found in sharedData -- retrieving individually");
                     }
                     $html = Zotero_Cite::getCitationFromCiteServer($item, $style);
                 }
                 $html = new SimpleXMLElement($html);
                 $html['xmlns'] = Zotero_Atom::$nsXHTML;
                 $subNode = dom_import_simplexml($html);
                 $importedNode = $domDoc->importNode($subNode, true);
                 $target->appendChild($importedNode);
             } else {
                 if ($type == 'bib') {
                     if (!$multiFormat) {
                         $target->setAttribute('type', 'xhtml');
                     }
                     if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) {
                         $html = $sharedData[$type][$item->libraryID . "/" . $item->key];
                     } else {
                         if ($sharedData !== null) {
                             error_log("Bibliography not found in sharedData -- retrieving individually");
                         }
                         $html = Zotero_Cite::getBibliographyFromCitationServer(array($item), $style);
                     }
                     $html = new SimpleXMLElement($html);
                     $html['xmlns'] = Zotero_Atom::$nsXHTML;
                     $subNode = dom_import_simplexml($html);
                     $importedNode = $domDoc->importNode($subNode, true);
                     $target->appendChild($importedNode);
                 } else {
                     if ($type == 'json') {
                         $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:etag", $item->etag);
                         $textNode = $domDoc->createTextNode($item->toJSON(false, $queryParams['pprint'], true));
                         $target->appendChild($textNode);
                     } else {
                         if ($type == 'csljson') {
                             $arr = $item->toCSLItem();
                             $mask = JSON_HEX_TAG | JSON_HEX_AMP;
                             if ($queryParams['pprint']) {
                                 $json = Zotero_Utilities::json_encode_pretty($arr, $mask);
                             } else {
                                 $json = json_encode($arr, $mask);
                             }
                             // Until JSON_UNESCAPED_SLASHES is available
                             $json = str_replace('\\/', '/', $json);
                             $textNode = $domDoc->createTextNode($json);
                             $target->appendChild($textNode);
                         } else {
                             if ($type == 'full') {
                                 if (!$multiFormat) {
                                     $target->setAttribute('type', 'xhtml');
                                 }
                                 $fullXML = Zotero_Items::convertItemToXML($item, array(), $apiVersion);
                                 $fullXML->addAttribute("xmlns", Zotero_Atom::$nsZoteroTransfer);
                                 $subNode = dom_import_simplexml($fullXML);
                                 $importedNode = $domDoc->importNode($subNode, true);
                                 $target->appendChild($importedNode);
                             } else {
                                 if (in_array($type, Zotero_Translate::$exportFormats)) {
                                     $export = Zotero_Translate::doExport(array($item), $type);
                                     $target->setAttribute('type', $export['mimeType']);
                                     // Insert XML into document
                                     if (preg_match('/\\+xml$/', $export['mimeType'])) {
                                         // Strip prolog
                                         $body = preg_replace('/^<\\?xml.+\\n/', "", $export['body']);
                                         $subNode = $domDoc->createDocumentFragment();
                                         $subNode->appendXML($body);
                                         $target->appendChild($subNode);
                                     } else {
                                         $textNode = $domDoc->createTextNode($export['body']);
                                         $target->appendChild($textNode);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $xml;
 }
Пример #4
0
 public function items()
 {
     if (($this->method == 'POST' || $this->method == 'PUT') && !$this->body) {
         $this->e400("{$this->method} data not provided");
     }
     $itemIDs = array();
     $responseItems = array();
     $responseKeys = array();
     $totalResults = null;
     //
     // Single item
     //
     if (($this->objectID || $this->objectKey) && !$this->subset) {
         if ($this->fileMode) {
             if ($this->fileView) {
                 $this->allowMethods(array('GET', 'HEAD', 'POST'));
             } else {
                 $this->allowMethods(array('GET', 'PUT', 'POST', 'HEAD', 'PATCH'));
             }
         } else {
             $this->allowMethods(array('GET', 'PUT', 'DELETE'));
         }
         // Check for general library access
         if (!$this->permissions->canAccess($this->objectLibraryID)) {
             //var_dump($this->objectLibraryID);
             //var_dump($this->permissions);
             $this->e403();
         }
         if ($this->objectKey) {
             $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         } else {
             try {
                 $item = Zotero_Items::get($this->objectLibraryID, $this->objectID);
             } catch (Exception $e) {
                 if ($e->getCode() == Z_ERROR_OBJECT_LIBRARY_MISMATCH) {
                     $item = false;
                 } else {
                     throw $e;
                 }
             }
         }
         if (!$item) {
             // Possibly temporary workaround to block unnecessary full syncs
             if ($this->fileMode && $this->method == 'POST') {
                 // If > 2 requests for missing file, trigger a full sync via 404
                 $cacheKey = "apiMissingFile_" . $this->objectLibraryID . "_" . ($this->objectKey ? $this->objectKey : $this->objectID);
                 $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 we have an id, make sure this isn't really an all-numeric key
             if ($this->objectID && strlen($this->objectID) == 8 && preg_match('/[0-9]{8}/', $this->objectID)) {
                 $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectID);
                 if ($item) {
                     $this->objectKey = $this->objectID;
                     unset($this->objectID);
                 }
             }
             if (!$item) {
                 $this->e404("Item does not exist");
             }
         }
         if ($item->isNote() && !$this->permissions->canAccess($this->objectLibraryID, 'notes')) {
             $this->e403();
         }
         // 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 id, redirect to key URL
         if ($this->objectID) {
             $this->allowMethods(array('GET'));
             $qs = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
             header("Location: " . Zotero_API::getItemURI($item) . $qs);
             exit;
         }
         if ($this->scopeObject) {
             switch ($this->scopeObject) {
                 // Remove item from collection
                 case 'collections':
                     $this->allowMethods(array('DELETE'));
                     if (!$this->permissions->canWrite($this->objectLibraryID)) {
                         $this->e403("Write access denied");
                     }
                     $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");
                     }
                     Zotero_DB::beginTransaction();
                     $timestamp = Zotero_Libraries::updateTimestamps($this->objectLibraryID);
                     Zotero_DB::registerTransactionTimestamp($timestamp);
                     $collection->removeItem($item->id);
                     Zotero_DB::commit();
                     $this->e204();
                 default:
                     $this->e400();
             }
         }
         if ($this->method == 'PUT' || $this->method == 'DELETE') {
             if (!$this->permissions->canWrite($this->objectLibraryID)) {
                 $this->e403("Write access denied");
             }
             if (!Z_CONFIG::$TESTING_SITE || empty($_GET['skipetag'])) {
                 if (empty($_SERVER['HTTP_IF_MATCH'])) {
                     $this->e400("If-Match header not provided");
                 }
                 if (!preg_match('/^"?([a-f0-9]{32})"?$/', $_SERVER['HTTP_IF_MATCH'], $matches)) {
                     $this->e400("Invalid ETag in If-Match header");
                 }
                 if ($item->etag != $matches[1]) {
                     $this->e412("ETag does not match current version of item");
                 }
             }
             // Update existing item
             if ($this->method == 'PUT') {
                 $obj = $this->jsonDecode($this->body);
                 Zotero_Items::updateFromJSON($item, $obj, false, null, $this->userID);
                 $this->queryParams['format'] = 'atom';
                 $this->queryParams['content'] = array('json');
                 if ($cacheKey = $this->getWriteTokenCacheKey()) {
                     Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                 }
             } else {
                 Zotero_Items::delete($this->objectLibraryID, $this->objectKey, true);
                 try {
                     Zotero_Processors::notifyProcessors('index');
                 } catch (Exception $e) {
                     Z_Core::logError($e);
                 }
                 $this->e204();
             }
         }
         // Display item
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_Items::convertItemToAtom($item, $this->queryParams, $this->apiVersion, $this->permissions);
                 break;
             case 'bib':
                 echo Zotero_Cite::getBibliographyFromCitationServer(array($item), $this->queryParams['style'], $this->queryParams['css']);
                 exit;
             case 'csljson':
                 $json = Zotero_Cite::getJSONFromItems(array($item), true);
                 if ($this->queryParams['pprint']) {
                     header("Content-Type: text/plain");
                     $json = Zotero_Utilities::json_encode_pretty($json);
                 } else {
                     header("Content-Type: application/vnd.citationstyles.csl+json");
                     $json = json_encode($json);
                 }
                 echo $json;
                 exit;
             default:
                 $export = Zotero_Translate::doExport(array($item), $this->queryParams['format']);
                 if ($this->queryParams['pprint']) {
                     header("Content-Type: text/plain");
                 } else {
                     header("Content-Type: " . $export['mimeType']);
                 }
                 echo $export['body'];
                 exit;
         }
     } else {
         $this->allowMethods(array('GET', 'POST'));
         if (!$this->permissions->canAccess($this->objectLibraryID)) {
             $this->e403();
         }
         $includeTrashed = false;
         $formatAsKeys = $this->queryParams['format'] == 'keys';
         if ($this->scopeObject) {
             $this->allowMethods(array('GET', 'POST'));
             // If id, redirect to key URL
             if ($this->scopeObjectID) {
                 $this->allowMethods(array('GET'));
                 if (!in_array($this->scopeObject, array("collections", "tags"))) {
                     $this->e400();
                 }
                 $className = 'Zotero_' . ucwords($this->scopeObject);
                 $obj = call_user_func(array($className, 'get'), $this->objectLibraryID, $this->scopeObjectID);
                 if (!$obj) {
                     $this->e404("Scope " . substr($this->scopeObject, 0, -1) . " not found");
                 }
                 $base = call_user_func(array('Zotero_API', 'get' . substr(ucwords($this->scopeObject), 0, -1) . 'URI'), $obj);
                 $qs = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
                 header("Location: " . $base . "/items" . $qs);
                 exit;
             }
             switch ($this->scopeObject) {
                 case 'collections':
                     $collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
                     if (!$collection) {
                         $this->e404("Collection not found");
                     }
                     // Add items to collection
                     if ($this->method == 'POST') {
                         if (!$this->permissions->canWrite($this->objectLibraryID)) {
                             $this->e403("Write access denied");
                         }
                         Zotero_DB::beginTransaction();
                         $timestamp = Zotero_Libraries::updateTimestamps($this->objectLibraryID);
                         Zotero_DB::registerTransactionTimestamp($timestamp);
                         $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);
                         Zotero_DB::commit();
                         $this->e204();
                     }
                     $title = "Items in Collection ‘" . $collection->name . "’";
                     $itemIDs = $collection->getChildItems();
                     break;
                 case 'tags':
                     $this->allowMethods(array('GET'));
                     $tagIDs = Zotero_Tags::getIDs($this->objectLibraryID, $this->scopeObjectName);
                     if (!$tagIDs) {
                         $this->e404("Tag not found");
                     }
                     $itemIDs = array();
                     $title = '';
                     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 . "’";
                         }
                         $itemIDs = array_merge($itemIDs, $tag->getLinkedItems(true));
                     }
                     $itemIDs = array_unique($itemIDs);
                     break;
                 default:
                     throw new Exception("Invalid items scope object '{$this->scopeObject}'");
             }
         } 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, false, $formatAsKeys);
             } else {
                 if ($this->subset == 'trash') {
                     $this->allowMethods(array('GET'));
                     $title = "Deleted Items";
                     $itemIDs = Zotero_Items::getDeleted($this->objectLibraryID, true);
                     $includeTrashed = true;
                 } else {
                     if ($this->subset == 'children') {
                         // If we have an id, make sure this isn't really an all-numeric key
                         if ($this->objectID && strlen($this->objectID) == 8 && preg_match('/[0-9]{8}/', $this->objectID)) {
                             $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectID);
                             if ($item) {
                                 $this->objectKey = $this->objectID;
                                 unset($this->objectID);
                             }
                         }
                         // If id, redirect to key URL
                         if ($this->objectID) {
                             $this->allowMethods(array('GET'));
                             $item = Zotero_Items::get($this->objectLibraryID, $this->objectID);
                             if (!$item) {
                                 $this->e404("Item not found");
                             }
                             $qs = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
                             header("Location: " . Zotero_API::getItemURI($item) . '/children' . $qs);
                             exit;
                         }
                         $item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
                         if (!$item) {
                             $this->e404("Item not found");
                         }
                         // Create new child items
                         if ($this->method == 'POST') {
                             if (!$this->permissions->canWrite($this->objectLibraryID)) {
                                 $this->e403("Write access denied");
                             }
                             $obj = $this->jsonDecode($this->body);
                             $keys = Zotero_Items::addFromJSON($obj, $this->objectLibraryID, $item, $this->userID);
                             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                             }
                             $uri = Zotero_API::getItemURI($item) . "/children";
                             $queryString = "itemKey=" . urlencode(implode(",", $keys)) . "&content=json";
                             if ($this->apiKey) {
                                 $queryString .= "&key=" . $this->apiKey;
                             }
                             $uri .= "?" . $queryString;
                             $this->responseCode = 201;
                             $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
                         }
                         // Display items
                         $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') {
                             if (!$this->permissions->canWrite($this->objectLibraryID)) {
                                 $this->e403("Write access denied");
                             }
                             $obj = $this->jsonDecode($this->body);
                             if (isset($obj->url)) {
                                 $response = Zotero_Items::addFromURL($obj, $this->objectLibraryID, $this->userID, $this->getTranslationToken());
                                 if ($response instanceof stdClass) {
                                     header("Content-Type: application/json");
                                     echo json_encode($response->select);
                                     $this->e300();
                                 } else {
                                     if (is_int($response)) {
                                         switch ($response) {
                                             case 501:
                                                 $this->e501("No translators found for URL");
                                                 break;
                                             default:
                                                 $this->e500("Error translating URL");
                                         }
                                     } else {
                                         $keys = $response;
                                     }
                                 }
                             } else {
                                 $keys = Zotero_Items::addFromJSON($obj, $this->objectLibraryID, null, $this->userID);
                             }
                             if (!$keys) {
                                 throw new Exception("No items added");
                             }
                             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
                             }
                             $uri = Zotero_API::getItemsURI($this->objectLibraryID);
                             $queryString = "itemKey=" . urlencode(implode(",", $keys)) . "&content=json";
                             if ($this->apiKey) {
                                 $queryString .= "&key=" . $this->apiKey;
                             }
                             $uri .= "?" . $queryString;
                             $this->responseCode = 201;
                             $this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
                         }
                         $title = "Items";
                         $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, false, $formatAsKeys);
                     }
                 }
             }
             if (!empty($results)) {
                 if ($formatAsKeys) {
                     $responseKeys = $results['keys'];
                 } else {
                     $responseItems = $results['items'];
                 }
                 $totalResults = $results['total'];
             }
         }
         if ($this->queryParams['format'] == 'bib') {
             if (($itemIDs ? sizeOf($itemIDs) : $results['total']) > Zotero_API::$maxBibliographyItems) {
                 $this->e413("Cannot generate bibliography with more than " . Zotero_API::$maxBibliographyItems . " items");
             }
         }
         if ($itemIDs) {
             $this->queryParams['itemIDs'] = $itemIDs;
             $results = Zotero_Items::search($this->objectLibraryID, false, $this->queryParams, $includeTrashed, $formatAsKeys);
             if ($formatAsKeys) {
                 $responseKeys = $results['keys'];
             } else {
                 $responseItems = $results['items'];
             }
             $totalResults = $results['total'];
         } else {
             if (!isset($results)) {
                 if ($formatAsKeys) {
                     $responseKeys = array();
                 } else {
                     $responseItems = array();
                 }
                 $totalResults = 0;
             }
         }
         // Remove notes if not user and not public
         for ($i = 0; $i < sizeOf($responseItems); $i++) {
             if ($responseItems[$i]->isNote() && !$this->permissions->canAccess($responseItems[$i]->libraryID, 'notes')) {
                 array_splice($responseItems, $i, 1);
                 $totalResults--;
                 $i--;
             }
         }
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_Atom::createAtomFeed($this->getFeedNamePrefix($this->objectLibraryID) . $title, $this->uri, $responseItems, $totalResults, $this->queryParams, $this->apiVersion, $this->permissions);
                 break;
             case 'bib':
                 echo Zotero_Cite::getBibliographyFromCitationServer($responseItems, $this->queryParams['style'], $this->queryParams['css']);
                 exit;
             case 'csljson':
                 $json = Zotero_Cite::getJSONFromItems($responseItems, true);
                 if ($this->queryParams['pprint']) {
                     header("Content-Type: text/plain");
                     $json = Zotero_Utilities::json_encode_pretty($json);
                 } else {
                     header("Content-Type: application/vnd.citationstyles.csl+json");
                     $json = json_encode($json);
                 }
                 echo $json;
                 exit;
             case 'keys':
                 if (!$formatAsKeys) {
                     $responseKeys = array();
                     foreach ($responseItems as $item) {
                         $responseKeys[] = $item->key;
                     }
                 }
                 header("Content-Type: text/plain");
                 echo implode("\n", $responseKeys) . "\n";
                 exit;
             default:
                 $export = Zotero_Translate::doExport($responseItems, $this->queryParams['format']);
                 if ($this->queryParams['pprint']) {
                     header("Content-Type: text/plain");
                 } else {
                     header("Content-Type: " . $export['mimeType']);
                 }
                 echo $export['body'];
                 exit;
         }
     }
     $this->end();
 }
Пример #5
0
 private function generateMultiResponse($results, $title = '')
 {
     $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 'bib':
             if ($this->method == 'HEAD') {
                 break;
             }
             if (isset($results['results'])) {
                 echo Zotero_Cite::getBibliographyFromCitationServer($results['results'], $this->queryParams);
             }
             break;
         case 'csljson':
         case 'json':
         case 'keys':
         case 'versions':
         case 'writereport':
             Zotero_API::multiResponse($options);
             break;
         default:
             if ($this->method == 'HEAD') {
                 break;
             }
             $export = Zotero_Translate::doExport($results['results'], $this->queryParams['format']);
             $this->queryParams['format'] = null;
             header("Content-Type: " . $export['mimeType']);
             echo $export['body'];
     }
 }