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