afform.php 16.1 KB
Newer Older
totten's avatar
totten committed
1
2
3
4
<?php

require_once 'afform.civix.php';
use CRM_Afform_ExtensionUtil as E;
5
use Civi\Api4\Action\Afform\Submit;
totten's avatar
totten committed
6

totten's avatar
totten committed
7
8
9
10
11
12
13
/**
 * Filter the content of $params to only have supported afform fields.
 *
 * @param array $params
 * @return array
 */
function _afform_fields_filter($params) {
colemanw's avatar
colemanw committed
14
  $result = [];
colemanw's avatar
colemanw committed
15
16
17
18
  $fields = \Civi\Api4\Afform::getfields()->setCheckPermissions(FALSE)->execute()->indexBy('name');
  foreach ($fields as $fieldName => $field) {
    if (isset($params[$fieldName])) {
      $result[$fieldName] = $params[$fieldName];
totten's avatar
totten committed
19
    }
totten's avatar
totten committed
20

colemanw's avatar
colemanw committed
21
22
    if (isset($result[$fieldName])) {
      switch ($fieldName) {
totten's avatar
totten committed
23
        case 'is_public':
colemanw's avatar
colemanw committed
24
          $result[$fieldName] = CRM_Utils_String::strtobool($result[$fieldName]);
totten's avatar
totten committed
25
26
27
28
          break;

      }
    }
totten's avatar
totten committed
29
30
31
32
  }
  return $result;
}

33
/**
colemanw's avatar
colemanw committed
34
 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
35
36
 */
function afform_civicrm_container($container) {
37
  $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
38
39
  $container->setDefinition('afform_scanner', new \Symfony\Component\DependencyInjection\Definition(
    'CRM_Afform_AfformScanner',
colemanw's avatar
colemanw committed
40
    []
41
42
43
  ));
}

totten's avatar
totten committed
44
45
46
47
48
49
50
/**
 * Implements hook_civicrm_config().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
 */
function afform_civicrm_config(&$config) {
  _afform_civix_civicrm_config($config);
51
52
53
54
55
56

  if (isset(Civi::$statics[__FUNCTION__])) {
    return;
  }
  Civi::$statics[__FUNCTION__] = 1;

57
58
  // Civi::dispatcher()->addListener(Submit::EVENT_NAME, [Submit::class, 'processContacts'], -500);
  Civi::dispatcher()->addListener(Submit::EVENT_NAME, [Submit::class, 'processGenericEntity'], -1000);
59
  Civi::dispatcher()->addListener('hook_civicrm_angularModules', '_afform_civicrm_angularModules_autoReq', -1000);
totten's avatar
totten committed
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
}

/**
 * Implements hook_civicrm_xmlMenu().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
 */
function afform_civicrm_xmlMenu(&$files) {
  _afform_civix_civicrm_xmlMenu($files);
}

/**
 * Implements hook_civicrm_install().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
 */
function afform_civicrm_install() {
  _afform_civix_civicrm_install();
}

/**
 * Implements hook_civicrm_postInstall().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall
 */
function afform_civicrm_postInstall() {
  _afform_civix_civicrm_postInstall();
}

/**
 * Implements hook_civicrm_uninstall().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
 */
function afform_civicrm_uninstall() {
  _afform_civix_civicrm_uninstall();
}

/**
 * Implements hook_civicrm_enable().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
 */
function afform_civicrm_enable() {
  _afform_civix_civicrm_enable();
}

/**
 * Implements hook_civicrm_disable().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
 */
function afform_civicrm_disable() {
  _afform_civix_civicrm_disable();
}

/**
 * Implements hook_civicrm_upgrade().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
 */
function afform_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
  return _afform_civix_civicrm_upgrade($op, $queue);
}

/**
 * Implements hook_civicrm_managed().
 *
 * Generate a list of entities to create/deactivate/delete when this module
 * is installed, disabled, uninstalled.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
 */
function afform_civicrm_managed(&$entities) {
  _afform_civix_civicrm_managed($entities);
}

