4 * The ManagedEntities system allows modules to add records to the database
5 * declaratively. Those records will be automatically inserted, updated,
6 * deactivated, and deleted in tandem with their modules.
8 class CRM_Core_ManagedEntities
{
11 * Get clean up options.
15 public static function getCleanupOptions() {
17 'always' => ts('Always'),
18 'never' => ts('Never'),
19 'unused' => ts('If Unused'),
25 * Array($status => array($name => CRM_Core_Module)).
27 protected $moduleIndex;
31 * List of all entity declarations.
32 * @see CRM_Utils_Hook::managed()
34 protected $declarations;
39 * @return \CRM_Core_ManagedEntities
41 public static function singleton($fresh = FALSE) {
43 if ($fresh ||
!$singleton) {
44 $singleton = new CRM_Core_ManagedEntities(CRM_Core_Module
::getAll(), NULL);
50 * Perform an asynchronous reconciliation when the transaction ends.
52 public static function scheduleReconciliation() {
53 CRM_Core_Transaction
::addCallback(
54 CRM_Core_Transaction
::PHASE_POST_COMMIT
,
56 CRM_Core_ManagedEntities
::singleton(TRUE)->reconcile();
59 'ManagedEntities::reconcile'
64 * @param array $modules
66 * @param array $declarations
67 * Per hook_civicrm_managed.
69 public function __construct($modules, $declarations) {
70 $this->moduleIndex
= self
::createModuleIndex($modules);
72 if ($declarations !== NULL) {
73 $this->declarations
= self
::cleanDeclarations($declarations);
76 $this->declarations
= NULL;
81 * Read a managed entity using APIv3.
83 * @param string $moduleName
84 * The name of the module which declared entity.
86 * The symbolic name of the entity.
88 * API representation, or NULL if the entity does not exist
90 public function get($moduleName, $name) {
91 $dao = new CRM_Core_DAO_Managed();
92 $dao->module
= $moduleName;
94 if ($dao->find(TRUE)) {
96 'id' => $dao->entity_id
,
100 $result = civicrm_api3($dao->entity_type
, 'getsingle', $params);
102 catch (Exception
$e) {
103 $this->onApiError($dao->entity_type
, 'getsingle', $params, $result);
113 * Identify any enabled/disabled modules. Add new entities, update
114 * existing entities, and remove orphaned (stale) entities.
115 * @param bool $ignoreUpgradeMode
119 public function reconcile($ignoreUpgradeMode = FALSE) {
120 // Do not reconcile whilst we are in upgrade mode
121 if (CRM_Core_Config
::singleton()->isUpgradeMode() && !$ignoreUpgradeMode) {
124 if ($error = $this->validate($this->getDeclarations())) {
125 throw new Exception($error);
127 $this->reconcileEnabledModules();
128 $this->reconcileDisabledModules();
129 $this->reconcileUnknownModules();
133 * For all enabled modules, add new entities, update
134 * existing entities, and remove orphaned (stale) entities.
138 public function reconcileEnabledModules() {
139 // Note: any thing currently declared is necessarily from
140 // an active module -- because we got it from a hook!
142 // index by moduleName,name
143 $decls = self
::createDeclarationIndex($this->moduleIndex
, $this->getDeclarations());
144 foreach ($decls as $moduleName => $todos) {
145 if (isset($this->moduleIndex
[TRUE][$moduleName])) {
146 $this->reconcileEnabledModule($this->moduleIndex
[TRUE][$moduleName], $todos);
148 elseif (isset($this->moduleIndex
[FALSE][$moduleName])) {
149 // do nothing -- module should get swept up later
152 throw new Exception("Entity declaration references invalid or inactive module name [$moduleName]");
158 * For one enabled module, add new entities, update existing entities,
159 * and remove orphaned (stale) entities.
161 * @param \CRM_Core_Module $module
162 * @param array $todos
163 * List of entities currently declared by this module.
164 * array(string $name => array $entityDef).
166 public function reconcileEnabledModule(CRM_Core_Module
$module, $todos) {
167 $dao = new CRM_Core_DAO_Managed();
168 $dao->module
= $module->name
;
170 while ($dao->fetch()) {
171 if (isset($todos[$dao->name
]) && $todos[$dao->name
]) {
172 // update existing entity; remove from $todos
173 $this->updateExistingEntity($dao, $todos[$dao->name
]);
174 unset($todos[$dao->name
]);
177 // remove stale entity; not in $todos
178 $this->removeStaleEntity($dao);
182 // create new entities from leftover $todos
183 foreach ($todos as $name => $todo) {
184 $this->insertNewEntity($todo);
189 * For all disabled modules, disable any managed entities.
191 public function reconcileDisabledModules() {
192 if (empty($this->moduleIndex
[FALSE])) {
196 $in = CRM_Core_DAO
::escapeStrings(array_keys($this->moduleIndex
[FALSE]));
197 $dao = new CRM_Core_DAO_Managed();
198 $dao->whereAdd("module in ($in)");
199 $dao->orderBy('id DESC');
201 while ($dao->fetch()) {
202 $this->disableEntity($dao);
208 * Remove any orphaned (stale) entities that are linked to
211 public function reconcileUnknownModules() {
213 if (array_key_exists(0, $this->moduleIndex
) && is_array($this->moduleIndex
[0])) {
214 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[0]));
216 if (array_key_exists(1, $this->moduleIndex
) && is_array($this->moduleIndex
[1])) {
217 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[1]));
220 $dao = new CRM_Core_DAO_Managed();
221 if (!empty($knownModules)) {
222 $in = CRM_Core_DAO
::escapeStrings($knownModules);
223 $dao->whereAdd("module NOT IN ($in)");
224 $dao->orderBy('id DESC');
227 while ($dao->fetch()) {
228 $this->removeStaleEntity($dao);
233 * Create a new entity.
236 * Entity specification (per hook_civicrm_managedEntities).
238 public function insertNewEntity($todo) {
239 $result = civicrm_api($todo['entity'], 'create', $todo['params']);
240 if ($result['is_error']) {
241 $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
244 $dao = new CRM_Core_DAO_Managed();
245 $dao->module
= $todo['module'];
246 $dao->name
= $todo['name'];
247 $dao->entity_type
= $todo['entity'];
248 $dao->entity_id
= $result['id'];
249 $dao->cleanup
= CRM_Utils_Array
::value('cleanup', $todo);
254 * Update an entity which (a) is believed to exist and which (b) ought to be active.
256 * @param CRM_Core_DAO_Managed $dao
258 * Entity specification (per hook_civicrm_managedEntities).
260 public function updateExistingEntity($dao, $todo) {
261 $policy = CRM_Utils_Array
::value('update', $todo, 'always');
262 $doUpdate = ($policy == 'always');
266 'id' => $dao->entity_id
,
267 // FIXME: test whether is_active is valid
270 $params = array_merge($defaults, $todo['params']);
271 $result = civicrm_api($dao->entity_type
, 'create', $params);
272 if ($result['is_error']) {
273 $this->onApiError($dao->entity_type
, 'create', $params, $result);
277 if (isset($todo['cleanup'])) {
278 $dao->cleanup
= $todo['cleanup'];
284 * Update an entity which (a) is believed to exist and which (b) ought to be
287 * @param CRM_Core_DAO_Managed $dao
289 public function disableEntity($dao) {
290 // FIXME: if ($dao->entity_type supports is_active) {
292 // FIXME cascading for payproc types?
295 'id' => $dao->entity_id
,
298 $result = civicrm_api($dao->entity_type
, 'create', $params);
299 if ($result['is_error']) {
300 $this->onApiError($dao->entity_type
, 'create', $params, $result);
306 * Remove a stale entity (if policy allows).
308 * @param CRM_Core_DAO_Managed $dao
311 public function removeStaleEntity($dao) {
312 $policy = empty($dao->cleanup
) ?
'always' : $dao->cleanup
;
323 $getRefCount = civicrm_api3($dao->entity_type
, 'getrefcount', [
325 'id' => $dao->entity_id
,
329 foreach ($getRefCount['values'] as $refCount) {
330 $total +
= $refCount['count'];
333 $doDelete = ($total == 0);
337 throw new \
Exception('Unrecognized cleanup policy: ' . $policy);
343 'id' => $dao->entity_id
,
345 $check = civicrm_api3($dao->entity_type
, 'get', $params);
346 if ((bool) $check['count']) {
347 $result = civicrm_api($dao->entity_type
, 'delete', $params);
348 if ($result['is_error']) {
349 $this->onApiError($dao->entity_type
, 'delete', $params, $result);
352 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', [
353 1 => [$dao->id
, 'Integer'],
363 public function getDeclarations() {
364 if ($this->declarations
=== NULL) {
365 $this->declarations
= [];
366 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
367 /** @var CRM_Core_Component_Info $component */
368 $this->declarations
= array_merge($this->declarations
, $component->getManagedEntities());
370 CRM_Utils_Hook
::managed($this->declarations
);
371 $this->declarations
= self
::cleanDeclarations($this->declarations
);
373 return $this->declarations
;
377 * @param array $modules
378 * Array<CRM_Core_Module>.
381 * indexed by is_active,name
383 protected static function createModuleIndex($modules) {
385 foreach ($modules as $module) {
386 $result[$module->is_active
][$module->name
] = $module;
392 * @param array $moduleIndex
393 * @param array $declarations
396 * indexed by module,name
398 protected static function createDeclarationIndex($moduleIndex, $declarations) {
400 if (!isset($moduleIndex[TRUE])) {
403 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
404 if ($module->is_active
) {
405 // need an empty array() for all active modules, even if there are no current $declarations
406 $result[$moduleName] = [];
409 foreach ($declarations as $declaration) {
410 $result[$declaration['module']][$declaration['name']] = $declaration;
416 * @param $declarations
418 * @return string|bool
419 * string on error, or FALSE
421 protected static function validate($declarations) {
422 foreach ($declarations as $declare) {
423 foreach (['name', 'module', 'entity', 'params'] as $key) {
424 if (empty($declare[$key])) {
425 $str = print_r($declare, TRUE);
426 return ("Managed Entity is missing field \"$key\": $str");
429 // FIXME: validate that each 'module' is known
435 * @param array $declarations
439 protected static function cleanDeclarations($declarations) {
440 foreach ($declarations as $name => &$declare) {
441 if (!array_key_exists('name', $declare)) {
442 $declare['name'] = $name;
445 return $declarations;
449 * @param string $entity
450 * @param string $action
451 * @param array $params
452 * @param array $result
456 protected function onApiError($entity, $action, $params, $result) {
457 CRM_Core_Error
::debug_var('ManagedEntities_failed', [
463 throw new Exception('API error: ' . $result['error_message']);