-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathapi.php
More file actions
5746 lines (5102 loc) · 257 KB
/
api.php
File metadata and controls
5746 lines (5102 loc) · 257 KB
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
/*
* This file is part of XenAPI <http://www.xenapi.net/>.
*
* XenAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* XenAPI 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// To change the API key, replace the REPLACE_THIS_WITH_AN_API_KEY with your desired API key.
$restAPI = new RestAPI('REPLACE_THIS_WITH_AN_API_KEY');
# DO NOT CHANGE ANYTHING BELOW THIS LINE UNLESS
# YOU REALLY KNOW WHAT ARE YOU DOING
// Process the request
if ($restAPI->getAPIKey() !== NULL && $restAPI->isDefaultAPIKey()) {
// API is set but not changed from the default API key.
$restAPI->throwError(17);
} else if ($restAPI->getAPIKey() !== NULL && !$restAPI->hasRequest('hash') && !$restAPI->isPublicAction()) {
// Hash argument is required and was not found, throw error.
$restAPI->throwError(3, 'hash');
} else if (!$restAPI->getHash() && !$restAPI->isPublicAction()) {
// Hash argument is empty or not set, throw error.
$restAPI->throwError(1, 'hash');
} else if (!$restAPI->isAuthenticated() && !$restAPI->isPublicAction()) {
// Hash is not valid and action is not public, throw error.
$restAPI->throwError(6, $restAPI->getHash(), 'hash');
} else if (!$restAPI->hasRequest('action')) {
// Action argument was not found, throw error.
$restAPI->throwError(3, 'action');
} else if (!$restAPI->getAction()) {
// Action argument is empty or not set, throw error.
$restAPI->throwError(1, 'action');
} else if (!$restAPI->isSupportedAction()) {
// Action is not supported, throw error.
$restAPI->throwError(2, $restAPI->getAction());
} else if (!$restAPI->isPermitted()) {
// User does not have permission to use this action, throw error.
if ($restAPI->hasRequest('value') && $restAPI->isUserAction()) {
$restAPI->throwError(9, $restAPI->getAction());
} else {
$restAPI->throwError(10, $restAPI->getAction());
}
}
// Process the request.
$restAPI->processRequest();
class RestAPI {
const VERSION = '1.4.2';
const DEFAULT_APIKEY = 'REPLACE_THIS_WITH_AN_API_KEY';
const GENERAL_ERROR = 0x201;
const USER_ERROR = 0x202;
const THREAD_ERROR = 0x203;
const POST_ERROR = 0x204;
/**
* Contains all the actions in an array, each action is 'action' => 'permission_name'
* 'action' is the name of the action in lowercase.
* 'permission_name' is the permission requirement of the action, see description under.
*
* Permission names and meaning:
* - public: A hash is not required to use this action, it can be used without
* without being 'authenticated'.
* - authenticated: The action requires the user to be authenticated to use the action
* with a 'value' argument.
* - moderator: The action requires the user to be a moderator to use the action
* with a 'value' argument.
* - administrator: The action requires the user to be an administrator to use the action
* with a 'value' argument.
* - private: User is only allowed to use the action on himself/herself.
* Example: If user tries to use 'getAlerts' with a 'value' argument,
* an error will be thrown.
* - api_key: An API key is required to perform this action.
*
* NOTE: Permissions are ignored when the API key is used as a hash, permissions are only
* used when the user is using the 'username:hash' format for the 'hash' argument.
*/
private $actions = array(
'authenticate' => 'public',
'createalert' => 'api_key',
'createconversation' => 'authenticated',
'createconversationreply' => 'authenticated',
'createpost' => 'authenticated',
'createprofilepost' => 'authenticated',
'createprofilepostcomment' => 'authenticated',
'createthread' => 'authenticated',
'deletepost' => 'authenticated',
'deleteuser' => 'authenticated',
'downgradeuser' => 'api_key',
'editpost' => 'authenticated',
'editthread' => 'authenticated',
'edituser' => 'api_key',
'getactions' => 'public',
'getaddon' => 'administrator',
'getaddons' => 'administrator',
'getalerts' => 'private',
'getavatar' => 'public',
'getconversation' => 'private',
'getconversations' => 'private',
'getgroup' => 'public',
'getnode' => 'public',
'getnodes' => 'public',
'getpost' => 'public',
'getposts' => 'public',
'getprofilepost' => 'authenticated',
'getprofileposts' => 'authenticated',
'getresource' => 'administrator',
'getresources' => 'administrator',
'getresourcecategories' => 'administrator',
'getstats' => 'public',
'getthread' => 'public',
'getthreads' => 'public',
'getuser' => 'authenticated',
'getusers' => 'public',
'getuserupgrade' => 'api_key',
'getuserupgrades' => 'api_key',
'login' => 'public',
'register' => 'api_key',
'search' => 'public',
'upgradeuser' => 'api_key'
);
// Array of actions that are user specific and require an username, ID or email for the 'value' parameter.
private $user_actions = array('getalerts', 'getavatar', 'getconversation', 'getconversations', 'createprofilepost', 'getuser');
// List of general errors, this is where the 'throwError' function gets the messages from.
private $general_errors = array(
0 => 'Unknown error',
1 => 'Argument: "{ERROR}", is empty/missing a value',
2 => '"{ERROR}", is not a supported action',
3 => 'Missing argument: "{ERROR}"',
4 => 'No {ERROR} found with the argument: "{ERROR2}"',
5 => 'Authentication error: "{ERROR}"',
6 => '"{ERROR}" is not a valid {ERROR2}',
7 => 'Something went wrong when "{ERROR}": "{ERROR2}"',
8 => 'The request had no values set, available fields are: "({ERROR})"',
9 => 'You are not permitted to use the "{ERROR}" action on others (remove the value argument)',
10 => 'You do not have permission to use the "{ERROR}" action',
11 => '"{ERROR}" is a supported action but there is no code for it yet',
12 => '"{ERROR}" is a unknown request method',
13 => '"{ERROR}" is not an installed addon',
14 => '"{ERROR}" is not an author of any resources',
15 => 'Could not find a resource with ID "{ERROR}"',
16 => 'Could not find a required model to perform this request: "{ERROR}"',
17 => 'The API key has not been changed, make sure you use another API key before using this API',
18 => '"{ERROR} is a unknown permission name, the request was terminated.',
19 => 'Could not find a {ERROR} with ID "{ERROR2}"',
20 => '{ERROR} not have permissions to view {ERROR2}',
21 => 'The "{ERROR}" argument has to be a number',
22 => 'The argument for "order_by", "{ERROR}", was not found in the list available order by list: "({ERROR2})"',
23 => 'The argument for "node_type", "{ERROR}", was not found in the list available node type list: "({ERROR2})"',
24 => 'The argument for "discussion_state", "{ERROR}", was not found in the list available discussion state list: "({ERROR2})"'
);
// Specific errors related to user actions.
private $user_errors = array(
0 => 'Unknown user error',
1 => 'Field was not recognised',
2 => 'Group not found',
3 => 'User data array was missing',
4 => 'The specified user is not registered',
5 => 'Invalid custom field array',
6 => 'Editing super admins is disabled',
7 => 'The add_groups parameter needs to be an array and have at least 1 item',
8 => 'The user is already a member of the group(s)',
9 => 'No values were changed',
10 => 'Missing required a required parameter',
11 => 'The remove_groups parameter needs to be an array and have at least 1 item',
12 => 'The user is not a member of the group(s)',
13 => 'An user is required to create a post/thread',
14 => 'The user does not have permissions to post in this thread',
30 => 'Missing required registration fields',
31 => 'Password invalid',
32 => 'Name length is too short',
33 => 'Name length is too long',
34 => 'Name contains disallowed words',
35 => 'Name does not follow the required format',
36 => 'Name contains censored words',
37 => 'Name contains CTRL characters',
38 => 'Name contains comma',
39 => 'Name resembles an email',
40 => 'User already exists',
41 => 'Invalid email',
42 => 'Email already used',
43 => 'Email banned by administrator',
44 => 'Invalid timezone',
45 => 'Custom title contains censored words',
46 => 'Custom title contains disallowed words',
47 => 'Invalid date of birth',
48 => 'Cannot delete your own account',
49 => 'Field contained an invalid value'
);
private $xenAPI, $method, $data = array(), $hash = FALSE, $apikey = FALSE;
/**
* Default constructor for the RestAPI class.
* The data gets set here depending on what kind of request method is being used.
*/
public function __construct($api_key = NULL) {
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
switch ($this->method) {
case 'get':
$this->data = $_GET;
break;
case 'post':
$this->data = $_POST;
break;
case 'put':
case 'delete':
parse_str(file_get_contents('php://input'), $put_vars);
$this->data = $put_vars;
break;
default:
$this->throwError(12, $this->method);
}
$this->xenAPI = new XenAPI();
// Set the API key.
$this->apikey = $api_key;
// Lowercase the key data, ignores the case of the arguments.
$this->data = array_change_key_case($this->data);
if ($this->hasRequest('hash')) {
// Sets the hash variable if the hash argument is set.
$this->hash = $this->getRequest('hash');
}
// Check if grab_as by argument is set.
if ($this->hasRequest('grab_as') && $this->hasAPIKey()) {
if (!$this->getRequest('grab_as')) {
// Throw error if the 'grab_as' argument is set but empty.
$this->throwError(1, 'grab_as');
}
// Create a user object with the 'grab_as' argument.
$this->grab_as = $this->xenAPI->getUser($this->getRequest('grab_as'));
if (!$this->grab_as->isRegistered()) {
// Throw error if the 'grab_as' user is not registered.
$this->throwError(4, 'user', $this->getRequest('grab_as'));
}
}
// Check if order by argument is set.
if ($this->hasRequest('order_by')) {
if (!$this->getRequest('order_by')) {
// Throw error if the 'order_by' argument is set but empty.
$this->throwError(1, 'order_by');
}
$this->order_by = $this->getRequest('order_by');
}
// Check if order argument is set.
if ($this->hasRequest('order')) {
if (!$this->getRequest('order')) {
// Throw error if the 'order' argument is set but empty.
$this->throwError(1, 'order');
}
$this->order = strtolower($this->getRequest('order'));
if ($this->order == 'd' || $this->order == 'desc' || $this->order == 'descending') {
// Order is descending (10-0).
$this->order = 'desc';
} else if ($this->order == 'a' || $this->order == 'asc' || $this->order == 'ascending') {
// Order is ascending (0-10).
$this->order = 'asc';
} else {
// Order is unknown, default to descending (10-0).
$this->order = 'desc';
}
} else {
// Order is not set, default to descending (10-0).
$this->order = 'desc';
}
// Set the limit.
$this->setLimit(100);
}
/**
* Returns the XenAPI, returns NULL if the XenAPI was not set.
*/
public function getXenAPI() {
return $this->xenAPI;
}
public function isDefaultAPIKey() {
return $this->getAPIKey() == self::DEFAULT_APIKEY;
}
/**
* Returns the API key, returns FALSE if an API key was not set.
*/
public function getAPIKey() {
return $this->apikey;
}
/**
* Sets the API key.
*/
public function setAPIKey($apikey) {
$this->apikey = $apikey;
}
/**
* Return the hash, returns FALSE if the hash was not set.
*/
public function getHash() {
return $this->hash;
}
/**
* TODO
*/
public function setLimit($default) {
// Check if limit argument is set.
if ($this->hasRequest('limit')) {
if (!$this->getRequest('limit') && (is_numeric($this->getRequest('limit')) && $this->getRequest('limit') != 0)) {
// Throw error if the 'limit' argument is set but empty.
$this->throwError(1, 'limit');
} else if (!is_numeric($this->getRequest('limit'))) {
// Throw error if the 'limit' argument is set but not a number.
$this->throwError(21, 'limit');
}
$this->limit = $this->getRequest('limit');
} else {
// Limit is not set, default to $default variable.
$this->limit = $default;
}
}
private function stripUserData($user) {
/*
* Run through an additional permission check if the request is
* not using an API key, unset some variables depending on the
* user level.
*/
$data = $user->getData();
if (!$this->hasAPIKey()) {
// Unset variables since the API key isn't used.
if (isset($data['style_id'])) {
unset($data['style_id']);
}
if (isset($data['display_style_group_id'])) {
unset($data['display_style_group_id']);
}
if (isset($data['permission_combination_id'])) {
unset($data['permission_combination_id']);
}
if (!$this->getUser()->isAdmin()) {
// Unset variables if user is not an admin.
if (isset($data['is_banned'])) {
unset($data['is_banned']);
}
}
if (!$this->getUser()->isModerator() && $this->getUser()->getID() != $user->getID()) {
// Unset variables if user is not a moderator.
if (isset($data['user_state'])) {
unset($data['user_state']);
}
if (isset($data['visible'])) {
unset($data['visible']);
}
if (isset($data['email'])) {
unset($data['email']);
}
if (isset($data['custom_fields'])) {
unset($data['custom_fields']);
}
}
if ($this->getUser()->getID() != $user->getID()) {
// Unset variables if user does not equal the requested user by the 'value' argument.
if (isset($data['language_id'])) {
unset($data['language_id']);
}
if (isset($data['message_count'])) {
unset($data['message_count']);
}
if (isset($data['conversations_unread'])) {
unset($data['conversations_unread']);
}
if (isset($data['alerts_unread'])) {
unset($data['alerts_unread']);
}
if (isset($data['upgrades'])) {
unset($data['upgrades']);
}
}
}
return $data;
}
/**
* Checks if the request is authenticated.
* Returns TRUE if the hash equals the API key.
* Returns TRUE if the hash equals the user hash.
* Returns FALSE if none of the above are TRUE.
*/
public function isAuthenticated() {
if ($this->getHash()) {
// Hash argument is set, continue.
if ($this->getHash() == $this->getAPIKey()) {
// The hash equals the API key, return TRUE.
return TRUE;
}
if (strpos($this->getHash(), ':') !== FALSE) {
// The hash contains : (username:hash), split it into an array.
$array = explode(':', $this->getHash());
// Get the user and check if the user is valid (registered).
$user = $this->xenAPI->getUser($array[0]);
if ($user->isRegistered()) {
// User is registered, get the hash from the authentication record.
$record = $user->getAuthenticationRecord();
$ddata = unserialize($record['data']);
$decoded = base64_decode($array[1], TRUE);
if ($ddata['hash'] == $array[1] || ($decoded !== FALSE && $ddata['hash'] == $decoded)) {
// The hash in the authentication record equals the hash in the 'hash' argument.
return TRUE;
}
}
}
}
return FALSE;
}
/**
* Checks if the request is permitted.
* Returns TRUE if API key is set and valid or the action's permission is public.
*/
public function isPermitted() {
$permission = $this->getActionPermission();
// Check if the request is authenticated and it's an user hash (and not an API key).
if ($this->isAuthenticated() && $this->getUser()) {
switch ($permission) {
case 'public':
return TRUE;
case 'authenticated':
return TRUE;
case 'moderator':
return $this->getUser()->isModerator();
case 'administrator':
return $this->getUser()->isAdmin();
case 'private':
// Check if the 'value' argument is set.
if ($this->hasRequest('value') && $this->getRequest('value')) {
/**
* Returns TRUE if the 'value' argument equals the username of the user hash.
* In other words, the request is not permitted if 'value' != username.
*/
return $this->getUser()->getUsername() == $this->getRequest('value');
}
// The value argument is not, request is permitted, return TRUE.
return TRUE;
case 'api_key':
return $this->hasAPIKey();
default:
$this->throwError(10, $this->getAction());
}
}
// Returns TRUE if permission of the action is public or the request has a valid API key.
return $permission == 'public' || $this->hasAPIKey();
}
public function getCustomArray($input_data) {
// Custom fields are set.
$custom_array_data = array();
// Check if there are more than one custom array.
if (strpos($input_data, ',') !== FALSE) {
// There are more than one custom array set.
$custom_arrays = explode(',', $input_data);
// Loop through the custom fields.
foreach ($custom_arrays as $custom_array) {
// Check if custom array string contains = symbol, ignore if not.
if (strpos($custom_array, '=') !== FALSE) {
// Custom array string contains = symbol, explode it.
$custom_array_list = explode('=', $custom_array);
// Add the custom item data to the array.
$custom_array_data[$custom_array_list[0]] = $custom_array_list[1];
}
}
} else if (strpos($input_data, '=') !== FALSE) {
// Custom array string contains = symbol, explode it.
$custom_array_list = explode('=', $input_data);
// Add the custom item data to the array.
$custom_array_data[$custom_array_list[0]] = $custom_array_list[1];
}
// Return the array(s).
return $custom_array_data;
}
/**
* Returns TRUE if the request has an API key that is valid, returns FALSE if not.
*/
public function hasAPIKey() {
if ($this->getHash()) {
return $this->getHash() == $this->getAPIKey();
}
return FALSE;
}
/**
* Returns the User class of the username if the hash is set and is an userhash.
* Returns FALSE if the hash is not an userhash.
*/
public function getUser() {
if (isset($this->user) && $this->user !== NULL) {
return $this->user;
} else if (isset($this->grab_as) && $this->grab_as !== NULL) {
return $this->grab_as;
} else if (strpos($this->getHash(), ':') !== FALSE) {
$array = explode(':', $this->getHash());
$this->user = $this->xenAPI->getUser($array[0]);
return $this->user;
}
return NULL;
}
/**
*
*/
public function checkOrderBy($order_by_array) {
if ($this->hasRequest('order_by')) {
if (!$this->getRequest('order_by')) {
// Throw error if the 'order_by' argument is set but empty.
$this->throwError(1, 'order_by');
}
if (!in_array(strtolower($this->getRequest('order_by')), $order_by_array)) {
// Throw error if the 'order_by' argument is set but could not be found in list of allowed order_by.
$this->throwError(22, $this->getRequest('order_by'), implode(', ', $order_by_array));
}
return strtolower($this->getRequest('order_by'));
}
return FALSE;
}
/**
* Returns the method (get, post, put, delete).
*/
public function getMethod() {
return $this->method;
}
/**
* Returns the action name.
*/
public function getAction() {
return $this->getRequest('action');
}
/**
* Returns the permission name of the action.
*/
public function getActionPermission() {
return (isset($this->data['action']) && isset($this->actions[strtolower($this->getAction())]))
? strtolower($this->actions[strtolower($this->getAction())])
: NULL;
}
/**
* Returns TRUE if the '$key' is set a argument, returns FALSE if not.
*/
public function hasRequest($key) {
return isset($this->data[strtolower($key)]);
}
/**
* Gets the data of the '$key', returns FALSE if the '$key' argument was not set.
*/
public function getRequest($key) {
if ($this->hasRequest($key)) {
return $this->data[strtolower($key)];
} else {
return FALSE;
}
}
/**
* Returns the array of all the arguments in the request.
*/
public function getData() {
return $this->data;
}
/**
* Returns TRUE if the action is supported, FALSE if not.
*/
public function isSupportedAction() {
return isset($this->data['action']) && array_key_exists(strtolower($this->data['action']), $this->actions);
}
/**
* Returns TRUE if the action is a public action (does not require a hash), FALSE if not.
*/
public function isPublicAction() {
return isset($this->data['action']) && isset($this->actions[strtolower($this->data['action'])]) && strtolower($this->actions[strtolower($this->data['action'])]) == 'public';
}
/**
* Returns TRUE if the action is a user action (the 'value' parameter has to be an username/id/email), FALSE if not.
*/
public function isUserAction() {
return isset($this->data['action']) && in_array(strtolower($this->data['action']), $this->user_actions);
}
/**
* TODO
*/
public function checkRequestParameter($parameter, $required = TRUE) {
if ($required && !$this->hasRequest($parameter)) {
// The '$parameter' argument has not been set, throw error.
$this->throwError(3, $parameter);
} else if ($this->hasRequest($parameter) && $this->getRequest($parameter) === FALSE) {
// Throw error if the '$parameter' argument is set but empty.
$this->throwError(1, $parameter);
}
return TRUE;
}
/**
* TODO
*/
public function checkRequestParameters(array $parameters, $required = TRUE) {
foreach ($parameters as $parameter) {
$this->checkRequestParameter($parameter, $required);
}
return TRUE;
}
/**
* TODO
*/
public function getUserErrorID($phrase_name) {
switch ($phrase_name) {
case 'please_enter_value_for_all_required_fields':
return 30;
case 'please_enter_valid_password':
return 31;
case 'please_enter_name_that_is_at_least_x_characters_long':
return 32;
case 'please_enter_name_that_is_at_most_x_characters_long':
return 33;
case 'please_enter_another_name_disallowed_words':
return 34;
case 'please_enter_another_name_required_format':
return 35;
case 'please_enter_name_that_does_not_contain_any_censored_words':
return 36;
case 'please_enter_name_without_using_control_characters':
return 37;
case 'please_enter_name_that_does_not_contain_comma':
return 38;
case 'please_enter_name_that_does_not_resemble_an_email_address':
return 39;
case 'usernames_must_be_unique':
return 40;
case 'please_enter_valid_email':
return 41;
case 'email_addresses_must_be_unique':
return 42;
case 'email_address_you_entered_has_been_banned_by_administrator':
return 43;
case 'please_select_valid_time_zone':
return 44;
case 'please_enter_custom_title_that_does_not_contain_any_censored_words':
return 45;
case 'please_enter_another_custom_title_disallowed_words':
return 46;
case 'please_enter_valid_date_of_birth':
return 47;
case 'you_cannot_delete_your_own_account':
return 48;
case 'please_enter_valid_value':
return 49;
default:
return 0;
}
}
/**
* Gets the error message and replaces {ERROR} with the $extra parameter.
*/
public function getError($error, $extra = NULL, $extra2 = NULL, $error_type = self::GENERAL_ERROR) {
if ($error_type == NULL) {
$error_type = self::GENERAL_ERROR;
}
if ($error_type == self::GENERAL_ERROR) {
if (!array_key_exists($error, $this->general_errors)) {
$error = 0;
}
$error_string = $this->general_errors[$error];
} else if ($error_type == self::USER_ERROR) {
if (!array_key_exists($error, $this->user_errors)) {
$error = 0;
}
$error_string = $this->user_errors[$error];
}
if ($extra !== NULL) {
$error_string = str_replace('{ERROR}', $extra, $error_string);
}
if ($extra2 !== NULL) {
$error_string = str_replace('{ERROR2}', $extra2, $error_string);
}
return array('id' => $error, 'message' => $error_string);
}
/**
* Throw the error message.
*/
public function throwError($error, $extra = NULL, $extra2 = NULL) {
if ($error == self::USER_ERROR || $error == self::THREAD_ERROR || $error == self::POST_ERROR) {
if ($error == self::USER_ERROR) {
$error_key = 'user';
} else if ($error == self::THREAD_ERROR) {
$error_key = 'thread';
} else if ($error == self::POST_ERROR) {
$error_key = 'post';
}
if ($extra2 == NULL) {
$extra2 = 'performing a ' . $error_key . ' action';
}
$user_error = $this->getError($extra['error_id'], NULL, NULL, self::USER_ERROR);
$general_error = $this->getError(7, $extra2, $user_error['message']);
$error_response = array(
'error' => $general_error['id'],
'message' => $general_error['message'],
$error_key . '_error_id' => $user_error['id'],
$error_key . '_error_field' => $extra['error_field'],
$error_key . '_error_key' => $extra['error_key'],
$error_key . '_error_phrase' => $extra['error_phrase']
);
} else {
if (is_array($extra)) {
$extra = implode(', ', $extra);
}
if (is_array($extra2)) {
$extra2 = implode(', ', $extra2);
}
$error = $this->getError($error, $extra, $extra2, $error_type);
$error_response = array('error' => $error['id'], 'message' => $error['message']);
}
// Throw a 400 error.
header('HTTP/1.1 400 API error', TRUE, 400);
// Send error.
$this->sendResponse($error_response);
}
private function handleUserError($user_results, $error_key, $error_message) {
if (!empty($user_results['error'])) {
// Contains errors, process errors.
if (is_array($user_results['errors'])) {
// The error message was an array, loop through the messages.
$error_keys = array();
foreach ($user_results['errors'] as $error_field => $error) {
if (!($error instanceof XenForo_Phrase)) {
$post_error = array(
'error_id' => 1,
'error_key' => 'field_not_recognised',
'error_field' => $error_field,
'error_phrase' => $error
);
$this->throwError(self::USER_ERROR, $post_error, $error_message);
}
// Let's init the error array.
$post_error = array(
'error_id' => $this->getUserErrorID($error->getPhraseName()),
'error_key' => $error->getPhraseName(),
'error_field' => $error_field,
'error_phrase' => $error->render()
);
$this->throwError(self::USER_ERROR, $post_error, $error_message);
}
} else {
$post_error = array(
'error_id' => $user_results['error'],
'error_key' => 'general_user_' . $error_key,
'error_phrase' => $user_results['errors']
);
$this->throwError(self::USER_ERROR, $post_error, $error_message);
// Throw error message.
}
} else {
// Reesult was successful, return results.
$this->sendResponse($user_results);
}
}
/**
* Processes the REST request.
*/
public function processRequest() {
// Check if the action is an user action.
if ($this->isUserAction()) {
if ($this->hasRequest('value')) {
if (!$this->getRequest('value')) {
// Throw error if the 'value' argument is set but empty.
$this->throwError(1, 'value');
}
// Create a user variable with the 'value' argument.
$user = $this->xenAPI->getUser($this->getRequest('value'));
if (!$user->isRegistered()) {
// Throw error if the 'value' user is not registered.
$this->throwError(4, 'user', $this->getRequest('value'));
}
} else if ($this->hasRequest('hash')) {
// The 'value' argument was not set, check if hash is an API key.
if ($this->hasAPIKey() && !isset($this->grab_as)) {
/**
* The 'hash' argument is an API key, and the 'value' argument
* is required but not set, throw error.
*/
$this->throwError(3, 'value');
}
// Get the user from the hash.
$user = $this->getUser();
} else {
// Nor the 'value' argument or the 'hash' argument has been set, throw error.
$this->throwError(3, 'value');
}
if ($this->hasRequest('with_upgrades')) {
$user_upgrades = $this->getXenAPI()->getUserUpgrades($user);
if (!$user_upgrades && $this->hasRequest('user')) {
$this->throwError(4, 'user upgrades', $this->getRequest('user'));
}
$user->data['upgrades'] = $user_upgrades;
}
}
switch (strtolower($this->getAction())) {
case 'authenticate':
/**
* Authenticates the user and returns the hash that the user has to use for future requests.
*
* EXAMPLE:
* - api.php?action=authenticate&username=USERNAME&password=PASSWORD
*/
if (!$this->hasRequest('username')) {
// The 'username' argument has not been set, throw error.
$this->throwError(3, 'username');
} else if (!$this->getRequest('username')) {
// Throw error if the 'username' argument is set but empty.
$this->throwError(1, 'username');
} else if (!$this->hasRequest('password')) {
// The 'password' argument has not been set, throw error.
$this->throwError(3, 'password');
} else if (!$this->getRequest('password')) {
// Throw error if the 'password' argument is set but empty.
$this->throwError(1, 'password');
}
// Get the user object.
$user = $this->xenAPI->getUser($this->getRequest('username'));
if (!$user->isRegistered()) {
// Requested user was not registered, throw error.
$this->throwError(4, 'user', $this->getRequest('username'));
} else {
// Requested user was registered, check authentication.
if ($user->validateAuthentication($this->getRequest('password'))) {
// Authentication was valid, grab the user's authentication record.
$record = $user->getAuthenticationRecord();
$ddata = unserialize($record['data']);
// Send the hash in responsel.
$this->sendResponse(array('hash' => base64_encode($ddata['hash'])));
} else {
// The username or password was wrong, throw error.
$this->throwError(5, 'Invalid username or password!');
}
}
case 'createalert':
if (!$this->hasRequest('user')) {
// The 'user' argument has not been set, throw error.
$this->throwError(3, 'user');
} else if (!$this->getRequest('user')) {
// Throw error if the 'user' argument is set but empty.
$this->throwError(1, 'user');
} else if (!$this->hasRequest('cause_user')) {
// The 'cause_user' argument has not been set, throw error.
$this->throwError(3, 'cause_user');
} else if (!$this->getRequest('cause_user')) {
// Throw error if the 'cause_user' argument is set but empty.
$this->throwError(1, 'cause_user');
} else if (!$this->hasRequest('content_type')) {
// The 'content_type' argument has not been set, throw error.
$this->throwError(3, 'content_type');
} else if (!$this->getRequest('content_type')) {
// Throw error if the 'content_type' argument is set but empty.
$this->throwError(1, 'content_type');
} else if (!$this->hasRequest('content_id')) {
// The 'content_id' argument has not been set, throw error.
$this->throwError(3, 'content_id');
} else if (!$this->getRequest('content_id')) {
// Throw error if the 'content_id' argument is set but empty.
$this->throwError(1, 'content_id');
} else if (!$this->hasRequest('alert_action')) {
// The 'alert_action' argument has not been set, throw error.
$this->throwError(3, 'alert_action');
} else if (!$this->getRequest('alert_action')) {
// Throw error if the 'alert_action' argument is set but empty.
$this->throwError(1, 'alert_action');
}
$alert_user = $this->getXenAPI()->getUser($this->getRequest('user'));
if (!$alert_user->isRegistered()) {
// Requested user was not registered, throw error.
$this->throwError(4, 'user', $this->getRequest('user'));
}
$cause_user = $this->getXenAPI()->getUser($this->getRequest('cause_user'));
if (!$cause_user->isRegistered()) {
// Requested user was not registered, throw error.
$this->throwError(4, 'cause_user', $this->getRequest('cause_user'));
}
$alert_data = array(
'content_type' => $this->getRequest('content_type'),
'content_id' => $this->getRequest('content_id'),
'action' => $this->getRequest('alert_action')
);
// Create the thread object.
$alert_results = $this->xenAPI->createAlert($alert_user, $cause_user, $alert_data);
// Alert was successful, return results.
$this->sendResponse($alert_results);
case 'createconversation':
/**
* TODO
*
* EXAMPLE:
* - api.php
*/
if ($this->hasAPIKey() && !$this->hasRequest('grab_as')) {
// The 'grab_as' argument has not been set, throw error.
$this->throwError(3, 'grab_as');
} else if ($this->hasAPIKey() && !$this->getRequest('grab_as')) {
// Throw error if the 'grab_as' argument is set but empty.
$this->throwError(1, 'grab_as');
}
$conversation_data = array();
// Array of required parameters.
$required_parameters = array('recipients', 'title', 'message');
// Array of additional parameters.
$additional_parameters = array('open_invite', 'conversation_locked');
foreach ($required_parameters as $required_parameter) {
// Check if the required parameter is set and not empty.
$this->checkRequestParameter($required_parameter);
// Set the request value.
$conversation_data[$required_parameter] = $this->getRequest($required_parameter);
}
if (strpos($this->getRequest('recipients'), ',') !== FALSE) {
$recipient_array = explode(',', $this->getRequest('recipients'));
foreach ($recipient_array as $recipient) {
$user = $this->getXenAPI()->getUser($recipient);
if (!$user->isRegistered()) {
// Requested user was not registered, throw error.
$this->throwError(4, 'user', $recipient);
}
}
} else {
$user = $this->getXenAPI()->getUser($this->getRequest('recipients'));
if (!$user->isRegistered()) {
// Requested user was not registered, throw error.
$this->throwError(4, 'user', $this->getRequest('recipients'));
}
}
foreach ($additional_parameters as $additional_parameter) {
if ($this->hasRequest($additional_parameter)) {
// Set the request value.
$conversation_data[$additional_parameter] = TRUE;
}
}
// Create the conversation object.
$conversation_results = $this->xenAPI->createConversation($this->getUser(), $conversation_data);
$this->handleUserError($conversation_results, 'conversation_creation_error', 'creating a new conversation');
case 'createconversationreply':
/**
* TODO
*
* EXAMPLE:
* - api.php