3 require_once 'afform.civix.php';
4 use CRM_Afform_ExtensionUtil
as E
;
7 * Filter the content of $params to only have supported afform fields.
12 function _afform_fields_filter($params) {
14 $fields = \Civi\Api4\Afform
::getfields(FALSE)->setAction('create')->execute()->indexBy('name');
15 foreach ($fields as $fieldName => $field) {
16 if (isset($params[$fieldName])) {
17 $result[$fieldName] = $params[$fieldName];
19 if ($field['data_type'] === 'Boolean' && !is_bool($params[$fieldName])) {
20 $result[$fieldName] = CRM_Utils_String
::strtobool($params[$fieldName]);
28 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
30 function afform_civicrm_container($container) {
31 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
32 $container->setDefinition('afform_scanner', new \Symfony\Component\DependencyInjection\
Definition(
33 'CRM_Afform_AfformScanner',
39 * Implements hook_civicrm_config().
41 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
43 function afform_civicrm_config(&$config) {
44 _afform_civix_civicrm_config($config);
46 if (isset(Civi
::$statics[__FUNCTION__
])) {
49 Civi
::$statics[__FUNCTION__
] = 1;
51 $dispatcher = Civi
::dispatcher();
52 $dispatcher->addListener('civi.afform.submit', ['\Civi\Api4\Action\Afform\Submit', 'processGenericEntity'], 0);
53 $dispatcher->addListener('civi.afform.submit', ['\Civi\Api4\Action\Afform\Submit', 'preprocessContact'], 10);
54 $dispatcher->addListener('civi.afform.submit', ['\Civi\Api4\Action\Afform\Submit', 'processRelationships'], 1);
55 $dispatcher->addListener('hook_civicrm_angularModules', ['\Civi\Afform\AngularDependencyMapper', 'autoReq'], -1000);
56 $dispatcher->addListener('hook_civicrm_alterAngular', ['\Civi\Afform\AfformMetadataInjector', 'preprocess']);
57 $dispatcher->addListener('hook_civicrm_check', ['\Civi\Afform\StatusChecks', 'hook_civicrm_check']);
58 $dispatcher->addListener('civi.afform.get', ['\Civi\Api4\Action\Afform\Get', 'getCustomGroupBlocks']);
60 // Register support for email tokens
61 if (CRM_Extension_System
::singleton()->getMapper()->isActiveModule('authx')) {
62 $dispatcher->addListener('hook_civicrm_alterMailContent', ['\Civi\Afform\Tokens', 'applyCkeditorWorkaround']);
63 $dispatcher->addListener('hook_civicrm_tokens', ['\Civi\Afform\Tokens', 'hook_civicrm_tokens']);
64 $dispatcher->addListener('hook_civicrm_tokenValues', ['\Civi\Afform\Tokens', 'hook_civicrm_tokenValues']);
69 * Implements hook_civicrm_install().
71 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
73 function afform_civicrm_install() {
74 _afform_civix_civicrm_install();
78 * Implements hook_civicrm_postInstall().
80 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall
82 function afform_civicrm_postInstall() {
83 _afform_civix_civicrm_postInstall();
87 * Implements hook_civicrm_uninstall().
89 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
91 function afform_civicrm_uninstall() {
92 _afform_civix_civicrm_uninstall();
96 * Implements hook_civicrm_enable().
98 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
100 function afform_civicrm_enable() {
101 _afform_civix_civicrm_enable();
105 * Implements hook_civicrm_disable().
107 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
109 function afform_civicrm_disable() {
110 _afform_civix_civicrm_disable();
114 * Implements hook_civicrm_upgrade().
116 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
118 function afform_civicrm_upgrade($op, CRM_Queue_Queue
$queue = NULL) {
119 return _afform_civix_civicrm_upgrade($op, $queue);
123 * Implements hook_civicrm_managed().
125 * Generate a list of entities to create/deactivate/delete when this module
126 * is installed, disabled, uninstalled.
128 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
130 function afform_civicrm_managed(&$entities, $modules) {
131 if ($modules && !in_array(E
::LONG_NAME
, $modules, TRUE)) {
134 /** @var \CRM_Afform_AfformScanner $scanner */
135 if (\Civi
::container()->has('afform_scanner')) {
136 $scanner = \Civi
::service('afform_scanner');
139 // This might happen at oddballs points - e.g. while you're in the middle of re-enabling the ext.
140 // This AfformScanner instance only lives during this method call, and it feeds off the regular cache.
141 $scanner = new CRM_Afform_AfformScanner();
144 foreach ($scanner->getMetas() as $afform) {
145 if (empty($afform['is_dashlet']) ||
empty($afform['name'])) {
149 'module' => E
::LONG_NAME
,
150 'name' => 'afform_dashlet_' . $afform['name'],
151 'entity' => 'Dashboard',
152 'update' => 'always',
153 // ideal cleanup policy might be to (a) deactivate if used and (b) remove if unused
154 'cleanup' => 'always',
158 // Q: Should we loop through all domains?
159 'domain_id' => 'current_domain',
161 'name' => $afform['name'],
162 'label' => $afform['title'] ?? E
::ts('(Untitled)'),
163 'directive' => _afform_angular_module_name($afform['name'], 'dash'),
164 'permission' => "@afform:" . $afform['name'],
173 * Implements hook_civicrm_tabset().
175 * Adds afforms as contact summary tabs.
177 function afform_civicrm_tabset($tabsetName, &$tabs, $context) {
178 if ($tabsetName !== 'civicrm/contact/view') {
181 $afforms = Civi\Api4\Afform
::get(FALSE)
182 ->addWhere('contact_summary', '=', 'tab')
183 ->addSelect('name', 'title', 'icon', 'module_name', 'directive_name')
186 foreach ($afforms as $afform) {
188 'id' => $afform['name'],
189 'title' => $afform['title'],
190 'weight' => $weight++
,
191 'icon' => 'crm-i ' . ($afform['icon'] ?
: 'fa-list-alt'),
193 'template' => 'afform/contactSummary/AfformTab.tpl',
194 'module' => $afform['module_name'],
195 'directive' => $afform['directive_name'],
197 // If this is the real contact summary page (and not a callback from ContactLayoutEditor), load module.
198 if (empty($context['caller'])) {
199 Civi
::service('angularjs.loader')->addModules($afform['module_name']);
205 * Implements hook_civicrm_pageRun().
207 * Adds afforms as contact summary blocks.
209 function afform_civicrm_pageRun(&$page) {
210 if (get_class($page) !== 'CRM_Contact_Page_View_Summary') {
213 $scanner = \Civi
::service('afform_scanner');
214 $cid = $page->get('cid');
216 foreach ($scanner->getMetas() as $afform) {
217 if (!empty($afform['contact_summary']) && $afform['contact_summary'] === 'block') {
218 $module = _afform_angular_module_name($afform['name']);
221 'directive' => _afform_angular_module_name($afform['name'], 'dash'),
223 $content = CRM_Core_Smarty
::singleton()->fetchWith('afform/contactSummary/AfformBlock.tpl', ['contactId' => $cid, 'block' => $block]);
224 CRM_Core_Region
::instance("contact-basic-info-$side")->add([
225 'markup' => '<div class="crm-summary-block">' . $content . '</div>',
228 Civi
::service('angularjs.loader')->addModules($module);
229 $side = $side === 'left' ?
'right' : 'left';
235 * Implements hook_civicrm_contactSummaryBlocks().
237 * @link https://github.com/civicrm/org.civicrm.contactlayout
239 function afform_civicrm_contactSummaryBlocks(&$blocks) {
240 $afforms = \Civi\Api4\Afform
::get(FALSE)
241 ->setSelect(['name', 'title', 'directive_name', 'module_name', 'type', 'type:icon', 'type:label'])
242 ->addWhere('contact_summary', '=', 'block')
244 foreach ($afforms as $index => $afform) {
245 // Create a group per afform type
247 "afform_{$afform['type']}" => [
248 'title' => $afform['type:label'],
249 'icon' => $afform['type:icon'],
253 $blocks["afform_{$afform['type']}"]['blocks'][$afform['name']] = [
254 'title' => $afform['title'],
255 'tpl_file' => 'afform/contactSummary/AfformBlock.tpl',
256 'module' => $afform['module_name'],
257 'directive' => $afform['directive_name'],
259 $afform['type:label'],
261 'edit' => 'civicrm/admin/afform#/edit/' . $afform['name'],
262 'system_default' => [0, $index %
2],
268 * Implements hook_civicrm_angularModules().
270 * Generate a list of Afform Angular modules.
272 function afform_civicrm_angularModules(&$angularModules) {
273 $afforms = \Civi\Api4\Afform
::get(FALSE)
274 ->setSelect(['name', 'requires', 'module_name', 'directive_name'])
277 foreach ($afforms as $afform) {
278 $angularModules[$afform['module_name']] = [
279 'ext' => E
::LONG_NAME
,
280 'js' => ['assetBuilder://afform.js?name=' . urlencode($afform['name'])],
281 'requires' => $afform['requires'],
283 'partialsCallback' => '_afform_get_partials',
284 '_afform' => $afform['name'],
285 // TODO: Allow afforms to declare their own theming requirements
286 'bundles' => ['bootstrap3'],
288 $afform['directive_name'] => 'E',
295 * Callback to retrieve partials for a given afform/angular module.
297 * @see afform_civicrm_angularModules
299 * @param string $moduleName
301 * @param array $module
302 * The module definition.
304 * Array(string $filename => string $html).
305 * @throws API_Exception
307 function _afform_get_partials($moduleName, $module) {
308 $afform = civicrm_api4('Afform', 'get', [
309 'where' => [['name', '=', $module['_afform']]],
310 'select' => ['layout'],
311 'layoutFormat' => 'html',
312 'checkPermissions' => FALSE,
315 "~/$moduleName/$moduleName.aff.html" => $afform['layout'],
320 * Implements hook_civicrm_entityTypes().
322 * Declare entity types provided by this module.
324 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
326 function afform_civicrm_entityTypes(&$entityTypes) {
327 _afform_civix_civicrm_entityTypes($entityTypes);
331 * Implements hook_civicrm_buildAsset().
333 function afform_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
334 if ($asset !== 'afform.js') {
338 if (empty($params['name'])) {
339 throw new RuntimeException("Missing required parameter: afform.js?name=NAME");
342 $moduleName = _afform_angular_module_name($params['name'], 'camel');
343 $formMetaData = (array) civicrm_api4('Afform', 'get', [
344 'checkPermissions' => FALSE,
345 'select' => ['redirect', 'name', 'title'],
346 'where' => [['name', '=', $params['name']]],
348 $smarty = CRM_Core_Smarty
::singleton();
349 $smarty->assign('afform', [
350 'camel' => $moduleName,
351 'meta' => $formMetaData,
352 'templateUrl' => "~/$moduleName/$moduleName.aff.html",
354 $mimeType = 'text/javascript';
355 $content = $smarty->fetch('afform/AfformAngularModule.tpl');
359 * Implements hook_civicrm_alterMenu().
361 function afform_civicrm_alterMenu(&$items) {
363 $afforms = \Civi\Api4\Afform
::get(FALSE)
364 ->addWhere('server_route', 'IS NOT EMPTY')
365 ->addSelect('name', 'server_route', 'is_public')
366 ->execute()->indexBy('name');
368 catch (Exception
$e) {
369 // During installation...
370 $scanner = new CRM_Afform_AfformScanner();
371 $afforms = $scanner->getMetas();
373 foreach ($afforms as $name => $meta) {
374 if (!empty($meta['server_route'])) {
375 $items[$meta['server_route']] = [
376 'page_callback' => 'CRM_Afform_Page_AfformBase',
377 'page_arguments' => 'afform=' . urlencode($name),
378 'access_arguments' => [["@afform:$name"], 'and'],
379 'is_public' => $meta['is_public'],
386 * Implements hook_civicrm_permission().
388 * Define Afform permissions.
390 function afform_civicrm_permission(&$permissions) {
391 $permissions['administer afform'] = [
392 E
::ts('Form Builder: edit and delete forms'),
393 E
::ts('Allows non-admin users to create, update and delete forms'),
398 * Implements hook_civicrm_permission_check().
400 * This extends the list of permissions available in `CRM_Core_Permission:check()`
401 * by introducing virtual-permissions named `@afform:myForm`. The evaluation
402 * of these virtual-permissions is dependent on the settings for `myForm`.
403 * `myForm` may be exposed/integrated through multiple subsystems (routing,
404 * nav-menu, API, etc), and the use of virtual-permissions makes easy to enforce
405 * consistent permissions across any relevant subsystems.
407 * @see CRM_Utils_Hook::permission_check()
409 function afform_civicrm_permission_check($permission, &$granted, $contactId) {
410 if ($permission[0] !== '@') {
411 // Micro-optimization - this function may get hit a lot.
415 if (preg_match('/^@afform:(.*)/', $permission, $m)) {
418 $afform = \Civi\Api4\Afform
::get()
419 ->setCheckPermissions(FALSE)
420 ->addWhere('name', '=', $name)
421 ->setSelect(['permission'])
425 $granted = CRM_Core_Permission
::check($afform['permission'], $contactId);
431 * Implements hook_civicrm_permissionList().
433 * @see CRM_Utils_Hook::permissionList()
435 function afform_civicrm_permissionList(&$permissions) {
436 $scanner = Civi
::service('afform_scanner');
437 foreach ($scanner->getMetas() as $name => $meta) {
438 $permissions['@afform:' . $name] = [
440 'title' => E
::ts('Afform: Inherit permission of %1', [
448 * Clear any local/in-memory caches based on afform data.
450 function _afform_clear() {
451 $container = \Civi
::container();
452 $container->get('afform_scanner')->clear();
453 $container->get('angular')->clear();
457 * @param string $fileBaseName
459 * @param string $format
462 * Ex: 'FooBar' or 'foo-bar'.
465 function _afform_angular_module_name($fileBaseName, $format = 'camel') {
469 foreach (preg_split('/[-_ ]/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY
) as $shortNamePart) {
470 $camelCase .= ucfirst($shortNamePart);
472 return strtolower($camelCase[0]) . substr($camelCase, 1);
475 return strtolower(implode('-', preg_split('/[-_ ]|(?=[A-Z])/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
)));
478 throw new \
Exception("Unrecognized format");
483 * Implements hook_civicrm_alterApiRoutePermissions().
485 * @see CRM_Utils_Hook::alterApiRoutePermissions
487 function afform_civicrm_alterApiRoutePermissions(&$permissions, $entity, $action) {
488 if ($entity == 'Afform') {
489 // These actions should be accessible to anonymous users; permissions are checked internally
490 $allowedActions = ['prefill', 'submit', 'submitFile', 'getOptions'];
491 if (in_array($action, $allowedActions, TRUE)) {
492 $permissions = CRM_Core_Permission
::ALWAYS_ALLOW_PERMISSION
;
498 * Implements hook_civicrm_preProcess().
500 * Wordpress only: Adds Afforms to the shortcode dialog (when editing pages/posts).
502 function afform_civicrm_preProcess($formName, &$form) {
503 if ($formName === 'CRM_Core_Form_ShortCode') {
504 $form->components
['afform'] = [
505 'label' => E
::ts('Form Builder'),
508 'entity' => 'Afform',
509 'select' => ['minimumInputLength' => 0],
511 'params' => ['type' => ['IN' => ['form', 'search']]],
519 * Implements hook_civicrm_pre().
521 function afform_civicrm_pre($op, $entity, $id, &$params) {
522 // When deleting a searchDisplay, also delete any Afforms the display is embedded within
523 if ($entity === 'SearchDisplay' && $op === 'delete') {
524 $display = \Civi\Api4\SearchDisplay
::get(FALSE)
525 ->addSelect('saved_search_id.name', 'name')
526 ->addWhere('id', '=', $id)
527 ->execute()->first();
528 \Civi\Api4\Afform
::revert(FALSE)
529 ->addWhere('search_displays', 'CONTAINS', $display['saved_search_id.name'] . ".{$display['name']}")
532 // When deleting a savedSearch, delete any Afforms which use the default display
533 elseif ($entity === 'SavedSearch' && $op === 'delete') {
534 $search = \Civi\Api4\SavedSearch
::get(FALSE)
536 ->addWhere('id', '=', $id)
537 ->execute()->first();
538 \Civi\Api4\Afform
::revert(FALSE)
539 ->addWhere('search_displays', 'CONTAINS', $search['name'])
545 * Implements hook_civicrm_referenceCounts().
547 function afform_civicrm_referenceCounts($dao, &$counts) {
548 // Count afforms which contain a search display
549 if (is_a($dao, 'CRM_Search_DAO_SearchDisplay') && $dao->id
) {
550 if (empty($dao->saved_search_id
) ||
empty($dao->name
)) {
553 $search = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $dao->saved_search_id
);
554 $afforms = \Civi\Api4\Afform
::get(FALSE)
556 ->addWhere('search_displays', 'CONTAINS', "$search.$dao->name")
558 if ($afforms->count()) {
562 'count' => $afforms->count(),
566 // Count afforms which contain any displays from a SavedSearch (including the default display)
567 elseif (is_a($dao, 'CRM_Contact_DAO_SavedSearch') && $dao->id
) {
568 if (empty($dao->name
)) {
572 ['search_displays', 'CONTAINS', $dao->name
],
575 $displays = civicrm_api4('SearchDisplay', 'get', [
576 'where' => [['saved_search_id', '=', $dao->id
]],
579 foreach ($displays as $displayName) {
580 $clauses[] = ['search_displays', 'CONTAINS', $dao->name
. '.' . $displayName];
583 catch (Exception
$e) {
584 // In case SearchKit is not installed, the api call would fail
586 $afforms = \Civi\Api4\Afform
::get(FALSE)
588 ->addClause('OR', $clauses)
590 if ($afforms->count()) {
594 'count' => $afforms->count(),
600 // Wordpress only: Register callback for rendering shortcodes
601 if (function_exists('add_filter')) {
602 add_filter('civicrm_shortcode_get_markup', 'afform_shortcode_content', 10, 4);
606 * Wordpress only: Render Afform content for shortcodes.
608 * @param string $content
611 * Shortcode attributes.
613 * Existing shortcode arguments.
614 * @param string $context
615 * How many shortcodes are present on the page: 'single' or 'multiple'.
619 function afform_shortcode_content($content, $atts, $args, $context) {
620 if ($atts['component'] === 'afform') {
621 $afform = civicrm_api4('Afform', 'get', [
622 'select' => ['directive_name', 'module_name'],
623 'where' => [['name', '=', $atts['name']]],
626 Civi
::service('angularjs.loader')->addModules($afform['module_name']);
628 <div class='crm-container' id='bootstrap-theme'>
629 <crm-angular-js modules='{$afform['module_name']}'>
630 <{$afform['directive_name']}></{$afform['directive_name']}>