remove newly introduced trailing spaces & tabs, new windows line-breaks also present...
[civicrm-core.git] / CRM / Contact / BAO / Contact.php
index 5988ab2d52263ef9590c80308fb4ac5e16b2ca58..dcff832d7eca963232367c93e357dd6435b82c16 100644 (file)
@@ -324,16 +324,15 @@ class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact {
       if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
         'is_enabled'
       )) {
-        // in order to make sure that every contact must be added to a group (CRM-4613) -
+        // Enabling multisite causes the contact to be added to the domain group
         $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
-        if (CRM_Utils_Array::value('group', $params) && is_array($params['group'])) {
-          $grpFlp = array_flip($params['group']);
-          if (!array_key_exists(1, $grpFlp)) {
+        if(!empty($domainGroupID)){
+          if (CRM_Utils_Array::value('group', $params) && is_array($params['group'])) {
             $params['group'][$domainGroupID] = 1;
           }
-        }
-        else {
-          $params['group'] = array($domainGroupID => 1);
+          else {
+            $params['group'] = array($domainGroupID => 1);
+          }
         }
       }
 
@@ -518,9 +517,9 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
       }
     }
 
-    CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::individualPrefix(), $reverse);
-    CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::individualSuffix(), $reverse);
-    CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::gender(), $reverse);
+    CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
+    CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
+    CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
 
     //lookup value of email/postal greeting, addressee, CRM-4575
     foreach (self::$_greetingTypes as $greeting) {
@@ -540,12 +539,12 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
       foreach ($defaults[$name] as $count => & $values) {
 
         //get location type id.
-        CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::locationType(), $reverse);
+        CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
 
         if ($name == 'address') {
           // FIXME: lookupValue doesn't work for vcard_name
           if (CRM_Utils_Array::value('location_type_id', $values)) {
-            $vcardNames = CRM_Core_PseudoConstant::locationVcardName();
+            $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
             $values['vcard_name'] = $vcardNames[$values['location_type_id']];
           }
 
@@ -610,7 +609,7 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
         if ($name == 'im') {
           CRM_Utils_Array::lookupValue($values,
             'provider',
-            CRM_Core_PseudoConstant::IMProvider(),
+            CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
             $reverse
           );
         }
@@ -618,7 +617,7 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
         if ($name == 'phone') {
           CRM_Utils_Array::lookupValue($values,
             'phone_type',
-            CRM_Core_PseudoConstant::phoneType(),
+            CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
             $reverse
           );
         }
@@ -725,6 +724,13 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
       return FALSE;
     }
 
+    // CRM-12929
+    // Restrict contact to be delete if contact has financial trxns
+    $error = NULL;
+    if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) {
+      return FALSE;
+    }
+
     // make sure this contact_id does not have any membership types
     $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
       $id,
@@ -772,19 +778,31 @@ WHERE     civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
       $logDAO->entity_table = 'civicrm_contact';
       $logDAO->entity_id = $id;
       $logDAO->delete();
-      
+
       // delete contact participants CRM-12155
       CRM_Event_BAO_Participant::deleteContactParticipant($id);
 
       // delete contact contributions CRM-12155
       CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
-      
+
       // do activity cleanup, CRM-5604
       CRM_Activity_BAO_Activity::cleanupActivity($id);
 
       // delete all notes related to contact
       CRM_Core_BAO_Note::cleanContactNotes($id);
 
+      // delete cases related to contact
+      $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
+      if (!empty($contactCases)) {
+        foreach ($contactCases as $caseId) {
+          //check if case is associate with other contact or not.
+          $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
+          if (count($caseContactId) <= 1) {
+            CRM_Case_BAO_Case::deleteCase($caseId);
+          }
+        }
+      }
+
       $contact->delete();
     }
     else {
@@ -1073,8 +1091,7 @@ WHERE id={$id}; ";
    * combine all the importable fields from the lower levels object
    *
    * The ordering is important, since currently we do not have a weight
-   * scheme. Adding weight is super important and should be done in the
-   * next week or so, before this can be called complete.
+   * scheme. Adding weight is super important
    *
    * @param int     $contactType     contact Type
    * @param boolean $status          status is used to manipulate first title
@@ -1141,12 +1158,8 @@ WHERE id={$id}; ";
 
       $fields = array_merge($fields, $locationFields);
 
-      $fields = array_merge($fields,
-        CRM_Contact_DAO_Contact::import()
-      );
-      $fields = array_merge($fields,
-        CRM_Core_DAO_Note::import()
-      );
+      $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
+      $fields = array_merge($fields, CRM_Core_DAO_Note::import());
 
       //website fields
       $fields = array_merge($fields, CRM_Core_DAO_Website::import());
@@ -1268,8 +1281,12 @@ WHERE id={$id}; ";
         $fields = CRM_Contact_DAO_Contact::export();
 
         // the fields are meant for contact types
-        if (in_array($contactType, array(
-          'Individual', 'Household', 'Organization', 'All'))) {
+        if (
+          in_array(
+            $contactType,
+            array('Individual', 'Household', 'Organization', 'All')
+          )
+        ) {
           $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
         }
         // add current employer for individuals
@@ -1384,14 +1401,14 @@ WHERE id={$id}; ";
               'legal_identifier', 'sic_code', 'home_URL', 'is_deceased',
               'deceased_date', 'current_employer', 'email_greeting_custom',
               'postal_greeting_custom', 'addressee_custom',
-              'individual_prefix', 'individual_suffix', 'gender',
+              'prefix_id', 'suffix_id'
             ),
             'Organization' => array(
               'first_name', 'middle_name', 'last_name', 'job_title',
               'gender_id', 'birth_date', 'household_name',
               'email_greeting_custom',
-              'postal_greeting_custom', 'individual_prefix',
-              'individual_suffix', 'gender', 'addressee_custom',
+              'postal_greeting_custom', 'prefix_id',
+              'suffix_id', 'gender_id', 'addressee_custom',
               'is_deceased', 'deceased_date', 'current_employer',
             ),
           );
