forked from piernov/zotprime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathItemsController.php
1192 lines (1032 loc) · 35 KB
/
ItemsController.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the Zotero Data Server.
Copyright © 2013 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 *****
*/
require('ApiController.php');
class ItemsController extends ApiController {
public function items() {
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();
}
// We don't update the library version in file mode, because currently
// to avoid conflicts in the client the timestamp can't change
// when the client updates file metadata
if (!$this->fileMode) {
Zotero_Libraries::updateVersionAndTimestamp($this->objectLibraryID);
}
}
$itemIDs = array();
$itemKeys = array();
$results = array();
$title = "";
if ($this->objectGlobalItemID) {
$id = $this->objectGlobalItemID;
$libraryItems = Zotero_GlobalItems::getGlobalItemLibraryItems($id);
if (!$libraryItems) {
$this->e404();
}
// TODO: Improve pagination
// Pagination isn't reliable here, because we
// don't know if library and key exist and if we have permissions
// to access it, until we actually query specific library and key.
// Empty object placeholders should be returned where item
// retrieval fails, or otherwise all items before 'start' must be fetched
//$start = $this->queryParams['start'];
$start = 0;
$limit = $this->queryParams['limit'];
// Group items by libraryID to later query all library's items at once
$groupedLibraryItems = [];
for ($i = 0, $len = sizeOf($libraryItems); $i < $len; $i++) {
list($libraryID, $key) = $libraryItems[$i];
$groupedLibraryItems[$libraryID][] = $key;
}
$allResults = ['results' => [], 'total' => 0];
foreach ($groupedLibraryItems as $libraryID => $keys) {
if (!$this->permissions->canAccess($libraryID)) {
continue;
}
$remaining = $limit - sizeOf($allResults['results']);
if (!$remaining) {
// If not adding more items, add approximate total based on number of items from
// libraryItems array. These might not all exist if they've been deleted recently,
// but we don't want to keep searching for all items after reaching the limit.
$allResults['total'] += sizeOf($keys);
continue;
}
// Do not pass $this->queryParams directly to prevent
// other query parameters from influencing Zotero_Items::search
$params = [
'format' => $this->queryParams['format'],
'itemKey' => $keys
];
$results = Zotero_Items::search(
$libraryID,
false,
$params
);
$allResults['results'] = array_merge(
$allResults['results'],
array_slice($results['results'], 0, $remaining)
);
$allResults['total'] += $results['total'];
}
$this->generateMultiResponse($allResults);
$this->end();
}
//
// Single item
//
if ($this->singleObject) {
if ($this->fileMode) {
if ($this->fileView) {
$this->allowMethods(array('HEAD', 'GET', 'POST'));
}
else {
$this->allowMethods(array('HEAD', 'GET', 'PUT', 'POST', 'PATCH'));
}
}
else {
$this->allowMethods(array('HEAD', 'GET', 'PUT', 'PATCH', 'DELETE'));
}
if (!Zotero_ID::isValidKey($this->objectKey)) {
$this->e404();
}
$item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
if ($item) {
// If no access to the item, don't show that it exists
if (!$this->permissions->canAccessObject($item)) {
$this->e404();
}
// Don't show an item in publications that doesn't belong there, even if user has
// access to it
if ($this->publications
&& ((!$this->legacyPublications && !$item->inPublications)
|| $item->deleted)) {
$this->e404();
}
// Make sure URL libraryID matches item libraryID
if ($this->objectLibraryID != $item->libraryID) {
$this->e404();
}
// File access mode
if ($this->fileMode) {
$this->_handleFileRequest($item);
}
if ($this->scopeObject) {
switch ($this->scopeObject) {
// Remove item from collection
case 'collections':
$this->allowMethods(array('DELETE'));
$collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
if (!$collection) {
$this->e404("Collection not found");
}
if (!$collection->hasItem($item->id)) {
$this->e404("Item not found in collection");
}
Zotero_DB::beginTransaction();
$collection->removeItem($item->id);
$item->updateVersion($this->userID);
Zotero_DB::commit();
$this->e204();
default:
$this->e400();
}
}
}
else {
if ($this->isWriteMethod() && $this->fileMode) {
$this->e404();
}
// Possibly temporary workaround to block unnecessary full syncs
if ($this->fileMode && $this->httpAuth && $this->method == 'POST') {
// If > 2 requests for missing file, trigger a full sync via 404
$cacheKey = "apiMissingFile_"
. $this->objectLibraryID . "_"
. $this->objectKey;
$set = Z_Core::$MC->get($cacheKey);
if (!$set) {
Z_Core::$MC->set($cacheKey, 1, 86400);
}
else if ($set < 2) {
Z_Core::$MC->increment($cacheKey);
}
else {
Z_Core::$MC->delete($cacheKey);
$this->e404("A file sync error occurred. Please sync again.");
}
$this->e500("A file sync error occurred. Please sync again.");
}
}
if ($this->isWriteMethod()) {
$item = $this->handleObjectWrite('item', $item ? $item : null);
if ($this->apiVersion < 2
&& ($this->method == 'PUT' || $this->method == 'PATCH')) {
$this->queryParams['format'] = 'atom';
$this->queryParams['content'] = ['json'];
}
}
if (!$item) {
$this->e404("Item does not exist");
}
$this->libraryVersion = $item->version;
if ($this->method == 'HEAD') {
$this->end();
}
// Display item
switch ($this->queryParams['format']) {
case 'atom':
$this->responseXML = Zotero_Items::convertItemToAtom(
$item, $this->queryParams, $this->permissions
);
break;
case 'bib':
echo Zotero_Cite::getBibliographyFromCitationServer(array($item), $this->queryParams);
break;
case 'csljson':
// TODO: Use in APIv4
//$json = Zotero_Cite::getJSONFromItems([$item], true)['items'][0];
$json = Zotero_Cite::getJSONFromItems(array($item), true);
echo Zotero_Utilities::formatJSON($json);
break;
case 'json':
$json = $item->toResponseJSON($this->queryParams, $this->permissions);
$this->checkObjectsForLegacySchema('item', [$json]);
echo Zotero_Utilities::formatJSON($json);
break;
default:
$export = Zotero_Translate::doExport([$item], $this->queryParams);
$this->queryParams['format'] = null;
header("Content-Type: " . $export['mimeType']);
echo $export['body'];
break;
}
}
//
// Multiple items
//
else {
$this->allowMethods(array('HEAD', 'GET', 'POST', 'DELETE'));
// Check for general library access
if (!$this->publications && !$this->permissions->canAccess($this->objectLibraryID)) {
$this->e403();
}
if ($this->publications) {
// Disabled until it actually works
/*// Include ETag in My Publications (or, in the future, public collections)
$this->etag = Zotero_Publications::getETag($this->objectUserID);
// Return 304 if ETag matches
if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $this->etag) {
$this->e304();
}*/
// TEMP: Remove after integrated publications upgrade
$this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
}
// Last-Modified-Version otherwise
else {
$this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
}
if ($this->scopeObject) {
$this->allowMethods(array('GET', 'POST'));
switch ($this->scopeObject) {
case 'collections':
// TEMP
if (Zotero_ID::isValidKey($this->scopeObjectKey)) {
$collection = Zotero_Collections::getByLibraryAndKey($this->objectLibraryID, $this->scopeObjectKey);
}
else {
$collection = false;
}
if (!$collection) {
// If old collectionID, redirect
if ($this->method == 'GET' && Zotero_Utilities::isPosInt($this->scopeObjectKey)) {
$collection = Zotero_Collections::get($this->objectLibraryID, $this->scopeObjectKey);
if ($collection) {
$qs = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
$base = Zotero_API::getCollectionURI($collection);
$suffix = $this->subset == 'top' ? '/top' : '';
$this->redirect($base . "/items$suffix" . $qs, 301);
}
}
$this->e404("Collection not found");
}
// Add items to collection
if ($this->method == 'POST') {
$itemKeys = explode(' ', $this->body);
$items = [];
$itemIDs = [];
foreach ($itemKeys as $key) {
try {
$item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $key);
}
catch (Exception $e) {
if ($e->getCode() == Z_ERROR_OBJECT_LIBRARY_MISMATCH) {
$item = false;
}
else {
throw ($e);
}
}
if (!$item) {
throw new Exception("Item '$key' not found in library", Z_ERROR_INVALID_INPUT);
}
if ($item->getSource()) {
throw new Exception("Child items cannot be added to collections directly", Z_ERROR_INVALID_INPUT);
}
$items[] = $item;
$itemIDs[] = $item->id;
}
Zotero_DB::beginTransaction();
$collection->addItems($itemIDs);
Zotero_Items::updateVersions($items, $this->userID);
Zotero_DB::commit();
$this->e204();
}
if ($this->subset == 'top' || $this->apiVersion < 2) {
$title = "Top-Level Items in Collection ‘" . $collection->name . "’";
$itemIDs = $collection->getItems();
}
else {
$title = "Items in Collection ‘" . $collection->name . "’";
$itemIDs = $collection->getItems(true);
}
break;
case 'tags':
if ($this->apiVersion >= 2) {
$this->e404();
}
$this->allowMethods(array('GET'));
$tagIDs = Zotero_Tags::getIDs($this->objectLibraryID, $this->scopeObjectName);
if (!$tagIDs) {
$this->e404("Tag not found");
}
foreach ($tagIDs as $tagID) {
$tag = new Zotero_Tag;
$tag->libraryID = $this->objectLibraryID;
$tag->id = $tagID;
// Use a real tag name, in case case differs
if (!$title) {
$title = "Items of Tag ‘" . $tag->name . "’";
}
$itemKeys = array_merge($itemKeys, $tag->getLinkedItems(true));
}
$itemKeys = array_unique($itemKeys);
break;
default:
$this->e404();
}
}
else {
// Top-level items
if ($this->subset == 'top') {
$this->allowMethods(array('GET'));
$title = "Top-Level Items";
$results = Zotero_Items::search(
$this->objectLibraryID,
true,
$this->queryParams,
$this->permissions
);
}
// Deleted items
else if ($this->subset == 'trash') {
$this->allowMethods(array('GET'));
$title = "Deleted Items";
$this->queryParams['includeTrashed'] = true;
$this->queryParams['trashedItemsOnly'] = true;
$results = Zotero_Items::search(
$this->objectLibraryID,
false,
$this->queryParams,
$this->permissions
);
}
else if ($this->subset == 'children') {
$item = Zotero_Items::getByLibraryAndKey($this->objectLibraryID, $this->objectKey);
if (!$item) {
$this->e404("Item not found");
}
// Don't show child items in publications mode of an item not in publications
if ($this->publications && !$item->inPublications) {
$this->e404("Item not found");
}
if ($item->isAttachment() && !$item->isPDFAttachment()) {
$this->e400("/children cannot be called on non-PDF attachments");
}
// Create new child items
if ($this->method == 'POST') {
if ($this->apiVersion >= 2) {
$this->allowMethods(array('GET'));
}
Zotero_DB::beginTransaction();
$obj = $this->jsonDecode($this->body);
$results = Zotero_Items::updateMultipleFromJSON(
$obj,
$this->queryParams,
$this->objectLibraryID,
$this->userID,
$this->permissions,
$libraryTimestampChecked ? 0 : 1,
$item
);
Zotero_DB::commit();
if ($cacheKey = $this->getWriteTokenCacheKey()) {
Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
}
$uri = Zotero_API::getItemsURI($this->objectLibraryID);
$keys = array_merge(
get_object_vars($results['success']),
get_object_vars($results['unchanged'])
);
$queryString = "itemKey="
. urlencode(implode(",", $keys))
. "&format=atom&content=json&order=itemKeyList&sort=asc";
if ($this->apiKey) {
$queryString .= "&key=" . $this->apiKey;
}
$uri .= "?" . $queryString;
$this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
$this->responseCode = 201;
$title = "Items";
$results = Zotero_Items::search(
$this->objectLibraryID,
false,
$this->queryParams,
$this->permissions
);
}
// Display items
else {
$title = "Child Items of ‘" . $item->getDisplayTitle() . "’";
if ($item->isAttachment()) {
$itemIDs = $item->getAnnotations();
}
else if ($item->isNote()) {
$itemIDs = $item->getAttachments();
}
else {
$notes = $item->getNotes();
$attachments = $item->getAttachments();
$itemIDs = array_merge($notes, $attachments);
}
}
}
// All items
else {
// Create new items
if ($this->method == 'POST') {
$this->queryParams['format'] = 'writereport';
$obj = $this->jsonDecode($this->body);
// Server-side translation
if (isset($obj->url)) {
if ($this->apiVersion < 2) {
$this->e501("URL translation requires APIv2 or later");
}
$results = Zotero_Items::addFromURL(
$obj,
$this->queryParams,
$this->objectLibraryID,
$this->userID,
$this->permissions
);
// Multiple choices
if ($results instanceof stdClass) {
$this->queryParams['format'] = null;
header("Content-Type: application/json");
echo Zotero_Utilities::formatJSON([
'url' => $obj->url,
'token' => $results->token,
'items' => $results->select
]);
$this->e300();
}
// Error from translation server
else if (is_int($results)) {
switch ($results) {
case 501:
$this->e501("No translators found for URL");
break;
default:
$this->e500("Error translating URL");
}
}
// Return write status report
}
// Uploaded items
else {
if ($this->apiVersion < 2) {
Zotero_DB::beginTransaction();
}
$results = Zotero_Items::updateMultipleFromJSON(
$obj,
$this->queryParams,
$this->objectLibraryID,
$this->userID,
$this->permissions,
$libraryTimestampChecked ? 0 : 1,
null
);
if ($this->apiVersion < 2) {
Zotero_DB::commit();
$uri = Zotero_API::getItemsURI($this->objectLibraryID);
$keys = array_merge(
get_object_vars($results['success']),
get_object_vars($results['unchanged'])
);
$queryString = "itemKey="
. urlencode(implode(",", $keys))
. "&format=atom&content=json&order=itemKeyList&sort=asc";
if ($this->apiKey) {
$queryString .= "&key=" . $this->apiKey;
}
$uri .= "?" . $queryString;
$this->queryParams = Zotero_API::parseQueryParams($queryString, $this->action, false);
$this->responseCode = 201;
$title = "Items";
$results = Zotero_Items::search(
$this->objectLibraryID,
false,
$this->queryParams,
$this->permissions
);
}
}
if ($cacheKey = $this->getWriteTokenCacheKey()) {
Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
}
}
// Delete items
else if ($this->method == 'DELETE') {
Zotero_DB::beginTransaction();
foreach ($this->queryParams['itemKey'] as $itemKey) {
Zotero_Items::delete($this->objectLibraryID, $itemKey);
}
Zotero_DB::commit();
$this->e204();
}
// Display items
else {
$title = "Items";
$results = Zotero_Items::search(
$this->objectLibraryID,
false,
$this->queryParams,
$this->permissions
);
}
}
}
if ($itemIDs || $itemKeys) {
if ($itemIDs) {
$this->queryParams['itemIDs'] = $itemIDs;
}
if ($itemKeys) {
$this->queryParams['itemKey'] = $itemKeys;
}
$results = Zotero_Items::search(
$this->objectLibraryID,
$this->subset == 'top',
$this->queryParams,
$this->permissions
);
}
if ($this->queryParams['format'] == 'bib') {
$maxBibItems = Zotero_API::MAX_BIBLIOGRAPHY_ITEMS;
if ($results['total'] > $maxBibItems) {
$this->e413("Cannot generate bibliography with more than $maxBibItems items");
}
}
$this->generateMultiResponse($results, $title);
}
$this->end();
}
private function generateMultiResponse($results, $title='') {
$options = [
'action' => $this->action,
'uri' => $this->uri,
'results' => $results,
'requestParams' => $this->queryParams,
'permissions' => $this->permissions,
'head' => $this->method == 'HEAD'
];
$format = $this->queryParams['format'];
switch ($format) {
case 'atom':
$this->responseXML = Zotero_API::multiResponse(
array_merge(
$options,
[
'title' => $this->getFeedNamePrefix($this->objectLibraryID) . $title
]
)
);
break;
case 'bib':
if ($this->method == 'HEAD') {
break;
}
if (isset($results['results'])) {
echo Zotero_Cite::getBibliographyFromCitationServer($results['results'], $this->queryParams);
}
break;
case 'csljson':
case 'json':
case 'keys':
case 'versions':
case 'writereport':
if ($format == 'json') {
$options['asObject'] = true;
}
$response = Zotero_API::multiResponse($options);
if ($format == 'json') {
$this->checkObjectsForLegacySchema('item', $response);
echo Zotero_Utilities::formatJSON($response);
}
break;
default:
if (Zotero_Translate::isExportFormat($format)) {
Zotero_API::multiResponse($options);
$this->queryParams['format'] = null;
}
else {
throw new Exception("Unexpected format '$format'");
}
}
}
/**
* Handle S3 request
*
* Permission-checking provided by items()
*/
private function _handleFileRequest($item) {
if (!$this->permissions->canAccess($this->objectLibraryID, 'files')
// Check access on specific item, for My Publications files
&& !$this->permissions->canAccessObject($item)) {
$this->e403();
}
$this->allowMethods(array('HEAD', 'GET', 'POST', 'PATCH'));
if (!$item->isAttachment()) {
$this->e400("Item is not an attachment");
}
// File info for 4.0 client sync
//
// Use of HEAD method was discontinued after 2.0.8/2.1b1 due to
// compatibility problems with proxies and security software
if ($this->method == 'GET' && $this->fileMode == 'info') {
$info = Zotero_Storage::getLocalFileItemInfo($item);
if (!$info) {
$this->e404();
}
StatsD::increment("storage.info", 1);
/*
header("Last-Modified: " . gmdate('r', $info['uploaded']));
header("Content-Type: " . $info['type']);
*/
header("Content-Length: " . $info['size']);
header("ETag: " . $info['hash']);
header("X-Zotero-Filename: " . $info['filename']);
header("X-Zotero-Modification-Time: " . $info['mtime']);
header("X-Zotero-Compressed: " . ($info['zip'] ? 'Yes' : 'No'));
header_remove("X-Powered-By");
$this->end();
}
// File viewing/download
//
// TEMP: allow POST for snapshot viewing until using session auth
else if ($this->method == 'GET') {
$info = Zotero_Storage::getLocalFileItemInfo($item);
if (!$info) {
$this->e404();
}
// Return 404 to non-members for files in PublicClosed groups
// TODO: Move this into Permissions
$type = Zotero_Libraries::getType($this->objectLibraryID);
if ($type == 'group') {
$groupID = Zotero_Groups::getGroupIDFromLibraryID($this->objectLibraryID);
$group = Zotero_Groups::get($groupID);
if ($group->type == 'PublicClosed'
&& !$this->permissions->canAccess($this->objectLibraryID, 'files')) {
$this->e404();
}
}
// File viewing
if ($this->fileView || $this->fileViewURL) {
$url = Zotero_Attachments::getTemporaryURL($item);
if (!$url) {
$this->e500();
}
if ($this->fileViewURL) {
header('Content-Type: text/plain');
echo $url . "\n";
$this->end();
}
StatsD::increment("storage.view", 1);
$this->redirect($url);
exit;
}
// File download
$url = Zotero_Storage::getDownloadURL($item, 60);
if (!$url) {
$this->e404();
}
// Provide some headers to let 5.0 client skip download
header("Zotero-File-Modification-Time: {$info['mtime']}");
header("Zotero-File-MD5: {$info['hash']}");
header("Zotero-File-Size: {$info['size']}");
header("Zotero-File-Compressed: " . ($info['zip'] ? 'Yes' : 'No'));
StatsD::increment("storage.download", 1);
$this->redirect($url);
exit;
}
else if ($this->method == 'POST' || $this->method == 'PATCH') {
if (!$item->isStoredFileAttachment()) {
$this->e400("Cannot upload file for linked file/URL attachment item");
}
$libraryID = $item->libraryID;
$type = Zotero_Libraries::getType($libraryID);
if ($type == 'group') {
$groupID = Zotero_Groups::getGroupIDFromLibraryID($libraryID);
$group = Zotero_Groups::get($groupID);
if (!$group->userCanEditFiles($this->userID)) {
$this->e403("You do not have file editing access");
}
}
else {
$group = null;
}
// If not the 4.0 client, require If-Match or If-None-Match
if (!$this->httpAuth) {
if (empty($_SERVER['HTTP_IF_MATCH']) && empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
$this->e428("If-Match/If-None-Match header not provided");
}
if (!empty($_SERVER['HTTP_IF_MATCH'])) {
if (!preg_match('/^"?([a-f0-9]{32})"?$/', $_SERVER['HTTP_IF_MATCH'], $matches)) {
$this->e400("Invalid ETag in If-Match header");
}
if (!$item->attachmentStorageHash) {
$this->e412("If-Match set but file does not exist");
}
if ($item->attachmentStorageHash != $matches[1]) {
$this->libraryVersion = $item->version;
$this->libraryVersionOnFailure = true;
$this->e412("ETag does not match current version of file");
}
}
else {
if ($_SERVER['HTTP_IF_NONE_MATCH'] != "*") {
$this->e400("Invalid value for If-None-Match header");
}
if ($item->attachmentStorageHash) {
$this->libraryVersion = $item->version;
$this->libraryVersionOnFailure = true;
$this->e412("If-None-Match: * set but file exists");
}
}
}
//
// Upload authorization
//
if (!isset($_POST['update']) && !isset($_REQUEST['upload'])) {
$info = new Zotero_StorageFileInfo;
// Validate upload metadata
if (empty($_REQUEST['md5'])) {
$this->e400('MD5 hash not provided');
}
if (!preg_match('/[abcdefg0-9]{32}/', $_REQUEST['md5'])) {
$this->e400('Invalid MD5 hash');
}
if (!isset($_REQUEST['filename']) || $_REQUEST['filename'] === "") {
$this->e400('Filename not provided');
}
// Multi-file upload
//
// For ZIP files, the filename and hash of the ZIP file are different from those
// of the main file. We use the former for S3, and we store the latter in the
// upload log to set the attachment metadata with them on file registration.
if (!empty($_REQUEST['zipMD5'])) {
if (!preg_match('/[abcdefg0-9]{32}/', $_REQUEST['zipMD5'])) {
$this->e400('Invalid ZIP MD5 hash');
}
if (empty($_REQUEST['zipFilename'])) {
$this->e400('ZIP filename not provided');
}
$info->zip = true;
$info->hash = $_REQUEST['zipMD5'];
$info->filename = $_REQUEST['zipFilename'];
$info->itemFilename = $_REQUEST['filename'];
$info->itemHash = $_REQUEST['md5'];
}
else if (!empty($_REQUEST['zipFilename'])) {
$this->e400('ZIP MD5 hash not provided');
}
// Single-file upload
else {
$info->zip = !empty($_REQUEST['zip']);
$info->filename = $_REQUEST['filename'];
$info->hash = $_REQUEST['md5'];
}
if (empty($_REQUEST['mtime'])) {
$this->e400('File modification time not provided');
}
$info->mtime = $_REQUEST['mtime'];
if (!isset($_REQUEST['filesize'])) {
$this->e400('File size not provided');
}
$info->size = $_REQUEST['filesize'];
if (!is_numeric($info->size)) {
$this->e400("Invalid file size");
}
// TEMP: Until the client supports multi-part upload
if ($info->size > 4000000000) {
$this->e400("Files above 4 GB are not currently supported");
}
$info->contentType = isset($_REQUEST['contentType']) ? $_REQUEST['contentType'] : null;
if (!preg_match("/^[a-zA-Z0-9\-\/]+$/", $info->contentType)) {
$info->contentType = null;
}
$info->charset = isset($_REQUEST['charset']) ? $_REQUEST['charset'] : null;
if (!preg_match("/^[a-zA-Z0-9\-]+$/", $info->charset)) {
$info->charset = null;
}
$contentTypeHeader = $info->contentType . (($info->contentType && $info->charset) ? "; charset=" . $info->charset : "");
// Reject file if it would put account over quota
if ($group) {
$quota = Zotero_Storage::getEffectiveUserQuota($group->ownerUserID);
$usage = Zotero_Storage::getUserUsage($group->ownerUserID, 'b');
}
else {
$quota = Zotero_Storage::getEffectiveUserQuota($this->objectUserID);
$usage = Zotero_Storage::getUserUsage($this->objectUserID, 'b');
}
$requestedMB = round(($usage['total'] + $info->size) / 1024 / 1024, 1);
if ($requestedMB > $quota) {
StatsD::increment("storage.upload.quota", 1);
$usageMB = round($usage['total'] / 1024 / 1024, 1);
header("Zotero-Storage-Usage: $usageMB");
header("Zotero-Storage-Quota: $quota");
$this->e413("File would exceed quota ($requestedMB > $quota)");
}
Zotero_DB::query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
Zotero_DB::beginTransaction();
// See if file exists with this filename
$localInfo = Zotero_Storage::getLocalFileInfo($info);
if ($localInfo) {
$storageFileID = $localInfo['storageFileID'];
// Verify file size
if ($localInfo['size'] != $info->size) {
error_log("Specified file size incorrect for existing file "
. $info->hash . "/" . $info->filename
. " ({$localInfo['size']} != {$info->size})");
$this->e400("Specified file size incorrect for known file");
}
}
// If not found, see if there's a copy with a different name
else {
$oldStorageFileID = Zotero_Storage::getFileByHash($info->hash, $info->zip);
if ($oldStorageFileID) {
// Verify file size
$localInfo = Zotero_Storage::getFileInfoByID($oldStorageFileID);
if ($localInfo['size'] != $info->size) {
error_log(
"Specified file size incorrect for duplicated file "
. $info->hash . "/" . $info->filename
. " ({$localInfo['size']} != {$info->size})"
);
$this->e400("Specified file size incorrect for known file");
}
// Create new file on S3 with new name
$storageFileID = Zotero_Storage::duplicateFile(
$oldStorageFileID,
$info->filename,
$info->zip,
$contentTypeHeader
);
}
}
// If we already have a file, add/update storageFileItems row and stop
if (!empty($storageFileID)) {
Zotero_Storage::updateFileItemInfo($item, $storageFileID, $info, $this->httpAuth);
Zotero_DB::commit();