forked from piernov/zotprime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiController.php
1442 lines (1221 loc) · 41.9 KB
/
ApiController.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
<?
/*
***** 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 *****
*/
declare(strict_types=1);
class ApiController extends Controller {
protected $writeTokenCacheTime = 43200; // 12 hours
private $profile = false;
private $timeLogThreshold = 5;
protected $apiVersion;
protected $method;
protected $uri;
protected $queryParams = array();
protected $ifUnmodifiedSince;
protected $body;
protected $apiKey;
protected $responseXML;
protected $responseCode = 200;
protected $userID; // request user
protected $permissions;
protected $objectUserID; // userID of object owner
protected $objectGroupID; // groupID of object owner
protected $objectLibraryID; // libraryID of object owner
protected $objectGlobalItemID;
protected $scopeObject;
protected $scopeObjectID;
protected $scopeObjectKey;
protected $scopeObjectName;
protected $objectID;
protected $objectKey;
protected $objectName;
protected $subset;
protected $singleObject;
protected $publications = false;
protected $legacyPublications = false;
protected $fileMode;
protected $fileView;
protected $httpAuth = false;
protected $cookieAuth = false;
protected $libraryVersion;
protected $libraryVersionOnFailure = false;
protected $headers = [];
protected $isLegacySchemaClient = false;
private $startTime = false;
private $timeLogged = false;
public function init($extra) {
$this->startTime = microtime(true);
if (!empty(Z_CONFIG::$BACKOFF)) {
header("Backoff: " . Z_CONFIG::$BACKOFF);
}
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'];
$this->uri = Z_CONFIG::$API_BASE_URI . substr($_SERVER["REQUEST_URI"], 1);
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: Authorization, Content-Type, If-Match, If-None-Match, If-Modified-Since-Version, If-Unmodified-Since-Version, Zotero-API-Key, 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 (isset($_SERVER['HTTP_CONTINUED'])) {
Zotero_NotifierObserver::setContinued();
}
if ($this->method == 'OPTIONS') {
$this->end();
}
if (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'sync.zotero.org') {
if ($this->method == 'GET' || $this->method == 'POST') {
header("Content-Type: text/xml");
header("HTTP/1.1 400");
echo '<response><error code="UPGRADE_REQUIRED">Zotero 4 syncing is no longer supported. Please upgrade to Zotero 5 to continue syncing.</error></response>';
$this->end();
}
$this->e400("Invalid endpoint");
}
if (!Z_CONFIG::$API_ENABLED) {
$this->e503(Z_CONFIG::$MAINTENANCE_MESSAGE);
}
if ($this->isWriteMethod() && Z_CONFIG::$READ_ONLY) {
$this->e503(Z_CONFIG::$MAINTENANCE_MESSAGE);
}
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 (!empty($_SERVER['HTTP_CONTENT_ENCODING']) && $_SERVER['HTTP_CONTENT_ENCODING'] == 'gzip') {
$this->body = gzdecode($this->body);
// If form data, parse uncompressed data into $_REQUEST. (This might not be used.)
if (isset($_SERVER['CONTENT_TYPE'])
&& $_SERVER['CONTENT_TYPE'] == 'application/x-www-form-urlencoded') {
parse_str($this->body, $_POST);
foreach ($_POST as $key => $val) {
$_REQUEST[$key] = $val;
}
}
}
}
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) {
if (!Z_ENV_TESTING_SITE
&& !IPAddress::isPrivateAddress($_SERVER['REMOTE_ADDR'])) {
error_log("Unexpected super-user request from " . $_SERVER['REMOTE_ADDR']);
Z_SNS::sendAlert(
"Unauthorized API access",
"{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']} from {$_SERVER['REMOTE_ADDR']}"
);
$this->e401('Invalid login');
}
$this->userID = 0;
$this->permissions = new Zotero_Permissions;
$this->permissions->setSuper();
}
// Allow HTTP Auth for file access
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']) || isset($headers['authorization'])) {
$val = isset($headers['Authorization'])
? $headers['Authorization']
: $headers['authorization'];
// Look for "Authorization: Bearer" from OAuth 2.0, and ignore everything else
if (preg_match('/^bearer/i', $val, $matches)) {
if (preg_match('/^bearer +([a-z0-9]+)$/i', $val, $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");
}
}
}
}
// Website cookie authentication
//
// For CSRF protection, session cookie has to be passed in the 'session' parameter,
// which JS code on other sites can't do because it can't access the website cookie.
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;
}
// No credentials provided
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' && empty($extra['noauth'])) {
$this->e403('An API key is required for write requests.');
}
// Anonymous request
$this->permissions = new Zotero_Permissions;
$this->permissions->setAnonymous();
}
}
// Request limiter needs initialized authentication parameters
$this->initRequestLimiter();
// 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) {
// Switch to DB writer
Zotero_DB::readOnly(false);
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();
}
}
// Get object group
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;
}
$this->isLegacySchemaClient = false;
if (strpos($_SERVER['HTTP_X_ZOTERO_VERSION'] ?? '', '5.0') === 0) {
require_once '../model/ToolkitVersionComparator.inc.php';
if (ToolkitVersionComparator::compare($_SERVER['HTTP_X_ZOTERO_VERSION'], "5.0.78" ) < 0
// Allow /keys and /groups requests, since prefs didn't display proper error
&& strpos($this->uri, '/keys') === false
&& strpos($this->uri, '/groups') === false) {
$this->e400("This version of Zotero is too old to sync. Please upgrade to a "
. "current version to continue syncing.", Z_ERROR_INVALID_INPUT);
}
$this->isLegacySchemaClient = ToolkitVersionComparator::compare(
$_SERVER['HTTP_X_ZOTERO_VERSION'], "5.0.78"
) < 0;
}
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();
}
if ($this->isWriteMethod()) {
$this->e405("Please upgrade to the latest version of Zotero to update My Publications.", Z_ERROR_INVALID_INPUT);
}
$this->permissions->setPublications();
// Added to queryParams below
$this->publications = true;
// If no publications items in main user library, see if there's a legacy publications library
if (!Zotero_Users::hasPublicationsInUserLibrary($this->objectUserID)) {
$publicationsLibraryID = Zotero_Users::getLibraryIDFromUserID(
$this->objectUserID, 'publications'
);
if ($publicationsLibraryID) {
$this->legacyPublications = true;
$this->objectLibraryID = $publicationsLibraryID;
}
}
// TEMP: Remove after integrated publications upgrade
if ($this->action == 'settings') {
// If publications in either legacy library or user library, show upgrade error
if (Zotero_Users::hasPublicationsInUserLibrary($this->objectUserID)
|| Zotero_Users::hasPublicationsInLegacyLibrary($this->objectUserID)) {
$this->e400("Please upgrade to the latest Zotero 5.0 beta to continue syncing My Publications.", Z_ERROR_INVALID_INPUT);
}
$this->apiVersion = 3;
header("Total-Results: 0");
$this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
$this->queryParams['format'] = 'json';
echo json_encode([]);
$this->end();
}
else if ($this->action == 'deleted') {
$this->apiVersion = 3;
$this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
$this->queryParams['format'] = 'json';
echo json_encode(new stdClass);
$this->end();
}
}
$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->fileViewURL = !empty($extra['viewurl']);
$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
);
$this->queryParams['schemaVersion'] = !empty($_SERVER['HTTP_ZOTERO_SCHEMA_VERSION'])
? (int) $_SERVER['HTTP_ZOTERO_SCHEMA_VERSION']
: 0;
if ($this->publications) {
$this->queryParams['publications'] = true;
// Don't show trashed items in publications view
$this->queryParams['includeTrashed'] = false;
}
// 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'];
if ($this->objectLibraryID) {
Zotero_DB::close();
}
header("Zotero-API-Version: " . $version);
StatsD::increment("api.request.version.v" . $version, 0.25);
header("Zotero-Schema-Version: " . \Zotero\Schema::getVersion());
}
public function index() {
$this->e400("Invalid Request");
}
public function noop() {
echo "Nothing to see here.";
exit;
}
/**
* Used for integration tests
*
* Valid only on testing site
*/
public function clear() {
if (!$this->permissions->isSuper()) {
$this->e404();
}
if (!Z_ENV_TESTING_SITE) {
$this->e404();
}
$this->allowMethods(array('POST'));
Zotero_Libraries::clearAllData($this->objectLibraryID);
$this->e204();
}
/**
* Used for integration tests
*
* Valid only on testing site
*/
public function testSetup() {
if (!$this->permissions->isSuper()) {
$this->e404();
}
if (!Z_ENV_TESTING_SITE) {
$this->e404();
}
$this->allowMethods(['POST']);
if (empty($_GET['u'])) {
throw new Exception("User not provided (e.g., ?u=1)");
}
if (empty($_GET['u2'])) {
throw new Exception("User 2 not provided (e.g., &u2=2)");
}
function getUserKey($userID) {
$keys = Zotero_Keys::getUserKeys($userID);
foreach ($keys as $keyObj) {
$keyObj->erase();
}
$keys = Zotero_Keys::getUserKeys($userID);
if ($keys) {
throw new Exception("Keys still exist");
}
// Create new key
$keyObj = new Zotero_Key;
$keyObj->userID = $userID;
$keyObj->name = "Tests Key";
$libraryID = Zotero_Users::getLibraryIDFromUserID($userID);
$keyObj->setPermission($libraryID, 'library', true);
$keyObj->setPermission($libraryID, 'notes', true);
$keyObj->setPermission($libraryID, 'write', true);
$keyObj->setPermission(0, 'group', true);
$keyObj->setPermission(0, 'write', true);
$keyObj->save();
$key = $keyObj->key;
Zotero_DB::beginTransaction();
// Clear data
Zotero_Users::clearAllData($userID);
// Delete publications library, so we can test auto-creating it
$publicationsLibraryID = Zotero_Users::getLibraryIDFromUserID($userID, 'publications');
if ($publicationsLibraryID) {
// Delete user publications shard library
$sql = "DELETE FROM shardLibraries WHERE libraryID=?";
Zotero_DB::query($sql, $publicationsLibraryID, Zotero_Shards::getByUserID($userID));
// Delete user publications library
$sql = "DELETE FROM libraries WHERE libraryID=?";
Zotero_DB::query($sql, $publicationsLibraryID);
Z_Core::$MC->delete('userPublicationsLibraryID_' . $userID);
Z_Core::$MC->delete('libraryUserID_' . $publicationsLibraryID);
}
Zotero_DB::commit();
return $key;
}
echo json_encode([
"user1" => [
"apiKey" => getUserKey($_GET['u'])
],
"user2" => [
"apiKey" => getUserKey($_GET['u2'])
]
]);
$this->end();
}
//
// Protected methods
//
protected function initRequestLimiter() {
$limits = $this->limits();
// Skip request limiter if controller 'limits' functions doesn't return anything
if (empty($limits)) {
return;
}
// Skip if neither rate nor concurrency limit isn't set
if (empty($limits['rate']) && empty($limits['concurrency'])) {
return;
}
// Skip if logOnly parameter isn't set
// (other parameters are checked in Z_RequestLimiter)
if (!empty($limits['rate']) && !isset($limits['rate']['logOnly']) ||
!empty($limits['concurrency']) && !isset($limits['concurrency']['logOnly'])) {
Z_Core::logError('Warning: Missing logOnly parameter, skipping request limiter');
return;
}
// Skip if failed to initialize (i.e. Redis error)
if (!Z_RequestLimiter::init()) return;
// Initialize rate limiter
if (!empty($limits['rate'])) {
if (Z_RequestLimiter::checkBucketRate($limits['rate']) === false) {
StatsD::increment('api.request.limit.rate.rejected', 1);
Z_Core::logError(($limits['rate']['logOnly'] ? '(WARN) ' : '')
. 'Request rate limit exceeded for ' . $limits['rate']['bucket']
. ' for ' . $this->method . ' to ' . $_SERVER['REQUEST_URI']);
if (!$limits['rate']['logOnly']) {
// Suggest to retry when the full capacity will be reached
header('Retry-After: ' . (int) $limits['rate']['capacity'] / $limits['rate']['replenishRate']);
$this->e429('Request rate limit exceeded');
}
}
}
// Initialize concurrency limiter
if (!empty($limits['concurrency'])) {
if (Z_RequestLimiter::beginConcurrentRequest($limits['concurrency']) === false) {
StatsD::increment('api.request.limit.concurrency.rejected', 1);
Z_Core::logError(($limits['concurrency']['logOnly'] ? '(WARN) ' : '')
. 'Concurrent request limit exceeded for ' . $limits['concurrency']['bucket']
. ' for ' . $this->method . ' to ' . $_SERVER['REQUEST_URI']);
if (!$limits['concurrency']['logOnly']) {
// Randomize retry suggestion delay to spread future requests in a wider time interval
header('Retry-After: ' . rand(1, 30));
$this->e429('Concurrent request limit exceeded');
}
}
}
}
/**
* Override this function on other controllers
* to set different request limits
* @return array ['rate'=>[], 'concurrency'=>[]]
*/
protected function limits() {
$limits = [];
// Rate limit
// For authorized request
if (!empty($this->userID)) {
// 10 requests per second, 100 requests burst
$limits['rate'] = [
'logOnly' => false,
'bucket' => $this->userID . '_' . $_SERVER['REMOTE_ADDR'],
'capacity' => 100,
'replenishRate' => 10
];
}
// For anonymous request
else {
// 30 requests per second, no burst
$limits['rate'] = [
'logOnly' => false,
'bucket' => $_SERVER['REMOTE_ADDR'],
'capacity' => 30,
'replenishRate' => 30
];
}
// Concurrency limit
// For authorized request
if (!empty($this->userID)) {
// 5 concurrent requests
$limits['concurrency'] = [
'logOnly' => false,
'bucket' => $this->userID,
'capacity' => 5,
// Maximum possible time the request can take
'ttl' => 60
];
}
// For anonymous request
else {
// 20 concurrent requests
$limits['concurrency'] = [
'logOnly' => false,
'bucket' => $_SERVER['REMOTE_ADDR'],
'capacity' => 20,
// Maximum possible time the request can take
'ttl' => 60
];
}
return $limits;
}
protected function getFeedNamePrefix($libraryID=false) {
$prefix = "Zotero / ";
if ($libraryID) {
$type = Zotero_Libraries::getType($this->objectLibraryID);
}
else {
$type = false;
}
switch ($type) {
case "user":
$title = $prefix . Zotero_Libraries::getName($this->objectLibraryID);
break;
case "group":
$title = $prefix . "" . Zotero_Libraries::getName($this->objectLibraryID) . " Group";
break;
default:
return $prefix;
}
return $title . " / ";
}
/**
* Verify the HTTP method
*/
protected function allowMethods($methods, $message="Method not allowed") {
if (!in_array($this->method, $methods)) {
header("Allow: " . implode(", ", $methods));
$this->e405($message);
}
}
protected function isWriteMethod() {
return in_array($this->method, array('POST', 'PUT', 'PATCH', 'DELETE'));
}
protected function handleObjectWrite($objectType, $obj=null) {
if (!is_object($obj) && !is_null($obj)) {
throw new Exception('$obj must be a data object or null');
}
$objectTypePlural = \Zotero\DataObjectUtilities::getObjectTypePlural($objectType);
$objectsClassName = "Zotero_" . ucwords($objectTypePlural);
$json = !empty($this->body) ? $this->jsonDecode($this->body) : false;
$objectVersionValidated = $this->checkSingleObjectWriteVersion($objectType, $obj, $json);
$this->libraryVersion = Zotero_Libraries::getUpdatedVersion($this->objectLibraryID);
// Update item
if ($this->method == 'PUT' || $this->method == 'PATCH') {
if ($this->apiVersion < 2) {
$this->allowMethods(['PUT']);
}
if (!$obj) {
$className = "Zotero_" . ucwords($objectType);
$obj = new $className;
$obj->libraryID = $this->objectLibraryID;
$obj->key = $this->objectKey;
}
if ($objectType == 'item') {
$changed = Zotero_Items::updateFromJSON(
$obj,
$json,
null,
$this->queryParams,
$this->userID,
$objectVersionValidated ? 0 : 2,
$this->method == 'PATCH'
);
}
else {
$changed = $objectsClassName::updateFromJSON(
$obj,
$json,
$this->queryParams,
$this->userID,
$objectVersionValidated ? 0 : 2,
$this->method == 'PATCH'
);
}
// If not updated, return the original library version
if (!$changed) {
$this->libraryVersion = Zotero_Libraries::getOriginalVersion(
$this->objectLibraryID
);
}
if ($cacheKey = $this->getWriteTokenCacheKey()) {
Z_Core::$MC->set($cacheKey, true, $this->writeTokenCacheTime);
}
}
// Delete item
else if ($this->method == 'DELETE') {
$objectsClassName::delete($this->objectLibraryID, $this->objectKey);
}
else {
throw new Exception("Unexpected method $this->method");
}
if ($this->apiVersion >= 2 || $this->method == 'DELETE') {
$this->e204();
}
return $obj;
}
/**
* For single-object requests for some actions, require If-Unmodified-Since-Version, the
* deprecated If-Match, or a JSON version property, and make sure the object hasn't been
* modified
*
* @param {String} $objectType
* @param {Zotero_DataObject}
* @return {Boolean} - True if the object has been cleared for writing, or false if the JSON
* version property still needs to pass
*/
protected function checkSingleObjectWriteVersion($objectType, $obj=null, $json=false) {
if (!is_object($obj) && !is_null($obj)) {
throw new Exception('$obj must be a data object or null');
}
// In versions below 3, no writes to missing objects
if (!$obj && $this->apiVersion < 3) {
$this->e404(ucwords($objectType) . " not found");
}
if (!in_array($objectType, array('item', 'collection', 'search', 'setting'))) {
throw new Exception("Invalid object type");
}
if (Z_CONFIG::$TESTING_SITE && !empty($_GET['skipetag'])) {
return true;
}
// If-Match (deprecated)
if ($this->apiVersion < 2) {
if (empty($_SERVER['HTTP_IF_MATCH'])) {
if ($this->method == 'DELETE') {
$this->e428("If-Match must be provided for delete requests");
}
else {
return false;
}
}
if (!preg_match('/^"?([a-f0-9]{32})"?$/', $_SERVER['HTTP_IF_MATCH'], $matches)) {
$this->e400("Invalid ETag in If-Match header");
}
if ($obj->etag != $matches[1]) {
$this->e412("ETag does not match current version of $objectType");
}
return true;
}
// Get version from If-Unmodified-Since-Version header
$headerVersion = isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE_VERSION'])
? $_SERVER['HTTP_IF_UNMODIFIED_SINCE_VERSION'] : false;
// Get version from JSON 'version' property
if ($json) {
$json = Zotero_API::extractEditableJSON($json);
if ($this->apiVersion >= 3) {
$versionProp = 'version';
}
else {
$versionProp = $objectType == 'setting' ? 'version' : $objectType . "Version";
}
$propVersion = isset($json->$versionProp) ? $json->$versionProp : false;
}
else {
$propVersion = false;
}
if ($this->method == 'DELETE' && $headerVersion === false) {
$this->e428("If-Unmodified-Since-Version must be provided for delete requests");
}
if ($headerVersion !== false) {
if (!is_numeric($headerVersion)) {
$this->e400("Invalid If-Unmodified-Since-Version value '$headerVersion'");
}
$headerVersion = (int) $headerVersion;
}
if ($propVersion !== false) {
if (!is_numeric($propVersion)) {
$this->e400("Invalid JSON 'version' property value '$propVersion'");
}
$propVersion = (int) $propVersion;
}
// If both header and property given, they have to match
if ($headerVersion !== false && $propVersion !== false && $headerVersion !== $propVersion) {
$this->e400("If-Unmodified-Since-Version value does not match JSON '$versionProp' property "
. "($headerVersion != $propVersion)");
}
$version = $headerVersion !== false ? $headerVersion : $propVersion;
// If object doesn't exist, version has to be 0 if provided
if (!$obj) {
// PATCH is only allowed for missing objects with version 0
if ($this->method == "PATCH" && $version === false) {
$this->e404(ucwords($objectType) . " not found "
. "(to create, use If-Unmodified-Since-Version: 0, JSON 'version' 0, or PUT method)");
}
if ($version > 0) {
$this->e404(ucwords($objectType) . " not found (expected version $version)");
}
return true;
}
if ($version === false) {
throw new HTTPException("Either If-Unmodified-Since-Version or object version "
. "property must be provided for key-based writes", 428
);
}
if ($obj->version !== $version) {
$this->libraryVersion = $obj->version;
$this->e412(ucwords($objectType) . " has been modified since specified version "
. "(expected $version, found " . $obj->version . ")");
}
return true;
}
/**
* For multi-object requests for some actions, require
* If-Unmodified-Since-Version and make sure the library
* hasn't been modified
*
* @param boolean $required Return 428 if header is missing
* @return boolean True if library version was checked, false if not
*/
protected function checkLibraryIfUnmodifiedSinceVersion($required=false) {
if (Z_CONFIG::$TESTING_SITE && !empty($_GET['skipetag'])) {
return true;
}
if (!isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE_VERSION'])) {
if ($required) {
$this->e428("If-Unmodified-Since-Version not provided");
}
return false;
}
$version = $_SERVER['HTTP_IF_UNMODIFIED_SINCE_VERSION'];
if (!is_numeric($version)) {
$this->e400("Invalid If-Unmodified-Since-Version value");
}
$libraryVersion = Zotero_Libraries::getVersion($this->objectLibraryID);
if ($libraryVersion > $version) {
$this->e412("Library has been modified since specified version "
. "(expected $version, found $libraryVersion)");
}
return true;
}
/**