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