Loosen restrictions on file names - allow underscores
[civicrm-core.git] / ext / afform / core / afform.php
CommitLineData
66aa0f5e
TO
1<?php
2
3require_once 'afform.civix.php';
4use CRM_Afform_ExtensionUtil as E;
fb388832 5use Civi\Api4\Action\Afform\Submit;
66aa0f5e 6
bc3b7c5b
TO
7/**
8 * Filter the content of $params to only have supported afform fields.
9 *
10 * @param array $params
11 * @return array
12 */
13function _afform_fields_filter($params) {
5591cfbf 14 $result = [];
e38db494 15 $fields = \Civi\Api4\Afform::getfields()->setCheckPermissions(FALSE)->setAction('create')->execute()->indexBy('name');
50868e8d
CW
16 foreach ($fields as $fieldName => $field) {
17 if (isset($params[$fieldName])) {
18 $result[$fieldName] = $params[$fieldName];
d1ec770c 19
e38db494
CW
20 if ($field['data_type'] === 'Boolean' && !is_bool($params[$fieldName])) {
21 $result[$fieldName] = CRM_Utils_String::strtobool($params[$fieldName]);
d1ec770c
TO
22 }
23 }
bc3b7c5b
TO
24 }
25 return $result;
26}
27
8f4a0ee9 28/**
5591cfbf 29 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
8f4a0ee9
TO
30 */
31function afform_civicrm_container($container) {
77dccccb 32 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
8f4a0ee9
TO
33 $container->setDefinition('afform_scanner', new \Symfony\Component\DependencyInjection\Definition(
34 'CRM_Afform_AfformScanner',
5591cfbf 35 []
8f4a0ee9
TO
36 ));
37}
38
66aa0f5e
TO
39/**
40 * Implements hook_civicrm_config().
41 *
42 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
43 */
44function afform_civicrm_config(&$config) {
45 _afform_civix_civicrm_config($config);
77dccccb
TO
46
47 if (isset(Civi::$statics[__FUNCTION__])) {
48 return;
49 }
50 Civi::$statics[__FUNCTION__] = 1;
51
e1aca853 52 Civi::dispatcher()->addListener(Submit::EVENT_NAME, [Submit::class, 'processContacts'], 500);
fb388832 53 Civi::dispatcher()->addListener(Submit::EVENT_NAME, [Submit::class, 'processGenericEntity'], -1000);
77dccccb 54 Civi::dispatcher()->addListener('hook_civicrm_angularModules', '_afform_civicrm_angularModules_autoReq', -1000);
66aa0f5e
TO
55}
56
57/**
58 * Implements hook_civicrm_xmlMenu().
59 *
60 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
61 */
62function afform_civicrm_xmlMenu(&$files) {
63 _afform_civix_civicrm_xmlMenu($files);
64}
65
66/**
67 * Implements hook_civicrm_install().
68 *
69 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
70 */
71function afform_civicrm_install() {
72 _afform_civix_civicrm_install();
73}
74
75/**
76 * Implements hook_civicrm_postInstall().
77 *
78 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall
79 */
80function afform_civicrm_postInstall() {
81 _afform_civix_civicrm_postInstall();
82}
83
84/**
85 * Implements hook_civicrm_uninstall().
86 *
87 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
88 */
89function afform_civicrm_uninstall() {
90 _afform_civix_civicrm_uninstall();
91}
92
93/**
94 * Implements hook_civicrm_enable().
95 *
96 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
97 */
98function afform_civicrm_enable() {
99 _afform_civix_civicrm_enable();
100}
101
102/**
103 * Implements hook_civicrm_disable().
104 *
105 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
106 */
107function afform_civicrm_disable() {
108 _afform_civix_civicrm_disable();
109}
110
111/**
112 * Implements hook_civicrm_upgrade().
113 *
114 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
115 */
116function afform_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
117 return _afform_civix_civicrm_upgrade($op, $queue);
118}
119
120/**
121 * Implements hook_civicrm_managed().
122 *
123 * Generate a list of entities to create/deactivate/delete when this module
124 * is installed, disabled, uninstalled.
125 *
126 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
127 */
128function afform_civicrm_managed(&$entities) {
129 _afform_civix_civicrm_managed($entities);
130}
131
132/**
133 * Implements hook_civicrm_caseTypes().
134 *
135 * Generate a list of case-types.
136 *
137 * Note: This hook only runs in CiviCRM 4.4+.
138 *
139 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
140 */
141function afform_civicrm_caseTypes(&$caseTypes) {
142 _afform_civix_civicrm_caseTypes($caseTypes);
143}
144
145/**
146 * Implements hook_civicrm_angularModules().
147 *
e1aca853 148 * Generate a list of Afform Angular modules.
66aa0f5e
TO
149 */
150function afform_civicrm_angularModules(&$angularModules) {
151 _afform_civix_civicrm_angularModules($angularModules);
bb56ac78 152
2d4bfef1
CW
153 $afforms = \Civi\Api4\Afform::get()
154 ->setCheckPermissions(FALSE)
e38db494 155 ->setSelect(['name', 'requires', 'module_name', 'directive_name'])
2d4bfef1
CW
156 ->execute();
157
158 foreach ($afforms as $afform) {
e38db494 159 $angularModules[$afform['module_name']] = [
bb56ac78 160 'ext' => E::LONG_NAME,
2d4bfef1
CW
161 'js' => ['assetBuilder://afform.js?name=' . urlencode($afform['name'])],
162 'requires' => $afform['requires'],
bb56ac78 163 'basePages' => [],
aa6abb77 164 'partialsCallback' => '_afform_get_partials',
2d4bfef1 165 '_afform' => $afform['name'],
77dccccb 166 'exports' => [
e38db494 167 $afform['directive_name'] => 'AE',
77dccccb 168 ],
bb56ac78 169 ];
bb56ac78 170 }
66aa0f5e
TO
171}
172
aa6abb77 173/**
2d4bfef1
CW
174 * Callback to retrieve partials for a given afform/angular module.
175 *
176 * @see afform_civicrm_angularModules
aa6abb77
TO
177 *
178 * @param string $moduleName
179 * The module name.
180 * @param array $module
181 * The module definition.
182 * @return array
183 * Array(string $filename => string $html).
2d4bfef1 184 * @throws API_Exception
aa6abb77
TO
185 */
186function _afform_get_partials($moduleName, $module) {
2d4bfef1
CW
187 $afform = civicrm_api4('Afform', 'get', [
188 'where' => [['name', '=', $module['_afform']]],
189 'select' => ['layout'],
190 'layoutFormat' => 'html',
191 'checkPermissions' => FALSE,
192 ], 0);
aa6abb77 193 return [
2d4bfef1 194 "~/$moduleName/$moduleName.aff.html" => $afform['layout'],
aa6abb77
TO
195 ];
196}
197
77dccccb
TO
198/**
199 * Scan the list of Angular modules and inject automatic-requirements.
200 *
201 * TLDR: if an afform uses element "<other-el/>", and if another module defines
202 * `$angularModules['otherMod']['exports']['el'][0] === 'other-el'`, then
203 * the 'otherMod' is automatically required.
204 *
205 * @param \Civi\Core\Event\GenericHookEvent $e
206 * @see CRM_Utils_Hook::angularModules()
207 */
208function _afform_civicrm_angularModules_autoReq($e) {
209 /** @var CRM_Afform_AfformScanner $scanner */
210 $scanner = Civi::service('afform_scanner');
211 $moduleEnvId = md5(\CRM_Core_Config_Runtime::getId() . implode(',', array_keys($e->angularModules)));
212 $depCache = CRM_Utils_Cache::create([
213 'name' => 'afdep_' . substr($moduleEnvId, 0, 32 - 6),
214 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
215 'withArray' => 'fast',
216 'prefetch' => TRUE,
217 ]);
218 $depCacheTtl = 2 * 60 * 60;
219
220 $revMap = _afform_reverse_deps($e->angularModules);
221
222 $formNames = array_keys($scanner->findFilePaths());
223 foreach ($formNames as $formName) {
224 $angModule = _afform_angular_module_name($formName, 'camel');
225 $cacheLine = $depCache->get($formName, NULL);
226
227 $jFile = $scanner->findFilePath($formName, 'aff.json');
228 $hFile = $scanner->findFilePath($formName, 'aff.html');
229
230 $jStat = stat($jFile);
231 $hStat = stat($hFile);
232
233 if ($cacheLine === NULL) {
234 $needsUpdate = TRUE;
235 }
236 elseif ($jStat !== FALSE && $jStat['size'] !== $cacheLine['js']) {
237 $needsUpdate = TRUE;
238 }
239 elseif ($jStat !== FALSE && $jStat['mtime'] > $cacheLine['jm']) {
240 $needsUpdate = TRUE;
241 }
242 elseif ($hStat !== FALSE && $hStat['size'] !== $cacheLine['hs']) {
243 $needsUpdate = TRUE;
244 }
245 elseif ($hStat !== FALSE && $hStat['mtime'] > $cacheLine['hm']) {
246 $needsUpdate = TRUE;
247 }
248 else {
249 $needsUpdate = FALSE;
250 }
251
252 if ($needsUpdate) {
253 $cacheLine = [
254 'js' => $jStat['size'] ?? NULL,
255 'jm' => $jStat['mtime'] ?? NULL,
256 'hs' => $hStat['size'] ?? NULL,
257 'hm' => $hStat['mtime'] ?? NULL,
258 'r' => array_values(array_unique(array_merge(
259 [CRM_Afform_AfformScanner::DEFAULT_REQUIRES],
260 $e->angularModules[$angModule]['requires'] ?? [],
261 _afform_reverse_deps_find($formName, file_get_contents($hFile), $revMap)
262 ))),
263 ];
264 // print_r(['cache update:' . $formName => $cacheLine]);
265 $depCache->set($formName, $cacheLine, $depCacheTtl);
266 }
267
268 $e->angularModules[$angModule]['requires'] = $cacheLine['r'];
269 }
270}
271
272/**
273 * @param $angularModules
274 * @return array
275 * 'attr': array(string $attrName => string $angModuleName)
276 * 'el': array(string $elementName => string $angModuleName)
277 */
278function _afform_reverse_deps($angularModules) {
23315411
TO
279 $revMap = ['attr' => [], 'el' => []];
280 foreach (array_keys($angularModules) as $module) {
281 if (!isset($angularModules[$module]['exports'])) {
282 continue;
283 }
284 foreach ($angularModules[$module]['exports'] as $symbolName => $symbolTypes) {
285 if (strpos($symbolTypes, 'A') !== FALSE) {
286 $revMap['attr'][$symbolName] = $module;
287 }
288 if (strpos($symbolTypes, 'E') !== FALSE) {
289 $revMap['el'][$symbolName] = $module;
77dccccb
TO
290 }
291 }
292 }
293 return $revMap;
294}
295
23315411
TO
296/**
297 * @param string $formName
298 * @param string $html
299 * @param array $revMap
300 * The reverse-dependencies map from _afform_reverse_deps().
301 * @return array
302 * @see _afform_reverse_deps()
303 */
77dccccb
TO
304function _afform_reverse_deps_find($formName, $html, $revMap) {
305 $symbols = \Civi\Afform\Symbols::scan($html);
306 $elems = array_intersect_key($revMap['el'], $symbols->elements);
307 $attrs = array_intersect_key($revMap['attr'], $symbols->attributes);
308 return array_values(array_unique(array_merge($elems, $attrs)));
309}
310
9384980c
TO
311/**
312 * @param \Civi\Angular\Manager $angular
313 * @see CRM_Utils_Hook::alterAngular()
314 */
315function afform_civicrm_alterAngular($angular) {
316 $fieldMetadata = \Civi\Angular\ChangeSet::create('fieldMetadata')
dd10599c 317 ->alterHtml(';\\.aff\\.html$;', function($doc, $path) {
9c84a124
CW
318 try {
319 $module = \Civi::service('angular')->getModule(basename($path, '.aff.html'));
344e8290 320 $meta = \Civi\Api4\Afform::get()->addWhere('name', '=', $module['_afform'])->setSelect(['join', 'block'])->setCheckPermissions(FALSE)->execute()->first();
9c84a124
CW
321 }
322 catch (Exception $e) {
323 }
324
344e8290 325 $blockEntity = $meta['join'] ?? $meta['block'] ?? NULL;
e1aca853
CW
326 if (!$blockEntity) {
327 $entities = _afform_getMetadata($doc);
328 }
9384980c
TO
329
330 foreach (pq('af-field', $doc) as $afField) {
331 /** @var DOMElement $afField */
56b9319d 332 $entityName = pq($afField)->parents('[af-fieldset]')->attr('af-fieldset');
344e8290 333 $joinName = pq($afField)->parents('[af-join]')->attr('af-join');
e1aca853 334 if (!$blockEntity && !preg_match(';^[a-zA-Z0-9\_\-\. ]+$;', $entityName)) {
9384980c
TO
335 throw new \CRM_Core_Exception("Cannot process $path: malformed entity name ($entityName)");
336 }
e1aca853 337 $entityType = $blockEntity ?? $entities[$entityName]['type'];
344e8290 338 _af_fill_field_metadata($joinName ? $joinName : $entityType, $afField);
9384980c
TO
339 }
340 });
341 $angular->add($fieldMetadata);
342}
343
e1aca853
CW
344/**
345 * Merge field definition metadata into an afform field's definition
346 *
347 * @param $entityType
348 * @param DOMElement $afField
349 * @throws API_Exception
350 */
351function _af_fill_field_metadata($entityType, DOMElement $afField) {
eb4f581a 352 $params = [
e1aca853 353 'action' => 'create',
eb4f581a 354 'where' => [['name', '=', $afField->getAttribute('name')]],
e1aca853
CW
355 'select' => ['title', 'input_type', 'input_attrs', 'options'],
356 'loadOptions' => TRUE,
eb4f581a
CW
357 ];
358 if (in_array($entityType, CRM_Contact_BAO_ContactType::basicTypes(TRUE))) {
359 $params['values'] = ['contact_type' => $entityType];
360 $entityType = 'Contact';
361 }
362 $getFields = civicrm_api4($entityType, 'getFields', $params);
e1aca853
CW
363 // Merge field definition data with whatever's already in the markup
364 $deep = ['input_attrs'];
365 foreach ($getFields as $fieldInfo) {
366 $existingFieldDefn = trim(pq($afField)->attr('defn') ?: '');
367 if ($existingFieldDefn && $existingFieldDefn[0] != '{') {
368 // If it's not an object, don't mess with it.
369 continue;
370 }
371 // TODO: Teach the api to return options in this format
372 if (!empty($fieldInfo['options'])) {
373 $fieldInfo['options'] = CRM_Utils_Array::makeNonAssociative($fieldInfo['options'], 'key', 'label');
374 }
375 // Default placeholder for select inputs
376 if ($fieldInfo['input_type'] === 'Select') {
377 $fieldInfo['input_attrs'] = ($fieldInfo['input_attrs'] ?? []) + ['placeholder' => ts('Select')];
378 }
379
380 $fieldDefn = $existingFieldDefn ? CRM_Utils_JS::getRawProps($existingFieldDefn) : [];
381 foreach ($fieldInfo as $name => $prop) {
382 // Merge array props 1 level deep
383 if (in_array($name, $deep) && !empty($fieldDefn[$name])) {
384 $fieldDefn[$name] = CRM_Utils_JS::writeObject(CRM_Utils_JS::getRawProps($fieldDefn[$name]) + array_map(['CRM_Utils_JS', 'encode'], $prop));
385 }
386 elseif (!isset($fieldDefn[$name])) {
387 $fieldDefn[$name] = CRM_Utils_JS::encode($prop);
388 }
389 }
390 pq($afField)->attr('defn', htmlspecialchars(CRM_Utils_JS::writeObject($fieldDefn)));
391 }
392}
393
9384980c
TO
394function _afform_getMetadata(phpQueryObject $doc) {
395 $entities = [];
c37151d2 396 foreach ($doc->find('af-entity') as $afmModelProp) {
8410442c 397 $entities[$afmModelProp->getAttribute('name')] = [
bbd6df21 398 'type' => $afmModelProp->getAttribute('type'),
9384980c
TO
399 ];
400 }
401 return $entities;
402}
403
66aa0f5e
TO
404/**
405 * Implements hook_civicrm_alterSettingsFolders().
406 *
407 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
408 */
409function afform_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
410 _afform_civix_civicrm_alterSettingsFolders($metaDataFolders);
411}
412
413/**
414 * Implements hook_civicrm_entityTypes().
415 *
416 * Declare entity types provided by this module.
417 *
418 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes
419 */
420function afform_civicrm_entityTypes(&$entityTypes) {
421 _afform_civix_civicrm_entityTypes($entityTypes);
422}
423
98f4a7cb
TO
424/**
425 * Implements hook_civicrm_themes().
426 */
427function afform_civicrm_themes(&$themes) {
428 _afform_civix_civicrm_themes($themes);
429}
430
bb56ac78
TO
431/**
432 * Implements hook_civicrm_buildAsset().
433 */
434function afform_civicrm_buildAsset($asset, $params, &$mimeType, &$content) {
435 if ($asset !== 'afform.js') {
436 return;
437 }
438
439 if (empty($params['name'])) {
440 throw new RuntimeException("Missing required parameter: afform.js?name=NAME");
441 }
442
2d4bfef1 443 $moduleName = _afform_angular_module_name($params['name'], 'camel');
bb56ac78
TO
444 $smarty = CRM_Core_Smarty::singleton();
445 $smarty->assign('afform', [
aa6abb77 446 'camel' => $moduleName,
2d4bfef1 447 'meta' => ['name' => $params['name']],
aa6abb77 448 'templateUrl' => "~/$moduleName/$moduleName.aff.html",
bb56ac78
TO
449 ]);
450 $mimeType = 'text/javascript';
9ec944f2 451 $content = $smarty->fetch('afform/AfformAngularModule.tpl');
bb56ac78
TO
452}
453
8775c48a
TO
454/**
455 * Implements hook_civicrm_alterMenu().
456 */
457function afform_civicrm_alterMenu(&$items) {
8f4a0ee9
TO
458 if (Civi::container()->has('afform_scanner')) {
459 $scanner = Civi::service('afform_scanner');
460 }
461 else {
462 // During installation...
463 $scanner = new CRM_Afform_AfformScanner();
464 }
8775c48a
TO
465 foreach ($scanner->getMetas() as $name => $meta) {
466 if (!empty($meta['server_route'])) {
467 $items[$meta['server_route']] = [
468 'page_callback' => 'CRM_Afform_Page_AfformBase',
469 'page_arguments' => 'afform=' . urlencode($name),
13bdd6d2 470 'title' => $meta['title'] ?? '',
f16b2aee 471 'access_arguments' => [["@afform:$name"], 'and'],
254f01f0 472 'is_public' => $meta['is_public'],
8775c48a
TO
473 ];
474 }
475 }
f16b2aee
TO
476}
477
478/**
479 * Implements hook_civicrm_permission_check().
480 *
586344a7
TO
481 * This extends the list of permissions available in `CRM_Core_Permission:check()`
482 * by introducing virtual-permissions named `@afform:myForm`. The evaluation
483 * of these virtual-permissions is dependent on the settings for `myForm`.
484 * `myForm` may be exposed/integrated through multiple subsystems (routing,
485 * nav-menu, API, etc), and the use of virtual-permissions makes easy to enforce
486 * consistent permissions across any relevant subsystems.
487 *
f16b2aee
TO
488 * @see CRM_Utils_Hook::permission_check()
489 */
490function afform_civicrm_permission_check($permission, &$granted, $contactId) {
491 if ($permission{0} !== '@') {
492 // Micro-optimization - this function may get hit a lot.
493 return;
494 }
495
496 if (preg_match('/^@afform:(.*)/', $permission, $m)) {
497 $name = $m[1];
498
2d4bfef1
CW
499 $afform = \Civi\Api4\Afform::get()
500 ->setCheckPermissions(FALSE)
501 ->addWhere('name', '=', $name)
502 ->setSelect(['permission'])
503 ->execute()
504 ->first();
505 if ($afform) {
506 $granted = CRM_Core_Permission::check($afform['permission'], $contactId);
507 }
f16b2aee 508 }
8775c48a
TO
509}
510
74f862e4
TO
511/**
512 * Clear any local/in-memory caches based on afform data.
513 */
514function _afform_clear() {
515 $container = \Civi::container();
516 $container->get('afform_scanner')->clear();
517
518 // Civi\Angular\Manager doesn't currently have a way to clear its in-memory
519 // data, so we just reset the whole object.
520 $container->set('angular', NULL);
521}
522
bb56ac78 523/**
87dde5eb
TO
524 * @param string $fileBaseName
525 * Ex: foo-bar
841850b1
TO
526 * @param string $format
527 * 'camel' or 'dash'.
bb56ac78 528 * @return string
841850b1 529 * Ex: 'FooBar' or 'foo-bar'.
3cd5c38b 530 * @throws \Exception
bb56ac78 531 */
87dde5eb 532function _afform_angular_module_name($fileBaseName, $format = 'camel') {
841850b1
TO
533 switch ($format) {
534 case 'camel':
87dde5eb 535 $camelCase = '';
9c84a124 536 foreach (preg_split('/[-_ ]/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY) as $shortNamePart) {
87dde5eb
TO
537 $camelCase .= ucfirst($shortNamePart);
538 }
539 return strtolower($camelCase{0}) . substr($camelCase, 1);
841850b1
TO
540
541 case 'dash':
9c84a124 542 return strtolower(implode('-', preg_split('/[-_ ]|(?=[A-Z])/', $fileBaseName, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
841850b1
TO
543
544 default:
545 throw new \Exception("Unrecognized format");
546 }
bb56ac78 547}