freeze the contact field in non standalone context
[civicrm-core.git] / CRM / Core / ManagedEntities.php
1 <?php
2
3 /**
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.
7 */
8 class CRM_Core_ManagedEntities {
9
10 /**
11 * Get clean up options.
12 *
13 * @return array
14 */
15 public static function getCleanupOptions() {
16 return [
17 'always' => ts('Always'),
18 'never' => ts('Never'),
19 'unused' => ts('If Unused'),
20 ];
21 }
22
23 /**
24 * @var array
25 * Array($status => array($name => CRM_Core_Module)).
26 */
27 protected $moduleIndex;
28
29 /**
30 * @var array
31 * List of all entity declarations.
32 * @see CRM_Utils_Hook::managed()
33 */
34 protected $declarations;
35
36 /**
37 * Get an instance.
38 * @param bool $fresh
39 * @return \CRM_Core_ManagedEntities
40 */
41 public static function singleton($fresh = FALSE) {
42 static $singleton;
43 if ($fresh || !$singleton) {
44 $singleton = new CRM_Core_ManagedEntities(CRM_Core_Module::getAll(), NULL);
45 }
46 return $singleton;
47 }
48
49 /**
50 * Perform an asynchronous reconciliation when the transaction ends.
51 */
52 public static function scheduleReconciliation() {
53 CRM_Core_Transaction::addCallback(
54 CRM_Core_Transaction::PHASE_POST_COMMIT,
55 function () {
56 CRM_Core_ManagedEntities::singleton(TRUE)->reconcile();
57 },
58 [],
59 'ManagedEntities::reconcile'
60 );
61 }
62
63 /**
64 * @param array $modules
65 * CRM_Core_Module.
66 * @param array $declarations
67 * Per hook_civicrm_managed.
68 */
69 public function __construct($modules, $declarations) {
70 $this->moduleIndex = self::createModuleIndex($modules);
71
72 if ($declarations !== NULL) {
73 $this->declarations = self::cleanDeclarations($declarations);
74 }
75 else {
76 $this->declarations = NULL;
77 }
78 }
79
80 /**
81 * Read a managed entity using APIv3.
82 *
83 * @param string $moduleName
84 * The name of the module which declared entity.
85 * @param string $name
86 * The symbolic name of the entity.
87 * @return array|NULL
88 * API representation, or NULL if the entity does not exist
89 */
90 public function get($moduleName, $name) {
91 $dao = new CRM_Core_DAO_Managed();
92 $dao->module = $moduleName;
93 $dao->name = $name;
94 if ($dao->find(TRUE)) {
95 $params = [
96 'id' => $dao->entity_id,
97 ];
98 $result = NULL;
99 try {
100 $result = civicrm_api3($dao->entity_type, 'getsingle', $params);
101 }
102 catch (Exception $e) {
103 $this->onApiError($dao->entity_type, 'getsingle', $params, $result);
104 }
105 return $result;
106 }
107 else {
108 return NULL;
109 }
110 }
111
112 /**
113 * Identify any enabled/disabled modules. Add new entities, update
114 * existing entities, and remove orphaned (stale) entities.
115 *
116 * @throws Exception
117 */
118 public function reconcile() {
119 if ($error = $this->validate($this->getDeclarations())) {
120 throw new Exception($error);
121 }
122 $this->reconcileEnabledModules();
123 $this->reconcileDisabledModules();
124 $this->reconcileUnknownModules();
125 }
126
127 /**
128 * For all enabled modules, add new entities, update
129 * existing entities, and remove orphaned (stale) entities.
130 *
131 * @throws Exception
132 */
133 public function reconcileEnabledModules() {
134 // Note: any thing currently declared is necessarily from
135 // an active module -- because we got it from a hook!
136
137 // index by moduleName,name
138 $decls = self::createDeclarationIndex($this->moduleIndex, $this->getDeclarations());
139 foreach ($decls as $moduleName => $todos) {
140 if (isset($this->moduleIndex[TRUE][$moduleName])) {
141 $this->reconcileEnabledModule($this->moduleIndex[TRUE][$moduleName], $todos);
142 }
143 elseif (isset($this->moduleIndex[FALSE][$moduleName])) {
144 // do nothing -- module should get swept up later
145 }
146 else {
147 throw new Exception("Entity declaration references invalid or inactive module name [$moduleName]");
148 }
149 }
150 }
151
152 /**
153 * For one enabled module, add new entities, update existing entities,
154 * and remove orphaned (stale) entities.
155 *
156 * @param \CRM_Core_Module $module
157 * @param array $todos
158 * List of entities currently declared by this module.
159 * array(string $name => array $entityDef).
160 */
161 public function reconcileEnabledModule(CRM_Core_Module $module, $todos) {
162 $dao = new CRM_Core_DAO_Managed();
163 $dao->module = $module->name;
164 $dao->find();
165 while ($dao->fetch()) {
166 if (isset($todos[$dao->name]) && $todos[$dao->name]) {
167 // update existing entity; remove from $todos
168 $this->updateExistingEntity($dao, $todos[$dao->name]);
169 unset($todos[$dao->name]);
170 }
171 else {
172 // remove stale entity; not in $todos
173 $this->removeStaleEntity($dao);
174 }
175 }
176
177 // create new entities from leftover $todos
178 foreach ($todos as $name => $todo) {
179 $this->insertNewEntity($todo);
180 }
181 }
182
183 /**
184 * For all disabled modules, disable any managed entities.
185 */
186 public function reconcileDisabledModules() {
187 if (empty($this->moduleIndex[FALSE])) {
188 return;
189 }
190
191 $in = CRM_Core_DAO::escapeStrings(array_keys($this->moduleIndex[FALSE]));
192 $dao = new CRM_Core_DAO_Managed();
193 $dao->whereAdd("module in ($in)");
194 $dao->orderBy('id DESC');
195 $dao->find();
196 while ($dao->fetch()) {
197 $this->disableEntity($dao);
198
199 }
200 }
201
202 /**
203 * Remove any orphaned (stale) entities that are linked to
204 * unknown modules.
205 */
206 public function reconcileUnknownModules() {
207 $knownModules = [];
208 if (array_key_exists(0, $this->moduleIndex) && is_array($this->moduleIndex[0])) {
209 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex[0]));
210 }
211 if (array_key_exists(1, $this->moduleIndex) && is_array($this->moduleIndex[1])) {
212 $knownModules = array_merge($knownModules, array_keys($this->moduleIndex[1]));
213 }
214
215 $dao = new CRM_Core_DAO_Managed();
216 if (!empty($knownModules)) {
217 $in = CRM_Core_DAO::escapeStrings($knownModules);
218 $dao->whereAdd("module NOT IN ($in)");
219 $dao->orderBy('id DESC');
220 }
221 $dao->find();
222 while ($dao->fetch()) {
223 $this->removeStaleEntity($dao);
224 }
225 }
226
227 /**
228 * Create a new entity.
229 *
230 * @param array $todo
231 * Entity specification (per hook_civicrm_managedEntities).
232 */
233 public function insertNewEntity($todo) {
234 $result = civicrm_api($todo['entity'], 'create', $todo['params']);
235 if ($result['is_error']) {
236 $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
237 }
238
239 $dao = new CRM_Core_DAO_Managed();
240 $dao->module = $todo['module'];
241 $dao->name = $todo['name'];
242 $dao->entity_type = $todo['entity'];
243 $dao->entity_id = $result['id'];
244 $dao->cleanup = CRM_Utils_Array::value('cleanup', $todo);
245 $dao->save();
246 }
247
248 /**
249 * Update an entity which (a) is believed to exist and which (b) ought to be active.
250 *
251 * @param CRM_Core_DAO_Managed $dao
252 * @param array $todo
253 * Entity specification (per hook_civicrm_managedEntities).
254 */
255 public function updateExistingEntity($dao, $todo) {
256 $policy = CRM_Utils_Array::value('update', $todo, 'always');
257 $doUpdate = ($policy == 'always');
258
259 if ($doUpdate) {
260 $defaults = [
261 'id' => $dao->entity_id,
262 // FIXME: test whether is_active is valid
263 'is_active' => 1,
264 ];
265 $params = array_merge($defaults, $todo['params']);
266 $result = civicrm_api($dao->entity_type, 'create', $params);
267 if ($result['is_error']) {
268 $this->onApiError($dao->entity_type, 'create', $params, $result);
269 }
270 }
271
272 if (isset($todo['cleanup'])) {
273 $dao->cleanup = $todo['cleanup'];
274 $dao->update();
275 }
276 }
277
278 /**
279 * Update an entity which (a) is believed to exist and which (b) ought to be
280 * inactive.
281 *
282 * @param CRM_Core_DAO_Managed $dao
283 */
284 public function disableEntity($dao) {
285 // FIXME: if ($dao->entity_type supports is_active) {
286 if (TRUE) {
287 // FIXME cascading for payproc types?
288 $params = [
289 'version' => 3,
290 'id' => $dao->entity_id,
291 'is_active' => 0,
292 ];
293 $result = civicrm_api($dao->entity_type, 'create', $params);
294 if ($result['is_error']) {
295 $this->onApiError($dao->entity_type, 'create', $params, $result);
296 }
297 }
298 }
299
300 /**
301 * Remove a stale entity (if policy allows).
302 *
303 * @param CRM_Core_DAO_Managed $dao
304 * @throws Exception
305 */
306 public function removeStaleEntity($dao) {
307 $policy = empty($dao->cleanup) ? 'always' : $dao->cleanup;
308 switch ($policy) {
309 case 'always':
310 $doDelete = TRUE;
311 break;
312
313 case 'never':
314 $doDelete = FALSE;
315 break;
316
317 case 'unused':
318 $getRefCount = civicrm_api3($dao->entity_type, 'getrefcount', [
319 'debug' => 1,
320 'id' => $dao->entity_id,
321 ]);
322
323 $total = 0;
324 foreach ($getRefCount['values'] as $refCount) {
325 $total += $refCount['count'];
326 }
327
328 $doDelete = ($total == 0);
329 break;
330
331 default:
332 throw new \Exception('Unrecognized cleanup policy: ' . $policy);
333 }
334
335 if ($doDelete) {
336 $params = [
337 'version' => 3,
338 'id' => $dao->entity_id,
339 ];
340 $check = civicrm_api3($dao->entity_type, 'get', $params);
341 if ((bool) $check['count']) {
342 $result = civicrm_api($dao->entity_type, 'delete', $params);
343 if ($result['is_error']) {
344 $this->onApiError($dao->entity_type, 'delete', $params, $result);
345 }
346 }
347 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', [
348 1 => [$dao->id, 'Integer'],
349 ]);
350 }
351 }
352
353 /**
354 * Get declarations.
355 *
356 * @return array|null
357 */
358 public function getDeclarations() {
359 if ($this->declarations === NULL) {
360 $this->declarations = [];
361 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
362 /** @var CRM_Core_Component_Info $component */
363 $this->declarations = array_merge($this->declarations, $component->getManagedEntities());
364 }
365 CRM_Utils_Hook::managed($this->declarations);
366 $this->declarations = self::cleanDeclarations($this->declarations);
367 }
368 return $this->declarations;
369 }
370
371 /**
372 * @param array $modules
373 * Array<CRM_Core_Module>.
374 *
375 * @return array
376 * indexed by is_active,name
377 */
378 protected static function createModuleIndex($modules) {
379 $result = [];
380 foreach ($modules as $module) {
381 $result[$module->is_active][$module->name] = $module;
382 }
383 return $result;
384 }
385
386 /**
387 * @param array $moduleIndex
388 * @param array $declarations
389 *
390 * @return array
391 * indexed by module,name
392 */
393 protected static function createDeclarationIndex($moduleIndex, $declarations) {
394 $result = [];
395 if (!isset($moduleIndex[TRUE])) {
396 return $result;
397 }
398 foreach ($moduleIndex[TRUE] as $moduleName => $module) {
399 if ($module->is_active) {
400 // need an empty array() for all active modules, even if there are no current $declarations
401 $result[$moduleName] = [];
402 }
403 }
404 foreach ($declarations as $declaration) {
405 $result[$declaration['module']][$declaration['name']] = $declaration;
406 }
407 return $result;
408 }
409
410 /**
411 * @param $declarations
412 *
413 * @return string|bool
414 * string on error, or FALSE
415 */
416 protected static function validate($declarations) {
417 foreach ($declarations as $declare) {
418 foreach (['name', 'module', 'entity', 'params'] as $key) {
419 if (empty($declare[$key])) {
420 $str = print_r($declare, TRUE);
421 return ("Managed Entity is missing field \"$key\": $str");
422 }
423 }
424 // FIXME: validate that each 'module' is known
425 }
426 return FALSE;
427 }
428
429 /**
430 * @param array $declarations
431 *
432 * @return array
433 */
434 protected static function cleanDeclarations($declarations) {
435 foreach ($declarations as $name => &$declare) {
436 if (!array_key_exists('name', $declare)) {
437 $declare['name'] = $name;
438 }
439 }
440 return $declarations;
441 }
442
443 /**
444 * @param string $entity
445 * @param string $action
446 * @param array $params
447 * @param array $result
448 *
449 * @throws Exception
450 */
451 protected function onApiError($entity, $action, $params, $result) {
452 CRM_Core_Error::debug_var('ManagedEntities_failed', [
453 'entity' => $entity,
454 'action' => $action,
455 'params' => $params,
456 'result' => $result,
457 ]);
458 throw new Exception('API error: ' . $result['error_message']);
459 }
460
461 }