+ $this->removeStaleEntity($dao);
+ }
+ }
+
+ /**
+ * Create a new entity
+ *
+ * @param array $todo
+ * Entity specification (per hook_civicrm_managedEntities).
+ */
+ public function insertNewEntity($todo) {
+ $result = civicrm_api($todo['entity'], 'create', $todo['params']);
+ if ($result['is_error']) {
+ $this->onApiError($todo['entity'], 'create', $todo['params'], $result);
+ }
+
+ $dao = new CRM_Core_DAO_Managed();
+ $dao->module = $todo['module'];
+ $dao->name = $todo['name'];
+ $dao->entity_type = $todo['entity'];
+ $dao->entity_id = $result['id'];
+ $dao->cleanup = CRM_Utils_Array::value('cleanup', $todo);
+ $dao->save();
+ }
+
+ /**
+ * Update an entity which (a) is believed to exist and which (b) ought to be active.
+ *
+ * @param CRM_Core_DAO_Managed $dao
+ * @param array $todo
+ * Entity specification (per hook_civicrm_managedEntities).
+ */
+ public function updateExistingEntity($dao, $todo) {
+ $policy = CRM_Utils_Array::value('update', $todo, 'always');
+ $doUpdate = ($policy == 'always');
+
+ if ($doUpdate) {
+ $defaults = array(
+ 'id' => $dao->entity_id,
+ 'is_active' => 1, // FIXME: test whether is_active is valid
+ );
+ $params = array_merge($defaults, $todo['params']);
+ $result = civicrm_api($dao->entity_type, 'create', $params);
+ if ($result['is_error']) {
+ $this->onApiError($dao->entity_type, 'create',$params, $result);
+ }
+ }
+
+ if (isset($todo['cleanup'])) {
+ $dao->cleanup = $todo['cleanup'];
+ $dao->update();
+ }
+ }
+
+ /**
+ * Update an entity which (a) is believed to exist and which (b) ought to be
+ * inactive.
+ *
+ * @param CRM_Core_DAO_Managed $dao
+ */
+ public function disableEntity($dao) {
+ // FIXME: if ($dao->entity_type supports is_active) {
+ if (TRUE) {
+ // FIXME cascading for payproc types?
+ $params = array(
+ 'version' => 3,
+ 'id' => $dao->entity_id,
+ 'is_active' => 0,
+ );
+ $result = civicrm_api($dao->entity_type, 'create', $params);
+ if ($result['is_error']) {
+ $this->onApiError($dao->entity_type, 'create',$params, $result);
+ }
+ }
+ }
+
+ /**
+ * Remove a stale entity (if policy allows)
+ *
+ * @param CRM_Core_DAO_Managed $dao
+ */
+ public function removeStaleEntity($dao) {
+ $policy = empty($dao->cleanup) ? 'always' : $dao->cleanup;
+ switch ($policy) {
+ case 'always':
+ $doDelete = TRUE;
+ break;
+ case 'never':
+ $doDelete = FALSE;
+ break;
+ case 'unused':
+ $getRefCount = civicrm_api3($dao->entity_type, 'getrefcount', array(
+ 'debug' => 1,
+ 'id' => $dao->entity_id,
+ ));
+
+ $total = 0;
+ foreach ($getRefCount['values'] as $refCount) {
+ $total += $refCount['count'];
+ }
+
+ $doDelete = ($total == 0);
+ break;
+ default:
+ throw new \Exception('Unrecognized cleanup policy: ' . $policy);
+ }
+
+ if ($doDelete) {