Commit | Line | Data |
---|---|---|
6a488035 TO |
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 | * Adjust Metadata for Get action | |
194 | * | |
195 | * @param array $params array or parameters determined by getfields | |
196 | */ | |
197 | function _civicrm_api3_contact_get_spec(&$params) { | |
198 | $params['contact_is_deleted']['api.default'] = 0; | |
199 | ||
200 | //we declare all these pseudofields as there are other undocumented fields accessible | |
201 | // via the api - but if check permissions is set we only allow declared fields | |
202 | $params['address_id']['title'] = 'Primary Address ID'; | |
203 | $params['street_address']['title'] = 'Primary Address Street Address'; | |
204 | $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1'; | |
205 | $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2'; | |
206 | $params['city']['title'] = 'Primary Address City'; | |
207 | $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix'; | |
208 | $params['postal_code']['title'] = 'Primary Address Post Code'; | |
209 | $params['geo_code_1']['title'] = 'Primary Address Latitude'; | |
210 | $params['geo_code_2']['title'] = 'Primary Address Longitude'; | |
211 | $params['state_province_id']['title'] = 'Primary Address State Province ID'; | |
212 | $params['state_province_name']['title'] = 'Primary Address State Province Name'; | |
213 | $params['state_province']['title'] = 'Primary Address State Province'; | |
214 | $params['country_id']['title'] = 'Primary Address State Province ID'; | |
215 | $params['country']['title'] = 'Primary Address country'; | |
216 | $params['worldregion_id']['title'] = 'Primary Address World Region ID'; | |
217 | $params['worldregion']['title'] = 'Primary Address World Region'; | |
218 | $params['phone_id']['title'] = 'Primary Phone ID'; | |
219 | $params['phone_type_id']['title'] = 'Primary Phone Type ID'; | |
220 | $params['provider_id']['title'] = 'Primary Phone Provider ID'; | |
221 | $params['email_id']['title'] = 'Primary Email ID'; | |
222 | $params['email']['title'] = 'Primary Email'; | |
223 | $params['on_hold']['title'] = 'Primary Email On Hold'; | |
224 | $params['im']['title'] = 'Primary Instant Messanger'; | |
225 | $params['im_id']['title'] = 'Primary Instant Messanger ID'; | |
226 | $params['group_id']['title'] = 'Group Memberships (filter)'; | |
227 | $params['group']['title'] = 'Group Memberships (filter, array)'; | |
228 | $params['tag']['title'] = 'Assigned tags (filter, array)'; | |
229 | } | |
230 | ||
231 | /* | |
232 | * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get | |
233 | * and for getcount | |
234 | * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of | |
235 | * 0, 1 or not set | |
236 | * | |
237 | * We also support 'filter_group_id' & 'filter.group_id' | |
238 | * | |
239 | * @param array $params as passed into api get or getcount function | |
240 | * @param array $options array of options (so we can modify the filter) | |
241 | */ | |
242 | function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) { | |
243 | if (isset($params['showAll'])) { | |
244 | if (strtolower($params['showAll']) == "active") { | |
245 | $params['contact_is_deleted'] = 0; | |
246 | } | |
247 | if (strtolower($params['showAll']) == "trash") { | |
248 | $params['contact_is_deleted'] = 1; | |
249 | } | |
250 | if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) { | |
251 | unset($params['contact_is_deleted']); | |
252 | } | |
253 | } | |
254 | // support for group filters | |
255 | if (array_key_exists('filter_group_id', $params)) { | |
256 | $params['filter.group_id'] = $params['filter_group_id']; | |
257 | unset($params['filter_group_id']); | |
258 | } | |
259 | // filter.group_id works both for 1,2,3 and array (1,2,3) | |
260 | if (array_key_exists('filter.group_id', $params)) { | |
261 | if (is_array($params['filter.group_id'])) { | |
262 | $groups = $params['filter.group_id']; | |
263 | } | |
264 | else $groups = explode(',', $params['filter.group_id']); | |
265 | unset($params['filter.group_id']); | |
266 | $groups = array_flip($groups); | |
267 | $groups[key($groups)] = 1; | |
268 | $options['input_params']['group'] = $groups; | |
269 | } | |
270 | } | |
271 | ||
272 | /** | |
273 | * Delete a contact with given contact id | |
274 | * | |
275 | * @param array $params (reference ) input parameters, contact_id element required | |
276 | * | |
277 | * @return array API Result Array | |
278 | * @access public | |
279 | * | |
280 | * @example ContactDelete.php | |
281 | * {@getfields contact_delete} | |
282 | */ | |
283 | function civicrm_api3_contact_delete($params) { | |
284 | ||
285 | $contactID = CRM_Utils_Array::value('id', $params); | |
286 | ||
287 | $session = CRM_Core_Session::singleton(); | |
288 | if ($contactID == $session->get('userID')) { | |
289 | return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.'); | |
290 | } | |
291 | $restore = CRM_Utils_Array::value('restore', $params) ? $params['restore'] : FALSE; | |
292 | $skipUndelete = CRM_Utils_Array::value('skip_undelete', $params) ? $params['skip_undelete'] : FALSE; | |
293 | if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) { | |
294 | return civicrm_api3_create_success(); | |
295 | } | |
296 | else { | |
297 | return civicrm_api3_create_error('Could not delete contact'); | |
298 | } | |
299 | } | |
300 | ||
301 | ||
302 | function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeErrorArray = false, $obsoletevalue = true, $dedupeRuleGroupID = null ) | |
303 | { | |
304 | ||
305 | switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) { | |
306 | case 'household': | |
307 | civicrm_api3_verify_mandatory($params, null, array('household_name')); | |
308 | break; | |
309 | case 'organization': | |
310 | civicrm_api3_verify_mandatory($params, null, array('organization_name')); | |
311 | break; | |
312 | case 'individual': | |
313 | civicrm_api3_verify_one_mandatory($params, null, array( | |
314 | 'first_name', | |
315 | 'last_name', | |
316 | 'email', | |
317 | 'display_name', | |
318 | ) | |
319 | ); | |
320 | break; | |
321 | } | |
322 | ||
323 | if (CRM_Utils_Array::value('contact_sub_type', $params) && CRM_Utils_Array::value('contact_type', $params)) { | |
324 | if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) { | |
325 | return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type'])); | |
326 | } | |
327 | } | |
328 | ||
329 | if ($dupeCheck) { | |
330 | // check for record already existing | |
331 | $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']); | |
332 | ||
333 | // CRM-6431 | |
334 | // setting 'check_permission' here means that the dedupe checking will be carried out even if the | |
335 | // person does not have permission to carry out de-dupes | |
336 | // this is similar to the front end form | |
337 | if (isset($params['check_permission'])) { | |
338 | $dedupeParams['check_permission'] = $params['check_permission']; | |
339 | } | |
340 | ||
341 | $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array()); | |
342 | ||
343 | if (count($ids) >0) { | |
344 | throw new API_Exception("Found matching contacts: ". implode(',',$ids),"duplicate",array("ids"=>$ids)); | |
345 | } | |
346 | } | |
347 | ||
348 | //check for organisations with same name | |
349 | if (!empty($params['current_employer'])) { | |
350 | $organizationParams = array(); | |
351 | $organizationParams['organization_name'] = $params['current_employer']; | |
352 | ||
353 | $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization'); | |
354 | ||
355 | $dedupParams['check_permission'] = FALSE; | |
356 | $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised'); | |
357 | ||
358 | // check for mismatch employer name and id | |
359 | if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) { | |
360 | throw new API_Exception('Employer name and Employer id Mismatch'); | |
361 | } | |
362 | ||
363 | // show error if multiple organisation with same name exist | |
364 | if (empty($params['employer_id']) && (count($dupeIds) > 1)) { | |
365 | throw new API_Exception('Found more than one Organisation with same Name.'); | |
366 | } | |
367 | } | |
368 | ||
369 | return NULL; | |
370 | } | |
371 | ||
372 | /** | |
373 | * Takes an associative array and creates a contact object and all the associated | |
374 | * derived objects (i.e. individual, location, email, phone etc) | |
375 | * | |
376 | * @param array $params (reference ) an assoc array of name/value pairs | |
377 | * @param int $contactID if present the contact with that ID is updated | |
378 | * | |
379 | * @return object CRM_Contact_BAO_Contact object | |
380 | * @access public | |
381 | * @static | |
382 | */ | |
383 | function _civicrm_api3_contact_update($params, $contactID = NULL) { | |
384 | $transaction = new CRM_Core_Transaction(); | |
385 | ||
386 | if ($contactID) { | |
387 | $params['contact_id'] = $contactID; | |
388 | } | |
389 | ||
390 | $contact = CRM_Contact_BAO_Contact::create($params); | |
391 | ||
392 | $transaction->commit(); | |
393 | ||
394 | return $contact; | |
395 | } | |
396 | ||
397 | /** | |
398 | * Validate the addressee or email or postal greetings | |
399 | * | |
400 | * @param $params Associative array of property name/value | |
401 | * pairs to insert in new contact. | |
402 | * | |
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 | return civicrm_api3_create_error(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 | return civicrm_api3_create_error(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 | return civicrm_api3_create_error(ts('Invalid %1 greeting Id', array(1 => $key))); | |
468 | } | |
469 | ||
470 | if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) { | |
471 | return civicrm_api3_create_error(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 | return civicrm_api3_create_error(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 = $params['contact_id'] ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', | |
490 | $params['contact_id'], | |
491 | "{$key}{$greeting}_custom" | |
492 | ) : FALSE; | |
493 | ||
494 | if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) { | |
495 | $nullValue = TRUE; | |
496 | } | |
497 | elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) { | |
498 | $nullValue = TRUE; | |
499 | } | |
500 | elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params) | |
501 | && empty($params["{$key}{$greeting}_custom"]) | |
502 | ) { | |
503 | $nullValue = TRUE; | |
504 | } | |
505 | ||
506 | $params["{$key}{$greeting}_id"] = $greetingId; | |
507 | ||
508 | if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) { | |
509 | unset($params["{$key}{$greeting}_custom"]); | |
510 | } | |
511 | ||
512 | if ($nullValue) { | |
513 | $params["{$key}{$greeting}_id"] = ''; | |
514 | $params["{$key}{$greeting}_custom"] = ''; | |
515 | } | |
516 | ||
517 | if (isset($params["{$key}{$greeting}"])) { | |
518 | unset($params["{$key}{$greeting}"]); | |
519 | } | |
520 | } | |
521 | } | |
522 | ||
523 | /** | |
524 | * Contact quick search api | |
525 | * | |
526 | * @access public | |
527 | * | |
528 | * {@example ContactGetquick.php 0} | |
529 | * | |
530 | */ | |
531 | function civicrm_api3_contact_quicksearch($params) { | |
532 | // kept as an alias for compatibility reasons. CRM-11136 | |
533 | return civicrm_api3_contact_getquick($params); | |
534 | } | |
535 | ||
536 | function civicrm_api3_contact_getquick($params) { | |
537 | civicrm_api3_verify_mandatory($params, NULL, array('name')); | |
538 | $name = CRM_Utils_Array::value('name', $params); | |
539 | ||
540 | // get the autocomplete options from settings | |
541 | $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR, | |
542 | CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, | |
543 | 'contact_autocomplete_options' | |
544 | ) | |
545 | ); | |
546 | ||
547 | // get the option values for contact autocomplete | |
548 | $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name'); | |
549 | ||
550 | $list = array(); | |
551 | foreach ($acpref as $value) { | |
552 | if ($value && CRM_Utils_Array::value($value, $acOptions)) { | |
553 | $list[$value] = $acOptions[$value]; | |
554 | } | |
555 | } | |
556 | // If we are doing quicksearch by a field other than name, make sure that field is added to results | |
557 | if (!empty($params['field_name'])) { | |
558 | // phone_numeric should be phone | |
559 | $searchField = str_replace('_numeric', '', $params['field_name']); | |
560 | if(!in_array($searchField, $list)) { | |
561 | $list[] = $searchField; | |
562 | } | |
563 | } | |
564 | ||
565 | $select = $actualSelectElements = array('sort_name'); | |
566 | $where = ''; | |
567 | $from = array(); | |
568 | foreach ($list as $value) { | |
569 | $suffix = substr($value, 0, 2) . substr($value, -1); | |
570 | switch ($value) { | |
571 | case 'street_address': | |
572 | case 'city': | |
573 | case 'postal_code': | |
574 | $selectText = $value; | |
575 | $value = "address"; | |
576 | $suffix = 'sts'; | |
577 | case 'phone': | |
578 | case 'email': | |
579 | $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value; | |
580 | $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) "; | |
581 | break; | |
582 | ||
583 | case 'country': | |
584 | case 'state_province': | |
585 | $select[] = "{$suffix}.name as {$value}"; | |
586 | $actualSelectElements[] = "{$suffix}.name"; | |
587 | if (!in_array('address', $from)) { | |
588 | $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) '; | |
589 | } | |
590 | $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) "; | |
591 | break; | |
592 | ||
593 | default: | |
594 | if ($value != 'id') { | |
595 | $suffix = 'cc'; | |
596 | if (!empty($params['field_name']) && $params['field_name'] == 'value') { | |
597 | $suffix = CRM_Utils_Array::value('table_name', $params, 'cc'); | |
598 | } | |
599 | $actualSelectElements[] = $select[] = $suffix . '.' . $value; | |
600 | } | |
601 | break; | |
602 | } | |
603 | } | |
604 | ||
605 | $config = CRM_Core_Config::singleton(); | |
606 | $as = $select; | |
607 | $select = implode(', ', $select); | |
608 | if (!empty($select)) { | |
609 | $select = ", $select"; | |
610 | } | |
611 | $actualSelectElements = implode(', ', $actualSelectElements); | |
612 | $selectAliases = $from; | |
613 | unset($selectAliases['address']); | |
614 | $selectAliases = implode(', ', array_keys($selectAliases)); | |
615 | if (!empty($selectAliases)) { | |
616 | $selectAliases = ", $selectAliases"; | |
617 | } | |
618 | $from = implode(' ', $from); | |
619 | $limit = CRM_Utils_Array::value('limit', $params, 10); | |
620 | ||
621 | // add acl clause here | |
622 | list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc'); | |
623 | ||
624 | if ($aclWhere) { | |
625 | $where .= " AND $aclWhere "; | |
626 | } | |
627 | ||
628 | if (CRM_Utils_Array::value('org', $params)) { | |
629 | $where .= " AND contact_type = \"Organization\""; | |
630 | ||
631 | // CRM-7157, hack: get current employer details when | |
632 | // employee_id is present. | |
633 | $currEmpDetails = array(); | |
634 | if (CRM_Utils_Array::value('employee_id', $params)) { | |
635 | if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', | |
636 | CRM_Utils_Array::value('employee_id', $params), | |
637 | 'employer_id' | |
638 | )) { | |
639 | if ($config->includeWildCardInName) { | |
640 | $strSearch = "%$name%"; | |
641 | } | |
642 | else { | |
643 | $strSearch = "$name%"; | |
644 | } | |
645 | ||
646 | // get current employer details | |
647 | $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name | |
648 | FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'"); | |
649 | if ($dao->fetch()) { | |
650 | $currEmpDetails = array( | |
651 | 'id' => $dao->id, | |
652 | 'data' => $dao->data, | |
653 | ); | |
654 | } | |
655 | } | |
656 | } | |
657 | } | |
658 | ||
659 | //set default for current_employer or return contact with particular id | |
660 | if (CRM_Utils_Array::value('id', $params)) { | |
661 | $where .= " AND cc.id = " .$params['id']; | |
662 | } | |
663 | ||
664 | if (CRM_Utils_Array::value('cid', $params)) { | |
665 | $where .= " AND cc.id <> {$params['cid']}"; | |
666 | } | |
667 | ||
668 | //contact's based of relationhip type | |
669 | $relType = NULL; | |
670 | if (CRM_Utils_Array::value('rel', $params)) { | |
671 | $relation = explode('_', CRM_Utils_Array::value('rel', $params)); | |
672 | $relType = CRM_Utils_Type::escape($relation[0], 'Integer'); | |
673 | $rel = CRM_Utils_Type::escape($relation[2], 'String'); | |
674 | } | |
675 | ||
676 | if ($config->includeWildCardInName) { | |
677 | $strSearch = "%$name%"; | |
678 | } | |
679 | else { | |
680 | $strSearch = "$name%"; | |
681 | } | |
682 | $includeEmailFrom = $includeNickName = $exactIncludeNickName = ''; | |
683 | if ($config->includeNickNameInName) { | |
684 | $includeNickName = " OR nick_name LIKE '$strSearch'"; | |
685 | $exactIncludeNickName = " OR nick_name LIKE '$name'"; | |
686 | } | |
687 | ||
688 | //CRM-10687 | |
689 | if (!empty($params['field_name']) && !empty($params['table_name'])) { | |
690 | $field_name = $params['field_name']; | |
691 | $table_name = $params['table_name']; | |
692 | $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')"; | |
693 | $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')"; | |
694 | // Search by id should be exact | |
695 | if ($field_name == 'id' || $field_name == 'external_identifier') { | |
696 | $whereClause = $exactWhereClause; | |
697 | } | |
698 | } | |
699 | else { | |
700 | if ($config->includeEmailInName) { | |
701 | if (!in_array('email', $list)) { | |
702 | $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )"; | |
703 | } | |
704 | $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} "; | |
705 | $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; | |
706 | } | |
707 | else { | |
708 | $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} "; | |
709 | $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} "; | |
710 | } | |
711 | } | |
712 | ||
713 | $additionalFrom = ''; | |
714 | if ($relType) { | |
715 | $additionalFrom = " | |
716 | INNER JOIN civicrm_relationship_type r ON ( | |
717 | r.id = {$relType} | |
718 | AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL ) | |
719 | AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL ) | |
720 | )"; | |
721 | } | |
722 | ||
723 | // check if only CMS users are requested | |
724 | if (CRM_Utils_Array::value('cmsuser', $params)) { | |
725 | $additionalFrom = " | |
726 | INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id) | |
727 | "; | |
728 | } | |
729 | ||
730 | //CRM-5954 | |
731 | $query = " | |
732 | SELECT DISTINCT(id), data, sort_name {$selectAliases} | |
733 | FROM ( | |
734 | ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select} | |
735 | FROM civicrm_contact cc {$from} | |
736 | {$aclFrom} | |
737 | {$additionalFrom} {$includeEmailFrom} | |
738 | {$exactWhereClause} | |
739 | LIMIT 0, {$limit} ) | |
740 | UNION | |
741 | ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select} | |
742 | FROM civicrm_contact cc {$from} | |
743 | {$aclFrom} | |
744 | {$additionalFrom} {$includeEmailFrom} | |
745 | {$whereClause} | |
746 | ORDER BY sort_name | |
747 | LIMIT 0, {$limit} ) | |
748 | ) t | |
749 | ORDER BY exactFirst, sort_name | |
750 | LIMIT 0, {$limit} | |
751 | "; | |
752 | // send query to hook to be modified if needed | |
753 | CRM_Utils_Hook::contactListQuery($query, | |
754 | $name, | |
755 | CRM_Utils_Array::value('context', $params), | |
756 | CRM_Utils_Array::value('id', $params) | |
757 | ); | |
758 | ||
759 | $dao = CRM_Core_DAO::executeQuery($query); | |
760 | ||
761 | $contactList = array(); | |
762 | $listCurrentEmployer = TRUE; | |
763 | while ($dao->fetch()) { | |
764 | $t = array('id' => $dao->id); | |
765 | foreach ($as as $k) { | |
766 | $t[$k] = isset($dao->$k)? $dao->$k: ''; | |
767 | } | |
768 | $t['data'] = $dao->data; | |
769 | $contactList[] = $t; | |
770 | if (CRM_Utils_Array::value('org', $params) && | |
771 | !empty($currEmpDetails) && | |
772 | $dao->id == $currEmpDetails['id'] | |
773 | ) { | |
774 | $listCurrentEmployer = FALSE; | |
775 | } | |
776 | } | |
777 | ||
778 | //return organization name if doesn't exist in db | |
779 | if (empty($contactList)) { | |
780 | if (CRM_Utils_Array::value('org', $params)) { | |
781 | if ($listCurrentEmployer && !empty($currEmpDetails)) { | |
782 | $contactList = array( | |
783 | array( | |
784 | 'data' => $currEmpDetails['data'], | |
785 | 'id' => $currEmpDetails['id'] | |
786 | ) | |
787 | ); | |
788 | } | |
789 | else { | |
790 | $contactList = array( | |
791 | array( | |
792 | 'data' => $name, | |
793 | 'id' => $name | |
794 | ) | |
795 | ); | |
796 | } | |
797 | } | |
798 | } | |
799 | ||
800 | return civicrm_api3_create_success($contactList, $params); | |
801 | } | |
802 | ||
803 | /** | |
804 | * Merges given pair of duplicate contacts. | |
805 | * | |
806 | * @param array $params input parameters | |
807 | * | |
808 | * Allowed @params array keys are: | |
809 | * {int main_id main contact id with whom merge has to happen} | |
810 | * {int other_id duplicate contact which would be deleted after merge operation} | |
811 | * {string mode helps decide how to behave when there are conflicts. | |
812 | * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.} | |
813 | * {boolean auto_flip wether to let api decide which contact to retain and which to delete.} | |
814 | * | |
815 | * @return array API Result Array | |
816 | * | |
817 | * @static void | |
818 | * @access public | |
819 | */ | |
820 | function civicrm_api3_contact_merge($params) { | |
821 | $mode = CRM_Utils_Array::value('mode', $params, 'safe'); | |
822 | $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE); | |
823 | ||
824 | $dupePairs = array(array('srcID' => CRM_Utils_Array::value('main_id', $params), | |
825 | 'dstID' => CRM_Utils_Array::value('other_id', $params), | |
826 | )); | |
827 | $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip); | |
828 | ||
829 | if ($result['is_error'] == 0) { | |
830 | return civicrm_api3_create_success(); | |
831 | } | |
832 | else { | |
833 | return civicrm_api3_create_error($result['messages']); | |
834 | } | |
835 | } | |
836 | ||
837 | function _civicrm_api3_contact_proximity_spec(&$params) { | |
838 | $params['latitude']['api.required'] = 1; | |
839 | $params['longitude']['api.required'] = 1; | |
840 | $params['unit']['api.default'] = 'meter'; | |
841 | } | |
842 | ||
843 | function civicrm_api3_contact_proximity($params) { | |
844 | $latitude = CRM_Utils_Array::value('latitude', $params); | |
845 | $longitude = CRM_Utils_Array::value('longitude', $params); | |
846 | $distance = CRM_Utils_Array::value('distance', $params); | |
847 | ||
848 | $unit = CRM_Utils_Array::value('unit', $params); | |
849 | ||
850 | // check and ensure that lat/long and distance are floats | |
851 | if ( | |
852 | !CRM_Utils_Rule::numeric($latitude) || | |
853 | !CRM_Utils_Rule::numeric($longitude) || | |
854 | !CRM_Utils_Rule::numeric($distance) | |
855 | ) { | |
856 | throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric')); | |
857 | } | |
858 | ||
859 | if ($unit == "mile") { | |
860 | $conversionFactor = 1609.344; | |
861 | } | |
862 | else { | |
863 | $conversionFactor = 1000; | |
864 | } | |
865 | //Distance in meters | |
866 | $distance = $distance * $conversionFactor; | |
867 | ||
868 | $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance); | |
869 | ||
870 | $query = " | |
871 | SELECT civicrm_contact.id as contact_id, | |
872 | civicrm_contact.display_name as display_name | |
873 | FROM civicrm_contact | |
874 | LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id | |
875 | WHERE $whereClause | |
876 | "; | |
877 | ||
878 | $dao = CRM_Core_DAO::executeQuery($query); | |
879 | $contacts = array(); | |
880 | while ($dao->fetch()) { | |
881 | $contacts[] = $dao->toArray(); | |
882 | } | |
883 | ||
884 | return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao); | |
885 | } | |
886 |