/**
 * Implements hook_civicrm_caseTypes().
 *
 * Generate a list of case-types.
 *
 * Note: This hook only runs in CiviCRM 4.4+.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
 */
function afform_civicrm_caseTypes(&$caseTypes) {
  _afform_civix_civicrm_caseTypes($caseTypes);
}

/**
 * Implements hook_civicrm_angularModules().
 *
 * Generate a list of Angular modules.
 *
 * Note: This hook only runs in CiviCRM 4.5+. It may
 * use features only available in v4.6+.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_angularModules
 */
function afform_civicrm_angularModules(&$angularModules) {
  _afform_civix_civicrm_angularModules($angularModules);
162

163
  /** @var CRM_Afform_AfformScanner $scanner */
164
  $scanner = Civi::service('afform_scanner');
165
166
167
  $names = array_keys($scanner->findFilePaths());
  foreach ($names as $name) {
    $meta = $scanner->getMeta($name);
168
    $angularModules[_afform_angular_module_name($name, 'camel')] = [
169
170
171
172
      'ext' => E::LONG_NAME,
      'js' => ['assetBuilder://afform.js?name=' . urlencode($name)],
      'requires' => $meta['requires'],
      'basePages' => [],
totten's avatar
totten committed
173
174
      'partialsCallback' => '_afform_get_partials',
      '_afform' => $name,
175
      'exports' => [
176
        _afform_angular_module_name($name, 'dash') => 'AE',
177
      ],
178
179
    ];
  }
totten's avatar
totten committed
180
181
}

totten's avatar
totten committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/**
 * Construct a list of partials for a given afform/angular module.
 *
 * @param string $moduleName
 *   The module name.
 * @param array $module
 *   The module definition.
 * @return array
 *   Array(string $filename => string $html).
 */
function _afform_get_partials($moduleName, $module) {
  /** @var CRM_Afform_AfformScanner $scanner */
  $scanner = Civi::service('afform_scanner');
  return [
    "~/$moduleName/$moduleName.aff.html" => $scanner->getLayout($module['_afform']),
  ];
}

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
/**
 * Scan the list of Angular modules and inject automatic-requirements.
 *
 * TLDR: if an afform uses element "<other-el/>", and if another module defines
 * `$angularModules['otherMod']['exports']['el'][0] === 'other-el'`, then
 * the 'otherMod' is automatically required.
 *
 * @param \Civi\Core\Event\GenericHookEvent $e
 * @see CRM_Utils_Hook::angularModules()
 */
function _afform_civicrm_angularModules_autoReq($e) {
  /** @var CRM_Afform_AfformScanner $scanner */
  $scanner = Civi::service('afform_scanner');
  $moduleEnvId = md5(\CRM_Core_Config_Runtime::getId() . implode(',', array_keys($e->angularModules)));
  $depCache = CRM_Utils_Cache::create([
    'name' => 'afdep_' . substr($moduleEnvId, 0, 32 - 6),
    'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
    'withArray' => 'fast',
    'prefetch' => TRUE,
  ]);
  $depCacheTtl = 2 * 60 * 60;

  $revMap = _afform_reverse_deps($e->angularModules);

  $formNames = array_keys($scanner->findFilePaths());
  foreach ($formNames as $formName) {
    $angModule = _afform_angular_module_name($formName, 'camel');
    $cacheLine = $depCache->get($formName, NULL);

    $jFile = $scanner->findFilePath($formName, 'aff.json');
    $hFile = $scanner->findFilePath($formName, 'aff.html');

    $jStat = stat($jFile);
    $hStat = stat($hFile);

    if ($cacheLine === NULL) {
      $needsUpdate = TRUE;
    }
    elseif ($jStat !== FALSE && $jStat['size'] !== $cacheLine['js']) {
      $needsUpdate = TRUE;
    }
    elseif ($jStat !== FALSE && $jStat['mtime'] > $cacheLine['jm']) {
      $needsUpdate = TRUE;
    }
    elseif ($hStat !== FALSE && $hStat['size'] !== $cacheLine['hs']) {
      $needsUpdate = TRUE;
    }
    elseif ($hStat !== FALSE && $hStat['mtime'] > $cacheLine['hm']) {
      $needsUpdate = TRUE;
    }
    else {
      $needsUpdate = FALSE;
    }

    if ($needsUpdate) {
      $cacheLine = [
        'js' => $jStat['size'] ?? NULL,
        'jm' => $jStat['mtime'] ?? NULL,
        'hs' => $hStat['size'] ?? NULL,
        'hm' => $hStat['mtime'] ?? NULL,
        'r' => array_values(array_unique(array_merge(
          [CRM_Afform_AfformScanner::DEFAULT_REQUIRES],
          $e->angularModules[$angModule]['requires'] ?? [],
          _afform_reverse_deps_find($formName, file_get_contents($hFile), $revMap)
        ))),
      ];
      // print_r(['cache update:' . $formName => $cacheLine]);
      $depCache->set($formName, $cacheLine, $depCacheTtl);
    }

    $e->angularModules[$angModule]['requires'] = $cacheLine['r'];
  }
}

