/** * An object type's primary data cache for a library has to be created before * */ public function testCacheCreatorPrimaryData() { $data = array("title" => "Title", "creators" => array(array("creatorType" => "author", "firstName" => "First", "lastName" => "Last"), array("creatorType" => "editor", "firstName" => "Ed", "lastName" => "McEditor"))); $key = API::createItem("book", $data, $this, 'key'); $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=csljson"); $json = json_decode(API::getContentFromResponse($response)); $this->assertEquals("First", $json->author[0]->given); $this->assertEquals("Last", $json->author[0]->family); $this->assertEquals("Ed", $json->editor[0]->given); $this->assertEquals("McEditor", $json->editor[0]->family); }
/** * @depends testNewSingleCollection */ public function testNewSingleSubcollection($data) { $name = "Test Subcollection"; $parent = $data['key']; $json = array('name' => $name, 'parent' => $parent); $response = API::userPost(self::$config['userID'], "collections?key=" . self::$config['apiKey'], json_encode($json), array("Content-Type: application/json")); $this->assert200($response); $xml = API::getXMLFromResponse($response); $this->assertEquals(1, (int) array_shift($xml->xpath('/atom:feed/zapi:totalResults'))); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $this->assertEquals($name, (string) $json->name); $this->assertEquals($parent, (string) $json->parent); $response = API::userGet(self::$config['userID'], "collections/{$parent}?key=" . self::$config['apiKey']); $this->assert200($response); $xml = API::getXMLFromResponse($response); $this->assertEquals(1, (int) array_shift($xml->xpath('/atom:entry/zapi:numCollections'))); }
public function testMultiContent() { $keys = array_keys(self::$items); $keyStr = implode(',', $keys); $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&itemKey={$keyStr}&content=bib,json"); $this->assert200($response); $xml = API::getXMLFromResponse($response); $this->assertEquals(sizeOf($keys), (int) array_shift($xml->xpath('/atom:feed/zapi:totalResults'))); $entries = $xml->xpath('//atom:entry'); foreach ($entries as $entry) { $key = (string) $entry->children("http://zotero.org/ns/api")->key; $content = $entry->content->asXML(); // Add namespace prefix (from <entry>) $content = str_replace('<content ', '<content xmlns:zapi="http://zotero.org/ns/api" ', $content); // Strip variable key and version $content = preg_replace('%"itemKey": "[A-Z0-9]{8}",(\\s+)"itemVersion": [0-9]+%', '"itemKey": "",$1"itemVersion": 0', $content); $this->assertXmlStringEqualsXmlString(self::$items[$key], $content); } }
public function testSettings() { $settingKey = 'tagColors'; $value = array(array("name" => "_READ", "color" => "#990000")); $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; $lastSyncTimestamp = (int) $xml['timestamp']; $libraryVersion = API::getLibraryVersion(); // Create item via sync $data = '<data version="9"><settings><setting libraryID="' . self::$config['libraryID'] . '" name="' . $settingKey . '">' . htmlspecialchars(json_encode($value)) . '</setting></settings></data>'; $response = Sync::upload(self::$sessionID, $updateKey, $data); Sync::waitForUpload(self::$sessionID, $response, $this); // Check via sync $xml = Sync::updated(self::$sessionID, $lastSyncTimestamp); $updateKey = (string) $xml['updateKey']; $lastSyncTimestamp = $xml['timestamp']; $settingXML = $xml->updated[0]->settings[0]->setting[0]; $this->assertEquals(self::$config['libraryID'], (int) $settingXML['libraryID']); $this->assertEquals($settingKey, (string) $settingXML['name']); $this->assertEquals($value, json_decode((string) $settingXML, true)); // Get setting via API and check value $response = API::userGet(self::$config['userID'], "settings/{$settingKey}?key=" . self::$config['apiKey']); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertNotNull($json); $this->assertEquals($value, $json['value']); $this->assertEquals($libraryVersion + 1, $json['version']); // Delete via sync $xmlstr = '<data version="9">' . '<deleted>' . '<settings>' . '<setting libraryID="' . self::$config['libraryID'] . '" key="' . $settingKey . '"/>' . '</settings>' . '</deleted>' . '</data>'; $response = Sync::upload(self::$sessionID, $updateKey, $xmlstr); $xml = Sync::waitForUpload(self::$sessionID, $response, $this); // Get setting via API and check value $response = API::userGet(self::$config['userID'], "settings/{$settingKey}?key=" . self::$config['apiKey']); $this->assertEquals(404, $response->getStatus()); // Check for missing via sync $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; $lastSyncTimestamp = $xml['timestamp']; $this->assertEquals(0, $xml->updated[0]->settings->count()); $this->assertEquals(1, $xml->updated[0]->deleted[0]->settings[0]->setting->count()); $this->assertEquals(self::$config['libraryID'], (int) $xml->updated[0]->deleted[0]->settings[0]->setting[0]['libraryID']); $this->assertEquals($settingKey, (string) $xml->updated[0]->deleted[0]->settings[0]->setting[0]['key']); }
public function testRelatedItems() { $itemKey1 = API::createItem("audioRecording", array("relations" => array('owl:sameAs' => 'http://zotero.org/groups/1/items/AAAAAAAA')), null, 'key'); $itemURI1 = 'http://zotero.org/users/' . self::$config['userID'] . '/items/' . $itemKey1; $itemKey2 = API::createItem("interview", array("relations" => array('dc:relation' => $itemURI1)), null, 'key'); $itemURI2 = 'http://zotero.org/users/' . self::$config['userID'] . '/items/' . $itemKey2; $itemKey3 = API::createItem("book", null, null, 'key'); $itemURI3 = 'http://zotero.org/users/' . self::$config['userID'] . '/items/' . $itemKey3; $libraryVersion = API::getLibraryVersion(); // Add related items via sync $xml = Sync::updated(self::$sessionID); $updateKey = $xml['updateKey']; $lastSyncTimestamp = $xml['timestamp']; $itemXML1 = array_shift($xml->updated[0]->items[0]->xpath("item[@key='{$itemKey1}']")); $itemXML2 = array_shift($xml->updated[0]->items[0]->xpath("item[@key='{$itemKey2}']")); $itemXML3 = array_shift($xml->updated[0]->items[0]->xpath("item[@key='{$itemKey3}']")); $itemXML1['libraryID'] = self::$config['libraryID']; $itemXML2['libraryID'] = self::$config['libraryID']; $itemXML3['libraryID'] = self::$config['libraryID']; $itemXML1->related = $itemKey2 . ' ' . $itemKey3; $itemXML2->related = $itemKey1; $itemXML3->related = $itemKey1; $xmlstr = '<data version="9">' . '<items>' . $itemXML1->asXML() . $itemXML2->asXML() . $itemXML3->asXML() . '</items>' . '</data>'; $response = Sync::upload(self::$sessionID, $updateKey, $xmlstr); Sync::waitForUpload(self::$sessionID, $response, $this); // Check via API $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&content=json&newer={$libraryVersion}"); $xml = API::getXMLFromResponse($response); // Item 2 already had the relation and shouldn't have been updated $this->assertEquals(2, (int) array_shift($xml->xpath('/atom:feed/zapi:totalResults'))); $itemJSON1 = json_decode(array_shift($xml->xpath("//atom:entry[atom:id='{$itemURI1}']"))->content, 1); $itemJSON3 = json_decode(array_shift($xml->xpath("//atom:entry[atom:id='{$itemURI3}']"))->content, 1); $this->assertInternalType('array', $itemJSON1['relations']['dc:relation']); $this->assertInternalType('string', $itemJSON3['relations']['dc:relation']); $this->assertCount(2, $itemJSON1['relations']['dc:relation']); $this->assertTrue(in_array($itemURI2, $itemJSON1['relations']['dc:relation'])); $this->assertTrue(in_array($itemURI3, $itemJSON1['relations']['dc:relation'])); $this->assertEquals($itemURI1, $itemJSON3['relations']['dc:relation']); }
private function _testNewerAndVersionsFormat($objectType) { $objectTypePlural = API::getPluralObjectType($objectType); $xmlArray = array(); switch ($objectType) { case 'collection': $xmlArray[] = API::createCollection("Name", false, $this); $xmlArray[] = API::createCollection("Name", false, $this); $xmlArray[] = API::createCollection("Name", false, $this); break; case 'item': $xmlArray[] = API::createItem("book", array("title" => "Title"), $this); $xmlArray[] = API::createItem("book", array("title" => "Title"), $this); $xmlArray[] = API::createItem("book", array("title" => "Title"), $this); break; case 'search': $xmlArray[] = API::createSearch("Name", array(array("condition" => "title", "operator" => "contains", "value" => "test")), $this); $xmlArray[] = API::createSearch("Name", array(array("condition" => "title", "operator" => "contains", "value" => "test")), $this); $xmlArray[] = API::createSearch("Name", array(array("condition" => "title", "operator" => "contains", "value" => "test")), $this); } $objects = array(); while ($xml = array_shift($xmlArray)) { $data = API::parseDataFromAtomEntry($xml); $objects[] = array("key" => $data['key'], "version" => $data['version']); } $firstVersion = $objects[0]['version']; $response = API::userGet(self::$config['userID'], "{$objectTypePlural}?key=" . self::$config['apiKey'] . "&format=versions&newer={$firstVersion}"); $this->assert200($response); $json = json_decode($response->getBody(), true); $this->assertNotNull($json); $keys = array_keys($json); $this->assertEquals($objects[2]['key'], array_shift($keys)); $this->assertEquals($objects[2]['version'], array_shift($json)); $this->assertEquals($objects[1]['key'], array_shift($keys)); $this->assertEquals($objects[1]['version'], array_shift($json)); $this->assertEmpty($json); }
public function testCollectionItems() { $collectionKey = API::createCollection('Test', false, $this, 'key'); $xml = API::createItem("book", array('collections' => array($collectionKey)), $this); $data = API::parseDataFromAtomEntry($xml); $itemKey1 = $data['key']; $itemVersion1 = $data['version']; $json = json_decode($data['content']); $this->assertEquals(array($collectionKey), $json->collections); $xml = API::createItem("journalArticle", array('collections' => array($collectionKey)), $this); $data = API::parseDataFromAtomEntry($xml); $itemKey2 = $data['key']; $itemVersion2 = $data['version']; $json = json_decode($data['content']); $this->assertEquals(array($collectionKey), $json->collections); $childItemKey1 = API::createAttachmentItem("linked_url", [], $itemKey1, $this, 'key'); $childItemKey2 = API::createAttachmentItem("linked_url", [], $itemKey2, $this, 'key'); $response = API::userGet(self::$config['userID'], "collections/{$collectionKey}/items?key=" . self::$config['apiKey'] . "&format=keys"); $this->assert200($response); $keys = explode("\n", trim($response->getBody())); $this->assertCount(4, $keys); $this->assertContains($itemKey1, $keys); $this->assertContains($itemKey2, $keys); $this->assertContains($childItemKey1, $keys); $this->assertContains($childItemKey2, $keys); $response = API::userGet(self::$config['userID'], "collections/{$collectionKey}/items/top?key=" . self::$config['apiKey'] . "&format=keys"); $this->assert200($response); $keys = explode("\n", trim($response->getBody())); $this->assertCount(2, $keys); $this->assertContains($itemKey1, $keys); $this->assertContains($itemKey2, $keys); }
private function _testPartialWriteFailureWithUnchanged($objectType) { API::userClear(self::$config['userID']); $objectTypePlural = API::getPluralObjectType($objectType); switch ($objectType) { case 'collection': $data = API::createCollection("Test", false, $this, 'data'); $json1 = json_decode($data['content']); $json2 = array("name" => str_repeat("1234567890", 6554)); $json3 = array("name" => "Test"); break; case 'item': $data = API::createItem("book", array("title" => "Title"), $this, 'data'); $json1 = json_decode($data['content']); $json2 = API::getItemTemplate('book'); $json3 = clone $json2; $json2->title = str_repeat("1234567890", 6554); break; case 'search': $conditions = array(array('condition' => 'title', 'operator' => 'contains', 'value' => 'value')); $data = API::createSearch("Name", $conditions, $this, 'data'); $json1 = json_decode($data['content']); $json2 = array("name" => str_repeat("1234567890", 6554), "conditions" => $conditions); $json3 = array("name" => "Test", "conditions" => $conditions); break; } $response = API::userPost(self::$config['userID'], "{$objectTypePlural}?key=" . self::$config['apiKey'], json_encode(array("{$objectTypePlural}" => array($json1, $json2, $json3))), array("Content-Type: application/json")); $this->assert200($response); $json = API::getJSONFromResponse($response); $this->assertUnchangedForObject($response, false, 0); $this->assert400ForObject($response, false, 1); $this->assert200ForObject($response, false, 2); $json = API::getJSONFromResponse($response); $response = API::userGet(self::$config['userID'], "{$objectTypePlural}?format=keys&key=" . self::$config['apiKey']); $this->assert200($response); $keys = explode("\n", trim($response->getBody())); $this->assertCount(2, $keys); foreach ($json['success'] as $key) { $this->assertContains($key, $keys); } }
private function _testDeleteAndDeleted($objectType) { API::userClear(self::$config['userID']); $objectTypePlural = API::getPluralObjectType($objectType); $xml = Sync::updated(self::$sessionID); $lastSyncTimestamp = (int) $xml['timestamp']; // Create via sync switch ($objectType) { case 'item': $keys[] = Sync::createItem(self::$sessionID, self::$config['libraryID'], "book", false, $this); break; case 'setting': $settingKey = "tagColors"; $response = API::userPut(self::$config['userID'], "settings/{$settingKey}?key=" . self::$config['apiKey'], json_encode(array("value" => array(array("name" => "_READ", "color" => "#990000")))), array("Content-Type: application/json", "If-Unmodified-Since-Version: 0")); $this->assertEquals(204, $response->getStatus()); $keys[] = $settingKey; break; } // Check via API foreach ($keys as $key) { $response = API::userGet(self::$config['userID'], "{$objectTypePlural}/{$key}?key=" . self::$config['apiKey']); $this->assertEquals(200, $response->getStatus()); $version = $response->getHeader("Last-Modified-Version"); $this->assertNotNull($version); } // Get empty deleted via API $response = API::userGet(self::$config['userID'], "deleted?key=" . self::$config['apiKey'] . "&newer={$version}"); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertEmpty($json[$objectTypePlural]); // Get empty deleted via API with newertime $response = API::userGet(self::$config['userID'], "deleted?key=" . self::$config['apiKey'] . "&newertime={$lastSyncTimestamp}"); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertEmpty($json[$objectTypePlural]); // Delete via sync foreach ($keys as $key) { switch ($objectType) { case 'item': Sync::deleteItem(self::$sessionID, self::$config['libraryID'], $key, $this); break; case 'setting': // Delete via sync $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; $xmlstr = '<data version="9">' . '<deleted>' . '<settings>' . '<setting libraryID="' . self::$config['libraryID'] . '" key="' . $key . '"/>' . '</settings>' . '</deleted>' . '</data>'; $response = Sync::upload(self::$sessionID, $updateKey, $xmlstr); Sync::waitForUpload(self::$sessionID, $response, $this); break; } } // Check 404 via API foreach ($keys as $key) { $response = API::userGet(self::$config['userID'], "{$objectTypePlural}/{$key}?key=" . self::$config['apiKey']); $this->assertEquals(404, $response->getStatus()); } // Get deleted via API $response = API::userGet(self::$config['userID'], "deleted?key=" . self::$config['apiKey'] . "&newer={$version}"); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertArrayHasKey($objectTypePlural, $json); $this->assertCount(sizeOf($keys), $json[$objectTypePlural]); foreach ($keys as $key) { $this->assertContains($key, $json[$objectTypePlural]); } // Get deleted via API with newertime $response = API::userGet(self::$config['userID'], "deleted?key=" . self::$config['apiKey'] . "&newertime={$lastSyncTimestamp}"); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertArrayHasKey($objectTypePlural, $json); $this->assertCount(sizeOf($keys), $json[$objectTypePlural]); foreach ($keys as $key) { $this->assertContains($key, $json[$objectTypePlural]); } // Should be empty with later newertime $xml = Sync::updated(self::$sessionID); $lastSyncTimestamp = (int) $xml['timestamp']; $response = API::userGet(self::$config['userID'], "deleted?key=" . self::$config['apiKey'] . "&newertime=" . ($lastSyncTimestamp + 2)); $this->assertEquals(200, $response->getStatus()); $json = json_decode($response->getBody(), true); $this->assertEmpty($json[$objectTypePlural]); }
/** * Changing a group's metadata should change its ETag */ public function testUpdateMetadata() { $response = API::userGet(self::$config['userID'], "groups?content=json&key=" . self::$config['apiKey']); $this->assert200($response); // Get group API URI and ETag $xml = API::getXMLFromResponse($response); $xml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom'); $xml->registerXPathNamespace('zapi', 'http://zotero.org/ns/api'); $groupID = (string) array_shift($xml->xpath("//atom:entry/zapi:groupID")); $url = (string) array_shift($xml->xpath("//atom:entry/atom:link[@rel='self']/@href")); $url = str_replace(self::$config['apiURLPrefix'], '', $url); $etag = (string) array_shift($xml->xpath("//atom:entry/atom:content/@etag")); // Make sure format=etags returns the same ETag $response = API::userGet(self::$config['userID'], "groups?format=etags&key=" . self::$config['apiKey']); $this->assert200($response); $json = json_decode($response->getBody()); $this->assertEquals($etag, $json->{$groupID}); // Update group metadata $json = json_decode(array_shift($xml->xpath("//atom:entry/atom:content"))); $xml = new SimpleXMLElement("<group/>"); foreach ($json as $key => $val) { switch ($key) { case 'id': case 'members': continue; case 'name': $name = "My Test Group " . uniqid(); $xml['name'] = $name; break; case 'description': $description = "This is a test description " . uniqid(); $xml->{$key} = $description; break; case 'url': $urlField = "http://example.com/" . uniqid(); $xml->{$key} = $urlField; break; default: $xml[$key] = $val; } } $xml = trim(preg_replace('/^<\\?xml.+\\n/', "", $xml->asXML())); $response = API::put($url, $xml, array("Content-Type: text/xml"), array("username" => self::$config['rootUsername'], "password" => self::$config['rootPassword'])); $this->assert200($response); $xml = API::getXMLFromResponse($response); $xml->registerXPathNamespace('zxfer', 'http://zotero.org/ns/transfer'); $group = $xml->xpath('//atom:entry/atom:content/zxfer:group'); $this->assertCount(1, $group); $this->assertEquals($name, $group[0]['name']); $response = API::userGet(self::$config['userID'], "groups?format=etags&key=" . self::$config['apiKey']); $this->assert200($response); $json = json_decode($response->getBody()); $newETag = $json->{$groupID}; $this->assertNotEquals($etag, $newETag); // Check ETag header on individual group request $response = API::groupGet($groupID, "?content=json&key=" . self::$config['apiKey']); $this->assert200($response); $this->assertEquals($newETag, $response->getHeader('ETag')); $json = json_decode(API::getContentFromResponse($response)); $this->assertEquals($name, $json->name); $this->assertEquals($description, $json->description); $this->assertEquals($urlField, $json->url); }
public function testUnsupportedSettingMultiple() { $settingKey = "unsupportedSetting"; $json = array("tagColors" => array("value" => array("name" => "_READ", "color" => "#990000"), "version" => 0), $settingKey => array("value" => false, "version" => 0)); $libraryVersion = API::getLibraryVersion(); $response = API::userPut(self::$config['userID'], "settings/{$settingKey}?key=" . self::$config['apiKey'], json_encode($json), array("Content-Type: application/json")); $this->assert400($response, "Invalid setting '{$settingKey}'"); // Valid setting shouldn't exist, and library version should be unchanged $response = API::userGet(self::$config['userID'], "settings/{$settingKey}?key=" . self::$config['apiKey']); $this->assert404($response); $this->assertEquals($libraryVersion, API::getLibraryVersion()); }
public function testComputerProgram() { $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; $itemKey = 'AAAAAAAA'; // Create item via sync $data = '<data version="9"><items><item libraryID="' . self::$config['libraryID'] . '" itemType="computerProgram" ' . 'dateAdded="2009-03-07 04:53:20" ' . 'dateModified="2009-03-07 04:54:09" ' . 'key="' . $itemKey . '">' . '<field name="version">1.0</field>' . '</item></items></data>'; $response = Sync::upload(self::$sessionID, $updateKey, $data); Sync::waitForUpload(self::$sessionID, $response, $this); // Get item version via API $response = API::userGet(self::$config['userID'], "items/{$itemKey}?key=" . self::$config['apiKey'] . "&content=json"); $this->assertEquals(200, $response->getStatus()); $xml = API::getItemXML($itemKey); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content'], true); $this->assertEquals('1.0', $json['version']); $json['version'] = '1.1'; $response = API::userPut(self::$config['userID'], "items/{$itemKey}?key=" . self::$config['apiKey'], json_encode($json)); $this->assertEquals(204, $response->getStatus()); $xml = Sync::updated(self::$sessionID); $this->assertEquals('version', (string) $xml->updated[0]->items[0]->item[0]->field[0]['name']); }
public function testContentBibMulti() { $keys = array_keys(self::$items); $keyStr = implode(',', $keys); foreach (self::$styles as $style) { $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&itemKey={$keyStr}&content=bib" . ($style == "default" ? "" : "&style={$style}")); $this->assert200($response); $xml = API::getXMLFromResponse($response); $this->assertEquals(sizeOf($keys), (int) array_shift($xml->xpath('/atom:feed/zapi:totalResults'))); $entries = $xml->xpath('//atom:entry'); foreach ($entries as $entry) { $key = (string) $entry->children("http://zotero.org/ns/api")->key; $content = $entry->content->asXML(); // Add zapi namespace $content = str_replace('<content ', '<content xmlns:zapi="http://zotero.org/ns/api" ', $content); $this->assertXmlStringEqualsXmlString(self::$items[$key]['bib'][$style], $content); } } }
public function testCreatorItemChangeViaAPI() { $key = 'AAAAAAAA'; $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; // Create item via sync $data = '<data version="9"><items><item libraryID="' . self::$config['libraryID'] . '" itemType="book" ' . 'dateAdded="2009-03-07 04:53:20" ' . 'dateModified="2009-03-07 04:54:09" ' . 'key="' . $key . '">' . '<creator key="BBBBBBBB" creatorType="author" index="0">' . '<creator libraryID="' . self::$config['libraryID'] . '" ' . 'key="BBBBBBBB" dateAdded="2009-03-07 04:53:20" dateModified="2009-03-07 04:54:09">' . '<firstName>First</firstName>' . '<lastName>Last</lastName>' . '<fieldMode>0</fieldMode>' . '</creator></creator></item></items></data>'; $response = Sync::upload(self::$sessionID, $updateKey, $data); Sync::waitForUpload(self::$sessionID, $response, $this); // Get item version via API and check creatorSummary API::useAPIVersion(1); $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=json"); $xml = API::getXMLFromResponse($response); $creatorSummary = (string) array_shift($xml->xpath('//atom:entry/zapi:creatorSummary')); $this->assertEquals("Last", $creatorSummary); $data = API::parseDataFromAtomEntry($xml); $etag = (string) array_shift($xml->xpath('//atom:entry/atom:content/@zapi:etag')); $this->assertNotEquals("", $etag); // Modify creator $json = json_decode($data['content'], true); $json['creators'][0] = array("name" => "First Last", "creatorType" => "author"); // Modify via API $response = API::userPut(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'], json_encode($json), array("If-Match: {$etag}")); $xml = API::getXMLFromResponse($response); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $creatorSummary = (string) array_shift($xml->xpath('//atom:entry/zapi:creatorSummary')); $this->assertEquals("First Last", $creatorSummary); $this->assertTrue(isset($json->creators[0]->name)); $this->assertEquals("First Last", $json->creators[0]->name); $newETag = (string) array_shift($xml->xpath('//atom:entry/zapi:etag')); $this->assertNotEquals($etag, $newETag); // Get item again via API $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=json"); $xml = API::getXMLFromResponse($response); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $creatorSummary = (string) array_shift($xml->xpath('//atom:entry/zapi:creatorSummary')); $this->assertEquals("First Last", $creatorSummary); $this->assertTrue(isset($json->creators[0]->name)); $this->assertEquals("First Last", $json->creators[0]->name); $newETag = (string) array_shift($xml->xpath('//atom:entry/zapi:etag')); $this->assertNotEquals($etag, $newETag); }
public function testSyncUploadUnchanged() { $data1 = API::createItem("audioRecording", array("title" => "Test", "relations" => array('owl:sameAs' => 'http://zotero.org/groups/1/items/AAAAAAAA')), null, 'data'); // dc:relation already exists, so item shouldn't change $data2 = API::createItem("interview", array("relations" => array('dc:relation' => 'http://zotero.org/users/' . self::$config['userID'] . '/items/' . $data1['key'])), null, 'data'); // Upload unchanged via sync $xml = Sync::updated(self::$sessionID); $updateKey = $xml['updateKey']; $lastSyncTimestamp = $xml['timestamp']; $itemXML1 = array_shift($xml->updated[0]->items[0]->xpath("item[@key='{$data1['key']}']")); $itemXML2 = array_shift($xml->updated[0]->items[0]->xpath("item[@key='{$data2['key']}']")); $itemXML1['libraryID'] = self::$config['libraryID']; $itemXML2['libraryID'] = self::$config['libraryID']; $xmlstr = '<data version="9">' . '<items>' . $itemXML1->asXML() . $itemXML2->asXML() . '</items>' . '</data>'; $response = Sync::upload(self::$sessionID, $updateKey, $xmlstr); Sync::waitForUpload(self::$sessionID, $response, $this); // Check via API to make sure they're the same $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&format=versions"); $json = API::getJSONFromResponse($response); $this->assertEquals($data1['version'], $json[$data1['key']]); $this->assertEquals($data2['version'], $json[$data2['key']]); }
public function testItemQuickSearchOrderByDate() { $title1 = "Test Title"; $title2 = "Another Title"; $keys = []; $keys[] = API::createItem("book", ['title' => $title1, 'date' => "February 12, 2013"], $this, 'key'); $keys[] = API::createItem("journalArticle", ['title' => $title2, 'date' => "November 25, 2012"], $this, 'key'); // Search for one by title $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&content=json&q=" . urlencode($title1)); $this->assert200($response); $this->assertNumResults(1, $response); $xml = API::getXMLFromResponse($response); $xpath = $xml->xpath('//atom:entry/zapi:key'); $key = (string) array_shift($xpath); $this->assertEquals($keys[0], $key); // Search by both by title, date asc $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&content=json&q=title&order=date&sort=asc"); $this->assert200($response); $this->assertNumResults(2, $response); $xml = API::getXMLFromResponse($response); $xpath = $xml->xpath('//atom:entry/zapi:key'); $key = (string) array_shift($xpath); $this->assertEquals($keys[1], $key); $key = (string) array_shift($xpath); $this->assertEquals($keys[0], $key); // Search by both by title, date desc $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&content=json&q=title&order=date&sort=desc"); $this->assert200($response); $this->assertNumResults(2, $response); $xml = API::getXMLFromResponse($response); $xpath = $xml->xpath('//atom:entry/zapi:key'); $key = (string) array_shift($xpath); $this->assertEquals($keys[0], $key); $key = (string) array_shift($xpath); $this->assertEquals($keys[1], $key); }
public function testTagDeleteUnmodifiedItemChange() { $key = 'AAAAAAAA'; $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; // Create item via sync $data = '<data version="9"><items><item libraryID="' . self::$config['libraryID'] . '" itemType="book" ' . 'dateAdded="2009-03-07 04:53:20" ' . 'dateModified="2009-03-07 04:54:09" ' . 'key="' . $key . '"/></items>' . '<tags><tag libraryID="' . self::$config['libraryID'] . '" name="Test" ' . 'dateAdded="2009-03-07 04:54:56" ' . 'dateModified="2009-03-07 04:54:56" ' . 'key="BBBBBBBB">' . '<items>' . $key . '</items>' . '</tag></tags></data>'; $response = Sync::upload(self::$sessionID, $updateKey, $data); Sync::waitForUpload(self::$sessionID, $response, $this); // Get item via API $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=json"); $xml = API::getXMLFromResponse($response); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $originalVersion = $data['version']; $this->assertCount(1, $json->tags); $this->assertTrue(isset($json->tags[0]->tag)); $this->assertEquals("Test", $json->tags[0]->tag); // Get item via sync $xml = Sync::updated(self::$sessionID); $this->assertEquals(1, sizeOf($xml->updated->items->item)); $this->assertEquals(1, sizeOf($xml->updated->tags->tag)); $this->assertEquals(1, sizeOf($xml->updated->tags->tag[0]->items)); $lastsync = (int) $xml['timestamp']; usleep(1500000); // Increment the library version, since we're testing the // version below API::createItem('newspaperArticle', false, false, 'key'); $libraryVersion = API::getLibraryVersion(); $xml = Sync::updated(self::$sessionID); $updateKey = (string) $xml['updateKey']; // Delete tag via sync, with unmodified item $data = '<data version="9"><items><item libraryID="' . self::$config['libraryID'] . '" itemType="book" ' . 'dateAdded="2009-03-07 04:53:20" ' . 'dateModified="2009-03-07 04:54:09" ' . 'key="' . $key . '"/></items>' . '<deleted><tags><tag libraryID="' . self::$config['libraryID'] . '" key="BBBBBBBB"/>' . '</tags></deleted></data>'; $response = Sync::upload(self::$sessionID, $updateKey, $data); Sync::waitForUpload(self::$sessionID, $response, $this); // Get item via sync $xml = Sync::updated(self::$sessionID); $this->assertEquals(1, sizeOf(isset($xml->updated->tags->tag))); $this->assertFalse(isset($xml->updated->tags->tag[0]->items)); // Get item version via API $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=json"); $xml = API::getXMLFromResponse($response); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $this->assertEquals(0, (int) array_shift($xml->xpath('/atom:entry/zapi:numTags'))); $this->assertCount(0, $json->tags); // New item version should be greater than before $this->assertGreaterThan($originalVersion, $data['version']); // And should be one more than previous version $this->assertEquals($libraryVersion + 1, $data['version']); // Only the newspaperArticle should be updated $xml = Sync::updated(self::$sessionID, $lastsync); $this->assertEquals(1, $xml->updated[0]->items[0]->count()); }
public function testUnicodeTitle() { $title = "Tést"; $xml = API::createItem("book", array("title" => $title), $this); $data = API::parseDataFromAtomEntry($xml); $key = $data['key']; // Test entry $response = API::userGet(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'] . "&content=json"); $this->assertContains('"title": "Tést"', $response->getBody()); // Test feed $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&content=json"); $this->assertContains('"title": "Tést"', $response->getBody()); }
public function testDeleteItemContent() { $key = API::createItem("book", false, $this, 'key'); $xml = API::createAttachmentItem("imported_file", [], $key, $this, 'atom'); $data = API::parseDataFromAtomEntry($xml); $content = "Ыюм мютат дэбетиз конвынёры эю, ку мэль жкрипта трактатоз.\nПро ут чтэт эрепюят граэкйж, дуо нэ выро рыкючабо пырикюлёз."; // Store content $response = API::userPut(self::$config['userID'], "items/{$data['key']}/fulltext?key=" . self::$config['apiKey'], json_encode(["content" => $content, "indexedPages" => 50]), array("Content-Type: application/json")); $this->assert204($response); $contentVersion = $response->getHeader("Last-Modified-Version"); // Retrieve it $response = API::userGet(self::$config['userID'], "items/{$data['key']}/fulltext?key=" . self::$config['apiKey']); $this->assert200($response); $json = json_decode($response->getBody(), true); $this->assertEquals($content, $json['content']); $this->assertEquals(50, $json['indexedPages']); // Set to empty string $response = API::userPut(self::$config['userID'], "items/{$data['key']}/fulltext?key=" . self::$config['apiKey'], json_encode(["content" => ""]), array("Content-Type: application/json")); $this->assert204($response); $this->assertGreaterThan($contentVersion, $response->getHeader("Last-Modified-Version")); // Make sure it's gone $response = API::userGet(self::$config['userID'], "items/{$data['key']}/fulltext?key=" . self::$config['apiKey']); $this->assert200($response); $json = json_decode($response->getBody(), true); $this->assertEquals("", $json['content']); $this->assertArrayNotHasKey("indexedPages", $json); }
public function testAddFileClientZip() { API::userClear(self::$config['userID']); $auth = array('username' => self::$config['username'], 'password' => self::$config['password']); // Get last storage sync $response = API::userGet(self::$config['userID'], "laststoragesync?auth=1", array(), $auth); $this->assert404($response); $xml = API::createItem("book", false, $this); $data = API::parseDataFromAtomEntry($xml); $key = $data['key']; $fileContentType = "text/html"; $fileCharset = "UTF-8"; $fileFilename = "file.html"; $fileModtime = time(); $xml = API::createAttachmentItem("imported_url", [], $key, $this); $data = API::parseDataFromAtomEntry($xml); $key = $data['key']; $version = $data['version']; $json = json_decode($data['content']); $json->contentType = $fileContentType; $json->charset = $fileCharset; $json->filename = $fileFilename; $response = API::userPut(self::$config['userID'], "items/{$key}?key=" . self::$config['apiKey'], json_encode($json), array("Content-Type: application/json")); $this->assert204($response); // Get a sync timestamp from before the file is updated sleep(1); require_once 'include/sync.inc.php'; $sessionID = Sync::login(); $xml = Sync::updated($sessionID); $lastsync = (int) $xml['timestamp']; Sync::logout($sessionID); // Get file info $response = API::userGet(self::$config['userID'], "items/{$data['key']}/file?auth=1&iskey=1&version=1&info=1", array(), $auth); $this->assert404($response); $zip = new ZipArchive(); $file = "work/{$key}.zip"; if ($zip->open($file, ZIPARCHIVE::CREATE) !== TRUE) { throw new Exception("Cannot open ZIP file"); } $zip->addFromString($fileFilename, self::getRandomUnicodeString()); $zip->addFromString("file.css", self::getRandomUnicodeString()); $zip->close(); $hash = md5_file($file); $filename = $key . ".zip"; $size = filesize($file); $fileContents = file_get_contents($file); // Get upload authorization $response = API::userPost(self::$config['userID'], "items/{$data['key']}/file?auth=1&iskey=1&version=1", $this->implodeParams(array("md5" => $hash, "filename" => $filename, "filesize" => $size, "mtime" => $fileModtime, "zip" => 1)), array("Content-Type: application/x-www-form-urlencoded"), $auth); $this->assert200($response); $this->assertContentType("application/xml", $response); $xml = new SimpleXMLElement($response->getBody()); self::$toDelete[] = "{$hash}"; $boundary = "---------------------------" . rand(); $postData = ""; foreach ($xml->params->children() as $key => $val) { $postData .= "--" . $boundary . "\r\nContent-Disposition: form-data; " . "name=\"{$key}\"\r\n\r\n{$val}\r\n"; } $postData .= "--" . $boundary . "\r\nContent-Disposition: form-data; " . "name=\"file\"\r\n\r\n" . $fileContents . "\r\n"; $postData .= "--" . $boundary . "--"; // Upload to S3 $response = HTTP::post((string) $xml->url, $postData, array("Content-Type: multipart/form-data; boundary=" . $boundary)); $this->assert201($response); // // Register upload // $response = API::userPost(self::$config['userID'], "items/{$data['key']}/file?auth=1&iskey=1&version=1", "update=" . $xml->key . "&mtime=" . $fileModtime, array("Content-Type: application/x-www-form-urlencoded"), $auth); $this->assert204($response); // Verify attachment item metadata $response = API::userGet(self::$config['userID'], "items/{$data['key']}?key=" . self::$config['apiKey'] . "&content=json"); $xml = API::getXMLFromResponse($response); $data = API::parseDataFromAtomEntry($xml); $json = json_decode($data['content']); $this->assertEquals($hash, $json->md5); $this->assertEquals($fileFilename, $json->filename); $this->assertEquals($fileModtime, $json->mtime); // Make sure attachment item wasn't updated (or else the client // will get a conflict when it tries to update the metadata) $sessionID = Sync::login(); $xml = Sync::updated($sessionID, $lastsync); Sync::logout($sessionID); $this->assertEquals(0, $xml->updated[0]->count()); $response = API::userGet(self::$config['userID'], "laststoragesync?auth=1", array(), array('username' => self::$config['username'], 'password' => self::$config['password'])); $this->assert200($response); $mtime = $response->getBody(); $this->assertRegExp('/^[0-9]{10}$/', $mtime); // File exists $response = API::userPost(self::$config['userID'], "items/{$data['key']}/file?auth=1&iskey=1&version=1", $this->implodeParams(array("md5" => $hash, "filename" => $filename, "filesize" => $size, "mtime" => $fileModtime + 1000, "zip" => 1)), array("Content-Type: application/x-www-form-urlencoded"), $auth); $this->assert200($response); $this->assertContentType("application/xml", $response); $this->assertEquals("<exists/>", $response->getBody()); // Make sure attachment item still wasn't updated $sessionID = Sync::login(); $xml = Sync::updated($sessionID, $lastsync); Sync::logout($sessionID); $this->assertEquals(0, $xml->updated[0]->count()); }
public function testMultiTagDelete() { $tags1 = array("a", "aa", "b"); $tags2 = array("b", "c", "cc"); $tags3 = array("Foo"); API::createItem("book", array("tags" => array_map(function ($tag) { return array("tag" => $tag); }, $tags1)), $this, 'key'); API::createItem("book", array("tags" => array_map(function ($tag) { return array("tag" => $tag, "type" => 1); }, $tags2)), $this, 'key'); API::createItem("book", array("tags" => array_map(function ($tag) { return array("tag" => $tag); }, $tags3)), $this, 'key'); $libraryVersion = API::getLibraryVersion(); // Missing version header $response = API::userDelete(self::$config['userID'], "tags?key=" . self::$config['apiKey'] . "&content=json&tag=" . implode("%20||%20", array_merge($tags1, $tags2))); $this->assert428($response); // Outdated version header $response = API::userDelete(self::$config['userID'], "tags?key=" . self::$config['apiKey'] . "&content=json&tag=" . implode("%20||%20", array_merge($tags1, $tags2)), array("If-Unmodified-Since-Version: " . ($libraryVersion - 1))); $this->assert412($response); // Delete $response = API::userDelete(self::$config['userID'], "tags?key=" . self::$config['apiKey'] . "&content=json&tag=" . implode("%20||%20", array_merge($tags1, $tags2)), array("If-Unmodified-Since-Version: {$libraryVersion}")); $this->assert204($response); // Make sure they're gone $response = API::userGet(self::$config['userID'], "tags?key=" . self::$config['apiKey'] . "&content=json&tag=" . implode("%20||%20", array_merge($tags1, $tags2, $tags3))); $this->assert200($response); $this->assertNumResults(1, $response); }
public function testKeyNoteAccess() { API::userClear(self::$config['userID']); API::setKeyOption(self::$config['userID'], self::$config['apiKey'], 'libraryNotes', 1); $keys = array(); $topLevelKeys = array(); $bookKeys = array(); $xml = API::createItem('book', array("title" => "A"), $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $bookKeys[] = $data['key']; $xml = API::createNoteItem("B", false, $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $xml = API::createNoteItem("C", false, $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $xml = API::createNoteItem("D", false, $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $xml = API::createNoteItem("E", false, $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $xml = API::createItem('book', array("title" => "F"), $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; $topKeys[] = $data['key']; $bookKeys[] = $data['key']; $xml = API::createNoteItem("G", $data['key'], $this); $data = API::parseDataFromAtomEntry($xml); $keys[] = $data['key']; // Create collection and add items to it $response = API::userPost(self::$config['userID'], "collections?key=" . self::$config['apiKey'], json_encode(array("collections" => array(array("name" => "Test", "parentCollection" => false)))), array("Content-Type: application/json")); $this->assert200ForObject($response); $collectionKey = API::getFirstSuccessKeyFromResponse($response); $response = API::userPost(self::$config['userID'], "collections/{$collectionKey}/items?key=" . self::$config['apiKey'], implode(" ", $topKeys)); $this->assert204($response); // // format=atom // // Root $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($keys), $response); $this->assertTotalResults(sizeOf($keys), $response); // Top $response = API::userGet(self::$config['userID'], "items/top?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($topKeys), $response); $this->assertTotalResults(sizeOf($topKeys), $response); // Collection $response = API::userGet(self::$config['userID'], "collections/{$collectionKey}/items/top?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($topKeys), $response); $this->assertTotalResults(sizeOf($topKeys), $response); // // format=keys // // Root $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&format=keys"); $this->assert200($response); $this->assertCount(sizeOf($keys), explode("\n", trim($response->getBody()))); // Top $response = API::userGet(self::$config['userID'], "items/top?key=" . self::$config['apiKey'] . "&format=keys"); $this->assert200($response); $this->assertCount(sizeOf($topKeys), explode("\n", trim($response->getBody()))); // Collection $response = API::userGet(self::$config['userID'], "collections/{$collectionKey}/items/top?key=" . self::$config['apiKey'] . "&format=keys"); $this->assert200($response); $this->assertCount(sizeOf($topKeys), explode("\n", trim($response->getBody()))); // Remove notes privilege from key API::setKeyOption(self::$config['userID'], self::$config['apiKey'], 'libraryNotes', 0); // // format=atom // // totalResults with limit $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&limit=1"); $this->assertNumResults(1, $response); $this->assertTotalResults(sizeOf($bookKeys), $response); // And without limit $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($bookKeys), $response); $this->assertTotalResults(sizeOf($bookKeys), $response); // Top $response = API::userGet(self::$config['userID'], "items/top?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($bookKeys), $response); $this->assertTotalResults(sizeOf($bookKeys), $response); // Collection $response = API::userGet(self::$config['userID'], "collections/{$collectionKey}/items?key=" . self::$config['apiKey']); $this->assertNumResults(sizeOf($bookKeys), $response); $this->assertTotalResults(sizeOf($bookKeys), $response); // // format=keys // $response = API::userGet(self::$config['userID'], "items?key=" . self::$config['apiKey'] . "&format=keys"); $keys = explode("\n", trim($response->getBody())); sort($keys); $this->assertEmpty(array_merge(array_diff($bookKeys, $keys), array_diff($keys, $bookKeys))); }
public function testSortTopItemsCreator() { $response = API::userGet(self::$config['userID'], "items/top?key=" . self::$config['apiKey'] . "&format=keys&order=creator"); $this->assert200($response); $keys = explode("\n", trim($response->getBody())); $names = self::$names; uasort($names, function ($a, $b) { if ($a === '' && $b !== '') { return 1; } if ($b === '' && $a !== '') { return -1; } return strcmp($a, $b); }); $this->assertCount(sizeOf($names), $keys); $endKeys = array_splice($keys, -2); $correct = []; foreach ($names as $k => $v) { // The key at position k in itemKeys should be at the same position in keys $correct[] = self::$itemKeys[$k]; } // Remove empty names array_splice($correct, -2); $this->assertEquals($correct, $keys); // Check attachment and note, which should fall back to ordered added (itemID) $this->assertEquals(array_slice(self::$itemKeys, -2), $endKeys); }