Fix api preferred_communication_method CRM-12548
[civicrm-core.git] / api / v3 / Contact.php
index 7ccbbfb4730818e17b7053c49afea60bf3132fba..e138091a78cff184cdfa383de8b792e8134e0b87 100644 (file)
@@ -1,6 +1,4 @@
 <?php
-// $Id$
-
 /*
   +--------------------------------------------------------------------+
   | CiviCRM version 4.3                                                |
@@ -78,49 +76,33 @@ function civicrm_api3_contact_create($params) {
   }
 
   if (!empty($params['home_url'])) {
-    $websiteTypes = CRM_Core_PseudoConstant::websiteType();
+    $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
     $params['website'] = array(1 => array('website_type_id' => key($websiteTypes),
         'url' => $params['home_url'],
       ),
     );
   }
 
-  if (isset($params['suffix_id']) && !(is_numeric($params['suffix_id']))) {
-    $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant::individualSuffix());
-  }
-
-  if (isset($params['prefix_id']) && !(is_numeric($params['prefix_id']))) {
-    $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant::individualPrefix());
-  }
-
-  if (isset($params['gender_id']) && !(is_numeric($params['gender_id']))) {
-    $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant::gender());
-  }
-
-  $error = _civicrm_api3_greeting_format_params($params);
-  if (civicrm_error($error)) {
-    return $error;
-  }
+  _civicrm_api3_greeting_format_params($params);
 
   $values = array();
-  $entityId = $contactID;
 
-  if (empty($params['contact_type']) && $entityId) {
-    $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($entityId);
+  if (empty($params['contact_type']) && $contactID) {
+    $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
   }
 
-  if (!isset($params['contact_sub_type']) && $entityId) {
-    $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($entityId);
+  if (!isset($params['contact_sub_type']) && $contactID) {
+    $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
   }
 
-  _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $entityId);
+  _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
 
   $params = array_merge($params, $values);
-
+  //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
   $contact = _civicrm_api3_contact_update($params, $contactID);
 
   if (is_a($contact, 'CRM_Core_Error')) {
-    return civicrm_api3_create_error($contact->_errors[0]['message']);
+    throw new API_Exception($contact->_errors[0]['message']);
   }
   else {
     $values = array();
@@ -146,6 +128,8 @@ function _civicrm_api3_contact_create_spec(&$params) {
     'title' => 'Check for Duplicates',
     'description' => 'Throw error if contact create matches dedupe rule',
   );
+  $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
+  $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
 }
 
 /**
@@ -165,33 +149,14 @@ function civicrm_api3_contact_get($params) {
   $options = array();
   _civicrm_api3_contact_get_supportanomalies($params, $options);
   $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
-
-  // CRM-7929 Quick fix by colemanw
-  // TODO: Figure out what function is responsible for prepending 'individual_' to these keys
-  // and sort it out there rather than going to all this trouble here.
-  // Eileen's note - not sure anymore if we went the right path stripping the 'individual' here
-  // as is arguable whether it makes more sense now I think it would make more sense to rename the table field  or uniquefield to have
-  // the individual prefix but we are stuck with it now for apiv3 series.
-  $returnContacts = array();
-  if (is_array($contacts)) {
-    foreach ($contacts as $cid => $contact) {
-      if (is_array($contact)) {
-        $returnContacts[$cid] = array();
-        foreach ($contact as $key => $value) {
-          $key = str_replace(array('individual_prefix', 'individual_suffix'), array('prefix', 'suffix'), $key);
-          $returnContacts[$cid][$key] = $value;
-        }
-      }
-    }
-  }
-  return civicrm_api3_create_success($returnContacts, $params, 'contact');
+  return civicrm_api3_create_success($contacts, $params, 'contact');
 }
 
 function civicrm_api3_contact_getcount($params) {
   $options = array();
   _civicrm_api3_contact_get_supportanomalies($params, $options);
   $count = _civicrm_api3_get_using_query_object('contact', $params, $options,1);
-  return $count;
+  return (int) $count;
 }
 
 /**
@@ -295,6 +260,13 @@ function civicrm_api3_contact_delete($params) {
   }
   $restore = CRM_Utils_Array::value('restore', $params) ? $params['restore'] : FALSE;
   $skipUndelete = CRM_Utils_Array::value('skip_undelete', $params) ? $params['skip_undelete'] : FALSE;
+
+  // CRM-12929
+  // restrict permanent delete if a contact has financial trxn associated with it
+  $error = NULL;
+  if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
+    return civicrm_api3_create_error($error['_qf_default']);
+  }
   if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) {
     return civicrm_api3_create_success();
   }
@@ -325,9 +297,14 @@ function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeE
     break;
   }
 
+  // Fixme: This really needs to be handled at a lower level. @See CRM-13123
+  if (isset($params['preferred_communication_method'])) {
+    $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
+  }
+
   if (CRM_Utils_Array::value('contact_sub_type', $params) && CRM_Utils_Array::value('contact_type', $params)) {
       if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
-        return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type']));
+        throw new API_Exception("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type']));
       }
     }
 
@@ -386,17 +363,12 @@ function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeE
  * @static
  */
 function _civicrm_api3_contact_update($params, $contactID = NULL) {
-  $transaction = new CRM_Core_Transaction();
-
+  //@todo - doesn't contact create support 'id' which is already set- check & remove
   if ($contactID) {
     $params['contact_id'] = $contactID;
   }
 
-  $contact = CRM_Contact_BAO_Contact::create($params);
-
-  $transaction->commit();
-
-  return $contact;
+  return CRM_Contact_BAO_Contact::create($params);
 }
 
 /**
@@ -453,7 +425,7 @@ function _civicrm_api3_greeting_format_params($params) {
     if ($customGreeting && $greetingId &&
       ($greetingId != array_search('Customized', $greetings))
     ) {
-      return civicrm_api3_create_error(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
+      throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
           array(1 => $key)
         ));
     }
@@ -461,7 +433,7 @@ function _civicrm_api3_greeting_format_params($params) {
     if ($greetingVal && $greetingId &&
       ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
     ) {
-      return civicrm_api3_create_error(ts('Mismatch in %1 greeting id and %1 greeting',
+      throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
           array(1 => $key)
         ));
     }
@@ -469,11 +441,11 @@ function _civicrm_api3_greeting_format_params($params) {
     if ($greetingId) {
 
       if (!array_key_exists($greetingId, $greetings)) {
-        return civicrm_api3_create_error(ts('Invalid %1 greeting Id', array(1 => $key)));
+        throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
       }
 
       if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
-        return civicrm_api3_create_error(ts('Please provide a custom value for %1 greeting',
+        throw new API_Exception(ts('Please provide a custom value for %1 greeting',
             array(1 => $key)
           ));
       }
@@ -481,7 +453,7 @@ function _civicrm_api3_greeting_format_params($params) {
     elseif ($greetingVal) {
 
       if (!in_array($greetingVal, $greetings)) {
-        return civicrm_api3_create_error(ts('Invalid %1 greeting', array(1 => $key)));
+        throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
       }
 
       $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
@@ -491,10 +463,13 @@ function _civicrm_api3_greeting_format_params($params) {
       $greetingId = CRM_Utils_Array::key('Customized', $greetings);
     }
 
-    $customValue = $params['contact_id'] ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
-      $params['contact_id'],
-      "{$key}{$greeting}_custom"
-    ) : FALSE;
+    $customValue = isset($params['contact_id']) ?
+      CRM_Core_DAO::getFieldValue(
+        'CRM_Contact_DAO_Contact',
+        $params['contact_id'],
+        "{$key}{$greeting}_custom"
+      ) :
+      FALSE;
 
     if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
       $nullValue = TRUE;
@@ -540,7 +515,7 @@ function civicrm_api3_contact_quicksearch($params) {
 
 function civicrm_api3_contact_getquick($params) {
   civicrm_api3_verify_mandatory($params, NULL, array('name'));
-  $name = CRM_Utils_Array::value('name', $params);
+  $name = CRM_Utils_Type::escape($params['name'], 'String');
 
   // get the autocomplete options from settings
   $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
@@ -560,8 +535,13 @@ function civicrm_api3_contact_getquick($params) {
   }
   // If we are doing quicksearch by a field other than name, make sure that field is added to results
   if (!empty($params['field_name'])) {
+    $field_name = CRM_Utils_String::munge($params['field_name']);
+    // Unique name contact_id = id
+    if ($field_name == 'contact_id') {
+      $field_name = 'id';
+    }
     // phone_numeric should be phone
-    $searchField = str_replace('_numeric', '', $params['field_name']);
+    $searchField = str_replace('_numeric', '', $field_name);
     if(!in_array($searchField, $list)) {
       $list[] = $searchField;
     }
@@ -599,7 +579,7 @@ function civicrm_api3_contact_getquick($params) {
         if ($value != 'id') {
           $suffix = 'cc';
           if (!empty($params['field_name']) && $params['field_name'] == 'value') {
-            $suffix = CRM_Utils_Array::value('table_name', $params, 'cc');
+            $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
           }
           $actualSelectElements[] = $select[] = $suffix . '.' . $value;
         }
@@ -621,7 +601,8 @@ function civicrm_api3_contact_getquick($params) {
     $selectAliases = ", $selectAliases";
   }
   $from = implode(' ', $from);
-  $limit = CRM_Utils_Array::value('limit', $params, 10);
+  $limit = (int) CRM_Utils_Array::value('limit', $params);
+  $limit = $limit > 0 ? $limit : 10;
 
   // add acl clause here
   list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
@@ -638,7 +619,7 @@ function civicrm_api3_contact_getquick($params) {
     $currEmpDetails = array();
     if (CRM_Utils_Array::value('employee_id', $params)) {
       if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
-          CRM_Utils_Array::value('employee_id', $params),
+          (int) $params['employee_id'],
           'employer_id'
         )) {
         if ($config->includeWildCardInName) {
@@ -663,11 +644,11 @@ function civicrm_api3_contact_getquick($params) {
 
   //set default for current_employer or return contact with particular id
   if (CRM_Utils_Array::value('id', $params)) {
-    $where .= " AND cc.id = " .$params['id'];
+    $where .= " AND cc.id = " . (int) $params['id'];
   }
 
   if (CRM_Utils_Array::value('cid', $params)) {
-    $where .= " AND cc.id <> {$params['cid']}";
+    $where .= " AND cc.id <> " . (int) $params['cid'];
   }
 
   //contact's based of relationhip type
@@ -692,8 +673,7 @@ function civicrm_api3_contact_getquick($params) {
 
   //CRM-10687
   if (!empty($params['field_name']) && !empty($params['table_name'])) {
-    $field_name = $params['field_name'];
-    $table_name = $params['table_name'];
+    $table_name = CRM_Utils_String::munge($params['table_name']);
     $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')";
     $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')";
     // Search by id should be exact
@@ -732,6 +712,13 @@ function civicrm_api3_contact_getquick($params) {
       ";
   }
 
+  $orderByInner = "";
+  $orderByOuter = "ORDER BY exactFirst";
+  if ($config->includeOrderByClause) {
+    $orderByInner = "ORDER BY sort_name";
+    $orderByOuter .= ", sort_name";
+  }
+
   //CRM-5954
   $query = "
         SELECT DISTINCT(id), data, sort_name {$selectAliases}
@@ -748,17 +735,17 @@ function civicrm_api3_contact_getquick($params) {
     {$aclFrom}
     {$additionalFrom} {$includeEmailFrom}
     {$whereClause}
-    ORDER BY sort_name
+    {$orderByInner}
     LIMIT 0, {$limit} )
 ) t
-ORDER BY exactFirst, sort_name
+{$orderByOuter}
 LIMIT    0, {$limit}
     ";
   // send query to hook to be modified if needed
   CRM_Utils_Hook::contactListQuery($query,
     $name,
-    CRM_Utils_Array::value('context', $params),
-    CRM_Utils_Array::value('id', $params)
+    empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
+    empty($params['id']) ? NULL : $params['id']
   );
 
   $dao = CRM_Core_DAO::executeQuery($query);