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