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