/**
 * @param $angularModules
 * @return array
 *   'attr': array(string $attrName => string $angModuleName)
 *   'el': array(string $elementName => string $angModuleName)
 */
function _afform_reverse_deps($angularModules) {
281
282
283
284
285
286
287
288
289
290
291
  $revMap = ['attr' => [], 'el' => []];
  foreach (array_keys($angularModules) as $module) {
    if (!isset($angularModules[$module]['exports'])) {
      continue;
    }
    foreach ($angularModules[$module]['exports'] as $symbolName => $symbolTypes) {
      if (strpos($symbolTypes, 'A') !== FALSE) {
        $revMap['attr'][$symbolName] = $module;
      }
      if (strpos($symbolTypes, 'E') !== FALSE) {
        $revMap['el'][$symbolName] = $module;
292
293
294
295
296
297
      }
    }
  }
  return $revMap;
}

298
299
300
301
302
303
304
305
/**
 * @param string $formName
 * @param string $html
 * @param array $revMap
 *   The reverse-dependencies map from _afform_reverse_deps().
 * @return array
 * @see _afform_reverse_deps()
 */
306
307
308
309
310
311
312
function _afform_reverse_deps_find($formName, $html, $revMap) {
  $symbols = \Civi\Afform\Symbols::scan($html);
  $elems = array_intersect_key($revMap['el'], $symbols->elements);
  $attrs = array_intersect_key($revMap['attr'], $symbols->attributes);
  return array_values(array_unique(array_merge($elems, $attrs)));
}

313
314
315
316
317
318
/**
 * @param \Civi\Angular\Manager $angular
 * @see CRM_Utils_Hook::alterAngular()
 */
