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