forked from zotero/dataserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollections.inc.php
477 lines (399 loc) · 13.9 KB
/
Collections.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the Zotero Data Server.
Copyright © 2010 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
class Zotero_Collections extends Zotero_DataObjects {
public static $maxLength = 255;
protected static $ZDO_object = 'collection';
protected static $primaryFields = array(
'id' => 'collectionID',
'libraryID' => '',
'key' => '',
'name' => 'collectionName',
'dateAdded' => '',
'dateModified' => '',
'parent' => 'parentCollectionID',
'version' => ''
);
public static function search($libraryID, $onlyTopLevel=false, $params) {
$results = array('results' => array(), 'total' => 0);
$shardID = Zotero_Shards::getByLibraryID($libraryID);
$sql = "SELECT SQL_CALC_FOUND_ROWS DISTINCT ";
if ($params['format'] == 'keys') {
$sql .= "`key`";
}
else {
$sql .= "`key`, version";
}
$sql .= " FROM collections WHERE libraryID=? ";
$sqlParams = array($libraryID);
if ($onlyTopLevel) {
$sql .= "AND parentCollectionID IS NULL ";
}
// Pass a list of collectionIDs, for when the initial search is done via SQL
$collectionIDs = !empty($params['collectionIDs'])
? $params['collectionIDs'] : array();
$collectionKeys = $params['collectionKey'];
if ($collectionIDs) {
$sql .= "AND collectionID IN ("
. implode(', ', array_fill(0, sizeOf($collectionIDs), '?'))
. ") ";
$sqlParams = array_merge($sqlParams, $collectionIDs);
}
if ($collectionKeys) {
$sql .= "AND `key` IN ("
. implode(', ', array_fill(0, sizeOf($collectionKeys), '?'))
. ") ";
$sqlParams = array_merge($sqlParams, $collectionKeys);
}
if (!empty($params['q'])) {
$sql .= "AND collectionName LIKE ? ";
$sqlParams[] = '%' . $params['q'] . '%';
}
if (!empty($params['since'])) {
$sql .= "AND version > ? ";
$sqlParams[] = $params['since'];
}
// TEMP: for sync transition
if (!empty($params['sincetime'])) {
$sql .= "AND serverDateModified >= FROM_UNIXTIME(?) ";
$sqlParams[] = $params['sincetime'];
}
if (!empty($params['sort'])) {
switch ($params['sort']) {
case 'title':
$orderSQL = 'collectionName';
break;
case 'collectionKeyList':
$orderSQL = "FIELD(`key`,"
. implode(',', array_fill(0, sizeOf($collectionKeys), '?')) . ")";
$sqlParams = array_merge($sqlParams, $collectionKeys);
break;
default:
$orderSQL = $params['sort'];
}
$sql .= "ORDER BY $orderSQL";
if (!empty($params['direction'])) {
$sql .= " {$params['direction']}";
}
$sql .= ", ";
}
$sql .= "version " . (!empty($params['direction']) ? $params['direction'] : "ASC")
. ", collectionID " . (!empty($params['direction']) ? $params['direction'] : "ASC") . " ";
if (!empty($params['limit'])) {
$sql .= "LIMIT ?, ?";
$sqlParams[] = $params['start'] ? $params['start'] : 0;
$sqlParams[] = $params['limit'];
}
if ($params['format'] == 'keys') {
$rows = Zotero_DB::columnQuery($sql, $sqlParams, $shardID);
}
// Keys and versions
else {
$rows = Zotero_DB::query($sql, $sqlParams, $shardID);
}
$results['total'] = Zotero_DB::valueQuery("SELECT FOUND_ROWS()", false, $shardID);
if ($rows) {
if ($params['format'] == 'keys') {
$results['results'] = $rows;
}
else if ($params['format'] == 'versions') {
foreach ($rows as $row) {
$results['results'][$row['key']] = $row['version'];
}
}
else {
$collections = [];
foreach ($rows as $row) {
$obj = self::getByLibraryAndKey($libraryID, $row['key']);
$obj->setAvailableVersion($row['version']);
$collections[] = $obj;
}
$results['results'] = $collections;
}
}
return $results;
}
public static function getLongDataValueFromXML(DOMDocument $doc) {
$xpath = new DOMXPath($doc);
$attr = $xpath->evaluate('//collections/collection[string-length(@name) > ' . self::$maxLength . ']/@name');
return $attr->length ? $attr->item(0)->value : false;
}
/**
* Converts a DOMElement item to a Zotero_Collection object
*
* @param DOMElement $xml Collection data as DOMElement
* @return Zotero_Collection Zotero collection object
*/
public static function convertXMLToCollection(DOMElement $xml) {
$libraryID = (int) $xml->getAttribute('libraryID');
$col = self::getByLibraryAndKey($libraryID, $xml->getAttribute('key'));
if (!$col) {
$col = new Zotero_Collection;
$col->libraryID = $libraryID;
$col->key = $xml->getAttribute('key');
}
$col->name = $xml->getAttribute('name');
$parentKey = $xml->getAttribute('parent');
if ($parentKey) {
$col->parentKey = $parentKey;
}
else {
$col->parent = false;
}
$col->dateAdded = $xml->getAttribute('dateAdded');
$col->dateModified = $xml->getAttribute('dateModified');
// TODO: move from SyncController?
return $col;
}
/**
* Converts a Zotero_Collection object to a SimpleXMLElement item
*
* @param object $item Zotero_Collection object
* @return SimpleXMLElement Collection data as SimpleXML element
*/
public static function convertCollectionToXML(Zotero_Collection $collection) {
$xml = new SimpleXMLElement('<collection/>');
$xml['libraryID'] = $collection->libraryID;
$xml['key'] = $collection->key;
$xml['name'] = $collection->name;
$xml['dateAdded'] = $collection->dateAdded;
$xml['dateModified'] = $collection->dateModified;
if ($collection->parent) {
$parentCol = self::get($collection->libraryID, $collection->parent);
$xml['parent'] = $parentCol->key;
}
$children = $collection->getChildren();
if ($children) {
$keys = array();
foreach($children as $child) {
if ($child['type'] == 'item') {
$keys[] = $child['key'];
}
}
if ($keys) {
$xml->items = implode(' ', $keys);
}
}
return $xml;
}
/**
* Converts a Zotero_Collection object to a SimpleXMLElement Atom object
*
* @param Zotero_Collection $collection Zotero_Collection object
* @param array $requestParams
* @return SimpleXMLElement Collection data as SimpleXML element
*/
public static function convertCollectionToAtom(Zotero_Collection $collection, $requestParams) {
// TEMP: multi-format support
if (!empty($requestParams['content'])) {
$content = $requestParams['content'];
}
else {
$content = array('none');
}
$content = $content[0];
$xml = new SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>'
. '<entry xmlns="' . Zotero_Atom::$nsAtom
. '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'
);
$title = $collection->name ? $collection->name : '[Untitled]';
$xml->title = $title;
$author = $xml->addChild('author');
// TODO: group item creator
$author->name = Zotero_Libraries::getName($collection->libraryID);
$author->uri = Zotero_URI::getLibraryURI($collection->libraryID, true);
$xml->id = Zotero_URI::getCollectionURI($collection);
$xml->published = Zotero_Date::sqlToISO8601($collection->dateAdded);
$xml->updated = Zotero_Date::sqlToISO8601($collection->dateModified);
$link = $xml->addChild("link");
$link['rel'] = "self";
$link['type'] = "application/atom+xml";
$link['href'] = Zotero_API::getCollectionURI($collection);
$parent = $collection->parent;
if ($parent) {
$parentCol = self::get($collection->libraryID, $parent);
$link = $xml->addChild("link");
$link['rel'] = "up";
$link['type'] = "application/atom+xml";
$link['href'] = Zotero_API::getCollectionURI($parentCol);
}
$link = $xml->addChild('link');
$link['rel'] = 'alternate';
$link['type'] = 'text/html';
$link['href'] = Zotero_URI::getCollectionURI($collection, true);
$xml->addChild('zapi:key', $collection->key, Zotero_Atom::$nsZoteroAPI);
$xml->addChild('zapi:version', $collection->version, Zotero_Atom::$nsZoteroAPI);
$collections = $collection->getChildCollections();
$xml->addChild(
'zapi:numCollections',
sizeOf($collections),
Zotero_Atom::$nsZoteroAPI
);
$xml->addChild(
'zapi:numItems',
$collection->numItems(),
Zotero_Atom::$nsZoteroAPI
);
if ($content == 'json') {
$xml->content['type'] = 'application/json';
// Deprecated
if ($requestParams['v'] < 2) {
$xml->content->addAttribute(
'zapi:etag',
$collection->etag,
Zotero_Atom::$nsZoteroAPI
);
$xml->content['etag'] = $collection->etag;
}
$xml->content = Zotero_Utilities::formatJSON($collection->toJSON($requestParams));
}
return $xml;
}
/**
* @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;
}
private static function validateJSONCollection($json, $requestParams, $partialUpdate=false) {
if (!is_object($json)) {
throw new Exception('$json must be a decoded JSON object');
}
if ($partialUpdate) {
$requiredProps = [];
}
else {
$requiredProps = ['name'];
}
foreach ($requiredProps as $prop) {
if (!isset($json->$prop)) {
throw new Exception("'$prop' property not provided", Z_ERROR_INVALID_INPUT);
}
}
foreach ($json as $key=>$val) {
switch ($key) {
// Handled by Zotero_API::checkJSONObjectVersion()
case 'key':
case 'version':
case 'collectionKey':
case 'collectionVersion':
break;
case 'name':
if (!is_string($val)) {
throw new Exception("'name' must be a string", Z_ERROR_INVALID_INPUT);
}
if ($val === "") {
throw new Exception("Collection name cannot be empty", Z_ERROR_INVALID_INPUT);
}
if (mb_strlen($val) > 255) {
throw new Exception("Collection name cannot be longer than 255 characters", Z_ERROR_INVALID_INPUT);
}
break;
case 'parent':
if ($requestParams['v'] >= 2) {
throw new Exception("'parent' property is now 'parentCollection'", Z_ERROR_INVALID_INPUT);
}
if (!is_string($val) && !empty($val)) {
throw new Exception("'$key' must be a collection key or FALSE (" . gettype($val) . ")", Z_ERROR_INVALID_INPUT);
}
break;
case 'parentCollection':
if ($requestParams['v'] < 2) {
throw new Exception("Invalid property '$key'", Z_ERROR_INVALID_INPUT);
}
if (!is_string($val) && !empty($val)) {
throw new Exception("'$key' must be a collection key or FALSE (" . gettype($val) . ")", Z_ERROR_INVALID_INPUT);
}
break;
case 'relations':
if ($requestParams['v'] < 2) {
throw new Exception("Invalid property '$key'", Z_ERROR_INVALID_INPUT);
}
if (!is_object($val)
// Allow an empty array, because it's annoying for some clients otherwise
&& !(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':
break;
default:
throw new Exception("Unsupported predicate '$predicate'", Z_ERROR_INVALID_INPUT);
}
if (!preg_match('/^http:\/\/zotero.org\/(users|groups)\/[0-9]+\/collections\/[A-Z0-9]{8}$/', $object)) {
throw new Exception("'$key' values currently must be Zotero collection URIs", Z_ERROR_INVALID_INPUT);
}
}
break;
default:
throw new Exception("Invalid property '$key'", Z_ERROR_INVALID_INPUT);
}
}
}
}
?>