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