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