当前位置: 首页>>代码示例>>PHP>>正文


PHP Zotero_DB::beginTransaction方法代码示例

本文整理汇总了PHP中Zotero_DB::beginTransaction方法的典型用法代码示例。如果您正苦于以下问题:PHP Zotero_DB::beginTransaction方法的具体用法?PHP Zotero_DB::beginTransaction怎么用?PHP Zotero_DB::beginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Zotero_DB的用法示例。


在下文中一共展示了Zotero_DB::beginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: add

 public static function add($userID)
 {
     Z_Core::debug("Creating publications library for user {$userID}");
     Zotero_DB::beginTransaction();
     // Use same shard as user library
     $shardID = Zotero_Shards::getByUserID($userID);
     $libraryID = Zotero_Libraries::add('publications', $shardID);
     $sql = "INSERT INTO userPublications (userID, libraryID) VALUES (?, ?)";
     Zotero_DB::query($sql, [$userID, $libraryID]);
     Zotero_DB::commit();
     return $libraryID;
 }
开发者ID:selenus,项目名称:dataserver,代码行数:12,代码来源:Publications.inc.php

示例2: upload

 /**
  * Handle uploaded data, overwriting existing data
  */
 public function upload()
 {
     $this->sessionCheck();
     // Another session is either queued or writing — upload data won't be valid,
     // so client should wait and return to /updated with 'upload' flag
     Zotero_DB::beginTransaction();
     if (Zotero_Sync::userIsReadLocked($this->userID) || Zotero_Sync::userIsWriteLocked($this->userID)) {
         Zotero_DB::commit();
         $locked = $this->responseXML->addChild('locked');
         $locked['wait'] = $this->getWaitTime($this->sessionID);
         $this->end();
     }
     Zotero_DB::commit();
     $this->clearWaitTime($this->sessionID);
     if (empty($_REQUEST['updateKey'])) {
         $this->error(400, 'INVALID_UPLOAD_DATA', 'Update key not provided');
     }
     if ($_REQUEST['updateKey'] != Zotero_Users::getUpdateKey($this->userID)) {
         $this->e409("Server data has changed since last retrieval");
     }
     // TODO: change to POST
     if (empty($_REQUEST['data'])) {
         $this->error(400, 'MISSING_UPLOAD_DATA', 'Uploaded data not provided');
     }
     $xmldata =& $_REQUEST['data'];
     try {
         $doc = new DOMDocument();
         $doc->loadXML($xmldata, LIBXML_PARSEHUGE);
         // For huge uploads, make sure notes aren't bigger than SimpleXML can parse
         if (strlen($xmldata) > 7000000) {
             $xpath = new DOMXPath($doc);
             $results = $xpath->query('/data/items/item/note[string-length(text()) > ' . Zotero_Notes::$MAX_NOTE_LENGTH . ']');
             if ($results->length) {
                 $noteElem = $results->item(0);
                 $text = $noteElem->textContent;
                 $libraryID = $noteElem->parentNode->getAttribute('libraryID');
                 $key = $noteElem->parentNode->getAttribute('key');
                 // UTF-8   (0xC2 0xA0) isn't trimmed by default
                 $whitespace = chr(0x20) . chr(0x9) . chr(0xa) . chr(0xd) . chr(0x0) . chr(0xb) . chr(0xc2) . chr(0xa0);
                 $excerpt = iconv("UTF-8", "UTF-8//IGNORE", Zotero_Notes::noteToTitle(trim($text), true));
                 $excerpt = trim($excerpt, $whitespace);
                 // If tag-stripped version is empty, just return raw HTML
                 if ($excerpt == '') {
                     $excerpt = iconv("UTF-8", "UTF-8//IGNORE", preg_replace('/\\s+/', ' ', mb_substr(trim($text), 0, Zotero_Notes::$MAX_TITLE_LENGTH)));
                     $excerpt = html_entity_decode($excerpt);
                     $excerpt = trim($excerpt, $whitespace);
                 }
                 $msg = "=Note '" . $excerpt . "...' too long";
                 if ($key) {
                     $msg .= " for item '" . $libraryID . "/" . $key . "'";
                 }
                 throw new Exception($msg, Z_ERROR_NOTE_TOO_LONG);
             }
         }
     } catch (Exception $e) {
         $this->handleUploadError($e, $xmldata);
     }
     function relaxNGErrorHandler($errno, $errstr)
     {
         //Z_Core::logError($errstr);
     }
     set_error_handler('relaxNGErrorHandler');
     set_time_limit(60);
     if (!$doc->relaxNGValidate(Z_ENV_MODEL_PATH . 'relax-ng/upload.rng')) {
         $id = substr(md5(uniqid(rand(), true)), 0, 10);
         $str = date("D M j G:i:s T Y") . "\n";
         $str .= "IP address: " . $_SERVER['REMOTE_ADDR'] . "\n";
         if (isset($_SERVER['HTTP_X_ZOTERO_VERSION'])) {
             $str .= "Version: " . $_SERVER['HTTP_X_ZOTERO_VERSION'] . "\n";
         }
         $str .= "Error: RELAX NG validation failed\n\n";
         $str .= $xmldata;
         if (!file_put_contents(Z_CONFIG::$SYNC_ERROR_PATH . $id, $str)) {
             error_log("Unable to save error report to " . Z_CONFIG::$SYNC_ERROR_PATH . $id);
         }
         $this->error(500, 'INVALID_UPLOAD_DATA', "Uploaded data not well-formed (Report ID: {$id})");
     }
     restore_error_handler();
     try {
         $xml = simplexml_import_dom($doc);
         $queue = true;
         if (Z_ENV_TESTING_SITE && !empty($_GET['noqueue'])) {
             $queue = false;
         }
         if ($queue) {
             $affectedLibraries = Zotero_Sync::parseAffectedLibraries($xmldata);
             // Relations-only uploads don't have affected libraries
             if (!$affectedLibraries) {
                 $affectedLibraries = array(Zotero_Users::getLibraryIDFromUserID($this->userID));
             }
             Zotero_Sync::queueUpload($this->userID, $this->sessionID, $xmldata, $affectedLibraries);
             try {
                 Zotero_Processors::notifyProcessors('upload');
                 Zotero_Processors::notifyProcessors('error');
                 usleep(750000);
             } catch (Exception $e) {
                 Z_Core::logError($e);
//.........这里部分代码省略.........
开发者ID:selenus,项目名称:dataserver,代码行数:101,代码来源:SyncController.php

示例3: save

	public function save($userID=false) {
		if (!$this->_libraryID) {
			trigger_error("Library ID must be set before saving", E_USER_ERROR);
		}
		
		Zotero_Items::editCheck($this, $userID);
		
		if (!$this->hasChanged()) {
			Z_Core::debug("Item $this->id has not changed");
			return false;
		}
		
		$this->cacheEnabled = false;
		
		// Make sure there are no gaps in the creator indexes
		$creators = $this->getCreators();
		$lastPos = -1;
		foreach ($creators as $pos=>$creator) {
			if ($pos != $lastPos + 1) {
				trigger_error("Creator index $pos out of sequence for item $this->id", E_USER_ERROR);
			}
			$lastPos++;
		}
		
		$shardID = Zotero_Shards::getByLibraryID($this->_libraryID);
		
		$env = [];
		
		Zotero_DB::beginTransaction();
		
		try {
			//
			// New item, insert and return id
			//
			if (!$this->id || (empty($this->changed['version']) && !$this->exists())) {
				Z_Core::debug('Saving data for new item to database');
				
				$isNew = $env['isNew'] = true;
				$sqlColumns = array();
				$sqlValues = array();
				
				//
				// Primary fields
				//
				$itemID = $this->_id = $this->_id ? $this->_id : Zotero_ID::get('items');
				$key = $this->_key = $this->_key ? $this->_key : Zotero_ID::getKey();
				
				$sqlColumns = array(
					'itemID',
					'itemTypeID',
					'libraryID',
					'key',
					'dateAdded',
					'dateModified',
					'serverDateModified',
					'version'
				);
				$timestamp = Zotero_DB::getTransactionTimestamp();
				$dateAdded = $this->_dateAdded ? $this->_dateAdded : $timestamp;
				$dateModified = $this->_dateModified ? $this->_dateModified : $timestamp;
				$version = Zotero_Libraries::getUpdatedVersion($this->_libraryID);
				$sqlValues = array(
					$itemID,
					$this->_itemTypeID,
					$this->_libraryID,
					$key,
					$dateAdded,
					$dateModified,
					$timestamp,
					$version
				);
				
				$sql = 'INSERT INTO items (`' . implode('`, `', $sqlColumns) . '`) VALUES (';
				// Insert placeholders for bind parameters
				for ($i=0; $i<sizeOf($sqlValues); $i++) {
					$sql .= '?, ';
				}
				$sql = substr($sql, 0, -2) . ')';
				
				// Save basic data to items table
				try {
					$insertID = Zotero_DB::query($sql, $sqlValues, $shardID);
				}
				catch (Exception $e) {
					if (strpos($e->getMessage(), "Incorrect datetime value") !== false) {
						preg_match("/Incorrect datetime value: '([^']+)'/", $e->getMessage(), $matches);
						throw new Exception("=Invalid date value '{$matches[1]}' for item $key", Z_ERROR_INVALID_INPUT);
					}
					throw $e;
				}
				if (!$this->_id) {
					if (!$insertID) {
						throw new Exception("Item id not available after INSERT");
					}
					$itemID = $insertID;
					$this->_serverDateModified = $timestamp;
				}
				
				// Group item data
				if (Zotero_Libraries::getType($this->_libraryID) == 'group' && $userID) {
//.........这里部分代码省略.........
开发者ID:kskod,项目名称:dataserver,代码行数:101,代码来源:Item.inc.php

示例4: setTags

 /**
  * $tags is an array of objects with properties 'tag' and 'type'
  */
 public function setTags($newTags)
 {
     if (!$this->id) {
         throw new Exception('itemID not set');
     }
     $numTags = $this->numTags();
     if (!$newTags && !$numTags) {
         return false;
     }
     Zotero_DB::beginTransaction();
     $existingTags = $this->getTags();
     $toAdd = array();
     $toRemove = array();
     // Get new tags not in existing
     for ($i = 0, $len = sizeOf($newTags); $i < $len; $i++) {
         if (!isset($newTags[$i]->type)) {
             $newTags[$i]->type = 0;
         }
         $name = trim($newTags[$i]->tag);
         // 'tag', not 'name', since that's what JSON uses
         $type = $newTags[$i]->type;
         foreach ($existingTags as $tag) {
             // Do a case-insensitive comparison, to match the client
             if (strtolower($tag->name) == strtolower($name) && $tag->type == $type) {
                 continue 2;
             }
         }
         $toAdd[] = $newTags[$i];
     }
     // Get existing tags not in new
     for ($i = 0, $len = sizeOf($existingTags); $i < $len; $i++) {
         $name = $existingTags[$i]->name;
         $type = $existingTags[$i]->type;
         foreach ($newTags as $tag) {
             if (strtolower($tag->tag) == strtolower($name) && $tag->type == $type) {
                 continue 2;
             }
         }
         $toRemove[] = $existingTags[$i];
     }
     foreach ($toAdd as $tag) {
         $name = $tag->tag;
         $type = $tag->type;
         $tagID = Zotero_Tags::getID($this->libraryID, $name, $type, true);
         if (!$tagID) {
             $tag = new Zotero_Tag();
             $tag->libraryID = $this->libraryID;
             $tag->name = $name;
             $tag->type = $type;
             $tagID = $tag->save();
         }
         $tag = Zotero_Tags::get($this->libraryID, $tagID);
         $tag->addItem($this->id);
         $tag->save();
     }
     foreach ($toRemove as $tag) {
         $tag->removeItem($this->id);
         $tag->save();
     }
     Zotero_DB::commit();
     return $toAdd || $toRemove;
 }
开发者ID:robinpaulson,项目名称:dataserver,代码行数:65,代码来源:Item.inc.php

示例5: keys

 public function keys()
 {
     $userID = $this->objectUserID;
     $key = $this->objectName;
     $this->allowMethods(['GET', 'POST', 'PUT', 'DELETE']);
     if ($this->method == 'GET') {
         // Single key
         if ($key) {
             $keyObj = Zotero_Keys::getByKey($key);
             if (!$keyObj) {
                 $this->e404("Key not found");
             }
             // /users/<userID>/keys/<keyID> (deprecated)
             if ($userID) {
                 // If we have a userID, make sure it matches
                 if ($keyObj->userID != $userID) {
                     $this->e404("Key not found");
                 }
             } else {
                 if ($this->apiVersion < 3) {
                     $this->e404();
                 }
             }
             if ($this->apiVersion >= 3) {
                 $json = $keyObj->toJSON();
                 // If not super-user, don't include name or recent IP addresses
                 if (!$this->permissions->isSuper()) {
                     unset($json['dateAdded']);
                     unset($json['lastUsed']);
                     unset($json['name']);
                     unset($json['recentIPs']);
                 }
                 header('application/json');
                 echo Zotero_Utilities::formatJSON($json);
             } else {
                 $this->responseXML = $keyObj->toXML();
                 // If not super-user, don't include name or recent IP addresses
                 if (!$this->permissions->isSuper()) {
                     unset($this->responseXML['dateAdded']);
                     unset($this->responseXML['lastUsed']);
                     unset($this->responseXML->name);
                     unset($this->responseXML->recentIPs);
                 }
             }
         } else {
             if (!$this->permissions->isSuper()) {
                 $this->e403();
             }
             $keyObjs = Zotero_Keys::getUserKeys($userID);
             if ($keyObjs) {
                 if ($this->apiVersion >= 3) {
                     $json = [];
                     foreach ($keyObjs as $keyObj) {
                         $json[] = $keyObj->toJSON();
                     }
                     echo Zotero_Utilities::formatJSON($json);
                 } else {
                     $xml = new SimpleXMLElement('<keys/>');
                     $domXML = dom_import_simplexml($xml);
                     foreach ($keyObjs as $keyObj) {
                         $keyXML = $keyObj->toXML();
                         $domKeyXML = dom_import_simplexml($keyXML);
                         $node = $domXML->ownerDocument->importNode($domKeyXML, true);
                         $domXML->appendChild($node);
                     }
                     $this->responseXML = $xml;
                 }
             }
         }
     } else {
         if ($this->method == 'DELETE') {
             if (!$key) {
                 $this->e400("DELETE requests must end with a key");
             }
             Zotero_DB::beginTransaction();
             $keyObj = Zotero_Keys::getByKey($key);
             if (!$keyObj) {
                 $this->e404("Key '{$key}' does not exist");
             }
             $keyObj->erase();
             Zotero_DB::commit();
             header("HTTP/1.1 204 No Content");
             exit;
         } else {
             // Require super-user for modifications
             if (!$this->permissions->isSuper()) {
                 $this->e403();
             }
             if ($this->method == 'POST') {
                 if ($key) {
                     $this->e400("POST requests cannot end with a key (did you mean PUT?)");
                 }
                 if ($this->apiVersion >= 3) {
                     $json = json_decode($this->body, true);
                     if (!$json) {
                         $this->e400("{$this->method} data is not valid JSON");
                     }
                     if (!empty($json['key'])) {
                         $this->e400("POST requests cannot contain a key in '" . $this->body . "'");
                     }
//.........这里部分代码省略.........
开发者ID:kskod,项目名称:dataserver,代码行数:101,代码来源:KeysController.php

示例6: copyLibrary

 public static function copyLibrary($libraryID, $newShardID, $overrideLock = false)
 {
     $currentShardID = self::getByLibraryID($libraryID);
     if ($currentShardID == $newShardID) {
         throw new Exception("Library {$libraryID} is already on shard {$newShardID}");
     }
     if (!self::shardIsWriteable($newShardID)) {
         throw new Exception("Shard {$newShardID} is not writeable");
     }
     if (!$overrideLock && Zotero_Libraries::isLocked($libraryID)) {
         throw new Exception("Library {$libraryID} is locked");
     }
     // Make sure there's no stale data on the new shard
     if (self::checkForLibrary($libraryID, $newShardID)) {
         throw new Exception("Library {$libraryID} data already exists on shard {$newShardID}");
     }
     Zotero_DB::beginTransaction();
     Zotero_DB::query("SET foreign_key_checks=0", false, $newShardID);
     $tables = array('shardLibraries', 'collections', 'creators', 'items', 'relations', 'savedSearches', 'tags', 'collectionItems', 'deletedItems', 'groupItems', 'itemAttachments', 'itemCreators', 'itemData', 'itemNotes', 'itemRelated', 'itemSortFields', 'itemTags', 'savedSearchConditions', 'storageFileItems', 'syncDeleteLogIDs', 'syncDeleteLogKeys');
     foreach ($tables as $table) {
         if (!$overrideLock && Zotero_Libraries::isLocked($libraryID)) {
             Zotero_DB::rollback();
             throw new Exception("Aborted due to library lock");
         }
         switch ($table) {
             case 'collections':
             case 'creators':
             case 'items':
             case 'relations':
             case 'savedSearches':
             case 'shardLibraries':
             case 'syncDeleteLogIDs':
             case 'syncDeleteLogKeys':
             case 'tags':
                 $sql = "SELECT * FROM {$table} WHERE libraryID=?";
                 break;
             case 'collectionItems':
                 $sql = "SELECT CI.* FROM collectionItems CI\n\t\t\t\t\t\t\tJOIN collections USING (collectionID) WHERE libraryID=?";
                 break;
             case 'deletedItems':
             case 'groupItems':
             case 'itemAttachments':
             case 'itemCreators':
             case 'itemData':
             case 'itemNotes':
             case 'itemRelated':
             case 'itemSortFields':
             case 'itemTags':
             case 'storageFileItems':
                 $sql = "SELECT T.* FROM {$table} T JOIN items USING (itemID) WHERE libraryID=?";
                 break;
             case 'savedSearchConditions':
                 $sql = "SELECT SSC.* FROM savedSearchConditions SSC\n\t\t\t\t\t\t\tJOIN savedSearches USING (searchID) WHERE libraryID=?";
                 break;
         }
         $rows = Zotero_DB::query($sql, $libraryID, $currentShardID);
         if ($rows) {
             $sets = array();
             foreach ($rows as $row) {
                 $sets[] = array_values($row);
             }
             $sql = "INSERT INTO {$table} VALUES ";
             Zotero_DB::bulkInsert($sql, $sets, 50, false, $newShardID);
         }
     }
     Zotero_DB::query("SET foreign_key_checks=1", false, $newShardID);
     if (!$overrideLock && Zotero_Libraries::isLocked($libraryID)) {
         Zotero_DB::rollback();
         throw new Exception("Aborted due to library lock");
     }
     Zotero_DB::commit();
     if (!$overrideLock && Zotero_Libraries::isLocked($libraryID)) {
         self::deleteLibrary($libraryID, $newShardID);
         throw new Exception("Aborted due to library lock");
     }
 }
开发者ID:ergo70,项目名称:dataserver,代码行数:76,代码来源:Shards.inc.php

示例7: storageadmin

 public function storageadmin()
 {
     if (!$this->permissions->isSuper()) {
         $this->e404();
     }
     $this->allowMethods(array('GET', 'POST'));
     Zotero_DB::beginTransaction();
     if ($this->method == 'POST') {
         if (!isset($_POST['quota'])) {
             $this->e400("Quota not provided");
         }
         // Accept 'unlimited' via API
         if ($_POST['quota'] == 'unlimited') {
             $_POST['quota'] = self::UNLIMITED;
         }
         if (!isset($_POST['expiration'])) {
             $this->e400("Expiration not provided");
         }
         if (!is_numeric($_POST['quota']) || $_POST['quota'] < 0) {
             $this->e400("Invalid quota");
         }
         if (!is_numeric($_POST['expiration'])) {
             $this->e400("Invalid expiration");
         }
         $halfHourAgo = strtotime("-30 minutes");
         if ($_POST['expiration'] != 0 && $_POST['expiration'] < $halfHourAgo) {
             $this->e400("Expiration is in the past");
         }
         try {
             Zotero_Storage::setUserValues($this->objectUserID, $_POST['quota'], $_POST['expiration']);
         } catch (Exception $e) {
             if ($e->getCode() == Z_ERROR_GROUP_QUOTA_SET_BELOW_USAGE) {
                 $this->e409("Cannot set quota below current usage");
             }
             $this->handleException($e);
         }
     }
     // GET request
     $xml = new SimpleXMLElement('<storage/>');
     $quota = Zotero_Storage::getEffectiveUserQuota($this->objectUserID);
     $xml->quota = $quota;
     $instQuota = Zotero_Storage::getInstitutionalUserQuota($this->objectUserID);
     // If personal quota is in effect
     if (!$instQuota || $quota > $instQuota) {
         $values = Zotero_Storage::getUserValues($this->objectUserID);
         if ($values) {
             $xml->expiration = (int) $values['expiration'];
         }
     }
     // Return 'unlimited' via API
     if ($quota == self::UNLIMITED) {
         $xml->quota = 'unlimited';
     }
     $usage = Zotero_Storage::getUserUsage($this->objectUserID);
     $xml->usage->total = $usage['total'];
     $xml->usage->library = $usage['library'];
     foreach ($usage['groups'] as $group) {
         if (!isset($group['id'])) {
             throw new Exception("Group id isn't set");
         }
         if (!isset($group['usage'])) {
             throw new Exception("Group usage isn't set");
         }
         $xmlGroup = $xml->usage->addChild('group', $group['usage']);
         $xmlGroup['id'] = $group['id'];
     }
     Zotero_DB::commit();
     header('application/xml');
     echo $xml->asXML();
     exit;
 }
开发者ID:kskod,项目名称:dataserver,代码行数:71,代码来源:StorageController.php

示例8: purgeUnusedFiles

 public static function purgeUnusedFiles()
 {
     throw new Exception("Now sharded");
     self::requireLibrary();
     // Get all used files and files that were last deleted more than a month ago
     $sql = "SELECT MD5(CONCAT(hash, filename, zip)) AS file FROM storageFiles\n\t\t\t\t\tJOIN storageFileItems USING (storageFileID)\n\t\t\t\tUNION\n\t\t\t\tSELECT MD5(CONCAT(hash, filename, zip)) AS file FROM storageFiles\n\t\t\t\t\tWHERE lastDeleted > NOW() - INTERVAL 1 MONTH";
     $files = Zotero_DB::columnQuery($sql);
     S3::setAuth(Z_CONFIG::$S3_ACCESS_KEY, Z_CONFIG::$S3_SECRET_KEY);
     $s3Files = S3::getBucket(Z_CONFIG::$S3_BUCKET);
     $toPurge = array();
     foreach ($s3Files as $s3File) {
         preg_match('/^([0-9a-g]{32})\\/(c\\/)?(.+)$/', $s3File['name'], $matches);
         if (!$matches) {
             throw new Exception("Invalid filename '" . $s3File['name'] . "'");
         }
         $zip = $matches[2] ? '1' : '0';
         // Compressed file
         $hash = md5($matches[1] . $matches[3] . $zip);
         if (!in_array($hash, $files)) {
             $toPurge[] = array('hash' => $matches[1], 'filename' => $matches[3], 'zip' => $zip);
         }
     }
     Zotero_DB::beginTransaction();
     foreach ($toPurge as $info) {
         S3::deleteObject(Z_CONFIG::$S3_BUCKET, self::getPathPrefix($info['hash'], $info['zip']) . $info['filename']);
         $sql = "DELETE FROM storageFiles WHERE hash=? AND filename=? AND zip=?";
         Zotero_DB::query($sql, array($info['hash'], $info['filename'], $info['zip']));
         // TODO: maybe check to make sure associated files haven't just been created?
     }
     Zotero_DB::commit();
     return sizeOf($toPurge);
 }
开发者ID:robinpaulson,项目名称:dataserver,代码行数:32,代码来源:S3.inc.php

示例9: erase

 public function erase()
 {
     if (!$this->loaded) {
         Z_Core::debug("Not deleting unloaded group {$this->id}");
         return;
     }
     Zotero_DB::beginTransaction();
     $userIDs = self::getUsers();
     $this->logGroupLibraryRemoval();
     Zotero_Libraries::deleteCachedData($this->libraryID);
     Zotero_Libraries::clearAllData($this->libraryID);
     $sql = "DELETE FROM shardLibraries WHERE libraryID=?";
     $deleted = Zotero_DB::query($sql, $this->libraryID, Zotero_Shards::getByLibraryID($this->libraryID));
     if (!$deleted) {
         throw new Exception("Group not deleted");
     }
     $sql = "DELETE FROM libraries WHERE libraryID=?";
     $deleted = Zotero_DB::query($sql, $this->libraryID);
     if (!$deleted) {
         throw new Exception("Group not deleted");
     }
     // Delete key permissions for this library, and then delete any keys
     // that had no other permissions
     $sql = "SELECT keyID FROM keyPermissions WHERE libraryID=?";
     $keyIDs = Zotero_DB::columnQuery($sql, $this->libraryID);
     if ($keyIDs) {
         $sql = "DELETE FROM keyPermissions WHERE libraryID=?";
         Zotero_DB::query($sql, $this->libraryID);
         $sql = "DELETE K FROM `keys` K LEFT JOIN keyPermissions KP USING (keyID)\n\t\t\t\t\tWHERE keyID IN (" . implode(', ', array_fill(0, sizeOf($keyIDs), '?')) . ") AND KP.keyID IS NULL";
         Zotero_DB::query($sql, $keyIDs);
     }
     // If group is locked by a sync, flag group for a timestamp update
     // once the sync is done so that the uploading user gets the change
     try {
         foreach ($userIDs as $userID) {
             if ($syncUploadQueueID = Zotero_Sync::getUploadQueueIDByUserID($userID)) {
                 Zotero_Sync::postWriteLog($syncUploadQueueID, 'group', $this->id, 'delete');
             }
         }
     } catch (Exception $e) {
         Z_Core::logError($e);
     }
     Zotero_Notifier::trigger('delete', 'library', $this->libraryID);
     Zotero_DB::commit();
     $this->erased = true;
 }
开发者ID:ergo70,项目名称:dataserver,代码行数:46,代码来源:Group.inc.php

示例10: addCustomType

 public static function addCustomType($name)
 {
     if (self::getID($name)) {
         trigger_error("Item type '{$name}' already exists", E_USER_ERROR);
     }
     if (!preg_match('/^[a-z][^\\s0-9]+$/', $name)) {
         trigger_error("Invalid item type name '{$name}'", E_USER_ERROR);
     }
     // TODO: make sure user hasn't added too many already
     Zotero_DB::beginTransaction();
     $sql = "SELECT NEXT_ID(creatorTypeID) FROM creatorTypes";
     $creatorTypeID = Zotero_DB::valueQuery($sql);
     $sql = "INSERT INTO creatorTypes (?, ?, ?)";
     Zotero_DB::query($sql, array($creatorTypeID, $name, 1));
     Zotero_DB::commit();
     return $creatorTypeID;
 }
开发者ID:selenus,项目名称:dataserver,代码行数:17,代码来源:CreatorTypes.inc.php

示例11: searches

 public function searches()
 {
     if ($this->apiVersion < 2) {
         $this->e404();
     }
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     $results = array();
     // Single search
     if ($this->singleObject) {
         $this->allowMethods(['HEAD', 'GET', 'PUT', 'PATCH', 'DELETE']);
         $search = Zotero_Searches::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if ($this->isWriteMethod()) {
             $search = $this->handleObjectWrite('search', $search ? $search : null);
             $this->e204();
         }
         if (!$search) {
             $this->e404("Search not found");
         }
         $this->libraryVersion = $search->version;
         if ($this->method == 'HEAD') {
             $this->end();
         }
         // Display search
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = $search->toAtom($this->queryParams);
                 break;
             case 'json':
                 $json = $search->toResponseJSON($this->queryParams, $this->permissions);
                 echo Zotero_Utilities::formatJSON($json);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     } else {
         $this->allowMethods(['HEAD', 'GET', 'POST', 'DELETE']);
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         // Create a search
         if ($this->method == 'POST') {
             $this->queryParams['format'] = 'writereport';
             $obj = $this->jsonDecode($this->body);
             $results = Zotero_Searches::updateMultipleFromJSON($obj, $this->objectLibraryID, $this->queryParams, $this->userID, $libraryTimestampChecked ? 0 : 1, null);
             if ($cacheKey = $this->getWriteTokenCacheKey()) {
                 Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
             }
         } else {
             if ($this->method == 'DELETE') {
                 Zotero_DB::beginTransaction();
                 foreach ($this->queryParams['searchKey'] as $searchKey) {
                     Zotero_Searches::delete($this->objectLibraryID, $searchKey);
                 }
                 Zotero_DB::commit();
                 $this->e204();
             } else {
                 $title = "Searches";
                 $results = Zotero_Searches::search($this->objectLibraryID, $this->queryParams);
             }
         }
         $options = ['action' => $this->action, 'uri' => $this->uri, 'results' => $results, 'requestParams' => $this->queryParams, 'permissions' => $this->permissions, 'head' => $this->method == 'HEAD'];
         switch ($this->queryParams['format']) {
             case 'atom':
                 $this->responseXML = Zotero_API::multiResponse(array_merge($options, ['title' => $this->getFeedNamePrefix($this->objectLibraryID) . $title]));
                 break;
             case 'json':
             case 'keys':
             case 'versions':
             case 'writereport':
                 Zotero_API::multiResponse($options);
                 break;
             default:
                 throw new Exception("Unexpected format '" . $this->queryParams['format'] . "'");
         }
     }
     $this->end();
 }
开发者ID:juego11,项目名称:dataserver,代码行数:89,代码来源:SearchesController.php

示例12: updateFileItemInfo

 public static function updateFileItemInfo($item, $storageFileID, Zotero_StorageFileInfo $info, $client = false)
 {
     if (!$item->isImportedAttachment()) {
         throw new Exception("Cannot add storage file for linked file/URL");
     }
     Zotero_DB::beginTransaction();
     if (!$client) {
         Zotero_Libraries::updateVersionAndTimestamp($item->libraryID);
     }
     self::updateLastAdded($storageFileID);
     // Note: We set the size on the shard so that usage queries are instantaneous
     $sql = "INSERT INTO storageFileItems (storageFileID, itemID, mtime, size) VALUES (?,?,?,?)\n\t\t\t\tON DUPLICATE KEY UPDATE storageFileID=?, mtime=?, size=?";
     Zotero_DB::query($sql, array($storageFileID, $item->id, $info->mtime, $info->size, $storageFileID, $info->mtime, $info->size), Zotero_Shards::getByLibraryID($item->libraryID));
     // 4.0 client doesn't set filename for ZIP files
     if (!$info->zip || !empty($info->itemFilename)) {
         $item->attachmentFilename = !empty($info->itemFilename) ? $info->itemFilename : $info->filename;
     }
     $item->attachmentStorageHash = !empty($info->itemHash) ? $info->itemHash : $info->hash;
     $item->attachmentStorageModTime = $info->mtime;
     // contentType and charset may not have been included in the
     // upload authorization, in which case we shouldn't overwrite
     // any values that may already be set on the attachment
     if (isset($info->contentType)) {
         $item->attachmentMIMEType = $info->contentType;
     }
     if (isset($info->charset)) {
         $item->attachmentCharset = $info->charset;
     }
     $item->save();
     Zotero_DB::commit();
 }
开发者ID:ergo70,项目名称:dataserver,代码行数:31,代码来源:Storage.inc.php

示例13: updateFromJSON

 public static function updateFromJSON(Zotero_Item $item, $json, $isNew = false, Zotero_Item $parentItem = null, $userID = null)
 {
     self::validateJSONItem($json, $item->libraryID, $isNew ? null : $item, !is_null($parentItem));
     Zotero_DB::beginTransaction();
     // Mark library as updated
     if (!$isNew) {
         $timestamp = Zotero_Libraries::updateTimestamps($item->libraryID);
         Zotero_DB::registerTransactionTimestamp($timestamp);
     }
     $forceChange = false;
     $twoStage = false;
     // Set itemType first
     $item->setField("itemTypeID", Zotero_ItemTypes::getID($json->itemType));
     foreach ($json as $key => $val) {
         switch ($key) {
             case 'itemType':
                 continue;
             case 'deleted':
                 continue;
             case 'creators':
                 if (!$val && !$item->numCreators()) {
                     continue 2;
                 }
                 $orderIndex = -1;
                 foreach ($val as $orderIndex => $newCreatorData) {
                     if ((!isset($newCreatorData->name) || trim($newCreatorData->name) == "") && (!isset($newCreatorData->firstName) || trim($newCreatorData->firstName) == "") && (!isset($newCreatorData->lastName) || trim($newCreatorData->lastName) == "")) {
                         // This should never happen, because of check in validateJSONItem()
                         if (!$isNew) {
                             throw new Exception("Nameless creator in update request");
                         }
                         // On item creation, ignore creators with empty names,
                         // because that's in the item template that the API returns
                         break;
                     }
                     // JSON uses 'name' and 'firstName'/'lastName',
                     // so switch to just 'firstName'/'lastName'
                     if (isset($newCreatorData->name)) {
                         $newCreatorData->firstName = '';
                         $newCreatorData->lastName = $newCreatorData->name;
                         unset($newCreatorData->name);
                         $newCreatorData->fieldMode = 1;
                     } else {
                         $newCreatorData->fieldMode = 0;
                     }
                     $newCreatorTypeID = Zotero_CreatorTypes::getID($newCreatorData->creatorType);
                     // Same creator in this position
                     $existingCreator = $item->getCreator($orderIndex);
                     if ($existingCreator && $existingCreator['ref']->equals($newCreatorData)) {
                         // Just change the creatorTypeID
                         if ($existingCreator['creatorTypeID'] != $newCreatorTypeID) {
                             $item->setCreator($orderIndex, $existingCreator['ref'], $newCreatorTypeID);
                         }
                         continue;
                     }
                     // Same creator in a different position, so use that
                     $existingCreators = $item->getCreators();
                     for ($i = 0, $len = sizeOf($existingCreators); $i < $len; $i++) {
                         if ($existingCreators[$i]['ref']->equals($newCreatorData)) {
                             $item->setCreator($orderIndex, $existingCreators[$i]['ref'], $newCreatorTypeID);
                             continue;
                         }
                     }
                     // Make a fake creator to use for the data lookup
                     $newCreator = new Zotero_Creator();
                     $newCreator->libraryID = $item->libraryID;
                     foreach ($newCreatorData as $key => $val) {
                         if ($key == 'creatorType') {
                             continue;
                         }
                         $newCreator->{$key} = $val;
                     }
                     // Look for an equivalent creator in this library
                     $candidates = Zotero_Creators::getCreatorsWithData($item->libraryID, $newCreator, true);
                     if ($candidates) {
                         $c = Zotero_Creators::get($item->libraryID, $candidates[0]);
                         $item->setCreator($orderIndex, $c, $newCreatorTypeID);
                         continue;
                     }
                     // None found, so make a new one
                     $creatorID = $newCreator->save();
                     $newCreator = Zotero_Creators::get($item->libraryID, $creatorID);
                     $item->setCreator($orderIndex, $newCreator, $newCreatorTypeID);
                 }
                 // Remove all existing creators above the current index
                 if (!$isNew && ($indexes = array_keys($item->getCreators()))) {
                     $i = max($indexes);
                     while ($i > $orderIndex) {
                         $item->removeCreator($i);
                         $i--;
                     }
                 }
                 break;
             case 'tags':
                 // If item isn't yet saved, add tags below
                 if (!$item->id) {
                     $twoStage = true;
                     break;
                 }
                 if ($item->setTags($val)) {
                     $forceChange = true;
//.........这里部分代码省略.........
开发者ID:robinpaulson,项目名称:dataserver,代码行数:101,代码来源:Items.inc.php

示例14: settings

 public function settings()
 {
     if ($this->apiVersion < 2) {
         $this->e404();
     }
     // Check for general library access
     if (!$this->permissions->canAccess($this->objectLibraryID)) {
         $this->e403();
     }
     if ($this->isWriteMethod()) {
         Zotero_DB::beginTransaction();
         // Check for library write access
         if (!$this->permissions->canWrite($this->objectLibraryID)) {
             $this->e403("Write access denied");
         }
         // Make sure library hasn't been modified
         if (!$this->singleObject) {
             $libraryTimestampChecked = $this->checkLibraryIfUnmodifiedSinceVersion();
         }
         Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
     }
     // Single setting
     if ($this->singleObject) {
         $this->allowMethods(array('GET', 'PUT', 'DELETE'));
         $setting = Zotero_Settings::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
         if (!$setting) {
             if ($this->method == 'PUT') {
                 $setting = new Zotero_Setting();
                 $setting->libraryID = $this->objectLibraryID;
                 $setting->name = $this->objectKey;
             } else {
                 $this->e404("Setting not found");
             }
         }
         if ($this->isWriteMethod()) {
             if ($this->method == 'PUT') {
                 $json = $this->jsonDecode($this->body);
                 $objectVersionValidated = $this->checkSingleObjectWriteVersion('setting', $setting, $json);
             }
             $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
             // Update setting
             if ($this->method == 'PUT') {
                 $changed = Zotero_Settings::updateFromJSON($setting, $json, $this->queryParams, $this->userID, $objectVersionValidated ? 0 : 2);
                 // If not updated, return the original library version
                 if (!$changed) {
                     $this->libraryVersion = Zotero_Libraries::getOriginalVersion($this->objectLibraryID);
                     Zotero_DB::rollback();
                     $this->e204();
                 }
             } else {
                 if ($this->method == 'DELETE') {
                     Zotero_Settings::delete($this->objectLibraryID, $this->objectKey);
                 } else {
                     throw new Exception("Unexpected method {$this->method}");
                 }
             }
             Zotero_DB::commit();
             $this->e204();
         } else {
             $this->libraryVersion = $setting->version;
             $json = $setting->toJSON(true, $this->queryParams);
             echo Zotero_Utilities::formatJSON($json);
         }
     } else {
         $this->allowMethods(array('GET', 'POST'));
         $this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
         // Create a setting
         if ($this->method == 'POST') {
             $obj = $this->jsonDecode($this->body);
             $changed = Zotero_Settings::updateMultipleFromJSON($obj, $this->queryParams, $this->objectLibraryID, $this->userID, $this->permissions, $libraryTimestampChecked ? 0 : 1, null);
             // If not updated, return the original library version
             if (!$changed) {
                 $this->libraryVersion = Zotero_Libraries::getOriginalVersion($this->objectLibraryID);
             }
             Zotero_DB::commit();
             $this->e204();
         } else {
             $settings = Zotero_Settings::search($this->objectLibraryID, $this->queryParams);
             $json = new stdClass();
             foreach ($settings as $setting) {
                 $json->{$setting->name} = $setting->toJSON(true, $this->queryParams);
             }
             echo Zotero_Utilities::formatJSON($json);
         }
     }
     $this->end();
 }
开发者ID:ergo70,项目名称:dataserver,代码行数:87,代码来源:SettingsController.php

示例15: updateFromJSON

 /**
  * @param Zotero_Collection $collection The collection object to update;
  *                                      this should be either an existing
  *                                      collection or a new collection
  *                                      with a library assigned.
  * @param object $json Collection data to write
  * @param boolean [$requireVersion=0] See Zotero_API::checkJSONObjectVersion()
  * @return boolean True if the collection was changed, false otherwise
  */
 public static function updateFromJSON(Zotero_Collection $collection, $json, $requestParams, $userID, $requireVersion = 0, $partialUpdate = false)
 {
     $json = Zotero_API::extractEditableJSON($json);
     $exists = Zotero_API::processJSONObjectKey($collection, $json, $requestParams);
     Zotero_API::checkJSONObjectVersion($collection, $json, $requestParams, $requireVersion);
     self::validateJSONCollection($json, $requestParams, $partialUpdate && $exists);
     $changed = false;
     if (!Zotero_DB::transactionInProgress()) {
         Zotero_DB::beginTransaction();
         $transactionStarted = true;
     } else {
         $transactionStarted = false;
     }
     if (isset($json->name)) {
         $collection->name = $json->name;
     }
     if ($requestParams['v'] >= 2 && isset($json->parentCollection)) {
         $collection->parentKey = $json->parentCollection;
     } else {
         if ($requestParams['v'] < 2 && isset($json->parent)) {
             $collection->parentKey = $json->parent;
         } else {
             if (!$partialUpdate) {
                 $collection->parent = false;
             }
         }
     }
     $changed = $collection->save() || $changed;
     if ($requestParams['v'] >= 2) {
         if (isset($json->relations)) {
             $changed = $collection->setRelations($json->relations, $userID) || $changed;
         } else {
             if (!$partialUpdate) {
                 $changed = $collection->setRelations(new stdClass(), $userID) || $changed;
             }
         }
     }
     if ($transactionStarted) {
         Zotero_DB::commit();
     }
     return $changed;
 }
开发者ID:juego11,项目名称:dataserver,代码行数:51,代码来源:Collections.inc.php


注:本文中的Zotero_DB::beginTransaction方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。