Merge pull request #13762 from mattwire/event_register_thankyou_region
[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 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 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 static $_importableFields = array();
90
91 /**
92 * Static field for all the contact information that we can potentially export.
93 *
94 * @var array
95 */
96 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 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
469 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
470 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
471 }
472 }
473 // Filter out other fields.
474 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
475 $params = array_merge($params, $savedGreetings);
476 }
477 else {
478 foreach ($missingGreetingParams as $greetingName => $greeting) {
479 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greetingName);
480 }
481 }
482
483 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
484 if ($params[$greetingParam] === 'null') {
485 // If we are setting it to null then null out the display field.
486 $params[$greetingIndex . '_display'] = 'null';
487 }
488 }
489 }
490
491 /**
492 * Get the display name and image of a contact.
493 *
494 * @param int $id
495 * The contactId.
496 *
497 * @param bool $includeTypeInReturnParameters
498 * Should type be part of the returned array?
499 *
500 * @return array
501 * the displayName and contactImage for this contact
502 */
503 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
504 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
505 $sql = "
506 SELECT civicrm_contact.*,
507 civicrm_email.email as email
508 FROM civicrm_contact
509 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
510 AND civicrm_email.is_primary = 1
511 WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
512 $dao = new CRM_Core_DAO();
513 $dao->query($sql);
514 if ($dao->fetch()) {
515 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
516 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
517 );
518 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
519 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
520 );
521
522 // use email if display_name is empty
523 if (empty($dao->display_name)) {
524 $displayName = $dao->email;
525 }
526 else {
527 $displayName = $dao->display_name;
528 }
529
530 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
531
532 return $includeTypeInReturnParameters ? array(
533 $displayName,
534 $image,
535 $dao->contact_type,
536 $dao->contact_sub_type,
537 $imageUrl,
538 ) : array($displayName, $image, $imageUrl);
539 }
540 return NULL;
541 }
542
543 /**
544 * Add billing fields to the params if appropriate.
545 *
546 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
547 * don't then we should set the name fields to the filling fields AND add the preserveDBName
548 * parameter (which will tell the BAO only to set those fields if none already exist.
549 *
550 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
551 * matching is best done by hipsters.
552 *
553 * @param array $params
554 */
555 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
556 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
557 foreach ($nameFields as $field) {
558 if (!empty($params[$field])) {
559 return;
560 }
561 }
562 // There are only 3 - we can iterate through them twice :-)
563 foreach ($nameFields as $field) {
564 if (!empty($params['billing_' . $field])) {
565 $params[$field] = $params['billing_' . $field];
566 }
567 $params['preserveDBName'] = TRUE;
568 }
569
570 }
571
572 /**
573 * Resolve a state province string (UT or Utah) to an ID.
574 *
575 * If country has been passed in we should select a state belonging to that country.
576 *
577 * Alternatively we should choose from enabled countries, prioritising the default country.
578 *
579 * @param array $values
580 * @param int|NULL $countryID
581 *
582 * @return int|null
583 */
584 protected static function resolveStateProvinceID($values, $countryID) {
585
586 if ($countryID) {
587 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID);
588 if (CRM_Utils_Array::lookupValue($values,
589 'state_province',
590 $stateProvinceList,
591 TRUE
592 )) {
593 return $values['state_province_id'];
594 }
595 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID, 'abbreviation');
596 if (CRM_Utils_Array::lookupValue($values,
597 'state_province',
598 $stateProvinceList,
599 TRUE
600 )) {
601 return $values['state_province_id'];
602 }
603 return NULL;
604 }
605 else {
606 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
607 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
608 // prefer matching country..
609 $stateProvinceList = CRM_Core_BAO_Address::buildOptions('state_province_id', NULL, array('country_id' => Civi::settings()->get('defaultContactCountry')));
610 if (CRM_Utils_Array::lookupValue($values,
611 'state_province',
612 $stateProvinceList,
613 TRUE
614 )) {
615 return $values['state_province_id'];
616 }
617
618 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
619 if (CRM_Utils_Array::lookupValue($values,
620 'state_province',
621 $stateProvinceList,
622 TRUE
623 )) {
624 return $values['state_province_id'];
625 }
626
627 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviationForDefaultCountry();
628 if (CRM_Utils_Array::lookupValue($values,
629 'state_province',
630 $stateProvinceList,
631 TRUE
632 )) {
633 return $values['state_province_id'];
634 }
635 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
636 if (CRM_Utils_Array::lookupValue($values,
637 'state_province',
638 $stateProvinceList,
639 TRUE
640 )) {
641 return $values['state_province_id'];
642 }
643 }
644
645 return NULL;
646 }
647
648 /**
649 * Get the relevant location entity for the array key.
650 *
651 * Based on the field name we determine which location entity
652 * we are dealing with. Apart from a few specific ones they
653 * are mostly 'address' (the default).
654 *
655 * @param string $fieldName
656 *
657 * @return string
658 */
659 protected static function getLocationEntityForKey($fieldName) {
660 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
661 return $fieldName;
662 }
663 if ($fieldName === 'phone_ext') {
664 return 'phone';
665 }
666 return 'address';
667 }
668
669 /**
670 * Create last viewed link to recently updated contact.
671 *
672 * @param array $crudLinkSpec
673 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
674 * - entity_table: string, eg "civicrm_contact"
675 * - entity_id: int
676 *
677 * @return array|NULL
678 * NULL if unavailable, or
679 * [path: string, query: string, title: string]
680 * @see CRM_Utils_System::createDefaultCrudLink
681 */
682 public function createDefaultCrudLink($crudLinkSpec) {
683 switch ($crudLinkSpec['action']) {
684 case CRM_Core_Action::VIEW:
685 $result = array(
686 'title' => $this->display_name,
687 'path' => 'civicrm/contact/view',
688 'query' => array(
689 'reset' => 1,
690 'cid' => $this->id,
691 ),
692 );
693 return $result;
694
695 case CRM_Core_Action::UPDATE:
696 $result = array(
697 'title' => $this->display_name,
698 'path' => 'civicrm/contact/add',
699 'query' => array(
700 'reset' => 1,
701 'action' => 'update',
702 'cid' => $this->id,
703 ),
704 );
705 return $result;
706 }
707 return NULL;
708 }
709
710 /**
711 * Get the values for pseudoconstants for name->value and reverse.
712 *
713 * @deprecated
714 *
715 * This is called specifically from the contact import parser & should be moved there
716 * as it is not truly a generic function.
717 *
718 * @param array $defaults
719 * (reference) the default values, some of which need to be resolved.
720 * @param bool $reverse
721 * Always true as this function is only called from one place..
722 */
723 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
724 // Hack for birth_date.
725 if (!empty($defaults['birth_date'])) {
726 if (is_array($defaults['birth_date'])) {
727 $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
728 }
729 }
730
731 CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
732 CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
733 CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
734 CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
735
736 //lookup value of email/postal greeting, addressee, CRM-4575
737 foreach (self::$_greetingTypes as $greeting) {
738 $filterCondition = array(
739 'contact_type' => CRM_Utils_Array::value('contact_type', $defaults),
740 'greeting_type' => $greeting,
741 );
742 CRM_Utils_Array::lookupValue($defaults, $greeting,
743 CRM_Core_PseudoConstant::greeting($filterCondition), $reverse
744 );
745 }
746
747 $blocks = array('address', 'im', 'phone');
748 foreach ($blocks as $name) {
749 if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
750 continue;
751 }
752 foreach ($defaults[$name] as $count => & $values) {
753
754 //get location type id.
755 CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
756
757 if ($name == 'address') {
758 // FIXME: lookupValue doesn't work for vcard_name
759 if (!empty($values['location_type_id'])) {
760 $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
761 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
762 }
763
764 if (!CRM_Utils_Array::lookupValue($values,
765 'country',
766 CRM_Core_PseudoConstant::country(),
767 $reverse
768 ) &&
769 $reverse
770 ) {
771 CRM_Utils_Array::lookupValue($values,
772 'country',
773 CRM_Core_PseudoConstant::countryIsoCode(),
774 $reverse
775 );
776 }
777 $stateProvinceID = self::resolveStateProvinceID($values, CRM_Utils_Array::value('country_id', $values));
778 if ($stateProvinceID) {
779 $values['state_province_id'] = $stateProvinceID;
780 }
781
782 if (!empty($values['state_province_id'])) {
783 $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
784 }
785 else {
786 $countyList = CRM_Core_PseudoConstant::county();
787 }
788 CRM_Utils_Array::lookupValue($values,
789 'county',
790 $countyList,
791 $reverse
792 );
793 }
794
795 if ($name == 'im') {
796 CRM_Utils_Array::lookupValue($values,
797 'provider',
798 CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
799 $reverse
800 );
801 }
802
803 if ($name == 'phone') {
804 CRM_Utils_Array::lookupValue($values,
805 'phone_type',
806 CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
807 $reverse
808 );
809 }
810
811 // Kill the reference.
812 unset($values);
813 }
814 }
815 }
816
817 /**
818 * Fetch object based on array of properties.
819 *
820 * @param array $params
821 * (reference ) an assoc array of name/value pairs.
822 * @param array $defaults
823 * (reference ) an assoc array to hold the name / value pairs.
824 * in a hierarchical manner
825 * @param bool $microformat
826 * For location in microformat.
827 *
828 * @return CRM_Contact_BAO_Contact
829 */
830 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
831 if (array_key_exists('contact_id', $params)) {
832 $params['id'] = $params['contact_id'];
833 }
834 elseif (array_key_exists('id', $params)) {
835 $params['contact_id'] = $params['id'];
836 }
837
838 $contact = self::getValues($params, $defaults);
839
840 unset($params['id']);
841
842 //get the block information for this contact
843 $entityBlock = array('contact_id' => $params['contact_id']);
844 $blocks = CRM_Core_BAO_Location::getValues($entityBlock, $microformat);
845 $defaults = array_merge($defaults, $blocks);
846 foreach ($blocks as $block => $value) {
847 $contact->$block = $value;
848 }
849
850 if (!isset($params['noNotes'])) {
851 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
852 }
853
854 if (!isset($params['noRelationships'])) {
855 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
856 }
857
858 if (!isset($params['noGroups'])) {
859 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
860 }
861
862 if (!isset($params['noWebsite'])) {
863 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
864 }
865
866 return $contact;
867 }
868
869 /**
870 * Get the display name of a contact.
871 *
872 * @param int $id
873 * Id of the contact.
874 *
875 * @return null|string
876 * display name of the contact if found
877 */
878 public static function displayName($id) {
879 $displayName = NULL;
880 if ($id) {
881 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
882 }
883
884 return $displayName;
885 }
886
887 /**
888 * Delete a contact and all its associated records.
889 *
890 * @param int $id
891 * Id of the contact to delete.
892 * @param bool $restore
893 * Whether to actually restore, not delete.
894 * @param bool $skipUndelete
895 * Whether to force contact delete or not.
896 * @param bool $checkPermissions
897 *
898 * @return bool
899 * Was contact deleted?
900 */
901 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
902
903 if (!$id) {
904 return FALSE;
905 }
906 // If trash is disabled in system settings then we always skip
907 if (!Civi::settings()->get('contact_undelete')) {
908 $skipUndelete = TRUE;
909 }
910
911 // make sure we have edit permission for this contact
912 // before we delete
913 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
914 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
915 ) {
916 return FALSE;
917 }
918
919 // CRM-12929
920 // Restrict contact to be delete if contact has financial trxns
921 $error = NULL;
922 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($id), $error)) {
923 return FALSE;
924 }
925
926 // make sure this contact_id does not have any membership types
927 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
928 $id,
929 'id',
930 'member_of_contact_id'
931 );
932 if ($membershipTypeID) {
933 return FALSE;
934 }
935
936 $contact = new CRM_Contact_DAO_Contact();
937 $contact->id = $id;
938 if (!$contact->find(TRUE)) {
939 return FALSE;
940 }
941
942 $contactType = $contact->contact_type;
943 // currently we only clear employer cache.
944 // we are now deleting inherited membership if any.
945 if ($contact->contact_type == 'Organization') {
946 $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE;
947 $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id);
948 if (!empty($relationshipDtls)) {
949 foreach ($relationshipDtls as $rId => $details) {
950 CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action);
951 }
952 }
953 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
954 }
955
956 if ($restore) {
957 return self::contactTrashRestore($contact, TRUE);
958 }
959
960 // start a new transaction
961 $transaction = new CRM_Core_Transaction();
962
963 if ($skipUndelete) {
964 CRM_Utils_Hook::pre('delete', $contactType, $id, CRM_Core_DAO::$_nullArray);
965
966 //delete billing address if exists.
967 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
968
969 // delete the log entries since we dont have triggers enabled as yet
970 $logDAO = new CRM_Core_DAO_Log();
971 $logDAO->entity_table = 'civicrm_contact';
972 $logDAO->entity_id = $id;
973 $logDAO->delete();
974
975 // delete contact participants CRM-12155
976 CRM_Event_BAO_Participant::deleteContactParticipant($id);
977
978 // delete contact contributions CRM-12155
979 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
980
981 // do activity cleanup, CRM-5604
982 CRM_Activity_BAO_Activity::cleanupActivity($id);
983
984 // delete all notes related to contact
985 CRM_Core_BAO_Note::cleanContactNotes($id);
986
987 // delete cases related to contact
988 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
989 if (!empty($contactCases)) {
990 foreach ($contactCases as $caseId) {
991 //check if case is associate with other contact or not.
992 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
993 if (count($caseContactId) <= 1) {
994 CRM_Case_BAO_Case::deleteCase($caseId);
995 }
996 }
997 }
998
999 $contact->delete();
1000 }
1001 else {
1002 self::contactTrashRestore($contact);
1003 }
1004
1005 //delete the contact id from recently view
1006 CRM_Utils_Recent::delContact($id);
1007 self::updateContactCache($id, empty($restore));
1008
1009 // delete any prevnext/dupe cache entry
1010 // These two calls are redundant in default deployments, but they're
1011 // meaningful if "prevnext" is memory-backed.
1012 Civi::service('prevnext')->deleteItem($id);
1013 CRM_Core_BAO_PrevNextCache::deleteItem($id);
1014
1015 $transaction->commit();
1016
1017 if ($skipUndelete) {
1018 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
1019 }
1020
1021 return TRUE;
1022 }
1023
1024 /**
1025 * Action to update any caches relating to a recently update contact.
1026 *
1027 * I was going to call this from delete as well as from create to ensure the delete is being
1028 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1029 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1030 * where the call involved a subquery that was locking the table.
1031 *
1032 * @param int $contactID
1033 * @param bool $isTrashed
1034 */
1035 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1036
1037 if ($isTrashed) {
1038 CRM_Contact_BAO_GroupContactCache::removeContact($contactID);
1039 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1040 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1041 // but this should not cause any change as long as contacts are not being trashed outside the
1042 // main functions for that.
1043 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1044 }
1045 else {
1046 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
1047 }
1048 }
1049
1050 /**
1051 * Delete the image of a contact.
1052 *
1053 * @param int $id
1054 * Id of the contact.
1055 *
1056 * @return bool
1057 * Was contact image deleted?
1058 */
1059 public static function deleteContactImage($id) {
1060 if (!$id) {
1061 return FALSE;
1062 }
1063
1064 $contact = new self();
1065 $contact->id = $id;
1066 $contact->image_URL = 'null';
1067 $contact->save();
1068
1069 return TRUE;
1070 }
1071
1072 /**
1073 * Return proportional height and width of the image.
1074 *
1075 * @param int $imageWidth
1076 * Width of image.
1077 *
1078 * @param int $imageHeight
1079 * Height of image.
1080 *
1081 * @return array
1082 * Thumb dimension of image
1083 */
1084 public static function getThumbSize($imageWidth, $imageHeight) {
1085 $thumbWidth = 100;
1086 if ($imageWidth && $imageHeight) {
1087 $imageRatio = $imageWidth / $imageHeight;
1088 }
1089 else {
1090 $imageRatio = 1;
1091 }
1092 if ($imageRatio > 1) {
1093 $imageThumbWidth = $thumbWidth;
1094 $imageThumbHeight = round($thumbWidth / $imageRatio);
1095 }
1096 else {
1097 $imageThumbHeight = $thumbWidth;
1098 $imageThumbWidth = round($thumbWidth * $imageRatio);
1099 }
1100
1101 return array($imageThumbWidth, $imageThumbHeight);
1102 }
1103
1104 /**
1105 * Validate type of contact image.
1106 *
1107 * @param array $params
1108 * @param string $imageIndex
1109 * Index of image field.
1110 * @param string $statusMsg
1111 * Status message to be set after operation.
1112 * @param string $opType
1113 * Type of operation like fatal, bounce etc.
1114 *
1115 * @return bool
1116 * true if valid image extension
1117 */
1118 public static function processImageParams(
1119 &$params,
1120 $imageIndex = 'image_URL',
1121 $statusMsg = NULL,
1122 $opType = 'status'
1123 ) {
1124 $mimeType = array(
1125 'image/jpeg',
1126 'image/jpg',
1127 'image/png',
1128 'image/bmp',
1129 'image/p-jpeg',
1130 'image/gif',
1131 'image/x-png',
1132 );
1133
1134 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1135 $photo = basename($params[$imageIndex]['name']);
1136 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1137 return TRUE;
1138 }
1139 else {
1140 unset($params[$imageIndex]);
1141 if (!$statusMsg) {
1142 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1143 }
1144 if ($opType == 'status') {
1145 CRM_Core_Session::setStatus($statusMsg, ts('Error'), 'error');
1146 }
1147 // FIXME: additional support for fatal, bounce etc could be added.
1148 return FALSE;
1149 }
1150 }
1151
1152 /**
1153 * Extract contact id from url for deleting contact image.
1154 */
1155 public static function processImage() {
1156
1157 $action = CRM_Utils_Request::retrieve('action', 'String');
1158 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
1159 // retrieve contact id in case of Profile context
1160 $id = CRM_Utils_Request::retrieve('id', 'Positive');
1161 $cid = $cid ? $cid : $id;
1162 if ($action & CRM_Core_Action::DELETE) {
1163 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
1164 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1165 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1166 $session = CRM_Core_Session::singleton();
1167 $toUrl = $session->popUserContext();
1168 CRM_Utils_System::redirect($toUrl);
1169 }
1170 }
1171 }
1172
1173 /**
1174 * Function to set is_delete true or restore deleted contact.
1175 *
1176 * @param CRM_Contact_DAO_Contact $contact
1177 * Contact DAO object.
1178 * @param bool $restore
1179 * True to set the is_delete = 1 else false to restore deleted contact,
1180 * i.e. is_delete = 0
1181 *
1182 * @return bool
1183 */
1184 public static function contactTrashRestore($contact, $restore = FALSE) {
1185 $updateParams = array(
1186 'id' => $contact->id,
1187 'is_deleted' => $restore ? 0 : 1,
1188 );
1189
1190 CRM_Utils_Hook::pre('update', $contact->contact_type, $contact->id, $updateParams);
1191
1192 $params = array(1 => array($contact->id, 'Integer'));
1193 if (!$restore) {
1194 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1195 CRM_Core_DAO::executeQuery($query, $params);
1196 }
1197
1198 $contact->copyValues($updateParams);
1199 $contact->save();
1200 CRM_Core_BAO_Log::register($contact->id, 'civicrm_contact', $contact->id);
1201
1202 CRM_Utils_Hook::post('update', $contact->contact_type, $contact->id, $contact);
1203
1204 return TRUE;
1205 }
1206
1207 /**
1208 * Get contact type for a contact.
1209 *
1210 * @param int $id
1211 * Id of the contact whose contact type is needed.
1212 *
1213 * @return string
1214 * contact_type if $id found else null ""
1215 */
1216 public static function getContactType($id) {
1217 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1218 }
1219
1220 /**
1221 * Get contact sub type for a contact.
1222 *
1223 * @param int $id
1224 * Id of the contact whose contact sub type is needed.
1225 *
1226 * @param string $implodeDelimiter
1227 *
1228 * @return string
1229 * contact_sub_type if $id found else null ""
1230 */
1231 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1232 $subtype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1233 if (!$subtype) {
1234 return $implodeDelimiter ? NULL : array();
1235 }
1236
1237 $subtype = CRM_Utils_Array::explodePadded($subtype);
1238
1239 if ($implodeDelimiter) {
1240 $subtype = implode($implodeDelimiter, $subtype);
1241 }
1242 return $subtype;
1243 }
1244
1245 /**
1246 * Get pair of contact-type and sub-type for a contact.
1247 *
1248 * @param int $id
1249 * Id of the contact whose contact sub/contact type is needed.
1250 *
1251 * @return array
1252 */
1253 public static function getContactTypes($id) {
1254 $params = array('id' => $id);
1255 $details = array();
1256 $contact = CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact',
1257 $params,
1258 $details,
1259 array('contact_type', 'contact_sub_type')
1260 );
1261
1262 if ($contact) {
1263 $contactTypes = array();
1264 if ($contact->contact_sub_type) {
1265 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
1266 }
1267 array_unshift($contactTypes, $contact->contact_type);
1268
1269 return $contactTypes;
1270 }
1271 else {
1272 CRM_Core_Error::fatal();
1273 }
1274 }
1275
1276 /**
1277 * Combine all the importable fields from the lower levels object.
1278 *
1279 * The ordering is important, since currently we do not have a weight
1280 * scheme. Adding weight is super important
1281 *
1282 * @param int|string $contactType contact Type
1283 * @param bool $status
1284 * Status is used to manipulate first title.
1285 * @param bool $showAll
1286 * If true returns all fields (includes disabled fields).
1287 * @param bool $isProfile
1288 * If its profile mode.
1289 * @param bool $checkPermission
1290 * If false, do not include permissioning clause (for custom data).
1291 *
1292 * @param bool $withMultiCustomFields
1293 *
1294 * @return array
1295 * array of importable Fields
1296 */
1297 public static function importableFields(
1298 $contactType = 'Individual',
1299 $status = FALSE,
1300 $showAll = FALSE,
1301 $isProfile = FALSE,
1302 $checkPermission = TRUE,
1303 $withMultiCustomFields = FALSE
1304 ) {
1305 if (empty($contactType)) {
1306 $contactType = 'All';
1307 }
1308
1309 $cacheKeyString = "importableFields $contactType";
1310 $cacheKeyString .= $status ? '_1' : '_0';
1311 $cacheKeyString .= $showAll ? '_1' : '_0';
1312 $cacheKeyString .= $isProfile ? '_1' : '_0';
1313 $cacheKeyString .= $checkPermission ? '_1' : '_0';
1314
1315 $fields = CRM_Utils_Array::value($cacheKeyString, self::$_importableFields);
1316
1317 if (!$fields) {
1318 // check if we can retrieve from database cache
1319 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1320 }
1321
1322 if (!$fields) {
1323 $fields = CRM_Contact_DAO_Contact::import();
1324
1325 // get the fields thar are meant for contact types
1326 if (in_array($contactType, array(
1327 'Individual',
1328 'Household',
1329 'Organization',
1330 'All',
1331 ))) {
1332 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1333 }
1334
1335 $locationFields = array_merge(CRM_Core_DAO_Address::import(),
1336 CRM_Core_DAO_Phone::import(),
1337 CRM_Core_DAO_Email::import(),
1338 CRM_Core_DAO_IM::import(TRUE),
1339 CRM_Core_DAO_OpenID::import()
1340 );
1341
1342 $locationFields = array_merge($locationFields,
1343 CRM_Core_BAO_CustomField::getFieldsForImport('Address',
1344 FALSE,
1345 FALSE,
1346 FALSE,
1347 FALSE
1348 )
1349 );
1350
1351 foreach ($locationFields as $key => $field) {
1352 $locationFields[$key]['hasLocationType'] = TRUE;
1353 }
1354
1355 $fields = array_merge($fields, $locationFields);
1356
1357 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1358 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
1359
1360 //website fields
1361 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
1362 $fields['url']['hasWebsiteType'] = TRUE;
1363
1364 if ($contactType != 'All') {
1365 $fields = array_merge($fields,
1366 CRM_Core_BAO_CustomField::getFieldsForImport($contactType,
1367 $showAll,
1368 TRUE,
1369 FALSE,
1370 FALSE,
1371 $withMultiCustomFields
1372 )
1373 );
1374 //unset the fields, which are not related to their
1375 //contact type.
1376 $commonValues = array(
1377 'Individual' => array(
1378 'household_name',
1379 'legal_name',
1380 'sic_code',
1381 'organization_name',
1382 ),
1383 'Household' => array(
1384 'first_name',
1385 'middle_name',
1386 'last_name',
1387 'formal_title',
1388 'job_title',
1389 'gender_id',
1390 'prefix_id',
1391 'suffix_id',
1392 'birth_date',
1393 'organization_name',
1394 'legal_name',
1395 'legal_identifier',
1396 'sic_code',
1397 'home_URL',
1398 'is_deceased',
1399 'deceased_date',
1400 ),
1401 'Organization' => array(
1402 'first_name',
1403 'middle_name',
1404 'last_name',
1405 'formal_title',
1406 'job_title',
1407 'gender_id',
1408 'prefix_id',
1409 'suffix_id',
1410 'birth_date',
1411 'household_name',
1412 'is_deceased',
1413 'deceased_date',
1414 ),
1415 );
1416 foreach ($commonValues[$contactType] as $value) {
1417 unset($fields[$value]);
1418 }
1419 }
1420 else {
1421 foreach (array('Individual', 'Household', 'Organization') as $type) {
1422 $fields = array_merge($fields,
1423 CRM_Core_BAO_CustomField::getFieldsForImport($type,
1424 $showAll,
1425 FALSE,
1426 FALSE,
1427 FALSE,
1428 $withMultiCustomFields
1429 )
1430 );
1431 }
1432 }
1433
1434 if ($isProfile) {
1435 $fields = array_merge($fields, array(
1436 'group' => array(
1437 'title' => ts('Group(s)'),
1438 'name' => 'group',
1439 ),
1440 'tag' => array(
1441 'title' => ts('Tag(s)'),
1442 'name' => 'tag',
1443 ),
1444 'note' => array(
1445 'title' => ts('Note'),
1446 'name' => 'note',
1447 ),
1448 'communication_style_id' => array(
1449 'title' => ts('Communication Style'),
1450 'name' => 'communication_style_id',
1451 ),
1452 ));
1453 }
1454
1455 //Sorting fields in alphabetical order(CRM-1507)
1456 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1457
1458 CRM_Core_BAO_Cache::setItem($fields, 'contact fields', $cacheKeyString);
1459 }
1460
1461 self::$_importableFields[$cacheKeyString] = $fields;
1462
1463 if (!$isProfile) {
1464 if (!$status) {
1465 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1466 self::$_importableFields[$cacheKeyString]
1467 );
1468 }
1469 else {
1470 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1471 self::$_importableFields[$cacheKeyString]
1472 );
1473 }
1474 }
1475 return $fields;
1476 }
1477
1478 /**
1479 * Combine all the exportable fields from the lower levels object.
1480 *
1481 * Currently we are using importable fields as exportable fields
1482 *
1483 * @param int|string $contactType contact Type
1484 * @param bool $status
1485 * True while exporting primary contacts.
1486 * @param bool $export
1487 * True when used during export.
1488 * @param bool $search
1489 * True when used during search, might conflict with export param?.
1490 *
1491 * @param bool $withMultiRecord
1492 *
1493 * @return array
1494 * array of exportable Fields
1495 */
1496 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1497 if (empty($contactType)) {
1498 $contactType = 'All';
1499 }
1500
1501 $cacheKeyString = "exportableFields $contactType";
1502 $cacheKeyString .= $export ? '_1' : '_0';
1503 $cacheKeyString .= $status ? '_1' : '_0';
1504 $cacheKeyString .= $search ? '_1' : '_0';
1505 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1506 //calculates custom fields takes into account the logged in user & caches that for all users
1507 //as an interim fix we will cache the fields by contact
1508 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1509
1510 if (!self::$_exportableFields || !CRM_Utils_Array::value($cacheKeyString, self::$_exportableFields)) {
1511 if (!self::$_exportableFields) {
1512 self::$_exportableFields = array();
1513 }
1514
1515 // check if we can retrieve from database cache
1516 $fields = CRM_Core_BAO_Cache::getItem('contact fields', $cacheKeyString);
1517
1518 if (!$fields) {
1519 $fields = CRM_Contact_DAO_Contact::export();
1520
1521 // The fields are meant for contact types.
1522 if (in_array($contactType, array(
1523 'Individual',
1524 'Household',
1525 'Organization',
1526 'All',
1527 )
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,
2391 array(
2392 'nick_name',
2393 'job_title',
2394 'middle_name',
2395 'birth_date',
2396 'gender_id',
2397 'current_employer',
2398 'prefix_id',
2399 'suffix_id',
2400 )) &&
2401 ($value == '' || !isset($value)) &&
2402 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2403 ($key == 'current_employer' && empty($params['current_employer']))) {
2404 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2405 // to avoid update with empty values
2406 continue;
2407 }
2408 else {
2409 $data[$key] = $value;
2410 }
2411 }
2412 }
2413 }
2414
2415 if (!isset($data['contact_type'])) {
2416 $data['contact_type'] = 'Individual';
2417 }
2418
2419 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2420 $privacy = CRM_Core_SelectValues::privacy();
2421 foreach ($privacy as $key => $value) {
2422 if (array_key_exists($key, $fields)) {
2423 // do not reset values for existing contacts, if fields are added to a profile
2424 if (array_key_exists($key, $params)) {
2425 $data[$key] = $params[$key];
2426 if (empty($params[$key])) {
2427 $data[$key] = 0;
2428 }
2429 }
2430 elseif (!$contactID) {
2431 $data[$key] = 0;
2432 }
2433 }
2434 }
2435
2436 return array($data, $contactDetails);
2437 }
2438
2439 /**
2440 * Find the get contact details.
2441 *
2442 * This function does not respect ACLs for now, which might need to be rectified at some
2443 * stage based on how its used.
2444 *
2445 * @param string $mail
2446 * Primary email address of the contact.
2447 * @param string $ctype
2448 * Contact type.
2449 *
2450 * @return object|null
2451 * $dao contact details
2452 */
2453 public static function matchContactOnEmail($mail, $ctype = NULL) {
2454 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2455 $mail = $strtolower(trim($mail));
2456 $query = "
2457 SELECT civicrm_contact.id as contact_id,
2458 civicrm_contact.hash as hash,
2459 civicrm_contact.contact_type as contact_type,
2460 civicrm_contact.contact_sub_type as contact_sub_type
2461 FROM civicrm_contact
2462 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2463
2464 if (Civi::settings()->get('uniq_email_per_site')) {
2465 // try to find a match within a site (multisite).
2466 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2467 if (!empty($groups)) {
2468 $query .= "
2469 INNER JOIN civicrm_group_contact gc ON
2470 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2471 }
2472 }
2473
2474 $query .= "
2475 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2476 $p = array(1 => array($mail, 'String'));
2477
2478 if ($ctype) {
2479 $query .= " AND civicrm_contact.contact_type = %3";
2480 $p[3] = array($ctype, 'String');
2481 }
2482
2483 $query .= " ORDER BY civicrm_email.is_primary DESC";
2484
2485 $dao = CRM_Core_DAO::executeQuery($query, $p);
2486
2487 if ($dao->fetch()) {
2488 return $dao;
2489 }
2490 return NULL;
2491 }
2492
2493 /**
2494 * Find the contact details associated with an OpenID.
2495 *
2496 * @param string $openId
2497 * OpenId of the contact.
2498 * @param string $ctype
2499 * Contact type.
2500 *
2501 * @return object|null
2502 * $dao contact details
2503 */
2504 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2505 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2506 $openId = $strtolower(trim($openId));
2507 $query = "
2508 SELECT civicrm_contact.id as contact_id,
2509 civicrm_contact.hash as hash,
2510 civicrm_contact.contact_type as contact_type,
2511 civicrm_contact.contact_sub_type as contact_sub_type
2512 FROM civicrm_contact
2513 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2514 WHERE civicrm_openid.openid = %1";
2515 $p = array(1 => array($openId, 'String'));
2516
2517 if ($ctype) {
2518 $query .= " AND civicrm_contact.contact_type = %3";
2519 $p[3] = array($ctype, 'String');
2520 }
2521
2522 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2523
2524 $dao = CRM_Core_DAO::executeQuery($query, $p);
2525
2526 if ($dao->fetch()) {
2527 return $dao;
2528 }
2529 return NULL;
2530 }
2531
2532 /**
2533 * Get primary email of the contact.
2534 *
2535 * @param int $contactID
2536 * Contact id.
2537 *
2538 * @return string
2539 * Email address if present else null
2540 */
2541 public static function getPrimaryEmail($contactID) {
2542 // fetch the primary email
2543 $query = "
2544 SELECT civicrm_email.email as email
2545 FROM civicrm_contact
2546 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2547 WHERE civicrm_email.is_primary = 1
2548 AND civicrm_contact.id = %1";
2549 $p = array(1 => array($contactID, 'Integer'));
2550 $dao = CRM_Core_DAO::executeQuery($query, $p);
2551
2552 $email = NULL;
2553 if ($dao->fetch()) {
2554 $email = $dao->email;
2555 }
2556 return $email;
2557 }
2558
2559 /**
2560 * Function to get primary OpenID of the contact.
2561 *
2562 * @param int $contactID
2563 * Contact id.
2564 *
2565 * @return string
2566 * >openid OpenID if present else null
2567 */
2568 public static function getPrimaryOpenId($contactID) {
2569 // fetch the primary OpenID
2570 $query = "
2571 SELECT civicrm_openid.openid as openid
2572 FROM civicrm_contact
2573 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2574 WHERE civicrm_contact.id = %1
2575 AND civicrm_openid.is_primary = 1";
2576 $p = array(1 => array($contactID, 'Integer'));
2577 $dao = CRM_Core_DAO::executeQuery($query, $p);
2578
2579 $openId = NULL;
2580 if ($dao->fetch()) {
2581 $openId = $dao->openid;
2582 }
2583 return $openId;
2584 }
2585
2586 /**
2587 * Fetch the object and store the values in the values array.
2588 *
2589 * @param array $params
2590 * Input parameters to find object.
2591 * @param array $values
2592 * Output values of the object.
2593 *
2594 * @return CRM_Contact_BAO_Contact|null
2595 * The found object or null
2596 */
2597 public static function getValues(&$params, &$values) {
2598 $contact = new CRM_Contact_BAO_Contact();
2599
2600 $contact->copyValues($params);
2601
2602 if ($contact->find(TRUE)) {
2603
2604 CRM_Core_DAO::storeValues($contact, $values);
2605
2606 $privacy = array();
2607 foreach (self::$_commPrefs as $name) {
2608 if (isset($contact->$name)) {
2609 $privacy[$name] = $contact->$name;
2610 }
2611 }
2612
2613 if (!empty($privacy)) {
2614 $values['privacy'] = $privacy;
2615 }
2616
2617 // communication Prefferance
2618 $preffComm = $comm = array();
2619 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2620 $contact->preferred_communication_method
2621 );
2622 foreach ($comm as $value) {
2623 $preffComm[$value] = 1;
2624 }
2625 $temp = array('preferred_communication_method' => $contact->preferred_communication_method);
2626
2627 $names = array(
2628 'preferred_communication_method' => array(
2629 'newName' => 'preferred_communication_method_display',
2630 'groupName' => 'preferred_communication_method',
2631 ),
2632 );
2633
2634 // @todo This can be figured out from metadata & we can avoid the uncached query.
2635 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2636
2637 $values['preferred_communication_method'] = $preffComm;
2638 $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp);
2639
2640 if ($contact->preferred_mail_format) {
2641 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2642 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2643 }
2644
2645 // get preferred languages
2646 if (!empty($contact->preferred_language)) {
2647 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2648 }
2649
2650 // Calculating Year difference
2651 if ($contact->birth_date) {
2652 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2653 if ($birthDate < date('Ymd')) {
2654 $age = CRM_Utils_Date::calculateAge($birthDate);
2655 $values['age']['y'] = CRM_Utils_Array::value('years', $age);
2656 $values['age']['m'] = CRM_Utils_Array::value('months', $age);
2657 }
2658 }
2659
2660 $contact->contact_id = $contact->id;
2661
2662 return $contact;
2663 }
2664 return NULL;
2665 }
2666
2667 /**
2668 * Given the component name and returns the count of participation of contact.
2669 *
2670 * @param string $component
2671 * Input component name.
2672 * @param int $contactId
2673 * Input contact id.
2674 * @param string $tableName
2675 * Optional tableName if component is custom group.
2676 *
2677 * @return int
2678 * total number in database
2679 */
2680 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2681 $object = NULL;
2682 switch ($component) {
2683 case 'tag':
2684 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2685
2686 case 'rel':
2687 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2688 CRM_Contact_BAO_Relationship::CURRENT,
2689 0, 1, 0,
2690 NULL, NULL,
2691 TRUE
2692 );
2693 return $result;
2694
2695 case 'group':
2696
2697 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE);
2698
2699 case 'log':
2700 if (CRM_Core_BAO_Log::useLoggingReport()) {
2701 return FALSE;
2702 }
2703 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2704
2705 case 'note':
2706 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2707
2708 case 'contribution':
2709 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2710
2711 case 'membership':
2712 return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE);
2713
2714 case 'participant':
2715 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2716
2717 case 'pledge':
2718 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2719
2720 case 'case':
2721 return CRM_Case_BAO_Case::caseCount($contactId);
2722
2723 case 'grant':
2724 return CRM_Grant_BAO_Grant::getContactGrantCount($contactId);
2725
2726 case 'activity':
2727 $input = array(
2728 'contact_id' => $contactId,
2729 'admin' => FALSE,
2730 'caseId' => NULL,
2731 'context' => 'activity',
2732 );
2733 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2734
2735 case 'mailing':
2736 $params = array('contact_id' => $contactId);
2737 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2738
2739 default:
2740 $custom = explode('_', $component);
2741 if ($custom['0'] = 'custom') {
2742 if (!$tableName) {
2743 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2744 }
2745 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2746 return CRM_Core_DAO::singleValueQuery($queryString);
2747 }
2748 }
2749 }
2750
2751 /**
2752 * Update contact greetings if an update has resulted in a custom field change.
2753 *
2754 * @param array $updatedFields
2755 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2756 * @param array $contactParams
2757 * Parameters known about the contact. At minimum array('contact_id' => x).
2758 * Fields in this array will take precedence over DB fields (so far only
2759 * in the case of greeting id fields).
2760 */
2761 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2762 $contactID = $contactParams['contact_id'];
2763 CRM_Contact_BAO_Contact::ensureGreetingParamsAreSet($contactParams);
2764 $tokens = CRM_Contact_BAO_Contact_Utils::getTokensRequiredForContactGreetings($contactParams);
2765 if (!empty($tokens['all']['contact'])) {
2766 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2767 if (!empty($affectedTokens)) {
2768 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2769 $contact = new CRM_Contact_BAO_Contact();
2770 $contact->id = $contactID;
2771 CRM_Contact_BAO_Contact::processGreetings($contact);
2772 }
2773 }
2774 }
2775
2776 /**
2777 * Process greetings and cache.
2778 *
2779 * @param object $contact
2780 * Contact object after save.
2781 */
2782 public static function processGreetings(&$contact) {
2783
2784 //@todo this function does a lot of unnecessary loading.
2785 // ensureGreetingParamsAreSet now makes sure that the contact is
2786 // loaded and using updateGreetingsOnTokenFieldChange
2787 // allows us the possibility of only doing an update if required.
2788
2789 // The contact object has not always required the
2790 // fields that are required to calculate greetings
2791 // so we need to retrieve it again.
2792 if ($contact->_query !== FALSE) {
2793 $contact->find(TRUE);
2794 }
2795
2796 // store object values to an array
2797 $contactDetails = array();
2798 CRM_Core_DAO::storeValues($contact, $contactDetails);
2799 $contactDetails = array(array($contact->id => $contactDetails));
2800
2801 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2802 $updateQueryString = array();
2803
2804 //cache email and postal greeting to greeting display
2805 if ($contact->email_greeting_custom != 'null' && $contact->email_greeting_custom) {
2806 $emailGreetingString = $contact->email_greeting_custom;
2807 }
2808 elseif ($contact->email_greeting_id != 'null' && $contact->email_greeting_id) {
2809 // the filter value for Individual contact type is set to 1
2810 $filter = array(
2811 'contact_type' => $contact->contact_type,
2812 'greeting_type' => 'email_greeting',
2813 );
2814
2815 $emailGreeting = CRM_Core_PseudoConstant::greeting($filter);
2816 $emailGreetingString = $emailGreeting[$contact->email_greeting_id];
2817 $updateQueryString[] = " email_greeting_custom = NULL ";
2818 }
2819 else {
2820 if ($contact->email_greeting_custom) {
2821 $updateQueryString[] = " email_greeting_display = NULL ";
2822 }
2823 }
2824
2825 if ($emailGreetingString) {
2826 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2827 $contactDetails,
2828 $contact->id,
2829 'CRM_Contact_BAO_Contact'
2830 );
2831 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2832 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2833 }
2834
2835 //postal greetings
2836 if ($contact->postal_greeting_custom != 'null' && $contact->postal_greeting_custom) {
2837 $postalGreetingString = $contact->postal_greeting_custom;
2838 }
2839 elseif ($contact->postal_greeting_id != 'null' && $contact->postal_greeting_id) {
2840 $filter = array(
2841 'contact_type' => $contact->contact_type,
2842 'greeting_type' => 'postal_greeting',
2843 );
2844 $postalGreeting = CRM_Core_PseudoConstant::greeting($filter);
2845 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id];
2846 $updateQueryString[] = " postal_greeting_custom = NULL ";
2847 }
2848 else {
2849 if ($contact->postal_greeting_custom) {
2850 $updateQueryString[] = " postal_greeting_display = NULL ";
2851 }
2852 }
2853
2854 if ($postalGreetingString) {
2855 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2856 $contactDetails,
2857 $contact->id,
2858 'CRM_Contact_BAO_Contact'
2859 );
2860 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2861 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2862 }
2863
2864 // addressee
2865 if ($contact->addressee_custom != 'null' && $contact->addressee_custom) {
2866 $addresseeString = $contact->addressee_custom;
2867 }
2868 elseif ($contact->addressee_id != 'null' && $contact->addressee_id) {
2869 $filter = array(
2870 'contact_type' => $contact->contact_type,
2871 'greeting_type' => 'addressee',
2872 );
2873
2874 $addressee = CRM_Core_PseudoConstant::greeting($filter);
2875 $addresseeString = $addressee[$contact->addressee_id];
2876 $updateQueryString[] = " addressee_custom = NULL ";
2877 }
2878 else {
2879 if ($contact->addressee_custom) {
2880 $updateQueryString[] = " addressee_display = NULL ";
2881 }
2882 }
2883
2884 if ($addresseeString) {
2885 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2886 $contactDetails,
2887 $contact->id,
2888 'CRM_Contact_BAO_Contact'
2889 );
2890 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2891 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2892 }
2893
2894 if (!empty($updateQueryString)) {
2895 $updateQueryString = implode(',', $updateQueryString);
2896 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2897 CRM_Core_DAO::executeQuery($queryString);
2898 }
2899 }
2900
2901 /**
2902 * Retrieve loc block ids w/ given condition.
2903 *
2904 * @param int $contactId
2905 * Contact id.
2906 * @param array $criteria
2907 * Key => value pair which should be.
2908 * fulfill by return record ids.
2909 * @param string $condOperator
2910 * Operator use for grouping multiple conditions.
2911 *
2912 * @return array
2913 * loc block ids which fulfill condition.
2914 */
2915 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2916 $locBlockIds = array();
2917 if (!$contactId) {
2918 return $locBlockIds;
2919 }
2920
2921 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2922 $name = strtolower($block);
2923 $className = "CRM_Core_DAO_$block";
2924 $blockDAO = new $className();
2925
2926 // build the condition.
2927 if (is_array($criteria)) {
2928 $fields = $blockDAO->fields();
2929 $conditions = array();
2930 foreach ($criteria as $field => $value) {
2931 if (array_key_exists($field, $fields)) {
2932 $cond = "( $field = $value )";
2933 // value might be zero or null.
2934 if (!$value || strtolower($value) == 'null') {
2935 $cond = "( $field = 0 OR $field IS NULL )";
2936 }
2937 $conditions[] = $cond;
2938 }
2939 }
2940 if (!empty($conditions)) {
2941 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2942 }
2943 }
2944
2945 $blockDAO->contact_id = $contactId;
2946 $blockDAO->find();
2947 while ($blockDAO->fetch()) {
2948 $locBlockIds[$name][] = $blockDAO->id;
2949 }
2950 $blockDAO->free();
2951 }
2952
2953 return $locBlockIds;
2954 }
2955
2956 /**
2957 * Build context menu items.
2958 *
2959 * @param int $contactId
2960 *
2961 * @return array
2962 * Array of context menu for logged in user.
2963 */
2964 public static function contextMenu($contactId = NULL) {
2965 $menu = array(
2966 'view' => array(
2967 'title' => ts('View Contact'),
2968 'weight' => 0,
2969 'ref' => 'view-contact',
2970 'class' => 'no-popup',
2971 'key' => 'view',
2972 'permissions' => array('view all contacts'),
2973 ),
2974 'add' => array(
2975 'title' => ts('Edit Contact'),
2976 'weight' => 0,
2977 'ref' => 'edit-contact',
2978 'class' => 'no-popup',
2979 'key' => 'add',
2980 'permissions' => array('edit all contacts'),
2981 ),
2982 'delete' => array(
2983 'title' => ts('Delete Contact'),
2984 'weight' => 0,
2985 'ref' => 'delete-contact',
2986 'key' => 'delete',
2987 'permissions' => array('access deleted contacts', 'delete contacts'),
2988 ),
2989 'contribution' => array(
2990 'title' => ts('Add Contribution'),
2991 'weight' => 5,
2992 'ref' => 'new-contribution',
2993 'key' => 'contribution',
2994 'tab' => 'contribute',
2995 'component' => 'CiviContribute',
2996 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2997 'reset=1&action=add&context=contribution'
2998 ),
2999 'permissions' => array(
3000 'access CiviContribute',
3001 'edit contributions',
3002 ),
3003 ),
3004 'participant' => array(
3005 'title' => ts('Register for Event'),
3006 'weight' => 10,
3007 'ref' => 'new-participant',
3008 'key' => 'participant',
3009 'tab' => 'participant',
3010 'component' => 'CiviEvent',
3011 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3012 'permissions' => array(
3013 'access CiviEvent',
3014 'edit event participants',
3015 ),
3016 ),
3017 'activity' => array(
3018 'title' => ts('Record Activity'),
3019 'weight' => 35,
3020 'ref' => 'new-activity',
3021 'key' => 'activity',
3022 'permissions' => array('edit all contacts'),
3023 ),
3024 'pledge' => array(
3025 'title' => ts('Add Pledge'),
3026 'weight' => 15,
3027 'ref' => 'new-pledge',
3028 'key' => 'pledge',
3029 'tab' => 'pledge',
3030 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
3031 'reset=1&action=add&context=pledge'
3032 ),
3033 'component' => 'CiviPledge',
3034 'permissions' => array(
3035 'access CiviPledge',
3036 'edit pledges',
3037 ),
3038 ),
3039 'membership' => array(
3040 'title' => ts('Add Membership'),
3041 'weight' => 20,
3042 'ref' => 'new-membership',
3043 'key' => 'membership',
3044 'tab' => 'member',
3045 'component' => 'CiviMember',
3046 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
3047 'reset=1&action=add&context=membership'
3048 ),
3049 'permissions' => array(
3050 'access CiviMember',
3051 'edit memberships',
3052 ),
3053 ),
3054 'case' => array(
3055 'title' => ts('Add Case'),
3056 'weight' => 25,
3057 'ref' => 'new-case',
3058 'key' => 'case',
3059 'tab' => 'case',
3060 'component' => 'CiviCase',
3061 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3062 'permissions' => array('add cases'),
3063 ),
3064 'grant' => array(
3065 'title' => ts('Add Grant'),
3066 'weight' => 26,
3067 'ref' => 'new-grant',
3068 'key' => 'grant',
3069 'tab' => 'grant',
3070 'component' => 'CiviGrant',
3071 'href' => CRM_Utils_System::url('civicrm/contact/view/grant',
3072 'reset=1&action=add&context=grant'
3073 ),
3074 'permissions' => array('edit grants'),
3075 ),
3076 'rel' => array(
3077 'title' => ts('Add Relationship'),
3078 'weight' => 30,
3079 'ref' => 'new-relationship',
3080 'key' => 'rel',
3081 'tab' => 'rel',
3082 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
3083 'reset=1&action=add'
3084 ),
3085 'permissions' => array('edit all contacts'),
3086 ),
3087 'note' => array(
3088 'title' => ts('Add Note'),
3089 'weight' => 40,
3090 'ref' => 'new-note',
3091 'key' => 'note',
3092 'tab' => 'note',
3093 'class' => 'medium-popup',
3094 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
3095 'reset=1&action=add'
3096 ),
3097 'permissions' => array('edit all contacts'),
3098 ),
3099 'email' => array(
3100 'title' => ts('Send an Email'),
3101 'weight' => 45,
3102 'ref' => 'new-email',
3103 'key' => 'email',
3104 'permissions' => array('view all contacts'),
3105 ),
3106 'group' => array(
3107 'title' => ts('Add to Group'),
3108 'weight' => 50,
3109 'ref' => 'group-add-contact',
3110 'key' => 'group',
3111 'tab' => 'group',
3112 'permissions' => array('edit groups'),
3113 ),
3114 'tag' => array(
3115 'title' => ts('Tag Contact'),
3116 'weight' => 55,
3117 'ref' => 'tag-contact',
3118 'key' => 'tag',
3119 'tab' => 'tag',
3120 'permissions' => array('edit all contacts'),
3121 ),
3122 );
3123
3124 $menu['otherActions'] = array(
3125 'print' => array(
3126 'title' => ts('Print Summary'),
3127 'description' => ts('Printer-friendly view of this page.'),
3128 'weight' => 5,
3129 'ref' => 'crm-contact-print',
3130 'key' => 'print',
3131 'tab' => 'print',
3132 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3133 "reset=1&print=1"
3134 ),
3135 'class' => 'print',
3136 'icon' => 'crm-i fa-print',
3137 ),
3138 'vcard' => array(
3139 'title' => ts('vCard'),
3140 'description' => ts('vCard record for this contact.'),
3141 'weight' => 10,
3142 'ref' => 'crm-contact-vcard',
3143 'key' => 'vcard',
3144 'tab' => 'vcard',
3145 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3146 "reset=1"
3147 ),
3148 'class' => 'vcard',
3149 'icon' => 'crm-i fa-list-alt',
3150 ),
3151 );
3152
3153 if (CRM_Core_Permission::check('access Contact Dashboard')) {
3154 $menu['otherActions']['dashboard'] = array(
3155 'title' => ts('Contact Dashboard'),
3156 'description' => ts('Contact Dashboard'),
3157 'weight' => 15,
3158 'ref' => 'crm-contact-dashboard',
3159 'key' => 'dashboard',
3160 'tab' => 'dashboard',
3161 'class' => 'dashboard',
3162 // NOTE: As an alternative you can also build url on CMS specific way
3163 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3164 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id={$contactId}"),
3165 'icon' => 'crm-i fa-tachometer',
3166 );
3167 }
3168
3169 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3170 if ($uid) {
3171 $menu['otherActions']['user-record'] = array(
3172 'title' => ts('User Record'),
3173 'description' => ts('User Record'),
3174 'weight' => 20,
3175 'ref' => 'crm-contact-user-record',
3176 'key' => 'user-record',
3177 'tab' => 'user-record',
3178 'class' => 'user-record',
3179 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
3180 'icon' => 'crm-i fa-user',
3181 );
3182 }
3183 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
3184 $menu['otherActions']['user-add'] = array(
3185 'title' => ts('Create User Record'),
3186 'description' => ts('Create User Record'),
3187 'weight' => 25,
3188 'ref' => 'crm-contact-user-add',
3189 'key' => 'user-add',
3190 'tab' => 'user-add',
3191 'class' => 'user-add',
3192 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3193 'icon' => 'crm-i fa-user-plus',
3194 );
3195 }
3196
3197 CRM_Utils_Hook::summaryActions($menu, $contactId);
3198 //1. check for component is active.
3199 //2. check for user permissions.
3200 //3. check for acls.
3201 //3. edit and view contact are directly accessible to user.
3202
3203 $aclPermissionedTasks = array(
3204 'view-contact',
3205 'edit-contact',
3206 'new-activity',
3207 'new-email',
3208 'group-add-contact',
3209 'tag-contact',
3210 'delete-contact',
3211 );
3212 $corePermission = CRM_Core_Permission::getPermission();
3213
3214 $contextMenu = array();
3215 foreach ($menu as $key => $values) {
3216 if ($key != 'otherActions') {
3217
3218 // user does not have necessary permissions.
3219 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3220 continue;
3221 }
3222 // build directly accessible action menu.
3223 if (in_array($values['ref'], array(
3224 'view-contact',
3225 'edit-contact',
3226 ))) {
3227 $contextMenu['primaryActions'][$key] = array(
3228 'title' => $values['title'],
3229 'ref' => $values['ref'],
3230 'class' => CRM_Utils_Array::value('class', $values),
3231 'key' => $values['key'],
3232 );
3233 continue;
3234 }
3235
3236 // finally get menu item for -more- action widget.
3237 $contextMenu['moreActions'][$values['weight']] = array(
3238 'title' => $values['title'],
3239 'ref' => $values['ref'],
3240 'href' => CRM_Utils_Array::value('href', $values),
3241 'tab' => CRM_Utils_Array::value('tab', $values),
3242 'class' => CRM_Utils_Array::value('class', $values),
3243 'key' => $values['key'],
3244 );
3245 }
3246 else {
3247 foreach ($values as $value) {
3248 // user does not have necessary permissions.
3249 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3250 continue;
3251 }
3252
3253 // finally get menu item for -more- action widget.
3254 $contextMenu['otherActions'][$value['weight']] = array(
3255 'title' => $value['title'],
3256 'ref' => $value['ref'],
3257 'href' => CRM_Utils_Array::value('href', $value),
3258 'tab' => CRM_Utils_Array::value('tab', $value),
3259 'class' => CRM_Utils_Array::value('class', $value),
3260 'icon' => CRM_Utils_Array::value('icon', $value),
3261 'key' => $value['key'],
3262 );
3263 }
3264 }
3265 }
3266
3267 ksort($contextMenu['moreActions']);
3268 ksort($contextMenu['otherActions']);
3269
3270 return $contextMenu;
3271 }
3272
3273 /**
3274 * Check if user has permissions to access items in action menu.
3275 *
3276 * @param array $aclPermissionedTasks
3277 * Array containing ACL related tasks.
3278 * @param string $corePermission
3279 * The permission of the user (edit or view or null).
3280 * @param array $menuOptions
3281 * Array containing params of the menu (title, href, etc).
3282 *
3283 * @return bool
3284 * TRUE if user has all permissions, FALSE if otherwise.
3285 */
3286 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3287 $componentName = CRM_Utils_Array::value('component', $menuOptions);
3288
3289 // if component action - make sure component is enable.
3290 if ($componentName && !in_array($componentName, CRM_Core_Config::singleton()->enableComponents)) {
3291 return FALSE;
3292 }
3293
3294 // make sure user has all required permissions.
3295 $hasAllPermissions = FALSE;
3296
3297 $permissions = CRM_Utils_Array::value('permissions', $menuOptions);
3298 if (!is_array($permissions) || empty($permissions)) {
3299 $hasAllPermissions = TRUE;
3300 }
3301
3302 // iterate for required permissions in given permissions array.
3303 if (!$hasAllPermissions) {
3304 $hasPermissions = 0;
3305 foreach ($permissions as $permission) {
3306 if (CRM_Core_Permission::check($permission)) {
3307 $hasPermissions++;
3308 }
3309 }
3310
3311 if (count($permissions) == $hasPermissions) {
3312 $hasAllPermissions = TRUE;
3313 }
3314
3315 // if still user does not have required permissions, check acl.
3316 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3317 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3318 $corePermission == CRM_Core_Permission::EDIT
3319 ) {
3320 $hasAllPermissions = TRUE;
3321 }
3322 elseif (in_array($menuOptions['ref'], array(
3323 'new-email',
3324 ))) {
3325 // grant permissions for these tasks.
3326 $hasAllPermissions = TRUE;
3327 }
3328 }
3329 }
3330
3331 return $hasAllPermissions;
3332 }
3333
3334 /**
3335 * Retrieve display name of contact that address is shared.
3336 *
3337 * This is based on $masterAddressId or $contactId .
3338 *
3339 * @param int $masterAddressId
3340 * Master id.
3341 * @param int $contactId
3342 * Contact id. (deprecated - do not use)
3343 *
3344 * @return string|null
3345 * the found display name or null.
3346 */
3347 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3348 $masterDisplayName = NULL;
3349 if (!$masterAddressId) {
3350 return $masterDisplayName;
3351 }
3352
3353 $sql = "
3354 SELECT display_name from civicrm_contact
3355 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3356 WHERE civicrm_address.id = " . $masterAddressId;
3357
3358 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3359 return $masterDisplayName;
3360 }
3361
3362 /**
3363 * Get the creation/modification times for a contact.
3364 *
3365 * @param int $contactId
3366 *
3367 * @return array
3368 * Dates - ('created_date' => $, 'modified_date' => $)
3369 */
3370 public static function getTimestamps($contactId) {
3371 $timestamps = CRM_Core_DAO::executeQuery(
3372 'SELECT created_date, modified_date
3373 FROM civicrm_contact
3374 WHERE id = %1',
3375 array(
3376 1 => array($contactId, 'Integer'),
3377 )
3378 );
3379 if ($timestamps->fetch()) {
3380 return array(
3381 'created_date' => $timestamps->created_date,
3382 'modified_date' => $timestamps->modified_date,
3383 );
3384 }
3385 else {
3386 return NULL;
3387 }
3388 }
3389
3390 /**
3391 * Get a list of triggers for the contact table.
3392 *
3393 * @see hook_civicrm_triggerInfo
3394 * @see CRM_Core_DAO::triggerRebuild
3395 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3396 *
3397 * @param $info
3398 * @param null $tableName
3399 */
3400 public static function triggerInfo(&$info, $tableName = NULL) {
3401 //during upgrade, first check for valid version and then create triggers
3402 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3403 if (CRM_Core_Config::isUpgradeMode()) {
3404 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
3405 //if current version is less than 4.3.alpha1 dont create below triggers
3406 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3407 return;
3408 }
3409 }
3410
3411 // Modifications to these records should update the contact timestamps.
3412 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3413 ->setRelations(array(
3414 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3415 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3416 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3417 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3418 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3419 )
3420 )
3421 ->alterTriggerInfo($info, $tableName);
3422
3423 // Update phone table to populate phone_numeric field
3424 if (!$tableName || $tableName == 'civicrm_phone') {
3425 // Define stored sql function needed for phones
3426 $sqlTriggers = Civi::service('sql_triggers');
3427 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3428 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3429 $info[] = array(
3430 'table' => array('civicrm_phone'),
3431 'when' => 'BEFORE',
3432 'event' => array('INSERT', 'UPDATE'),
3433 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3434 );
3435 }
3436 }
3437
3438 /**
3439 * Check if contact is being used in civicrm_domain based on $contactId.
3440 *
3441 * @param int $contactId
3442 * Contact id.
3443 *
3444 * @return bool
3445 * true if present else false.
3446 */
3447 public static function checkDomainContact($contactId) {
3448 if (!$contactId) {
3449 return FALSE;
3450 }
3451 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3452
3453 if ($domainId) {
3454 return TRUE;
3455 }
3456 else {
3457 return FALSE;
3458 }
3459 }
3460
3461 /**
3462 * Get options for a given contact field.
3463 *
3464 * @see CRM_Core_DAO::buildOptions
3465 *
3466 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3467 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3468 *
3469 * @param string $fieldName
3470 * @param string $context
3471 * @see CRM_Core_DAO::buildOptionsContext
3472 * @param array $props
3473 * whatever is known about this dao object.
3474 *
3475 * @return array|bool
3476 */
3477 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3478 $params = array();
3479 // Special logic for fields whose options depend on context or properties
3480 switch ($fieldName) {
3481 case 'contact_sub_type':
3482 if (!empty($props['contact_type'])) {
3483 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3484 }
3485 break;
3486
3487 case 'contact_type':
3488 if ($context == 'search') {
3489 // CRM-15495 - EntityRef filters and basic search forms expect this format
3490 // FIXME: Search builder does not
3491 return CRM_Contact_BAO_ContactType::getSelectElements();
3492 }
3493 break;
3494
3495 // The contact api supports some related entities so we'll honor that by fetching their options
3496 case 'group_id':
3497 case 'group':
3498 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3499
3500 case 'tag_id':
3501 case 'tag':
3502 $props['entity_table'] = 'civicrm_contact';
3503 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3504
3505 case 'state_province_id':
3506 case 'state_province':
3507 case 'state_province_name':
3508 case 'country_id':
3509 case 'country':
3510 case 'county_id':
3511 case 'worldregion':
3512 case 'worldregion_id':
3513 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3514
3515 }
3516 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3517 }
3518
3519 /**
3520 * Delete a contact-related object that has an 'is_primary' field.
3521 *
3522 * Ensures that is_primary gets assigned to another object if available
3523 * Also calls pre/post hooks
3524 *
3525 * @param string $type
3526 * @param int $id
3527 * @return bool
3528 */
3529 public static function deleteObjectWithPrimary($type, $id) {
3530 if (!$id || !is_numeric($id)) {
3531 return FALSE;
3532 }
3533 $daoName = "CRM_Core_DAO_$type";
3534 $obj = new $daoName();
3535 $obj->id = $id;
3536 $obj->find();
3537 $hookParams = [];
3538 if ($obj->fetch()) {
3539 CRM_Utils_Hook::pre('delete', $type, $id, $hookParams);
3540 $contactId = $obj->contact_id;
3541 $obj->delete();
3542 }
3543 else {
3544 return FALSE;
3545 }
3546 // is_primary is only relavent if this field belongs to a contact
3547 if ($contactId) {
3548 $dao = new $daoName();
3549 $dao->contact_id = $contactId;
3550 $dao->is_primary = 1;
3551 // Pick another record to be primary (if one isn't already)
3552 if (!$dao->find(TRUE)) {
3553 $dao->is_primary = 0;
3554 $dao->find();
3555 if ($dao->fetch()) {
3556 $dao->is_primary = 1;
3557 $dao->save();
3558 }
3559 }
3560 }
3561 CRM_Utils_Hook::post('delete', $type, $id, $obj);
3562 $obj->free();
3563 return TRUE;
3564 }
3565
3566 /**
3567 * @inheritDoc
3568 */
3569 public function addSelectWhereClause() {
3570 // We always return an array with these keys, even if they are empty,
3571 // because this tells the query builder that we have considered these fields for acls
3572 $clauses = array(
3573 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3574 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? array() : array('!= 1'),
3575 );
3576 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3577 return $clauses;
3578 }
3579
3580 /**
3581 * Get any existing duplicate contacts based on the input parameters.
3582 *
3583 * @param array $input
3584 * Input parameters to be matched.
3585 * @param string $contactType
3586 * @param string $rule
3587 * - Supervised
3588 * - Unsupervised
3589 * @param $excludedContactIDs
3590 * An array of ids not to be included in the results.
3591 * @param bool $checkPermissions
3592 * @param int $ruleGroupID
3593 * ID of the rule group to be used if an override is desirable.
3594 * @param array $contextParams
3595 * The context if relevant, eg. ['event_id' => X]
3596 *
3597 * @return array
3598 */
3599 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3600 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3601 $dedupeParams['check_permission'] = $checkPermissions;
3602 $dedupeParams['contact_type'] = $contactType;
3603 $dedupeParams['rule'] = $rule;
3604 $dedupeParams['rule_group_id'] = $ruleGroupID;
3605 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3606 $dedupeResults['ids'] = [];
3607 $dedupeResults['handled'] = FALSE;
3608 CRM_Utils_Hook::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3609 if (!$dedupeResults['handled']) {
3610 $dedupeResults['ids'] = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3611 }
3612 return $dedupeResults['ids'];
3613 }
3614
3615 /**
3616 * Get the first duplicate contacts based on the input parameters.
3617 *
3618 * @param array $input
3619 * Input parameters to be matched.
3620 * @param string $contactType
3621 * @param string $rule
3622 * - Supervised
3623 * - Unsupervised
3624 * @param $excludedContactIDs
3625 * An array of ids not to be included in the results.
3626 * @param bool $checkPermissions
3627 * @param int $ruleGroupID
3628 * ID of the rule group to be used if an override is desirable.
3629 * @param array $contextParams
3630 * The context if relevant, eg. ['event_id' => X]
3631 *
3632 * @return int|NULL
3633 */
3634 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3635 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3636 if (empty($ids)) {
3637 return NULL;
3638 }
3639 return $ids[0];
3640 }
3641
3642 /**
3643 * Check if a field is associated with an entity that has a location type.
3644 *
3645 * (ie. is an address, phone, email etc field).
3646 *
3647 * @param string $fieldTitle
3648 * Title of the field (not the name - create a new function for that if required).
3649 *
3650 * @return bool
3651 */
3652 public static function isFieldHasLocationType($fieldTitle) {
3653 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3654 if ($field['title'] === $fieldTitle) {
3655 return CRM_Utils_Array::value('hasLocationType', $field);
3656 }
3657 }
3658 return FALSE;
3659 }
3660
3661 /**
3662 * @param array $appendProfiles
3663 * Name of profile(s) to append to each link.
3664 *
3665 * @return array
3666 */
3667 public static function getEntityRefCreateLinks($appendProfiles = []) {
3668 // You'd think that "create contacts" would be the permission to check,
3669 // But new contact popups are profile forms and those use their own permissions.
3670 if (!CRM_Core_Permission::check([['profile create', 'profile listings and forms']])) {
3671 return FALSE;
3672 }
3673 $profiles = [];
3674 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $contactType) {
3675 $profiles[] = 'new_' . strtolower($contactType);
3676 }
3677 $retrieved = civicrm_api3('uf_group', 'get', [
3678 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3679 'is_active' => 1,
3680 ]);
3681 $links = $append = [];
3682 if (!empty($retrieved['values'])) {
3683 $icons = [
3684 'individual' => 'fa-user',
3685 'organization' => 'fa-building',
3686 'household' => 'fa-home',
3687 ];
3688 foreach ($retrieved['values'] as $id => $profile) {
3689 if (in_array($profile['name'], $profiles)) {
3690 $links[] = array(
3691 'label' => $profile['title'],
3692 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3693 NULL, NULL, FALSE, FALSE, TRUE),
3694 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3695 'icon' => CRM_Utils_Array::value(str_replace('new_', '', $profile['name']), $icons),
3696 );
3697 }
3698 else {
3699 $append[] = $id;
3700 }
3701 }
3702 foreach ($append as $id) {
3703 foreach ($links as &$link) {
3704 $link['url'] .= ",$id";
3705 }
3706 }
3707 }
3708 return $links;
3709 }
3710
3711 /**
3712 * @return array
3713 */
3714 public static function getEntityRefFilters() {
3715 return [
3716 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3717 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3718 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3719 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3720 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3721 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3722 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3723 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3724 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3725 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3726 ];
3727 }
3728
3729 }