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 public static function singleton($fresh = FALSE) {
33 if ($fresh ||
!$singleton) {
34 $singleton = new CRM_Core_ManagedEntities(CRM_Core_Module
::getAll(), NULL);
40 * Perform an asynchronous reconciliation when the transaction ends.
42 public static function scheduleReconcilation() {
43 CRM_Core_Transaction
::addCallback(
44 CRM_Core_Transaction
::PHASE_POST_COMMIT
,
46 CRM_Core_ManagedEntities
::singleton(TRUE)->reconcile();
49 'ManagedEntities::reconcile'
54 * @param array $modules CRM_Core_Module
55 * @param array $declarations per hook_civicrm_managed
57 public function __construct($modules, $declarations) {
58 $this->moduleIndex
= self
::createModuleIndex($modules);
60 if ($declarations !== NULL) {
61 $this->declarations
= self
::cleanDeclarations($declarations);
63 $this->declarations
= NULL;
68 * Read the managed entity
70 * @return array|NULL API representation, or NULL if the entity does not exist
72 public function get($moduleName, $name) {
73 $dao = new CRM_Core_DAO_Managed();
74 $dao->module
= $moduleName;
76 if ($dao->find(TRUE)) {
78 'id' => $dao->entity_id
,
82 $result = civicrm_api3($dao->entity_type
, 'getsingle', $params);
84 catch (Exception
$e) {
85 $this->onApiError($dao->entity_type
, 'getsingle', $params, $result);
93 public function reconcile() {
94 if ($error = $this->validate($this->getDeclarations())) {
95 throw new Exception($error);
97 $this->reconcileEnabledModules();
98 $this->reconcileDisabledModules();
99 $this->reconcileUnknownModules();
103 public function reconcileEnabledModules() {
104 // Note: any thing currently declared is necessarily from
105 // an active module -- because we got it from a hook!
107 // index by moduleName,name
108 $decls = self
::createDeclarationIndex($this->moduleIndex
, $this->getDeclarations());
109 foreach ($decls as $moduleName => $todos) {
110 if (isset($this->moduleIndex
[TRUE][$moduleName])) {
111 $this->reconcileEnabledModule($this->moduleIndex
[TRUE][$moduleName], $todos);
112 } elseif (isset($this->moduleIndex
[FALSE][$moduleName])) {
113 // do nothing -- module should get swept up later
115 throw new Exception("Entity declaration references invalid or inactive module name [$moduleName]");
121 * Create, update, and delete entities declared by an active module
123 * @param \CRM_Core_Module|string $module string
124 * @param $todos array $name => array()
126 public function reconcileEnabledModule(CRM_Core_Module
$module, $todos) {
127 $dao = new CRM_Core_DAO_Managed();
128 $dao->module
= $module->name
;
130 while ($dao->fetch()) {
131 if (isset($todos[$dao->name
]) && $todos[$dao->name
]) {
132 // update existing entity; remove from $todos
133 $this->updateExistingEntity($dao, $todos[$dao->name
]);
134 unset($todos[$dao->name
]);
136 // remove stale entity; not in $todos
137 $this->removeStaleEntity($dao);
141 // create new entities from leftover $todos
142 foreach ($todos as $name => $todo) {
143 $this->insertNewEntity($todo);
147 public function reconcileDisabledModules() {
148 if (empty($this->moduleIndex
[FALSE])) {
152 $in = CRM_Core_DAO
::escapeStrings(array_keys($this->moduleIndex
[FALSE]));
153 $dao = new CRM_Core_DAO_Managed();
154 $dao->whereAdd("module in ($in)");
156 while ($dao->fetch()) {
157 $this->disableEntity($dao);
162 public function reconcileUnknownModules() {
163 $knownModules = array();
164 if (array_key_exists(0, $this->moduleIndex
) && is_array($this->moduleIndex
[0])) {
165 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[0]));
167 if (array_key_exists(1, $this->moduleIndex
) && is_array($this->moduleIndex
[1])) {
168 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[1]));
172 $dao = new CRM_Core_DAO_Managed();
173 if (!empty($knownModules)) {
174 $in = CRM_Core_DAO
::escapeStrings($knownModules);
175 $dao->whereAdd("module NOT IN ($in)");
178 while ($dao->fetch()) {
179 $this->removeStaleEntity($dao);
184 * Create a new entity
186 * @param array $todo entity specification (per hook_civicrm_managedEntities)
188 public function insertNewEntity($todo) {
189 $result = civicrm_api($todo['entity'], 'create', $todo['params']);
190 if ($result['is_error']) {
191 $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
194 $dao = new CRM_Core_DAO_Managed();
195 $dao->module
= $todo['module'];
196 $dao->name
= $todo['name'];
197 $dao->entity_type
= $todo['entity'];
198 $dao->entity_id
= $result['id'];
199 $dao->cleanup
= CRM_Utils_Array
::value('cleanup', $todo);
204 * Update an entity which (a) is believed to exist and which (b) ought to be active.
206 * @param CRM_Core_DAO_Managed $dao
207 * @param array $todo entity specification (per hook_civicrm_managedEntities)
209 public function updateExistingEntity($dao, $todo) {
210 $policy = CRM_Utils_Array
::value('update', $todo, 'always');
211 $doUpdate = ($policy == 'always');
215 'id' => $dao->entity_id
,
216 'is_active' => 1, // FIXME: test whether is_active is valid
218 $params = array_merge($defaults, $todo['params']);
219 $result = civicrm_api($dao->entity_type
, 'create', $params);
220 if ($result['is_error']) {
221 $this->onApiError($dao->entity_type
, 'create',$params, $result);
225 if (isset($todo['cleanup'])) {
226 $dao->cleanup
= $todo['cleanup'];
232 * Update an entity which (a) is believed to exist and which (b) ought to be
235 * @param CRM_Core_DAO_Managed $dao
237 public function disableEntity($dao) {
238 // FIXME: if ($dao->entity_type supports is_active) {
240 // FIXME cascading for payproc types?
243 'id' => $dao->entity_id
,
246 $result = civicrm_api($dao->entity_type
, 'create', $params);
247 if ($result['is_error']) {
248 $this->onApiError($dao->entity_type
, 'create',$params, $result);
254 * Remove a stale entity (if policy allows)
256 * @param CRM_Core_DAO_Managed $dao
258 public function removeStaleEntity($dao) {
259 $policy = empty($dao->cleanup
) ?
'always' : $dao->cleanup
;
268 $getRefCount = civicrm_api3($dao->entity_type
, 'getrefcount', array(
270 'id' => $dao->entity_id
274 foreach ($getRefCount['values'] as $refCount) {
275 $total +
= $refCount['count'];
278 $doDelete = ($total == 0);
281 throw new \
Exception('Unrecognized cleanup policy: ' . $policy);
287 'id' => $dao->entity_id
,
289 $result = civicrm_api($dao->entity_type
, 'delete', $params);
290 if ($result['is_error']) {
291 $this->onApiError($dao->entity_type
, 'delete', $params, $result);
294 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', array(
295 1 => array($dao->id
, 'Integer')
300 public function getDeclarations() {
301 if ($this->declarations
=== NULL) {
302 $this->declarations
= array();
303 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
304 /** @var CRM_Core_Component_Info $component */
305 $this->declarations
= array_merge($this->declarations
, $component->getManagedEntities());
307 CRM_Utils_Hook
::managed($this->declarations
);
308 $this->declarations
= self
::cleanDeclarations($this->declarations
);
310 return $this->declarations
;
316 * @return array indexed by is_active,name
318 protected static function createModuleIndex($modules) {
320 foreach ($modules as $module) {
321 $result[$module->is_active
][$module->name
] = $module;
327 * @param $moduleIndex
328 * @param $declarations
330 * @return array indexed by module,name
332 protected static function createDeclarationIndex($moduleIndex, $declarations) {
334 if (!isset($moduleIndex[TRUE])) {
337 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
338 if ($module->is_active
) {
339 // need an empty array() for all active modules, even if there are no current $declarations
340 $result[$moduleName] = array();
343 foreach ($declarations as $declaration) {
344 $result[$declaration['module']][$declaration['name']] = $declaration;
350 * @param $declarations
352 * @return mixed string on error, or FALSE
354 protected static function validate($declarations) {
355 foreach ($declarations as $declare) {
356 foreach (array('name', 'module', 'entity', 'params') as $key) {
357 if (empty($declare[$key])) {
358 $str = print_r($declare, TRUE);
359 return ("Managed Entity is missing field \"$key\": $str");
362 // FIXME: validate that each 'module' is known
368 * @param $declarations
372 protected static function cleanDeclarations($declarations) {
373 foreach ($declarations as $name => &$declare) {
374 if (!array_key_exists('name', $declare)) {
375 $declare['name'] = $name;
378 return $declarations;
382 * @param string $entity
383 * @param string $action
384 * @param array $params
385 * @param array $result
389 protected function onApiError($entity, $action, $params, $result) {
390 CRM_Core_Error
::debug_var('ManagedEntities_failed', array(
396 throw new Exception('API error: ' . $result['error_message']);