Beispiel #1
0
 /**
  * Returns user's object ids updated since |timestamp|, keyed by libraryID,
  * or count of all updated items if $countOnly is true
  *
  * @param	int			$libraryID			User ID
  * @param	string		$timestamp			Unix timestamp of last sync time
  * @param	array		$updatedLibraryIDs	Libraries with updated data
  * @return	array|int
  */
 public static function getUpdated($userID, $timestamp, $updatedLibraryIDs, $countOnly = false)
 {
     $table = self::$table;
     $id = self::$idColumn;
     $type = self::$objectType;
     $types = self::$objectTypePlural;
     $timestampCol = "serverDateModified";
     // All joined groups have to be checked
     $joinedGroupIDs = Zotero_Groups::getJoined($userID, $timestamp);
     $joinedLibraryIDs = array();
     foreach ($joinedGroupIDs as $groupID) {
         $joinedLibraryIDs[] = Zotero_Groups::getLibraryIDFromGroupID($groupID);
     }
     // Separate libraries into shards for querying
     $libraryIDs = array_unique(array_merge($joinedLibraryIDs, $updatedLibraryIDs));
     $shardLibraryIDs = array();
     foreach ($libraryIDs as $libraryID) {
         $shardID = Zotero_Shards::getByLibraryID($libraryID);
         if (!isset($shardLibraryIDs[$shardID])) {
             $shardLibraryIDs[$shardID] = array('updated' => array(), 'joined' => array());
         }
         if (in_array($libraryID, $joinedLibraryIDs)) {
             $shardLibraryIDs[$shardID]['joined'][] = $libraryID;
         } else {
             $shardLibraryIDs[$shardID]['updated'][] = $libraryID;
         }
     }
     if ($countOnly) {
         $count = 0;
         $fieldList = "COUNT(*)";
     } else {
         $updatedByLibraryID = array();
         $fieldList = "libraryID, {$id} AS id";
     }
     // Send query at each shard
     foreach ($shardLibraryIDs as $shardID => $libraryIDs) {
         $sql = "SELECT {$fieldList} FROM {$table} WHERE ";
         if ($libraryIDs['updated']) {
             $sql .= "(libraryID IN (" . implode(', ', array_fill(0, sizeOf($libraryIDs['updated']), '?')) . ")";
             $params = $libraryIDs['updated'];
             $sql .= " AND {$timestampCol} >= FROM_UNIXTIME(?))";
             $params[] = $timestamp;
         }
         if ($libraryIDs['joined']) {
             if ($libraryIDs['updated']) {
                 $sql .= " OR ";
             } else {
                 $params = array();
             }
             $sql .= "libraryID IN (" . implode(', ', array_fill(0, sizeOf($libraryIDs['joined']), '?')) . ")";
             $params = array_merge($params, $libraryIDs['joined']);
         }
         if ($countOnly) {
             $count += Zotero_DB::valueQuery($sql, $params, $shardID);
         } else {
             $rows = Zotero_DB::query($sql, $params, $shardID);
             if ($rows) {
                 // Separate ids by libraryID
                 foreach ($rows as $row) {
                     $updatedByLibraryID[$row['libraryID']][] = $row['id'];
                 }
             }
         }
     }
     return $countOnly ? $count : $updatedByLibraryID;
 }
