3 require_once 'afform.civix.php';
4 use CRM_Afform_ExtensionUtil
as E
;
5 use Civi\Api4\Action\Afform\Submit
;
8 * Filter the content of $params to only have supported afform fields.
10 * @param array $params
13 function _afform_fields_filter($params) {
15 $fields = \Civi\Api4\Afform
::getfields()->setCheckPermissions(FALSE)->setAction('create')->execute()->indexBy('name');
16 foreach ($fields as $fieldName => $field) {
17 if (isset($params[$fieldName])) {
18 $result[$fieldName] = $params[$fieldName];
20 if ($field['data_type'] === 'Boolean' && !is_bool($params[$fieldName])) {
21 $result[$fieldName] = CRM_Utils_String
::strtobool($params[$fieldName]);
29 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
31 function afform_civicrm_container($container) {
32 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
33 $container->setDefinition('afform_scanner', new \Symfony\Component\DependencyInjection\
Definition(
34 'CRM_Afform_AfformScanner',
40 * Implements hook_civicrm_config().
42 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
44 function afform_civicrm_config(&$config) {
45 _afform_civix_civicrm_config($config);
47 if (isset(Civi
::$statics[__FUNCTION__
])) {
50 Civi
::$statics[__FUNCTION__
] = 1;
52 Civi
::dispatcher()->addListener(Submit
::EVENT_NAME
, [Submit
::class, 'processContacts'], 500);
53 Civi
::dispatcher()->addListener(Submit
::EVENT_NAME
, [Submit
::class, 'processGenericEntity'], -1000);
54 Civi
::dispatcher()->addListener('hook_civicrm_angularModules', '_afform_civicrm_angularModules_autoReq', -1000);
58 * Implements hook_civicrm_xmlMenu().
60 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
62 function afform_civicrm_xmlMenu(&$files) {
63 _afform_civix_civicrm_xmlMenu($files);
67 * Implements hook_civicrm_install().
69 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
71 function afform_civicrm_install() {
72 _afform_civix_civicrm_install();
76 * Implements hook_civicrm_postInstall().
78 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall
80 function afform_civicrm_postInstall() {
81 _afform_civix_civicrm_postInstall();
85 * Implements hook_civicrm_uninstall().
87 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
89 function afform_civicrm_uninstall() {
90 _afform_civix_civicrm_uninstall();
94 * Implements hook_civicrm_enable().
96 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
98 function afform_civicrm_enable() {
99 _afform_civix_civicrm_enable();
103 * Implements hook_civicrm_disable().
105 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
107 function afform_civicrm_disable() {
108 _afform_civix_civicrm_disable();
112 * Implements hook_civicrm_upgrade().
114 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
116 function afform_civicrm_upgrade($op, CRM_Queue_Queue
$queue = NULL) {
117 return _afform_civix_civicrm_upgrade($op, $queue);
121 * Implements hook_civicrm_managed().
123 * Generate a list of entities to create/deactivate/delete when this module
124 * is installed, disabled, uninstalled.
126 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
128 function afform_civicrm_managed(&$entities) {
129 _afform_civix_civicrm_managed($entities);
131 /** @var \CRM_Afform_AfformScanner $scanner */
132 if (\Civi
::container()->has('afform_scanner')) {
133 $scanner = \Civi
::service('afform_scanner');
136 // This might happen at oddballs points - e.g. while you're in the middle of re-enabling the ext.
137 // This AfformScanner instance only lives during this method call, and it feeds off the regular cache.
138 $scanner = new CRM_Afform_AfformScanner();
141 foreach ($scanner->getMetas() as $afform) {
142 if (empty($afform['is_dashlet']) ||
empty($afform['name'])) {
146 'module' => E
::LONG_NAME
,
147 'name' => 'afform_dashlet_' . $afform['name'],
148 'entity' => 'Dashboard',
149 'update' => 'always',
150 // ideal cleanup policy might be to (a) deactivate if used and (b) remove if unused
151 'cleanup' => 'always',
154 // Q: Should we loop through all domains?
155 'domain_id' => CRM_Core_BAO_Domain
::getDomain()->id
,
157 'name' => $afform['name'],
158 'label' => $afform['title'] ??
ts('(Untitled)'),
159 'directive' => _afform_angular_module_name($afform['name'], 'dash'),
160 'permission' => "@afform:" . $afform['name'],
167 * Implements hook_civicrm_caseTypes().
169 * Generate a list of case-types.
171 * Note: This hook only runs in CiviCRM 4.4+.
173 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
175 function afform_civicrm_caseTypes(&$caseTypes) {
176 _afform_civix_civicrm_caseTypes($caseTypes);
180 * Implements hook_civicrm_angularModules().
182 * Generate a list of Afform Angular modules.
184 function afform_civicrm_angularModules(&$angularModules) {
185 _afform_civix_civicrm_angularModules($angularModules);
187 $afforms = \Civi\Api4\Afform
::get(FALSE)
188 ->setSelect(['name', 'requires', 'module_name', 'directive_name'])
191 foreach ($afforms as $afform) {
192 $angularModules[$afform['module_name']] = [
193 'ext' => E
::LONG_NAME
,
194 'js' => ['assetBuilder://afform.js?name=' . urlencode($afform['name'])],
195 'requires' => $afform['requires'],
197 'partialsCallback' => '_afform_get_partials',
198 '_afform' => $afform['name'],
200 $afform['directive_name'] => 'AE',
207 * Callback to retrieve partials for a given afform/angular module.
209 * @see afform_civicrm_angularModules
211 * @param string $moduleName
213 * @param array $module
214 * The module definition.
216 * Array(string $filename => string $html).
217 * @throws API_Exception
219 function _afform_get_partials($moduleName, $module) {
220 $afform = civicrm_api4('Afform', 'get', [
221 'where' => [['name', '=', $module['_afform']]],
222 'select' => ['layout'],
223 'layoutFormat' => 'html',
224 'checkPermissions' => FALSE,
227 "~/$moduleName/$moduleName.aff.html" => $afform['layout'],
232 * Scan the list of Angular modules and inject automatic-requirements.
234 * TLDR: if an afform uses element "<other-el/>", and if another module defines
235 * `$angularModules['otherMod']['exports']['el'][0] === 'other-el'`, then
236 * the 'otherMod' is automatically required.
238 * @param \Civi\Core\Event\GenericHookEvent $e
239 * @see CRM_Utils_Hook::angularModules()
241 function _afform_civicrm_angularModules_autoReq($e) {
242 /** @var CRM_Afform_AfformScanner $scanner */
243 $scanner = Civi
::service('afform_scanner');
244 $moduleEnvId = md5(\CRM_Core_Config_Runtime
::getId() . implode(',', array_keys($e->angularModules
)));
245 $depCache = CRM_Utils_Cache
::create([
246 'name' => 'afdep_' . substr($moduleEnvId, 0, 32 - 6),
247 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
248 'withArray' => 'fast',
251 $depCacheTtl = 2 * 60 * 60;
253 $revMap = _afform_reverse_deps($e->angularModules
);
255 $formNames = array_keys($scanner->findFilePaths());
256 foreach ($formNames as $formName) {
257 $angModule = _afform_angular_module_name($formName, 'camel');
258 $cacheLine = $depCache->get($formName, NULL);
260 $jFile = $scanner->findFilePath($formName, 'aff.json');
261 $hFile = $scanner->findFilePath($formName, 'aff.html');
263 $jStat = stat($jFile);
264 $hStat = stat($hFile);
266 if ($cacheLine === NULL) {
269 elseif ($jStat !== FALSE && $jStat['size'] !== $cacheLine['js']) {
272 elseif ($jStat !== FALSE && $jStat['mtime'] > $cacheLine['jm']) {
275 elseif ($hStat !== FALSE && $hStat['size'] !== $cacheLine['hs']) {
278 elseif ($hStat !== FALSE && $hStat['mtime'] > $cacheLine['hm']) {
282 $needsUpdate = FALSE;
287 'js' => $jStat['size'] ??
NULL,
288 'jm' => $jStat['mtime'] ??
NULL,
289 'hs' => $hStat['size'] ??
NULL,
290 'hm' => $hStat['mtime'] ??
NULL,
291 'r' => array_values(array_unique(array_merge(
292 [CRM_Afform_AfformScanner
::DEFAULT_REQUIRES
],
293 $e->angularModules
[$angModule]['requires'] ??
[],
294 _afform_reverse_deps_find($formName, file_get_contents($hFile), $revMap)
297 // print_r(['cache update:' . $formName => $cacheLine]);
298 $depCache->set($formName, $cacheLine, $depCacheTtl);
301 $e->angularModules
[$angModule]['requires'] = $cacheLine['r'];
306 * @param $angularModules
308 * 'attr': array(string $attrName => string $angModuleName)
309 * 'el': array(string $elementName => string $angModuleName)
311 function _afform_reverse_deps($angularModules) {
312 $revMap = ['attr' => [], 'el' => []];
313 foreach (array_keys($angularModules) as $module) {
314 if (!isset($angularModules[$module]['exports'])) {
317 foreach ($angularModules[$module]['exports'] as $symbolName => $symbolTypes) {
318 if (strpos($symbolTypes, 'A') !== FALSE) {
319 $revMap['attr'][$symbolName] = $module;
321 if (strpos($symbolTypes, 'E') !== FALSE) {
322 $revMap['el'][$symbolName] = $module;
330 * @param string $formName
331 * @param string $html
332 * @param array $revMap
333 * The reverse-dependencies map from _afform_reverse_deps().
335 * @see _afform_reverse_deps()
337 function _afform_reverse_deps_find($formName, $html, $revMap) {
338 $symbols = \Civi\Afform\Symbols
::scan($html);
339 $elems = array_intersect_key($revMap['el'], $symbols->elements
);
340 $attrs = array_intersect_key($revMap['attr'], $symbols->attributes
);
341 return array_values(array_unique(array_merge($elems, $attrs)));
345 * @param \Civi\Angular\Manager $angular
346 * @see CRM_Utils_Hook::alterAngular()
348 function afform_civicrm_alterAngular($angular) {
349 $fieldMetadata = \Civi\Angular\ChangeSet
::create('fieldMetadata')
350 ->alterHtml(';\\.aff\\.html$;', function($doc, $path) {
352 $module = \Civi
::service('angular')->getModule(basename($path, '.aff.html'));
353 $meta = \Civi\Api4\Afform
::get()->addWhere('name', '=', $module['_afform'])->setSelect(['join', 'block'])->setCheckPermissions(FALSE)->execute()->first();
355 catch (Exception
$e) {
358 $blockEntity = $meta['join'] ??
$meta['block'] ??
NULL;
360 $entities = _afform_getMetadata($doc);
363 foreach (pq('af-field', $doc) as $afField) {
364 /** @var DOMElement $afField */
365 $entityName = pq($afField)->parents('[af-fieldset]')->attr('af-fieldset');
366 $joinName = pq($afField)->parents('[af-join]')->attr('af-join');
367 if (!$blockEntity && !preg_match(';^[a-zA-Z0-9\_\-\. ]+$;', $entityName)) {
368 throw new \
CRM_Core_Exception("Cannot process $path: malformed entity name ($entityName)");
370 $entityType = $blockEntity ??
$entities[$entityName]['type'];
371 _af_fill_field_metadata($joinName ?
$joinName : $entityType, $afField);
374 $angular->add($fieldMetadata);
378 * Merge field definition metadata into an afform field's definition
381 * @param DOMElement $afField
382 * @throws API_Exception
384 function _af_fill_field_metadata($entityType, DOMElement
$afField) {
386 'action' => 'create',
387 'where' => [['name', '=', $afField->getAttribute('name')]],
388 'select' => ['label', 'input_type', 'input_attrs', 'options'],
389 'loadOptions' => TRUE,
391 if (in_array($entityType, CRM_Contact_BAO_ContactType
::basicTypes(TRUE))) {
392 $params['values'] = ['contact_type' => $entityType];
393 $entityType = 'Contact';
395 // Merge field definition data with whatever's already in the markup.
396 // If the admin has chosen to include this field on the form, then it's OK for us to get metadata about the field - regardless of user's other permissions.
397 $getFields = civicrm_api4($entityType, 'getFields', $params +
['checkPermissions' => FALSE]);
398 $deep = ['input_attrs'];
399 foreach ($getFields as $fieldInfo) {
400 $existingFieldDefn = trim(pq($afField)->attr('defn') ?
: '');
401 if ($existingFieldDefn && $existingFieldDefn[0] != '{') {
402 // If it's not an object, don't mess with it.
405 // TODO: Teach the api to return options in this format
406 if (!empty($fieldInfo['options'])) {
407 $fieldInfo['options'] = CRM_Utils_Array
::makeNonAssociative($fieldInfo['options'], 'key', 'label');
409 // Default placeholder for select inputs
410 if ($fieldInfo['input_type'] === 'Select') {
411 $fieldInfo['input_attrs'] = ($fieldInfo['input_attrs'] ??
[]) +
['placeholder' => ts('Select')];
414 $fieldDefn = $existingFieldDefn ? CRM_Utils_JS
::getRawProps($existingFieldDefn) : [];
415 foreach ($fieldInfo as $name => $prop) {
416 // Merge array props 1 level deep
417 if (in_array($name, $deep) && !empty($fieldDefn[$name])) {
418 $fieldDefn[$name] = CRM_Utils_JS
::writeObject(CRM_Utils_JS
::getRawProps($fieldDefn[$name]) +
array_map(['CRM_Utils_JS', 'encode'], $prop));
420 elseif (!isset($fieldDefn[$name])) {
421 $fieldDefn[$name] = CRM_Utils_JS
::encode($prop);
424 pq($afField)->attr('defn', htmlspecialchars(CRM_Utils_JS
::writeObject($fieldDefn)));
428 function _afform_getMetadata(phpQueryObject
$doc) {
430 foreach ($doc->find('af-entity') as $afmModelProp) {
431 $entities[$afmModelProp->getAttribute('name')] = [
432 'type' => $afmModelProp->getAttribute('type'),
439 * Implements hook_civicrm_alterSettingsFolders().
441 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
443 function afform_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
444 _afform_civix_civicrm_alterSettingsFolders($metaDataFolders);
448 * Implements hook_civicrm_entityTypes().
450 * Declare entity types provided by this module.
452 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
454 function afform_civicrm_entityTypes(&$entityTypes) {
455 _afform_civix_civicrm_entityTypes($entityTypes);
459 * Implements hook_civicrm_themes().
461 function afform_civicrm_themes(&$themes) {
462 _afform_civix_civicrm_themes($themes);
466 * Implements hook_civicrm_buildAsset().
468 function afform_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
469 if ($asset !== 'afform.js') {
473 if (empty($params['name'])) {
474 throw new RuntimeException("Missing required parameter: afform.js?name=NAME");
477 $moduleName = _afform_angular_module_name($params['name'], 'camel');
478 $smarty = CRM_Core_Smarty
::singleton();
479 $smarty->assign('afform', [
480 'camel' => $moduleName,
481 'meta' => ['name' => $params['name']],
482 'templateUrl' => "~/$moduleName/$moduleName.aff.html",
484 $mimeType = 'text/javascript';
485 $content = $smarty->fetch('afform/AfformAngularModule.tpl');
489 * Implements hook_civicrm_alterMenu().
491 function afform_civicrm_alterMenu(&$items) {
492 if (Civi
::container()->has('afform_scanner')) {
493 $scanner = Civi
::service('afform_scanner');
496 // During installation...
497 $scanner = new CRM_Afform_AfformScanner();
499 foreach ($scanner->getMetas() as $name => $meta) {
500 if (!empty($meta['server_route'])) {
501 $items[$meta['server_route']] = [
502 'page_callback' => 'CRM_Afform_Page_AfformBase',
503 'page_arguments' => 'afform=' . urlencode($name),
504 'title' => $meta['title'] ??
'',
505 'access_arguments' => [["@afform:$name"], 'and'],
506 'is_public' => $meta['is_public'],
513 * Implements hook_civicrm_permission_check().
515 * This extends the list of permissions available in `CRM_Core_Permission:check()`
516 * by introducing virtual-permissions named `@afform:myForm`. The evaluation
517 * of these virtual-permissions is dependent on the settings for `myForm`.
518 * `myForm` may be exposed/integrated through multiple subsystems (routing,
519 * nav-menu, API, etc), and the use of virtual-permissions makes easy to enforce
520 * consistent permissions across any relevant subsystems.
522 * @see CRM_Utils_Hook::permission_check()
524 function afform_civicrm_permission_check($permission, &$granted, $contactId) {
525 if ($permission[0] !== '@') {
526 // Micro-optimization - this function may get hit a lot.
530 if (preg_match('/^@afform:(.*)/', $permission, $m)) {
533 $afform = \Civi\Api4\Afform
::get()
534 ->setCheckPermissions(FALSE)
535 ->addWhere('name', '=', $name)
536 ->setSelect(['permission'])
540 $granted = CRM_Core_Permission
::check($afform['permission'], $contactId);
546 * Clear any local/in-memory caches based on afform data.
548 function _afform_clear() {
549 $container = \Civi
::container();
550 $container->get('afform_scanner')->clear();
551 $container->get('angular')->clear();
555 * @param string $fileBaseName
557 * @param string $format
560 * Ex: 'FooBar' or 'foo-bar'.
563 function _afform_angular_module_name($fileBaseName, $format = 'camel') {
567 foreach (preg_split('/[-_ ]/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY
) as $shortNamePart) {
568 $camelCase .= ucfirst($shortNamePart);
570 return strtolower($camelCase[0]) . substr($camelCase, 1);
573 return strtolower(implode('-', preg_split('/[-_ ]|(?=[A-Z])/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
)));
576 throw new \
Exception("Unrecognized format");