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