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