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