Beispiel #2
0
 private static function getURIObject($objectURI, $type)
 {
     $Types = ucwords($type) . 's';
     $types = strtolower($Types);
     $libraryType = null;
     $baseURI = self::getBaseURI();
     // If not found, try global URI
     if (strpos($objectURI, $baseURI) !== 0) {
         throw new Exception("Invalid base URI '{$objectURI}'");
     }
     $objectURI = substr($objectURI, strlen($baseURI));
     $typeRE = "/^(users|groups)\\/([0-9]+)(?:\\/|\$)/";
     if (!preg_match($typeRE, $objectURI, $matches)) {
         throw new Exception("Invalid library URI '{$objectURI}'");
     }
     $libraryType = substr($matches[1], 0, -1);
     $id = $matches[2];
     $objectURI = preg_replace($typeRE, '', $objectURI);
     if ($libraryType == 'user') {
         if (!Zotero_Users::exists($id)) {
             return false;
         }
         $libraryID = Zotero_Users::getLibraryIDFromUserID($id);
     } else {
         if ($libraryType == 'group') {
             if (!Zotero_Groups::get($id)) {
                 return false;
             }
             $libraryID = Zotero_Groups::getLibraryIDFromGroupID($id);
         } else {
             throw new Exception("Invalid library type {$libraryType}");
         }
     }
     if ($type === 'library') {
         return $libraryID;
     } else {
         // TODO: objectID-based URI?
         if (!preg_match($types . "\\/([A-Z0-9]{8})", $objectURI, $matches)) {
             throw new Exception("Invalid object URI '{$objectURI}'");
         }
         $objectKey = $matches[1];
         return call_user_func(array("Zotero_{$Types}", "getByLibraryAndKey"), $libraryID, $objectKey);
     }
 }
Beispiel #3
0
 public static function getUserOwnedGroupLibraries($userID)
 {
     $groups = self::getUserOwnedGroups($userID);
     $libraries = array();
     foreach ($groups as $group) {
         $libraries[] = Zotero_Groups::getLibraryIDFromGroupID($group);
     }
     return $libraries;
 }
Beispiel #4
0
 public static function getByGroupID($groupID)
 {
     $libraryID = Zotero_Groups::getLibraryIDFromGroupID($groupID);
     return self::getByLibraryID($libraryID);
 }
