forked from backdrop-contrib/services
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservices.module
1298 lines (1188 loc) · 38.9 KB
/
services.module
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
/**
* @file
* Provides a generic but powerful API for web services.
*/
/**
* Minimum CTools version needed.
*/
define('SERVICES_REQUIRED_CTOOLS_API', '1.7');
define('SERVICES_ALLOWED_EXTENSIONS', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp');
/*
* Function to return list of batch options
*/
function services_security_get_update_options() {
return array(
'services_security_update_reset_users_since_date',
'services_security_update_reset_users_with_password_one',
'services_security_update_do_nothing',
);
}
/*
* Function to setup batch processing.
*/
function services_security_setup_batch($op, $drush = FALSE) {
switch ($op) {
case 'services_security_update_reset_users_since_date':
services_security_update_reset_users_since_date();
services_security_user_update_finish();
break;
case 'services_security_update_reset_users_with_password_one':
batch_set(services_security_update_reset_users_with_password_one());
if ($drush) {
$batch =& batch_get();
//Because we are doing this on the back-end, we set progressive to false.
$batch['progressive'] = FALSE;
//Start processing the batch operations.
drush_backend_batch_process();
}
break;
case 'services_security_update_do_nothing':
services_security_user_update_finish();
break;
}
}
function services_security_update_reset_users_since_date() {
// Update all users created since August 30th, 2013
$result = db_update('users')
->fields(array(
'pass' => "ZZZservices_security",
))
->condition('created', 1377892483, '>=')
->execute();
backdrop_set_message($result . ' users were updated');
}
function services_security_user_update_finished($success, $results, $operations) {
if ($success) {
backdrop_set_message(t('@count users passwords were reset.', array('@count' => count($results))));
services_security_user_update_finish();
}
else {
$error_operation = reset($operations);
backdrop_set_message(
t('An error occurred while processing @operation with arguments : @args',
array(
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
)
)
);
}
}
/**
* Executes final tasks at the end of the security update follow up.
*/
function services_security_user_update_finish() {
backdrop_set_message('Services security update follow up is complete.');
config_set('services.settings', 'services_security_update_1', TRUE);
if (!backdrop_is_cli()) {
backdrop_goto('admin/reports/status');
}
}
function services_security_update_reset_users_with_password_one() {
$users = array();
// Query the database to get all user ID
$query = db_select('users', 'u')
->fields('u', array('uid'));
$users = $query->execute()->fetchAll();
$num_of_users = count($users);
$progress = 0; // where to start
$limit = config_get('services.settings', 'services_security_reset_limit_per_batch'); // how many to process for each run
$max = $num_of_users; // how many records to process until stop
//Set up our batch operations
while ($progress < $max) {
$operations[] = array('services_security_update_reset_users_with_password_one_op', array($progress, $limit, $max));
$progress = $progress + $limit;
}
// build the batch instructions
$batch = array(
'operations' => $operations,
'finished' => 'services_security_user_update_finished',
'file' => backdrop_get_path('module', 'services') . '/services.admin.inc',
'progress_message' => t('Processed batch #@current out of @total.'),
);
return $batch;
}
function services_security_update_reset_users_with_password_one_op($progress, $limit, $max, &$context) {
//Set default starting values
if (empty($context['sandbox'])) {
$context['sandbox'] = array();
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_user'] = 0;
$context['sandbox']['max'] = $limit;
}
// Required for user_check_password.
require_once BACKDROP_ROOT . '/' . config_get('services.settings', 'password_inc');
//Set the password we are looking for.
$password = "1";
//Fetch all users in our current range.
$result = db_select('users', 'u')
->fields('u', array('uid', 'pass',))
->orderBy('u.uid', 'ASC')
->range($progress, $limit)
->execute()
->fetchAll();
// Loop through our ranged results and check their password.
foreach ($result as $row) {
$uid = $row->uid;
$pass = $row->pass;
//Setup account object, much faster than user_load
$account = new stdClass();
$account->uid = $uid;
$account->pass = $pass;
// Check the current user's password against the password.
if (user_check_password($password, $account)) {
// This means we have a matched password.
// Process the user
$updated_user = db_update('users')
->fields(array(
'pass' => "ZZZservices_security",
))
->condition('uid', $uid)
->execute();
$context['results'][] = 'Updating user uid: '. $uid;
}
// Update our progress information.
$context['sandbox']['progress']++;
$context['sandbox']['current_user'] = $uid;
// update progress for message
$shown_progress = $progress + $limit;
// update message during each run so you know where you are in the process
$context['message'] = 'Checking user uid: '. $uid;
}
// Inform the batch engine that we are not finished,
// and provide an estimation of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = (($context['sandbox']['max'] - $context['sandbox']['progress']) <= $limit) || ($context['sandbox']['progress'] >= $context['sandbox']['max']);
}
}
/**
* Implements hook_perm().
*/
function services_permission() {
return array(
'administer services' => array(
'title' => t('Administer services'),
'description' => t('Configure and setup services module.'),
),
// File resource permissions
'get any binary files' => array(
'title' => t('Get any binary files'),
'description' => t(''),
),
'get own binary files' => array(
'title' => t('Get own binary files'),
'description' => t(''),
),
'save file information' => array(
'title' => t('Save file information'),
'description' => t(''),
),
// System resource permissions
'get a system variable' => array(
'title' => t('Get a system variable'),
'description' => t(''),
),
'set a system variable' => array(
'title' => t('Set a system variable'),
'description' => t(''),
),
// Query-limiting permissions
'perform unlimited index queries' => array(
'title' => t('Perform unlimited index queries'),
'description' => t('This permission will allow user to perform index queries with unlimited number of results.'),
),
);
}
/**
* Implements hook_hook_info().
*/
function services_hook_info() {
$hooks['services_resources'] = array(
'group' => 'services',
);
return $hooks;
}
/**
* Implements hook_menu().
*/
function services_menu() {
$items = array();
$endpoints = services_endpoint_load_all();
foreach ($endpoints as $endpoint) {
if (!empty($endpoint->status)) {
$items[$endpoint->path] = array(
'title' => 'Services endpoint',
'access callback' => 'services_access_menu',
'page callback' => 'services_endpoint_callback',
'page arguments' => array($endpoint->name),
'type' => MENU_CALLBACK,
);
}
}
$base = array(
'access callback' => 'user_access',
'access arguments' => array('administer services'),
'file' => 'services.admin.inc',
);
$items['admin/structure/services'] = array(
'title' => 'Services',
'description' => 'Manage customized lists of content.',
'page callback' => 'services_list_page',
'type' => MENU_NORMAL_ITEM,
) + $base;
$items['admin/structure/services/list'] = array(
'title' => 'List endpoints',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -1,
);
$items['admin/structure/services/add'] = array(
'title' => 'Add endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_endpoint_edit_form', NULL),
'type' => MENU_LOCAL_ACTION,
) + $base;
// Additional pages for acting on an endpoint.
$items['admin/structure/services/list/%services_endpoint'] = array(
'title' => 'Edit endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_endpoint_edit_form', 4),
'type' => MENU_NORMAL_ITEM,
'weight' => -10,
) + $base;
// Additional pages for acting on an endpoint.
$items['admin/structure/services/list/%services_endpoint/edit'] = array(
'title' => 'Edit endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_endpoint_edit_form', 4),
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
) + $base;
$items['admin/structure/services/list/%services_endpoint/clone'] = array(
'title' => 'Clone endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_endpoint_clone_form', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/delete'] = array(
'title' => 'Delete endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_endpoint_delete_form', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/enable'] = array(
'title' => 'Enable endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_toggle_enable_page', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/disable'] = array(
'title' => 'Disable endpoint',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_toggle_enable_page', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/resources'] = array(
'title' => 'Resources',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_edit_form_endpoint_resources', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/server'] = array(
'title' => 'Resources',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_edit_form_endpoint_server', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['admin/structure/services/list/%services_endpoint/authentication'] = array(
'title' => 'Resources',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_edit_form_endpoint_authentication', 4),
'type' => MENU_VISIBLE_IN_BREADCRUMB,
) + $base;
$items['services/session/token'] = array(
'page callback' => '_services_session_token',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['admin/config/services/services-security'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => 'Services Security update',
'description' => 'Services module security updates',
'page callback' => 'backdrop_get_form',
'page arguments' => array('services_security_admin_form'),
'access arguments' => array('administer site configuration'),
'file' => 'services.admin.inc',
);
return $items;
}
/**
* Access callback that always returns TRUE.
*
* This callback is necessary for services like login and logout that should
* always be wide open and accessible.
*
* *** USE THIS WITH GREAT CAUTION ***
*
* If you think you need it you are almost certainly wrong.
*/
function services_access_menu() {
return TRUE;
}
/**
* Implements hook_theme().
*/
function services_theme() {
return array(
'services_endpoint_index' => array(
'template' => 'services_endpoint_index',
'arguments' => array('endpoints' => NULL),
),
'services_resource_table' => array(
'render element' => 'table',
'file' => 'services.admin.inc',
),
);
}
/**
* Returns information about the installed server modules on the system.
*
* @return array
* An associative array keyed after module name containing information about
* the installed server implementations.
*/
function services_get_servers($reset = FALSE) {
$servers = &backdrop_static(__FUNCTION__);
if (!$servers || $reset) {
$servers = array();
foreach (module_implements('server_info') as $module) {
if ($module != 'sqlsrv') {
$servers[$module] = call_user_func($module . '_server_info');
}
}
}
return $servers;
}
/**
* Menu system page callback for server endpoints.
*
* @param string $endpoint
* The endpoint name.
* @return void
*/
function services_endpoint_callback($endpoint_name) {
module_load_include('inc', 'services', 'includes/services.runtime');
// Explicitly set the title to avoid expensive menu calls in token
// and elsewhere.
if (!($title = backdrop_set_title())) {
backdrop_set_title('Services endpoint');
}
$endpoint = services_endpoint_load($endpoint_name);
$server = $endpoint->server;
if (function_exists($server . '_server')) {
// call the server
services_set_server_info_from_array(array(
'module' => $server,
'endpoint' => $endpoint_name,
'endpoint_path' => $endpoint->path,
'debug' => $endpoint->debug,
'settings' => $endpoint->server_settings,
));
if ($endpoint->debug) {
watchdog('services', 'Calling server: %server', array('%server' => $server . '_server'), WATCHDOG_DEBUG);
watchdog('services', 'Server info main object: <pre>@info</pre>', array('@info' => print_r(services_server_info_object(), TRUE)), WATCHDOG_DEBUG);
}
print call_user_func($server . '_server');
// Do not let this output
backdrop_page_footer();
exit();
}
// return 404 if the server doesn't exist
backdrop_not_found();
}
/**
* Create a new endpoint with defaults appropriately set from schema.
*
* @return stdClass
* An endpoint initialized with the default values.
*/
function services_endpoint_new() {
$schema = backdrop_get_schema('services_endpoint');
$object = new stdClass;
foreach ($schema['fields'] as $field => $info) {
if (isset($info['object default'])) {
$object->$field = $info['object default'];
}
else if (isset($info['default'])) {
$object->$field = $info['default'];
}
else {
$object->$field = NULL;
}
}
return $object;
}
/**
* Load a single endpoint.
*
* @param string $name
* The name of the endpoint.
* @return stdClass
* The endpoint configuration.
*/
function services_endpoint_load($name) {
$result = services_endpoint_load_all($name);
if (isset($result[$name])) {
return $result[$name];
}
return FALSE;
}
/**
* Load all endpoints.
*
* @return array
* Array of endpoint objects keyed by endpoint names.
*/
function services_endpoint_load_all() {
return services_load_endpoint_object();
}
/**
* Saves an endpoint in the database.
*
* @return void
*/
function services_endpoint_save($endpoint) {
// Set a default of an array if the value is not present.
foreach (array('server_settings', 'resources', 'authentication') as $endpoint_field) {
if (empty($endpoint->{$endpoint_field})) {
$endpoint->{$endpoint_field} = array();
}
}
if (!empty($endpoint->is_new)) {
// New record.
$update = array();
}
else {
// Existing record.
$update = array('name');
}
backdrop_write_record('services_endpoint', $endpoint, $update);
backdrop_static_reset('services_load_endpoint_object');
menu_rebuild();
cache_clear_all('services:' . $endpoint->name . ':', 'cache', TRUE);
}
/**
* Remove an endpoint.
*
* @return void
*/
function services_endpoint_delete($endpoint) {
db_delete('services_endpoint')
->condition('name', $endpoint->name)
->execute();
backdrop_static_reset('services_load_endpoint_object');
menu_rebuild();
cache_clear_all('services:' . $endpoint->name . ':', 'cache', TRUE);
}
/**
* Gets all resource definitions.
*
* @param string $endpoint_name
* Optional. The endpoint endpoint that's being used.
* @return array
* An array containing all resources.
*/
function services_get_resources($endpoint_name = '') {
$cache_key = 'services:' . $endpoint_name . ':resources';
$resources = array();
if (($cache = cache_get($cache_key)) && isset($cache->data)) {
$resources = $cache->data;
}
else {
module_load_include('inc', 'services', 'includes/services.resource_build');
$resources = _services_build_resources($endpoint_name);
cache_set($cache_key, $resources);
}
return $resources;
}
/**
* Load the resources of the endpoint.
*
* @return array
*/
function services_get_resources_apply_settings($endpoint_name) {
$resources = services_get_resources($endpoint_name);
module_load_include('inc', 'services', 'includes/services.resource_build');
$endpoint = services_endpoint_load($endpoint_name);
_services_apply_endpoint($resources, $endpoint, TRUE);
return $resources;
}
/**
* Returns information about resource API version information.
* The resource API is the way modules expose resources to services,
* not the API that is exposed to the consumers of your services.
*
* @return array
* API version information. 'default_version' is the version that's assumed
* if the module doesn't declare an API version. 'versions' is an array
* containing the known API versions. 'current_version' is the current
* version number.
*/
function services_resource_api_version_info() {
$info = array(
'default_version' => 3001,
'versions' => array(3002),
);
$info['current_version'] = max($info['versions']);
return $info;
}
/**
* Implements hook_services_resources().
*/
function services_services_resources() {
module_load_include('inc', 'services', 'includes/services.resource_build');
// Return resources representing legacy services
return _services_core_resources();
}
/**
* Implementation of hook_services_authentication_info().
*/
function services_services_authentication_info() {
return array(
'title' => t('Session authentication'),
'description' => t("Uses Backdrop's built in sessions to authenticate."),
'authenticate_call' => '_services_sessions_authenticate_call',
);
}
/**
* Authenticates a call using Backdrop's built in sessions
*
* @return string
* Error message in case error occured.
*/
function _services_sessions_authenticate_call($module, $controller) {
global $user;
$original_user = services_get_server_info('original_user');
if ($original_user->uid == 0) {
return;
}
if ($controller['callback'] != '_user_resource_get_token') {
$non_safe_method_called = !in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
$csrf_token = NULL;
if (isset($_SERVER['HTTP_X_CSRF_TOKEN'])) {
$csrf_token = $_SERVER['HTTP_X_CSRF_TOKEN'];
}
elseif (isset($_REQUEST['services_token'])) {
$csrf_token = $_REQUEST['services_token'];
}
if ($non_safe_method_called && !backdrop_valid_token($csrf_token, 'services')) {
return t('CSRF validation failed');
}
}
if ($user->uid != $original_user->uid) {
$user = $original_user;
}
}
/**
* Get operation class information.
*
* @return array An array with operation class information keyed by operation machine name.
*/
function services_operation_class_info() {
return array(
'operations' => array(
'title' => t('CRUD operations'),
'name' => t('CRUD operation'),
'class_singular' => 'operation',
),
'actions' => array(
'title' => t('Actions'),
'name' => t('action'),
'class_singular' => 'action',
),
'relationships' => array(
'title' => t('Relationships'),
'name' => t('relationship'),
'class_singular' => 'relationship',
),
'targeted_actions' => array(
'title' => t('Targeted actions'),
'name' => t('targeted action'),
'class_singular' => 'targeted_action',
),
);
}
/**
* Returns all the controller names for a endpoint.
*
* @param string $endpoint
* The endpoint that should be used.
* @return array
* An array containing all controller names.
*/
function services_controllers_list($endpoint) {
$controllers = array();
$class_info = services_operation_class_info();
$resources = services_get_resources($endpoint);
foreach ($resources as $resource_name => $resource) {
foreach ($class_info as $class_name => $class) {
if (empty($resource[$class_name])) {
continue;
}
foreach ($resource[$class_name] as $op_name => $op) {
$method = "{$resource_name}.{$op_name}";
if (empty($controllers[$method])) {
$controllers[$method] = $method;
}
else {
watchdog('services', 'Naming collision when listing controllers as methods. The %class %operation is not included in the listing.', array(
'%class' => $class['name'],
'%operation' => $op_name,
), WATCHDOG_WARNING);
}
}
}
}
return $controllers;
}
/**
* Returns the requested controller.
*
* @param string $name
* The name of the controller in the format: {resource}.{name} or
* {resource}.{operation}. Examples: "node.retrieve", "system.getVariable".
* @param string $endpoint
* The endpoint that should be used.
*/
function services_controller_get($name, $endpoint) {
list($resource_name, $method) = explode('.', $name);
$resources = services_get_resources($endpoint);
if (isset($resources[$resource_name])) {
$res = $resources[$resource_name];
if (isset($res[$method])) {
return $res[$method];
}
else {
$class_info = services_operation_class_info();
// Handle extended operations
foreach ($class_info as $class => $info) {
if (isset($res[$class]) && isset($res[$class][$method])) {
return $res[$class][$method];
}
}
}
}
}
/**
* Returns an array of available updates versions for a resource.
*
* @return
* If services has updates, an array of available updates sorted by version.
* Otherwise, array().
*/
function services_get_updates() {
$updates = &backdrop_static(__FUNCTION__, array());
if (!isset($updates) || empty($updates)) {
$updates = array();
module_load_include('inc', 'services', 'includes/services.resource_build');
// Load the resources for services.
_services_core_resources();
// Prepare regular expression to match all possible defined
// _resource_resource_method_update_N_N().
$regexp = '/_(?P<resource>.+)_resource_(?P<method>.+)_update_(?P<major>\d+)_(?P<minor>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// _resource_resource_method_update_N_N() functions end this way, and there
// are other possible functions which match '_update_'. We use preg_grep()
// here, instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time.
// Luckily this only happens when the cache is cleared for an endpoint and
// resources are re-generated.
$functions = preg_grep('/_\d+$/', $functions['user']);
// Sort functions in alphabetical order, so functions with a larger version
// number will be used when needed.
asort($functions);
foreach ($functions as $function) {
// If this function is a service update function, add it to the list of
// services updates.
if (preg_match($regexp, $function, $matches)) {
$resource = $matches['resource'];
$method = $matches['method'];
$major = $matches['major'];
$minor = $matches['minor'];
$updates[$resource][$method][] = array(
'version' => $major .'_'. $minor,
'major' => $major,
'minor' => $minor,
'callback' => $function,
'resource' => $resource,
'method' => $method,
);
}
}
}
return $updates;
}
/**
* Determine if any potential versions exist as valid headers.
* returns false if no version is present in the header for the specific call.
*/
function _services_version_header_options() {
$available_headers = array();
$updates = services_get_updates();
if(is_array($updates)) {
foreach ($updates as $resource => $update) {
foreach ($update as $method_name => $method) {
$available_headers[] = 'services_'. $resource .'_'.$method_name .'_version';
}
}
}
$headers = _services_parse_request_headers();
foreach($available_headers as $key => $version_header_option) {
$header_key = _services_fix_header_key($version_header_option);
$headers = _services_parse_request_headers();
if(array_key_exists($header_key, $headers)) {
$version = $headers[$header_key];
}
}
return isset($version) ? $version : FALSE;
}
/**
* Returns all request headers.
* @return
* And array with all request headers
*/
function _services_parse_request_headers() {
$headers = array();
foreach($_SERVER as $key => $value) {
$length = 5;
if (substr($key, 0, $length) <> 'HTTP_') {
continue;
}
$header = _services_fix_header_key($key, $length);
$headers[$header] = $value;
}
return $headers;
}
/**
* Fixes request headers to match what PHP gives us.
* @return
* a string with the correct syntax for a header value.
*/
function _services_fix_header_key($key, $length = 0) {
return str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, $length)))));
}
/**
* Returns currently set api version for an endpoint resource method.
*
* @param $endpoint
* A fully loadded endpoint.
* @param $resource
* A resource name.
* @param $method
* A method name.
* @return
* an array with the major and minor api versions
*/
function services_get_resource_api_version($endpoint, $resource, $method) {
if (isset($endpoint->resources[$resource]) ) {
$class_info = services_operation_class_info();
foreach ($class_info as $class_name => $class) {
if (!empty($endpoint->resources[$resource][$class_name])) {
if (isset($endpoint->resources[$resource][$class_name][$method]['settings']['services']['resource_api_version'])) {
if($version = _services_version_header_options()) {
$split = explode('.', $version);
}
else {
$split = explode('.', $endpoint->resources[$resource][$class_name][$method]['settings']['services']['resource_api_version']);
}
return array(
'major' => $split[0],
'minor' => $split[1],
);
}
}
}
}
}
/**
* Apply versions to the controller.
*
* @param $controller
* A controller array.
* @param $options
* A options array filled with verison information.
* @return
* An array with the major and minor api versions
*/
function services_request_apply_version(&$controller, $options = array()) {
if (isset($options)) {
extract($options);
}
if (isset($version) && $version == '1.0') {
//do nothing
return;
}
$updates = services_get_updates();
if (isset($method) && isset($updates[$resource][$method])) {
foreach ($updates[$resource][$method] as $update) {
if (!isset($version)) {
$endpoint = services_get_server_info('endpoint', '');
$endpoint = services_endpoint_load($endpoint);
$default_version = services_get_resource_api_version($endpoint, $resource, $method);
}
else {
$default_version = explode('.', $version);
$default_version['major'] = $default_version[0];
$default_version['minor'] = $default_version[1];
}
// Apply updates until we hit our default update for the site.
if ($update['major'] <= $default_version['major'] && $update['minor'] <= $default_version['minor']) {
$update_data = call_user_func($update['callback']);
$controller = array_merge($controller, $update_data);
}
}
}
}
/**
* Convert a resource to RPC-style methods.
*
* @param array $resource
* A resource definition.
* @param string $resource_name
* The resource name, ie: node.
*
* @return array
* An array of RPC method definitions
*/
function services_resources_as_procedures($resource, $resource_name) {
$methods = array();
$class_info = services_operation_class_info();
foreach ($class_info as $class_name => $class) {
if (empty($resource[$class_name])) {
continue;
}
foreach ($resource[$class_name] as $op_name => $op) {
$method_name = "{$resource_name}.{$op_name}";
if (empty($methods[$method_name])) {
$methods[$method_name] = array(
'method' => $method_name,
) + $op;
}
else {
watchdog('services', 'Naming collision when listing controllers as methods. The %class %operation wont be available for RPC-style servers.', array(
'%class' => $class['name'],
'%operation' => $op_name,
), WATCHDOG_WARNING);
}
}
}
return $methods;
}
/**
* Helper function to build index queries.
*
* @param $query
* Object database query object.
* @param $page
* Integer page number we are requesting.
* @param $fields
* Array fields to return.
* @param $parameter
* Array parameters to add to the index query.
* @param $page_size
* Integer number of items to be returned.
* @param $resource
* String name of the resource building the index query
* @param $options
* Additional query options.
*/
function services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, $resource, $options = array()) {
$default_limit = config_get('services.settings', "services_{$resource}_index_page_size");
if (!user_access('perform unlimited index queries') && $page_size > $default_limit) {
$page_size = $default_limit;
}
$query->range($page * $page_size, $page_size);
if ($fields == '*') {
$query->fields('t');
}
else {
$query->fields('t', explode(',', $fields));
}
if (isset($parameters) && is_array($parameters)) {
foreach ($parameters as $parameter => $parameter_value) {
$op = 'IN';
if (isset($options['parameters_op']) && isset($options['parameters_op'][$parameter])) {
if (_services_is_valid_query_op($options['parameters_op'][$parameter])) {
$op = strtoupper($options['parameters_op'][$parameter]);
}
}
$query->condition($parameter, services_str_getcsv($parameter_value), $op);
}
}
if (isset($options['orderby'])) {
foreach($options['orderby'] as $column => $sort) {
$query->orderBy(db_escape_field($column), $sort);