This repository was archived by the owner on Aug 3, 2024. It is now read-only.
forked from RESTful-Drupal/restful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestful.module
697 lines (622 loc) · 21.5 KB
/
restful.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
<?php
/**
* @file
* Turn Drupal to a RESTful server, following best practices.
*/
/**
* Implements hook_ctools_plugin_directory().
*/
function restful_ctools_plugin_directory($module, $plugin) {
if ($module == 'restful') {
return 'plugins/' . $plugin;
}
}
/**
* Add defaults values to the restful related plugins.
*
* Properties for the "restful" plugin type:
* - description: The description of the resource. Defaults to empty string.
* - major_version: The major version of the resource. This will change the URL
* of the resource endpoint. For example setting major version to 2 for the
* "articles" resource will result with "api/v2/articles" as the URL. Defaults
* to 1.
* - minor_version: The minor version of the resource. Setting the minor version
* via CURL is done by setting HTTP_X_RESTFUL_MINOR_VERSION in the HTTP headers.
* Defaults to 0.
* - options: Array of options needed for the plugin. See
* "per_role_content__1_0.inc" in RESTful example module. Defaults to empty
* array.
* - entity type: The entity type of the resource. Defaults to FALSE, which
* indicates the resource isn't connected to any entity type.
* - bundle: The name of a single bundle the resource is connected to. Defaults
* to FALSE.
* - authentication_types: TRUE or Array with name of authentication providers
* that should "protect" the resource, and ensure only authenticated users can
* use it. If set to TRUE, then all the existing authentication providers
* would be used until the user is authenticated. If user was not
* authenticated with any of the authentication providers, an
* \RestfulUnauthorizedException exception would be thrown.
* Defaults to empty array, which means no authentication is done by default.
* - authentication_optional: If "authentication_types" and TRUE this determines
* if the resource may be accessed by an anonymous user when no provider was
* able to authenticate the user. Otherwise a \RestfulUnauthorizedException
* exception would be thrown.
* - hook_menu: Determines if RESTful module should declare the resource in its
* pwn hook_menu(). If FALSE, it is up to the implementing module to declare
* it. Defaults to TRUE.
* - cache: Stores the cache settings. An associative array with:
* - render: Set it to FALSE to disable the render cache completely
* Defaults to FALSE.
* - class: The cache class for this resource. Defaults to NULL, which
* will probably end up resolving to 'DrupalDatabaseCache'.
* - bin: The name of the bin. It is the developer's responsibility to
* create this bin in the cache backend if it does not exist. Defaults to
* 'cache_restful'.
* - expire: TTL for the cache records. See DrupalCacheInterface::set()
* for the allowed values. Defaults to CACHE_PERMANENT.
* - simple_invalidate: Set it to false to prevent the RESTful module to
* invalidate any cache it may have been generated. The developer will be
* responsible to invalidate caches in this scenario. Defaults to TRUE.
* - rate_limit: The configuration array for the rate limits.
* - period: A \DateInterval object representing the period on which the rate
* limitations apply.
* - event: The name of the event to limit as declared in the rate_limit
* plugin.
* - limits: An associative array with the number of allowed requests in the
* selected period for every role.
* array(
* 'request' => array(
* 'event' => 'request',
* 'period' => new \DateInterval('P1D'),
* 'limits' => array(
* 'authenticated user' => 100,
* 'anonymous user' => 10,
* 'administrator' => \RestfulRateLimitManager::UNLIMITED_RATE_LIMIT,
* ),
* ),
* ),
*
* Properties for the "authentication" plugin type:
* - description: The description of the authentication provider. Defaults to
* empty string.
* - settings: Array with the settings needed for the plugin. Defaults to empty
* array.
*
* Properties for the "rate_limit" plugin type:
* - description: The description of the event. Defaults to an empty string.
* - name: The name of the event.
* - class: Name of the class implementing RestfulRateLimitInterface.
*
*/
function restful_plugin_process(&$plugin, $info) {
if ($info['type'] == 'restful') {
$plugin += array(
'description' => '',
'major_version' => 1,
'minor_version' => 0,
'options' => array(),
'entity_type' => FALSE,
'bundle' => FALSE,
'authentication_types' => array(),
'authentication_optional' => FALSE,
'hook_menu' => TRUE,
'cache' => array(),
);
$plugin['cache'] += array(
'render' => FALSE,
'class' => NULL,
'bin' => 'cache_restful',
'expire' => CACHE_PERMANENT,
'simple_invalidate' => TRUE,
);
if (!empty($plugin['rate_limit'])) {
foreach ($plugin['rate_limit'] as $event_name => $rate_limit_info) {
$plugin['rate_limit'][$event_name]['limits'] += array('anonymous user' => 0);
}
}
if ($plugin['hook_menu'] && empty($plugin['menu_item'])) {
// Set a default menu item.
$base_path = variable_get('restful_hook_menu_base_path', 'api/%');
$base_path = str_replace('%', 'v' . $plugin['major_version'], $base_path);
$plugin['menu_item'] = $base_path . '/' . $plugin['resource'];
}
}
elseif ($info['type'] == 'authentication') {
$plugin += array(
'description' => '',
'settings' => array(),
);
}
elseif ($info['type'] == 'rate_limit') {
$plugin += array(
'description' => '',
);
}
}
/**
* Implements hook_ctools_plugin_type().
*/
function restful_ctools_plugin_type() {
$plugins['authentication'] = $plugins['restful'] = $plugins['rate_limit'] = array(
'classes' => array('class'),
'process' => 'restful_plugin_process',
);
$plugins['restful']['child plugins'] = TRUE;
return $plugins;
}
/**
* Include CTools plugins and get all restful plugins.
*
* @return array
* All plugins for restful resources.
*/
function restful_get_restful_plugins() {
ctools_include('plugins');
return ctools_get_plugins('restful', 'restful');
}
/**
* Include CTools plugins and get all authentication plugins.
*
* @return array
* All plugins for restful authentication.
*/
function restful_get_authentication_plugins() {
ctools_include('plugins');
return ctools_get_plugins('restful', 'authentication');
}
/**
* Include CTools plugins and get all rate_limit plugins.
*
* @return array
* All plugins for restful authentication.
*/
function restful_get_rate_limit_plugins() {
ctools_include('plugins');
return ctools_get_plugins('restful', 'rate_limit');
}
/**
* Include CTools plugins and get the specified authentication plugin.
*
* @param string $plugin_name
* If provided this function only returns the selected plugin.
*
* @return array
* The selected plugin for restful authentication.
*/
function restful_get_authentication_plugin($plugin_name) {
ctools_include('plugins');
return ctools_get_plugins('restful', 'authentication', $plugin_name);
}
/**
* Include CTools plugins and get the specified rate_limit plugin.
*
* @param string $plugin_name
* If provided this function only returns the selected plugin.
*
* @return array
* The selected plugin for restful authentication.
*/
function restful_get_rate_limit_plugin($plugin_name) {
ctools_include('plugins');
return ctools_get_plugins('restful', 'rate_limit', $plugin_name);
}
/**
* Implements hook_menu().
*/
function restful_menu() {
$items = array();
foreach (restful_get_restful_plugins() as $plugin) {
if (!$plugin['hook_menu']) {
// Plugin explicitly declared no hook menu should be created automatically
// for it.
continue;
}
$items[$plugin['menu_item']] = array(
'title' => $plugin['name'],
'access callback' => 'restful_menu_access_callback',
'access arguments' => array(1, 2),
'page callback' => 'restful_menu_process_callback',
'page arguments' => array(1, 2),
'delivery callback' => 'restful_json_output',
);
}
// A special login endpoint, that returns a JSON output along with the Drupal
// authentication cookie.
if (variable_get('restful_user_login_menu_item', TRUE)) {
$items['api/login'] = array(
'title' => 'Login',
'description' => 'Login using base auth and recieve a JSON response along with an authentication cookie.',
'access callback' => 'user_is_anonymous',
'page callback' => 'restful_menu_process_callback',
'page arguments' => array('1', 'login_cookie'),
'delivery callback' => 'restful_json_output',
);
}
// A special file upload endpoint, that returns a JSON with the newly saved
// files.
if (variable_get('restful_file_upload', FALSE)) {
$items['api/file-upload'] = array(
'title' => 'File upload',
'access arguments' => array('restful_file_upload_access'),
'page callback' => 'restful_menu_process_callback',
'page arguments' => array('1', 'files'),
'delivery callback' => 'restful_json_output',
);
}
$items['api/session/token'] = array(
'page callback' => 'restful_csrf_session_token',
'access callback' => 'user_is_logged_in',
'delivery callback' => 'restful_json_output',
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Return the handler based on major and minor version, and resource name.
*
* @param $resource_name
* The name of the resource (e.g. "articles").
* @param int $major_version
* (optional) The major version (not prefixed with "v"). Defaults to 1.
* @param int $minor_version
* (optional) The minor version. Defaults to 0.
*
* @return RestfulInterface | NULL
* The handler object if found, or NULL.
*/
function restful_get_restful_handler($resource_name, $major_version = 1, $minor_version = 0) {
$cache = &drupal_static(__FUNCTION__);
$identifier = implode(':', array($major_version, $resource_name, $minor_version));
if (isset($cache[$identifier])) {
return $cache[$identifier];
}
$cache[$identifier] = NULL;
// Array with all the handlers with the same major version and resource name.
// We get all of them, so we can find the correct one if minor version is
// present.
$valid_plugins = array();
foreach (restful_get_restful_plugins() as $plugin) {
if ($plugin['major_version'] != $major_version) {
continue;
}
if ($plugin['resource'] != $resource_name) {
continue;
}
if ($minor_version == $plugin['minor_version']) {
// We found out handler, so we can break.
$valid_plugins[$plugin['minor_version']] = $plugin;
break;
}
if ($plugin['minor_version'] > $minor_version) {
// Minor version is above the needed one.
continue;
}
$valid_plugins[$plugin['minor_version']] = $plugin;
}
if (!$valid_plugins) {
return;
}
// Sort the handlers, and get the last one, as it is the closest one to the
// requested minor version.
ksort($valid_plugins);
$plugin = end($valid_plugins);
$cache[$identifier] = restful_get_restful_handler_by_name($plugin['name']);
return $cache[$identifier];
}
/**
* Return the handler based on major and minor version, and resource name.
*
* @param $plugin_name
* The name of the plugin, including version. (e.g. "articles__1_2").
*
* @return RestfulInterface | NULL
* The handler object if found, or NULL.
*/
function restful_get_restful_handler_by_name($plugin_name) {
ctools_include('plugins');
$plugin = ctools_get_plugins('restful', 'restful', $plugin_name);
$class = ctools_plugin_load_class('restful', 'restful', $plugin_name, 'class');
$handler = new $class($plugin);
// If the restful plugin needs authentication load the corresponding
// authentication plugin.
// Handler set explicitly to allow all authentication types.
$auth_plugins = $plugin['authentication_types'] === TRUE ? array_keys(restful_get_authentication_plugins()) : $plugin['authentication_types'];
// We can have multiple authentication plugins.
foreach ($auth_plugins as $auth_plugin_name) {
$auth_handler = restful_get_authentication_handler($auth_plugin_name);
$handler->getAuthenticationManager()->addAuthenticationProvider($auth_handler);
}
// Set the "optional" flag of the authentication manager.
$handler->getAuthenticationManager()->setIsOptional($plugin['authentication_optional']);
return $handler;
}
/**
* Return the authentication handler based on the authentication plugin name.
*
* @param string $auth_plugin_name
* Name of the authentication plugin.
*
* @return \RestfulAuthenticationInterface
* The authentication provider object.
*
* @throws \RestfulException if the authentication provider does not exist.
*/
function restful_get_authentication_handler($auth_plugin_name) {
$auth_plugin = restful_get_authentication_plugin($auth_plugin_name);
$auth_class = ctools_plugin_get_class($auth_plugin, 'class');
return new $auth_class($auth_plugin);
}
/**
* Access callback; Determine access for an API call.
*
* @param $major_version
* The major version, prefixed with v (e.g. v1, v2).
* @param $resource_name
* The name of the resource (e.g. "articles").
*
* @return bool
* TRUE if user is allowed to access resource.
*/
function restful_menu_access_callback($major_version, $resource_name) {
if ($major_version[0] != 'v') {
// Major version not prefixed with "v".
return;
}
if (!$major_version = intval(str_replace('v', '', $major_version))) {
// Major version is not an integer.
return;
}
$minor_version = !empty($_SERVER['HTTP_X_RESTFUL_MINOR_VERSION']) && is_int($_SERVER['HTTP_X_RESTFUL_MINOR_VERSION']) ? $_SERVER['HTTP_X_RESTFUL_MINOR_VERSION'] : 0;
if (!$handler = restful_get_restful_handler($resource_name, $major_version, $minor_version)) {
return;
}
if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'POST', 'PUT', 'PATCH', 'DELETE'))) {
return;
}
return $handler->access();
}
/**
* Page callback; Return the response for an API call.
*
* @param $major_version
* The major version, prefixed with v (e.g. v1, v2).
* @param $resource_name
* The name of the resource (e.g. "articles").
*
* @return string
* JSON output with the result of the API call.
*
* @see http://tools.ietf.org/html/draft-nottingham-http-problem-06
*/
function restful_menu_process_callback($major_version, $resource_name) {
$major_version = intval(str_replace('v', '', $major_version));
$minor_version = !empty($_SERVER['HTTP_X_RESTFUL_MINOR_VERSION']) && is_numeric($_SERVER['HTTP_X_RESTFUL_MINOR_VERSION']) ? $_SERVER['HTTP_X_RESTFUL_MINOR_VERSION'] : 0;
$handler = restful_get_restful_handler($resource_name, $major_version, $minor_version);
$path = func_get_args();
unset($path[0], $path[1]);
$path = implode('/', $path);
$method = strtolower($_SERVER['REQUEST_METHOD']);
$request = restful_parse_request();
try {
$result = $handler->{$method}($path, $request);
// Allow the handler to change the HTTP headers.
foreach ($handler->getHttpHeaders() as $key => $value) {
drupal_add_http_header($key, $value);
}
drupal_add_http_header('Content-Type', 'application/hal+json; charset=utf-8');
return $result;
}
catch (RestfulException $e) {
$result = array(
'type' => $e->getType(),
'title' => $e->getMessage(),
'status' => $e->getCode(),
'detail' => $e->getDescription(),
);
if ($instance = $e->getInstance()) {
$result['instance'] = $instance;
}
if ($errors = $e->getFieldErrors()) {
$result['errors'] = $errors;
}
}
catch (Exception $e) {
$result = array(
'type' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1',
'title' => $e->getMessage(),
'status' => 500,
);
}
// Adhere to the API Problem draft proposal.
drupal_add_http_header('Status', $result['status']);
drupal_add_http_header('Content-Type', 'application/problem+json; charset=utf-8');
return $result;
}
/**
* Build the request array from PHP globals and input stream.
*
* @return array
* The request array.
*/
function restful_parse_request() {
$request = NULL;
$method = strtolower($_SERVER['REQUEST_METHOD']);
if ($method == \RestfulInterface::GET) {
$request = $_GET;
}
elseif ($method == \RestfulInterface::POST) {
$request = $_POST;
}
if (!$request && $query_string = file_get_contents('php://input')) {
// When trying to POST using curl on simpleTest it doesn't reach
// $_POST, so we try to re-grab it here.
parse_str($query_string, $request);
}
// This flag is used to identify if the request is done "via Drupal" or "via
// CURL";
$request['__application'] = array(
'rest_call' => TRUE,
'csrf_token' => !empty($_SERVER['HTTP_X_CSRF_TOKEN']) ? $_SERVER['HTTP_X_CSRF_TOKEN'] : NULL,
);
return $request;
}
/**
* Returns data in JSON format.
*
* We do not use drupal_json_output(), in order to maintain the "Content-Type"
* header.
*
* @param $var
* (optional) If set, the variable will be converted to JSON and output.
*
* @see restful_menu_process_callback()
*/
function restful_json_output($var = NULL) {
if (!isset($var)) {
return;
}
if (is_int($var)) {
_restful_get_json_from_menu_status($var);
// Adhere to the API Problem draft proposal.
drupal_add_http_header('Status', $var['status']);
drupal_add_http_header('Content-Type', 'application/problem+json; charset=utf-8');
}
echo drupal_json_encode($var);
}
/**
* Convert a menu status response to a valid JSON.
*
* @param int $var
* The integer value of the menu status, passed by reference.
*/
function _restful_get_json_from_menu_status(&$var) {
switch ($var) {
case MENU_ACCESS_DENIED:
$class_name = 'RestfulForbiddenException';
break;
case MENU_SITE_OFFLINE:
$class_name = 'RestfulServiceUnavailable';
break;
}
$e = new $class_name;
$var = array(
'type' => $e->getType(),
'title' => $e->getMessage(),
'status' => $e->getCode(),
'detail' => $e->getDescription(),
'instance' => $e->getInstance(),
);
}
/**
* Implements hook_entity_info().
*/
function restful_entity_info() {
$items['rate_limit'] = array(
'label' => t('Rate limit'),
'entity class' => 'RestfulRateLimit',
'controller class' => 'EntityAPIController',
'base table' => 'restful_rate_limit',
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'rlid',
'label' => 'identifier',
'bundle' => 'event',
),
'bundles' => array(),
'bundle keys' => array(
'bundle' => 'type',
),
'module' => 'restful',
'entity cache' => module_exists('entitycache'),
);
return $items;
}
/**
* Implements hook_cron().
*/
function restful_cron() {
// Clear the expired restful_rate_limit entries.
$query = new \EntityFieldQuery();
$results = $query
->entityCondition('entity_type', 'rate_limit')
->propertyCondition('expiration', REQUEST_TIME, '>')
->execute();
if (!empty($results['rate_limit'])) {
$rlids = array_keys($results['rate_limit']);
entity_delete_multiple('rate_limit', $rlids);
}
}
/**
* Implements hook_entity_update().
*/
function restful_entity_update($entity, $type) {
list($entity_id) = entity_extract_ids($type, $entity);
$cid = 'et' . $type . '::ei' . $entity_id . '::uu';
_restful_invalidate_entity_cache($cid);
}
/**
* Implements hook_entity_delete().
*/
function restful_entity_delete($entity, $type) {
list($entity_id) = entity_extract_ids($type, $entity);
$cid = 'et' . $type . '::ei' . $entity_id . '::uu';
_restful_invalidate_entity_cache($cid);
}
/**
* Implements hook_user_update().
*/
function restful_user_update(&$edit, $account, $category) {
// Due to the limitations for cid matching on clearing caches, we need to
// clear all the bin. We cannot do $cid = '%::uu' . $account->uid . '::pa';
_restful_invalidate_entity_cache('*');
}
/**
* Implements hook_user_delete().
*/
function restful_user_delete($account) {
// Due to the limitations for cid matching on clearing caches, we need to
// clear all the bin. We cannot do $cid = '%::uu' . $account->uid . '::pa';
_restful_invalidate_entity_cache('*');
}
/**
* Delete cached entities from all the cache bins associated to restful
* resources.
*
* @param string $cid
* The wildcard cache id to invalidate.
*/
function _restful_invalidate_entity_cache($cid) {
$plugins = restful_get_restful_plugins();
foreach ($plugins as $plugin) {
$handler = restful_get_restful_handler($plugin['resource'], $plugin['major_version'], $plugin['minor_version']);
$reflector = new \ReflectionClass($handler);
if ($reflector->hasMethod('cacheInvalidate')) {
$version = $handler->getVersion();
$version_cid = 'v' . $version['major'] . '.' . $version['minor'];
$handler->cacheInvalidate($version_cid . '::' . $cid);
}
}
}
/**
* Access callback; Determine if user can access file uploading.
*
* If "File entity" module exists, determine access by its provided permissions
* otherwise, check if variable is set to allow anonymous users to upload.
* Defaults to authenticated user.
*
* @return bool
*/
function restful_file_upload_access() {
global $user;
if (module_exists('file_entity')) {
return user_access('bypass file access') || user_access('create files');
}
return variable_get('restful_file_upload_allow_anonymous_user', FALSE) || $user->uid;
}
/**
* Page callback: returns a session token for the currently active user.
*/
function restful_csrf_session_token() {
drupal_add_http_header('Content-Type', 'text/plain');
return array('X-CSRF-Token' => drupal_get_token(\RestfulInterface::TOKEN_VALUE));
}