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