forked from SU-SWS/stanford_capx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stanford_capx.module
721 lines (613 loc) · 20.5 KB
/
stanford_capx.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
<?php
/**
* @file
* @author [author]
*/
// Make sure this is loaded.
require_once "includes/autoloader.php";
require_once "includes/vendor/autoload.php";
require_once "stanford_capx.entity.hooks.inc";
require_once "stanford_capx.forms.inc";
require_once "stanford_capx.blocks.inc";
require_once "stanford_capx.theme.inc";
require_once "stanford_capx.docs.inc";
require_once "stanford_capx.views.inc";
require_once "stanford_capx.pages.inc";
use CAPx\Drupal\Importer\EntityImporterBatch;
use CAPx\Drupal\Processors\EntityProcessor;
use CAPx\Drupal\Mapper\EntityMapper;
use CAPx\Drupal\Mapper\FieldCollectionMapper;
use CAPx\Drupal\Util\CAPx;
use CAPx\Drupal\Util\CAPxMapper;
use CAPx\Drupal\Util\CAPxImporter;
use CAPx\Drupal\Util\CAPxConnection;
use CAPx\Drupal\Organizations\Orgs;
// No mapping into these entity types.
global $CAP_RESTRICTED_ENTITY_TYPES;
$CAP_RESTRICTED_ENTITY_TYPES = array(
'capx_cfe',
'capx_cfe_type',
'file',
'comment',
'taxonomy_vocabulary',
'field_collection_item',
'redirect',
'wysiwyg_profile',
'menu_link',
);
global $CAP_RESTRICTED_FIELD_PROPERTIES;
$CAP_RESTRICTED_FIELD_PROPERTIES = array(
'format',
'attributes',
);
define('STANFORD_CAPX_FILE_PATH', 'private://stanford_capx');
define('STANFORD_CAPX_SCHEMA_FILE', 'schema.json');
/**
* Implements hook_help().
*/
function stanford_capx_help($path, $arg) {
switch ($path) {
case 'admin/capx':
return '<p>' . t('Contact %email', array('%email' => l(t('email'), 'mailto:[email protected]'))) . '</p>';
}
}
/**
* Implements hook_permission().
*/
function stanford_capx_permission() {
return array(
'administer capx' => array(
'title' => t('Administer CAPx'),
'description' => t('Administer and configure CAPx settings.'),
),
// 'capx administer importers' => array(
// 'title' => t('Administer CAPx Importers'),
// 'description' => t('Administer and configure CAPx importers.'),
// ),
// 'capx administer mappers' => array(
// 'title' => t('Administer CAPx Mappers'),
// 'description' => t('Administer and configure CAPx mappers.'),
// ),
'capx advanced administrator' => array(
'title' => t('Administer Advanced CAPx settings'),
'description' => t('Administer and Ccnfigure CAPx advanced settings.'),
),
);
}
/**
* Implements hook_node_access().
*/
function stanford_capx_node_access($node, $op, $account) {
// Returning nothing from this function would have the same effect.
$access = NODE_ACCESS_IGNORE;
// Disable deletion of nodes synced from CAP.
if ($op == 'delete' && isset($node->capx) && !empty($node->capx['sync'])) {
$access = NODE_ACCESS_DENY;
}
return $access;
}
/**
* Implments hook_views_api().
*/
function stanford_capx_views_api() {
return array("version" => "3.0");
}
/**
* Implements hook_menu().
*/
function stanford_capx_menu() {
// Overview page.
$items['admin/config/capx'] = array(
'title' => 'CAPx',
'page callback' => 'stanford_capx_admin_config',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
// Settings Page.
$items['admin/config/capx/settings'] = array(
'title' => 'Settings',
'page callback' => 'stanford_capx_admin_config_settings',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
'weight' => -9,
);
// Sync organizations callback.
$items['admin/config/capx/organizations/sync'] = array(
'title' => 'Organizations Sync',
'page callback' => 'stanford_capx_organizations_sync',
'access arguments' => array('administer capx'),
'type' => MENU_CALLBACK,
);
// Help Page.
$items['admin/config/capx/help'] = array(
'title' => 'Help',
'page callback' => 'stanford_capx_admin_config_help',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
'weight' => 10,
);
// Data Browser.
$items['admin/config/capx/data-browser'] = array(
'title' => 'Data Browser',
'page callback' => 'stanford_capx_admin_config_data_browser',
'file' => 'stanford_capx.docs.inc',
'access arguments' => array('administer capx'),
'type' => MENU_SUGGESTED_ITEM,
'weight' => 10,
);
// Mapper pages
// ---------------------------------------------------------------------------
$items['admin/config/capx/mapper'] = array(
'title' => 'Map',
'page callback' => 'stanford_capx_admin_config_mapper',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
'weight' => -5,
);
$items['admin/config/capx/mapper/new'] = array(
'title' => 'Create new mapping',
'page callback' => 'stanford_capx_admin_config_mapper_new',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/mapper/edit/%'] = array(
'title' => 'Edit mapping',
'page callback' => 'stanford_capx_admin_config_mapper_edit',
'page arguments' => array(5),
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/mapper/delete/%'] = array(
'title' => 'Delete mapping',
'page callback' => 'drupal_get_form',
'page arguments' => array('stanford_capx_admin_config_mapper_delete', 5),
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
// Importer pages
// ---------------------------------------------------------------------------
$items['admin/config/capx/importer'] = array(
'title' => 'Import',
'page callback' => 'stanford_capx_admin_config_import',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
'weight' => -4,
);
$items['admin/config/capx/importer/new'] = array(
'title' => 'Create new importer',
'page callback' => 'stanford_capx_admin_config_import_new',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/importer/edit/%'] = array(
'title' => 'Edit importer',
'page arguments' => array(5),
'page callback' => 'stanford_capx_admin_config_import_edit',
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/importer/delete/%'] = array(
'title' => 'Delete Importer',
'page callback' => 'drupal_get_form',
'page arguments' => array('stanford_capx_admin_config_importer_delete', 5),
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/importer/sync/%'] = array(
'title' => 'Sync Importer',
'page callback' => 'stanford_capx_sync_importer',
'page arguments' => array(5),
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/importer/orphans/%'] = array(
'title' => 'Orphanator Importer',
'page callback' => 'stanford_capx_orphan_importer',
'page arguments' => array(5),
'access arguments' => array('administer capx'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/config/capx/importer/sync-all'] = array(
'title' => 'Sync All Importers',
'page callback' => 'stanford_capx_sync_all_importers',
'access arguments' => array('administer capx'),
'type' => MENU_CALLBACK,
);
// Profile pages
// ---------------------------------------------------------------------------
// In views now...
// MISC
// ---------------------------------------------------------------------------
$items['admin/config/capx/autocomplete/%'] = array(
'title' => 'Autocomplete Callback Endpoint',
'page callback' => 'stanford_capx_autocomplete',
'page arguments' => array(4),
'access arguments' => array('administer capx'),
'type' => MENU_CALLBACK,
);
$items['admin/config/capx/profile-update/%/%'] = array(
'title' => 'Force profile update callback',
'page callback' => 'stanford_capx_profile_update',
'page arguments' => array(4, 5),
'access arguments' => array('administer capx'),
'type' => MENU_CALLBACK,
);
$items['admin/config/capx/profile-sync/%/%'] = array(
'title' => 'Profile synchronization settings change callback',
'page callback' => 'stanford_capx_profile_sync_status',
'page arguments' => array(4, 5),
'access arguments' => array('administer capx'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_flush_caches().
*/
function stanford_capx_flush_caches() {
// Sort of hacky but this works...
variable_del("stanford_capx_admin_messages");
return array();
}
// Cron
// /////////////////////////////////////////////////////////////////////////////
/**
* Implements hook_cron().
*/
function stanford_capx_cron() {
// Call cron on all importers.
$importers = CAPxImporter::loadAllImporters();
foreach ($importers as $key => $importer) {
$entity_importer = CAPxImporter::loadEntityImporter($importer->identifier());
if ($entity_importer) {
$entity_importer->cron();
}
else {
$vars = array(
'%name' => $importer->identifier(),
);
watchdog('There was an issue loading the importer with %name machine name.', $vars, WATCHDOG_ERROR);
}
}
}
/**
* Implements hook_cron_queue_info().
*/
function stanford_capx_cron_queue_info() {
// A queue process for importing/sync profiles.
$queues['stanford_capx_profiles'] = array(
'worker callback' => 'stanford_capx_cron_queue_callback',
'time' => variable_get('stanford_capx_runtime_limit', 120),
'skip on cron' => FALSE,
);
// A queue process for finding and removing orphans.
$queues['stanford_capx_profile_orphans'] = array(
'worker callback' => 'stanford_capx_cron_orphan_queue_callback',
'time' => variable_get('stanford_capx_runtime_limit', 120),
'skip on cron' => FALSE,
);
return $queues;
}
/**
* Callback function.
*
* This function exists merely as a callback function as the static class
* function was not able to be called directly.
*
* @param array $item
* An array of item information to process.
*/
function stanford_capx_cron_queue_callback($item) {
EntityImporterBatch::queue($item);
}
/**
* Callback function.
*
* Callback function for creating and running the orphan functionality.
*
* @param array $item
* An array of item information to process.
* $item['importer']
* $item['profiles']
*/
function stanford_capx_cron_orphan_queue_callback($item) {
$orphanator = CAPxImporter::getEntityOrphanator($item['importer'], $item['profiles']);
if (!$orphanator) {
watchdog('stanford_capx_orphans', 'Could not load orphanator for %porter', array('%porter' => $item['importer']), WATCHDOG_WARNING);
return FALSE;
}
$orphanator->execute();
}
/**
* Passthrough function...
* @return [type] [description]
*/
function stanford_capx_orgs_batch_finished($success, $results, $operations) {
Orgs::syncOrganizationsBatchFinished($success, $results, $operations);
}
/**
* Batch finished callback
* @param [type] $success [description]
* @param [type] $results [description]
* @param [type] $operations [description]
* @return [type] [description]
*/
function stanford_capx_importer_batch_finished($success, $results, $operations) {
if ($success) {
drupal_set_message(t("Sync successfully completed."), "status");
}
else {
drupal_set_message(t("Sync failed. Please try again."), "error");
}
}
/**
* Batch finished callback.
* @param [type] $success [description]
* @param [type] $results [description]
* @param [type] $operations [description]
* @return [type] [description]
*/
function stanford_capx_orphan_check_batch_finished($success, $results, $operations) {
if ($success) {
drupal_set_message(t("Check for orphans completed."), "status");
}
else {
drupal_set_message(t("Check for orphans failed. Please try again."), "error");
}
}
// END CRON AND BATCH
// /////////////////////////////////////////////////////////////////////////////
// AUTOCOMPLETE
// /////////////////////////////////////////////////////////////////////////////
/**
* Autocomplete callback endpoint for organizations.
* @param string $type the type of autocomplete callback we are looking up.
* @param string $string the string that is in the autocomplete field.
* @return string
* Json results
*/
function stanford_capx_autocomplete($type, $string) {
$matches = array();
switch ($type) {
case "orgs":
$matches += stanford_capx_autocomplete_orgs($string);
break;
}
return drupal_json_output($matches);
}
/**
* Matches function for organization lookup.
*
* @param string $string
* $string the string that came from the autocomplete field.
*
* @return array
* An array of results
*/
function stanford_capx_autocomplete_orgs($string) {
$matches = array();
$items = array_map('trim', explode(',', $string));
$last_item = array_pop($items);
$prefix = implode(', ', $items);
// Two ways to look up an org. By org code or by name.
// Look for the exact code match.
$byname = taxonomy_get_term_by_name($last_item);
if (!empty($byname)) {
$option = array_pop($byname);
$value = !empty($prefix) ? $prefix . ', ' . $option->name : $option->name;
$matches[$value] = '[' . $option->name . '] ' . t(ucwords($option->description));
}
// If we have an exact match lets not go any further.
if ($matches) {
return $matches;
}
$vocab = Orgs::getVocabulary();
// Partial code lookup. eg: AAH for AAHH
// Partial name lookup. eg: Busi for Business and Operations.
$or = db_or()
->condition('name', db_like($last_item) . '%', 'LIKE')
->condition('description', db_like($last_item) . '%', 'LIKE');
$query = db_select('taxonomy_term_data', 'ttd')
->fields('ttd', array('tid', 'name', 'description'))
->condition($or)
->execute()
->fetchAll();
foreach ($query as $option) {
$value = !empty($prefix) ? $prefix . ', ' . $option->name : $option->name;
$matches[$value] = '[' . $option->name . '] ' . t(ucwords($option->description));
}
return $matches;
}
// END AUTOCOMPLETE
// /////////////////////////////////////////////////////////////////////////////
// SCHEMA (API)
// /////////////////////////////////////////////////////////////////////////////
/**
* Implements hook_schema_load.
* @param string $format the format type to return in.
* @param bool $reset A boolean value to reset the cache or not.
*
* @return string
* The file's contents.
*/
function stanford_capx_schema_load($format = 'json', $reset = FALSE) {
// If the directory doesn't exist, the file won't either.
if (!stanford_capx_files_dir_exists()) {
return FALSE;
}
$file = STANFORD_CAPX_FILE_PATH . "/" . STANFORD_CAPX_SCHEMA_FILE;
// @TODO: Refresh automatically under some condition? Weekly?
// If forcing a refesh or the schema hasn't been downloaded, download it!
if ($reset || !file_exists($file)) {
$file_contents = stanford_capx_schema_refresh();
}
else {
$file_contents = file_get_contents($file);
}
if (empty($file_contents)) {
return FALSE;
}
if ($format === 'object') {
$file_contents = json_decode($file_contents);
}
elseif ($format === 'array') {
$file_contents = json_decode($file_contents, TRUE);
}
return $file_contents;
}
/**
* Refresh the schema with fresh information from the API.
*
* @return mixed
* FALSE if failed or a json string if success.
*/
function stanford_capx_schema_refresh() {
$file = STANFORD_CAPX_FILE_PATH . "/" . STANFORD_CAPX_SCHEMA_FILE;
// Ensure the modules' private files directory exists and is writable.
if (stanford_capx_files_dir_exists()) {
// Query the API for the profile schema as raw JSON.
$client = CAPxConnection::getAuthenticatedHTTPClient();
$response = $client->api('schema')->getRaw('profile');
if (empty($response)) {
drupal_set_message(t("Error: Something went wrong. Could not update schema information. Please contact your site administrator."), "error");
return FALSE;
}
$schema = $response->getBody(TRUE);
// Cache the result in a private file.
if ($schema && !empty($schema)) {
file_unmanaged_save_data($schema, $file, FILE_EXISTS_REPLACE);
}
drupal_set_message(t("Schema information refreshed"), "status");
variable_set("capx_last_schema_sync", format_date(time()));
return $schema;
}
return FALSE;
}
/**
* Check to see if the private directory has been set up properly and is writable.
*
* @return bool
* TRUE if check passes FALSE if not
*/
function stanford_capx_files_dir_exists() {
$dir = STANFORD_CAPX_FILE_PATH;
// Ensure the modules' private files directory exists and is writable.
if (variable_get('file_private_path', FALSE) && file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
return TRUE;
}
// Display an error to the user.
$summary = t('The !directory must be configured for the CAPx module to work correctly.',
array('!directory' => l(t('private files directory'), 'admin/config/media/file-system')));
drupal_set_message($summary, 'error');
return FALSE;
}
/**
* Implements hook_init().
*
* Shows error messages to admin user on admin pages.
*/
function stanford_capx_init() {
$path = current_path();
if (user_access('administer capx') && path_is_admin($path) && $path != 'batch') {
// We don't want to set message on some forms
// submission because message get set before it's processed in the submit
// handler and this can confuse a user if this mapper was the last one that
// was affected by issue specified in the message.
$forms = array(
'stanford_capx_importer_form',
'stanford_capx_mapper_form',
);
if (empty($_POST['form_id']) || !in_array($_POST['form_id'], $forms)) {
$messages = variable_get('stanford_capx_admin_messages', array());
foreach ($messages as $key => $message) {
$formatted_message = format_string(
$message['text'],
isset($message['message_vars']) ? $message['message_vars'] : NULL
);
drupal_set_message($formatted_message, 'error', FALSE);
}
}
}
}
/**
* Sync profile page callback.
*
* Do profile synchronization in enforcing mode.
*
* @param int $profile_id
* Profile ID to sync.
* @param string $importer
* Importer machine name.
*/
function stanford_capx_profile_update($profile_id, $importer) {
$importer = CAPxImporter::loadEntityImporter($importer);
if (!$importer || !$importer->valid()) {
drupal_set_message(t('There was an error in importer validation.'));
return FALSE;
}
$client = $importer->getClient();
$profile = $client->api('profile')->get($profile_id);
// Allow altering of the results.
drupal_alter('capx_preprocess_profile_update', $profile, $importer);
$mapper = $importer->getMapper();
$processor = new EntityProcessor($mapper, $profile);
$processor->setEntityImporter($importer);
$processor->skipEtagCheck(TRUE);
$processor->execute(TRUE);
$message = $processor->getStatusMessage();
drupal_set_message($message);
// Log some information.
watchdog('stanford_capx_profile_force_update', check_plain($message) . " | " . check_plain($profile['displayName']), array(), WATCHDOG_INFO);
drupal_goto();
}
/**
* Page callback for changing profile sync status.
*
* @param int $id
* Internal profile ID.
*
* @param string $sync
* Synchronization operation. One from 'enable', 'disable'.
*/
function stanford_capx_profile_sync_status($id, $sync) {
$sync_value = NULL;
$message = "";
switch ($sync) {
case 'enable':
$sync_value = 1;
$message = t("Automatic updates ENABLED for this profile.");
break;
case 'disable':
$sync_value = 0;
$message = t("Automatic updates DISABLED for this profile.");
break;
}
if (isset($sync_value)) {
db_update('capx_profiles')
->condition('id', $id)
->fields(array('sync' => $sync_value))
->execute();
}
drupal_set_message($message, "status");
drupal_goto();
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function stanford_capx_form_user_profile_form_alter(&$form, &$form_state) {
global $user;
// Disable deletion of users synced from CAP.
if ($user->uid != 1 && isset($form_state['user']->capx) && !empty($form_state['user']->capx['sync'])) {
$form['actions']['cancel']['#disabled'] = TRUE;
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function stanford_capx_form_taxonomy_form_term_alter(&$form, &$form_state) {
global $user;
// Disable deletion of taxonomy terms synced from CAP.
if ($user->uid != 1 && isset($form_state['term']->capx) && !empty($form_state['term']->capx['sync'])) {
$form['actions']['delete']['#disabled'] = TRUE;
}
}