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);
55 Civi
::dispatcher()->addListener('hook_civicrm_alterAngular', ['\Civi\Afform\AfformMetadataInjector', 'preprocess']);
59 * Implements hook_civicrm_xmlMenu().
61 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
63 function afform_civicrm_xmlMenu(&$files) {
64 _afform_civix_civicrm_xmlMenu($files);
68 * Implements hook_civicrm_install().
70 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
72 function afform_civicrm_install() {
73 _afform_civix_civicrm_install();
77 * Implements hook_civicrm_postInstall().
79 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall
81 function afform_civicrm_postInstall() {
82 _afform_civix_civicrm_postInstall();
86 * Implements hook_civicrm_uninstall().
88 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
90 function afform_civicrm_uninstall() {
91 _afform_civix_civicrm_uninstall();
95 * Implements hook_civicrm_enable().
97 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
99 function afform_civicrm_enable() {
100 _afform_civix_civicrm_enable();
104 * Implements hook_civicrm_disable().
106 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
108 function afform_civicrm_disable() {
109 _afform_civix_civicrm_disable();
113 * Implements hook_civicrm_upgrade().
115 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
117 function afform_civicrm_upgrade($op, CRM_Queue_Queue
$queue = NULL) {
118 return _afform_civix_civicrm_upgrade($op, $queue);
122 * Implements hook_civicrm_managed().
124 * Generate a list of entities to create/deactivate/delete when this module
125 * is installed, disabled, uninstalled.
127 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
129 function afform_civicrm_managed(&$entities) {
130 _afform_civix_civicrm_managed($entities);
132 /** @var \CRM_Afform_AfformScanner $scanner */
133 if (\Civi
::container()->has('afform_scanner')) {
134 $scanner = \Civi
::service('afform_scanner');
137 // This might happen at oddballs points - e.g. while you're in the middle of re-enabling the ext.
138 // This AfformScanner instance only lives during this method call, and it feeds off the regular cache.
139 $scanner = new CRM_Afform_AfformScanner();
142 foreach ($scanner->getMetas() as $afform) {
143 if (empty($afform['is_dashlet']) ||
empty($afform['name'])) {
147 'module' => E
::LONG_NAME
,
148 'name' => 'afform_dashlet_' . $afform['name'],
149 'entity' => 'Dashboard',
150 'update' => 'always',
151 // ideal cleanup policy might be to (a) deactivate if used and (b) remove if unused
152 'cleanup' => 'always',
155 // Q: Should we loop through all domains?
156 'domain_id' => CRM_Core_BAO_Domain
::getDomain()->id
,
158 'name' => $afform['name'],
159 'label' => $afform['title'] ??
ts('(Untitled)'),
160 'directive' => _afform_angular_module_name($afform['name'], 'dash'),
161 'permission' => "@afform:" . $afform['name'],
168 * Implements hook_civicrm_caseTypes().
170 * Generate a list of case-types.
172 * Note: This hook only runs in CiviCRM 4.4+.
174 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
176 function afform_civicrm_caseTypes(&$caseTypes) {
177 _afform_civix_civicrm_caseTypes($caseTypes);
181 * Implements hook_civicrm_angularModules().
183 * Generate a list of Afform Angular modules.
185 function afform_civicrm_angularModules(&$angularModules) {
186 _afform_civix_civicrm_angularModules($angularModules);
188 $afforms = \Civi\Api4\Afform
::get(FALSE)
189 ->setSelect(['name', 'requires', 'module_name', 'directive_name'])
192 foreach ($afforms as $afform) {
193 $angularModules[$afform['module_name']] = [
194 'ext' => E
::LONG_NAME
,
195 'js' => ['assetBuilder://afform.js?name=' . urlencode($afform['name'])],
196 'requires' => $afform['requires'],
198 'partialsCallback' => '_afform_get_partials',
199 '_afform' => $afform['name'],
201 $afform['directive_name'] => 'E',
208 * Callback to retrieve partials for a given afform/angular module.
210 * @see afform_civicrm_angularModules
212 * @param string $moduleName
214 * @param array $module
215 * The module definition.
217 * Array(string $filename => string $html).
218 * @throws API_Exception
220 function _afform_get_partials($moduleName, $module) {
221 $afform = civicrm_api4('Afform', 'get', [
222 'where' => [['name', '=', $module['_afform']]],
223 'select' => ['layout'],
224 'layoutFormat' => 'html',
225 'checkPermissions' => FALSE,
228 "~/$moduleName/$moduleName.aff.html" => $afform['layout'],
233 * Scan the list of Angular modules and inject automatic-requirements.
235 * TLDR: if an afform uses element "<other-el/>", and if another module defines
236 * `$angularModules['otherMod']['exports']['el'][0] === 'other-el'`, then
237 * the 'otherMod' is automatically required.
239 * @param \Civi\Core\Event\GenericHookEvent $e
240 * @see CRM_Utils_Hook::angularModules()
242 function _afform_civicrm_angularModules_autoReq($e) {
243 /** @var CRM_Afform_AfformScanner $scanner */
244 $scanner = Civi
::service('afform_scanner');
245 $moduleEnvId = md5(\CRM_Core_Config_Runtime
::getId() . implode(',', array_keys($e->angularModules
)));
246 $depCache = CRM_Utils_Cache
::create([
247 'name' => 'afdep_' . substr($moduleEnvId, 0, 32 - 6),
248 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
249 'withArray' => 'fast',
252 $depCacheTtl = 2 * 60 * 60;
254 $revMap = _afform_reverse_deps($e->angularModules
);
256 $formNames = array_keys($scanner->findFilePaths());
257 foreach ($formNames as $formName) {
258 $angModule = _afform_angular_module_name($formName, 'camel');
259 $cacheLine = $depCache->get($formName, NULL);
261 $jFile = $scanner->findFilePath($formName, 'aff.json');
262 $hFile = $scanner->findFilePath($formName, 'aff.html');
264 $jStat = stat($jFile);
265 $hStat = stat($hFile);
267 if ($cacheLine === NULL) {
270 elseif ($jStat !== FALSE && $jStat['size'] !== $cacheLine['js']) {
273 elseif ($jStat !== FALSE && $jStat['mtime'] > $cacheLine['jm']) {
276 elseif ($hStat !== FALSE && $hStat['size'] !== $cacheLine['hs']) {
279 elseif ($hStat !== FALSE && $hStat['mtime'] > $cacheLine['hm']) {
283 $needsUpdate = FALSE;
288 'js' => $jStat['size'] ??
NULL,
289 'jm' => $jStat['mtime'] ??
NULL,
290 'hs' => $hStat['size'] ??
NULL,
291 'hm' => $hStat['mtime'] ??
NULL,
292 'r' => array_values(array_unique(array_merge(
293 [CRM_Afform_AfformScanner
::DEFAULT_REQUIRES
],
294 $e->angularModules
[$angModule]['requires'] ??
[],
295 _afform_reverse_deps_find($formName, file_get_contents($hFile), $revMap)
298 // print_r(['cache update:' . $formName => $cacheLine]);
299 $depCache->set($formName, $cacheLine, $depCacheTtl);
302 $e->angularModules
[$angModule]['requires'] = $cacheLine['r'];
307 * @param $angularModules
309 * 'attr': array(string $attrName => string $angModuleName)
310 * 'el': array(string $elementName => string $angModuleName)
312 function _afform_reverse_deps($angularModules) {
313 $revMap = ['attr' => [], 'el' => []];
314 foreach (array_keys($angularModules) as $module) {
315 if (!isset($angularModules[$module]['exports'])) {
318 foreach ($angularModules[$module]['exports'] as $symbolName => $symbolTypes) {
319 if (strpos($symbolTypes, 'A') !== FALSE) {
320 $revMap['attr'][$symbolName] = $module;
322 if (strpos($symbolTypes, 'E') !== FALSE) {
323 $revMap['el'][$symbolName] = $module;
331 * @param string $formName
332 * @param string $html
333 * @param array $revMap
334 * The reverse-dependencies map from _afform_reverse_deps().
336 * @see _afform_reverse_deps()
338 function _afform_reverse_deps_find($formName, $html, $revMap) {
339 $symbols = \Civi\Afform\Symbols
::scan($html);
340 $elems = array_intersect_key($revMap['el'], $symbols->elements
);
341 $attrs = array_intersect_key($revMap['attr'], $symbols->attributes
);
342 return array_values(array_unique(array_merge($elems, $attrs)));
346 * Implements hook_civicrm_alterSettingsFolders().
348 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
350 function afform_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
351 _afform_civix_civicrm_alterSettingsFolders($metaDataFolders);
355 * Implements hook_civicrm_entityTypes().
357 * Declare entity types provided by this module.
359 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
361 function afform_civicrm_entityTypes(&$entityTypes) {
362 _afform_civix_civicrm_entityTypes($entityTypes);
366 * Implements hook_civicrm_themes().
368 function afform_civicrm_themes(&$themes) {
369 _afform_civix_civicrm_themes($themes);
373 * Implements hook_civicrm_buildAsset().
375 function afform_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
376 if ($asset !== 'afform.js') {
380 if (empty($params['name'])) {
381 throw new RuntimeException("Missing required parameter: afform.js?name=NAME");
384 $moduleName = _afform_angular_module_name($params['name'], 'camel');
385 $smarty = CRM_Core_Smarty
::singleton();
386 $smarty->assign('afform', [
387 'camel' => $moduleName,
388 'meta' => ['name' => $params['name']],
389 'templateUrl' => "~/$moduleName/$moduleName.aff.html",
391 $mimeType = 'text/javascript';
392 $content = $smarty->fetch('afform/AfformAngularModule.tpl');
396 * Implements hook_civicrm_alterMenu().
398 function afform_civicrm_alterMenu(&$items) {
399 if (Civi
::container()->has('afform_scanner')) {
400 $scanner = Civi
::service('afform_scanner');
403 // During installation...
404 $scanner = new CRM_Afform_AfformScanner();
406 foreach ($scanner->getMetas() as $name => $meta) {
407 if (!empty($meta['server_route'])) {
408 $items[$meta['server_route']] = [
409 'page_callback' => 'CRM_Afform_Page_AfformBase',
410 'page_arguments' => 'afform=' . urlencode($name),
411 'title' => $meta['title'] ??
'',
412 'access_arguments' => [["@afform:$name"], 'and'],
413 'is_public' => $meta['is_public'],
420 * Implements hook_civicrm_permission_check().
422 * This extends the list of permissions available in `CRM_Core_Permission:check()`
423 * by introducing virtual-permissions named `@afform:myForm`. The evaluation
424 * of these virtual-permissions is dependent on the settings for `myForm`.
425 * `myForm` may be exposed/integrated through multiple subsystems (routing,
426 * nav-menu, API, etc), and the use of virtual-permissions makes easy to enforce
427 * consistent permissions across any relevant subsystems.
429 * @see CRM_Utils_Hook::permission_check()
431 function afform_civicrm_permission_check($permission, &$granted, $contactId) {
432 if ($permission[0] !== '@') {
433 // Micro-optimization - this function may get hit a lot.
437 if (preg_match('/^@afform:(.*)/', $permission, $m)) {
440 $afform = \Civi\Api4\Afform
::get()
441 ->setCheckPermissions(FALSE)
442 ->addWhere('name', '=', $name)
443 ->setSelect(['permission'])
447 $granted = CRM_Core_Permission
::check($afform['permission'], $contactId);
453 * Implements hook_civicrm_permissionList().
455 * @see CRM_Utils_Hook::permissionList()
457 function afform_civicrm_permissionList(&$permissions) {
458 $scanner = Civi
::service('afform_scanner');
459 foreach ($scanner->getMetas() as $name => $meta) {
460 $permissions['@afform:' . $name] = [
462 'title' => ts('Afform: Inherit permission of %1', [
470 * Clear any local/in-memory caches based on afform data.
472 function _afform_clear() {
473 $container = \Civi
::container();
474 $container->get('afform_scanner')->clear();
475 $container->get('angular')->clear();
479 * @param string $fileBaseName
481 * @param string $format
484 * Ex: 'FooBar' or 'foo-bar'.
487 function _afform_angular_module_name($fileBaseName, $format = 'camel') {
491 foreach (preg_split('/[-_ ]/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY
) as $shortNamePart) {
492 $camelCase .= ucfirst($shortNamePart);
494 return strtolower($camelCase[0]) . substr($camelCase, 1);
497 return strtolower(implode('-', preg_split('/[-_ ]|(?=[A-Z])/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
)));
500 throw new \
Exception("Unrecognized format");