function afform_civicrm_alterAngular($angular) {
  $fieldMetadata = \Civi\Angular\ChangeSet::create('fieldMetadata')
colemanw's avatar
colemanw committed
319
    ->alterHtml(';\\.aff\\.html$;', function($doc, $path) {
colemanw's avatar
colemanw committed
320
      $entities = _afform_getMetadata($doc);
321
322
323

      foreach (pq('af-field', $doc) as $afField) {
        /** @var DOMElement $afField */
324
        $fieldName = $afField->getAttribute('name');
325
        $entityName = pq($afField)->parents('[af-fieldset]')->attr('af-fieldset');
326
327
328
329
330
        if (!preg_match(';^[a-zA-Z0-9\_\-\. ]+$;', $entityName)) {
          throw new \CRM_Core_Exception("Cannot process $path: malformed entity name ($entityName)");
        }
        $entityType = $entities[$entityName]['type'];
        $getFields = civicrm_api4($entityType, 'getFields', [
colemanw's avatar
colemanw committed
331
          'action' => 'create',
332
          'where' => [['name', '=', $fieldName]],
colemanw's avatar
colemanw committed
333
          'select' => ['title', 'input_type', 'input_attrs', 'options'],
334
          'loadOptions' => TRUE,
335
        ]);
colemanw's avatar
colemanw committed
336
        // Merge field definition data with whatever's already in the markup
337
338
        $deep = ['input_attrs'];
        foreach ($getFields as $fieldInfo) {
339
          $existingFieldDefn = trim(pq($afField)->attr('defn') ?: '');
colemanw's avatar
colemanw committed
340
341
342
343
          if ($existingFieldDefn && $existingFieldDefn[0] != '{') {
            // If it's not an object, don't mess with it.
            continue;
          }
colemanw's avatar
colemanw committed
344
345
346
347
          // TODO: Teach the api to return options in this format
          if (!empty($fieldInfo['options'])) {
            $fieldInfo['options'] = CRM_Utils_Array::makeNonAssociative($fieldInfo['options'], 'key', 'label');
          }
348
349
350
351
          // Default placeholder for select inputs
          if ($fieldInfo['input_type'] === 'Select') {
            $fieldInfo['input_attrs'] = ($fieldInfo['input_attrs'] ?? []) + ['placeholder' => ts('Select')];
          }
colemanw's avatar
colemanw committed
352

353
354
355
356
357
358
359
360
361
          $fieldDefn = $existingFieldDefn ? CRM_Utils_JS::getRawProps($existingFieldDefn) : [];
          foreach ($fieldInfo as $name => $prop) {
            // Merge array props 1 level deep
            if (in_array($name, $deep) && !empty($fieldDefn[$name])) {
              $fieldDefn[$name] = CRM_Utils_JS::writeObject(CRM_Utils_JS::getRawProps($fieldDefn[$name]) + array_map(['CRM_Utils_JS', 'encode'], $prop));
            }
            elseif (!isset($fieldDefn[$name])) {
              $fieldDefn[$name] = CRM_Utils_JS::encode($prop);
            }
colemanw's avatar
colemanw committed
362
          }
363
          pq($afField)->attr('defn', htmlspecialchars(CRM_Utils_JS::writeObject($fieldDefn)));
364
365
366
367
368
369
370
371
        }
      }
    });
  $angular->add($fieldMetadata);
}

function _afform_getMetadata(phpQueryObject $doc) {
  $entities = [];
372
  foreach ($doc->find('af-entity') as $afmModelProp) {
373
    $entities[$afmModelProp->getAttribute('name')] = [
totten's avatar
totten committed
374
      'type' => $afmModelProp->getAttribute('type'),
375
376
377
378
379
    ];
  }
  return $entities;
}

totten's avatar
totten committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/**
 * Implements hook_civicrm_alterSettingsFolders().
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
 */
function afform_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
  _afform_civix_civicrm_alterSettingsFolders($metaDataFolders);
}

/**
 * Implements hook_civicrm_entityTypes().
 *
 * Declare entity types provided by this module.
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
 */
function afform_civicrm_entityTypes(&$entityTypes) {
  _afform_civix_civicrm_entityTypes($entityTypes);
}

400
401
402
403
404
405
406
/**
 * Implements hook_civicrm_themes().
 */
function afform_civicrm_themes(&$themes) {
  _afform_civix_civicrm_themes($themes);
}

totten's avatar
totten committed
407
408
// --- Functions below this ship commented out. Uncomment as required. ---

409
410
411
412
413
414
415
416
417
418
419
420
421
/**
 * Implements hook_civicrm_buildAsset().
 */
function afform_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
  if ($asset !== 'afform.js') {
    return;
  }

  if (empty($params['name'])) {
    throw new RuntimeException("Missing required parameter: afform.js?name=NAME");
  }

  $name = $params['name'];
totten's avatar
totten committed
422
  /** @var \CRM_Afform_AfformScanner $scanner */
423
  $scanner = Civi::service('afform_scanner');
424
  $meta = $scanner->getMeta($name);
totten's avatar
totten committed
425
  $moduleName = _afform_angular_module_name($name, 'camel');
