Merge pull request #16772 from eileenmcnaughton/mem_tax
[civicrm-core.git] / CRM / Core / BAO / UFMatch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * The basic class that interfaces with the external user framework.
20 */
21 class CRM_Core_BAO_UFMatch extends CRM_Core_DAO_UFMatch {
22
23 /**
24 * Create UF Match, Note that this function is here in it's simplest form @ the moment
25 *
26 * @param $params
27 *
28 * @return \CRM_Core_DAO_UFMatch
29 */
30 public static function create($params) {
31 $hook = empty($params['id']) ? 'create' : 'edit';
32 CRM_Utils_Hook::pre($hook, 'UFMatch', CRM_Utils_Array::value('id', $params), $params);
33 if (empty($params['domain_id'])) {
34 $params['domain_id'] = CRM_Core_Config::domainID();
35 }
36 $dao = new CRM_Core_DAO_UFMatch();
37 $dao->copyValues($params);
38 // Fixme: this function cannot update records
39 if (!$dao->find(TRUE)) {
40 $dao->save();
41 Civi::$statics[__CLASS__][$params['domain_id']][(int) $dao->contact_id] = (int) $dao->uf_id;
42 CRM_Utils_Hook::post($hook, 'UFMatch', $dao->id, $dao);
43 }
44 return $dao;
45 }
46
47 /**
48 * Given a UF user object, make sure there is a contact
49 * object for this user. If the user has new values, we need
50 * to update the CRM DB with the new values
51 *
52 * @param Object $user
53 * The drupal user object.
54 * @param bool $update
55 * Has the user object been edited.
56 * @param $uf
57 *
58 * @param $ctype
59 * @param bool $isLogin
60 */
61 public static function synchronize(&$user, $update, $uf, $ctype, $isLogin = FALSE) {
62 $userSystem = CRM_Core_Config::singleton()->userSystem;
63 $session = CRM_Core_Session::singleton();
64 if (!is_object($session)) {
65 CRM_Core_Error::fatal('wow, session is not an object?');
66 return;
67 }
68
69 $userSystemID = $userSystem->getBestUFID($user);
70 $uniqId = $userSystem->getBestUFUniqueIdentifier($user);
71
72 // if the id of the object is zero (true for anon users in drupal)
73 // have we already processed this user, if so early
74 // return.
75 $userID = $session->get('userID');
76 $ufID = $session->get('ufID');
77
78 if (!$update && $ufID == $userSystemID) {
79 return;
80 }
81
82 //check do we have logged in user.
83 $isUserLoggedIn = CRM_Utils_System::isUserLoggedIn();
84
85 // reset the session if we are a different user
86 if ($ufID && $ufID != $userSystemID) {
87 $session->reset();
88
89 //get logged in user ids, and set to session.
90 if ($isUserLoggedIn) {
91 $userIds = self::getUFValues();
92 $session->set('ufID', CRM_Utils_Array::value('uf_id', $userIds, ''));
93 $session->set('userID', CRM_Utils_Array::value('contact_id', $userIds, ''));
94 $session->set('ufUniqID', CRM_Utils_Array::value('uf_name', $userIds, ''));
95 }
96 }
97
98 // return early
99 if ($userSystemID == 0) {
100 return;
101 }
102
103 $ufmatch = self::synchronizeUFMatch($user, $userSystemID, $uniqId, $uf, NULL, $ctype, $isLogin);
104 if (!$ufmatch) {
105 return;
106 }
107
108 //make sure we have session w/ consistent ids.
109 $ufID = $ufmatch->uf_id;
110 $userID = $ufmatch->contact_id;
111 $ufUniqID = '';
112 if ($isUserLoggedIn) {
113 $loggedInUserUfID = CRM_Utils_System::getLoggedInUfID();
114 //are we processing logged in user.
115 if ($loggedInUserUfID && $loggedInUserUfID != $ufID) {
116 $userIds = self::getUFValues($loggedInUserUfID);
117 $ufID = CRM_Utils_Array::value('uf_id', $userIds, '');
118 $userID = CRM_Utils_Array::value('contact_id', $userIds, '');
119 $ufUniqID = CRM_Utils_Array::value('uf_name', $userIds, '');
120 }
121 }
122
123 //set user ids to session.
124 $session->set('ufID', $ufID);
125 $session->set('userID', $userID);
126 $session->set('ufUniqID', $ufUniqID);
127
128 // add current contact to recently viewed
129 if ($ufmatch->contact_id) {
130 list($displayName, $contactImage, $contactType, $contactSubtype, $contactImageUrl)
131 = CRM_Contact_BAO_Contact::getDisplayAndImage($ufmatch->contact_id, TRUE, TRUE);
132
133 $otherRecent = [
134 'imageUrl' => $contactImageUrl,
135 'subtype' => $contactSubtype,
136 'editUrl' => CRM_Utils_System::url('civicrm/contact/add', "reset=1&action=update&cid={$ufmatch->contact_id}"),
137 ];
138
139 CRM_Utils_Recent::add($displayName,
140 CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$ufmatch->contact_id}"),
141 $ufmatch->contact_id,
142 $contactType,
143 $ufmatch->contact_id,
144 $displayName,
145 $otherRecent
146 );
147 }
148 }
149
150 /**
151 * Synchronize the object with the UF Match entry. Can be called stand-alone from
152 * the drupalUsers script
153 *
154 * @param Object $user
155 * The drupal user object.
156 * @param string $userKey
157 * The id of the user from the uf object.
158 * @param string $uniqId
159 * The OpenID of the user.
160 * @param string $uf
161 * The name of the user framework.
162 * @param int $status
163 * Returns the status if user created or already exits (used for CMS sync).
164 * @param string $ctype
165 * contact type
166 * @param bool $isLogin
167 *
168 * @return CRM_Core_DAO_UFMatch|bool
169 */
170 public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = NULL, $ctype = NULL, $isLogin = FALSE) {
171 $config = CRM_Core_Config::singleton();
172
173 if (!CRM_Utils_Rule::email($uniqId)) {
174 $retVal = $status ? NULL : FALSE;
175 return $retVal;
176 }
177
178 $newContact = FALSE;
179
180 // make sure that a contact id exists for this user id
181 $ufmatch = new CRM_Core_DAO_UFMatch();
182 $ufmatch->domain_id = CRM_Core_Config::domainID();
183 $ufmatch->uf_id = $userKey;
184
185 if (!$ufmatch->find(TRUE)) {
186 $transaction = new CRM_Core_Transaction();
187
188 $dao = NULL;
189 if (!empty($_POST) && !$isLogin) {
190 $params = $_POST;
191 $params['email'] = $uniqId;
192
193 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, 'Individual', 'Unsupervised', [], FALSE);
194
195 if (!empty($ids) && Civi::settings()->get('uniq_email_per_site')) {
196 // restrict dupeIds to ones that belong to current domain/site.
197 $siteContacts = CRM_Core_BAO_Domain::getContactList();
198 foreach ($ids as $index => $dupeId) {
199 if (!in_array($dupeId, $siteContacts)) {
200 unset($ids[$index]);
201 }
202 }
203 // re-index the array
204 $ids = array_values($ids);
205 }
206 if (!empty($ids)) {
207 $dao = new CRM_Core_DAO();
208 $dao->contact_id = $ids[0];
209 }
210 }
211 else {
212 $dao = CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
213 }
214
215 $found = FALSE;
216 if ($dao) {
217 // ensure there does not exists a contact_id / uf_id pair
218 // in the DB. This might be due to multiple emails per contact
219 // CRM-9091
220 $sql = "
221 SELECT id
222 FROM civicrm_uf_match
223 WHERE contact_id = %1
224 AND domain_id = %2
225 ";
226 $params = [
227 1 => [$dao->contact_id, 'Integer'],
228 2 => [CRM_Core_Config::domainID(), 'Integer'],
229 ];
230 $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
231
232 if (!$conflict) {
233 $found = TRUE;
234 $ufmatch->contact_id = $dao->contact_id;
235 $ufmatch->uf_name = $uniqId;
236 }
237 }
238
239 if (!$found) {
240 // Not sure why we're testing for this. Is there ever a case
241 // in which $user is not an object?
242 if (is_object($user)) {
243 if ($config->userSystem->is_drupal) {
244 $primary_email = $uniqId;
245 }
246 elseif ($uf == 'WordPress') {
247 $primary_email = $user->user_email;
248 }
249 else {
250 $primary_email = $user->email;
251 }
252 $params = ['email-Primary' => $primary_email];
253 }
254
255 if ($ctype == 'Organization') {
256 $params['organization_name'] = $uniqId;
257 }
258 elseif ($ctype == 'Household') {
259 $params['household_name'] = $uniqId;
260 }
261
262 if (!$ctype) {
263 $ctype = "Individual";
264 }
265 $params['contact_type'] = $ctype;
266
267 // extract first / middle / last name
268 // for joomla
269 if ($uf == 'Joomla' && $user->name) {
270 CRM_Utils_String::extractName($user->name, $params);
271 }
272
273 if ($uf == 'WordPress') {
274 if ($user->first_name) {
275 $params['first_name'] = $user->first_name;
276 }
277
278 if ($user->last_name) {
279 $params['last_name'] = $user->last_name;
280 }
281 }
282
283 $contactId = CRM_Contact_BAO_Contact::createProfileContact($params);
284 $ufmatch->contact_id = $contactId;
285 $ufmatch->uf_name = $uniqId;
286 }
287
288 // check that there are not two CMS IDs matching the same CiviCRM contact - this happens when a civicrm
289 // user has two e-mails and there is a cms match for each of them
290 // the gets rid of the nasty fata error but still reports the error
291 $sql = "
292 SELECT uf_id
293 FROM civicrm_uf_match
294 WHERE ( contact_id = %1
295 OR uf_name = %2
296 OR uf_id = %3 )
297 AND domain_id = %4
298 ";
299 $params = [
300 1 => [$ufmatch->contact_id, 'Integer'],
301 2 => [$ufmatch->uf_name, 'String'],
302 3 => [$ufmatch->uf_id, 'Integer'],
303 4 => [$ufmatch->domain_id, 'Integer'],
304 ];
305
306 $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
307
308 if (!$conflict) {
309 $ufmatch = CRM_Core_BAO_UFMatch::create((array) $ufmatch);
310 $newContact = TRUE;
311 $transaction->commit();
312 }
313 else {
314 $msg = ts("Contact ID %1 is a match for %2 user %3 but has already been matched to %4",
315 [
316 1 => $ufmatch->contact_id,
317 2 => $uf,
318 3 => $ufmatch->uf_id,
319 4 => $conflict,
320 ]
321 );
322 unset($conflict);
323 }
324 }
325
326 if ($status) {
327 return $newContact;
328 }
329 else {
330 return $ufmatch;
331 }
332 }
333
334 /**
335 * Update the uf_name in the user object.
336 *
337 * @param int $contactId
338 * Id of the contact to update.
339 */
340 public static function updateUFName($contactId) {
341 if (!Civi::settings()->get('syncCMSEmail') || !$contactId) {
342 return;
343 }
344
345 $config = CRM_Core_Config::singleton();
346 $ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
347
348 if (!$ufName) {
349 return;
350 }
351
352 $update = FALSE;
353
354 // 1.do check for contact Id.
355 $ufmatch = new CRM_Core_DAO_UFMatch();
356 $ufmatch->contact_id = $contactId;
357 $ufmatch->domain_id = CRM_Core_Config::domainID();
358 if (!$ufmatch->find(TRUE)) {
359 return;
360 }
361 if ($ufmatch->uf_name != $ufName) {
362 $update = TRUE;
363 }
364
365 // CRM-6928
366 // 2.do check for duplicate ufName.
367 $ufDupeName = new CRM_Core_DAO_UFMatch();
368 $ufDupeName->uf_name = $ufName;
369 $ufDupeName->domain_id = CRM_Core_Config::domainID();
370 if ($ufDupeName->find(TRUE) &&
371 $ufDupeName->contact_id != $contactId
372 ) {
373 $update = FALSE;
374 }
375
376 if (!$update) {
377 return;
378 }
379
380 // save the updated ufmatch object
381 $ufmatch->uf_name = $ufName;
382 $ufmatch->save();
383 $config->userSystem->updateCMSName($ufmatch->uf_id, $ufName);
384 }
385
386 /**
387 * Update the email value for the contact and user profile.
388 *
389 * @param int $contactId
390 * Contact ID of the user.
391 * @param string $emailAddress
392 * Email to be modified for the user.
393 */
394 public static function updateContactEmail($contactId, $emailAddress) {
395 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
396 $emailAddress = $strtolower($emailAddress);
397
398 $ufmatch = new CRM_Core_DAO_UFMatch();
399 $ufmatch->contact_id = $contactId;
400 $ufmatch->domain_id = CRM_Core_Config::domainID();
401 if ($ufmatch->find(TRUE)) {
402 // Save the email in UF Match table
403 $ufmatch->uf_name = $emailAddress;
404 CRM_Core_BAO_UFMatch::create((array) $ufmatch);
405
406 // If CMS integration is disabled skip Civi email update if CMS user email is changed
407 if (Civi::settings()->get('syncCMSEmail') == FALSE) {
408 return;
409 }
410
411 //check if the primary email for the contact exists
412 //$contactDetails[1] - email
413 //$contactDetails[3] - email id
414 $contactDetails = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactId);
415
416 if (trim($contactDetails[1])) {
417 //update if record is found but different
418 $emailID = $contactDetails[3];
419 if (trim($contactDetails[1]) != $emailAddress) {
420 civicrm_api3('Email', 'create', [
421 'id' => $emailID,
422 'email' => $emailAddress,
423 ]);
424 }
425 }
426 else {
427 //else insert a new email record
428 $result = civicrm_api3('Email', 'create', [
429 'contact_id' => $contactId,
430 'email' => $emailAddress,
431 'is_primary' => 1,
432 ]);
433 $emailID = $result['id'];
434 }
435
436 CRM_Core_BAO_Log::register($contactId,
437 'civicrm_email',
438 $emailID
439 );
440 }
441 }
442
443 /**
444 * Delete the object records that are associated with this cms user.
445 *
446 * @param int $ufID
447 * Id of the user to delete.
448 */
449 public static function deleteUser($ufID) {
450 $ufmatch = new CRM_Core_DAO_UFMatch();
451
452 $ufmatch->uf_id = $ufID;
453 $ufmatch->domain_id = $domainId = CRM_Core_Config::domainID();
454 $ufmatch->delete();
455
456 // Flush cache
457 Civi::$statics[__CLASS__][$domainId] = [];
458 }
459
460 /**
461 * Get the contact_id given a uf_id.
462 *
463 * @param int $ufID
464 * Id of UF for which related contact_id is required.
465 *
466 * @return int|null
467 * contact_id on success, null otherwise
468 */
469 public static function getContactId($ufID) {
470 if (!$ufID) {
471 return NULL;
472 }
473 $domainId = CRM_Core_Config::domainID();
474
475 if (!isset(Civi::$statics[__CLASS__][$domainId])) {
476 Civi::$statics[__CLASS__][$domainId] = [];
477 }
478 $contactId = array_search($ufID, Civi::$statics[__CLASS__][$domainId]);
479 if ($contactId) {
480 return $contactId;
481 }
482 $ufmatch = new CRM_Core_DAO_UFMatch();
483 $ufmatch->uf_id = $ufID;
484 $ufmatch->domain_id = $domainId;
485 if ($ufmatch->find(TRUE)) {
486 $contactId = (int) $ufmatch->contact_id;
487 Civi::$statics[__CLASS__][$domainId][$contactId] = (int) $ufID;
488 return $contactId;
489 }
490 return NULL;
491 }
492
493 /**
494 * Get the uf_id given a contact_id.
495 *
496 * @param int $contactID
497 * ID of the contact for which related uf_id is required.
498 *
499 * @return int|null
500 * uf_id of the given contact_id on success, null otherwise
501 */
502 public static function getUFId($contactID) {
503 if (!$contactID) {
504 return NULL;
505 }
506 $domainId = CRM_Core_Config::domainID();
507 $contactID = (int) $contactID;
508
509 if (empty(Civi::$statics[__CLASS__][$domainId]) || !array_key_exists($contactID, Civi::$statics[__CLASS__][$domainId])) {
510 Civi::$statics[__CLASS__][$domainId][$contactID] = NULL;
511 $ufmatch = new CRM_Core_DAO_UFMatch();
512 $ufmatch->contact_id = $contactID;
513 $ufmatch->domain_id = $domainId;
514 if ($ufmatch->find(TRUE)) {
515 Civi::$statics[__CLASS__][$domainId][$contactID] = (int) $ufmatch->uf_id;
516 }
517 }
518 return Civi::$statics[__CLASS__][$domainId][$contactID];
519 }
520
521 /**
522 * @deprecated
523 * @return bool
524 */
525 public static function isEmptyTable() {
526 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
527 $sql = "SELECT count(id) FROM civicrm_uf_match";
528 return CRM_Core_DAO::singleValueQuery($sql) > 0 ? FALSE : TRUE;
529 }
530
531 /**
532 * Get the list of contact_id.
533 *
534 * @deprecated
535 * @return int
536 * contact_id on success, null otherwise
537 */
538 public static function getContactIDs() {
539 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
540 $id = [];
541 $dao = new CRM_Core_DAO_UFMatch();
542 $dao->find();
543 while ($dao->fetch()) {
544 $id[] = $dao->contact_id;
545 }
546 return $id;
547 }
548
549 /**
550 * See if this user exists, and if so, if they're allowed to login
551 *
552 * @deprecated
553 * @param int $openId
554 *
555 * @return bool
556 * true if allowed to login, false otherwise
557 */
558 public static function getAllowedToLogin($openId) {
559 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
560 $ufmatch = new CRM_Core_DAO_UFMatch();
561 $ufmatch->uf_name = $openId;
562 $ufmatch->allowed_to_login = 1;
563 if ($ufmatch->find(TRUE)) {
564 return TRUE;
565 }
566 return FALSE;
567 }
568
569 /**
570 * Get the next unused uf_id value, since the standalone UF doesn't
571 * have id's (it uses OpenIDs, which go in a different field)
572 *
573 * @deprecated
574 * @return int
575 * next highest unused value for uf_id
576 */
577 public static function getNextUfIdValue() {
578 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
579 $query = "SELECT MAX(uf_id)+1 AS next_uf_id FROM civicrm_uf_match";
580 $dao = CRM_Core_DAO::executeQuery($query);
581 if ($dao->fetch()) {
582 $ufId = $dao->next_uf_id;
583 }
584
585 if (!isset($ufId)) {
586 $ufId = 1;
587 }
588 return $ufId;
589 }
590
591 /**
592 * @param $email
593 * @deprecated
594 * @return bool
595 */
596 public static function isDuplicateUser($email) {
597 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
598 $session = CRM_Core_Session::singleton();
599 $contactID = $session->get('userID');
600 if (!empty($email) && isset($contactID)) {
601 $dao = new CRM_Core_DAO_UFMatch();
602 $dao->uf_name = $email;
603 if ($dao->find(TRUE) && $contactID != $dao->contact_id) {
604 return TRUE;
605 }
606 }
607 return FALSE;
608 }
609
610 /**
611 * Get uf match values for given uf id or logged in user.
612 *
613 * @param int $ufID
614 * Uf id.
615 *
616 * @return array
617 * uf values.
618 */
619 public static function getUFValues($ufID = NULL) {
620 if (!$ufID) {
621 //get logged in user uf id.
622 $ufID = CRM_Utils_System::getLoggedInUfID();
623 }
624 if (!$ufID) {
625 return [];
626 }
627
628 static $ufValues;
629 if ($ufID && !isset($ufValues[$ufID])) {
630 $ufmatch = new CRM_Core_DAO_UFMatch();
631 $ufmatch->uf_id = $ufID;
632 $ufmatch->domain_id = CRM_Core_Config::domainID();
633 if ($ufmatch->find(TRUE)) {
634 $ufValues[$ufID] = [
635 'uf_id' => $ufmatch->uf_id,
636 'uf_name' => $ufmatch->uf_name,
637 'contact_id' => $ufmatch->contact_id,
638 'domain_id' => $ufmatch->domain_id,
639 ];
640 }
641 }
642 return $ufValues[$ufID];
643 }
644
645 /**
646 * @inheritDoc
647 */
648 public function addSelectWhereClause() {
649 // Prevent default behavior of joining ACLs onto the contact_id field
650 $clauses = [];
651 CRM_Utils_Hook::selectWhereClause($this, $clauses);
652 return $clauses;
653 }
654
655 }