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