private static function validateJSONItem($json, $libraryID, Zotero_Item $item = null, $isChild, $requestParams, $partialUpdate = false) { $isNew = !$item || !$item->version; if (!is_object($json)) { throw new Exception("Invalid item object (found " . gettype($json) . " '" . $json . "')", Z_ERROR_INVALID_INPUT); } if (isset($json->items) && is_array($json->items)) { throw new Exception("An 'items' array is not valid for single-item updates", Z_ERROR_INVALID_INPUT); } $apiVersion = $requestParams['v']; if ($partialUpdate) { $requiredProps = []; } else { if (isset($json->itemType) && $json->itemType == "attachment") { $requiredProps = array('linkMode', 'tags'); } else { if (isset($json->itemType) && $json->itemType == "attachment") { $requiredProps = array('tags'); } else { if ($isNew) { $requiredProps = array('itemType'); } else { if ($apiVersion < 2) { $requiredProps = array('itemType', 'tags'); } else { $requiredProps = array('itemType', 'tags', 'relations'); if (!$isChild) { $requiredProps[] = 'collections'; } } } } } } foreach ($requiredProps as $prop) { if (!isset($json->{$prop})) { throw new Exception("'{$prop}' property not provided", Z_ERROR_INVALID_INPUT); } } // For partial updates where item type isn't provided, use the existing item type if (!isset($json->itemType) && $partialUpdate) { $itemType = Zotero_ItemTypes::getName($item->itemTypeID); } else { $itemType = $json->itemType; } foreach ($json as $key => $val) { switch ($key) { // Handled by Zotero_API::checkJSONObjectVersion() case 'key': case 'version': if ($apiVersion < 3) { throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT); } break; case 'itemKey': case 'itemVersion': if ($apiVersion != 2) { throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT); } break; case 'parentItem': if ($apiVersion < 2) { throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT); } if (!Zotero_ID::isValidKey($val) && $val !== false) { throw new Exception("'{$key}' must be a valid item key", Z_ERROR_INVALID_INPUT); } break; case 'itemType': if (!is_string($val)) { throw new Exception("'itemType' must be a string", Z_ERROR_INVALID_INPUT); } if ($isChild || !empty($json->parentItem)) { switch ($val) { case 'note': case 'attachment': break; default: throw new Exception("Child item must be note or attachment", Z_ERROR_INVALID_INPUT); } } else { if ($val == 'attachment' && (!$item || !$item->getSource())) { if ($json->linkMode == 'linked_url' || $json->linkMode == 'imported_url' && (empty($json->contentType) || $json->contentType != 'application/pdf')) { throw new Exception("Only file attachments and PDFs can be top-level items", Z_ERROR_INVALID_INPUT); } } } if (!Zotero_ItemTypes::getID($val)) { throw new Exception("'{$val}' is not a valid itemType", Z_ERROR_INVALID_INPUT); } break; case 'tags': if (!is_array($val)) { throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT); } foreach ($val as $tag) { $empty = true; if (is_string($tag)) { if ($tag === "") { throw new Exception("Tag cannot be empty", Z_ERROR_INVALID_INPUT); } continue; } if (!is_object($tag)) { throw new Exception("Tag must be an object", Z_ERROR_INVALID_INPUT); } foreach ($tag as $k => $v) { switch ($k) { case 'tag': if (!is_scalar($v)) { throw new Exception("Invalid tag name", Z_ERROR_INVALID_INPUT); } if ($v === "") { throw new Exception("Tag cannot be empty", Z_ERROR_INVALID_INPUT); } break; case 'type': if (!is_numeric($v)) { throw new Exception("Invalid tag type '{$v}'", Z_ERROR_INVALID_INPUT); } break; default: throw new Exception("Invalid tag property '{$k}'", Z_ERROR_INVALID_INPUT); } $empty = false; } if ($empty) { throw new Exception("Tag object is empty", Z_ERROR_INVALID_INPUT); } } break; case 'collections': if (!is_array($val)) { throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT); } if ($isChild && $val) { throw new Exception("Child items cannot be assigned to collections", Z_ERROR_INVALID_INPUT); } foreach ($val as $k) { if (!Zotero_ID::isValidKey($k)) { throw new Exception("'{$k}' is not a valid collection key", Z_ERROR_INVALID_INPUT); } } break; case 'relations': if ($apiVersion < 2) { throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT); } if (!is_object($val) && !(is_array($val) && empty($val))) { throw new Exception("'{$key}' property must be an object", Z_ERROR_INVALID_INPUT); } foreach ($val as $predicate => $object) { switch ($predicate) { case 'owl:sameAs': case 'dc:replaces': case 'dc:relation': break; default: throw new Exception("Unsupported predicate '{$predicate}'", Z_ERROR_INVALID_INPUT); } $arr = is_string($object) ? [$object] : $object; foreach ($arr as $uri) { if (!preg_match('/^http:\\/\\/zotero.org\\/(users|groups)\\/[0-9]+\\/(publications\\/)?items\\/[A-Z0-9]{8}$/', $uri)) { throw new Exception("'{$key}' values currently must be Zotero item URIs", Z_ERROR_INVALID_INPUT); } } } break; case 'creators': if (!is_array($val)) { throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT); } foreach ($val as $creator) { $empty = true; if (!isset($creator->creatorType)) { throw new Exception("creator object must contain 'creatorType'", Z_ERROR_INVALID_INPUT); } if ((!isset($creator->name) || trim($creator->name) == "") && (!isset($creator->firstName) || trim($creator->firstName) == "") && (!isset($creator->lastName) || trim($creator->lastName) == "")) { // On item creation, ignore single nameless creator, // because that's in the item template that the API returns if (sizeOf($val) == 1 && $isNew) { continue; } else { throw new Exception("creator object must contain 'firstName'/'lastName' or 'name'", Z_ERROR_INVALID_INPUT); } } foreach ($creator as $k => $v) { switch ($k) { case 'creatorType': $creatorTypeID = Zotero_CreatorTypes::getID($v); if (!$creatorTypeID) { throw new Exception("'{$v}' is not a valid creator type", Z_ERROR_INVALID_INPUT); } $itemTypeID = Zotero_ItemTypes::getID($itemType); if (!Zotero_CreatorTypes::isValidForItemType($creatorTypeID, $itemTypeID)) { // Allow 'author' in all item types, but reject other invalid creator types if ($creatorTypeID != Zotero_CreatorTypes::getID('author')) { throw new Exception("'{$v}' is not a valid creator type for item type '{$itemType}'", Z_ERROR_INVALID_INPUT); } } break; case 'firstName': if (!isset($creator->lastName)) { throw new Exception("'lastName' creator field must be set if 'firstName' is set", Z_ERROR_INVALID_INPUT); } if (isset($creator->name)) { throw new Exception("'firstName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT); } break; case 'lastName': if (!isset($creator->firstName)) { throw new Exception("'firstName' creator field must be set if 'lastName' is set", Z_ERROR_INVALID_INPUT); } if (isset($creator->name)) { throw new Exception("'lastName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT); } break; case 'name': if (isset($creator->firstName)) { throw new Exception("'firstName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT); } if (isset($creator->lastName)) { throw new Exception("'lastName' and 'name' creator fields are mutually exclusive", Z_ERROR_INVALID_INPUT); } break; default: throw new Exception("Invalid creator property '{$k}'", Z_ERROR_INVALID_INPUT); } $empty = false; } if ($empty) { throw new Exception("Creator object is empty", Z_ERROR_INVALID_INPUT); } } break; case 'note': switch ($itemType) { case 'note': case 'attachment': break; default: throw new Exception("'note' property is valid only for note and attachment items", Z_ERROR_INVALID_INPUT); } break; case 'attachments': case 'notes': if ($apiVersion > 1) { throw new Exception("'{$key}' property is no longer supported", Z_ERROR_INVALID_INPUT); } if (!$isNew) { throw new Exception("'{$key}' property is valid only for new items", Z_ERROR_INVALID_INPUT); } if (!is_array($val)) { throw new Exception("'{$key}' property must be an array", Z_ERROR_INVALID_INPUT); } foreach ($val as $child) { // Check child item type ('attachment' or 'note') $t = substr($key, 0, -1); if (isset($child->itemType) && $child->itemType != $t) { throw new Exception("Child {$t} must be of itemType '{$t}'", Z_ERROR_INVALID_INPUT); } if ($key == 'note') { if (!isset($child->note)) { throw new Exception("'note' property not provided for child note", Z_ERROR_INVALID_INPUT); } } } break; case 'deleted': break; // Attachment properties // Attachment properties case 'linkMode': try { $linkMode = Zotero_Attachments::linkModeNameToNumber($val, true); } catch (Exception $e) { throw new Exception("'{$val}' is not a valid linkMode", Z_ERROR_INVALID_INPUT); } // Don't allow changing of linkMode if (!$isNew && $linkMode != $item->attachmentLinkMode) { throw new Exception("Cannot change attachment linkMode", Z_ERROR_INVALID_INPUT); } break; case 'contentType': case 'charset': case 'filename': case 'md5': case 'mtime': if ($itemType != 'attachment') { throw new Exception("'{$key}' is valid only for attachment items", Z_ERROR_INVALID_INPUT); } switch ($key) { case 'filename': case 'md5': case 'mtime': $lm = isset($json->linkMode) ? $json->linkMode : Zotero_Attachments::linkModeNumberToName($item->attachmentLinkMode); if (strpos(strtolower($lm), 'imported_') !== 0) { throw new Exception("'{$key}' is valid only for imported attachment items", Z_ERROR_INVALID_INPUT); } break; } switch ($key) { case 'contentType': case 'charset': case 'filename': $propName = 'attachment' . ucwords($key); break; case 'md5': $propName = 'attachmentStorageHash'; break; case 'mtime': $propName = 'attachmentStorageModTime'; break; } if (Zotero_Libraries::getType($libraryID) == 'group') { if ($item && $item->{$propName} !== $val || !$item && $val !== null && $val !== "") { throw new Exception("Cannot change '{$key}' directly in group library", Z_ERROR_INVALID_INPUT); } } else { if ($key == 'md5') { if ($val && !preg_match("/^[a-f0-9]{32}\$/", $val)) { throw new Exception("'{$val}' is not a valid MD5 hash", Z_ERROR_INVALID_INPUT); } } } break; case 'accessDate': if ($apiVersion >= 3 && $val !== '' && $val != 'CURRENT_TIMESTAMP' && !Zotero_Date::isSQLDate($val) && !Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) { throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD[ hh-mm-dd]' format or 'CURRENT_TIMESTAMP' ({$val})", Z_ERROR_INVALID_INPUT); } break; case 'dateAdded': if (!Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) { throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD hh-mm-dd' format", Z_ERROR_INVALID_INPUT); } if (!$isNew) { // Convert ISO date to SQL date for equality comparison if (Zotero_Date::isISO8601($val)) { $val = Zotero_Date::iso8601ToSQL($val); } if ($val != $item->{$key}) { throw new Exception("'{$key}' cannot be modified for existing items", Z_ERROR_INVALID_INPUT); } } break; case 'dateModified': if (!Zotero_Date::isSQLDateTime($val) && !Zotero_Date::isISO8601($val)) { throw new Exception("'{$key}' must be in ISO 8601 or UTC 'YYYY-MM-DD hh-mm-dd' format ({$val})", Z_ERROR_INVALID_INPUT); } break; default: if (!Zotero_ItemFields::getID($key)) { throw new Exception("Invalid property '{$key}'", Z_ERROR_INVALID_INPUT); } if (is_array($val)) { throw new Exception("Unexpected array for property '{$key}'", Z_ERROR_INVALID_INPUT); } break; } } // Publications libraries have additional restrictions if (Zotero_Libraries::getType($libraryID) == 'publications') { Zotero_Publications::validateJSONItem($json); } }
public function init($extra) { $this->startTime = microtime(true); if (!Z_CONFIG::$API_ENABLED) { $this->e503(Z_CONFIG::$MAINTENANCE_MESSAGE); } set_exception_handler(array($this, 'handleException')); // TODO: Throw error on some notices but allow DB/Memcached/etc. failures? //set_error_handler(array($this, 'handleError'), E_ALL | E_USER_ERROR | E_RECOVERABLE_ERROR); set_error_handler(array($this, 'handleError'), E_USER_ERROR | E_RECOVERABLE_ERROR); require_once '../model/Error.inc.php'; // On testing sites, include notifications in headers if (Z_CONFIG::$TESTING_SITE) { Zotero_NotifierObserver::addMessageReceiver(function ($topic, $msg) { $header = "Zotero-Debug-Notifications"; if (!empty($this->headers[$header])) { $notifications = json_decode(base64_decode($this->headers[$header])); } else { $notifications = []; } $notifications[] = $msg; $this->headers[$header] = base64_encode(json_encode($notifications)); }); } register_shutdown_function(array($this, 'checkDBTransactionState')); register_shutdown_function(array($this, 'logTotalRequestTime')); register_shutdown_function(array($this, 'checkForFatalError')); register_shutdown_function(array($this, 'addHeaders')); $this->method = $_SERVER['REQUEST_METHOD']; if (!in_array($this->method, array('HEAD', 'OPTIONS', 'GET', 'PUT', 'POST', 'DELETE', 'PATCH'))) { $this->e501(); } StatsD::increment("api.request.method." . strtolower($this->method), 0.25); // There doesn't seem to be a way for PHP to start processing the request // before the entire body is sent, so an Expect: 100 Continue will, // depending on the client, either fail or cause a delay while the client // waits for the 100 response. To make this explicit, we return an error. if (!empty($_SERVER['HTTP_EXPECT'])) { header("HTTP/1.1 417 Expectation Failed"); die("Expect header is not supported"); } // CORS if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE"); header("Access-Control-Allow-Headers: Content-Type, If-Match, If-None-Match, If-Modified-Since-Version, If-Unmodified-Since-Version, Zotero-API-Version, Zotero-Write-Token"); header("Access-Control-Expose-Headers: Backoff, ETag, Last-Modified-Version, Link, Retry-After, Total-Results, Zotero-API-Version"); } if ($this->method == 'OPTIONS') { $this->end(); } if (in_array($this->method, array('POST', 'PUT', 'PATCH'))) { $this->ifUnmodifiedSince = isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) : false; $this->body = file_get_contents("php://input"); if ($this->body == "" && !in_array($this->action, array('clear', 'laststoragesync', 'removestoragefiles', 'itemContent'))) { $this->e400("{$this->method} data not provided"); } } if ($this->profile) { Zotero_DB::profileStart(); } // If HTTP Basic Auth credentials provided, authenticate if (isset($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; if ($username == Z_CONFIG::$API_SUPER_USERNAME && $password == Z_CONFIG::$API_SUPER_PASSWORD) { $this->userID = 0; $this->permissions = new Zotero_Permissions(); $this->permissions->setSuper(); } else { if (!empty($extra['allowHTTP']) || !empty($extra['auth'])) { $userID = Zotero_Users::authenticate('password', array('username' => $username, 'password' => $password)); if (!$userID) { $this->e401('Invalid login'); } $this->httpAuth = true; $this->userID = $userID; $this->grantUserPermissions($userID); } } } if (!isset($this->userID)) { $key = false; // Allow Zotero-API-Key header if (!empty($_SERVER['HTTP_ZOTERO_API_KEY'])) { $key = $_SERVER['HTTP_ZOTERO_API_KEY']; } // Allow ?key=<apikey> if (isset($_GET['key'])) { if (!$key) { $key = $_GET['key']; } else { if ($_GET['key'] !== $key) { $this->e400("Zotero-API-Key header and 'key' parameter differ"); } } } // If neither of the above passed, allow "Authorization: Bearer <apikey>" // // Apache/mod_php doesn't seem to make Authorization available for auth schemes // other than Basic/Digest, so use an Apache-specific method to get the header if (!$key && function_exists('apache_request_headers')) { $headers = apache_request_headers(); if (isset($headers['Authorization'])) { // Look for "Authorization: Bearer" from OAuth 2.0, and ignore everything else if (preg_match('/^bearer/i', $headers['Authorization'], $matches)) { if (preg_match('/^bearer +([a-z0-9]+)$/i', $headers['Authorization'], $matches)) { $key = $matches[1]; } else { $this->e400("Invalid Authorization header format"); } } } } if ($key) { $keyObj = Zotero_Keys::authenticate($key); if (!$keyObj) { $this->e403('Invalid key'); } $this->apiKey = $key; $this->userID = $keyObj->userID; $this->permissions = $keyObj->getPermissions(); // Check Zotero-Write-Token if it exists to make sure // this isn't a duplicate request if ($this->isWriteMethod()) { if ($cacheKey = $this->getWriteTokenCacheKey()) { if (Z_Core::$MC->get($cacheKey)) { $this->e412("Write token already used"); } } } } else { if (!empty($_GET['session']) && ($this->userID = Zotero_Users::getUserIDFromSessionID($_GET['session']))) { // Users who haven't synced may not exist in our DB if (!Zotero_Users::exists($this->userID)) { Zotero_Users::add($this->userID); } $this->grantUserPermissions($this->userID); $this->cookieAuth = true; } else { if (!empty($_GET['auth']) || !empty($extra['auth'])) { $this->e401(); } // Explicit auth request or not a GET request // // /users/<id>/keys is an exception, since the key is embedded in the URL if ($this->method != "GET" && $this->action != 'keys') { $this->e403('An API key is required for write requests.'); } // Anonymous request $this->permissions = new Zotero_Permissions(); $this->permissions->setAnonymous(); } } } $this->uri = Z_CONFIG::$API_BASE_URI . substr($_SERVER["REQUEST_URI"], 1); // Get object user if (isset($this->objectUserID)) { if (!$this->objectUserID) { $this->e400("Invalid user ID", Z_ERROR_INVALID_INPUT); } try { $this->objectLibraryID = Zotero_Users::getLibraryIDFromUserID($this->objectUserID); } catch (Exception $e) { if ($e->getCode() == Z_ERROR_USER_NOT_FOUND) { try { Zotero_Users::addFromWWW($this->objectUserID); } catch (Exception $e) { if ($e->getCode() == Z_ERROR_USER_NOT_FOUND) { $this->e404("User {$this->objectUserID} not found"); } throw $e; } $this->objectLibraryID = Zotero_Users::getLibraryIDFromUserID($this->objectUserID); } else { throw $e; } } // Make sure user isn't banned if (!Zotero_Users::isValidUser($this->objectUserID)) { $this->e404(); } } else { if (isset($this->objectGroupID)) { if (!$this->objectGroupID) { $this->e400("Invalid group ID", Z_ERROR_INVALID_INPUT); } // Make sure group exists $group = Zotero_Groups::get($this->objectGroupID); if (!$group) { $this->e404(); } // Don't show groups owned by banned users if (!Zotero_Users::isValidUser($group->ownerUserID)) { $this->e404(); } $this->objectLibraryID = Zotero_Groups::getLibraryIDFromGroupID($this->objectGroupID); } } $apiVersion = !empty($_SERVER['HTTP_ZOTERO_API_VERSION']) ? (int) $_SERVER['HTTP_ZOTERO_API_VERSION'] : false; // Serve v1 to ZotPad 1.x, at Mikko's request if (!$apiVersion && !empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'ZotPad 1') === 0) { $apiVersion = 1; } // For publications URLs (e.g., /users/:userID/publications/items), swap in // objectLibraryID of user's publications library if (!empty($extra['publications'])) { // Query parameters not yet parsed, so check version parameter if ($apiVersion && $apiVersion < 3 || !empty($_REQUEST['v']) && $_REQUEST['v'] < 3 || !empty($_REQUEST['version']) && $_REQUEST['version'] == 1) { $this->e404(); } $userLibraryID = $this->objectLibraryID; $this->objectLibraryID = Zotero_Users::getLibraryIDFromUserID($this->objectUserID, 'publications'); // If one doesn't exist, for write requests create a library if the key // has write permission to the user library. For read requests, just // return a 404. if (!$this->objectLibraryID) { if ($this->isWriteMethod()) { if (!$this->permissions->canAccess($userLibraryID) || !$this->permissions->canWrite($userLibraryID)) { $this->e403(); } $this->objectLibraryID = Zotero_Publications::add($this->objectUserID); } else { $this->objectLibraryID = 0; } } } // Return 409 if target library is locked switch ($this->method) { case 'POST': case 'PUT': case 'DELETE': switch ($this->action) { // Library lock doesn't matter for some admin requests case 'keys': case 'storageadmin': break; default: if ($this->objectLibraryID && Zotero_Libraries::isLocked($this->objectLibraryID)) { $this->e409("Target library is locked"); } break; } } $this->scopeObject = !empty($extra['scopeObject']) ? $extra['scopeObject'] : $this->scopeObject; $this->subset = !empty($extra['subset']) ? $extra['subset'] : $this->subset; $this->fileMode = !empty($extra['file']) ? !empty($_GET['info']) ? 'info' : 'download' : false; $this->fileView = !empty($extra['view']); $this->singleObject = $this->objectKey && !$this->subset; $this->checkLibraryIfModifiedSinceVersion($this->action); // If Accept header includes application/atom+xml, send Atom, as long as there's no 'format' $atomAccepted = false; if (!empty($_SERVER['HTTP_ACCEPT'])) { $accept = preg_split('/\\s*,\\s*/', $_SERVER['HTTP_ACCEPT']); $atomAccepted = in_array('application/atom+xml', $accept); } $this->queryParams = Zotero_API::parseQueryParams($_SERVER['QUERY_STRING'], $this->action, $this->singleObject, $apiVersion, $atomAccepted); // Sorting by Item Type or Added By currently require writing to shard tables, so don't // send those to the read replicas if ($this->queryParams['sort'] == 'itemType' || $this->queryParams['sort'] == 'addedBy') { Zotero_DB::readOnly(false); } $this->apiVersion = $version = $this->queryParams['v']; header("Zotero-API-Version: " . $version); StatsD::increment("api.request.version.v" . $version, 0.25); }