APIv4 - Limit SortableEntity exports by domain
[civicrm-core.git] / CRM / Core / ManagedEntities.php
CommitLineData
6a488035
TO
1<?php
2
a092536e
EM
3use Civi\Api4\Managed;
4
6a488035
TO
5/**
6 * The ManagedEntities system allows modules to add records to the database
7 * declaratively. Those records will be automatically inserted, updated,
8 * deactivated, and deleted in tandem with their modules.
9 */
10class CRM_Core_ManagedEntities {
1f103dc4 11
4b62bc4f
EM
12 /**
13 * Get clean up options.
14 *
15 * @return array
16 */
1f103dc4 17 public static function getCleanupOptions() {
be2fb01f 18 return [
1f103dc4
TO
19 'always' => ts('Always'),
20 'never' => ts('Never'),
21 'unused' => ts('If Unused'),
be2fb01f 22 ];
1f103dc4
TO
23 }
24
6a488035 25 /**
88718db2
TO
26 * @var array
27 * Array($status => array($name => CRM_Core_Module)).
6a488035 28 */
e9b95545 29 protected $moduleIndex;
6a488035 30
a092536e
EM
31 /**
32 * Actions arising from the managed entities.
33 *
34 * @var array
35 */
36 protected $managedActions = [];
37
6a488035 38 /**
88718db2
TO
39 * @var array
40 * List of all entity declarations.
41 * @see CRM_Utils_Hook::managed()
6a488035 42 */
e9b95545 43 protected $declarations;
6a488035
TO
44
45 /**
d09edf64 46 * Get an instance.
ba3228d1
EM
47 * @param bool $fresh
48 * @return \CRM_Core_ManagedEntities
6a488035
TO
49 */
50 public static function singleton($fresh = FALSE) {
51 static $singleton;
52 if ($fresh || !$singleton) {
8cb5ca10 53 $singleton = new CRM_Core_ManagedEntities(CRM_Core_Module::getAll());
6a488035
TO
54 }
55 return $singleton;
56 }
57
9c19292b
TO
58 /**
59 * Perform an asynchronous reconciliation when the transaction ends.
60 */
ba3228d1 61 public static function scheduleReconciliation() {
9c19292b
TO
62 CRM_Core_Transaction::addCallback(
63 CRM_Core_Transaction::PHASE_POST_COMMIT,
64 function () {
e70a7fc0 65 CRM_Core_ManagedEntities::singleton(TRUE)->reconcile();
9c19292b 66 },
be2fb01f 67 [],
9c19292b
TO
68 'ManagedEntities::reconcile'
69 );
70 }
71
6a488035 72 /**
6a0b768e
TO
73 * @param array $modules
74 * CRM_Core_Module.
6a488035 75 */
8cb5ca10 76 public function __construct(array $modules) {
85917c3b 77 $this->moduleIndex = $this->createModuleIndex($modules);
6a488035
TO
78 }
79
80 /**
88718db2 81 * Read a managed entity using APIv3.
378e2654 82 *
a092536e
EM
83 * @deprecated
84 *
88718db2
TO
85 * @param string $moduleName
86 * The name of the module which declared entity.
87 * @param string $name
88 * The symbolic name of the entity.
72b3a70c
CW
89 * @return array|NULL
90 * API representation, or NULL if the entity does not exist
6a488035
TO
91 */
92 public function get($moduleName, $name) {
93 $dao = new CRM_Core_DAO_Managed();
94 $dao->module = $moduleName;
95 $dao->name = $name;
96 if ($dao->find(TRUE)) {
be2fb01f 97 $params = [
6a488035 98 'id' => $dao->entity_id,
be2fb01f 99 ];
bbf66e9c 100 $result = NULL;
637ea2cf
E
101 try {
102 $result = civicrm_api3($dao->entity_type, 'getsingle', $params);
103 }
104 catch (Exception $e) {
e9b95545 105 $this->onApiError($dao->entity_type, 'getsingle', $params, $result);
6a488035 106 }
637ea2cf 107 return $result;
0db6c3e1
TO
108 }
109 else {
6a488035
TO
110 return NULL;
111 }
112 }
113
88718db2
TO
114 /**
115 * Identify any enabled/disabled modules. Add new entities, update
116 * existing entities, and remove orphaned (stale) entities.
8cb5ca10 117 *
912511a3 118 * @param bool $ignoreUpgradeMode
88718db2 119 *
8cb5ca10 120 * @throws \CRM_Core_Exception
88718db2 121 */
912511a3
SL
122 public function reconcile($ignoreUpgradeMode = FALSE) {
123 // Do not reconcile whilst we are in upgrade mode
124 if (CRM_Core_Config::singleton()->isUpgradeMode() && !$ignoreUpgradeMode) {
125 return;
126 }
f9ee37c9 127 $this->loadDeclarations();
e9b95545 128 if ($error = $this->validate($this->getDeclarations())) {
8cb5ca10 129 throw new CRM_Core_Exception($error);
6a488035 130 }
a092536e 131 $this->loadManagedEntityActions();
6a488035
TO
132 $this->reconcileEnabledModules();
133 $this->reconcileDisabledModules();
134 $this->reconcileUnknownModules();
135 }
136
9626d0a1
CW
137 /**
138 * Force-revert a record back to its original state.
139 * @param array $params
140 * Key->value properties of CRM_Core_DAO_Managed used to match an existing record
141 */
142 public function revert(array $params) {
143 $mgd = new \CRM_Core_DAO_Managed();
144 $mgd->copyValues($params);
145 $mgd->find(TRUE);
3bbce6e9 146 $this->loadDeclarations();
9626d0a1
CW
147 $declarations = CRM_Utils_Array::findAll($this->declarations, [
148 'module' => $mgd->module,
149 'name' => $mgd->name,
150 'entity' => $mgd->entity_type,
151 ]);
152 if ($mgd->id && isset($declarations[0])) {
153 $this->updateExistingEntity($mgd, ['update' => 'always'] + $declarations[0]);
154 return TRUE;
155 }
156 return FALSE;
157 }
158
88718db2
TO
159 /**
160 * For all enabled modules, add new entities, update
161 * existing entities, and remove orphaned (stale) entities.
88718db2 162 */
5c095937 163 protected function reconcileEnabledModules(): void {
6a488035
TO
164 // Note: any thing currently declared is necessarily from
165 // an active module -- because we got it from a hook!
166
167 // index by moduleName,name
85917c3b 168 $decls = $this->createDeclarationIndex($this->moduleIndex, $this->getDeclarations());
6a488035 169 foreach ($decls as $moduleName => $todos) {
9cf68fcc 170 if ($this->isModuleEnabled($moduleName)) {
a092536e 171 $this->reconcileEnabledModule($moduleName);
0db6c3e1 172 }
6a488035
TO
173 }
174 }
175
176 /**
88718db2
TO
177 * For one enabled module, add new entities, update existing entities,
178 * and remove orphaned (stale) entities.
6a488035 179 *
a092536e 180 * @param string $module
6a488035 181 */
5c095937 182 protected function reconcileEnabledModule(string $module): void {
a092536e
EM
183 foreach ($this->getManagedEntitiesToUpdate(['module' => $module]) as $todo) {
184 $dao = new CRM_Core_DAO_Managed();
185 $dao->module = $todo['module'];
186 $dao->name = $todo['name'];
187 $dao->entity_type = $todo['entity_type'];
188 $dao->entity_id = $todo['entity_id'];
095e8ae4 189 $dao->entity_modified_date = $todo['entity_modified_date'];
a092536e
EM
190 $dao->id = $todo['id'];
191 $this->updateExistingEntity($dao, $todo);
6a488035
TO
192 }
193
a092536e
EM
194 foreach ($this->getManagedEntitiesToDelete(['module' => $module]) as $todo) {
195 $dao = new CRM_Core_DAO_Managed();
196 $dao->module = $todo['module'];
197 $dao->name = $todo['name'];
198 $dao->entity_type = $todo['entity_type'];
199 $dao->id = $todo['id'];
200 $dao->cleanup = $todo['cleanup'];
201 $dao->entity_id = $todo['entity_id'];
202 $this->removeStaleEntity($dao);
203 }
204 foreach ($this->getManagedEntitiesToCreate(['module' => $module]) as $todo) {
7cddb4ae 205 $this->insertNewEntity($todo);
6a488035
TO
206 }
207 }
208
a092536e
EM
209 /**
210 * Get the managed entities to be created.
211 *
212 * @param array $filters
213 *
214 * @return array
215 */
216 protected function getManagedEntitiesToCreate(array $filters = []): array {
217 return $this->getManagedEntities(array_merge($filters, ['managed_action' => 'create']));
218 }
219
220 /**
9626d0a1 221 * Get the managed entities to be updated.
a092536e
EM
222 *
223 * @param array $filters
224 *
225 * @return array
226 */
227 protected function getManagedEntitiesToUpdate(array $filters = []): array {
228 return $this->getManagedEntities(array_merge($filters, ['managed_action' => 'update']));
229 }
230
231 /**
232 * Get the managed entities to be deleted.
233 *
234 * @param array $filters
235 *
236 * @return array
237 */
238 protected function getManagedEntitiesToDelete(array $filters = []): array {
095e8ae4
CW
239 // Return array in reverse-order so that child entities are cleaned up before their parents
240 return array_reverse($this->getManagedEntities(array_merge($filters, ['managed_action' => 'delete'])));
a092536e
EM
241 }
242
243 /**
244 * Get the managed entities that fit the criteria.
245 *
246 * @param array $filters
247 *
248 * @return array
249 */
250 protected function getManagedEntities(array $filters = []): array {
251 $return = [];
252 foreach ($this->managedActions as $actionKey => $action) {
253 foreach ($filters as $filterKey => $filterValue) {
254 if ($action[$filterKey] !== $filterValue) {
255 continue 2;
256 }
257 }
258 $return[$actionKey] = $action;
259 }
260 return $return;
261 }
262
88718db2
TO
263 /**
264 * For all disabled modules, disable any managed entities.
265 */
5c095937 266 protected function reconcileDisabledModules() {
6a488035
TO
267 if (empty($this->moduleIndex[FALSE])) {
268 return;
269 }
270
271 $in = CRM_Core_DAO::escapeStrings(array_keys($this->moduleIndex[FALSE]));
272 $dao = new CRM_Core_DAO_Managed();
273 $dao->whereAdd("module in ($in)");
04b08baa 274 $dao->orderBy('id DESC');
6a488035
TO
275 $dao->find();
276 while ($dao->fetch()) {
7cddb4ae
TO
277 $this->disableEntity($dao);
278
6a488035
TO
279 }
280 }
281
88718db2
TO
282 /**
283 * Remove any orphaned (stale) entities that are linked to
284 * unknown modules.
285 */
5c095937 286 protected function reconcileUnknownModules() {
be2fb01f 287 $knownModules = [];
6a488035
TO
288 if (array_key_exists(0, $this->moduleIndex) && is_array($this->moduleIndex[0])) {
289 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex[0]));
290 }
291 if (array_key_exists(1, $this->moduleIndex) && is_array($this->moduleIndex[1])) {
292 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex[1]));
6a488035
TO
293 }
294
295 $dao = new CRM_Core_DAO_Managed();
296 if (!empty($knownModules)) {
297 $in = CRM_Core_DAO::escapeStrings($knownModules);
298 $dao->whereAdd("module NOT IN ($in)");
04b08baa 299 $dao->orderBy('id DESC');
6a488035
TO
300 }
301 $dao->find();
302 while ($dao->fetch()) {
bbf66e9c
TO
303 $this->removeStaleEntity($dao);
304 }
305 }
6a488035 306
7cddb4ae 307 /**
88718db2 308 * Create a new entity.
7cddb4ae 309 *
6a0b768e
TO
310 * @param array $todo
311 * Entity specification (per hook_civicrm_managedEntities).
7cddb4ae 312 */
d80c6631 313 protected function insertNewEntity($todo) {
9626d0a1
CW
314 if ($todo['params']['version'] == 4) {
315 $todo['params']['checkPermissions'] = FALSE;
316 }
317
a092536e 318 $result = civicrm_api($todo['entity_type'], 'create', $todo['params']);
ef902ada 319 if (!empty($result['is_error'])) {
a092536e 320 $this->onApiError($todo['entity_type'], 'create', $todo['params'], $result);
7cddb4ae
TO
321 }
322
323 $dao = new CRM_Core_DAO_Managed();
324 $dao->module = $todo['module'];
325 $dao->name = $todo['name'];
a092536e 326 $dao->entity_type = $todo['entity_type'];
be76e704 327 // A fatal error will result if there is no valid id but if
328 // this is v4 api we might need to access it via ->first().
329 $dao->entity_id = $result['id'] ?? $result->first()['id'];
9c1bc317 330 $dao->cleanup = $todo['cleanup'] ?? NULL;
7cddb4ae
TO
331 $dao->save();
332 }
333
334 /**
20429eb9 335 * Update an entity which is believed to exist.
7cddb4ae
TO
336 *
337 * @param CRM_Core_DAO_Managed $dao
6a0b768e
TO
338 * @param array $todo
339 * Entity specification (per hook_civicrm_managedEntities).
7cddb4ae 340 */
5c095937 341 protected function updateExistingEntity($dao, $todo) {
69e13f9b 342 $policy = $todo['update'] ?? 'always';
35c1c211 343 $doUpdate = ($policy === 'always');
0dd54586 344
095e8ae4
CW
345 if ($policy === 'unmodified') {
346 // If this is not an APIv4 managed entity, the entity_modidfied_date will always be null
347 if (!CRM_Core_BAO_Managed::isApi4ManagedType($dao->entity_type)) {
348 Civi::log()->warning('ManagedEntity update policy "unmodified" specified for entity type ' . $dao->entity_type . ' which is not an APIv4 ManagedEntity. Falling back to policy "always".');
349 }
350 $doUpdate = empty($dao->entity_modified_date);
351 }
352
9626d0a1 353 if ($doUpdate && $todo['params']['version'] == 3) {
3cf02556
TO
354 $defaults = ['id' => $dao->entity_id];
355 if ($this->isActivationSupported($dao->entity_type)) {
356 $defaults['is_active'] = 1;
357 }
0dd54586 358 $params = array_merge($defaults, $todo['params']);
20429eb9
RL
359
360 $manager = CRM_Extension_System::singleton()->getManager();
361 if ($dao->entity_type === 'Job' && !$manager->extensionIsBeingInstalledOrEnabled($dao->module)) {
362 // Special treatment for scheduled jobs:
363 //
364 // If we're being called as part of enabling/installing a module then
365 // we want the default behaviour of setting is_active = 1.
366 //
367 // However, if we're just being called by a normal cache flush then we
368 // should not re-enable a job that an administrator has decided to disable.
369 //
370 // Without this logic there was a problem: site admin might disable
371 // a job, but then when there was a flush op, the job was re-enabled
372 // which can cause significant embarrassment, depending on the job
373 // ("Don't worry, sending mailings is disabled right now...").
374 unset($params['is_active']);
375 }
376
0dd54586
TO
377 $result = civicrm_api($dao->entity_type, 'create', $params);
378 if ($result['is_error']) {
353ffa53 379 $this->onApiError($dao->entity_type, 'create', $params, $result);
0dd54586 380 }
7cddb4ae 381 }
9626d0a1
CW
382 elseif ($doUpdate && $todo['params']['version'] == 4) {
383 $params = ['checkPermissions' => FALSE] + $todo['params'];
384 $params['values']['id'] = $dao->entity_id;
385 civicrm_api4($dao->entity_type, 'update', $params);
386 }
1f103dc4 387
69e13f9b
CW
388 if (isset($todo['cleanup']) || $doUpdate) {
389 $dao->cleanup = $todo['cleanup'] ?? NULL;
390 // Reset the `entity_modified_date` timestamp if reverting record.
391 $dao->entity_modified_date = $doUpdate ? 'null' : NULL;
1f103dc4
TO
392 $dao->update();
393 }
7cddb4ae
TO
394 }
395
396 /**
397 * Update an entity which (a) is believed to exist and which (b) ought to be
398 * inactive.
399 *
400 * @param CRM_Core_DAO_Managed $dao
8b91d849 401 *
402 * @throws \CiviCRM_API3_Exception
7cddb4ae 403 */
d80c6631 404 protected function disableEntity($dao): void {
fc625166
TO
405 $entity_type = $dao->entity_type;
406 if ($this->isActivationSupported($entity_type)) {
7cddb4ae 407 // FIXME cascading for payproc types?
be2fb01f 408 $params = [
7cddb4ae
TO
409 'version' => 3,
410 'id' => $dao->entity_id,
411 'is_active' => 0,
be2fb01f 412 ];
7cddb4ae
TO
413 $result = civicrm_api($dao->entity_type, 'create', $params);
414 if ($result['is_error']) {
353ffa53 415 $this->onApiError($dao->entity_type, 'create', $params, $result);
7cddb4ae 416 }
69e13f9b
CW
417 // Reset the `entity_modified_date` timestamp to indicate that the entity has not been modified by the user.
418 $dao->entity_modified_date = 'null';
419 $dao->update();
7cddb4ae
TO
420 }
421 }
422
bbf66e9c 423 /**
88718db2 424 * Remove a stale entity (if policy allows).
bbf66e9c
TO
425 *
426 * @param CRM_Core_DAO_Managed $dao
a092536e 427 * @throws CRM_Core_Exception
bbf66e9c 428 */
d80c6631 429 protected function removeStaleEntity($dao) {
1f103dc4 430 $policy = empty($dao->cleanup) ? 'always' : $dao->cleanup;
378e2654
TO
431 switch ($policy) {
432 case 'always':
433 $doDelete = TRUE;
434 break;
ea100cb5 435
378e2654
TO
436 case 'never':
437 $doDelete = FALSE;
438 break;
ea100cb5 439
378e2654 440 case 'unused':
095e8ae4
CW
441 if (CRM_Core_BAO_Managed::isApi4ManagedType($dao->entity_type)) {
442 $getRefCount = \Civi\Api4\Utils\CoreUtil::getRefCount($dao->entity_type, $dao->entity_id);
443 }
444 else {
445 $getRefCount = civicrm_api3($dao->entity_type, 'getrefcount', [
446 'id' => $dao->entity_id,
447 ])['values'];
448 }
378e2654 449
095e8ae4 450 // FIXME: This extra counting should be unnecessary, because getRefCount only returns values if count > 0
378e2654 451 $total = 0;
095e8ae4 452 foreach ($getRefCount as $refCount) {
378e2654
TO
453 $total += $refCount['count'];
454 }
455
456 $doDelete = ($total == 0);
457 break;
ea100cb5 458
378e2654 459 default:
a092536e 460 throw new CRM_Core_Exception('Unrecognized cleanup policy: ' . $policy);
378e2654 461 }
bbf66e9c 462
a2bf5923
CW
463 // APIv4 delete - deletion from `civicrm_managed` will be taken care of by
464 // CRM_Core_BAO_Managed::on_hook_civicrm_post()
465 if ($doDelete && CRM_Core_BAO_Managed::isApi4ManagedType($dao->entity_type)) {
466 civicrm_api4($dao->entity_type, 'delete', [
467 'where' => [['id', '=', $dao->entity_id]],
468 ]);
469 }
470 // APIv3 delete
471 elseif ($doDelete) {
be2fb01f 472 $params = [
1f103dc4
TO
473 'version' => 3,
474 'id' => $dao->entity_id,
be2fb01f 475 ];
a60c0bc8 476 $check = civicrm_api3($dao->entity_type, 'get', $params);
a2bf5923 477 if ($check['count']) {
a60c0bc8
SL
478 $result = civicrm_api($dao->entity_type, 'delete', $params);
479 if ($result['is_error']) {
9f4f065a
MW
480 if (isset($dao->name)) {
481 $params['name'] = $dao->name;
482 }
a60c0bc8
SL
483 $this->onApiError($dao->entity_type, 'delete', $params, $result);
484 }
a60c0bc8 485 }
be2fb01f
CW
486 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', [
487 1 => [$dao->id, 'Integer'],
488 ]);
1f103dc4 489 }
6a488035
TO
490 }
491
2e2605fe
EM
492 /**
493 * Get declarations.
494 *
495 * @return array|null
496 */
d80c6631 497 protected function getDeclarations() {
e9b95545
TO
498 return $this->declarations;
499 }
500
6a488035 501 /**
88718db2
TO
502 * @param array $modules
503 * Array<CRM_Core_Module>.
77b97be7 504 *
a6c01b45
CW
505 * @return array
506 * indexed by is_active,name
6a488035 507 */
85917c3b 508 protected function createModuleIndex($modules) {
be2fb01f 509 $result = [];
6a488035
TO
510 foreach ($modules as $module) {
511 $result[$module->is_active][$module->name] = $module;
512 }
513 return $result;
514 }
515
516 /**
88718db2
TO
517 * @param array $moduleIndex
518 * @param array $declarations
77b97be7 519 *
a6c01b45
CW
520 * @return array
521 * indexed by module,name
6a488035 522 */
85917c3b 523 protected function createDeclarationIndex($moduleIndex, $declarations) {
be2fb01f 524 $result = [];
6a488035
TO
525 if (!isset($moduleIndex[TRUE])) {
526 return $result;
527 }
528 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
529 if ($module->is_active) {
530 // need an empty array() for all active modules, even if there are no current $declarations
be2fb01f 531 $result[$moduleName] = [];
6a488035
TO
532 }
533 }
534 foreach ($declarations as $declaration) {
535 $result[$declaration['module']][$declaration['name']] = $declaration;
536 }
537 return $result;
538 }
539
540 /**
fd31fa4c
EM
541 * @param $declarations
542 *
72b3a70c
CW
543 * @return string|bool
544 * string on error, or FALSE
6a488035 545 */
85917c3b 546 protected function validate($declarations) {
9cf68fcc 547 foreach ($declarations as $module => $declare) {
be2fb01f 548 foreach (['name', 'module', 'entity', 'params'] as $key) {
6a488035
TO
549 if (empty($declare[$key])) {
550 $str = print_r($declare, TRUE);
9cf68fcc 551 return ts('Managed Entity (%1) is missing field "%2": %3', [$module, $key, $str]);
6a488035
TO
552 }
553 }
9cf68fcc
EM
554 if (!$this->isModuleRecognised($declare['module'])) {
555 return ts('Entity declaration references invalid or inactive module name [%1]', [$declare['module']]);
556 }
6a488035
TO
557 }
558 return FALSE;
559 }
560
9cf68fcc
EM
561 /**
562 * Is the module recognised (as an enabled or disabled extension in the system).
563 *
564 * @param string $module
565 *
566 * @return bool
567 */
568 protected function isModuleRecognised(string $module): bool {
569 return $this->isModuleDisabled($module) || $this->isModuleEnabled($module);
570 }
571
572 /**
573 * Is the module enabled.
574 *
575 * @param string $module
576 *
577 * @return bool
578 */
579 protected function isModuleEnabled(string $module): bool {
580 return isset($this->moduleIndex[TRUE][$module]);
581 }
582
583 /**
584 * Is the module disabled.
585 *
586 * @param string $module
587 *
588 * @return bool
589 */
590 protected function isModuleDisabled(string $module): bool {
591 return isset($this->moduleIndex[FALSE][$module]);
592 }
593
a0ee3941 594 /**
72b3a70c 595 * @param array $declarations
a0ee3941 596 *
72b3a70c 597 * @return array
a0ee3941 598 */
85917c3b 599 protected function cleanDeclarations(array $declarations): array {
6a488035
TO
600 foreach ($declarations as $name => &$declare) {
601 if (!array_key_exists('name', $declare)) {
602 $declare['name'] = $name;
603 }
604 }
605 return $declarations;
606 }
607
a0ee3941 608 /**
e9b95545
TO
609 * @param string $entity
610 * @param string $action
611 * @param array $params
612 * @param array $result
a0ee3941
EM
613 *
614 * @throws Exception
615 */
e9b95545 616 protected function onApiError($entity, $action, $params, $result) {
be2fb01f 617 CRM_Core_Error::debug_var('ManagedEntities_failed', [
e9b95545
TO
618 'entity' => $entity,
619 'action' => $action,
6a488035
TO
620 'params' => $params,
621 'result' => $result,
be2fb01f 622 ]);
35c1c211 623 throw new Exception('API error: ' . $result['error_message'] . ' on ' . $entity . '.' . $action
9f4f065a 624 . (!empty($params['name']) ? '( entity name ' . $params['name'] . ')' : '')
35c1c211 625 );
cbb7c7e0 626 }
96025800 627
fc625166
TO
628 /**
629 * Determine if an entity supports APIv3-based activation/de-activation.
630 * @param string $entity_type
631 *
632 * @return bool
633 * @throws \CiviCRM_API3_Exception
634 */
635 private function isActivationSupported(string $entity_type): bool {
636 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__][$entity_type])) {
637 $actions = civicrm_api3($entity_type, 'getactions', [])['values'];
638 Civi::$statics[__CLASS__][__FUNCTION__][$entity_type] = FALSE;
639 if (in_array('create', $actions, TRUE) && in_array('getfields', $actions)) {
640 $fields = civicrm_api3($entity_type, 'getfields', ['action' => 'create'])['values'];
641 Civi::$statics[__CLASS__][__FUNCTION__][$entity_type] = array_key_exists('is_active', $fields);
642 }
643 }
644 return Civi::$statics[__CLASS__][__FUNCTION__][$entity_type];
645 }
646
78ce6ebb
EM
647 /**
648 * Load declarations into the class property.
649 *
650 * This picks it up from hooks and enabled components.
651 */
652 protected function loadDeclarations(): void {
653 $this->declarations = [];
654 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
655 $this->declarations = array_merge($this->declarations, $component->getManagedEntities());
656 }
657 CRM_Utils_Hook::managed($this->declarations);
658 $this->declarations = $this->cleanDeclarations($this->declarations);
659 }
660
a092536e
EM
661 protected function loadManagedEntityActions(): void {
662 $managedEntities = Managed::get(FALSE)->addSelect('*')->execute();
663 foreach ($managedEntities as $managedEntity) {
664 $key = "{$managedEntity['module']}_{$managedEntity['name']}_{$managedEntity['entity_type']}";
665 // Set to 'delete' - it will be overwritten below if it is to be updated.
666 $action = 'delete';
667 $this->managedActions[$key] = array_merge($managedEntity, ['managed_action' => $action]);
668 }
669 foreach ($this->declarations as $declaration) {
670 $key = "{$declaration['module']}_{$declaration['name']}_{$declaration['entity']}";
671 if (isset($this->managedActions[$key])) {
672 $this->managedActions[$key]['params'] = $declaration['params'];
673 $this->managedActions[$key]['managed_action'] = 'update';
674 $this->managedActions[$key]['cleanup'] = $declaration['cleanup'] ?? NULL;
675 $this->managedActions[$key]['update'] = $declaration['update'] ?? 'always';
676 }
677 else {
678 $this->managedActions[$key] = [
679 'module' => $declaration['module'],
680 'name' => $declaration['name'],
681 'entity_type' => $declaration['entity'],
682 'managed_action' => 'create',
683 'params' => $declaration['params'],
684 'cleanup' => $declaration['cleanup'] ?? NULL,
685 'update' => $declaration['update'] ?? 'always',
686 ];
687 }
688 }
689 }
690
6a488035 691}