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
76 * API representation, or NULL if the entity does not exist
78 public function get($moduleName, $name) {
79 $dao = new CRM_Core_DAO_Managed();
80 $dao->module
= $moduleName;
82 if ($dao->find(TRUE)) {
84 'id' => $dao->entity_id
,
88 $result = civicrm_api3($dao->entity_type
, 'getsingle', $params);
90 catch (Exception
$e) {
91 $this->onApiError($dao->entity_type
, 'getsingle', $params, $result);
100 public function reconcile() {
101 if ($error = $this->validate($this->getDeclarations())) {
102 throw new Exception($error);
104 $this->reconcileEnabledModules();
105 $this->reconcileDisabledModules();
106 $this->reconcileUnknownModules();
110 public function reconcileEnabledModules() {
111 // Note: any thing currently declared is necessarily from
112 // an active module -- because we got it from a hook!
114 // index by moduleName,name
115 $decls = self
::createDeclarationIndex($this->moduleIndex
, $this->getDeclarations());
116 foreach ($decls as $moduleName => $todos) {
117 if (isset($this->moduleIndex
[TRUE][$moduleName])) {
118 $this->reconcileEnabledModule($this->moduleIndex
[TRUE][$moduleName], $todos);
120 elseif (isset($this->moduleIndex
[FALSE][$moduleName])) {
121 // do nothing -- module should get swept up later
124 throw new Exception("Entity declaration references invalid or inactive module name [$moduleName]");
130 * Create, update, and delete entities declared by an active module
132 * @param \CRM_Core_Module|string $module string
133 * @param array $todos
136 public function reconcileEnabledModule(CRM_Core_Module
$module, $todos) {
137 $dao = new CRM_Core_DAO_Managed();
138 $dao->module
= $module->name
;
140 while ($dao->fetch()) {
141 if (isset($todos[$dao->name
]) && $todos[$dao->name
]) {
142 // update existing entity; remove from $todos
143 $this->updateExistingEntity($dao, $todos[$dao->name
]);
144 unset($todos[$dao->name
]);
147 // remove stale entity; not in $todos
148 $this->removeStaleEntity($dao);
152 // create new entities from leftover $todos
153 foreach ($todos as $name => $todo) {
154 $this->insertNewEntity($todo);
158 public function reconcileDisabledModules() {
159 if (empty($this->moduleIndex
[FALSE])) {
163 $in = CRM_Core_DAO
::escapeStrings(array_keys($this->moduleIndex
[FALSE]));
164 $dao = new CRM_Core_DAO_Managed();
165 $dao->whereAdd("module in ($in)");
167 while ($dao->fetch()) {
168 $this->disableEntity($dao);
173 public function reconcileUnknownModules() {
174 $knownModules = array();
175 if (array_key_exists(0, $this->moduleIndex
) && is_array($this->moduleIndex
[0])) {
176 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[0]));
178 if (array_key_exists(1, $this->moduleIndex
) && is_array($this->moduleIndex
[1])) {
179 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex
[1]));
183 $dao = new CRM_Core_DAO_Managed();
184 if (!empty($knownModules)) {
185 $in = CRM_Core_DAO
::escapeStrings($knownModules);
186 $dao->whereAdd("module NOT IN ($in)");
189 while ($dao->fetch()) {
190 $this->removeStaleEntity($dao);
195 * Create a new entity
198 * Entity specification (per hook_civicrm_managedEntities).
200 public function insertNewEntity($todo) {
201 $result = civicrm_api($todo['entity'], 'create', $todo['params']);
202 if ($result['is_error']) {
203 $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
206 $dao = new CRM_Core_DAO_Managed();
207 $dao->module
= $todo['module'];
208 $dao->name
= $todo['name'];
209 $dao->entity_type
= $todo['entity'];
210 $dao->entity_id
= $result['id'];
211 $dao->cleanup
= CRM_Utils_Array
::value('cleanup', $todo);
216 * Update an entity which (a) is believed to exist and which (b) ought to be active.
218 * @param CRM_Core_DAO_Managed $dao
220 * Entity specification (per hook_civicrm_managedEntities).
222 public function updateExistingEntity($dao, $todo) {
223 $policy = CRM_Utils_Array
::value('update', $todo, 'always');
224 $doUpdate = ($policy == 'always');
228 'id' => $dao->entity_id
,
229 'is_active' => 1, // FIXME: test whether is_active is valid
231 $params = array_merge($defaults, $todo['params']);
232 $result = civicrm_api($dao->entity_type
, 'create', $params);
233 if ($result['is_error']) {
234 $this->onApiError($dao->entity_type
, 'create', $params, $result);
238 if (isset($todo['cleanup'])) {
239 $dao->cleanup
= $todo['cleanup'];
245 * Update an entity which (a) is believed to exist and which (b) ought to be
248 * @param CRM_Core_DAO_Managed $dao
250 public function disableEntity($dao) {
251 // FIXME: if ($dao->entity_type supports is_active) {
253 // FIXME cascading for payproc types?
256 'id' => $dao->entity_id
,
259 $result = civicrm_api($dao->entity_type
, 'create', $params);
260 if ($result['is_error']) {
261 $this->onApiError($dao->entity_type
, 'create', $params, $result);
267 * Remove a stale entity (if policy allows)
269 * @param CRM_Core_DAO_Managed $dao
271 public function removeStaleEntity($dao) {
272 $policy = empty($dao->cleanup
) ?
'always' : $dao->cleanup
;
283 $getRefCount = civicrm_api3($dao->entity_type
, 'getrefcount', array(
285 'id' => $dao->entity_id
,
289 foreach ($getRefCount['values'] as $refCount) {
290 $total +
= $refCount['count'];
293 $doDelete = ($total == 0);
297 throw new \
Exception('Unrecognized cleanup policy: ' . $policy);
303 'id' => $dao->entity_id
,
305 $result = civicrm_api($dao->entity_type
, 'delete', $params);
306 if ($result['is_error']) {
307 $this->onApiError($dao->entity_type
, 'delete', $params, $result);
310 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', array(
311 1 => array($dao->id
, 'Integer'),
316 public function getDeclarations() {
317 if ($this->declarations
=== NULL) {
318 $this->declarations
= array();
319 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
320 /** @var CRM_Core_Component_Info $component */
321 $this->declarations
= array_merge($this->declarations
, $component->getManagedEntities());
323 CRM_Utils_Hook
::managed($this->declarations
);
324 $this->declarations
= self
::cleanDeclarations($this->declarations
);
326 return $this->declarations
;
333 * indexed by is_active,name
335 protected static function createModuleIndex($modules) {
337 foreach ($modules as $module) {
338 $result[$module->is_active
][$module->name
] = $module;
344 * @param $moduleIndex
345 * @param $declarations
348 * indexed by module,name
350 protected static function createDeclarationIndex($moduleIndex, $declarations) {
352 if (!isset($moduleIndex[TRUE])) {
355 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
356 if ($module->is_active
) {
357 // need an empty array() for all active modules, even if there are no current $declarations
358 $result[$moduleName] = array();
361 foreach ($declarations as $declaration) {
362 $result[$declaration['module']][$declaration['name']] = $declaration;
368 * @param $declarations
370 * @return string|bool
371 * string on error, or FALSE
373 protected static function validate($declarations) {
374 foreach ($declarations as $declare) {
375 foreach (array('name', 'module', 'entity', 'params') as $key) {
376 if (empty($declare[$key])) {
377 $str = print_r($declare, TRUE);
378 return ("Managed Entity is missing field \"$key\": $str");
381 // FIXME: validate that each 'module' is known
387 * @param array $declarations
391 protected static function cleanDeclarations($declarations) {
392 foreach ($declarations as $name => &$declare) {
393 if (!array_key_exists('name', $declare)) {
394 $declare['name'] = $name;
397 return $declarations;
401 * @param string $entity
402 * @param string $action
403 * @param array $params
404 * @param array $result
408 protected function onApiError($entity, $action, $params, $result) {
409 CRM_Core_Error
::debug_var('ManagedEntities_failed', array(
415 throw new Exception('API error: ' . $result['error_message']);