426

427
428
  $smarty = CRM_Core_Smarty::singleton();
  $smarty->assign('afform', [
totten's avatar
totten committed
429
    'camel' => $moduleName,
430
    'meta' => $meta,
431
    'metaJson' => json_encode($meta),
totten's avatar
totten committed
432
    'templateUrl' => "~/$moduleName/$moduleName.aff.html",
433
434
  ]);
  $mimeType = 'text/javascript';
435
  $content = $smarty->fetch('afform/AfformAngularModule.tpl');
436
437
}

438
439
440
441
/**
 * Implements hook_civicrm_alterMenu().
 */
function afform_civicrm_alterMenu(&$items) {
442
443
444
445
446
447
448
  if (Civi::container()->has('afform_scanner')) {
    $scanner = Civi::service('afform_scanner');
  }
  else {
    // During installation...
    $scanner = new CRM_Afform_AfformScanner();
  }
449
450
451
452
453
  foreach ($scanner->getMetas() as $name => $meta) {
    if (!empty($meta['server_route'])) {
      $items[$meta['server_route']] = [
        'page_callback' => 'CRM_Afform_Page_AfformBase',
        'page_arguments' => 'afform=' . urlencode($name),
colemanw's avatar
colemanw committed
454
        'title' => $meta['title'] ?? '',
455
        'access_arguments' => [["@afform:$name"], 'and'],
456
        'is_public' => $meta['is_public'],
457
458
459
      ];
    }
  }
460
461
462
463
464
}

/**
 * Implements hook_civicrm_permission_check().
 *
465
466
467
468
469
470
471
 * This extends the list of permissions available in `CRM_Core_Permission:check()`
 * by introducing virtual-permissions named `@afform:myForm`. The evaluation
 * of these virtual-permissions is dependent on the settings for `myForm`.
 * `myForm` may be exposed/integrated through multiple subsystems (routing,
 * nav-menu, API, etc), and the use of virtual-permissions makes easy to enforce
 * consistent permissions across any relevant subsystems.
 *
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
 * @see CRM_Utils_Hook::permission_check()
 */
function afform_civicrm_permission_check($permission, &$granted, $contactId) {
  if ($permission{0} !== '@') {
    // Micro-optimization - this function may get hit a lot.
    return;
  }

  if (preg_match('/^@afform:(.*)/', $permission, $m)) {
    $name = $m[1];

    /** @var CRM_Afform_AfformScanner $scanner */
    $scanner = \Civi::container()->get('afform_scanner');
    $meta = $scanner->getMeta($name);
    $granted = CRM_Core_Permission::check($meta['permission'], $contactId);
  }
488
489
}

490
491
492
493
494
495
496
497
498
499
500
501
/**
 * Clear any local/in-memory caches based on afform data.
 */
function _afform_clear() {
  $container = \Civi::container();
  $container->get('afform_scanner')->clear();

  // Civi\Angular\Manager doesn't currently have a way to clear its in-memory
  // data, so we just reset the whole object.
  $container->set('angular', NULL);
}

502
/**
503
504
 * @param string $fileBaseName
 *   Ex: foo-bar
505
506
 * @param string $format
 *   'camel' or 'dash'.
507
 * @return string
508
 *   Ex: 'FooBar' or 'foo-bar'.
colemanw's avatar
colemanw committed
509
 * @throws \Exception
510
 */
511
function _afform_angular_module_name($fileBaseName, $format = 'camel') {
512
513
  switch ($format) {
    case 'camel':
514
515
516
517
518
      $camelCase = '';
      foreach (explode('-', $fileBaseName) as $shortNamePart) {
        $camelCase .= ucfirst($shortNamePart);
      }
      return strtolower($camelCase{0}) . substr($camelCase, 1);
519
520

    case 'dash':
521
      return strtolower(implode('-', array_filter(preg_split('/(?=[A-Z])/', $fileBaseName))));
522
523
524
525

    default:
      throw new \Exception("Unrecognized format");
  }
526
}