@@ -1455,7 +1472,7 @@ WHERE id={$id}; ";
    * @static
    */
   static function &makeHierReturnProperties($fields, $contactId = NULL) {
-    $locationTypes = CRM_Core_PseudoConstant::locationType();
+    $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
 
     $returnProperties = array();
 
@@ -1802,7 +1819,7 @@ ORDER BY civicrm_email.is_primary DESC";
     }
 
     // get the billing location type
-    $locationTypes = CRM_Core_PseudoConstant::locationType();
+    $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $billingLocationTypeId = array_search('Billing', $locationTypes);
 
     $blocks = array('email', 'phone', 'im', 'openid');
@@ -2274,8 +2291,7 @@ AND       civicrm_openid.is_primary = 1";
 
       // get preferred languages
       if (!empty($contact->preferred_language)) {
-        $languages = CRM_Core_PseudoConstant::languages();
-        $values['preferred_language'] = CRM_Utils_Array::value($contact->preferred_language, $languages);
+        $values['preferred_language'] = CRM_Core_PseudoConstant::getValue('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
       }
 
       // Calculating Year difference
@@ -2366,6 +2382,13 @@ AND       civicrm_openid.is_primary = 1";
         );
         return CRM_Activity_BAO_Activity::getActivitiesCount($input);
 
+      case 'mailing':
+        $params = array(
+          'contact_id' => $contactId,
+          'admin' => FALSE,
+        );
+        return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
+
       default:
         $custom = explode('_', $component);
         if ($custom['0'] = 'custom') {
@@ -2538,22 +2561,20 @@ AND       civicrm_openid.is_primary = 1";
    * @return array  $locBlockIds  loc block ids which fulfill condition.
    * @static
    */
-  static function getLocBlockIds($contactId, $criteria = array(
-    ), $condOperator = 'AND') {
+  static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
     $locBlockIds = array();
     if (!$contactId) {
       return $locBlockIds;
     }
 
-    foreach (array(
-      'Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
+    foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
       $name = strtolower($block);
-      eval("\$blockDAO = new CRM_Core_DAO_$block();");
+      $className = "CRM_Core_DAO_$block";
+      $blockDAO = new $className();
 
       // build the condition.
       if (is_array($criteria)) {
-        eval('$object = new CRM_Core_DAO_' . $block . '( );');
-        $fields = $object->fields();
+        $fields = $blockDAO->fields();
         $conditions = array();
         foreach ($criteria as $field => $value) {
           if (array_key_exists($field, $fields)) {
@@ -2974,4 +2995,73 @@ LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
       return FALSE;
     }
   }
+
+  /**
+   * Get options for a given contact field.
+   * @see CRM_Core_DAO::buildOptions
+   *
+   * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
+   * TODO: In context of chainselect, what to return if e.g. a country has no states?
+   *
+   * @param String $fieldName
+   * @param String $context: @see CRM_Core_DAO::buildOptionsContext
+   * @param Array  $props: whatever is known about this dao object
+   */
+  public static function buildOptions($fieldName, $context = NULL, $props = array()) {
+    $params = array();
+    // Special logic for fields whose options depend on context or properties
+    switch ($fieldName) {
+      case 'contact_sub_type':
+        if (!empty($props['contact_type'])) {
+          $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
+        }
+        break;
+    }
+    return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
+  }
+
+  /**
+   * Delete a contact-related object that has an 'is_primary' field
+   * Ensures that is_primary gets assigned to another object if available
+   * Also calls pre/post hooks
+   *
+   * @var $type: object type
+   * @var $id: object id
+   */
+  public static function deleteObjectWithPrimary($type, $id) {
+    if (!$id || !is_numeric($id)) {
+      return FALSE;
+    }
+    $daoName = "CRM_Core_DAO_$type";
+    $obj = new $daoName();
+    $obj->id = $id;
+    $obj->find();
+    if ($obj->fetch()) {
+      CRM_Utils_Hook::pre('delete', $type, $id, CRM_Core_DAO::$_nullArray);
+      $contactId = $obj->contact_id;
+      $obj->delete();
+    }
+    else {
+      return FALSE;
+    }
+    // is_primary is only relavent if this field belongs to a contact
+    if ($contactId) {
+      $dao = new $daoName();
+      $dao->contact_id = $contactId;
+      $dao->is_primary = 1;
+      // Pick another record to be primary (if one isn't already)
+      if (!$dao->find(TRUE)) {
+        $dao->is_primary = 0;
+        $dao->find();
+        if ($dao->fetch()) {
+          $dao->is_primary = 1;
+          $dao->save();
+        }
+      }
+      $dao->free();
+    }
+    CRM_Utils_Hook::post('delete', $type, $id, $obj);
+    $obj->free();
+    return TRUE;
+  }
 }