-
Notifications
You must be signed in to change notification settings - Fork 13
/
open_data_schema_map.module
1759 lines (1660 loc) · 54.4 KB
/
open_data_schema_map.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
* Maps entity types to Open Data schemas.
*/
$module_path = drupal_get_path('module', 'open_data_schema_map');
require_once $module_path . '/open_data_schema_map.file_cache.inc';
include __DIR__ . '/autoload.php';
require_once $module_path . '/src/OdsmValidatorInterface.php';
require_once $module_path . '/src/OdsmValidator.php';
define('OPEN_DATA_SCHEMA_MAP_ADMIN_PATH', 'admin/config/services/odsm');
/**
* Class OpenDataSchemaMapException
*/
class OpenDataSchemaMapException extends Exception {
private $data;
/**
* Override Exception constructor to add data parameter.
*
* {@inheritdoc}
*/
public function __construct($message, $code = 0, $data = NULL) {
parent::__construct($message, $code);
$this->data = !empty($data) ? $data : $message;
}
/**
* Returns the data associated with the exception.
*/
public function getData() {
return $this->data;
}
/**
* Returns HTTP status error given a code.
*/
public function getHTTPError() {
$code = $this->getCode();
switch ($code) {
case 400:
return '400 Bad Request';
case 403:
return '403 Forbidden';
case 404:
return '404 Not Found';
case 406:
return '406 Not Acceptable';
case 412:
return '412 Precondition Failed';
case 422:
return '422 Unprocessable Entity';
default:
return '500 Internal Server Error';
}
}
}
/**
* Implements hook_menu().
*/
function open_data_schema_map_menu() {
$items = array();
$pre = OPEN_DATA_SCHEMA_MAP_ADMIN_PATH;
$config_parent_normal_path = 'admin/dkan';
$config_plid = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :parent AND menu_name = :menu", array(':parent' => $config_parent_normal_path, ':menu' => 'menu-command-center-menu'))->fetchField();
$items['admin/dkan/datasets_per_page'] = array(
'title' => t('Datasets per page'),
'description' => t('Configure datasets per page for catalog.xml endpoints'),
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_datasets_per_page_form'),
'access arguments' => array('administer DKAN configuration'),
'type' => MENU_NORMAL_ITEM,
);
$items['cc/admin/dkan/datasets_per_page'] = array(
'access arguments' => array('administer DKAN configuration'),
'description' => t('Configure datasets per page for catalog.xml endpoints'),
'page callback' => 'drupal_goto',
'page arguments' => array('admin/dkan/datasets_per_page'),
'title' => t('Datasets per page'),
'menu_name' => 'menu-command-center-menu',
'parent_identifier' => 'menu-command-center-menu_site-configuration:admin/dkan',
'plid' => $config_plid,
'type' => MENU_NORMAL_ITEM,
'weight' => 11,
);
$apis = open_data_schema_map_api_load_all();
if ($apis) {
foreach ($apis as $num => $api) {
$description = isset($api->description) ? $api->description : '';
if ($api->enabled) {
$items[$api->endpoint] = array(
'title' => $api->name,
'description' => $description,
'page callback' => 'open_data_schema_map_endpoint',
'page arguments' => array($api),
'access arguments' => array('access content'),
'file' => 'open_data_schema_map.pages.inc',
);
}
}
}
$items[$pre] = array(
'title' => 'Open Data Schema Mapper',
'description' => 'Map Drupal structures to Open Data specfications',
'page callback' => 'open_data_schema_map_page_overview',
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.pages.inc',
);
$items[$pre . '/overview'] = array(
'title' => 'Overview',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items[$pre . '/add/api'] = array(
'title' => 'Add API',
'description' => 'Add a new API Endpoint',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_manage'),
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.pages.inc',
'type' => MENU_LOCAL_ACTION,
);
$items[$pre . '/settings'] = array(
'title' => 'Settings',
'description' => 'Open Data Schema Map Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_admin_settings_form'),
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.admin.inc',
'type' => MENU_LOCAL_ACTION,
);
$items[$pre . '/edit/%open_data_schema_map_api'] = array(
'title' => 'Edit API',
'description' => 'Edit an existing API Endpoint',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_manage', 5),
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.pages.inc',
);
$items[$pre . '/cache/%open_data_schema_map_api'] = array(
'title' => 'API Cache File',
'description' => 'Administer an existing API Endpoint File Cache',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_cache_manage', 5),
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.file_cache.inc',
);
$items[$pre . '/delete/%open_data_schema_map_api'] = array(
'title' => 'Delete API',
'description' => 'Delete an existing API Endpoint',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_data_schema_map_delete', 5),
'access arguments' => array('administer open data schema mapper'),
'file' => 'open_data_schema_map.pages.inc',
);
// Read validation implementation and add to menu.
foreach (module_implements('open_data_schema_map_info') as $module) {
$data = module_invoke($module, 'open_data_schema_map_info');
$path = OPEN_DATA_SCHEMA_MAP_ADMIN_PATH . '/validate/' . $data['name'];
$items[$path] = array(
'title' => $data['title'],
'page callback' => 'open_data_schema_map_validation_page',
'page arguments' => array($data['validation_class'], $data['api_endpoint']),
'access arguments' => array('administer open data schema mapper'),
'type' => MENU_NORMAL_ITEM,
'file' => 'open_data_schema_map.pages.inc',
'file path' => drupal_get_path('module', 'open_data_schema_map'),
);
}
return $items;
}
/**
* Datasets per page form.
*
* @param array $form_state
* Form state array
*
* @return array
* Form array
*/
function open_data_schema_map_datasets_per_page_form() {
$form['datasets_per_page'] = array(
'#type' => 'textfield',
'#size' => 5,
'#maxlength' => 5,
'#default_value' => variable_get('datasets_per_page', ''),
'#title' => t('Amount of datasets per page'),
'#description' => t('If your catalog contains thousands of datasets, your API endpoints may get too large to load. To reduce the strain on your server, we recommend that you add pagination to the catalog.xml endpoints. To enable pagination, simply specify the number of results per page you would like in the field above and click save. If nothing is entered, all datasets will be included on a single page.'),
);
return system_settings_form($form);
}
/**
* Validate function.
*/
function open_data_schema_map_datasets_per_page_form_validate($form, &$form_state) {
$max_num = $form_state['values']['datasets_per_page'];
if (empty($max_num)) {
if ($max_num == "0") {
form_set_error('datasets_per_page', t('Amount of datasets per page cannot be 0.'));
}
} else {
if (!is_numeric($max_num)) {
form_set_error('datasets_per_page', t('You must enter a number for the amount of datasets per page.'));
} else {
if ($max_num < 0) {
form_set_error('datasets_per_page', t('Amount of datasets per page must be positive.'));
}
}
}
}
/**
* Implements hook_permission().
*/
function open_data_schema_map_permission() {
return array(
'administer open data schema mapper' => array(
'title' => t('Administer Open Data Schema Mapper'),
'description' => t('Make and update open data schema maps'),
'restrict access' => TRUE,
));
}
/**
* Implements hook_libraries_info().
*/
function open_data_schema_map_libraries_info() {
$libraries['symfonyserializer'] = array(
'name' => 'Simfony Serializer',
'vendor url' => 'https://github.com/symfony/serializer',
'download url' => 'https://github.com/symfony/serializer/zipball/master',
'version' => 'master',
'files' => array(),
);
$libraries['json-schema'] = array(
'name' => 'Justinrainbow JSON-Schema',
'vendor url' => 'https://github.com/justinrainbow/json-schema.git',
'download url' => 'https://github.com/justinrainbow/json-schema/tree/master/src/JsonSchema',
'version' => 'master',
'files' => array(),
);
return $libraries;
}
/**
* Registers declared schemas.
*/
function open_data_schema_map_register() {
static $schemas = array();
if ($schemas) {
return $schemas;
}
foreach (module_implements('open_data_schema') as $module) {
$module_schemas = module_invoke($module, 'open_data_schema');
foreach ($module_schemas as $schema) {
$schemas[$schema['short_name']] = $schema;
}
}
return $schemas;
}
/**
* Implements hook_help().
*/
function open_data_schema_map_help($path, $arg) {
switch ($path) {
case 'admin/config/services/odsm':
return t('Create APIs using Drupal entities that map to Open Data specifications. See !docs for more instructions.',
array('!docs' => l(t('documentation'), 'https://github.com/GetDKAN/open_data_schema_map#open-data-schema-map')));
}
return NULL;
}
/**
* Provides form type from field type.
*
* @param string $field_type
* Field type
*
* @return string
* Form type
*/
function open_data_schema_map_form_field_type($field_type) {
switch ($field_type) {
case "string":
return 'textfield';
}
return '';
}
/**
* Recursive function to generate mapping form.
*
* @param array $form
* Form api ready array to build.
* @param array $schema
* Schema array which is reduced.
* @param object $api
* $api object which is passed around because procedural.
* @param array $defaults
* Array of defaults which matches up with the $schema.
*
* @return array
* Form array
*/
function open_data_schema_map_form_recursion(&$form, $schema, $api, $defaults = NULL) {
$entity_ref_fields = open_data_schema_map_entity_ref_fields($api->type, $api->bundle);
foreach ($schema as $key => $value) {
// Skip if not a top level item.
if (!is_array($value)) {
continue;
}
if (count($value) == count($value, COUNT_RECURSIVE)) {
$desc = isset($value['description']) ? $value['description'] : '';
$description = t('Machine name: %machine_name field type: %type description: %desc', array(
'%machine_name' => $key, '%type' => $value['type'], '%desc' => $desc));
$default = isset($defaults[$key]) ? $defaults[$key] : '';
$form[$key] = array(
'#title' => $value['title'],
'#type' => 'textfield',
'#maxlength' => 512,
'#description' => $description,
'#default_value' => $default,
);
}
elseif ($key) {
$form[$key] = array(
'#title' => $key,
'#type' => 'fieldset',
'#collapsible' => TRUE,
);
$entity_ref_fields = open_data_schema_map_entity_ref_fields($api->type, $api->bundle);
if ($value['type'] == 'array' && $entity_ref_fields) {
$odsm_entity_reference = isset($defaults[$key]['odsm_entity_reference']['value']) ? $defaults[$key]['odsm_entity_reference']['value'] : '';
$form[$key]['odsm_entity_reference'] = array(
'#title' => $key . ' Multivalue Field',
'#type' => 'select',
'#options' => array('' => t('-- none --')) + $entity_ref_fields,
'#default_value' => $odsm_entity_reference,
'#description' => t('This array can iterate over multi-value fields as long as they are an entity reference. Select entity reference field to use. If none is selected this output will not loop and accept single value tokens. "Nth" represents iteratable tokens.'),
);
}
open_data_schema_map_form_recursion($form[$key], $schema[$key], $api, $defaults[$key]);
}
}
return $form;
}
/**
* Lists APIs created with this module.
*/
function open_data_schema_map_api_table() {
$apis = open_data_schema_map_api_load_all();
foreach ($apis as $num => $api) {
unset($apis[$num]->id);
unset($apis[$num]->description);
unset($apis[$num]->mapping);
unset($apis[$num]->arguments);
$apis[$num]->edit = l(t('edit'), 'admin/config/services/odsm/edit/' . $api->machine_name);
$apis[$num]->cache = open_data_schema_map_file_cache_admin_link($api);
}
return $apis;
}
/**
* Determines whether a machine name exists.
*
* @param string $machine_name
* API machine name.
*
* @return bool
* Returns FALSE
*/
function open_data_schema_map_api_exist($machine_name) {
return FALSE;
}
/**
* Loads all APIs.
*/
function open_data_schema_map_api_load_all() {
$list = array();
$records = &drupal_static(__FUNCTION__, array());
if ($records) {
return $records;
}
$results = db_query("select machine_name from {open_data_schema_map}")->fetchAll();
foreach ($results as $result) {
$list[] = $result->machine_name;
}
drupal_alter('open_data_schema_map_endpoints', $list);
foreach ($list as $item) {
$records[] = open_data_schema_map_api_load($item);
}
return $records;
}
/**
* Loads API.
*
* @param string $machine_name
* API machine name.
*
* @return object
* API object.
*/
function open_data_schema_map_api_load($machine_name) {
if ($record = module_invoke_all('open_data_schema_map_load', $machine_name)) {
return $record[0];
}
elseif ($record = db_query("select * from {open_data_schema_map} where machine_name = :machine_name", array(':machine_name' => $machine_name))->fetchObject()) {
$record->mapping = unserialize($record->mapping);
$record->arguments = unserialize($record->arguments);
return $record;
}
return NULL;
}
/**
* Loads schema from file.
*
* @param string $schema_name
* Schema name
*
* @return array
* Schema array
*/
function open_data_schema_map_schema_load($schema_name) {
$schemas = &drupal_static(__FUNCTION__, array());
if ($schemas) {
return $schemas;
}
$schemas = open_data_schema_map_register();
$loaded_schema = $schemas[$schema_name];
$json_file = $loaded_schema['schema_file'];
$json = file_get_contents($json_file);
$schema = drupal_json_decode($json);
foreach (module_implements('open_data_schema_fill_references') as $module) {
$hook_implementation = $module . '_open_data_schema_fill_references';
$hook_implementation($schema_name, $schema);
}
return $schema;
}
/**
* Retrieves public, published dataset nodes.
*
* @param object $api
* Api object.
* @param int $limit
* Number of results to return.
* @param int $offset
* Offset of results to return.
* @param array $args
* - query: current value of query.
* - value: value field
* - token: token to get data from
*
* @return array
* An array of dataset nodes.
*/
function open_data_schema_map_endpoint_query($api, $limit = 0, $offset = 0, $args = array()) {
$type = $api->type;
$bundle = $api->bundle;
$args = is_array($args) ? $args : array($args);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $type)
->entityCondition('bundle', $bundle)
->propertyCondition('status', 1)
->propertyOrderBy('created', 'DESC')
// Run the query as user 1.
->addMetaData('account', user_load(1));
if ($limit) {
$query->range($offset, $limit);
}
foreach ($args as $arg => $arg_value) {
$field = open_data_schema_map_discover_field($arg_value['token']['value']);
drupal_alter('open_data_schema_map_args', $field, $arg_value, $api->machine_name);
// Pass conditions if no queries.
if (!isset($arg_value['query']) || !$arg_value['query']) {
continue;
}
if (!empty($field) && $field[0] == 'node') {
if (substr($field[1], 0, 5) == 'field' || $field[1] == 'og_group_ref') {
$query->fieldCondition($field[1], $arg_value['value'], $arg_value['query']);
}
else {
$query->propertyCondition($field[1], $arg_value['query']);
}
}
}
drupal_alter('open_data_schema_map_endpoint_query', $query, $api->machine_name);
$entities = $query->execute();
$ids = NULL;
if ($entities) {
$ids = array_keys($entities[$type]);
}
return $ids;
}
/**
* Returns array from token.
*
* @param string $token
* Token
*
* @return array
* Array from token
*/
function open_data_schema_map_discover_field($token) {
$token = rtrim(trim($token, '['), ']');
return explode(':', $token);
}
/**
* Discovers callback for argument options.
*
* @param string $id
* Argument option
*
* @return string
* Callback
*/
function open_data_schema_map_schema_options_callback($id) {
$schema_types = open_data_schema_map_schema_types();
foreach ($schema_types as $schema_type => $data) {
if ($data['id'] == $id) {
return $data['options_callback'];
}
}
return NULL;
}
/**
* Discovers callback for schema type.
*
* @param string $id
* Schema type
*
* @return string
* Callback
*/
function open_data_schema_map_schema_types_callback($id) {
$schema_types = open_data_schema_map_schema_types();
foreach ($schema_types as $schema_type => $data) {
if ($data['id'] == $id) {
return $data['callback'];
}
}
return NULL;
}
/**
* Creates array of schema types.
*/
function open_data_schema_map_schema_types() {
$schemas = array(
'json-4' => array(
'id' => 'http://json-schema.org/draft-04/schema#',
'callback' => 'open_data_schema_map_json_4',
'options_callback' => 'open_data_schema_mapper_args_options_json_4',
),
'json-3' => array(
'id' => 'http://json-schema.org/draft-03/schema#',
'callback' => 'open_data_schema_map_json_3',
'options_callback' => 'open_data_schema_mapper_args_options_json_3',
),
);
drupal_alter('open_data_schema_map_schema_types', $schemas);
return $schemas;
}
/**
* Creates argument form.
*
* @param int $num_args
* Number of args
* @param array $options
* Options array
* @param array $defaults
* Defaults array
* @param object $api
* API Object
*
* @return array
* Form array
*/
function open_data_schema_map_args_form($num_args, $options, $defaults, $api) {
$map = $api->mapping;
$form = $columns = array();
for ($i = 1; $i <= $num_args; $i++) {
if (isset($defaults[$i]['field']) &&
isset($map[$defaults[$i]['field']]['value']) &&
$token = $map[$defaults[$i]['field']]['value']) {
$token = open_data_schema_map_discover_field($token);
if ($token[0] == 'node') {
if (substr($token[1], 0, 5) == 'field') {
$field = str_replace('-', '_', $token[1]);
$field_info = field_info_field($field);
foreach ($field_info['columns'] as $column => $data) {
$columns[$column] = $column;
}
}
}
}
$form[$i] = array(
'#title' => 'Argument ' . $i,
'#type' => 'fieldset',
);
$form[$i]['field'] = array(
'#title' => 'Schema Field',
'#type' => 'select',
'#description' => t('Schema field to use as an argument. The schema field is the "key" in /endpoint?key=123456. Also available are special arguments "offset" and "limit."'),
'#options' => $options,
'#default_value' => isset($defaults[$i]['field']) ? $defaults[$i]['field'] : '',
);
$form[$i]['required'] = array(
'#title' => 'Required',
'#type' => 'checkbox',
'#description' => t('Whether argument is required.'),
'#default_value' => isset($defaults[$i]['required']) ? $defaults[$i]['required'] : 1,
);
$special_args = open_data_schema_map_special_arguments();
if (isset($defaults[$i]['field']) && isset($special_args[$defaults[$i]['field']])) {
$form[$i]['value'] = array(
'#title' => 'Default ' . $special_args[$defaults[$i]['field']] . ' Value',
'#type' => 'textfield',
'#description' => t('Defaut value for !value. IE /endpoint?%field=X.', array('!value' => $special_args[$defaults[$i]['field']], '%field' => $defaults[$i]['field'])),
'#default_value' => isset($defaults[$i]['value']) ? $defaults[$i]['value'] : '',
);
}
else {
if ($columns) {
$form[$i]['value'] = array(
'#title' => 'Schema Field Column',
'#type' => 'select',
'#options' => $columns,
'#description' => t('Value for schema field. Only for tokens with [nodes:field_FIELD_NAME]. This is the column name in the field table to grab. Defaults to "safe_value".'),
'#default_value' => isset($defaults[$i]['value']) ? $defaults[$i]['value'] : '',
);
}
}
}
return $form;
}
/**
* Special fields for arguments.
*
* @return array
* Array of arguments
*/
function open_data_schema_map_special_arguments() {
return array(
'offset' => t('offset'),
'limit' => t('limit'),
);
}
/**
* Finds entity reference fields for a given bundle.
*
* @param string $entity
* Entity machine name.
* @param string $bundle
* Bundle machine name.
* @param array $ref_fields
* List of fields
*
* @return array
* Array of entity reference or similar fields.
*/
function open_data_schema_map_entity_ref_fields($entity, $bundle, $ref_fields = array('entityreference', 'taxonomy')) {
// Get instances.
$instances = field_info_instances($entity, $bundle);
// Get reference fields.
$query = db_select('field_config', 'f');
$query->fields('f', array('field_name'));
$or = db_or();
$or->condition('cardinality', '1', '>');
$or->condition('cardinality', '-1', '=');
$query->condition($or);
$query->distinct();
$rows = $query->execute();
$field_names = array();
foreach ($rows as $row) {
$field_name = $row->field_name;
// See if reference field is used in bundle.
if (isset($instances[$field_name])) {
$field_names[$field_name] = $instances[$field_name]['label'];
}
}
return $field_names;
}
/**
* Creates form from JSON 4 schema.
*
* @param array $schema
* Schema array
* @param object $api
* API object
* @param array $defaults
* Array of defaults
*
* @return array
* Form array
*/
function open_data_schema_map_json_4($schema, $api, $defaults) {
$form = array();
$form['#title'] = $schema['title'] ? $schema['title'] : t('Mapping');
$form['#description'] = $schema['description'] ? $schema['description'] : t('Fields to map.');
$form['#type'] = 'fieldset';
foreach ($schema['properties'] as $item => $data) {
if (!isset($data['type'])) {
if (isset($data['anyOf'][0]['type'])) {
$data['type'] = $data['anyOf'][0]['type'];
}
else {
$data['type'] = 'string';
}
}
$desc = isset($data['description']) ? $data['description'] . t('Type:') . $data['type'] : t('Type:') . $data['type'];
$form[$item] = array(
'#title' => $data['title'] . ' (' . $item . ')',
'#type' => 'textfield',
'#maxlength' => 512,
'#description' => $desc,
'#default_value' => isset($defaults[$item]['value']) ? $defaults[$item]['value'] : '',
'#field_type' => $data['type'],
);
if ($data['type'] == 'array' && isset($data['anyOf'][0]['items']['type']) && $data['anyOf'][0]['items']['type'] == 'object') {
$entity_ref_fields = open_data_schema_map_entity_ref_fields($api->type, $api->bundle);
$odsm_entity_reference = isset($defaults[$item]['odsm_entity_reference']['value']) ? $defaults[$item]['odsm_entity_reference']['value'] : '';
$form[$item] = array(
'#title' => $data['title'],
'#type' => 'fieldset',
'#description' => isset($data['description']) ? $data['description'] : '',
);
$form[$item]['odsm_entity_reference'] = array(
'#title' => $item . ' Multivalue Field',
'#type' => 'select',
'#options' => array('' => t('-- none --')) + $entity_ref_fields,
'#default_value' => $odsm_entity_reference,
'#description' => t('This array can iterate over multi-value fields. Select multi-value field to use. If none is selected this output will not loop and accept single value tokens. Selecting and saving an entity reference will produce a list of chaiabale tokens. For non entity reference fields, replace "?" with "Nth:value". "Nth" represents iteratable tokens.'),
);
foreach ($data['anyOf'][0]['items']['properties'] as $subitem => $subdata) {
$desc = isset($subdata['description']) ? $subdata['description'] : '';
$desc .= isset($subdata['type']) ? ' ' . t('Type:') . $subdata['type'] : '';
$form[$item][$subitem] = array(
'#title' => $subdata['title'] . ' (' . $subitem . ')',
'#type' => 'textfield',
'#maxlength' => 256,
'#description' => $desc,
'#default_value' => isset($defaults[$item][$subitem]['value']) ? $defaults[$item][$subitem]['value'] : '',
);
}
}
if ($data['type'] == 'object') {
$description = '';
if (isset($data['description'])) {
$description = $data['description'];
}
$form[$item] = array(
'#title' => $data['title'],
'#type' => 'fieldset',
'#description' => $description,
);
if (isset($data['properties'])) {
foreach ($data['properties'] as $subitem => $subdata) {
$desc = isset($subdata['description']) ? $subdata['description'] : '';
$desc .= isset($subdata['type']) ? ' ' . t('Type:') . $subdata['type'] : '';
$form[$item][$subitem] = array(
'#title' => $subdata['title'] . ' (' . $subitem . ')',
'#type' => 'textfield',
'#maxlength' => 512,
'#description' => $desc,
'#default_value' => isset($defaults[$item][$subitem]['value']) ? $defaults[$item][$subitem]['value'] : '',
);
}
}
}
}
return $form;
}
/**
* Constructs form for json schema 3.
*
* @param array $form
* Form array
* @param array $schema
* Schema
* @param object $api
* API object
* @param array $defaults
* Array of defaults
*/
function open_data_schema_map_json_3_recursion(&$form, $schema, $api, $defaults = NULL) {
foreach ($schema as $item => $data) {
$default_value = isset($defaults[$item]['value']) ? $defaults[$item]['value'] : '';
// Skip if not a top level item.
if (!is_array($data)) {
continue;
}
$field_type = $data['type'] ? $data['type'] : 'string';
$form[$item] = array(
'#title' => $item,
'#type' => 'textfield',
'#maxlength' => 512,
'#description' => $data['description'],
'#field_type' => $field_type,
'#default_value' => $default_value,
);
if ($field_type == 'object' || $field_type == 'array' && $data['items']['type'] == 'object') {
$entity_ref_fields = open_data_schema_map_entity_ref_fields($api->type, $api->bundle);
$odsm_entity_reference = isset($defaults[$item]['odsm_entity_reference']['value']) ? $defaults[$item]['odsm_entity_reference']['value'] : '';
$form[$item] = array(
'#title' => $item,
'#type' => 'fieldset',
'#description' => $data['description'],
'#field_type' => $field_type,
);
$form[$item]['odsm_entity_reference'] = array(
'#title' => $item . ' Multivalue Field',
'#type' => 'select',
'#options' => array('' => t('-- none --')) + $entity_ref_fields,
'#default_value' => $odsm_entity_reference,
'#description' => t('This array can iterate over multi-value fields as long as they are an entity reference. Select entity reference field to use. If none is selected this output will not loop and accept single value tokens. "Nth" represents iteratable tokens.'),
);
if ($data['type'] == 'object') {
open_data_schema_map_json_3_recursion($form[$item], $data['properties'], $api, $defaults[$item]);
}
elseif ($data['type'] == 'array' && $data['items']['type'] == 'object') {
open_data_schema_map_json_3_recursion($form[$item], $data['items']['properties'], $api, $defaults[$item]);
}
}
}
}
/**
* Creates form from JSON 3 schema.
*
* @param array $schema
* Schema array
* @param object $api
* API object
* @param array $defaults
* Array of defaults
*
* @return array
* Form array
*/
function open_data_schema_map_json_3($schema, $api, $defaults) {
$form = array();
$form['#title'] = t('Mapping');
$form['#description'] = $schema['description'] ? $schema['description'] : t('Fields to map.');
$form['#type'] = 'fieldset';
open_data_schema_map_json_3_recursion($form, $schema['properties'], $api, $defaults);
return $form;
}
/**
* Creates option list from available arguments.
*
* @param array $schema
* Schema array
*
* @return array
* Options array
*/
function open_data_schema_mapper_args_options_json_4($schema) {
$options = array();
foreach ($schema['properties'] as $id => $data) {
$options[$id] = $id;
}
return $options;
}
/**
* Creates option list from available arguments.
*
* @param array $schema
* Schema array
*
* @return array
* Options array
*/
function open_data_schema_mapper_args_options_json_3($schema) {
$options = array();
foreach ($schema['properties'] as $id => $data) {
$options[$id] = $id;
}
return $options;
}
/**
* Wrapper around token_replace.
*
* @param string $token
* Token
* @param string $entity_type
* Entity Type
* @param object $entity
* Entity object
*
* @return string
* Token replaced string
*/
function open_data_schema_mapper_token_replace($token, $entity_type, $entity) {
$rend_tokens = array();
// Does the token have an "or".
$output = '';
if (preg_match('/\] \|\| \[/', $token)) {
$tokens = explode(' || ', $token);
foreach ($tokens as $token) {
if ($output = token_replace($token, array($entity_type => $entity), array('clear' => TRUE))) {
return $output;
}
}
}
// Does the token have an "and".
elseif (preg_match('/\] && \[/', $token)) {
$tokens = explode(' && ', $token);
foreach ($tokens as $token) {
$rend_tokens[] = token_replace($token, array($entity_type => $entity), array('clear' => TRUE));
}
$output = implode(' ', $rend_tokens);
}
else {
$output = token_replace($token, array($entity_type => $entity), array('clear' => TRUE));
}
return $output;
}
/**
* Provides working arguments by validating fields and queries.
*
* @param array $map
* Map array
* @param array $queries
* Queries array
* @param array $args
* Args array
*
* @return array
* Array of args
*/
function open_data_schema_map_endpoint_args(&$map, $queries, $args = array()) {
$output = array();
foreach ($args as $num => $arg) {
if ($queries) {
foreach ($queries as $query_field => $query_value) {
// Make sure query passed to enpoint is actual argument field.
if ($arg['field'] == $query_field) {
$output[$num]['field'] = $query_field;
$output[$num]['query'] = $query_value;
$output[$num]['token'] = isset($map[$arg['field']]) ? $map[$arg['field']] : '';
$output[$num]['value'] = isset($args[$num]['value']) ? $args[$num]['value'] : 'value';
}
}
}
if ($arg['required'] == 1 && (!isset($output[$num]) || empty($output[$num]['query']))) {