Beispiel #5
0
 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);
 }
 public function __construct($action, $settings, $extra)
 {
     if (!Z_CONFIG::$API_ENABLED) {
         $this->e503(Z_CONFIG::$MAINTENANCE_MESSAGE);
     }
     set_exception_handler(array($this, 'handleException'));
     set_error_handler(array($this, 'handleError'), E_USER_ERROR);
     require_once '../model/Error.inc.php';
     $this->startTime = microtime(true);
     $this->method = $_SERVER['REQUEST_METHOD'];
     /*if (isset($_SERVER['REMOTE_ADDR'])
     				&& in_array($_SERVER['REMOTE_ADDR'], array(''))) {
     			header("HTTP/1.1 429 Rate Limited");
     			die("Too many requests");
     		}*/
     if (!in_array($this->method, array('HEAD', 'GET', 'PUT', 'POST', 'DELETE', 'PATCH'))) {
         header("HTTP/1.1 501 Not Implemented");
         die("Method is not implemented");
     }
     // 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");
     }
     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->profile) {
         Zotero_DB::profileStart($this->profileShard);
     }
     // 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'])) {
                 $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);
             } else {
                 $this->e401('Invalid login');
             }
         }
     } else {
         if (isset($_GET['key'])) {
             $keyObj = Zotero_Keys::authenticate($_GET['key']);
             if (!$keyObj) {
                 $this->e403('Invalid key');
             }
             $this->apiKey = $_GET['key'];
             $this->userID = $keyObj->userID;
             $this->permissions = $keyObj->getPermissions();
             // Check X-Zotero-Write-Token if it exists to make sure
             if ($this->method == 'POST' || $this->method == 'PUT') {
                 if ($cacheKey = $this->getWriteTokenCacheKey()) {
                     if (Z_Core::$MC->get($cacheKey)) {
                         $this->e412("Write token already used");
                     }
                 }
             }
         } else {
             if (!empty($_COOKIE) && !empty($_GET['session']) && ($this->userID = Zotero_Users::getUserIDFromSession($_COOKIE, $_GET['session']))) {
                 $this->grantUserPermissions($this->userID);
                 $this->cookieAuth = true;
             } else {
                 if (!empty($_GET['auth'])) {
                     $this->e401();
                 }
                 // Always challenge a 'me' request
                 if (!empty($extra['userID']) && $extra['userID'] == 'me') {
                     $this->e403('You must specify a key when making a /me request.');
                 }
                 // Explicit auth request or not a GET request
                 if ($this->method != "GET") {
                     $this->e403('You must specify a key to access the Zotero API.');
                 }
                 // Anonymous request
                 $this->permissions = new Zotero_Permissions();
                 $this->permissions->setAnonymous();
             }
         }
     }
     // Get the API version
     if (empty($_REQUEST['version'])) {
         $this->apiVersion = $this->defaultAPIVersion;
     } else {
         if (!in_array($_REQUEST['version'], $this->validAPIVersions)) {
             $this->e400("Invalid request API version '{$_REQUEST['version']}'");
         }
         $this->apiVersion = (int) $_REQUEST['version'];
     }
     $this->uri = Z_CONFIG::$API_BASE_URI . substr($_SERVER["REQUEST_URI"], 1);
     // Get object user
     if (!empty($extra['userID'])) {
         // Possibly temporary shortcut for viewing one's own data via HTTP Auth
         if ($extra['userID'] == 'me') {
             $objectUserID = $this->userID;
         } else {
             $objectUserID = (int) $extra['userID'];
             if (!$objectUserID) {
                 $this->e400("Invalid user ID", Z_ERROR_INVALID_INPUT);
             }
         }
         $this->objectUserID = $objectUserID;
         try {
             $this->objectLibraryID = Zotero_Users::getLibraryIDFromUserID($objectUserID);
         } catch (Exception $e) {
             if ($e->getCode() == Z_ERROR_USER_NOT_FOUND) {
                 try {
                     Zotero_Users::addFromWWW($objectUserID);
                 } catch (Exception $e) {
                     if ($e->getCode() == Z_ERROR_USER_NOT_FOUND) {
                         $this->e404();
                     }
                     throw $e;
                 }
                 $this->objectLibraryID = Zotero_Users::getLibraryIDFromUserID($objectUserID);
             } else {
                 throw $e;
             }
         }
         // Make sure user isn't banned
         if (!Zotero_Users::isValidUser($objectUserID)) {
             $this->e404();
         }
     } else {
         if (!empty($extra['groupID'])) {
             $objectGroupID = (int) $extra['groupID'];
             if (!$objectGroupID) {
                 $this->e400("Invalid group ID", Z_ERROR_INVALID_INPUT);
             }
             // Make sure group exists
             $group = Zotero_Groups::get($objectGroupID);
             if (!$group) {
                 $this->e404();
             }
             // Don't show groups owned by banned users
             if (!Zotero_Users::isValidUser($group->ownerUserID)) {
                 $this->e404();
             }
             $this->objectGroupID = $objectGroupID;
             $this->objectLibraryID = Zotero_Groups::getLibraryIDFromGroupID($objectGroupID);
         }
     }
     // Return 409 if target library is locked
     switch ($this->method) {
         case 'POST':
         case 'PUT':
         case 'DELETE':
             switch ($action) {
                 // Library lock doesn't matter for some admin requests
                 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'] : null;
     $this->scopeObjectID = !empty($extra['scopeObjectID']) ? (int) $extra['scopeObjectID'] : null;
     if (!empty($extra['scopeObjectKey'])) {
         // Handle incoming requests using ids instead of keys
         //  - Keys might be all numeric, so only do this if length != 8
         if (preg_match('/^[0-9]+$/', $extra['scopeObjectKey']) && strlen($extra['scopeObjectKey']) != 8) {
             $this->scopeObjectID = (int) $extra['scopeObjectKey'];
         } else {
             if (preg_match('/[A-Z0-9]{8}/', $extra['scopeObjectKey'])) {
                 $this->scopeObjectKey = $extra['scopeObjectKey'];
             }
         }
     }
     $this->scopeObjectName = !empty($extra['scopeObjectName']) ? urldecode($extra['scopeObjectName']) : null;
     // Can be either id or key
     if (!empty($extra['key'])) {
         if (!empty($_GET['key']) && strlen($_GET['key']) == 8) {
             $this->objectKey = $extra['key'];
         } else {
             if (!empty($_GET['iskey'])) {
                 $this->objectKey = $extra['key'];
             } else {
                 if (preg_match('/^[0-9]+$/', $extra['key'])) {
                     $this->objectID = (int) $extra['key'];
                 } else {
                     if (preg_match('/^[A-Z0-9]{8}$/', $extra['key'])) {
                         $this->objectKey = $extra['key'];
                     } else {
                         if ($extra['key'] != 'top') {
                             Z_Core::logError("=============");
                             Z_Core::logError("Invalid key");
                             Z_Core::logError($extra['key']);
                         }
                     }
                 }
             }
         }
     }
     if (!empty($extra['id'])) {
         $this->objectID = (int) $extra['id'];
     }
     $this->objectName = !empty($extra['name']) ? urldecode($extra['name']) : null;
     $this->subset = !empty($extra['subset']) ? $extra['subset'] : null;
     $this->fileMode = !empty($extra['file']) ? !empty($_GET['info']) ? 'info' : 'download' : false;
     $this->fileView = !empty($extra['view']);
     $singleObject = ($this->objectID || $this->objectKey) && !$this->subset;
     $this->queryParams = Zotero_API::parseQueryParams($_SERVER['QUERY_STRING'], $action, $singleObject);
 }
Beispiel #7
0
 private static function getDeletedObjectIDs($userID, $timestamp, $includeAllUserObjects = false)
 {
     /*
     $sql = "SELECT version FROM version WHERE schema='syncdeletelog'";
     $syncLogStart = Zotero_DB::valueQuery($sql);
     if (!$syncLogStart) {
     	throw ('Sync log start time not found');
     }
     */
     /*
     // Last sync time is before start of log
     if ($lastSyncDate && new Date($syncLogStart * 1000) > $lastSyncDate) {
     	return -1;
     }
     */
     // Personal library
     $shardID = Zotero_Shards::getByUserID($userID);
     $libraryID = Zotero_Users::getLibraryIDFromUserID($userID);
     $shardLibraryIDs[$shardID] = array($libraryID);
     // Group libraries
     if ($includeAllUserObjects) {
         $groupIDs = Zotero_Groups::getUserGroups($userID);
         if ($groupIDs) {
             // Separate groups into shards for querying
             foreach ($groupIDs as $groupID) {
                 $libraryID = Zotero_Groups::getLibraryIDFromGroupID($groupID);
                 $shardID = Zotero_Shards::getByLibraryID($libraryID);
                 if (!isset($shardLibraryIDs[$shardID])) {
                     $shardLibraryIDs[$shardID] = array();
                 }
                 $shardLibraryIDs[$shardID][] = $libraryID;
             }
         }
     }
     // Send query at each shard
     $rows = array();
     foreach ($shardLibraryIDs as $shardID => $libraryIDs) {
         $sql = "SELECT libraryID, objectType, id, timestamp\n\t\t\t\t\tFROM syncDeleteLogIDs WHERE libraryID IN (" . implode(', ', array_fill(0, sizeOf($libraryIDs), '?')) . ")";
         $params = $libraryIDs;
         if ($timestamp) {
             // Send any entries from before these were being properly sent
             if ($timestamp < 1260778500) {
                 $sql .= " AND (timestamp >= FROM_UNIXTIME(?) OR timestamp BETWEEN 1257968068 AND FROM_UNIXTIME(?))";
                 $params[] = $timestamp;
                 $params[] = 1260778500;
             } else {
                 $sql .= " AND timestamp >= FROM_UNIXTIME(?)";
                 $params[] = $timestamp;
             }
         }
         $sql .= " ORDER BY timestamp";
         $shardRows = Zotero_DB::query($sql, $params, $shardID);
         if ($shardRows) {
             $rows = array_merge($rows, $shardRows);
         }
     }
     if (!$rows) {
         return false;
     }
     $deletedIDs = array('groups' => array());
     foreach ($rows as $row) {
         $type = $row['objectType'] . 's';
         $deletedIDs[$type][] = $row['id'];
     }
     return $deletedIDs;
 }