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
{
10 public static function getCleanupOptions() {
12 'always' => ts('Always'),
13 'never' => ts('Never'),
14 'unused' => ts('If Unused'),
19 * @var array($status => array($name => CRM_Core_Module))
21 protected $moduleIndex;
24 * @var array per hook_civicrm_managed
26 protected $declarations;
31 * @return \CRM_Core_ManagedEntities
33 public static function singleton($fresh = FALSE) {
35 if ($fresh ||
!$singleton) {
36 $singleton = new CRM_Core_ManagedEntities(CRM_Core_Module
::getAll(), NULL);
42 * Perform an asynchronous reconciliation when the transaction ends.
44 public static function scheduleReconciliation() {
45 CRM_Core_Transaction
::addCallback(
46 CRM_Core_Transaction
::PHASE_POST_COMMIT
,
48 CRM_Core_ManagedEntities
::singleton(TRUE)->reconcile();
51 'ManagedEntities::reconcile'
56 * @param array $modules
58 * @param array $declarations
59 * Per hook_civicrm_managed.
61 public function __construct($modules, $declarations) {
62 $this->moduleIndex
= self
::createModuleIndex($modules);
64 if ($declarations !== NULL) {
65 $this->declarations
= self
::cleanDeclarations($declarations);
68 $this->declarations
= NULL;
73 * Read the managed entity
75 * @return array|NULL API representation, or NULL if the entity does not exist
77 public function get($moduleName, $name) {
78 $dao = new CRM_Core_DAO_Managed();
79 $dao->module
= $moduleName;
81 if ($dao->find(TRUE)) {
83 'id' => $dao->entity_id
,
87 $result = civicrm_api3($dao->entity_type
, 'getsingle', $params);
89 catch (Exception
$e) {
90 $this->onApiError($dao->entity_type
, 'getsingle', $params, $result);
99 public function reconcile() {
100 if ($error = $this->validate($this->getDeclarations())) {
101 throw new Exception($error);
103 $this->reconcileEnabledModules();
104 $this->reconcileDisabledModules();
105 $this->reconcileUnknownModules();
109 public function reconcileEnabledModules() {
110 // Note: any thing currently declared is necessarily from
111 // an active module -- because we got it from a hook!
113 // index by moduleName,name
114 $decls = self
::createDeclarationIndex($this->moduleIndex
, $this->getDeclarations());
115 foreach ($decls as $moduleName => $todos) {
116 if (isset($this->moduleIndex
[TRUE][$moduleName])) {
117 $this->reconcileEnabledModule($this->moduleIndex
[TRUE][$moduleName], $todos);
119 elseif (isset($this->moduleIndex
[FALSE][$moduleName])) {
120 // do nothing -- module should get swept up later
123 throw new Exception("Entity declaration references invalid or inactive module name [$moduleName]");
129 * Create, update, and delete entities declared by an active module
131 * @param \CRM_Core_Module|string $module string
133 * Array $name => array().
135 public function reconcileEnabledModule(CRM_Core_Module
$module, $todos) {
136 $dao = new CRM_Core_DAO_Managed();
137 $dao->module
= $module->name
;
139 while ($dao->fetch()) {
140 if (isset($todos[$dao->name
]) && $todos[$dao->name
]) {
141 // update existing entity; remove from $todos
142 $this->updateExistingEntity($dao, $todos[$dao->name
]);
143 unset($todos[$dao->name
]);
146 // remove stale entity; not in $todos
147 $this->removeStaleEntity($dao);
151 // create new entities from leftover $todos
152 foreach ($todos as $name => $todo) {
153 $this->insertNewEntity($todo);
157 public function reconcileDisabledModules() {
158 if (empty($this->moduleIndex
[FALSE])) {
162 $in = CRM_Core_DAO
::escapeStrings(array_keys($this->moduleIndex
[FALSE]));
163 $dao = new CRM_Core_DAO_Managed();
164 $dao->whereAdd("module in ($in)");
166 while ($dao->fetch()) {
167 $this->disableEntity($dao);
172 public function reconcileUnknownModules() {
173 $knownModules = array();
174 if (array_key_exists(0, $this->moduleIndex
) && is_array($this->moduleIndex
[0])) {
175 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[0]));
177 if (array_key_exists(1, $this->moduleIndex
) && is_array($this->moduleIndex
[1])) {
178 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[1]));
182 $dao = new CRM_Core_DAO_Managed();
183 if (!empty($knownModules)) {
184 $in = CRM_Core_DAO
::escapeStrings($knownModules);
185 $dao->whereAdd("module NOT IN ($in)");
188 while ($dao->fetch()) {
189 $this->removeStaleEntity($dao);
194 * Create a new entity
197 * Entity specification (per hook_civicrm_managedEntities).
199 public function insertNewEntity($todo) {
200 $result = civicrm_api($todo['entity'], 'create', $todo['params']);
201 if ($result['is_error']) {
202 $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
205 $dao = new CRM_Core_DAO_Managed();
206 $dao->module
= $todo['module'];
207 $dao->name
= $todo['name'];
208 $dao->entity_type
= $todo['entity'];
209 $dao->entity_id
= $result['id'];
210 $dao->cleanup
= CRM_Utils_Array
::value('cleanup', $todo);
215 * Update an entity which (a) is believed to exist and which (b) ought to be active.
217 * @param CRM_Core_DAO_Managed $dao
219 * Entity specification (per hook_civicrm_managedEntities).
221 public function updateExistingEntity($dao, $todo) {
222 $policy = CRM_Utils_Array
::value('update', $todo, 'always');
223 $doUpdate = ($policy == 'always');
227 'id' => $dao->entity_id
,
228 'is_active' => 1, // FIXME: test whether is_active is valid
230 $params = array_merge($defaults, $todo['params']);
231 $result = civicrm_api($dao->entity_type
, 'create', $params);
232 if ($result['is_error']) {
233 $this->onApiError($dao->entity_type
, 'create',$params, $result);
237 if (isset($todo['cleanup'])) {
238 $dao->cleanup
= $todo['cleanup'];
244 * Update an entity which (a) is believed to exist and which (b) ought to be
247 * @param CRM_Core_DAO_Managed $dao
249 public function disableEntity($dao) {
250 // FIXME: if ($dao->entity_type supports is_active) {
252 // FIXME cascading for payproc types?
255 'id' => $dao->entity_id
,
258 $result = civicrm_api($dao->entity_type
, 'create', $params);
259 if ($result['is_error']) {
260 $this->onApiError($dao->entity_type
, 'create',$params, $result);
266 * Remove a stale entity (if policy allows)
268 * @param CRM_Core_DAO_Managed $dao
270 public function removeStaleEntity($dao) {
271 $policy = empty($dao->cleanup
) ?
'always' : $dao->cleanup
;
280 $getRefCount = civicrm_api3($dao->entity_type
, 'getrefcount', array(
282 'id' => $dao->entity_id
286 foreach ($getRefCount['values'] as $refCount) {
287 $total +
= $refCount['count'];
290 $doDelete = ($total == 0);
293 throw new \
Exception('Unrecognized cleanup policy: ' . $policy);
299 'id' => $dao->entity_id
,
301 $result = civicrm_api($dao->entity_type
, 'delete', $params);
302 if ($result['is_error']) {
303 $this->onApiError($dao->entity_type
, 'delete', $params, $result);
306 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', array(
307 1 => array($dao->id
, 'Integer')
312 public function getDeclarations() {
313 if ($this->declarations
=== NULL) {
314 $this->declarations
= array();
315 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
316 /** @var CRM_Core_Component_Info $component */
317 $this->declarations
= array_merge($this->declarations
, $component->getManagedEntities());
319 CRM_Utils_Hook
::managed($this->declarations
);
320 $this->declarations
= self
::cleanDeclarations($this->declarations
);
322 return $this->declarations
;
328 * @return array indexed by is_active,name
330 protected static function createModuleIndex($modules) {
332 foreach ($modules as $module) {
333 $result[$module->is_active
][$module->name
] = $module;
339 * @param $moduleIndex
340 * @param $declarations
342 * @return array indexed by module,name
344 protected static function createDeclarationIndex($moduleIndex, $declarations) {
346 if (!isset($moduleIndex[TRUE])) {
349 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
350 if ($module->is_active
) {
351 // need an empty array() for all active modules, even if there are no current $declarations
352 $result[$moduleName] = array();
355 foreach ($declarations as $declaration) {
356 $result[$declaration['module']][$declaration['name']] = $declaration;
362 * @param $declarations
364 * @return mixed string on error, or FALSE
366 protected static function validate($declarations) {
367 foreach ($declarations as $declare) {
368 foreach (array('name', 'module', 'entity', 'params') as $key) {
369 if (empty($declare[$key])) {
370 $str = print_r($declare, TRUE);
371 return ("Managed Entity is missing field \"$key\": $str");
374 // FIXME: validate that each 'module' is known
380 * @param $declarations
384 protected static function cleanDeclarations($declarations) {
385 foreach ($declarations as $name => &$declare) {
386 if (!array_key_exists('name', $declare)) {
387 $declare['name'] = $name;
390 return $declarations;
394 * @param string $entity
395 * @param string $action
396 * @param array $params
397 * @param array $result
401 protected function onApiError($entity, $action, $params, $result) {
402 CRM_Core_Error
::debug_var('ManagedEntities_failed', array(
408 throw new Exception('API error: ' . $result['error_message']);