forked from RESTful-Drupal/restful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestful.module
751 lines (661 loc) · 22.3 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
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
<?php
/**
* @file
* Turn Drupal to a RESTful server, following best practices.
*/
include_once __DIR__ . '/restful.entity.inc';
/**
* 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.
*/
function restful_plugin_process(&$plugin, $info) {
// Common operations.
$plugin += array(
'description' => '',
);
// Call the plugin specific process functions.
$function = array('\RestfulManager', 'pluginProcess' . preg_replace('/ /', '', ucwords(preg_replace('/_/', ' ', $info['type']))));
if (is_callable($function)) {
$plugin = call_user_func_array($function, array($plugin, $info));
}
}
/**
* Implements hook_ctools_plugin_type().
*/
function restful_ctools_plugin_type() {
$plugins['authentication'] = $plugins['restful'] = $plugins['rate_limit'] = $plugins['formatter'] = 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 the restful rate_limit plugins.
*/
function restful_get_rate_limit_plugins() {
ctools_include('plugins');
return ctools_get_plugins('restful', 'rate_limit');
}
/**
* Include CTools plugins and get all formatter plugins.
*
* @return array
* All the restful formatter plugins.
*/
function restful_get_formatter_plugins() {
ctools_include('plugins');
return ctools_get_plugins('restful', 'formatter');
}
/**
* 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 formatter plugin.
*
* @param string $plugin_name
* If provided this function only returns the selected plugin.
*
* @return array
* The selected plugin for restful formatter.
*/
function restful_get_formatter_plugin($plugin_name) {
ctools_include('plugins');
return ctools_get_plugins('restful', 'formatter', $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 rate limits.
*/
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() {
$base_path = variable_get('restful_hook_menu_base_path', 'api');
$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;
}
$item = array(
'title' => $plugin['name'],
'access callback' => 'restful_menu_access_callback',
'access arguments' => array($plugin['resource']),
'page callback' => 'restful_menu_process_callback',
'page arguments' => array($plugin['resource']),
'delivery callback' => 'restful_formatted_delivery',
'type' => MENU_CALLBACK,
);
// If there is no specific menu item allow the different version variations.
if ($plugin['hook_menu'] && empty($plugin['menu_item'])) {
// Add the version string to the arguments.
$item['access arguments'][] = 1;
$item['page arguments'][] = 1;
// Ex: api/v1.2/articles
$items[$base_path . '/v' . $plugin['major_version'] . '.' . $plugin['minor_version'] . '/' . $plugin['resource']] = $item;
// Ex: api/v1/articles will use the latest minor version.
$items[$base_path . '/v' . $plugin['major_version'] . '/' . $plugin['resource']] = $item;
// Ex: api/articles will use the header or the latest version.
// Do not add the version string to the arguments.
$item['access arguments'] = $item['page arguments'] = array(1);
$items[$base_path . '/' . $plugin['resource']] = $item;
}
else {
$items[$plugin['menu_item']] = $item;
}
}
// Make sure the CRSF token endpoint is not HAL.
if (!empty($items[$base_path . '/session/token'])) {
$items[$base_path . '/session/token']['delivery callback'] = 'restful_unprepared_delivery';
}
// Make sure the Login endpoint has the correct access callback.
if (!empty($items[$base_path . '/login'])) {
$items[$base_path . '/login']['access callback'] = 'user_is_anonymous';
}
// Add administration page.
$items['admin/config/services/restful'] = array(
'title' => 'RESTful',
'description' => 'Administer the RESTful module.',
'page callback' => 'drupal_get_form',
'page arguments' => array('restful_admin_settings'),
'access arguments' => array('administer restful'),
'file' => 'restful.admin.inc',
);
$items['admin/config/services/restful/restful'] = $items['admin/config/services/restful'];
$items['admin/config/services/restful/restful']['type'] = MENU_DEFAULT_LOCAL_TASK;
return $items;
}
/**
* Implements hook_permission().
*/
function restful_permission() {
return array(
'administer restful' => array(
'title' => t('Administer the RESTful module'),
'description' => t('Access the administration pages for the RESTful module.'),
),
);
}
/**
* Implements hook_help().
*/
function restful_help($path, $arg) {
switch ($path) {
case 'admin/structure/block':
case 'admin/help#restful':
return '<p>' . t('This module is managed in GitHub. Please make sure to read the docs in the !link page for more help.', array(
'!link' => l('README.md', 'https://github.com/Gizra/restful/blob/7.x-1.x/README.md'),
)) . '</p>';
}
}
/**
* 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
* The handler object if found, or NULL.
*
* @throws \RestfulException
*/
function restful_get_restful_handler_by_name($plugin_name) {
ctools_include('plugins');
$plugin = ctools_get_plugins('restful', 'restful', $plugin_name);
if (!$class = ctools_plugin_load_class('restful', 'restful', $plugin_name, 'class')) {
throw new \RestfulServiceUnavailable(format_string('Restful plugin class (@plugin) was not found.', array('@plugin' => $plugin_name)));
}
$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);
if (!$auth_class = ctools_plugin_get_class($auth_plugin, 'class')) {
throw new \RestfulServiceUnavailable(format_string('Authentication plugin class (@plugin) was not found.', array('@plugin' => $auth_plugin_name)));
}
return new $auth_class($auth_plugin);
}
/**
* Return the formatter handler based on the formatter plugin name.
*
* @param string $formatter_plugin_name
* Name of the formatter plugin.
*
* @param \RestfulBase $restful_handler
* The resource handler.
*
* @return \RestfulFormatterInterface
* The formatter provider object.
*
* @throws \RestfulException if the formatter provider does not exist.
*/
function restful_get_formatter_handler($formatter_plugin_name, $restful_handler) {
$formatter_plugin = restful_get_formatter_plugin($formatter_plugin_name);
if (!$formatter_class = ctools_plugin_get_class($formatter_plugin, 'class')) {
throw new \RestfulServiceUnavailable(format_string('Formatter plugin class (@plugin) was not found.', array('@plugin' => $formatter_plugin_name)));
}
return new $formatter_class($formatter_plugin, $restful_handler);
}
/**
* Helper function to get the restful handler for the selected path.
*
* @param string $path
* The path you want to get the handler for. Defaults to the current page.
*
* @return \RestfulEntityBase
* The restful handler or NULL.
*/
function restful_get_restful_handler_for_path($path = NULL) {
$handlers = &drupal_static(__FUNCTION__);
$path = is_null($path) ? $_GET['q'] : $path;
if (isset($handlers[$path])) {
return $handlers[$path];
}
$router_item = \RestfulBase::getMenuItem($path);
// We can only get the information if the current path was processed by
// restful_menu_process_callback.
if ($router_item['page_callback'] != 'restful_menu_process_callback') {
$handlers[$path] = FALSE;
return;
}
list($resource,) = \RestfulBase::getPageArguments($path);
list($major_version, $minor_version) = \RestfulBase::getVersionFromRequest($path);
$handlers[$path] = restful_get_restful_handler($resource, $major_version, $minor_version);
return $handlers[$path];
}
/**
* Access callback; Determine access for an API call.
*
* @param $version
* The version, prefixed with v (e.g. v1, v2.2).
* @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($resource_name, $version = NULL) {
if (!$versions = \RestfulBase::getVersionFromRequest()) {
// No version could be found.
return;
}
if (!$handler = restful_get_restful_handler($resource_name, $versions[0], $versions[1])) {
return;
}
if (!\RestfulBase::isValidMethod($_SERVER['REQUEST_METHOD'], FALSE)) {
return;
}
$method = strtoupper($_SERVER['REQUEST_METHOD']);
if ($method == \RestfulInterface::POST && \RestfulManager::getRequestHttpHeader('X-HTTP-Method-Override')) {
$method = strtoupper(\RestfulManager::getRequestHttpHeader('X-HTTP-Method-Override'));
}
if (!\RestfulBase::isValidMethod($method, FALSE)) {
// HTTP method is invalid.
return;
}
return $handler->access();
}
/**
* Page callback; Return the response for an API call.
*
* @param $resource_name
* The name of the resource (e.g. "articles").
* @param $version
* The version, prefixed with v (e.g. v1, v2.2).
*
* @throws RestfulServiceUnavailable
*
* @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($resource_name, $version = NULL) {
$path = func_get_args();
array_shift($path);
if (preg_match('/^v\d+(\.\d+)?$/', $version)) {
array_shift($path);
}
list($major_version, $minor_version) = \RestfulBase::getVersionFromRequest();
$handler = restful_get_restful_handler($resource_name, $major_version, $minor_version);
if (!$handler instanceof \RestfulDataProviderInterface) {
throw new \RestfulServiceUnavailable(format_string('The selected plugin (@plugin) does not implement \RestfulDataProviderInterface.', array('@plugin' => $resource_name . ' v' . $major_version . '.' . $minor_version)));
}
// Vary the response with the presence of the X-API-Version or Accept headers.
$headers = $handler->getHttpHeaders();
$vary = empty($headers['Vary']) ? '' : $headers['Vary'];
$additional_variations = array($vary, 'Accept');
if (\RestfulManager::getRequestHttpHeader('X-API-Version')) {
$additional_variations[] = 'X-API-Version';
}
if ($additional_variations) {
$handler->setHttpHeaders('Vary', implode(',', $additional_variations));
}
// Always add the allow origin if configured.
if ($allowed_origin = $handler->getPluginKey('allow_origin')) {
$handler->setHttpHeaders('Access-Control-Allow-Origin', $allowed_origin);
}
$path = implode('/', $path);
$method = strtoupper($_SERVER['REQUEST_METHOD']);
if ($method == \RestfulInterface::POST && \RestfulManager::getRequestHttpHeader('X-HTTP-Method-Override')) {
$method = strtoupper(\RestfulManager::getRequestHttpHeader('X-HTTP-Method-Override'));
}
$method = strtolower($method);
$request = restful_parse_request();
try {
return $handler->{$method}($path, $request);
}
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;
}
foreach ($e->getHeaders() as $header_name => $header_value) {
drupal_add_http_header($header_name, $header_value);
}
}
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 = strtoupper($_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.
// Also, sometimes the client might send the input still encoded.
if ($decoded_json = drupal_json_decode($query_string)) {
$request = $decoded_json;
}
else {
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' => \RestfulManager::getRequestHttpHeader('X-CSRF-Token'),
);
// Allow implemeting modules to alter the request.
drupal_alter('restful_parse_request', $request);
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.
* @param string $method
* Name of the method for the formatter.
*
* @see restful_menu_process_callback()
*/
function restful_delivery($var = NULL, $method = 'format') {
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');
}
// Get the formatter for the current resource.
if ($restful_handler = restful_get_restful_handler_for_path()) {
// Allow the handler to change the HTTP headers.
foreach ($restful_handler->getHttpHeaders() as $key => $value) {
drupal_add_http_header($key, $value);
}
// If we are returning from an OPTIONS call, always use render.
if ($restful_handler->getMethod() == \RestfulInterface::OPTIONS) {
$method = 'render';
}
}
try {
$formatter_handler = \RestfulManager::outputFormat($restful_handler);
$output = $formatter_handler->{$method}($var);
// The content type header is modified after the massaging if there is
// an error code. Therefore we need to set the content type header after
// formatting the output.
drupal_add_http_header('Content-Type', $formatter_handler->getContentTypeHeader());
}
catch (\RestfulException $e) {
// Handle if the formatter does not exist.
drupal_add_http_header('Status', $e->getCode());
echo $e->getMessage();
return;
}
print $output;
\RestfulManager::pageFooter();
}
/**
* Returns data in JSON format using data preparation in the formatter plugin.
*
* @param $var
* (optional) If set, the variable will be converted to JSON and output.
*
* @see restful_menu_process_callback()
*/
function restful_formatted_delivery($var = NULL) {
restful_delivery($var, 'format');
}
/**
* Returns data in JSON format not using data preparation in the formatter
* plugin.
*
* @param $var
* (optional) If set, the variable will be converted to JSON and output.
*
* @see restful_menu_process_callback()
*/
function restful_unprepared_delivery($var = NULL) {
restful_delivery($var, 'render');
}
/**
* 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_NOT_FOUND:
$class_name = 'RestfulNotFoundException';
$message = 'Invalid URL path.';
break;
case MENU_ACCESS_DENIED:
$class_name = 'RestfulForbiddenException';
$message = 'Access denied.';
break;
case MENU_SITE_OFFLINE:
$class_name = 'RestfulServiceUnavailable';
$message = 'Site is offline.';
break;
}
$e = new $class_name($message);
$var = array(
'type' => $e->getType(),
'title' => $e->getMessage(),
'status' => $e->getCode(),
'detail' => $e->getDescription(),
);
if ($instance = $e->getInstance()) {
$var['instance'] = $instance;
}
if ($errors = $e->getFieldErrors()) {
$var['errors'] = $errors;
}
}
/**
* Implements hook_page_delivery_callback_alter().
*
* Hijack api/* to be under RESTful. We make sure that any call to api/* pages
* that isn't valid, will still return with a well formatted error, instead of
* a 404 HTML page.
*/
function restful_page_delivery_callback_alter(&$callback) {
if (!variable_get('restful_hijack_api_pages', TRUE)) {
return;
}
$base_path = variable_get('restful_hook_menu_base_path', 'api');
if (strpos($_GET['q'], $base_path . '/') !== 0 && $_GET['q'] != $base_path) {
// Page doesn't start with the base path (e.g. "api" or "api/").
return;
}
if (menu_get_item()) {
// Path is valid (i.e. not 404).
return;
}
$callback = 'restful_deliver_menu_not_found';
}
/**
* Delivers a not found (404) error.
*/
function restful_deliver_menu_not_found($page_callback_result) {
restful_delivery(MENU_NOT_FOUND);
}
/**
* Implements hook_cron().
*/
function restful_cron() {
\RestfulRateLimitManager::deleteExpired();
}
/**
* Page callback: returns a session token for the currently active user.
*/
function restful_csrf_session_token() {
return array('X-CSRF-Token' => drupal_get_token(\RestfulInterface::TOKEN_VALUE));
}
/**
* Element validate \DateTime format function.
*/
function restful_date_time_format_element_validate($element, &$form_state) {
$value = $element['#value'];
try {
new \DateInterval($value);
}
catch (\Exception $e) {
form_error($element, t('%name must be compatible with the !link.', array(
'%name' => $element['#title'],
'!link' => l(t('\DateInterval format'), 'http://php.net/manual/en/class.dateinterval.php'),
)));
}
}