Merge pull request #14062 from civicrm/5.13
[civicrm-core.git] / CRM / Contact / BAO / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact {
34
35 /**
36 * SQL function used to format the phone_numeric field via trigger.
37 * @see self::triggerInfo()
38 *
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
41 */
42 const DROP_STRIP_FUNCTION_43 = "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43 = "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
46 DETERMINISTIC
47 NO SQL
48 BEGIN
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
54 END IF;
55 SET iterator = iterator + 1;
56 END WHILE;
57 RETURN output;
58 END";
59
60 /**
61 * The types of communication preferences.
62 *
63 * @var array
64 */
65 public static $_commPrefs = array(
66 'do_not_phone',
67 'do_not_email',
68 'do_not_mail',
69 'do_not_sms',
70 'do_not_trade',
71 );
72
73 /**
74 * Types of greetings.
75 *
76 * @var array
77 */
78 public static $_greetingTypes = array(
79 'addressee',
80 'email_greeting',
81 'postal_greeting',
82 );
83
84 /**
85 * Static field for all the contact information that we can potentially import.
86 *
87 * @var array
88 */
89 public static $_importableFields = array();
90
91 /**
92 * Static field for all the contact information that we can potentially export.
93 *
94 * @var array
95 */
96 public static $_exportableFields = NULL;
97
98 /**
99 * Class constructor.
100 */
101 public function __construct() {
102 parent::__construct();
103 }
104
105 /**
106 * Takes an associative array and creates a contact object.
107 *
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
110 * pairs
111 *
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
114 *
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
118 */
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
121
122 if (empty($params)) {
123 return NULL;
124 }
125
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
130 }
131 else {
132 if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
134 )
135 ) {
136 // we'll need to fix tests to handle this
137 // CRM-7925
138 CRM_Core_Error::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
139 }
140 $params['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
141 }
142 }
143 else {
144 // Reset the value.
145 // CRM-101XX.
146 $params['contact_sub_type'] = 'null';
147 }
148
149 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
150 CRM_Utils_Array::formatArrayKeys($params['preferred_communication_method']);
151 $contact->preferred_communication_method = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
152 unset($params['preferred_communication_method']);
153 }
154
155 $defaults = ['source' => CRM_Utils_Array::value('contact_source', $params)];
156 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
157 $defaults['display_name'] = $params['organization_name'];
158 $defaults['sort_name'] = $params['organization_name'];
159 }
160 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
161 $defaults['display_name'] = $params['household_name'];
162 $defaults['sort_name'] = $params['household_name'];
163 }
164 $params = array_merge($defaults, $params);
165
166 $allNull = $contact->copyValues($params);
167
168 $contact->id = CRM_Utils_Array::value('contact_id', $params);
169
170 if ($contact->contact_type == 'Individual') {
171 $allNull = FALSE;
172 // @todo allow the lines below to be overridden by input or hooks & add tests,
173 // as has been done for households and organizations.
174 // Format individual fields.
175 CRM_Contact_BAO_Individual::format($params, $contact);
176 }
177
178 if (strlen($contact->display_name) > 128) {
179 $contact->display_name = substr($contact->display_name, 0, 128);
180 }
181 if (strlen($contact->sort_name) > 128) {
182 $contact->sort_name = substr($contact->sort_name, 0, 128);
183 }
184
185 $privacy = CRM_Utils_Array::value('privacy', $params);
186 if ($privacy &&
187 is_array($privacy) &&
188 !empty($privacy)
189 ) {
190 $allNull = FALSE;
191 foreach (self::$_commPrefs as $name) {
192 $contact->$name = CRM_Utils_Array::value($name, $privacy, FALSE);
193 }
194 }
195
196 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
197 // @todo - does this mean we can remove this block?
198 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
199 if ((!array_key_exists('hash', $contact) || !$contact->hash) && !$contact->id) {
200 $allNull = FALSE;
201 $contact->hash = md5(uniqid(rand(), TRUE));
202 }
203
204 // Even if we don't need $employerId, it's important to call getFieldValue() before
205 // the contact is saved because we want the existing value to be cached.
206 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
207 $employerId = empty($contact->id) ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
208
209 if (!$allNull) {
210 $contact->save();
211
212 CRM_Core_BAO_Log::register($contact->id,
213 'civicrm_contact',
214 $contact->id
215 );
216 }
217
218 if ($contact->contact_type == 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
219 // Create current employer.
220 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : CRM_Utils_Array::value('current_employer', $params);
221
222 $newContact = FALSE;
223 if (empty($params['contact_id'])) {
224 $newContact = TRUE;
225 }
226 if ($newEmployer) {
227 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
228 }
229 else {
230 if ($employerId) {
231 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
232 }
233 }
234 }
235
236 // Update cached employer name.
237 if ($contact->contact_type == 'Organization') {
238 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
239 }
240
241 return $contact;
242 }
243
244 /**
245 * Create contact.
246 *
247 * takes an associative array and creates a contact object and all the associated
248 * derived objects (i.e. individual, location, email, phone etc)
249 *
250 * This function is invoked from within the web form layer and also from the api layer
251 *
252 * @param array $params
253 * (reference ) an assoc array of name/value pairs.
254 * @param bool $fixAddress
255 * If we need to fix address.
256 * @param bool $invokeHooks
257 * If we need to invoke hooks.
258 *
259 * @param bool $skipDelete
260 * Unclear parameter, passed to website create
261 *
262 * @todo explain this parameter
263 *
264 * @throws Exception
265 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
266 * Created or updated contribution object. We are deprecating returning an error in
267 * favour of exceptions
268 */
269 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
270 $contact = NULL;
271 if (empty($params['contact_type']) && empty($params['contact_id'])) {
272 return $contact;
273 }
274
275 $isEdit = TRUE;
276 if ($invokeHooks) {
277 if (!empty($params['contact_id'])) {
278 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
279 }
280 else {
281 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
282 $isEdit = FALSE;
283 }
284 }
285
286 self::ensureGreetingParamsAreSet($params);
287
288 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
289 if (empty($params['contact_id'])) {
290 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
291 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
292 $params['preferred_language'] = $language;
293 }
294
295 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
296 if (empty($params['communication_style_id'])) {
297 $defaultCommunicationStyleId = CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
298 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
299 }
300 }
301
302 $transaction = new CRM_Core_Transaction();
303
304 $contact = self::add($params);
305 if (!$contact) {
306 // Not dying here is stupid, since we get into weird situation and into a bug that
307 // is impossible to figure out for the user or for us
308 // CRM-7925
309 CRM_Core_Error::fatal();
310 }
311
312 $params['contact_id'] = $contact->id;
313
314 if (Civi::settings()->get('is_enabled')) {
315 // Enabling multisite causes the contact to be added to the domain group.
316 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
317 if (!empty($domainGroupID)) {
318 if (!empty($params['group']) && is_array($params['group'])) {
319 $params['group'][$domainGroupID] = 1;
320 }
321 else {
322 $params['group'] = array($domainGroupID => 1);
323 }
324 }
325 }
326
327 if (array_key_exists('group', $params)) {
328 $contactIds = array($params['contact_id']);
329 foreach ($params['group'] as $groupId => $flag) {
330 if ($flag == 1) {
331 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
332 }
333 elseif ($flag == -1) {
334 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
335 }
336 }
337 }
338
339 // Add location Block data.
340 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
341 foreach ($blocks as $name => $value) {
342 $contact->$name = $value;
343 }
344 if (!empty($params['updateBlankLocInfo'])) {
345 $skipDelete = TRUE;
346 }
347
348 if (isset($params['website'])) {
349 CRM_Core_BAO_Website::process($params['website'], $contact->id, $skipDelete);
350 }
351
352 $userID = CRM_Core_Session::singleton()->get('userID');
353 // add notes
354 if (!empty($params['note'])) {
355 if (is_array($params['note'])) {
356 foreach ($params['note'] as $note) {
357 $contactId = $contact->id;
358 if (isset($note['contact_id'])) {
359 $contactId = $note['contact_id'];
360 }
361 //if logged in user, overwrite contactId
362 if ($userID) {
363 $contactId = $userID;
364 }
365
366 $noteParams = array(
367 'entity_id' => $contact->id,
368 'entity_table' => 'civicrm_contact',
369 'note' => $note['note'],
370 'subject' => CRM_Utils_Array::value('subject', $note),
371 'contact_id' => $contactId,
372 );
373 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
374 }
375 }
376 else {
377 $contactId = $contact->id;
378 //if logged in user, overwrite contactId
379 if ($userID) {
380 $contactId = $userID;
381 }
382
383 $noteParams = array(
384 'entity_id' => $contact->id,
385 'entity_table' => 'civicrm_contact',
386 'note' => $params['note'],
387 'subject' => CRM_Utils_Array::value('subject', $params),
388 'contact_id' => $contactId,
389 );
390 CRM_Core_BAO_Note::add($noteParams, CRM_Core_DAO::$_nullArray);
391 }
392 }
393
394 // update the UF user_unique_id if that has changed
395 CRM_Core_BAO_UFMatch::updateUFName($contact->id);
396
397 if (!empty($params['custom']) &&
398 is_array($params['custom'])
399 ) {
400 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id);
401 }
402
403 // make a civicrm_subscription_history entry only on contact create (CRM-777)
404 if (empty($params['contact_id'])) {
405 $subscriptionParams = array(
406 'contact_id' => $contact->id,
407 'status' => 'Added',
408 'method' => 'Admin',
409 );
410 CRM_Contact_BAO_SubscriptionHistory::create($subscriptionParams);
411 }
412
413 $transaction->commit();
414
415 // CRM-6367: fetch the right label for contact type’s display
416 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
417 'CRM_Contact_DAO_ContactType',
418 $contact->contact_type,
419 'label',
420 'name'
421 );
422
423 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
424
425 if ($invokeHooks) {
426 if ($isEdit) {
427 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
428 }
429 else {
430 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
431 }
432 }
433
434 // In order to prevent a series of expensive queries in intensive batch processing
435 // api calls may pass in skip_greeting_processing, probably doing it later via the
436 // scheduled job. CRM-21551
437 if (empty($params['skip_greeting_processing'])) {
438 self::processGreetings($contact);
439 }
440
441 return $contact;
442 }
443
444 /**
445 * Ensure greeting parameters are set.
446 *
447 * By always populating greetings here we can be sure they are set if required & avoid a call later.
448 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
449 *
450 * @param array $params
451 */
452 public static function ensureGreetingParamsAreSet(&$params) {
453 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
454 $missingGreetingParams = array();
455
456 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
457 if (empty($params[$greetingParam])) {
458 $missingGreetingParams[$greetingIndex] = $greetingParam;
459 }
460 }
461
462 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
463 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
464 'id' => $params['contact_id'],
465 'return' => array_keys($missingGreetingParams),
466 )
467 );
468
469 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
470 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
471 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
472 }
473 }
474 // Filter out other fields.
475 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
476 $params = array_merge($params, $savedGreetings);
477 }
478 else {
479 foreach ($missingGreetingParams as $greetingName => $greeting) {
480 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greetingName);
481 }
482 }
483
484 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
485 if ($params[$greetingParam] === 'null') {
486 // If we are setting it to null then null out the display field.
487 $params[$greetingIndex . '_display'] = 'null';
488 }
489 }
490 }
491
492 /**
493 * Get the display name and image of a contact.
494 *
495 * @param int $id
496 * The contactId.
497 *
498 * @param bool $includeTypeInReturnParameters
499 * Should type be part of the returned array?
500 *
501 * @return array
502 * the displayName and contactImage for this contact
503 */
504 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
505 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
506 $sql = "
507 SELECT civicrm_contact.*,
508 civicrm_email.email as email
509 FROM civicrm_contact
510 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
511 AND civicrm_email.is_primary = 1
512 WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
513 $dao = new CRM_Core_DAO();
514 $dao->query($sql);
515 if ($dao->fetch()) {
516 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
517 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
518 );
519 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
520 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
521 );
522
523 // use email if display_name is empty
524 if (empty($dao->display_name)) {
525 $displayName = $dao->email;
526 }
527 else {
528 $displayName = $dao->display_name;
529 }
530
531 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
532
533 return $includeTypeInReturnParameters ? array(
534 $displayName,
535 $image,
536 $dao->contact_type,
537 $dao->contact_sub_type,
538 $imageUrl,
539 ) : array($displayName, $image, $imageUrl);
540 }
541 return NULL;
542 }
543
544 /**
545 * Add billing fields to the params if appropriate.
546 *
547 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
548 * don't then we should set the name fields to the filling fields AND add the preserveDBName
549 * parameter (which will tell the BAO only to set those fields if none already exist.
550 *
551 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
552 * matching is best done by hipsters.
553 *
554 * @param array $params
555 */
556 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
557 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
558 foreach ($nameFields as $field) {
559 if (!empty($params[$field])) {
560 return;
561 }
562 }
563 // There are only 3 - we can iterate through them twice :-)
564 foreach ($nameFields as $field) {
565 if (!empty($params['billing_' . $field])) {
566 $params[$field] = $params['billing_' . $field];
567 }
568 $params['preserveDBName'] = TRUE;
569 }
570
571 }
572
573 /**
574 * Resolve a state province string (UT or Utah) to an ID.
575 *
576 * If country has been passed in we should select a state belonging to that country.
577 *
578 * Alternatively we should choose from enabled countries, prioritising the default country.
579 *
580 * @param array $values
581 * @param int|NULL $countryID
582 *
583 * @return int|null
584 */
585 protected static function resolveStateProvinceID($values, $countryID) {
586
587 if ($countryID) {
588 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID);
589 if (CRM_Utils_Array::lookupValue($values,
590 'state_province',
591 $stateProvinceList,
592 TRUE
593 )) {
594 return $values['state_province_id'];
595 }
596 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID, 'abbreviation');
597 if (CRM_Utils_Array::lookupValue($values,
598 'state_province',
599 $stateProvinceList,
600 TRUE
601 )) {
602 return $values['state_province_id'];
603 }
604 return NULL;
605 }
606 else {
607 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
608 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
609 // prefer matching country..
610 $stateProvinceList = CRM_Core_BAO_Address::buildOptions('state_province_id', NULL, array('country_id' => Civi::settings()->get('defaultContactCountry')));
611 if (CRM_Utils_Array::lookupValue($values,
612 'state_province',
613 $stateProvinceList,
614 TRUE
615 )) {
616 return $values['state_province_id'];
617 }
618
619 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
620 if (CRM_Utils_Array::lookupValue($values,
621 'state_province',
622 $stateProvinceList,
623 TRUE
624 )) {
625 return $values['state_province_id'];
626 }
627
628 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviationForDefaultCountry();
629 if (CRM_Utils_Array::lookupValue($values,
630 'state_province',
631 $stateProvinceList,
632 TRUE
633 )) {
634 return $values['state_province_id'];
635 }
636 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
637 if (CRM_Utils_Array::lookupValue($values,
638 'state_province',
639 $stateProvinceList,
640 TRUE
641 )) {
642 return $values['state_province_id'];
643 }
644 }
645
646 return NULL;
647 }
648
649 /**
650 * Get the relevant location entity for the array key.
651 *
652 * Based on the field name we determine which location entity
653 * we are dealing with. Apart from a few specific ones they
654 * are mostly 'address' (the default).
655 *
656 * @param string $fieldName
657 *
658 * @return string
659 */
660 protected static function getLocationEntityForKey($fieldName) {
661 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
662 return $fieldName;
663 }
664 if ($fieldName === 'phone_ext') {
665 return 'phone';
666 }
667 return 'address';
668 }
669
670 /**
671 * Create last viewed link to recently updated contact.
672 *
673 * @param array $crudLinkSpec
674 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
675 * - entity_table: string, eg "civicrm_contact"
676 * - entity_id: int
677 *
678 * @return array|NULL
679 * NULL if unavailable, or
680 * [path: string, query: string, title: string]
681 * @see CRM_Utils_System::createDefaultCrudLink
682 */
683 public function createDefaultCrudLink($crudLinkSpec) {
684 switch ($crudLinkSpec['action']) {
685 case CRM_Core_Action::VIEW:
686 $result = array(
687 'title' => $this->display_name,
688 'path' => 'civicrm/contact/view',
689 'query' => array(
690 'reset' => 1,
691 'cid' => $this->id,
692 ),
693 );
694 return $result;
695
696 case CRM_Core_Action::UPDATE:
697 $result = array(
698 'title' => $this->display_name,
699 'path' => 'civicrm/contact/add',
700 'query' => array(
701 'reset' => 1,
702 'action' => 'update',
703 'cid' => $this->id,
704 ),
705 );
706 return $result;
707 }
708 return NULL;
709 }
710
711 /**
712 * Get the values for pseudoconstants for name->value and reverse.
713 *
714 * @deprecated
715 *
716 * This is called specifically from the contact import parser & should be moved there
717 * as it is not truly a generic function.
718 *
719 * @param array $defaults
720 * (reference) the default values, some of which need to be resolved.
721 * @param bool $reverse
722 * Always true as this function is only called from one place..
723 */
724 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
725 // Hack for birth_date.
726 if (!empty($defaults['birth_date'])) {
727 if (is_array($defaults['birth_date'])) {
728 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
729 }
730 }
731
732 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
733 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
734 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
735 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
736
737 //lookup value of email/postal greeting, addressee, CRM-4575
738 foreach (self::$_greetingTypes as $greeting) {
739 $filterCondition = array(
740 'contact_type' => CRM_Utils_Array::value('contact_type', $defaults),
741 'greeting_type' => $greeting,
742 );
743 CRM_Utils_Array::lookupValue($defaults, $greeting,
744 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
745 );
746 }
747
748 $blocks = array('address', 'im', 'phone');
749 foreach ($blocks as $name) {
750 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
751 continue;
752 }
753 foreach ($defaults[$name] as $count => & $values) {
754
755 //get location type id.
756 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
757
758 if ($name == 'address') {
759 // FIXME: lookupValue doesn't work for vcard_name
760 if (!empty($values['location_type_id'])) {
761 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
762 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
763 }
764
765 if (!CRM_Utils_Array::lookupValue($values,
766 'country',
767 CRM_Core_PseudoConstant::country(),
768 $reverse
769 ) &&
770 $reverse
771 ) {
772 CRM_Utils_Array::lookupValue($values,
773 'country',
774 CRM_Core_PseudoConstant::countryIsoCode(),
775 $reverse
776 );
777 }
778 $stateProvinceID = self::resolveStateProvinceID($values, CRM_Utils_Array::value('country_id', $values));
779 if ($stateProvinceID) {
780 $values['state_province_id'] = $stateProvinceID;
781 }
782
783 if (!empty($values['state_province_id'])) {
784 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
785 }
786 else {
787 $countyList = CRM_Core_PseudoConstant::county();
788 }
789 CRM_Utils_Array::lookupValue($values,
790 'county',
791 $countyList,
792 $reverse
793 );
794 }
795
796 if ($name == 'im') {
797 CRM_Utils_Array::lookupValue($values,
798 'provider',
799 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
800 $reverse
801 );
802 }
803
804 if ($name == 'phone') {
805 CRM_Utils_Array::lookupValue($values,
806 'phone_type',
807 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
808 $reverse
809 );
810 }
811
812 // Kill the reference.
813 unset($values);
814 }
815 }
816 }
817
818 /**
819 * Fetch object based on array of properties.
820 *
821 * @param array $params
822 * (reference ) an assoc array of name/value pairs.
823 * @param array $defaults
824 * (reference ) an assoc array to hold the name / value pairs.
825 * in a hierarchical manner
826 * @param bool $microformat
827 * For location in microformat.
828 *
829 * @return CRM_Contact_BAO_Contact
830 */
831 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
832 if (array_key_exists('contact_id', $params)) {
833 $params['id'] = $params['contact_id'];
834 }
835 elseif (array_key_exists('id', $params)) {
836 $params['contact_id'] = $params['id'];
837 }
838
839 $contact = self::getValues($params, $defaults);
840
841 unset($params['id']);
842
843 //get the block information for this contact
844 $entityBlock = array('contact_id' => $params['contact_id']);
845 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
846 $defaults = array_merge($defaults, $blocks);
847 foreach ($blocks as $block => $value) {
848 $contact->$block = $value;
849 }
850
851 if (!isset($params['noNotes'])) {
852 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
853 }
854
855 if (!isset($params['noRelationships'])) {
856 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
857 }
858
859 if (!isset($params['noGroups'])) {
860 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
861 }
862
863 if (!isset($params['noWebsite'])) {
864 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
865 }
866
867 return $contact;
868 }
869
870 /**
871 * Get the display name of a contact.
872 *
873 * @param int $id
874 * Id of the contact.
875 *
876 * @return null|string
877 * display name of the contact if found
878 */
879 public static function displayName($id) {
880 $displayName = NULL;
881 if ($id) {
882 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
883 }
884
885 return $displayName;
886 }
887
888 /**
889 * Delete a contact and all its associated records.
890 *
891 * @param int $id
892 * Id of the contact to delete.
893 * @param bool $restore
894 * Whether to actually restore, not delete.
895 * @param bool $skipUndelete
896 * Whether to force contact delete or not.
897 * @param bool $checkPermissions
898 *
899 * @return bool
900 * Was contact deleted?
901 */
902 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
903
904 if (!$id) {
905 return FALSE;
906 }
907 // If trash is disabled in system settings then we always skip
908 if (!Civi::settings()->get('contact_undelete')) {
909 $skipUndelete = TRUE;
910 }
911
912 // make sure we have edit permission for this contact
913 // before we delete
914 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
915 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
916 ) {
917 return FALSE;
918 }
919
920 // CRM-12929
921 // Restrict contact to be delete if contact has financial trxns
922 $error = NULL;
923 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) {
924 return FALSE;
925 }
926
927 // make sure this contact_id does not have any membership types
928 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
929 $id,
930 'id',
931 'member_of_contact_id'
932 );
933 if ($membershipTypeID) {
934 return FALSE;
935 }
936
937 $contact = new CRM_Contact_DAO_Contact();
938 $contact->id = $id;
939 if (!$contact->find(TRUE)) {
940 return FALSE;
941 }
942
943 $contactType = $contact->contact_type;
944 // currently we only clear employer cache.
945 // we are now deleting inherited membership if any.
946 if ($contact->contact_type == 'Organization') {
947 $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE;
948 $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id);
949 if (!empty($relationshipDtls)) {
950 foreach ($relationshipDtls as $rId => $details) {
951 CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action);
952 }
953 }
954 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
955 }
956
957 if ($restore) {
958 return self::contactTrashRestore($contact, TRUE);
959 }
960
961 // start a new transaction
962 $transaction = new CRM_Core_Transaction();
963
964 if ($skipUndelete) {
965 CRM_Utils_Hook::pre('delete', $contactType, $id, CRM_Core_DAO::$_nullArray);
966
967 //delete billing address if exists.
968 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
969
970 // delete the log entries since we dont have triggers enabled as yet
971 $logDAO = new CRM_Core_DAO_Log();
972 $logDAO->entity_table = 'civicrm_contact';
973 $logDAO->entity_id = $id;
974 $logDAO->delete();
975
976 // delete contact participants CRM-12155
977 CRM_Event_BAO_Participant::deleteContactParticipant($id);
978
979 // delete contact contributions CRM-12155
980 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
981
982 // do activity cleanup, CRM-5604
983 CRM_Activity_BAO_Activity::cleanupActivity($id);
984
985 // delete all notes related to contact
986 CRM_Core_BAO_Note::cleanContactNotes($id);
987
988 // delete cases related to contact
989 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
990 if (!empty($contactCases)) {
991 foreach ($contactCases as $caseId) {
992 //check if case is associate with other contact or not.
993 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
994 if (count($caseContactId) <= 1) {
995 CRM_Case_BAO_Case::deleteCase($caseId);
996 }
997 }
998 }
999
1000 $contact->delete();
1001 }
1002 else {
1003 self::contactTrashRestore($contact);
1004 }
1005
1006 //delete the contact id from recently view
1007 CRM_Utils_Recent::delContact($id);
1008 self::updateContactCache($id, empty($restore));
1009
1010 // delete any prevnext/dupe cache entry
1011 // These two calls are redundant in default deployments, but they're
1012 // meaningful if "prevnext" is memory-backed.
1013 Civi::service('prevnext')->deleteItem($id);
1014 CRM_Core_BAO_PrevNextCache::deleteItem($id);
1015
1016 $transaction->commit();
1017
1018 if ($skipUndelete) {
1019 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
1020 }
1021
1022 return TRUE;
1023 }
1024
1025 /**
1026 * Action to update any caches relating to a recently update contact.
1027 *
1028 * I was going to call this from delete as well as from create to ensure the delete is being
1029 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1030 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1031 * where the call involved a subquery that was locking the table.
1032 *
1033 * @param int $contactID
1034 * @param bool $isTrashed
1035 */
1036 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1037
1038 if ($isTrashed) {
1039 CRM_Contact_BAO_GroupContactCache::removeContact($contactID);
1040 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1041 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1042 // but this should not cause any change as long as contacts are not being trashed outside the
1043 // main functions for that.
1044 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1045 }
1046 else {
1047 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
1048 }
1049 }
1050
1051 /**
1052 * Delete the image of a contact.
1053 *
1054 * @param int $id
1055 * Id of the contact.
1056 *
1057 * @return bool
1058 * Was contact image deleted?
1059 */
1060 public static function deleteContactImage($id) {
1061 if (!$id) {
1062 return FALSE;
1063 }
1064
1065 $contact = new self();
1066 $contact->id = $id;
1067 $contact->image_URL = 'null';
1068 $contact->save();
1069
1070 return TRUE;
1071 }
1072
1073 /**
1074 * Return proportional height and width of the image.
1075 *
1076 * @param int $imageWidth
1077 * Width of image.
1078 *
1079 * @param int $imageHeight
1080 * Height of image.
1081 *
1082 * @return array
1083 * Thumb dimension of image
1084 */
1085 public static function getThumbSize($imageWidth, $imageHeight) {
1086 $thumbWidth = 100;
1087 if ($imageWidth && $imageHeight) {
1088 $imageRatio = $imageWidth / $imageHeight;
1089 }
1090 else {
1091 $imageRatio = 1;
1092 }
1093 if ($imageRatio > 1) {
1094 $imageThumbWidth = $thumbWidth;
1095 $imageThumbHeight = round($thumbWidth / $imageRatio);
1096 }
1097 else {
1098 $imageThumbHeight = $thumbWidth;
1099 $imageThumbWidth = round($thumbWidth * $imageRatio);
1100 }
1101
1102 return array($imageThumbWidth, $imageThumbHeight);
1103 }
1104
1105 /**
1106 * Validate type of contact image.
1107 *
1108 * @param array $params
1109 * @param string $imageIndex
1110 * Index of image field.
1111 * @param string $statusMsg
1112 * Status message to be set after operation.
1113 * @param string $opType
1114 * Type of operation like fatal, bounce etc.
1115 *
1116 * @return bool
1117 * true if valid image extension
1118 */
1119 public static function processImageParams(
1120 &$params,
1121 $imageIndex = 'image_URL',
1122 $statusMsg = NULL,
1123 $opType = 'status'
1124 ) {
1125 $mimeType = array(
1126 'image/jpeg',
1127 'image/jpg',
1128 'image/png',
1129 'image/bmp',
1130 'image/p-jpeg',
1131 'image/gif',
1132 'image/x-png',
1133 );
1134
1135 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1136 $photo = basename($params[$imageIndex]['name']);
1137 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1138 return TRUE;
1139 }
1140 else {
1141 unset($params[$imageIndex]);
1142 if (!$statusMsg) {
1143 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1144 }
1145 if ($opType == 'status') {
1146 CRM_Core_Session::setStatus($statusMsg, ts('Error'), 'error');
1147 }
1148 // FIXME: additional support for fatal, bounce etc could be added.
1149 return FALSE;
1150 }
1151 }
1152
1153 /**
1154 * Extract contact id from url for deleting contact image.
1155 */
1156 public static function processImage() {
1157
1158 $action = CRM_Utils_Request::retrieve('action', 'String');
1159 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
1160 // retrieve contact id in case of Profile context
1161 $id = CRM_Utils_Request::retrieve('id', 'Positive');
1162 $cid = $cid ? $cid : $id;
1163 if ($action & CRM_Core_Action::DELETE) {
1164 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
1165 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1166 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1167 $session = CRM_Core_Session::singleton();
1168 $toUrl = $session->popUserContext();
1169 CRM_Utils_System::redirect($toUrl);
1170 }
1171 }
1172 }
1173
1174 /**
1175 * Function to set is_delete true or restore deleted contact.
1176 *
1177 * @param CRM_Contact_DAO_Contact $contact
1178 * Contact DAO object.
1179 * @param bool $restore
1180 * True to set the is_delete = 1 else false to restore deleted contact,
1181 * i.e. is_delete = 0
1182 *
1183 * @return bool
1184 */
1185 public static function contactTrashRestore($contact, $restore = FALSE) {
1186 $updateParams = array(
1187 'id' => $contact->id,
1188 'is_deleted' => $restore ? 0 : 1,
1189 );
1190
1191 CRM_Utils_Hook::pre('update', $contact->contact_type, $contact->id, $updateParams);
1192
1193 $params = array(1 => array($contact->id, 'Integer'));
1194 if (!$restore) {
1195 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1196 CRM_Core_DAO::executeQuery($query, $params);
1197 }
1198
1199 $contact->copyValues($updateParams);
1200 $contact->save();
1201 CRM_Core_BAO_Log::register($contact->id, 'civicrm_contact', $contact->id);
1202
1203 CRM_Utils_Hook::post('update', $contact->contact_type, $contact->id, $contact);
1204
1205 return TRUE;
1206 }
1207
1208 /**
1209 * Get contact type for a contact.
1210 *
1211 * @param int $id
1212 * Id of the contact whose contact type is needed.
1213 *
1214 * @return string
1215 * contact_type if $id found else null ""
1216 */
1217 public static function getContactType($id) {
1218 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1219 }
1220
1221 /**
1222 * Get contact sub type for a contact.
1223 *
1224 * @param int $id
1225 * Id of the contact whose contact sub type is needed.
1226 *
1227 * @param string $implodeDelimiter
1228 *
1229 * @return string
1230 * contact_sub_type if $id found else null ""
1231 */
1232 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1233 $subtype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1234 if (!$subtype) {
1235 return $implodeDelimiter ? NULL : array();
1236 }
1237
1238 $subtype = CRM_Utils_Array::explodePadded($subtype);
1239
1240 if ($implodeDelimiter) {
1241 $subtype = implode($implodeDelimiter, $subtype);
1242 }
1243 return $subtype;
1244 }
1245
1246 /**
1247 * Get pair of contact-type and sub-type for a contact.
1248 *
1249 * @param int $id
1250 * Id of the contact whose contact sub/contact type is needed.
1251 *
1252 * @return array
1253 */
1254 public static function getContactTypes($id) {
1255 $params = array('id' => $id);
1256 $details = array();
1257 $contact = CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact',
1258 $params,
1259 $details,
1260 array('contact_type', 'contact_sub_type')
1261 );
1262
1263 if ($contact) {
1264 $contactTypes = array();
1265 if ($contact->contact_sub_type) {
1266 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
1267 }
1268 array_unshift($contactTypes, $contact->contact_type);
1269
1270 return $contactTypes;
1271 }
1272 else {
1273 CRM_Core_Error::fatal();
1274 }
1275 }
1276
1277 /**
1278 * Combine all the importable fields from the lower levels object.
1279 *
1280 * The ordering is important, since currently we do not have a weight
1281 * scheme. Adding weight is super important
1282 *
1283 * @param int|string $contactType contact Type
1284 * @param bool $status
1285 * Status is used to manipulate first title.
1286 * @param bool $showAll
1287 * If true returns all fields (includes disabled fields).
1288 * @param bool $isProfile
1289 * If its profile mode.
1290 * @param bool $checkPermission
1291 * If false, do not include permissioning clause (for custom data).
1292 *
1293 * @param bool $withMultiCustomFields
1294 *
1295 * @return array
1296 * array of importable Fields
1297 */
1298 public static function importableFields(
1299 $contactType = 'Individual',
1300 $status = FALSE,
1301 $showAll = FALSE,
1302 $isProfile = FALSE,
1303 $checkPermission = TRUE,
1304 $withMultiCustomFields = FALSE
1305 ) {
1306 if (empty($contactType)) {
1307 $contactType = 'All';
1308 }
1309
1310 $cacheKeyString = "importableFields $contactType";
1311 $cacheKeyString .= $status ? '_1' : '_0';
1312 $cacheKeyString .= $showAll ? '_1' : '_0';
1313 $cacheKeyString .= $isProfile ? '_1' : '_0';
1314 $cacheKeyString .= $checkPermission ? '_1' : '_0';
1315
1316 $fields = CRM_Utils_Array::value($cacheKeyString, self::$_importableFields);
1317
1318 if (!$fields) {
1319 // check if we can retrieve from database cache
1320 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1321 }
1322
1323 if (!$fields) {
1324 $fields = CRM_Contact_DAO_Contact::import();
1325
1326 // get the fields thar are meant for contact types
1327 if (in_array($contactType, array(
1328 'Individual',
1329 'Household',
1330 'Organization',
1331 'All',
1332 ))) {
1333 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1334 }
1335
1336 $locationFields = array_merge(CRM_Core_DAO_Address::import(),
1337 CRM_Core_DAO_Phone::import(),
1338 CRM_Core_DAO_Email::import(),
1339 CRM_Core_DAO_IM::import(TRUE),
1340 CRM_Core_DAO_OpenID::import()
1341 );
1342
1343 $locationFields = array_merge($locationFields,
1344 CRM_Core_BAO_CustomField::getFieldsForImport('Address',
1345 FALSE,
1346 FALSE,
1347 FALSE,
1348 FALSE
1349 )
1350 );
1351
1352 foreach ($locationFields as $key => $field) {
1353 $locationFields[$key]['hasLocationType'] = TRUE;
1354 }
1355
1356 $fields = array_merge($fields, $locationFields);
1357
1358 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1359 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
1360
1361 //website fields
1362 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
1363 $fields['url']['hasWebsiteType'] = TRUE;
1364
1365 if ($contactType != 'All') {
1366 $fields = array_merge($fields,
1367 CRM_Core_BAO_CustomField::getFieldsForImport($contactType,
1368 $showAll,
1369 TRUE,
1370 FALSE,
1371 FALSE,
1372 $withMultiCustomFields
1373 )
1374 );
1375 //unset the fields, which are not related to their
1376 //contact type.
1377 $commonValues = array(
1378 'Individual' => array(
1379 'household_name',
1380 'legal_name',
1381 'sic_code',
1382 'organization_name',
1383 ),
1384 'Household' => array(
1385 'first_name',
1386 'middle_name',
1387 'last_name',
1388 'formal_title',
1389 'job_title',
1390 'gender_id',
1391 'prefix_id',
1392 'suffix_id',
1393 'birth_date',
1394 'organization_name',
1395 'legal_name',
1396 'legal_identifier',
1397 'sic_code',
1398 'home_URL',
1399 'is_deceased',
1400 'deceased_date',
1401 ),
1402 'Organization' => array(
1403 'first_name',
1404 'middle_name',
1405 'last_name',
1406 'formal_title',
1407 'job_title',
1408 'gender_id',
1409 'prefix_id',
1410 'suffix_id',
1411 'birth_date',
1412 'household_name',
1413 'is_deceased',
1414 'deceased_date',
1415 ),
1416 );
1417 foreach ($commonValues[$contactType] as $value) {
1418 unset($fields[$value]);
1419 }
1420 }
1421 else {
1422 foreach (array('Individual', 'Household', 'Organization') as $type) {
1423 $fields = array_merge($fields,
1424 CRM_Core_BAO_CustomField::getFieldsForImport($type,
1425 $showAll,
1426 FALSE,
1427 FALSE,
1428 FALSE,
1429 $withMultiCustomFields
1430 )
1431 );
1432 }
1433 }
1434
1435 if ($isProfile) {
1436 $fields = array_merge($fields, array(
1437 'group' => array(
1438 'title' => ts('Group(s)'),
1439 'name' => 'group',
1440 ),
1441 'tag' => array(
1442 'title' => ts('Tag(s)'),
1443 'name' => 'tag',
1444 ),
1445 'note' => array(
1446 'title' => ts('Note'),
1447 'name' => 'note',
1448 ),
1449 'communication_style_id' => array(
1450 'title' => ts('Communication Style'),
1451 'name' => 'communication_style_id',
1452 ),
1453 ));
1454 }
1455
1456 //Sorting fields in alphabetical order(CRM-1507)
1457 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1458
1459 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1460 }
1461
1462 self::$_importableFields[$cacheKeyString] = $fields;
1463
1464 if (!$isProfile) {
1465 if (!$status) {
1466 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1467 self::$_importableFields[$cacheKeyString]
1468 );
1469 }
1470 else {
1471 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1472 self::$_importableFields[$cacheKeyString]
1473 );
1474 }
1475 }
1476 return $fields;
1477 }
1478
1479 /**
1480 * Combine all the exportable fields from the lower levels object.
1481 *
1482 * Currently we are using importable fields as exportable fields
1483 *
1484 * @param int|string $contactType contact Type
1485 * @param bool $status
1486 * True while exporting primary contacts.
1487 * @param bool $export
1488 * True when used during export.
1489 * @param bool $search
1490 * True when used during search, might conflict with export param?.
1491 *
1492 * @param bool $withMultiRecord
1493 * @param bool $checkPermissions
1494 * @return array
1495 * array of exportable Fields
1496 */
1497 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1498 if (empty($contactType)) {
1499 $contactType = 'All';
1500 }
1501
1502 $cacheKeyString = "exportableFields $contactType";
1503 $cacheKeyString .= $export ? '_1' : '_0';
1504 $cacheKeyString .= $status ? '_1' : '_0';
1505 $cacheKeyString .= $search ? '_1' : '_0';
1506 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1507 //calculates custom fields takes into account the logged in user & caches that for all users
1508 //as an interim fix we will cache the fields by contact
1509 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1510
1511 if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
1512 if (!self::$_exportableFields) {
1513 self::$_exportableFields = array();
1514 }
1515
1516 // check if we can retrieve from database cache
1517 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1518
1519 if (!$fields) {
1520 $fields = CRM_Contact_DAO_Contact::export();
1521
1522 // The fields are meant for contact types.
1523 if (in_array($contactType, array(
1524 'Individual',
1525 'Household',
1526 'Organization',
1527 'All',
1528 ))) {
1529 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1530 }
1531 // add current employer for individuals
1532 $fields = array_merge($fields, array(
1533 'current_employer' =>
1534 array(
1535 'name' => 'organization_name',
1536 'title' => ts('Current Employer'),
1537 ),
1538 ));
1539
1540 $locationType = array(
1541 'location_type' => array(
1542 'name' => 'location_type',
1543 'where' => 'civicrm_location_type.name',
1544 'title' => ts('Location Type'),
1545 ),
1546 );
1547
1548 $IMProvider = array(
1549 'im_provider' => array(
1550 'name' => 'im_provider',
1551 'where' => 'civicrm_im.provider_id',
1552 'title' => ts('IM Provider'),
1553 ),
1554 );
1555
1556 $locationFields = array_merge($locationType,
1557 CRM_Core_DAO_Address::export(),
1558 CRM_Core_DAO_Phone::export(),
1559 CRM_Core_DAO_Email::export(),
1560 $IMProvider,
1561 CRM_Core_DAO_IM::export(TRUE),
1562 CRM_Core_DAO_OpenID::export()
1563 );
1564
1565 $locationFields = array_merge($locationFields,
1566 CRM_Core_BAO_CustomField::getFieldsForImport('Address')
1567 );
1568
1569 foreach ($locationFields as $key => $field) {
1570 $locationFields[$key]['hasLocationType'] = TRUE;
1571 }
1572
1573 $fields = array_merge($fields, $locationFields);
1574
1575 //add world region
1576 $fields = array_merge($fields,
1577 CRM_Core_DAO_Worldregion::export()
1578 );
1579
1580 $fields = array_merge($fields,
1581 CRM_Contact_DAO_Contact::export()
1582 );
1583
1584 //website fields
1585 $fields = array_merge($fields, CRM_Core_DAO_Website::export());
1586
1587 if ($contactType != 'All') {
1588 $fields = array_merge($fields,
1589 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1590 );
1591 }
1592 else {
1593 foreach (array(
1594 'Individual',
1595 'Household',
1596 'Organization',
1597 ) as $type) {
1598 $fields = array_merge($fields,
1599 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1600 );
1601 }
1602 }
1603 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1604 //fix for CRM-791
1605 if ($export) {
1606 $fields = array_merge($fields, array(
1607 'groups' => array(
1608 'title' => ts('Group(s)'),
1609 'name' => 'groups',
1610 ),
1611 'tags' => array(
1612 'title' => ts('Tag(s)'),
1613 'name' => 'tags',
1614 ),
1615 'notes' => array(
1616 'title' => ts('Note(s)'),
1617 'name' => 'notes',
1618 ),
1619 ));
1620 }
1621 else {
1622 $fields = array_merge($fields, array(
1623 'group' => array(
1624 'title' => ts('Group(s)'),
1625 'name' => 'group',
1626 ),
1627 'tag' => array(
1628 'title' => ts('Tag(s)'),
1629 'name' => 'tag',
1630 ),
1631 'note' => array(
1632 'title' => ts('Note(s)'),
1633 'name' => 'note',
1634 ),
1635 ));
1636 }
1637
1638 //Sorting fields in alphabetical order(CRM-1507)
1639 foreach ($fields as $k => $v) {
1640 $sortArray[$k] = CRM_Utils_Array::value('title', $v);
1641 }
1642
1643 $fields = array_merge($sortArray, $fields);
1644 //unset the field which are not related to their contact type.
1645 if ($contactType != 'All') {
1646 $commonValues = array(
1647 'Individual' => array(
1648 'household_name',
1649 'legal_name',
1650 'sic_code',
1651 'organization_name',
1652 'email_greeting_custom',
1653 'postal_greeting_custom',
1654 'addressee_custom',
1655 ),
1656 'Household' => array(
1657 'first_name',
1658 'middle_name',
1659 'last_name',
1660 'formal_title',
1661 'job_title',
1662 'gender_id',
1663 'prefix_id',
1664 'suffix_id',
1665 'birth_date',
1666 'organization_name',
1667 'legal_name',
1668 'legal_identifier',
1669 'sic_code',
1670 'home_URL',
1671 'is_deceased',
1672 'deceased_date',
1673 'current_employer',
1674 'email_greeting_custom',
1675 'postal_greeting_custom',
1676 'addressee_custom',
1677 'prefix_id',
1678 'suffix_id',
1679 ),
1680 'Organization' => array(
1681 'first_name',
1682 'middle_name',
1683 'last_name',
1684 'formal_title',
1685 'job_title',
1686 'gender_id',
1687 'prefix_id',
1688 'suffix_id',
1689 'birth_date',
1690 'household_name',
1691 'email_greeting_custom',
1692 'postal_greeting_custom',
1693 'prefix_id',
1694 'suffix_id',
1695 'gender_id',
1696 'addressee_custom',
1697 'is_deceased',
1698 'deceased_date',
1699 'current_employer',
1700 ),
1701 );
1702 foreach ($commonValues[$contactType] as $value) {
1703 unset($fields[$value]);
1704 }
1705 }
1706
1707 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1708 }
1709 self::$_exportableFields[$cacheKeyString] = $fields;
1710 }
1711
1712 if (!$status) {
1713 $fields = self::$_exportableFields[$cacheKeyString];
1714 }
1715 else {
1716 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1717 self::$_exportableFields[$cacheKeyString]
1718 );
1719 }
1720
1721 return $fields;
1722 }
1723
1724 /**
1725 * Get the all contact details (Hierarchical).
1726 *
1727 * @param int $contactId
1728 * Contact id.
1729 * @param array $fields
1730 * Fields array.
1731 *
1732 * @return array
1733 * Contact details
1734 */
1735 public static function getHierContactDetails($contactId, &$fields) {
1736 $params = array(array('contact_id', '=', $contactId, 0, 0));
1737 $options = array();
1738
1739 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1740
1741 // We don't know the contents of return properties, but we need the lower
1742 // level ids of the contact so add a few fields.
1743 $returnProperties['first_name'] = 1;
1744 $returnProperties['organization_name'] = 1;
1745 $returnProperties['household_name'] = 1;
1746 $returnProperties['contact_type'] = 1;
1747 $returnProperties['contact_sub_type'] = 1;
1748 return list($query, $options) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, $options);
1749 }
1750
1751 /**
1752 * Given a set of flat profile style field names, create a hierarchy.
1753 *
1754 * This is for the query to use, create the right sql.
1755 *
1756 * @param $fields
1757 * @param int $contactId
1758 * Contact id.
1759 *
1760 * @return array
1761 * A hierarchical property tree if appropriate
1762 */
1763 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1764 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1765
1766 $returnProperties = array();
1767
1768 $multipleFields = array('website' => 'url');
1769 foreach ($fields as $name => $dontCare) {
1770 if (strpos($name, '-') !== FALSE) {
1771 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
1772
1773 if (!in_array($fieldName, $multipleFields)) {
1774 if ($id == 'Primary') {
1775 $locationTypeName = 1;
1776 }
1777 else {
1778 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
1779 if (!$locationTypeName) {
1780 continue;
1781 }
1782 }
1783
1784 if (empty($returnProperties['location'])) {
1785 $returnProperties['location'] = array();
1786 }
1787 if (empty($returnProperties['location'][$locationTypeName])) {
1788 $returnProperties['location'][$locationTypeName] = array();
1789 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1790 }
1791 if (in_array($fieldName, array(
1792 'phone',
1793 'im',
1794 'email',
1795 'openid',
1796 'phone_ext',
1797 ))) {
1798 if ($type) {
1799 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1800 }
1801 else {
1802 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1803 }
1804 }
1805 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1806 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1807 }
1808 else {
1809 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1810 }
1811 }
1812 else {
1813 $returnProperties['website'][$id][$fieldName] = 1;
1814 }
1815 }
1816 else {
1817 $returnProperties[$name] = 1;
1818 }
1819 }
1820
1821 return $returnProperties;
1822 }
1823
1824 /**
1825 * Return the primary location type of a contact.
1826 *
1827 * $params int $contactId contact_id
1828 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1829 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1830 *
1831 * @param int $contactId
1832 * @param bool $skipDefaultPriamry
1833 * @param null $block
1834 *
1835 * @return int
1836 * $locationType location_type_id
1837 */
1838 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1839 if ($block) {
1840 $entityBlock = array('contact_id' => $contactId);
1841 $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
1842 foreach ($blocks[$block] as $key => $value) {
1843 if (!empty($value['is_primary'])) {
1844 $locationType = CRM_Utils_Array::value('location_type_id', $value);
1845 }
1846 }
1847 }
1848 else {
1849 $query = "
1850 SELECT
1851 IF ( civicrm_email.location_type_id IS NULL,
1852 IF ( civicrm_address.location_type_id IS NULL,
1853 IF ( civicrm_phone.location_type_id IS NULL,
1854 IF ( civicrm_im.location_type_id IS NULL,
1855 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1856 ,civicrm_im.location_type_id)
1857 ,civicrm_phone.location_type_id)
1858 ,civicrm_address.location_type_id)
1859 ,civicrm_email.location_type_id) as locationType
1860 FROM civicrm_contact
1861 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1862 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1863 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1864 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1865 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1866 WHERE civicrm_contact.id = %1 ";
1867
1868 $params = array(1 => array($contactId, 'Integer'));
1869
1870 $dao = CRM_Core_DAO::executeQuery($query, $params);
1871
1872 $locationType = NULL;
1873 if ($dao->fetch()) {
1874 $locationType = $dao->locationType;
1875 }
1876 }
1877 if (isset($locationType)) {
1878 return $locationType;
1879 }
1880 elseif ($skipDefaultPriamry) {
1881 // if there is no primary contact location then return null
1882 return NULL;
1883 }
1884 else {
1885 // if there is no primart contact location, then return default
1886 // location type of the system
1887 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1888 return $defaultLocationType->id;
1889 }
1890 }
1891
1892 /**
1893 * Get the display name, primary email and location type of a contact.
1894 *
1895 * @param int $id
1896 * Id of the contact.
1897 *
1898 * @return array
1899 * Array of display_name, email if found, do_not_email or (null,null,null)
1900 */
1901 public static function getContactDetails($id) {
1902 // check if the contact type
1903 $contactType = self::getContactType($id);
1904
1905 $nameFields = ($contactType == 'Individual') ? "civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1906
1907 $sql = "
1908 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1909 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1910 WHERE civicrm_contact.id = %1
1911 ORDER BY civicrm_email.is_primary DESC";
1912 $params = array(1 => array($id, 'Integer'));
1913 $dao = CRM_Core_DAO::executeQuery($sql, $params);
1914
1915 if ($dao->fetch()) {
1916 if ($contactType == 'Individual') {
1917 if ($dao->first_name || $dao->last_name) {
1918 $name = "{$dao->first_name} {$dao->last_name}";
1919 }
1920 else {
1921 $name = $dao->display_name;
1922 }
1923 }
1924 else {
1925 $name = $dao->display_name;
1926 }
1927 $email = $dao->email;
1928 $doNotEmail = $dao->do_not_email ? TRUE : FALSE;
1929 $onHold = $dao->on_hold ? TRUE : FALSE;
1930 $isDeceased = $dao->is_deceased ? TRUE : FALSE;
1931 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1932 }
1933 return array(NULL, NULL, NULL, NULL, NULL);
1934 }
1935
1936 /**
1937 * Add/edit/register contacts through profile.
1938 *
1939 * @param array $params
1940 * Array of profile fields to be edited/added.
1941 * @param array $fields
1942 * Array of fields from UFGroup.
1943 * @param int $contactID
1944 * Id of the contact to be edited/added.
1945 * @param int $addToGroupID
1946 * Specifies the default group to which contact is added.
1947 * @param int $ufGroupId
1948 * Uf group id (profile id).
1949 * @param string $ctype
1950 * @param bool $visibility
1951 * Basically lets us know where this request is coming from.
1952 * if via a profile from web, we restrict what groups are changed
1953 *
1954 * @return int
1955 * contact id created/edited
1956 */
1957 public static function createProfileContact(
1958 &$params,
1959 &$fields,
1960 $contactID = NULL,
1961 $addToGroupID = NULL,
1962 $ufGroupId = NULL,
1963 $ctype = NULL,
1964 $visibility = FALSE
1965 ) {
1966 // add ufGroupID to params array ( CRM-2012 )
1967 if ($ufGroupId) {
1968 $params['uf_group_id'] = $ufGroupId;
1969 }
1970 self::addBillingNameFieldsIfOtherwiseNotSet($params);
1971
1972 // If a user has logged in, or accessed via a checksum
1973 // Then deliberately 'blanking' a value in the profile should remove it from their record
1974 $session = CRM_Core_Session::singleton();
1975 $params['updateBlankLocInfo'] = TRUE;
1976 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0) {
1977 $params['updateBlankLocInfo'] = FALSE;
1978 }
1979
1980 if ($contactID) {
1981 $editHook = TRUE;
1982 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1983 }
1984 else {
1985 $editHook = FALSE;
1986 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
1987 }
1988
1989 list($data, $contactDetails) = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1990
1991 // manage is_opt_out
1992 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1993 $wasOptOut = CRM_Utils_Array::value('is_opt_out', $contactDetails, FALSE);
1994 $isOptOut = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
1995 $data['is_opt_out'] = $isOptOut;
1996 // on change, create new civicrm_subscription_history entry
1997 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1998 $shParams = array(
1999 'contact_id' => $contactDetails['contact_id'],
2000 'status' => $isOptOut ? 'Removed' : 'Added',
2001 'method' => 'Web',
2002 );
2003 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
2004 }
2005 }
2006
2007 $contact = self::create($data);
2008
2009 // contact is null if the profile does not have any contact fields
2010 if ($contact) {
2011 $contactID = $contact->id;
2012 }
2013
2014 if (empty($contactID)) {
2015 CRM_Core_Error::fatal('Cannot proceed without a valid contact id');
2016 }
2017
2018 // Process group and tag
2019 if (!empty($fields['group'])) {
2020 $method = 'Admin';
2021 // this for sure means we are coming in via profile since i added it to fix
2022 // removing contacts from user groups -- lobo
2023 if ($visibility) {
2024 $method = 'Web';
2025 }
2026 CRM_Contact_BAO_GroupContact::create($params['group'], $contactID, $visibility, $method);
2027 }
2028
2029 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2030 // Convert comma separated form values from select2 v3
2031 $tags = is_array($params['tag']) ? $params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2032 CRM_Core_BAO_EntityTag::create($tags, 'civicrm_contact', $contactID);
2033 }
2034
2035 //to add profile in default group
2036 if (is_array($addToGroupID)) {
2037 $contactIds = array($contactID);
2038 foreach ($addToGroupID as $groupId) {
2039 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
2040 }
2041 }
2042 elseif ($addToGroupID) {
2043 $contactIds = array($contactID);
2044 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
2045 }
2046
2047 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
2048
2049 if ($editHook) {
2050 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
2051 }
2052 else {
2053 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
2054 }
2055 return $contactID;
2056 }
2057
2058 /**
2059 * Format profile contact parameters.
2060 *
2061 * @param array $params
2062 * @param $fields
2063 * @param int $contactID
2064 * @param int $ufGroupId
2065 * @param null $ctype
2066 * @param bool $skipCustom
2067 *
2068 * @return array
2069 */
2070 public static function formatProfileContactParams(
2071 &$params,
2072 &$fields,
2073 $contactID = NULL,
2074 $ufGroupId = NULL,
2075 $ctype = NULL,
2076 $skipCustom = FALSE
2077 ) {
2078
2079 $data = $contactDetails = array();
2080
2081 // get the contact details (hier)
2082 if ($contactID) {
2083 list($details, $options) = self::getHierContactDetails($contactID, $fields);
2084
2085 $contactDetails = $details[$contactID];
2086 $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails);
2087 $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails);
2088 }
2089 else {
2090 //we should get contact type only if contact
2091 if ($ufGroupId) {
2092 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId);
2093
2094 //special case to handle profile with only contact fields
2095 if ($data['contact_type'] == 'Contact') {
2096 $data['contact_type'] = 'Individual';
2097 }
2098 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
2099 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
2100 }
2101 }
2102 elseif ($ctype) {
2103 $data['contact_type'] = $ctype;
2104 }
2105 else {
2106 $data['contact_type'] = 'Individual';
2107 }
2108 }
2109
2110 //fix contact sub type CRM-5125
2111 if (array_key_exists('contact_sub_type', $params) &&
2112 !empty($params['contact_sub_type'])
2113 ) {
2114 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
2115 }
2116 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2117 !empty($params['contact_sub_type_hidden'])
2118 ) {
2119 // if profile was used, and had any subtype, we obtain it from there
2120 //CRM-13596 - add to existing contact types, rather than overwriting
2121 if (empty($data['contact_sub_type'])) {
2122 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2123 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2124 }
2125 else {
2126 $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2127 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2128 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2129 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR);
2130 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2131 }
2132 }
2133 }
2134
2135 if ($ctype == 'Organization') {
2136 $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails);
2137 }
2138 elseif ($ctype == 'Household') {
2139 $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails);
2140 }
2141
2142 $locationType = array();
2143 $count = 1;
2144
2145 if ($contactID) {
2146 //add contact id
2147 $data['contact_id'] = $contactID;
2148 $primaryLocationType = self::getPrimaryLocationType($contactID);
2149 }
2150 else {
2151 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2152 $defaultLocationId = $defaultLocation->id;
2153 }
2154
2155 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
2156
2157 $blocks = array('email', 'phone', 'im', 'openid');
2158
2159 $multiplFields = array('url');
2160 // prevent overwritten of formatted array, reset all block from
2161 // params if it is not in valid format (since import pass valid format)
2162 foreach ($blocks as $blk) {
2163 if (array_key_exists($blk, $params) &&
2164 !is_array($params[$blk])
2165 ) {
2166 unset($params[$blk]);
2167 }
2168 }
2169
2170 $primaryPhoneLoc = NULL;
2171 $session = CRM_Core_Session::singleton();
2172 foreach ($params as $key => $value) {
2173 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3);
2174
2175 if ($locTypeId == 'Primary') {
2176 if ($contactID) {
2177 if (in_array($fieldName, $blocks)) {
2178 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2179 }
2180 else {
2181 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2182 }
2183 $primaryLocationType = $locTypeId;
2184 }
2185 else {
2186 $locTypeId = $defaultLocationId;
2187 }
2188 }
2189
2190 if (is_numeric($locTypeId) &&
2191 !in_array($fieldName, $multiplFields) &&
2192 substr($fieldName, 0, 7) != 'custom_'
2193 ) {
2194 $index = $locTypeId;
2195
2196 if (is_numeric($typeId)) {
2197 $index .= '-' . $typeId;
2198 }
2199 if (!in_array($index, $locationType)) {
2200 $locationType[$count] = $index;
2201 $count++;
2202 }
2203
2204 $loc = CRM_Utils_Array::key($index, $locationType);
2205
2206 $blockName = self::getLocationEntityForKey($fieldName);
2207
2208 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2209
2210 //set is_billing true, for location type "Billing"
2211 if ($locTypeId == $billingLocationTypeId) {
2212 $data[$blockName][$loc]['is_billing'] = 1;
2213 }
2214
2215 if ($contactID) {
2216 //get the primary location type
2217 if ($locTypeId == $primaryLocationType) {
2218 $data[$blockName][$loc]['is_primary'] = 1;
2219 }
2220 }
2221 elseif ($locTypeId == $defaultLocationId) {
2222 $data[$blockName][$loc]['is_primary'] = 1;
2223 }
2224
2225 if (in_array($fieldName, array('phone'))) {
2226 if ($typeId) {
2227 $data['phone'][$loc]['phone_type_id'] = $typeId;
2228 }
2229 else {
2230 $data['phone'][$loc]['phone_type_id'] = '';
2231 }
2232 $data['phone'][$loc]['phone'] = $value;
2233
2234 //special case to handle primary phone with different phone types
2235 // in this case we make first phone type as primary
2236 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2237 $primaryPhoneLoc = $loc;
2238 }
2239
2240 if ($loc != $primaryPhoneLoc) {
2241 unset($data['phone'][$loc]['is_primary']);
2242 }
2243 }
2244 elseif ($fieldName == 'email') {
2245 $data['email'][$loc]['email'] = $value;
2246 if (empty($contactID)) {
2247 $data['email'][$loc]['is_primary'] = 1;
2248 }
2249 }
2250 elseif ($fieldName == 'im') {
2251 if (isset($params[$key . '-provider_id'])) {
2252 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2253 }
2254 if (strpos($key, '-provider_id') !== FALSE) {
2255 $data['im'][$loc]['provider_id'] = $params[$key];
2256 }
2257 else {
2258 $data['im'][$loc]['name'] = $value;
2259 }
2260 }
2261 elseif ($fieldName == 'openid') {
2262 $data['openid'][$loc]['openid'] = $value;
2263 }
2264 else {
2265 if ($fieldName === 'state_province') {
2266 // CRM-3393
2267 if (is_numeric($value) && ((int ) $value) >= 1000) {
2268 $data['address'][$loc]['state_province_id'] = $value;
2269 }
2270 elseif (empty($value)) {
2271 $data['address'][$loc]['state_province_id'] = '';
2272 }
2273 else {
2274 $data['address'][$loc]['state_province'] = $value;
2275 }
2276 }
2277 elseif ($fieldName === 'country') {
2278 // CRM-3393
2279 if (is_numeric($value) && ((int ) $value) >= 1000
2280 ) {
2281 $data['address'][$loc]['country_id'] = $value;
2282 }
2283 elseif (empty($value)) {
2284 $data['address'][$loc]['country_id'] = '';
2285 }
2286 else {
2287 $data['address'][$loc]['country'] = $value;
2288 }
2289 }
2290 elseif ($fieldName === 'county') {
2291 $data['address'][$loc]['county_id'] = $value;
2292 }
2293 elseif ($fieldName == 'address_name') {
2294 $data['address'][$loc]['name'] = $value;
2295 }
2296 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2297 $data['address'][$loc][substr($fieldName, 8)] = $value;
2298 }
2299 else {
2300 $data[$blockName][$loc][$fieldName] = $value;
2301 }
2302 }
2303 }
2304 else {
2305 if (substr($key, 0, 4) === 'url-') {
2306 $websiteField = explode('-', $key);
2307 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2308 $data['website'][$websiteField[1]]['url'] = $value;
2309 }
2310 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
2311 //save email/postal greeting and addressee values if any, CRM-4575
2312 $data[$key . '_id'] = $value;
2313 }
2314 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2315 // for autocomplete transfer hidden value instead of label
2316 if ($params[$key] && isset($params[$key . '_id'])) {
2317 $value = $params[$key . '_id'];
2318 }
2319
2320 // we need to append time with date
2321 if ($params[$key] && isset($params[$key . '_time'])) {
2322 $value .= ' ' . $params[$key . '_time'];
2323 }
2324
2325 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2326 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
2327 ($value == '' || !isset($value))
2328 ) {
2329 continue;
2330 }
2331
2332 $valueId = NULL;
2333 if (!empty($params['customRecordValues'])) {
2334 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2335 foreach ($params['customRecordValues'] as $recId => $customFields) {
2336 if (is_array($customFields) && !empty($customFields)) {
2337 foreach ($customFields as $customFieldName) {
2338 if ($customFieldName == $key) {
2339 $valueId = $recId;
2340 break;
2341 }
2342 }
2343 }
2344 }
2345 }
2346 }
2347
2348 //CRM-13596 - check for contact_sub_type_hidden first
2349 if (array_key_exists('contact_sub_type_hidden', $params)) {
2350 $type = $params['contact_sub_type_hidden'];
2351 }
2352 else {
2353 $type = $data['contact_type'];
2354 if (!empty($data['contact_sub_type'])) {
2355 $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2356 }
2357 }
2358
2359 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2360 $data['custom'],
2361 $value,
2362 $type,
2363 $valueId,
2364 $contactID,
2365 FALSE,
2366 FALSE
2367 );
2368 }
2369 elseif ($key == 'edit') {
2370 continue;
2371 }
2372 else {
2373 if ($key == 'location') {
2374 foreach ($value as $locationTypeId => $field) {
2375 foreach ($field as $block => $val) {
2376 if ($block == 'address' && array_key_exists('address_name', $val)) {
2377 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2378 }
2379 }
2380 }
2381 }
2382 if ($key == 'phone' && isset($params['phone_ext'])) {
2383 $data[$key] = $value;
2384 foreach ($value as $cnt => $phoneBlock) {
2385 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2386 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2387 }
2388 }
2389 }
2390 elseif (in_array($key, array(
2391 'nick_name',
2392 'job_title',
2393 'middle_name',
2394 'birth_date',
2395 'gender_id',
2396 'current_employer',
2397 'prefix_id',
2398 'suffix_id',
2399 )) && ($value == '' || !isset($value)) &&
2400 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2401 ($key == 'current_employer' && empty($params['current_employer']))) {
2402 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2403 // to avoid update with empty values
2404 continue;
2405 }
2406 else {
2407 $data[$key] = $value;
2408 }
2409 }
2410 }
2411 }
2412
2413 if (!isset($data['contact_type'])) {
2414 $data['contact_type'] = 'Individual';
2415 }
2416
2417 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2418 $privacy = CRM_Core_SelectValues::privacy();
2419 foreach ($privacy as $key => $value) {
2420 if (array_key_exists($key, $fields)) {
2421 // do not reset values for existing contacts, if fields are added to a profile
2422 if (array_key_exists($key, $params)) {
2423 $data[$key] = $params[$key];
2424 if (empty($params[$key])) {
2425 $data[$key] = 0;
2426 }
2427 }
2428 elseif (!$contactID) {
2429 $data[$key] = 0;
2430 }
2431 }
2432 }
2433
2434 return array($data, $contactDetails);
2435 }
2436
2437 /**
2438 * Find the get contact details.
2439 *
2440 * This function does not respect ACLs for now, which might need to be rectified at some
2441 * stage based on how its used.
2442 *
2443 * @param string $mail
2444 * Primary email address of the contact.
2445 * @param string $ctype
2446 * Contact type.
2447 *
2448 * @return object|null
2449 * $dao contact details
2450 */
2451 public static function matchContactOnEmail($mail, $ctype = NULL) {
2452 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2453 $mail = $strtolower(trim($mail));
2454 $query = "
2455 SELECT civicrm_contact.id as contact_id,
2456 civicrm_contact.hash as hash,
2457 civicrm_contact.contact_type as contact_type,
2458 civicrm_contact.contact_sub_type as contact_sub_type
2459 FROM civicrm_contact
2460 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2461
2462 if (Civi::settings()->get('uniq_email_per_site')) {
2463 // try to find a match within a site (multisite).
2464 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2465 if (!empty($groups)) {
2466 $query .= "
2467 INNER JOIN civicrm_group_contact gc ON
2468 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2469 }
2470 }
2471
2472 $query .= "
2473 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2474 $p = array(1 => array($mail, 'String'));
2475
2476 if ($ctype) {
2477 $query .= " AND civicrm_contact.contact_type = %3";
2478 $p[3] = array($ctype, 'String');
2479 }
2480
2481 $query .= " ORDER BY civicrm_email.is_primary DESC";
2482
2483 $dao = CRM_Core_DAO::executeQuery($query, $p);
2484
2485 if ($dao->fetch()) {
2486 return $dao;
2487 }
2488 return NULL;
2489 }
2490
2491 /**
2492 * Find the contact details associated with an OpenID.
2493 *
2494 * @param string $openId
2495 * OpenId of the contact.
2496 * @param string $ctype
2497 * Contact type.
2498 *
2499 * @return object|null
2500 * $dao contact details
2501 */
2502 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2503 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2504 $openId = $strtolower(trim($openId));
2505 $query = "
2506 SELECT civicrm_contact.id as contact_id,
2507 civicrm_contact.hash as hash,
2508 civicrm_contact.contact_type as contact_type,
2509 civicrm_contact.contact_sub_type as contact_sub_type
2510 FROM civicrm_contact
2511 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2512 WHERE civicrm_openid.openid = %1";
2513 $p = array(1 => array($openId, 'String'));
2514
2515 if ($ctype) {
2516 $query .= " AND civicrm_contact.contact_type = %3";
2517 $p[3] = array($ctype, 'String');
2518 }
2519
2520 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2521
2522 $dao = CRM_Core_DAO::executeQuery($query, $p);
2523
2524 if ($dao->fetch()) {
2525 return $dao;
2526 }
2527 return NULL;
2528 }
2529
2530 /**
2531 * Get primary email of the contact.
2532 *
2533 * @param int $contactID
2534 * Contact id.
2535 *
2536 * @return string
2537 * Email address if present else null
2538 */
2539 public static function getPrimaryEmail($contactID) {
2540 // fetch the primary email
2541 $query = "
2542 SELECT civicrm_email.email as email
2543 FROM civicrm_contact
2544 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2545 WHERE civicrm_email.is_primary = 1
2546 AND civicrm_contact.id = %1";
2547 $p = array(1 => array($contactID, 'Integer'));
2548 $dao = CRM_Core_DAO::executeQuery($query, $p);
2549
2550 $email = NULL;
2551 if ($dao->fetch()) {
2552 $email = $dao->email;
2553 }
2554 return $email;
2555 }
2556
2557 /**
2558 * Function to get primary OpenID of the contact.
2559 *
2560 * @param int $contactID
2561 * Contact id.
2562 *
2563 * @return string
2564 * >openid OpenID if present else null
2565 */
2566 public static function getPrimaryOpenId($contactID) {
2567 // fetch the primary OpenID
2568 $query = "
2569 SELECT civicrm_openid.openid as openid
2570 FROM civicrm_contact
2571 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2572 WHERE civicrm_contact.id = %1
2573 AND civicrm_openid.is_primary = 1";
2574 $p = array(1 => array($contactID, 'Integer'));
2575 $dao = CRM_Core_DAO::executeQuery($query, $p);
2576
2577 $openId = NULL;
2578 if ($dao->fetch()) {
2579 $openId = $dao->openid;
2580 }
2581 return $openId;
2582 }
2583
2584 /**
2585 * Fetch the object and store the values in the values array.
2586 *
2587 * @param array $params
2588 * Input parameters to find object.
2589 * @param array $values
2590 * Output values of the object.
2591 *
2592 * @return CRM_Contact_BAO_Contact|null
2593 * The found object or null
2594 */
2595 public static function getValues(&$params, &$values) {
2596 $contact = new CRM_Contact_BAO_Contact();
2597
2598 $contact->copyValues($params);
2599
2600 if ($contact->find(TRUE)) {
2601
2602 CRM_Core_DAO::storeValues($contact, $values);
2603
2604 $privacy = array();
2605 foreach (self::$_commPrefs as $name) {
2606 if (isset($contact->$name)) {
2607 $privacy[$name] = $contact->$name;
2608 }
2609 }
2610
2611 if (!empty($privacy)) {
2612 $values['privacy'] = $privacy;
2613 }
2614
2615 // communication Prefferance
2616 $preffComm = $comm = array();
2617 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2618 $contact->preferred_communication_method
2619 );
2620 foreach ($comm as $value) {
2621 $preffComm[$value] = 1;
2622 }
2623 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2624
2625 $names = array(
2626 'preferred_communication_method' => array(
2627 'newName' => 'preferred_communication_method_display',
2628 'groupName' => 'preferred_communication_method',
2629 ),
2630 );
2631
2632 // @todo This can be figured out from metadata & we can avoid the uncached query.
2633 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2634
2635 $values['preferred_communication_method'] = $preffComm;
2636 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2637
2638 if ($contact->preferred_mail_format) {
2639 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2640 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2641 }
2642
2643 // get preferred languages
2644 if (!empty($contact->preferred_language)) {
2645 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2646 }
2647
2648 // Calculating Year difference
2649 if ($contact->birth_date) {
2650 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2651 if ($birthDate < date('Ymd')) {
2652 $age = CRM_Utils_Date::calculateAge($birthDate);
2653 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2654 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2655 }
2656 }
2657
2658 $contact->contact_id = $contact->id;
2659
2660 return $contact;
2661 }
2662 return NULL;
2663 }
2664
2665 /**
2666 * Given the component name and returns the count of participation of contact.
2667 *
2668 * @param string $component
2669 * Input component name.
2670 * @param int $contactId
2671 * Input contact id.
2672 * @param string $tableName
2673 * Optional tableName if component is custom group.
2674 *
2675 * @return int
2676 * total number in database
2677 */
2678 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2679 $object = NULL;
2680 switch ($component) {
2681 case 'tag':
2682 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2683
2684 case 'rel':
2685 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2686 CRM_Contact_BAO_Relationship::CURRENT,
2687 0, 1, 0,
2688 NULL, NULL,
2689 TRUE
2690 );
2691 return $result;
2692
2693 case 'group':
2694
2695 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2696
2697 case 'log':
2698 if (CRM_Core_BAO_Log::useLoggingReport()) {
2699 return FALSE;
2700 }
2701 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2702
2703 case 'note':
2704 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2705
2706 case 'contribution':
2707 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2708
2709 case 'membership':
2710 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2711
2712 case 'participant':
2713 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2714
2715 case 'pledge':
2716 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2717
2718 case 'case':
2719 return CRM_Case_BAO_Case::caseCount($contactId);
2720
2721 case 'grant':
2722 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2723
2724 case 'activity':
2725 $input = array(
2726 'contact_id' => $contactId,
2727 'admin' => FALSE,
2728 'caseId' => NULL,
2729 'context' => 'activity',
2730 );
2731 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2732
2733 case 'mailing':
2734 $params = array('contact_id' => $contactId);
2735 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2736
2737 default:
2738 $custom = explode('_', $component);
2739 if ($custom['0'] = 'custom') {
2740 if (!$tableName) {
2741 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2742 }
2743 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2744 return CRM_Core_DAO::singleValueQuery($queryString);
2745 }
2746 }
2747 }
2748
2749 /**
2750 * Update contact greetings if an update has resulted in a custom field change.
2751 *
2752 * @param array $updatedFields
2753 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2754 * @param array $contactParams
2755 * Parameters known about the contact. At minimum array('contact_id' => x).
2756 * Fields in this array will take precedence over DB fields (so far only
2757 * in the case of greeting id fields).
2758 */
2759 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2760 $contactID = $contactParams['contact_id'];
2761 CRM_Contact_BAO_Contact::ensureGreetingParamsAreSet($contactParams);
2762 $tokens = CRM_Contact_BAO_Contact_Utils::getTokensRequiredForContactGreetings($contactParams);
2763 if (!empty($tokens['all']['contact'])) {
2764 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2765 if (!empty($affectedTokens)) {
2766 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2767 $contact = new CRM_Contact_BAO_Contact();
2768 $contact->id = $contactID;
2769 CRM_Contact_BAO_Contact::processGreetings($contact);
2770 }
2771 }
2772 }
2773
2774 /**
2775 * Process greetings and cache.
2776 *
2777 * @param object $contact
2778 * Contact object after save.
2779 */
2780 public static function processGreetings(&$contact) {
2781
2782 //@todo this function does a lot of unnecessary loading.
2783 // ensureGreetingParamsAreSet now makes sure that the contact is
2784 // loaded and using updateGreetingsOnTokenFieldChange
2785 // allows us the possibility of only doing an update if required.
2786
2787 // The contact object has not always required the
2788 // fields that are required to calculate greetings
2789 // so we need to retrieve it again.
2790 if ($contact->_query !== FALSE) {
2791 $contact->find(TRUE);
2792 }
2793
2794 // store object values to an array
2795 $contactDetails = array();
2796 CRM_Core_DAO::storeValues($contact, $contactDetails);
2797 $contactDetails = array(array($contact->id => $contactDetails));
2798
2799 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2800 $updateQueryString = array();
2801
2802 //cache email and postal greeting to greeting display
2803 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2804 $emailGreetingString = $contact->email_greeting_custom;
2805 }
2806 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2807 // the filter value for Individual contact type is set to 1
2808 $filter = array(
2809 'contact_type' => $contact->contact_type,
2810 'greeting_type' => 'email_greeting',
2811 );
2812
2813 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2814 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2815 $updateQueryString[] = " email_greeting_custom = NULL ";
2816 }
2817 else {
2818 if ($contact->email_greeting_custom) {
2819 $updateQueryString[] = " email_greeting_display = NULL ";
2820 }
2821 }
2822
2823 if ($emailGreetingString) {
2824 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2825 $contactDetails,
2826 $contact->id,
2827 'CRM_Contact_BAO_Contact'
2828 );
2829 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2830 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2831 }
2832
2833 //postal greetings
2834 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2835 $postalGreetingString = $contact->postal_greeting_custom;
2836 }
2837 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2838 $filter = array(
2839 'contact_type' => $contact->contact_type,
2840 'greeting_type' => 'postal_greeting',
2841 );
2842 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2843 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2844 $updateQueryString[] = " postal_greeting_custom = NULL ";
2845 }
2846 else {
2847 if ($contact->postal_greeting_custom) {
2848 $updateQueryString[] = " postal_greeting_display = NULL ";
2849 }
2850 }
2851
2852 if ($postalGreetingString) {
2853 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2854 $contactDetails,
2855 $contact->id,
2856 'CRM_Contact_BAO_Contact'
2857 );
2858 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2859 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2860 }
2861
2862 // addressee
2863 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2864 $addresseeString = $contact->addressee_custom;
2865 }
2866 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2867 $filter = array(
2868 'contact_type' => $contact->contact_type,
2869 'greeting_type' => 'addressee',
2870 );
2871
2872 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2873 $addresseeString = $addressee[$contact->addressee_id];
2874 $updateQueryString[] = " addressee_custom = NULL ";
2875 }
2876 else {
2877 if ($contact->addressee_custom) {
2878 $updateQueryString[] = " addressee_display = NULL ";
2879 }
2880 }
2881
2882 if ($addresseeString) {
2883 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2884 $contactDetails,
2885 $contact->id,
2886 'CRM_Contact_BAO_Contact'
2887 );
2888 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2889 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2890 }
2891
2892 if (!empty($updateQueryString)) {
2893 $updateQueryString = implode(',', $updateQueryString);
2894 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2895 CRM_Core_DAO::executeQuery($queryString);
2896 }
2897 }
2898
2899 /**
2900 * Retrieve loc block ids w/ given condition.
2901 *
2902 * @param int $contactId
2903 * Contact id.
2904 * @param array $criteria
2905 * Key => value pair which should be.
2906 * fulfill by return record ids.
2907 * @param string $condOperator
2908 * Operator use for grouping multiple conditions.
2909 *
2910 * @return array
2911 * loc block ids which fulfill condition.
2912 */
2913 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2914 $locBlockIds = array();
2915 if (!$contactId) {
2916 return $locBlockIds;
2917 }
2918
2919 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2920 $name = strtolower($block);
2921 $className = "CRM_Core_DAO_$block";
2922 $blockDAO = new $className();
2923
2924 // build the condition.
2925 if (is_array($criteria)) {
2926 $fields = $blockDAO->fields();
2927 $conditions = array();
2928 foreach ($criteria as $field => $value) {
2929 if (array_key_exists($field, $fields)) {
2930 $cond = "( $field = $value )";
2931 // value might be zero or null.
2932 if (!$value || strtolower($value) == 'null') {
2933 $cond = "( $field = 0 OR $field IS NULL )";
2934 }
2935 $conditions[] = $cond;
2936 }
2937 }
2938 if (!empty($conditions)) {
2939 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2940 }
2941 }
2942
2943 $blockDAO->contact_id = $contactId;
2944 $blockDAO->find();
2945 while ($blockDAO->fetch()) {
2946 $locBlockIds[$name][] = $blockDAO->id;
2947 }
2948 }
2949
2950 return $locBlockIds;
2951 }
2952
2953 /**
2954 * Build context menu items.
2955 *
2956 * @param int $contactId
2957 *
2958 * @return array
2959 * Array of context menu for logged in user.
2960 */
2961 public static function contextMenu($contactId = NULL) {
2962 $menu = array(
2963 'view' => array(
2964 'title' => ts('View Contact'),
2965 'weight' => 0,
2966 'ref' => 'view-contact',
2967 'class' => 'no-popup',
2968 'key' => 'view',
2969 'permissions' => array('view all contacts'),
2970 ),
2971 'add' => array(
2972 'title' => ts('Edit Contact'),
2973 'weight' => 0,
2974 'ref' => 'edit-contact',
2975 'class' => 'no-popup',
2976 'key' => 'add',
2977 'permissions' => array('edit all contacts'),
2978 ),
2979 'delete' => array(
2980 'title' => ts('Delete Contact'),
2981 'weight' => 0,
2982 'ref' => 'delete-contact',
2983 'key' => 'delete',
2984 'permissions' => array('access deleted contacts', 'delete contacts'),
2985 ),
2986 'contribution' => array(
2987 'title' => ts('Add Contribution'),
2988 'weight' => 5,
2989 'ref' => 'new-contribution',
2990 'key' => 'contribution',
2991 'tab' => 'contribute',
2992 'component' => 'CiviContribute',
2993 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2994 'reset=1&action=add&context=contribution'
2995 ),
2996 'permissions' => array(
2997 'access CiviContribute',
2998 'edit contributions',
2999 ),
3000 ),
3001 'participant' => array(
3002 'title' => ts('Register for Event'),
3003 'weight' => 10,
3004 'ref' => 'new-participant',
3005 'key' => 'participant',
3006 'tab' => 'participant',
3007 'component' => 'CiviEvent',
3008 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3009 'permissions' => array(
3010 'access CiviEvent',
3011 'edit event participants',
3012 ),
3013 ),
3014 'activity' => array(
3015 'title' => ts('Record Activity'),
3016 'weight' => 35,
3017 'ref' => 'new-activity',
3018 'key' => 'activity',
3019 'permissions' => array('edit all contacts'),
3020 ),
3021 'pledge' => array(
3022 'title' => ts('Add Pledge'),
3023 'weight' => 15,
3024 'ref' => 'new-pledge',
3025 'key' => 'pledge',
3026 'tab' => 'pledge',
3027 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
3028 'reset=1&action=add&context=pledge'
3029 ),
3030 'component' => 'CiviPledge',
3031 'permissions' => array(
3032 'access CiviPledge',
3033 'edit pledges',
3034 ),
3035 ),
3036 'membership' => array(
3037 'title' => ts('Add Membership'),
3038 'weight' => 20,
3039 'ref' => 'new-membership',
3040 'key' => 'membership',
3041 'tab' => 'member',
3042 'component' => 'CiviMember',
3043 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
3044 'reset=1&action=add&context=membership'
3045 ),
3046 'permissions' => array(
3047 'access CiviMember',
3048 'edit memberships',
3049 ),
3050 ),
3051 'case' => array(
3052 'title' => ts('Add Case'),
3053 'weight' => 25,
3054 'ref' => 'new-case',
3055 'key' => 'case',
3056 'tab' => 'case',
3057 'component' => 'CiviCase',
3058 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3059 'permissions' => array('add cases'),
3060 ),
3061 'grant' => array(
3062 'title' => ts('Add Grant'),
3063 'weight' => 26,
3064 'ref' => 'new-grant',
3065 'key' => 'grant',
3066 'tab' => 'grant',
3067 'component' => 'CiviGrant',
3068 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
3069 'reset=1&action=add&context=grant'
3070 ),
3071 'permissions' => array('edit grants'),
3072 ),
3073 'rel' => array(
3074 'title' => ts('Add Relationship'),
3075 'weight' => 30,
3076 'ref' => 'new-relationship',
3077 'key' => 'rel',
3078 'tab' => 'rel',
3079 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
3080 'reset=1&action=add'
3081 ),
3082 'permissions' => array('edit all contacts'),
3083 ),
3084 'note' => array(
3085 'title' => ts('Add Note'),
3086 'weight' => 40,
3087 'ref' => 'new-note',
3088 'key' => 'note',
3089 'tab' => 'note',
3090 'class' => 'medium-popup',
3091 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
3092 'reset=1&action=add'
3093 ),
3094 'permissions' => array('edit all contacts'),
3095 ),
3096 'email' => array(
3097 'title' => ts('Send an Email'),
3098 'weight' => 45,
3099 'ref' => 'new-email',
3100 'key' => 'email',
3101 'permissions' => array('view all contacts'),
3102 ),
3103 'group' => array(
3104 'title' => ts('Add to Group'),
3105 'weight' => 50,
3106 'ref' => 'group-add-contact',
3107 'key' => 'group',
3108 'tab' => 'group',
3109 'permissions' => array('edit groups'),
3110 ),
3111 'tag' => array(
3112 'title' => ts('Tag Contact'),
3113 'weight' => 55,
3114 'ref' => 'tag-contact',
3115 'key' => 'tag',
3116 'tab' => 'tag',
3117 'permissions' => array('edit all contacts'),
3118 ),
3119 );
3120
3121 $menu['otherActions'] = array(
3122 'print' => array(
3123 'title' => ts('Print Summary'),
3124 'description' => ts('Printer-friendly view of this page.'),
3125 'weight' => 5,
3126 'ref' => 'crm-contact-print',
3127 'key' => 'print',
3128 'tab' => 'print',
3129 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3130 "reset=1&print=1"
3131 ),
3132 'class' => 'print',
3133 'icon' => 'crm-i fa-print',
3134 ),
3135 'vcard' => array(
3136 'title' => ts('vCard'),
3137 'description' => ts('vCard record for this contact.'),
3138 'weight' => 10,
3139 'ref' => 'crm-contact-vcard',
3140 'key' => 'vcard',
3141 'tab' => 'vcard',
3142 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3143 "reset=1"
3144 ),
3145 'class' => 'vcard',
3146 'icon' => 'crm-i fa-list-alt',
3147 ),
3148 );
3149
3150 if (CRM_Core_Permission::check('access Contact Dashboard')) {
3151 $menu['otherActions']['dashboard'] = array(
3152 'title' => ts('Contact Dashboard'),
3153 'description' => ts('Contact Dashboard'),
3154 'weight' => 15,
3155 'ref' => 'crm-contact-dashboard',
3156 'key' => 'dashboard',
3157 'tab' => 'dashboard',
3158 'class' => 'dashboard',
3159 // NOTE: As an alternative you can also build url on CMS specific way
3160 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3161 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id={$contactId}"),
3162 'icon' => 'crm-i fa-tachometer',
3163 );
3164 }
3165
3166 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3167 if ($uid) {
3168 $menu['otherActions']['user-record'] = array(
3169 'title' => ts('User Record'),
3170 'description' => ts('User Record'),
3171 'weight' => 20,
3172 'ref' => 'crm-contact-user-record',
3173 'key' => 'user-record',
3174 'tab' => 'user-record',
3175 'class' => 'user-record',
3176 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
3177 'icon' => 'crm-i fa-user',
3178 );
3179 }
3180 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
3181 $menu['otherActions']['user-add'] = array(
3182 'title' => ts('Create User Record'),
3183 'description' => ts('Create User Record'),
3184 'weight' => 25,
3185 'ref' => 'crm-contact-user-add',
3186 'key' => 'user-add',
3187 'tab' => 'user-add',
3188 'class' => 'user-add',
3189 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3190 'icon' => 'crm-i fa-user-plus',
3191 );
3192 }
3193
3194 CRM_Utils_Hook::summaryActions($menu, $contactId);
3195 //1. check for component is active.
3196 //2. check for user permissions.
3197 //3. check for acls.
3198 //3. edit and view contact are directly accessible to user.
3199
3200 $aclPermissionedTasks = array(
3201 'view-contact',
3202 'edit-contact',
3203 'new-activity',
3204 'new-email',
3205 'group-add-contact',
3206 'tag-contact',
3207 'delete-contact',
3208 );
3209 $corePermission = CRM_Core_Permission::getPermission();
3210
3211 $contextMenu = array();
3212 foreach ($menu as $key => $values) {
3213 if ($key != 'otherActions') {
3214
3215 // user does not have necessary permissions.
3216 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3217 continue;
3218 }
3219 // build directly accessible action menu.
3220 if (in_array($values['ref'], array(
3221 'view-contact',
3222 'edit-contact',
3223 ))) {
3224 $contextMenu['primaryActions'][$key] = array(
3225 'title' => $values['title'],
3226 'ref' => $values['ref'],
3227 'class' => CRM_Utils_Array::value('class', $values),
3228 'key' => $values['key'],
3229 );
3230 continue;
3231 }
3232
3233 // finally get menu item for -more- action widget.
3234 $contextMenu['moreActions'][$values['weight']] = array(
3235 'title' => $values['title'],
3236 'ref' => $values['ref'],
3237 'href' => CRM_Utils_Array::value('href', $values),
3238 'tab' => CRM_Utils_Array::value('tab', $values),
3239 'class' => CRM_Utils_Array::value('class', $values),
3240 'key' => $values['key'],
3241 );
3242 }
3243 else {
3244 foreach ($values as $value) {
3245 // user does not have necessary permissions.
3246 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3247 continue;
3248 }
3249
3250 // finally get menu item for -more- action widget.
3251 $contextMenu['otherActions'][$value['weight']] = array(
3252 'title' => $value['title'],
3253 'ref' => $value['ref'],
3254 'href' => CRM_Utils_Array::value('href', $value),
3255 'tab' => CRM_Utils_Array::value('tab', $value),
3256 'class' => CRM_Utils_Array::value('class', $value),
3257 'icon' => CRM_Utils_Array::value('icon', $value),
3258 'key' => $value['key'],
3259 );
3260 }
3261 }
3262 }
3263
3264 ksort($contextMenu['moreActions']);
3265 ksort($contextMenu['otherActions']);
3266
3267 return $contextMenu;
3268 }
3269
3270 /**
3271 * Check if user has permissions to access items in action menu.
3272 *
3273 * @param array $aclPermissionedTasks
3274 * Array containing ACL related tasks.
3275 * @param string $corePermission
3276 * The permission of the user (edit or view or null).
3277 * @param array $menuOptions
3278 * Array containing params of the menu (title, href, etc).
3279 *
3280 * @return bool
3281 * TRUE if user has all permissions, FALSE if otherwise.
3282 */
3283 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3284 $componentName = CRM_Utils_Array::value('component', $menuOptions);
3285
3286 // if component action - make sure component is enable.
3287 if ($componentName && !in_array($componentName, CRM_Core_Config::singleton()->enableComponents)) {
3288 return FALSE;
3289 }
3290
3291 // make sure user has all required permissions.
3292 $hasAllPermissions = FALSE;
3293
3294 $permissions = CRM_Utils_Array::value('permissions', $menuOptions);
3295 if (!is_array($permissions) || empty($permissions)) {
3296 $hasAllPermissions = TRUE;
3297 }
3298
3299 // iterate for required permissions in given permissions array.
3300 if (!$hasAllPermissions) {
3301 $hasPermissions = 0;
3302 foreach ($permissions as $permission) {
3303 if (CRM_Core_Permission::check($permission)) {
3304 $hasPermissions++;
3305 }
3306 }
3307
3308 if (count($permissions) == $hasPermissions) {
3309 $hasAllPermissions = TRUE;
3310 }
3311
3312 // if still user does not have required permissions, check acl.
3313 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3314 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3315 $corePermission == CRM_Core_Permission::EDIT
3316 ) {
3317 $hasAllPermissions = TRUE;
3318 }
3319 elseif (in_array($menuOptions['ref'], array(
3320 'new-email',
3321 ))) {
3322 // grant permissions for these tasks.
3323 $hasAllPermissions = TRUE;
3324 }
3325 }
3326 }
3327
3328 return $hasAllPermissions;
3329 }
3330
3331 /**
3332 * Retrieve display name of contact that address is shared.
3333 *
3334 * This is based on $masterAddressId or $contactId .
3335 *
3336 * @param int $masterAddressId
3337 * Master id.
3338 * @param int $contactId
3339 * Contact id. (deprecated - do not use)
3340 *
3341 * @return string|null
3342 * the found display name or null.
3343 */
3344 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3345 $masterDisplayName = NULL;
3346 if (!$masterAddressId) {
3347 return $masterDisplayName;
3348 }
3349
3350 $sql = "
3351 SELECT display_name from civicrm_contact
3352 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3353 WHERE civicrm_address.id = " . $masterAddressId;
3354
3355 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3356 return $masterDisplayName;
3357 }
3358
3359 /**
3360 * Get the creation/modification times for a contact.
3361 *
3362 * @param int $contactId
3363 *
3364 * @return array
3365 * Dates - ('created_date' => $, 'modified_date' => $)
3366 */
3367 public static function getTimestamps($contactId) {
3368 $timestamps = CRM_Core_DAO::executeQuery(
3369 'SELECT created_date, modified_date
3370 FROM civicrm_contact
3371 WHERE id = %1',
3372 array(
3373 1 => array($contactId, 'Integer'),
3374 )
3375 );
3376 if ($timestamps->fetch()) {
3377 return array(
3378 'created_date' => $timestamps->created_date,
3379 'modified_date' => $timestamps->modified_date,
3380 );
3381 }
3382 else {
3383 return NULL;
3384 }
3385 }
3386
3387 /**
3388 * Get a list of triggers for the contact table.
3389 *
3390 * @see hook_civicrm_triggerInfo
3391 * @see CRM_Core_DAO::triggerRebuild
3392 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3393 *
3394 * @param $info
3395 * @param null $tableName
3396 */
3397 public static function triggerInfo(&$info, $tableName = NULL) {
3398 //during upgrade, first check for valid version and then create triggers
3399 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3400 if (CRM_Core_Config::isUpgradeMode()) {
3401 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3402 //if current version is less than 4.3.alpha1 dont create below triggers
3403 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3404 return;
3405 }
3406 }
3407
3408 // Modifications to these records should update the contact timestamps.
3409 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3410 ->setRelations(array(
3411 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3412 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3413 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3414 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3415 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3416 ))
3417 ->alterTriggerInfo($info, $tableName);
3418
3419 // Update phone table to populate phone_numeric field
3420 if (!$tableName || $tableName == 'civicrm_phone') {
3421 // Define stored sql function needed for phones
3422 $sqlTriggers = Civi::service('sql_triggers');
3423 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3424 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3425 $info[] = array(
3426 'table' => array('civicrm_phone'),
3427 'when' => 'BEFORE',
3428 'event' => array('INSERT', 'UPDATE'),
3429 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3430 );
3431 }
3432 }
3433
3434 /**
3435 * Check if contact is being used in civicrm_domain based on $contactId.
3436 *
3437 * @param int $contactId
3438 * Contact id.
3439 *
3440 * @return bool
3441 * true if present else false.
3442 */
3443 public static function checkDomainContact($contactId) {
3444 if (!$contactId) {
3445 return FALSE;
3446 }
3447 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3448
3449 if ($domainId) {
3450 return TRUE;
3451 }
3452 else {
3453 return FALSE;
3454 }
3455 }
3456
3457 /**
3458 * Get options for a given contact field.
3459 *
3460 * @see CRM_Core_DAO::buildOptions
3461 *
3462 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3463 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3464 *
3465 * @param string $fieldName
3466 * @param string $context
3467 * @see CRM_Core_DAO::buildOptionsContext
3468 * @param array $props
3469 * whatever is known about this dao object.
3470 *
3471 * @return array|bool
3472 */
3473 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3474 $params = array();
3475 // Special logic for fields whose options depend on context or properties
3476 switch ($fieldName) {
3477 case 'contact_sub_type':
3478 if (!empty($props['contact_type'])) {
3479 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3480 }
3481 break;
3482
3483 case 'contact_type':
3484 if ($context == 'search') {
3485 // CRM-15495 - EntityRef filters and basic search forms expect this format
3486 // FIXME: Search builder does not
3487 return CRM_Contact_BAO_ContactType::getSelectElements();
3488 }
3489 break;
3490
3491 // The contact api supports some related entities so we'll honor that by fetching their options
3492 case 'group_id':
3493 case 'group':
3494 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3495
3496 case 'tag_id':
3497 case 'tag':
3498 $props['entity_table'] = 'civicrm_contact';
3499 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3500
3501 case 'state_province_id':
3502 case 'state_province':
3503 case 'state_province_name':
3504 case 'country_id':
3505 case 'country':
3506 case 'county_id':
3507 case 'worldregion':
3508 case 'worldregion_id':
3509 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3510
3511 }
3512 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3513 }
3514
3515 /**
3516 * Delete a contact-related object that has an 'is_primary' field.
3517 *
3518 * Ensures that is_primary gets assigned to another object if available
3519 * Also calls pre/post hooks
3520 *
3521 * @param string $type
3522 * @param int $id
3523 * @return bool
3524 */
3525 public static function deleteObjectWithPrimary($type, $id) {
3526 if (!$id || !is_numeric($id)) {
3527 return FALSE;
3528 }
3529 $daoName = "CRM_Core_DAO_$type";
3530 $obj = new $daoName();
3531 $obj->id = $id;
3532 $obj->find();
3533 $hookParams = [];
3534 if ($obj->fetch()) {
3535 CRM_Utils_Hook::pre('delete', $type, $id, $hookParams);
3536 $contactId = $obj->contact_id;
3537 $obj->delete();
3538 }
3539 else {
3540 return FALSE;
3541 }
3542 // is_primary is only relavent if this field belongs to a contact
3543 if ($contactId) {
3544 $dao = new $daoName();
3545 $dao->contact_id = $contactId;
3546 $dao->is_primary = 1;
3547 // Pick another record to be primary (if one isn't already)
3548 if (!$dao->find(TRUE)) {
3549 $dao->is_primary = 0;
3550 $dao->find();
3551 if ($dao->fetch()) {
3552 $dao->is_primary = 1;
3553 $dao->save();
3554 }
3555 }
3556 }
3557 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3558 return TRUE;
3559 }
3560
3561 /**
3562 * @inheritDoc
3563 */
3564 public function addSelectWhereClause() {
3565 // We always return an array with these keys, even if they are empty,
3566 // because this tells the query builder that we have considered these fields for acls
3567 $clauses = array(
3568 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3569 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? array() : array('!= 1'),
3570 );
3571 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3572 return $clauses;
3573 }
3574
3575 /**
3576 * Get any existing duplicate contacts based on the input parameters.
3577 *
3578 * @param array $input
3579 * Input parameters to be matched.
3580 * @param string $contactType
3581 * @param string $rule
3582 * - Supervised
3583 * - Unsupervised
3584 * @param $excludedContactIDs
3585 * An array of ids not to be included in the results.
3586 * @param bool $checkPermissions
3587 * @param int $ruleGroupID
3588 * ID of the rule group to be used if an override is desirable.
3589 * @param array $contextParams
3590 * The context if relevant, eg. ['event_id' => X]
3591 *
3592 * @return array
3593 */
3594 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3595 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3596 $dedupeParams['check_permission'] = $checkPermissions;
3597 $dedupeParams['contact_type'] = $contactType;
3598 $dedupeParams['rule'] = $rule;
3599 $dedupeParams['rule_group_id'] = $ruleGroupID;
3600 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3601 $dedupeResults['ids'] = [];
3602 $dedupeResults['handled'] = FALSE;
3603 CRM_Utils_Hook::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3604 if (!$dedupeResults['handled']) {
3605 $dedupeResults['ids'] = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3606 }
3607 return $dedupeResults['ids'];
3608 }
3609
3610 /**
3611 * Get the first duplicate contacts based on the input parameters.
3612 *
3613 * @param array $input
3614 * Input parameters to be matched.
3615 * @param string $contactType
3616 * @param string $rule
3617 * - Supervised
3618 * - Unsupervised
3619 * @param $excludedContactIDs
3620 * An array of ids not to be included in the results.
3621 * @param bool $checkPermissions
3622 * @param int $ruleGroupID
3623 * ID of the rule group to be used if an override is desirable.
3624 * @param array $contextParams
3625 * The context if relevant, eg. ['event_id' => X]
3626 *
3627 * @return int|NULL
3628 */
3629 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3630 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3631 if (empty($ids)) {
3632 return NULL;
3633 }
3634 return $ids[0];
3635 }
3636
3637 /**
3638 * Check if a field is associated with an entity that has a location type.
3639 *
3640 * (ie. is an address, phone, email etc field).
3641 *
3642 * @param string $fieldTitle
3643 * Title of the field (not the name - create a new function for that if required).
3644 *
3645 * @return bool
3646 */
3647 public static function isFieldHasLocationType($fieldTitle) {
3648 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3649 if ($field['title'] === $fieldTitle) {
3650 return CRM_Utils_Array::value('hasLocationType', $field);
3651 }
3652 }
3653 return FALSE;
3654 }
3655
3656 /**
3657 * @param array $appendProfiles
3658 * Name of profile(s) to append to each link.
3659 *
3660 * @return array
3661 */
3662 public static function getEntityRefCreateLinks($appendProfiles = []) {
3663 // You'd think that "create contacts" would be the permission to check,
3664 // But new contact popups are profile forms and those use their own permissions.
3665 if (!CRM_Core_Permission::check([['profile create', 'profile listings and forms']])) {
3666 return FALSE;
3667 }
3668 $profiles = [];
3669 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $contactType) {
3670 $profiles[] = 'new_' . strtolower($contactType);
3671 }
3672 $retrieved = civicrm_api3('uf_group', 'get', [
3673 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3674 'is_active' => 1,
3675 ]);
3676 $links = $append = [];
3677 if (!empty($retrieved['values'])) {
3678 $icons = [
3679 'individual' => 'fa-user',
3680 'organization' => 'fa-building',
3681 'household' => 'fa-home',
3682 ];
3683 foreach ($retrieved['values'] as $id => $profile) {
3684 if (in_array($profile['name'], $profiles)) {
3685 $links[] = array(
3686 'label' => $profile['title'],
3687 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3688 NULL, NULL, FALSE, FALSE, TRUE),
3689 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3690 'icon' => CRM_Utils_Array::value(str_replace('new_', '', $profile['name']), $icons),
3691 );
3692 }
3693 else {
3694 $append[] = $id;
3695 }
3696 }
3697 foreach ($append as $id) {
3698 foreach ($links as &$link) {
3699 $link['url'] .= ",$id";
3700 }
3701 }
3702 }
3703 return $links;
3704 }
3705
3706 /**
3707 * @return array
3708 */
3709 public static function getEntityRefFilters() {
3710 return [
3711 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3712 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3713 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3714 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3715 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3716 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3717 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3718 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3719 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3720 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3721 ];
3722 }
3723
3724 }