/** * Load a single item by itemKey only if it belongs to a specific collection * * @param Zotero_Library $library * @param string $itemKey * @param string $collectionKey * @return Zotero_Item */ function fetchCollectionItem($library, $itemKey, $collectionKey) { $citemKey = $itemKey . ','; //hackish way to get a single item by itemKey + collectionKey by forcing itemKey into querystring $aparams = array('target' => 'items', 'content' => 'json', 'itemKey' => $itemKey, 'collectionKey' => $collectionKey); $reqUrl = $library->apiRequestUrl($aparams) . $library->apiQueryString($aparams); $response = $library->_request($reqUrl, 'GET'); if ($response->isError()) { return false; throw new Exception("Error fetching items"); } $body = $response->getRawBody(); $doc = new DOMDocument(); $doc->loadXml($body); $entries = $doc->getElementsByTagName("entry"); if (!$entries->length) { return false; throw new Exception("no item with specified key found"); } else { $entry = $entries->item(0); $item = new Zotero_Item($entry); $library->items->addItem($item); return $item; } }
public function getChildren() { //short circuit if has item has no children if (!$this->numChildren) { //} || (this.parentItemKey !== false)){ return array(); } $config = array('target' => 'children', 'libraryType' => $this->owningLibrary->libraryType, 'libraryID' => $this->owningLibrary->libraryID, 'itemKey' => $this->itemKey, 'content' => 'json'); $requestUrl = $this->owningLibrary->apiRequestString($config); $response = $this->owningLibrary->_request($requestUrl, 'GET'); //load response into item objects $fetchedItems = array(); if ($response->isError()) { return false; throw new Exception("Error fetching items"); } $feed = new Zotero_Feed($response->getRawBody()); $fetchedItems = $this->owningLibrary->items->addItemsFromFeed($feed); return $fetchedItems; }
<?php require_once './user_writing_config.php'; //library credentials require_once '../build/libZoteroSingle.php'; //create the zotero library object which will be our interface for interacting with the Zotero API $zlib = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); $zItems = array(); for ($i = 0; $i < 70; $i++) { $item = $zlib->getTemplateItem('webpage'); $item->set('title', 'zotero webpage item'); $zItems[] = $item; } #make the request to save the items to the Zotero server $writtenItems = $zlib->items->writeItems($zItems); #individual items may fail even if the request goes through, so we should check each one for errors foreach ($writtenItems as $item) { if ($item->writeFailure != false) { echo "Failed writing item {$item->writeFailure['key']} - {$item->get('title')}\n"; echo "Status code: {$item->writeFailure['code']}\n"; echo "Message: {$item->writeFailure['message']}\n\n"; } else { echo "Item successfully created. itemKey: {$item->get('itemKey')} - {$item->get('title')}"; } } #get the version of the last item to use for delete requests $version = $writtenItems[count($writtenItems) - 1]->get('itemVersion'); #split written items into chunks since we can only delete 50 at a time $chunks = array_chunk($writtenItems, 50); foreach ($chunks as $chunk) { $deletedItemResponse = $zlib->items->deleteItems($chunk, $version);
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); $library->setCacheTtl(90); //load a couple items with multiple content types $items = $library->fetchItemsTop(array('limit' => 10, 'content' => 'bib,citation,coins', 'linkwrap' => 1, 'style' => 'chicago-fullnote-bibliography')); ?> <html> <head> <title>Multi-Content</title> <meta charset="utf-8"> </head> <body> <h2>Bib-Content</h2> <?foreach($items as $item):?> <? $doc = new DOMDocument(); $doc->loadXml($item->bibContent); $linkNodes = $doc->getElementsByTagName("a"); foreach($linkNodes as $node){ $node->nodeValue = "Link"; } $newBibContent = $doc->saveXML(); ?> <p><?php echo $newBibContent; ?> </p>
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //get permissions for the key $userID = ''; $key = ''; $permissions = $library->getKeyPermissions($userID, $key); ?> <html> <head> <title>Key Permissions</title> <meta charset="utf-8"> </head> <body> <h2>Key Permissions</h2> <?if($key == ''):?> No key specified in library. <?else:?> <?php echo nl2br(print_r($permissions, true)); ?> <?endif;?> </body> </html>
<?php require_once './user_writing_config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $userSlug, $apiKey); //create a new item of type book $newItem = $library->getTemplateItem('book'); $newItem->set('title', 'This is a book'); $newItem->set('abstractNote', 'Created using a zotero php library and the write api'); $createItemResponse = $library->createItem($newItem); if ($createItemResponse->isError()) { echo $createItemResponse->getStatus() . "\n"; echo $createItemResponse->getBody() . "\n"; die("Error creating Zotero item\n\n"); } else { //load the item into the library so it is included and has the itemKey and etag //and anything else the api populates that we didn't set in our item $createItemFeed = new Zotero_Feed($createItemResponse->getBody()); $createdItem = $library->items->addItemsFromFeed($createItemFeed); $createdItem = $createdItem[0]; echo "Item created\n\n\n<br />"; } $existingItem = new Zotero_Item($createItemResponse->getBody()); //add child note $newNoteItem = $library->getTemplateItem('note'); $addNoteResponse = $library->addNotes($existingItem, $newNoteItem); if ($addNoteResponse->isError()) { echo $addNoteResponse->getStatus() . "\n"; echo $addNoteResponse->getBody() . "\n"; die("error adding child note to item");
<th></th> <td><input type="submit" value="Add Items" /></td> </tr> </table> </form> <?php error_reporting(E_ALL | E_STRICT); ini_set('display_startup_errors', 1); ini_set('display_errors', 1); require_once '../build/libZoteroSingle.php'; if (!empty($_POST)) { $libraryID = $_POST['libraryID']; $libraryType = $_POST['libraryType']; $apiKey = $_POST['apiKey']; $starredJson = file_get_contents($_FILES['jsonfile']['tmp_name']); $zlib = new Zotero_Library($libraryType, $libraryID, '', $apiKey); $starredCollection = $zlib->createCollection('Google Reader Starred'); if ($starredCollection === false || $starredCollection->writeFailure != false) { print "<p>Error creating collection</p>"; var_dump($zlib->getLastResponse()); var_dump($starredCollection->writeFailure); die; } print "<p>New Zotero collection created for google reader starred items with collectionKey {$starredCollection->get('collectionKey')}</p>"; //read the starred items from the json and create a Zotero item for each one $starredObject = json_decode($starredJson, true); $starredReaderItems = $starredObject['items']; $zItems = array(); foreach ($starredReaderItems as $readerItem) { print "<p>Reader starred item: {$readerItem['title']}</p>"; $item = $zlib->getTemplateItem('webpage');
function shortcode($attributes) { // extract the shortcode attributes extract(shortcode_atts(array('library_type' => false, 'library_id' => false, 'library_slug' => "", 'api_key' => false, 'item_key' => false, 'collection_key' => false, 'content' => 'bib,coins', 'style' => false, 'order' => 'creator', 'sort' => 'asc', 'limit' => "100", 'format' => false, 'tag_name' => false, 'cache_time' => "3600"), $attributes)); $params = array(); if ($collection_key) { $params['collectionKey'] = $collection_key; } if ($content) { $params['content'] = $content; } if ($style) { $params['style'] = $style; } if ($order) { $params['order'] = $order; } if ($sort) { $params['sort'] = $sort; } if ($limit) { $totalItemLimit = $limit; } if ($format) { $params['format'] = $format; } if ($item_key) { $params['itemKey'] = $item_key; } $base_url = "http://www.zotero.org"; $library = new Zotero_Library($library_type, $library_id, $library_slug, $api_key, $base_url, $cache_time); // code to step through multiple requests for bibliographies longer than 100 items //start at the beginning of our list by setting an offset of 0 $offset = 0; //limit to 100 items per http request //this is the maximum number of items the API will return in a single request $perRequestLimit = 100; //keep count of the items we've gotten $fetchedItemsCount = 0; //keep track of whether there are more items to fetch $moreItems = true; //where we'll keep the list of items we retrieve $items = array(); //while there are more items and we haven't gotten to our limit yet while ($fetchedItemsCount < $totalItemLimit && $moreItems) { //fetching items starting at $offset with $perRequestLimit items per request $fetchedItems = $library->fetchItemsTop(array_merge($params, array('limit' => $perRequestLimit, 'start' => $offset))); //put the items from this last request into our array of items $items = array_merge($items, $fetchedItems); //update the count of items we've got and offset by that amount $fetchedItemsCount += count($fetchedItems); $offset = $fetchedItemsCount; //Zotero_Library keeps track of the last feed it got so we can check if there is a 'next' link //indicating more results to be fetched if (!isset($library->getLastFeed()->links['next'])) { $moreItems = false; } } return $this->display_zotero_items($items); }
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //fetch subcollections of a collection $collections = $library->fetchCollections(array('collectionKey' => '', 'content' => 'json')); $collectionKey = ''; if (count($collections)) { $collectionKey = $collections[0]->collectionKey; } //fetch items from this library $items = $library->fetchItemsTop(array('limit' => 10, 'collectionKey' => $collectionKey)); ?> <html> <head> <title>Collection and Items</title> <meta charset="utf-8"> </head> <body> <h2>Collections</h2> <ul> <?foreach($collections as $collection):?> <li><?php echo $collection->name; ?> : <?php echo $collection->collectionKey; ?> </li>
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); $library->setCacheTtl(300); //load a couple items with multiple content types $items = $library->fetchItems(array('content' => 'bib,coins', 'linkwrap' => 1, 'style' => 'chicago-fullnote-bibliography', 'collectionKey' => $collectionKey)); ?> <html> <head> <title>Publications</title> <meta charset="utf-8"> </head> <body> <h2>Publications</h2> <?php foreach ($items as $item) { ?> <p><?php echo $item->bibContent; ?> <a href="./download.php?itemkey=<?php echo $item->itemKey; ?> ">Download</a></p> <?php echo htmlspecialchars_decode($item->subContents['coins']); ?> <?php
if (empty($_GET['uncached'])) { if ($libraryCacheType == 'file') { if (file_exists($librarySaveFilePath)) { $lcacheString = file_get_contents($librarySaveFilePath); } if ($lcacheString) { $library = unserialize($lcacheString); } } elseif ($libraryCacheType == 'apc') { $library = apc_fetch('zreportlibrarycache'); } } else { apc_clear_cache('user'); } if (empty($library)) { $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey, "http://www.zotero.org", 3600); } $itemKeys = $library->fetchItemKeys(array('collectionKey' => $reportCollectionKey, 'order' => 'date', 'sort' => 'desc')); $unknownItemKeys = array(); foreach ($itemKeys as $key) { if ($library->items->getItem($key) === false && $key != '') { $unknownItemKeys[] = $key; } } $offset = 0; $length = 50; $index = count($unknownItemKeys); try { while ($offset < $index) { if ($index - $offset > $length) { $uindex = $offset + $length;
<?php require_once './user_writing_config.php'; //library credentials require_once '../build/libZoteroSingle.php'; //create the zotero library object which will be our interface for interacting with the Zotero API $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); /* create a new item of type book * getting a template item causes the appropriate fields to be present in the item * without doing this the item doesn't know what fields are valid for this item type * even if we do */ $newBookItem = $library->getTemplateItem('book'); // give the book a title $newBookItem->set('title', "Foo"); //create a note item that we'll attach to the book $newNote = $library->getTemplateItem('note'); $newNote->set('note', "Bar"); //create a second note item we'll also attach $newNote2 = $library->getTemplateItem('note'); $newNote2->set('note', "Baz"); //Attach the items to the book. Attaching them this way means they'll also be //written to the Zotero server when we write the book. $newBookItem->addNote($newNote); $newBookItem->addNote($newNote2); //create a journal article item we'll also create in the library $newJournalItem = $library->getTemplateItem('journalArticle'); $newJournalItem->set('title', 'Bat'); //write multiple items in a single request //we only pass in the book and journal items, since the notes go with the book //(Note that we could also create the notes separately by giving them a parentItem,
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //get some tags $tags = $library->fetchTags(array('limit' => 20, 'order' => 'title', 'sort' => 'desc')); ?> <html> <head> <title>Tags</title> <meta charset="utf-8"> </head> <body> <h2>Tags</h2> <ul> <?foreach($tags as $tag):?> <li><?php echo $tag->name; ?> has <?php echo $tag->numItems; ?> items associated with it.</li> <?endforeach;?> </ul> </body> </html>
<?php //library credentials require_once './config.php'; //load the zotero php library require_once '../build/libZoteroSingle.php'; //create a library object to interact with the zotero API $library = new Zotero_Library($libraryType, $libraryID, $userSlug, $apiKey); //use Alternative PHP Cache to save API responses for 30 minutes //this will cache unique api responses so we get faster responses //and don't get rate-limited by the API for making too many requests $library->setCacheTtl(1800); //parameters we'll pass when retrieving items to order by item titles $feedParams = array('order' => 'title'); //restrict the total items we'll fetch to 200 $totalItemLimit = 200; //start at the beginning of our list by setting an offset of 0 $offset = 0; //limit to 100 items per http request //this is the maximum number of items the API will return in a single request $perRequestLimit = 100; //keep count of the items we've gotten $fetchedItemsCount = 0; //keep track of whether there are more items to fetch $moreItems = true; //where we'll keep the list of items we retrieve $items = array(); //while there are more items and we haven't gotten to our limit yet while ($fetchedItemsCount < $totalItemLimit && $moreItems) { echo "fetching items starting at {$offset} with {$perRequestLimit} items per request <br />"; //fetching items starting at $offset with $perRequestLimit items per request
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); if (isset($_GET['userID'])) { $cv = $library->getCV($_GET['userID']); } else { $cv = false; } ?> <html> <head> <title>User C.V.</title> <meta charset="utf-8"> </head> <body> <h2>User C.V.</h2> <?if($cv):?> <?foreach($cv as $section):?> <div class='cv-section' style="padding:5px; margin:5px;"> <h2><?php echo $section['title']; ?> </h2> <?php echo $section['content']; ?> </div> <?endforeach;?>
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //load a couple items with multiple content types $items = $library->fetchItemsTop(array('limit' => 2, 'content' => 'json,bib')); ?> <html> <head> <title>Multi-Content</title> <meta charset="utf-8"> </head> <body> <h2>Multi-Content</h2> <?foreach($items as $item):?> <p>Citation:</p> <p><?php echo $item->bibContent; ?> </p> <p>JSON encoded metadata:</p> <p> <?php echo json_encode($item->apiObject); ?> </p> <?endforeach;?> </body> </html>
<?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //load all itemkeys in the library $itemKeys = $library->fetchItemKeys(); ?> <!DOCTYPE html> <html> <head> <title>Item Keys</title> <meta charset="utf-8"> </head> <body> <p>List of all item keys in the library.</p> <p>There are a total of <?php echo count($itemKeys); ?> items in this library/collection, including top level items and their children (notes/attachments).</p> <ul> <?php foreach ($itemKeys as $itemKey) { ?> <li><?php echo $itemKey; ?> </li> <?php }
<?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); $requestUrl = isset($_GET["requestUrl"]) ? $_GET["requestUrl"] : false; //limit requestUrl to zotero.org if (strpos($requestUrl, 'zotero.org') === false) { die; } //optionally add api key to request here so JS does not need a copy if (isset($addKeyAtProxy) && $addKeyAtProxy === true) { if (strpos($requestUrl, '?') !== false) { $requestUrl .= "&key={$apiKey}"; } else { $requestUrl .= "?key={$apiKey}"; } } //act as transparent proxy until JS lib can make requests directly to api $requestMethod = $_SERVER['REQUEST_METHOD']; //raw body of the request $rawbody = @file_get_contents('php://input'); $relevantHeaders = array("If-Modified-Since", "If-Modified-Since-Version", "Last-Modified", "Last-Modified-Version", "If-Unmodified-Since-Version", "Zotero-Write-Token", "If-Match", "If-None-Match", "Zotero-API-Version", "Backoff", "Retry-After", "Content-Type"); $aheaders = apache_request_headers(); $headers = array(); foreach ($aheaders as $key => $val) { if (in_array($key, $relevantHeaders)) { $headers[$key] = $val; } }
<!DOCTYPE html> <?php //load credentials and library info from our config file require_once './config.php'; //load the zotero php library require_once '../build/libZoteroSingle.php'; //create a library object to interact with the zotero API $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //use Alternative PHP Cache to save API responses for 30 minutes $library->setCacheTtl(1800); //fetch most recently added items from a collection //since the collection will never change we just use a hard coded collection key //that was set in our config file $items = $library->fetchItemsTop(array('limit' => 10, 'collectionKey' => $collectionKey, 'order' => 'dateAdded', 'sort' => 'desc')); //output the page //if the item has a url, we'll turn the title into a link ?> <html> <head> <title>Recent Items</title> <meta charset="utf-8"> </head> <body> <ul> <?foreach($items as $item):?> <li> <?$url = $item->get('url');?> <?if($url):?> <a href="<?php echo $url;
<?php require_once './user_writing_config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //create parent item that our attachments will live under $parentItem = $library->getTemplateItem('book'); $parentItem->set('title', "Attachment Example Parent Book"); //create attachment item and upload imported_file $importedFileItem = $library->getTemplateItem('attachment', 'imported_file'); //create attachment item that is linked_file $linkedFileItem = $library->getTemplateItem('attachment', 'linked_file'); //create attachment item that is imported_url $importedUrlItem = $library->getTemplateItem('attachment', 'imported_url'); //create attachment item that is linked_url $linkedUrlItem = $library->getTemplateItem('attachment', 'linked_url'); //add child attachment //get attachment template echo "adding attachment item\n"; try { $templateItem = $library->getTemplateItem('attachment', 'imported_file'); $templateItem->parentKey = 'HP8M9UQB'; echo "creating attachment \n"; $createAttachmentResponse = $library->createItem($templateItem); if ($createAttachmentResponse->isError()) { echo $createAttachmentResponse->getStatus() . "\n"; echo $createAttachmentResponse->getBody() . "\n"; die("Error creating attachment item\n\n"); } else { //read new item we created
<!DOCTYPE html> <?php require_once './config.php'; //library credentials require_once '../build/libZoteroSingle.php'; $library = new Zotero_Library($libraryType, $libraryID, $librarySlug, $apiKey); //load the items currently in the trash $trashedItems = $library->fetchTrashedItems(array('limit' => 10)); ?> <html> <head> <title>Trash</title> <meta charset="utf-8"> </head> <body> <h2>Trashed Items</h2> <?if(count($trashedItems) == 0):?> <p>There are no items in this library's trash</p> <?else:?> <ul> <?foreach($trashedItems as $item):?> <li><?php echo $item->get('title'); ?> </li> <?endforeach;?> </ul> <?endif;?> </body> </html>