| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 4.4 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2013 | |
| 7 | +--------------------------------------------------------------------+ |
| 8 | | This file is a part of CiviCRM. | |
| 9 | | | |
| 10 | | CiviCRM is free software; you can copy, modify, and distribute it | |
| 11 | | under the terms of the GNU Affero General Public License | |
| 12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | |
| 13 | | | |
| 14 | | CiviCRM is distributed in the hope that it will be useful, but | |
| 15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | |
| 16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
| 17 | | See the GNU Affero General Public License for more details. | |
| 18 | | | |
| 19 | | You should have received a copy of the GNU Affero General Public | |
| 20 | | License and the CiviCRM Licensing Exception along | |
| 21 | | with this program; if not, contact CiviCRM LLC | |
| 22 | | at info[AT]civicrm[DOT]org. If you have questions about the | |
| 23 | | GNU Affero General Public License or the licensing of CiviCRM, | |
| 24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | |
| 25 | +--------------------------------------------------------------------+ |
| 26 | */ |
| 27 | |
| 28 | /** |
| 29 | * new version of civicrm apis. See blog post at |
| 30 | * http://civicrm.org/node/131 |
| 31 | * @todo Write sth |
| 32 | * |
| 33 | * @package CiviCRM_APIv3 |
| 34 | * @subpackage API_Contact |
| 35 | * @copyright CiviCRM LLC (c) 2004-2013 |
| 36 | * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $ |
| 37 | * |
| 38 | */ |
| 39 | |
| 40 | /** |
| 41 | * Create or update a contact (note you should always call this via civicrm_api() & never directly) |
| 42 | * |
| 43 | * @param array $params input parameters |
| 44 | * |
| 45 | * Allowed @params array keys are: |
| 46 | * {@getfields contact_create} |
| 47 | * |
| 48 | * |
| 49 | * @example ContactCreate.php Example of Create Call |
| 50 | * |
| 51 | * @return array API Result Array |
| 52 | * |
| 53 | * @static void |
| 54 | * @access public |
| 55 | */ |
| 56 | function civicrm_api3_contact_create($params) { |
| 57 | |
| 58 | $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params)); |
| 59 | $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE); |
| 60 | $values = _civicrm_api3_contact_check_params($params, $dupeCheck); |
| 61 | if ($values) { |
| 62 | return $values; |
| 63 | } |
| 64 | |
| 65 | if (!$contactID) { |
| 66 | // If we get here, we're ready to create a new contact |
| 67 | if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) { |
| 68 | $defLocType = CRM_Core_BAO_LocationType::getDefault(); |
| 69 | $params['email'] = array( |
| 70 | 1 => array('email' => $email, |
| 71 | 'is_primary' => 1, |
| 72 | 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1, |
| 73 | ), |
| 74 | ); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | if (!empty($params['home_url'])) { |
| 79 | $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); |
| 80 | $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), |
| 81 | 'url' => $params['home_url'], |
| 82 | ), |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | _civicrm_api3_greeting_format_params($params); |
| 87 | |
| 88 | $values = array(); |
| 89 | |
| 90 | if (empty($params['contact_type']) && $contactID) { |
| 91 | $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID); |
| 92 | } |
| 93 | |
| 94 | if (!isset($params['contact_sub_type']) && $contactID) { |
| 95 | $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID); |
| 96 | } |
| 97 | |
| 98 | _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID); |
| 99 | |
| 100 | $params = array_merge($params, $values); |
| 101 | //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao |
| 102 | $contact = _civicrm_api3_contact_update($params, $contactID); |
| 103 | |
| 104 | if (is_a($contact, 'CRM_Core_Error')) { |
| 105 | throw new API_Exception($contact->_errors[0]['message']); |
| 106 | } |
| 107 | else { |
| 108 | $values = array(); |
| 109 | _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]); |
| 110 | } |
| 111 | |
| 112 | return civicrm_api3_create_success($values, $params, 'Contact', 'create'); |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Adjust Metadata for Create action |
| 117 | * |
| 118 | * @param array $params array or parameters determined by getfields |
| 119 | */ |
| 120 | function _civicrm_api3_contact_create_spec(&$params) { |
| 121 | $params['contact_type']['api.required'] = 1; |
| 122 | $params['id']['api.aliases'] = array('contact_id'); |
| 123 | $params['current_employer'] = array( |
| 124 | 'title' => 'Current Employer', |
| 125 | 'description' => 'Name of Current Employer', |
| 126 | 'type' => CRM_Utils_Type::T_STRING, |
| 127 | ); |
| 128 | $params['dupe_check'] = array( |
| 129 | 'title' => 'Check for Duplicates', |
| 130 | 'description' => 'Throw error if contact create matches dedupe rule', |
| 131 | ); |
| 132 | $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id'); |
| 133 | $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id'); |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Retrieve one or more contacts, given a set of search params |
| 138 | * |
| 139 | * @param array input parameters |
| 140 | * |
| 141 | * @return array API Result Array |
| 142 | * (@getfields contact_get} |
| 143 | * @static void |
| 144 | * @access public |
| 145 | * |
| 146 | * @example ContactGet.php Standard GET example |
| 147 | * |
| 148 | */ |
| 149 | function civicrm_api3_contact_get($params) { |
| 150 | $options = array(); |
| 151 | _civicrm_api3_contact_get_supportanomalies($params, $options); |
| 152 | $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options); |
| 153 | return civicrm_api3_create_success($contacts, $params, 'contact'); |
| 154 | } |
| 155 | |
| 156 | function civicrm_api3_contact_getcount($params) { |
| 157 | $options = array(); |
| 158 | _civicrm_api3_contact_get_supportanomalies($params, $options); |
| 159 | $count = _civicrm_api3_get_using_query_object('contact', $params, $options,1); |
| 160 | return (int) $count; |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Adjust Metadata for Get action |
| 165 | * |
| 166 | * @param array $params array or parameters determined by getfields |
| 167 | */ |
| 168 | function _civicrm_api3_contact_get_spec(&$params) { |
| 169 | $params['contact_is_deleted']['api.default'] = 0; |
| 170 | |
| 171 | //we declare all these pseudofields as there are other undocumented fields accessible |
| 172 | // via the api - but if check permissions is set we only allow declared fields |
| 173 | $params['address_id']['title'] = 'Primary Address ID'; |
| 174 | $params['street_address']['title'] = 'Primary Address Street Address'; |
| 175 | $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1'; |
| 176 | $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2'; |
| 177 | $params['current_employer']['title'] = 'Current Employer'; |
| 178 | $params['city']['title'] = 'Primary Address City'; |
| 179 | $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix'; |
| 180 | $params['postal_code']['title'] = 'Primary Address Post Code'; |
| 181 | $params['geo_code_1']['title'] = 'Primary Address Latitude'; |
| 182 | $params['geo_code_2']['title'] = 'Primary Address Longitude'; |
| 183 | $params['state_province_id']['title'] = 'Primary Address State Province ID'; |
| 184 | $params['state_province_name']['title'] = 'Primary Address State Province Name'; |
| 185 | $params['state_province']['title'] = 'Primary Address State Province'; |
| 186 | $params['country_id']['title'] = 'Primary Address Country ID'; |
| 187 | $params['country']['title'] = 'Primary Address country'; |
| 188 | $params['worldregion_id']['title'] = 'Primary Address World Region ID'; |
| 189 | $params['worldregion']['title'] = 'Primary Address World Region'; |
| 190 | $params['phone_id']['title'] = 'Primary Phone ID'; |
| 191 | $params['phone']['title'] = 'Primary Phone'; |
| 192 | $params['phone_type_id']['title'] = 'Primary Phone Type ID'; |
| 193 | $params['provider_id']['title'] = 'Primary Phone Provider ID'; |
| 194 | $params['email_id']['title'] = 'Primary Email ID'; |
| 195 | $params['email']['title'] = 'Primary Email'; |
| 196 | $params['gender_id']['title'] = 'Gender ID'; |
| 197 | $params['gender']['title'] = 'Gender'; |
| 198 | $params['on_hold']['title'] = 'Primary Email On Hold'; |
| 199 | $params['im']['title'] = 'Primary Instant Messanger'; |
| 200 | $params['im_id']['title'] = 'Primary Instant Messanger ID'; |
| 201 | $params['group_id']['title'] = 'Group Memberships (filter)'; |
| 202 | $params['group']['title'] = 'Group Memberships (filter, array)'; |
| 203 | $params['tag']['title'] = 'Assigned tags (filter, array)'; |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get |
| 208 | * and for getcount |
| 209 | * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of |
| 210 | * 0, 1 or not set |
| 211 | * |
| 212 | * We also support 'filter_group_id' & 'filter.group_id' |
| 213 | * |
| 214 | * @param array $params as passed into api get or getcount function |
| 215 | * @param array $options array of options (so we can modify the filter) |
| 216 | */ |
| 217 | function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) { |
| 218 | if (isset($params['showAll'])) { |
| 219 | if (strtolower($params['showAll']) == "active") { |
| 220 | $params['contact_is_deleted'] = 0; |
| 221 | } |
| 222 | if (strtolower($params['showAll']) == "trash") { |
| 223 | $params['contact_is_deleted'] = 1; |
| 224 | } |
| 225 | if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) { |
| 226 | unset($params['contact_is_deleted']); |
| 227 | } |
| 228 | } |
| 229 | // support for group filters |
| 230 | if (array_key_exists('filter_group_id', $params)) { |
| 231 | $params['filter.group_id'] = $params['filter_group_id']; |
| 232 | unset($params['filter_group_id']); |
| 233 | } |
| 234 | // filter.group_id works both for 1,2,3 and array (1,2,3) |
| 235 | if (array_key_exists('filter.group_id', $params)) { |
| 236 | if (is_array($params['filter.group_id'])) { |
| 237 | $groups = $params['filter.group_id']; |
| 238 | } |
| 239 | else $groups = explode(',', $params['filter.group_id']); |
| 240 | unset($params['filter.group_id']); |
| 241 | $groups = array_flip($groups); |
| 242 | $groups[key($groups)] = 1; |
| 243 | $options['input_params']['group'] = $groups; |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /** |
| 248 | * Delete a contact with given contact id |
| 249 | * |
| 250 | * @param array $params (reference ) input parameters, contact_id element required |
| 251 | * |
| 252 | * @return array API Result Array |
| 253 | * @access public |
| 254 | * |
| 255 | * @example ContactDelete.php |
| 256 | * {@getfields contact_delete} |
| 257 | */ |
| 258 | function civicrm_api3_contact_delete($params) { |
| 259 | |
| 260 | $contactID = CRM_Utils_Array::value('id', $params); |
| 261 | |
| 262 | $session = CRM_Core_Session::singleton(); |
| 263 | if ($contactID == $session->get('userID')) { |
| 264 | return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.'); |
| 265 | } |
| 266 | $restore = !empty($params['restore']) ? $params['restore'] : FALSE; |
| 267 | $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE; |
| 268 | |
| 269 | // CRM-12929 |
| 270 | // restrict permanent delete if a contact has financial trxn associated with it |
| 271 | $error = NULL; |
| 272 | if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) { |
| 273 | return civicrm_api3_create_error($error['_qf_default']); |
| 274 | } |
| 275 | if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) { |
| 276 | return civicrm_api3_create_success(); |
| 277 | } |
| 278 | else { |
| 279 | return civicrm_api3_create_error('Could not delete contact'); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | |
| 284 | function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeErrorArray = false, $obsoletevalue = true, $dedupeRuleGroupID = null ) |
| 285 | { |
| 286 | |
| 287 | switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) { |
| 288 | case 'household': |
| 289 | civicrm_api3_verify_mandatory($params, null, array('household_name')); |
| 290 | break; |
| 291 | case 'organization': |
| 292 | civicrm_api3_verify_mandatory($params, null, array('organization_name')); |
| 293 | break; |
| 294 | case 'individual': |
| 295 | civicrm_api3_verify_one_mandatory($params, null, array( |
| 296 | 'first_name', |
| 297 | 'last_name', |
| 298 | 'email', |
| 299 | 'display_name', |
| 300 | ) |
| 301 | ); |
| 302 | break; |
| 303 | } |
| 304 | |
| 305 | // Fixme: This really needs to be handled at a lower level. @See CRM-13123 |
| 306 | if (isset($params['preferred_communication_method'])) { |
| 307 | $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']); |
| 308 | } |
| 309 | |
| 310 | if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) { |
| 311 | if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) { |
| 312 | throw new API_Exception("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type'])); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | if ($dupeCheck) { |
| 317 | // check for record already existing |
| 318 | $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']); |
| 319 | |
| 320 | // CRM-6431 |
| 321 | // setting 'check_permission' here means that the dedupe checking will be carried out even if the |
| 322 | // person does not have permission to carry out de-dupes |
| 323 | // this is similar to the front end form |
| 324 | if (isset($params['check_permission'])) { |
| 325 | $dedupeParams['check_permission'] = $params['check_permission']; |
| 326 | } |
| 327 | |
| 328 | $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array()); |
| 329 | |
| 330 | if (count($ids) >0) { |
| 331 | throw new API_Exception("Found matching contacts: ". implode(',',$ids),"duplicate",array("ids"=>$ids)); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | //check for organisations with same name |
| 336 | if (!empty($params['current_employer'])) { |
| 337 | $organizationParams = array(); |
| 338 | $organizationParams['organization_name'] = $params['current_employer']; |
| 339 | |
| 340 | $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization'); |
| 341 | |
| 342 | $dedupParams['check_permission'] = FALSE; |
| 343 | $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised'); |
| 344 | |
| 345 | // check for mismatch employer name and id |
| 346 | if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) { |
| 347 | throw new API_Exception('Employer name and Employer id Mismatch'); |
| 348 | } |
| 349 | |
| 350 | // show error if multiple organisation with same name exist |
| 351 | if (empty($params['employer_id']) && (count($dupeIds) > 1)) { |
| 352 | throw new API_Exception('Found more than one Organisation with same Name.'); |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | return NULL; |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Takes an associative array and creates a contact object and all the associated |
| 361 | * derived objects (i.e. individual, location, email, phone etc) |
| 362 | * |
| 363 | * @param array $params (reference ) an assoc array of name/value pairs |
| 364 | * @param int $contactID if present the contact with that ID is updated |
| 365 | * |
| 366 | * @return object CRM_Contact_BAO_Contact object |
| 367 | * @access public |
| 368 | * @static |
| 369 | */ |
| 370 | function _civicrm_api3_contact_update($params, $contactID = NULL) { |
| 371 | //@todo - doesn't contact create support 'id' which is already set- check & remove |
| 372 | if ($contactID) { |
| 373 | $params['contact_id'] = $contactID; |
| 374 | } |
| 375 | |
| 376 | return CRM_Contact_BAO_Contact::create($params); |
| 377 | } |
| 378 | |
| 379 | /** |
| 380 | * Validate the addressee or email or postal greetings |
| 381 | * |
| 382 | * @param $params Associative array of property name/value |
| 383 | * pairs to insert in new contact. |
| 384 | * |
| 385 | * @return array (reference ) null on success, error message otherwise |
| 386 | * |
| 387 | * @access public |
| 388 | */ |
| 389 | function _civicrm_api3_greeting_format_params($params) { |
| 390 | $greetingParams = array('', '_id', '_custom'); |
| 391 | foreach (array('email', 'postal', 'addressee') as $key) { |
| 392 | $greeting = '_greeting'; |
| 393 | if ($key == 'addressee') { |
| 394 | $greeting = ''; |
| 395 | } |
| 396 | |
| 397 | $formatParams = FALSE; |
| 398 | // unset display value from params. |
| 399 | if (isset($params["{$key}{$greeting}_display"])) { |
| 400 | unset($params["{$key}{$greeting}_display"]); |
| 401 | } |
| 402 | |
| 403 | // check if greetings are present in present |
| 404 | foreach ($greetingParams as $greetingValues) { |
| 405 | if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) { |
| 406 | $formatParams = TRUE; |
| 407 | break; |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | if (!$formatParams) { |
| 412 | continue; |
| 413 | } |
| 414 | |
| 415 | $nullValue = FALSE; |
| 416 | $filter = array( |
| 417 | 'contact_type' => $params['contact_type'], |
| 418 | 'greeting_type' => "{$key}{$greeting}", |
| 419 | ); |
| 420 | |
| 421 | $greetings = CRM_Core_PseudoConstant::greeting($filter); |
| 422 | $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params); |
| 423 | $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params); |
| 424 | $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params); |
| 425 | |
| 426 | if (!$greetingId && $greetingVal) { |
| 427 | $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings); |
| 428 | } |
| 429 | |
| 430 | if ($customGreeting && $greetingId && |
| 431 | ($greetingId != array_search('Customized', $greetings)) |
| 432 | ) { |
| 433 | throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting', |
| 434 | array(1 => $key) |
| 435 | )); |
| 436 | } |
| 437 | |
| 438 | if ($greetingVal && $greetingId && |
| 439 | ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings)) |
| 440 | ) { |
| 441 | throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting', |
| 442 | array(1 => $key) |
| 443 | )); |
| 444 | } |
| 445 | |
| 446 | if ($greetingId) { |
| 447 | |
| 448 | if (!array_key_exists($greetingId, $greetings)) { |
| 449 | throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key))); |
| 450 | } |
| 451 | |
| 452 | if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) { |
| 453 | throw new API_Exception(ts('Please provide a custom value for %1 greeting', |
| 454 | array(1 => $key) |
| 455 | )); |
| 456 | } |
| 457 | } |
| 458 | elseif ($greetingVal) { |
| 459 | |
| 460 | if (!in_array($greetingVal, $greetings)) { |
| 461 | throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key))); |
| 462 | } |
| 463 | |
| 464 | $greetingId = CRM_Utils_Array::key($greetingVal, $greetings); |
| 465 | } |
| 466 | |
| 467 | if ($customGreeting) { |
| 468 | $greetingId = CRM_Utils_Array::key('Customized', $greetings); |
| 469 | } |
| 470 | |
| 471 | $customValue = isset($params['contact_id']) ? |
| 472 | CRM_Core_DAO::getFieldValue( |
| 473 | 'CRM_Contact_DAO_Contact', |
| 474 | $params['contact_id'], |
| 475 | "{$key}{$greeting}_custom" |
| 476 | ) : |
| 477 | FALSE; |
| 478 | |
| 479 | if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) { |
| 480 | $nullValue = TRUE; |
| 481 | } |
| 482 | elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) { |
| 483 | $nullValue = TRUE; |
| 484 | } |
| 485 | elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params) |
| 486 | && empty($params["{$key}{$greeting}_custom"]) |
| 487 | ) { |
| 488 | $nullValue = TRUE; |
| 489 | } |
| 490 | |
| 491 | $params["{$key}{$greeting}_id"] = $greetingId; |
| 492 | |
| 493 | if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) { |
| 494 | unset($params["{$key}{$greeting}_custom"]); |
| 495 | } |
| 496 | |
| 497 | if ($nullValue) { |
| 498 | $params["{$key}{$greeting}_id"] = ''; |
| 499 | $params["{$key}{$greeting}_custom"] = ''; |
| 500 | } |
| 501 | |
| 502 | if (isset($params["{$key}{$greeting}"])) { |
| 503 | unset($params["{$key}{$greeting}"]); |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /** |
| 509 | * Old contact quick search api |
| 510 | * |
| 511 | * @deprecated |
| 512 | * |
| 513 | * {@example ContactGetquick.php 0} |
| 514 | * |
| 515 | */ |
| 516 | function civicrm_api3_contact_getquick($params) { |
| 517 | civicrm_api3_verify_mandatory($params, NULL, array('name')); |
| 518 | $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String'); |
| 519 | |
| 520 | // get the autocomplete options from settings |
| 521 | $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR, |
| 522 | CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, |
| 523 | 'contact_autocomplete_options' |
| 524 | ) |
| 525 | ); |
| 526 | |
| 527 | // get the option values for contact autocomplete |
| 528 | $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name'); |
| 529 | |
| 530 | $list = array(); |
| 531 | foreach ($acpref as $value) { |
| 532 | if ($value && !empty($acOptions[$value])) { |
| 533 | $list[$value] = $acOptions[$value]; |
| 534 | } |
| 535 | } |
| 536 | // If we are doing quicksearch by a field other than name, make sure that field is added to results |
| 537 | if (!empty($params['field_name'])) { |
| 538 | $field_name = CRM_Utils_String::munge($params['field_name']); |
| 539 | // Unique name contact_id = id |
| 540 | if ($field_name == 'contact_id') { |
| 541 | $field_name = 'id'; |
| 542 | } |
| 543 | // phone_numeric should be phone |
| 544 | $searchField = str_replace('_numeric', '', $field_name); |
| 545 | if(!in_array($searchField, $list)) { |
| 546 | $list[] = $searchField; |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | $select = $actualSelectElements = array('sort_name'); |
| 551 | $where = ''; |
| 552 | $from = array(); |
| 553 | foreach ($list as $value) { |
| 554 | $suffix = substr($value, 0, 2) . substr($value, -1); |
| 555 | switch ($value) { |
| 556 | case 'street_address': |
| 557 | case 'city': |
| 558 | case 'postal_code': |
| 559 | $selectText = $value; |
| 560 | $value = "address"; |
| 561 | $suffix = 'sts'; |
| 562 | case 'phone': |
| 563 | case 'email': |
| 564 | $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value; |
| 565 | if ($value == 'phone') { |
| 566 | $actualSelectElements[] = $select[] = 'phone_ext'; |
| 567 | } |
| 568 | $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) "; |
| 569 | break; |
| 570 | |
| 571 | case 'country': |
| 572 | case 'state_province': |
| 573 | $select[] = "{$suffix}.name as {$value}"; |
| 574 | $actualSelectElements[] = "{$suffix}.name"; |
| 575 | if (!in_array('address', $from)) { |
| 576 | $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) '; |
| 577 | } |
| 578 | $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) "; |
| 579 | break; |
| 580 | |
| 581 | default: |
| 582 | if ($value != 'id') { |
| 583 | $suffix = 'cc'; |
| 584 | if (!empty($params['field_name']) && $params['field_name'] == 'value') { |
| 585 | $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc')); |
| 586 | } |
| 587 | $actualSelectElements[] = $select[] = $suffix . '.' . $value; |
| 588 | } |
| 589 | break; |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | $config = CRM_Core_Config::singleton(); |
| 594 | $as = $select; |
| 595 | $select = implode(', ', $select); |
| 596 | if (!empty($select)) { |
| 597 | $select = ", $select"; |
| 598 | } |
| 599 | $actualSelectElements = implode(', ', $actualSelectElements); |
| 600 | $selectAliases = $from; |
| 601 | unset($selectAliases['address']); |
| 602 | $selectAliases = implode(', ', array_keys($selectAliases)); |
| 603 | if (!empty($selectAliases)) { |
| 604 | $selectAliases = ", $selectAliases"; |
| 605 | } |
| 606 | $from = implode(' ', $from); |
| 607 | $limit = (int) CRM_Utils_Array::value('limit', $params); |
| 608 | $limit = $limit > 0 ? $limit : 10; |
| 609 | |
| 610 | // add acl clause here |
| 611 | list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc'); |
| 612 | |
| 613 | if ($aclWhere) { |
| 614 | $where .= " AND $aclWhere "; |
| 615 | } |
| 616 | |
| 617 | if (!empty($params['org'])) { |
| 618 | $where .= " AND contact_type = \"Organization\""; |
| 619 | |
| 620 | // CRM-7157, hack: get current employer details when |
| 621 | // employee_id is present. |
| 622 | $currEmpDetails = array(); |
| 623 | if (!empty($params['employee_id'])) { |
| 624 | if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', |
| 625 | (int) $params['employee_id'], |
| 626 | 'employer_id' |
| 627 | )) { |
| 628 | if ($config->includeWildCardInName) { |
| 629 | $strSearch = "%$name%"; |
| 630 | } |
| 631 | else { |
| 632 | $strSearch = "$name%"; |
| 633 | } |
| 634 | |
| 635 | // get current employer details |
| 636 | $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name |
| 637 | FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'"); |
| 638 | if ($dao->fetch()) { |
| 639 | $currEmpDetails = array( |
| 640 | 'id' => $dao->id, |
| 641 | 'data' => $dao->data, |
| 642 | ); |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | if (!empty($params['contact_sub_type'])) { |
| 649 | $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String'); |
| 650 | $where .= " AND cc.contact_sub_type = '{$contactSubType}'"; |
| 651 | } |
| 652 | |
| 653 | if (!empty($params['contact_type'])) { |
| 654 | $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String'); |
| 655 | $where .= " AND cc.contact_type LIKE '{$contactType}'"; |
| 656 | } |
| 657 | |
| 658 | //set default for current_employer or return contact with particular id |
| 659 | if (!empty($params['id'])) { |
| 660 | $where .= " AND cc.id = " . (int) $params['id']; |
| 661 | } |
| 662 | |
| 663 | if (!empty($params['cid'])) { |
| 664 | $where .= " AND cc.id <> " . (int) $params['cid']; |
| 665 | } |
| 666 | |
| 667 | //contact's based of relationhip type |
| 668 | $relType = NULL; |
| 669 | if (!empty($params['rel'])) { |
| 670 | $relation = explode('_', CRM_Utils_Array::value('rel', $params)); |
| 671 | $relType = CRM_Utils_Type::escape($relation[0], 'Integer'); |
| 672 | $rel = CRM_Utils_Type::escape($relation[2], 'String'); |
| 673 | } |
| 674 | |
| 675 | if ($config->includeWildCardInName) { |
| 676 | $strSearch = "%$name%"; |
| 677 | } |
| 678 | else { |
| 679 | $strSearch = "$name%"; |
| 680 | } |
| 681 | $includeEmailFrom = $includeNickName = $exactIncludeNickName = ''; |
| 682 | if ($config->includeNickNameInName) { |
| 683 | $includeNickName = " OR nick_name LIKE '$strSearch'"; |
| 684 | $exactIncludeNickName = " OR nick_name LIKE '$name'"; |
| 685 | } |
| 686 | |
| 687 | //CRM-10687 |
| 688 | if (!empty($params['field_name']) && !empty($params['table_name'])) { |
| 689 | $table_name = CRM_Utils_String::munge($params['table_name']); |
| 690 | $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')"; |
| 691 | $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')"; |
| 692 | // Search by id should be exact |
| 693 | if ($field_name == 'id' || $field_name == 'external_identifier') { |
| 694 | $whereClause = $exactWhereClause; |
| 695 | } |
| 696 | } |
| 697 | else { |
| 698 | if ($config->includeEmailInName) { |
| 699 | if (!in_array('email', $list)) { |
| 700 | $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )"; |
| 701 | } |
| 702 | $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} "; |
| 703 | $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; |
| 704 | } |
| 705 | else { |
| 706 | $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} "; |
| 707 | $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | $additionalFrom = ''; |
| 712 | if ($relType) { |
| 713 | $additionalFrom = " |
| 714 | INNER JOIN civicrm_relationship_type r ON ( |
| 715 | r.id = {$relType} |
| 716 | AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL ) |
| 717 | AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL ) |
| 718 | )"; |
| 719 | } |
| 720 | |
| 721 | // check if only CMS users are requested |
| 722 | if (!empty($params['cmsuser'])) { |
| 723 | $additionalFrom = " |
| 724 | INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id) |
| 725 | "; |
| 726 | } |
| 727 | |
| 728 | $orderByInner = ""; |
| 729 | $orderByOuter = "ORDER BY exactFirst"; |
| 730 | if ($config->includeOrderByClause) { |
| 731 | $orderByInner = "ORDER BY sort_name"; |
| 732 | $orderByOuter .= ", sort_name"; |
| 733 | } |
| 734 | |
| 735 | //CRM-5954 |
| 736 | $query = " |
| 737 | SELECT DISTINCT(id), data, sort_name {$selectAliases} |
| 738 | FROM ( |
| 739 | ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select} |
| 740 | FROM civicrm_contact cc {$from} |
| 741 | {$aclFrom} |
| 742 | {$additionalFrom} {$includeEmailFrom} |
| 743 | {$exactWhereClause} |
| 744 | LIMIT 0, {$limit} ) |
| 745 | UNION |
| 746 | ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select} |
| 747 | FROM civicrm_contact cc {$from} |
| 748 | {$aclFrom} |
| 749 | {$additionalFrom} {$includeEmailFrom} |
| 750 | {$whereClause} |
| 751 | {$orderByInner} |
| 752 | LIMIT 0, {$limit} ) |
| 753 | ) t |
| 754 | {$orderByOuter} |
| 755 | LIMIT 0, {$limit} |
| 756 | "; |
| 757 | // send query to hook to be modified if needed |
| 758 | CRM_Utils_Hook::contactListQuery($query, |
| 759 | $name, |
| 760 | empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'), |
| 761 | empty($params['id']) ? NULL : $params['id'] |
| 762 | ); |
| 763 | |
| 764 | $dao = CRM_Core_DAO::executeQuery($query); |
| 765 | |
| 766 | $contactList = array(); |
| 767 | $listCurrentEmployer = TRUE; |
| 768 | while ($dao->fetch()) { |
| 769 | $t = array('id' => $dao->id); |
| 770 | foreach ($as as $k) { |
| 771 | $t[$k] = isset($dao->$k)? $dao->$k: ''; |
| 772 | } |
| 773 | $t['data'] = $dao->data; |
| 774 | $contactList[] = $t; |
| 775 | if (!empty($params['org']) && |
| 776 | !empty($currEmpDetails) && |
| 777 | $dao->id == $currEmpDetails['id'] |
| 778 | ) { |
| 779 | $listCurrentEmployer = FALSE; |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | //return organization name if doesn't exist in db |
| 784 | if (empty($contactList)) { |
| 785 | if (!empty($params['org'])) { |
| 786 | if ($listCurrentEmployer && !empty($currEmpDetails)) { |
| 787 | $contactList = array( |
| 788 | array( |
| 789 | 'data' => $currEmpDetails['data'], |
| 790 | 'id' => $currEmpDetails['id'] |
| 791 | ) |
| 792 | ); |
| 793 | } |
| 794 | else { |
| 795 | $contactList = array( |
| 796 | array( |
| 797 | 'data' => $name, |
| 798 | 'id' => $name |
| 799 | ) |
| 800 | ); |
| 801 | } |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | return civicrm_api3_create_success($contactList, $params); |
| 806 | } |
| 807 | |
| 808 | /** |
| 809 | * Merges given pair of duplicate contacts. |
| 810 | * |
| 811 | * @param array $params input parameters |
| 812 | * |
| 813 | * Allowed @params array keys are: |
| 814 | * {int main_id main contact id with whom merge has to happen} |
| 815 | * {int other_id duplicate contact which would be deleted after merge operation} |
| 816 | * {string mode helps decide how to behave when there are conflicts. |
| 817 | * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.} |
| 818 | * {boolean auto_flip wether to let api decide which contact to retain and which to delete.} |
| 819 | * |
| 820 | * @return array API Result Array |
| 821 | * |
| 822 | * @static void |
| 823 | * @access public |
| 824 | */ |
| 825 | function civicrm_api3_contact_merge($params) { |
| 826 | $mode = CRM_Utils_Array::value('mode', $params, 'safe'); |
| 827 | $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE); |
| 828 | |
| 829 | $dupePairs = array(array('srcID' => CRM_Utils_Array::value('main_id', $params), |
| 830 | 'dstID' => CRM_Utils_Array::value('other_id', $params), |
| 831 | )); |
| 832 | $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip); |
| 833 | |
| 834 | if ($result['is_error'] == 0) { |
| 835 | return civicrm_api3_create_success(); |
| 836 | } |
| 837 | else { |
| 838 | return civicrm_api3_create_error($result['messages']); |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | function _civicrm_api3_contact_proximity_spec(&$params) { |
| 843 | $params['latitude']['api.required'] = 1; |
| 844 | $params['longitude']['api.required'] = 1; |
| 845 | $params['unit']['api.default'] = 'meter'; |
| 846 | } |
| 847 | |
| 848 | function civicrm_api3_contact_proximity($params) { |
| 849 | $latitude = CRM_Utils_Array::value('latitude', $params); |
| 850 | $longitude = CRM_Utils_Array::value('longitude', $params); |
| 851 | $distance = CRM_Utils_Array::value('distance', $params); |
| 852 | |
| 853 | $unit = CRM_Utils_Array::value('unit', $params); |
| 854 | |
| 855 | // check and ensure that lat/long and distance are floats |
| 856 | if ( |
| 857 | !CRM_Utils_Rule::numeric($latitude) || |
| 858 | !CRM_Utils_Rule::numeric($longitude) || |
| 859 | !CRM_Utils_Rule::numeric($distance) |
| 860 | ) { |
| 861 | throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric')); |
| 862 | } |
| 863 | |
| 864 | if ($unit == "mile") { |
| 865 | $conversionFactor = 1609.344; |
| 866 | } |
| 867 | else { |
| 868 | $conversionFactor = 1000; |
| 869 | } |
| 870 | //Distance in meters |
| 871 | $distance = $distance * $conversionFactor; |
| 872 | |
| 873 | $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance); |
| 874 | |
| 875 | $query = " |
| 876 | SELECT civicrm_contact.id as contact_id, |
| 877 | civicrm_contact.display_name as display_name |
| 878 | FROM civicrm_contact |
| 879 | LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id |
| 880 | WHERE $whereClause |
| 881 | "; |
| 882 | |
| 883 | $dao = CRM_Core_DAO::executeQuery($query); |
| 884 | $contacts = array(); |
| 885 | while ($dao->fetch()) { |
| 886 | $contacts[] = $dao->toArray(); |
| 887 | } |
| 888 | |
| 889 | return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao); |
| 890 | } |
| 891 | |
| 892 | |
| 893 | /** |
| 894 | * Overrides _civicrm_api3_generic_getlist_params. |
| 895 | * |
| 896 | * @param $request array |
| 897 | */ |
| 898 | function _civicrm_api3_contact_getlist_params(&$request) { |
| 899 | // get the autocomplete options from settings |
| 900 | $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR, |
| 901 | CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, |
| 902 | 'contact_autocomplete_options' |
| 903 | ) |
| 904 | ); |
| 905 | |
| 906 | // get the option values for contact autocomplete |
| 907 | $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name'); |
| 908 | |
| 909 | $list = array(); |
| 910 | foreach ($acpref as $value) { |
| 911 | if ($value && !empty($acOptions[$value])) { |
| 912 | $list[] = $acOptions[$value]; |
| 913 | } |
| 914 | } |
| 915 | // If we are doing quicksearch by a field other than name, make sure that field is added to results |
| 916 | $field_name = CRM_Utils_String::munge($request['search_field']); |
| 917 | // Unique name contact_id = id |
| 918 | if ($field_name == 'contact_id') { |
| 919 | $field_name = 'id'; |
| 920 | } |
| 921 | // phone_numeric should be phone |
| 922 | $searchField = str_replace('_numeric', '', $field_name); |
| 923 | if(!in_array($searchField, $list)) { |
| 924 | $list[] = $searchField; |
| 925 | } |
| 926 | $list[] = 'contact_type'; |
| 927 | $request['params']['return'] = $list; |
| 928 | $request['params']['options']['sort'] = 'sort_name'; |
| 929 | // Contact api doesn't support array(LIKE => 'foo') syntax |
| 930 | $request['params'][$request['search_field']] = $request['input']; |
| 931 | } |
| 932 | |
| 933 | /** |
| 934 | * Overrides _civicrm_api3_generic_getlist_output |
| 935 | * |
| 936 | * @param $result array |
| 937 | * @param $request array |
| 938 | * |
| 939 | * @return array |
| 940 | */ |
| 941 | function _civicrm_api3_contact_getlist_output($result, $request) { |
| 942 | $output = array(); |
| 943 | if (!empty($result['values'])) { |
| 944 | $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']); |
| 945 | foreach ($result['values'] as $row) { |
| 946 | $data = array( |
| 947 | 'id' => $row[$request['id_field']], |
| 948 | 'label' => $row[$request['label_field']], |
| 949 | 'description' => array(), |
| 950 | ); |
| 951 | foreach ($request['params']['return'] as $item) { |
| 952 | if (!strpos($item, '_name') && $item != 'contact_type' && !in_array($item, $addressFields) && !empty($row[$item])) { |
| 953 | $data['description'][] = $row[$item]; |
| 954 | } |
| 955 | } |
| 956 | $address = array(); |
| 957 | foreach($addressFields as $item) { |
| 958 | if (!empty($row[$item])) { |
| 959 | $address[] = $row[$item]; |
| 960 | } |
| 961 | } |
| 962 | if ($address) { |
| 963 | $data['description'][] = implode(' ', $address); |
| 964 | } |
| 965 | if (!empty($request['image_field'])) { |
| 966 | $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : ''; |
| 967 | } |
| 968 | else { |
| 969 | $data['icon_class'] = $row['contact_type']; |
| 970 | } |
| 971 | $output[] = $data; |
| 972 | } |
| 973 | } |
| 974 | return $output; |
| 975 | } |