-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-api-handler.php
More file actions
1625 lines (1391 loc) · 41.8 KB
/
class-api-handler.php
File metadata and controls
1625 lines (1391 loc) · 41.8 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
/* a helper class for registering custom API Handler */
require_once ( BB_WP_API_PATH . '/class-api-registration-unit.php');
/* load the default package handlers */
require_once ( BB_WP_API_PATH . '/class-api-data-package-handler.php');
/* custom custom API Handler, the are all extensions of this abstrat class */
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-abstract-post.php');
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-review.php');
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-attachment.php');
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-comment.php');
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-user.php');
require_once ( BB_WP_API_PATH . '/api-handler/class-api-handler-loginuser.php');
/**
* Abstract BB_WP_API_Handler class.
*
*
* CORE
*
* @use $this->set_request to bind a request from backbone
* call $this->read, create, update or delete to process the request
*
* the read method
* @use $this->read
* calls $this->_query_single or $this->_query_all
*
* the create, update, delete method
* @use $this->create, update, delete
* calls $this->parse_model_request to parse the incoming model from backbone
* interacts with the database
*
* after the action (read, create, update, delate) $this->parse_model_response ...
* ...is called to parse the response, ready to send to backbone
*
* @use $this->send_response to terminate the handler and send the response to wp
*
* REGISTER
*
* calls Class BB_WP_API_Registration_Unit
* supply register_data() in the child class to register all needed data
* @use this class to extend
*
* DATAPACKAGE HANDLER
*
* calls Class BB_WP_API_Handler_Data_Package
* joins registered data sets to the handler
* processing is done by to helper functions under the hood
*
* @abstract
*/
abstract class BB_WP_API_Handler {
/**
* debugger
*
*
* @var bool
* @access private
*/
private $debugger = false;
/**
* modelclasses
*
* whitelist for supported modelclasses
* post represents wp posttype
* comment represents a wp comment
* user represents a WP_User
* attachment is a wp post with an url
* idone is a special modelclass, without an id (id-one) and without a core data package, for experimental use only
*
* those cant be extended by a child class
*
* @var array
* @access private
*/
private $modelclasses = array('post', 'comment', 'user', 'attachment', 'idone');
/**
* core_data_packages
*
* the handling of those 3 datapackages in hardcoded
* distinguish modelclass and core data packages:
* the modelclass is the overall object, a modelclass contains various data packages, the core data packages are such
*
* @var array
* @access protected
*/
protected $core_data_packages = array('post', 'comment', 'user');
/**
* request
*
* The raw request, received from backbone over AJAX
* All wich was sent is in there
* Used only by the parser methods
*
* @var array
* @access protected
*/
private $request;
/**
* request_method
*
* read, create, put, delete
*
* @var string
* @access protected
*/
protected $request_method;
/**
* request_query_vars
*
* query vars sent from backbone collection fetch call
* in the same format as WP_Query args
*
* @var array
* @access protected
*/
protected $request_query_vars = array();
/**
* properties
*
* all the registered properties from the extended class
* will be populated by registration unit
* check the registration unit class for more info
*
* @var std object
* @access protected
*/
protected $properties = array();
/**
* id
*
* when there is an id sent in the request it is stored here
* this id represents the id of the "model" stored in the database
*
* @var int | string
* @access protected
*/
protected $id = 0;
/**
* parent_id
*
* some modelclasses like attachments or comments require a parent post to be registered
*
* @var int
* @access public
*/
protected $parent_id = 0;
/**
* parsed_model_request
*
* incoming model from request is stored here after being parsed for further wp processing
* used for create, update, and delete methods
*
* @var array
* @access protected
*/
protected $parsed_model_request;
/**
* query
*
* the database results for models are stored here
* used for read requests
*
* @var array
* @access protected
*/
protected $query = array();
/**
* wp_query
*
* the instance of the WP_Query
*
* @var mixed
* @access protected
*/
protected $wp_query = null;
/**
* parsed_model_response
*
* parsed model is stored here, ready for sending to backbone
*
* @var array
* @access protected
*/
public $parsed_model_response = false;
/**
* parsed_response
*
* the complete response, ready to return to backbone
*
* @var mixed
* @access protected
*/
protected $parsed_response;
/**
* current_user
*
* the current wp user
*
* @depreciated
* @var WP_User
* @access protected
*/
protected $current_user;
/**
* errors
*
* keeps all errors for the respond
*
* @var WP_Error
* @access private
*/
private $errors = NULL;
/**
* cache_time
*
* overwrite in the extended class
* default is 0 , so no caching
*
* @var int
* @access private
*/
protected $cache_time = 0;
/**
* __construct function.
*
* @access public
* @param array $request
* @return void
*/
public function __construct($request = NULL) {
/*
* register all data for the handler from the extended class
*
* this class handles all settings to be registered from the Extended Handler Class
* the registration unit will be instanceld on construct and destroyed immediatly after registration
*/
/* make an object that handles registration */
$register = new BB_WP_API_Registration_Unit(
array( 'core_data_packages' => $this->core_data_packages,
'modelclasses' => $this->modelclasses
)
);
/* call the abstract method with the registration data, and pass the registration object to it */
/* this method must exist in the child class */
$this->register_data($register);
/* get the registered data */
$this->properties = $register->get_properties();
$register = NULL; // destroy registration unit
/* set the current wp user */
$this->current_user = wp_get_current_user();
/* set an error object */
$this->errors = new WP_Error();
/*
* error checking
*/
/* a valid modelclass is rerquired */
if( ! $this->properties->modelclass )
$this->set_error( 55, 'no valid modelclass registered' );
/* request can be set as an constructor argument or via the setter */
if($request)
$this->set_request($request);
}
/* ===============
GETTER & SETTER
=============== */
/**
* set_request function.
*
* passes the request to the handler class
*
* @access public
* @final
* @param array $request (default: array())
* @return void
*/
public final function set_request($request = array()) {
/* set vars from the server request */
$this->request = $request;
/* extracts the method, but this is not really importand to do at this point, as it will be set later too */
/* $this method is also set when the corresponding action ($this-read, create, ...) is called */
if( isset($request['method']))
$this->request_method = $request['method'];
/* extract query vars */
if( isset($request['queryvars']))
$this->request_query_vars = (array) $request['queryvars']; // array is expected
/* looking for model ids in the request */
$this->id = $this->_find_in_request($this->properties->id_attribute);
$this->parent_id = $this->_find_in_request($this->properties->parent_id_attribute);
/* USER HANDLING */
/* is the user allowed to make this request */
if ( ( $this->properties->access == "loggedin" ) && ( ! is_user_logged_in() ) ) {
$this->set_error( 56, 'user must be logged in for this request' );
}
/* some extra authentication */
/* is the uer allowed to make this request */
$allowed = $this->is_authenticated($request, $this->request_method);
if(! $allowed)
$this->set_error( 56, 'user is not authenticated' );
}
/**
* set_cache function.
*
* try to get a cache object
*
* @access protected
* @param mixed $value
* @return void
*/
protected function set_cache($value) {
set_transient( $this->get_cache_id(), $value, $this->cache_time );
}
/**
* get_cache function.
*
* check strict: return === false
*
* @access private
* @return false or mixed
*/
protected function get_cache() {
// uncomment next line to flush previous cache
//delete_transient($this->get_cache_id());
return get_transient( $this->get_cache_id() );
}
/**
* get_cache_id function.
*
* make an id with the classname
*
* @access private
* @return void
*/
private function get_cache_id() {
$handlername = get_class($this);
if($this->id)
$cache_id = '_cache_' . $handlername . '_' . $this->id;
else
$cache_id = '_cache_' . $handlername . '_all';
return $cache_id;
}
/**
* set_error function.
*
* throw an error
*
* @access protected
* @param int | string $code
* @param string $message
* @return void
*/
protected function set_error( $code, $message) {
$this->errors->add($code, $message);
}
/**
* get_errors function.
*
* get all errors occured in this handler
*
* @access public
* @return array
*/
public function get_errors() {
return $this->errors->get_error_messages();
}
/**
* merge_errors function.
*
* merges a new WP_Error with the classes WP_Error
* merge is done very loosly, but it works for the purpose of the class
*
* @access public
* @param WP_Error $wp_error
* @return void
*/
public function merge_errors($wp_error) {
$new_errors = $wp_error->get_error_messages();
foreach ($new_errors as $code => $message) {
$this->errors->add($code, $message);
}
}
/* ===============
MAIN CONTROLLER
=============== */
/**
* action function.
*
* a wrapper method for create, update, read, delete
*
* @access public
* @return void
*/
public function action() {
if( ! $this->request_method )
return false;
switch ($this->request_method) {
case 'read':
$this->read();
break;
case 'create':
$this->create();
break;
case 'update':
$this->update();
break;
case 'delete':
$this->delete();
break;
}
}
/**
* read function.
*
* prepares the wp response for a backbone read request
*
* must call parse_model_response to parse the result
*
* @access public
* @return void
*/
public function read( $id = null ){
/* set method */
$this->request_method = 'read';
/* read the data from backbone */
$this->parse_model_request();
if($this->get_errors())
return;
/* set id */
if($id)
$this->id = $id;
/* when caching is enabled, try to get the cache */
if($this->cache_time && false !== $this->get_cache()) {
$query = $this->get_cache();
$this->query = $query;
/* call the database query */
} else {
if($this->id)
$query = $this->_query_single();
else
$query = $this->_query_all();
}
/* format the retrieved models */
$this->parse_model_response($query);
do_action('bb-wp-api_after_read', $this->id, $this->properties, $this );
}
/**
* create function.
*
* processes the wp response for a backbone create request
* saves the model to database after error checking
* id of the new object will be returned
*
* must call parse_model_response to parse the result
*
* @access public
* @return void
*/
public function create() {
/* set method */
$this->request_method = 'create';
/* check for a model id */
if( $this->id) {
$this->set_error( 4, 'A model id is set in the request, cant create a new item on server' );
return;
}
/* read the data from backbone */
$this->parse_model_request();
if($this->get_errors())
return;
/* get the parsed post data from request */
$item_data = $this->parsed_model_request;
/* privileg checking @TODO outsource to filter */
if( $this->properties->access == "loggedin" && ! current_user_can('edit_posts')) { // TODO improve CPT
$this->set_error( 9, 'no user privileges to save the item on server' );
return;
}
/* insert database */
switch( $this->properties->modelclass ) {
/* posts */
case('post'):
$post = $item_data['post'];
$result = wp_insert_post( $post );
/* was there an error saving the post */
if( ! $result) {
$this->set_error( 6, 'saving the item failed on the server' );
return;
}
/* got the id of the created post */
$new_id = $result;
break;
case('attachment'):
//@TODO
$attachment = $item_data['post'];
/* a post parent for a attachment must be set */
if( ! $this->parent_id ) {
$this->set_error( 7, 'the attachment has no parent id' );
return;
}
/* upload the file ($_FILE) and attach it to the parent post */
$result = media_handle_upload('async-upload', $this->parent_id, $attachment);
if ( is_wp_error( $result )) {
$this->set_error( 8, 'saving the attachment failed on the server' );
return;
}
$new_id = $result;
break;
/* comment */
case('comment'):
$comment = $item_data['comment'];
/* a post parent for a comment must be set */
if( ! $this->parent_id ) {
$this->set_error( 7, 'the comment has no parent id' );
return;
}
/* in some odd cases it maybe that the parent id is not yet present in the comment array */
$comment['comment_post_ID'] = $this->parent_id;
$result = wp_insert_comment($comment);
/* was there an error saving the comment */
if( ! $result) {
$this->set_error( 8, 'saving the comment failed on the server' );
return;
}
/* got the id of the created comment */
$new_id = $result;
break;
case('user'):
//@TODO
break;
case('idone'):
$new_id = $this->id; // interacting with the databse is outsourced to the data package handlers
break;
}
/* save custom data, this only method does all the magic, details must be specified in the custom package handlers */
$this->_action_custom_package_data( $new_id, $item_data);
/* set a clean response */
$this->parse_model_response($new_id);
do_action('bb-wp-api_after_create', $new_id, $this->properties, $this );
}
/**
* update function.
*
* processes the wp response for a backbone update request
* updates an existing wp object
*
* @access public
* @return void
*/
public function update(){
/* set method */
$this->request_method = 'update';
/* check for a model id */
if( ! $this->id) {
$this->set_error( 10, 'No model id in request, cant update' );
return;
}
/* read the data received from backbone */
$this->parse_model_request();
if($this->get_errors())
return;
/* get the parsed post data from request */
$item_data = $this->parsed_model_request;
/* insert database */
switch( $this->properties->modelclass ) {
/* posts */
case('post'):
case('attachment'):
$post = $item_data['post'];
/* privileg check */ //improve this for coded api calls, like when setting up bootstrap data (for reading it is no problem any way, because this check is only made for update and create and delete)
if( $this->properties->access == "loggedin" && ! current_user_can('edit_post', $this->id)) {
$this->set_error( 11, 'no user privileges to update the item on server' );
return;
}
$result = wp_update_post( $post );
/* maybe an error while updating */
if( ! $result) {
$this->set_error( 12, 'updating the item failed on the server' );
return;
}
/* geting the id means update was a success */
$updated_id = $result;
/* save custom data, this only method does all the magic,
details must be specified in the custom package handlers */
$this->_action_custom_package_data( $updated_id, $item_data);
/* set a clean response */
$this->parse_model_response($updated_id);
break;
/* comment */
case('comment'):
$comment = $item_data['comment'];
/* comment updateding is not supported */
$this->set_error( 13, 'comments cant be updated!' );
return;
break;
case('user'):
//@TODO
break;
case('idone'):
$new_id = $this->id;
$this->_action_custom_package_data( $new_id, $item_data);
$this->parse_model_response($new_id);
break;
}
do_action('bb-wp-api_after_update', $updated_id, $this->properties, $this );
}
/**
* delete function.
*
* processes the wp response for a backbone delete request
* deletes an existing wp object
*
* @access public
* @return void
*/
public function delete(){
/* set method */
$this->request_method = 'delete';
/* check for id */
if( ! $this->id) {
$this->set_error( 14, 'No model id in request, cant delete' );
return;
}
/* parse the data from backbone */
$this->parse_model_request();
if($this->get_errors())
return;
/* access the parsed post data from request */
$item_data = $this->parsed_model_request;
/* delete from database */
switch( $this->properties->modelclass ) {
/* posts */
case('post'):
case('attachment'):
$post = $item_data['post'];
/* privileg check */
if( $this->properties->access == "loggedin" && ! current_user_can('delete_post', $this->id)) {
$this->set_error( 15, 'no user privileges to delete the item on server' );
return;
}
$result = wp_delete_post($this->id);
/* error checking while delete */
if( ! $result) {
$this->set_error( 16, 'deleting the item failed on the server' );
return;
}
/* success, the id of the deleted post was returned */
$deleted_id = $result->ID;
/* setup a clean response */
$this->parse_model_response($deleted_id);
break;
/* comment */
case('comment'):
$comment = $item_data['comment'];
/* @TODO better permission handling */
$comment_in_db = get_comment( $this->id );
$comment_author = $comment_in_db->user_id;
if ( $this->properties->access == "loggedin" && $comment_author != $this->current_user->ID ) {
$this->set_error( 17, 'This comment can only be deleted by the comment author :' . $comment_author );
return;
}
$result = wp_delete_comment($this->id);
/* true is returned on success delete */
if( ! $result) {
$this->set_error( 17, 'deleting the comment failed on the server' );
return;
}
/* setup a clean response */
$this->parse_model_response($result);
break;
case('user'):
//@TODO
break;
case('idone'):
$new_id = $this->id;
$this->_action_custom_package_data( $new_id, $item_data);
$this->parse_model_response($new_id);
break;
}
do_action('bb-wp-api_after_upd', $updated_id, $this->properties, $this );
}
/**
* get_response function.
*
* get the full response that will be sent to the server
*
* @access public
* @return void
*/
public function get_response($options = array('json' => false) ) {
/* collect the response in an array ... */
$return = array();
/* access the prepared model response by the main controllers ($this->read, $this->create, ...) */
$return = $this->parsed_model_response;
/* add errors to the response if we have any */
if($this->get_errors())
$return = $this->get_errors();
/* when debug is on send the whole instance */
if($this->debugger) {
echo (print_r($this));
die();
}
/* allow a filter to change or add stuff to the response */
$return = $this->filter_response($return);
/* get through the output options */
if($options['json'])
return json_encode($return);
else
return $return;
}
/**
* send_response function.
*
* finally sends back the respone to wp and terminates the class
*
* @access public
* @return void
*/
public function send_response() {
$return = $this->get_response();
/* send it and terminate this instance */
if($this->get_errors()) {
wp_send_json_error($return);
} else {
if( null === $this->wp_query ) {
wp_send_json_success($return);
} else {
$data = array(
'success' => true,
'data' => $return,
'query' => $this->parse_wp_query_object_2_js( $this->wp_query )
);
wp_send_json($data); // build a custom wp_send_json_success with an extra property
}
}
}
/* ===============
FILTER
=============== */
/**
* filter_pre_parse_model_request function.
*
* filter the model request before being parsed
* can be used to set default values that may be overwritten during parsing
*
* @access protected
* @param array $parsed
* @param string $modelmethod
* @return array
*/
protected function filter_pre_parse_model_request( $parsed, $modelmethod ) {
return $parsed;
}
/**
* filter_post_parse_model_request function.
*
* filter the model request after being parsed
* can be used to override values
*
* @access protected
* @param array $parsed
* @param string $modelmethod
* @return array
*/
protected function filter_post_parse_model_request( $parsed, $modelmethod ) {
return $parsed;
}
/**
* filter_query_args function.
*
* use this filter to override queryvars sent from backbone
*
* @access protected
* @param array $queryargs
* @return array
*/
protected function filter_query_args($queryargs) {
return $queryargs;
}
/**
* filter_found_item function.
*
* use this filter for escaping the output
*
* @access protected
* @param mixed $object
* @return void
*/
protected function filter_found_item($object) {
return $object;
}
/**
* filter_response function.
*
* add something to the response right before it is sent back to backbone
*
* @access protected
* @param array $return
* @return array
*/
protected function filter_response($return) {
return $return;
}
/* ===============
PARSER
=============== */
/**
* parse_model_request function.
*
* prepare the incomin backbone model request for further processing
* for create, update, delete requests
* sets
*
* @access protected
* @final
* @return void
*/
protected final function parse_model_request() {
/* get the model from the request */
$modeldata = (is_array($this->request['model'])) ? $this->request['model'] : array();
/*
* looks something like this now:
* $modeldata = array(
* 'title' => 'my title',
* 'content' => 'some content',
* 'any backbone key' => 'any backbone value'
* );
*/
/* the formatting of the parsed output */
$parsed = array();
/* get all data packages, also the core packages and parse them */
$data_packages = array_merge($this->core_data_packages, $this->properties->custom_data_packages );
foreach ($data_packages as $data_package) {
$parsed[$data_package] = array();
}
/*
* looks something like this now:
* $parsed = array(
* 'post' => array(),
* 'postmeta' => array(),
* 'comment' => array(),
* 'any registered data package' => array()
* );
*/
/* get default values if some are set in the extended handler class */
$parsed = $this->filter_pre_parse_model_request($parsed, $this->request_method);
/* start parsing */
foreach ($modeldata as $id_backbone => $value) {
/* check if the data package field is registered */
/* only data_package_fields registered in backbone pass this gate */
if ( ! array_key_exists($id_backbone, $this->properties->data_package_fields) )
continue;