Merge pull request #11881 from yashodha/CRM-21854
[civicrm-core.git] / CRM / Core / ManagedEntities.php
index 4de184a28c1b1d11092c1f98481327da4c5e87f4..fe9631d0dbd0a0ef1d5b3bd9413bec6c0e42013b 100644 (file)
@@ -191,6 +191,7 @@ class CRM_Core_ManagedEntities {
     $in = CRM_Core_DAO::escapeStrings(array_keys($this->moduleIndex[FALSE]));
     $dao = new CRM_Core_DAO_Managed();
     $dao->whereAdd("module in ($in)");
+    $dao->orderBy('id DESC');
     $dao->find();
     while ($dao->fetch()) {
       $this->disableEntity($dao);
@@ -215,6 +216,7 @@ class CRM_Core_ManagedEntities {
     if (!empty($knownModules)) {
       $in = CRM_Core_DAO::escapeStrings($knownModules);
       $dao->whereAdd("module NOT IN ($in)");
+      $dao->orderBy('id DESC');
     }
     $dao->find();
     while ($dao->fetch()) {
@@ -334,11 +336,13 @@ class CRM_Core_ManagedEntities {
         'version' => 3,
         'id' => $dao->entity_id,
       );
-      $result = civicrm_api($dao->entity_type, 'delete', $params);
-      if ($result['is_error']) {
-        $this->onApiError($dao->entity_type, 'delete', $params, $result);
+      $check = civicrm_api3($dao->entity_type, 'get', $params);
+      if ((bool) $check['count']) {
+        $result = civicrm_api($dao->entity_type, 'delete', $params);
+        if ($result['is_error']) {
+          $this->onApiError($dao->entity_type, 'delete', $params, $result);
+        }
       }
-
       CRM_Core_DAO::executeQuery('DELETE FROM civicrm_managed WHERE id = %1', array(
         1 => array($dao->id, 'Integer'),
       ));