Merge pull request #9599 from colemanw/CRM-19812
[civicrm-core.git] / CRM / Core / BAO / UFMatch.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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) {
3eb59ab5
AS
257 // Not sure why we're testing for this. Is there ever a case
258 // in which $user is not an object?
6a488035 259 if (is_object($user)) {
3eb59ab5
AS
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);
6a488035
TO
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
353ffa53 300 $contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
6a488035 301 $ufmatch->contact_id = $contactId;
353ffa53 302 $ufmatch->uf_name = $uniqId;
6a488035
TO
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 = "
309SELECT uf_id
310FROM civicrm_uf_match
311WHERE ( contact_id = %1
312OR uf_name = %2
313OR uf_id = %3 )
314AND 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,
21dfd5f5 337 4 => $conflict,
6a488035
TO
338 )
339 );
340 unset($conflict);
341 }
342 }
343
344 if ($status) {
345 return $newContact;
346 }
347 else {
348 return $ufmatch;
349 }
350 }
351
352 /**
fe482240 353 * Update the uf_name in the user object.
6a488035 354 *
6a0b768e
TO
355 * @param int $contactId
356 * Id of the contact to update.
6a488035 357 */
00be9182 358 public static function updateUFName($contactId) {
6a488035
TO
359 if (!$contactId) {
360 return;
361 }
362 $config = CRM_Core_Config::singleton();
363 $ufName = CRM_Contact_BAO_Contact::getPrimaryEmail($contactId);
364
365 if (!$ufName) {
366 return;
367 }
368
369 $update = FALSE;
370
371 // 1.do check for contact Id.
353ffa53 372 $ufmatch = new CRM_Core_DAO_UFMatch();
6a488035 373 $ufmatch->contact_id = $contactId;
353ffa53 374 $ufmatch->domain_id = CRM_Core_Config::domainID();
6a488035
TO
375 if (!$ufmatch->find(TRUE)) {
376 return;
377 }
378 if ($ufmatch->uf_name != $ufName) {
379 $update = TRUE;
380 }
381
382 // CRM-6928
383 // 2.do check for duplicate ufName.
384 $ufDupeName = new CRM_Core_DAO_UFMatch();
385 $ufDupeName->uf_name = $ufName;
386 $ufDupeName->domain_id = CRM_Core_Config::domainID();
387 if ($ufDupeName->find(TRUE) &&
388 $ufDupeName->contact_id != $contactId
389 ) {
390 $update = FALSE;
391 }
392
393 if (!$update) {
394 return;
395 }
396
397 // save the updated ufmatch object
398 $ufmatch->uf_name = $ufName;
399 $ufmatch->save();
400 $config->userSystem->updateCMSName($ufmatch->uf_id, $ufName);
401 }
402
403 /**
fe482240 404 * Update the email value for the contact and user profile.
6a488035 405 *
5a4f6742
CW
406 * @param int $contactId
407 * Contact ID of the user.
8eedd10a 408 * @param string $emailAddress
6a0b768e 409 * Email to be modified for the user.
6a488035 410 */
00be9182 411 public static function updateContactEmail($contactId, $emailAddress) {
6a488035
TO
412 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
413 $emailAddress = $strtolower($emailAddress);
414
353ffa53 415 $ufmatch = new CRM_Core_DAO_UFMatch();
6a488035 416 $ufmatch->contact_id = $contactId;
353ffa53 417 $ufmatch->domain_id = CRM_Core_Config::domainID();
6a488035
TO
418 if ($ufmatch->find(TRUE)) {
419 // Save the email in UF Match table
420 $ufmatch->uf_name = $emailAddress;
421 CRM_Core_BAO_UFMatch::create((array) $ufmatch);
422
423 //check if the primary email for the contact exists
424 //$contactDetails[1] - email
425 //$contactDetails[3] - email id
426 $contactDetails = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactId);
427
428 if (trim($contactDetails[1])) {
429 $emailID = $contactDetails[3];
430 //update if record is found
431 $query = "UPDATE civicrm_email
432 SET email = %1
433 WHERE id = %2";
434 $p = array(
435 1 => array($emailAddress, 'String'),
436 2 => array($emailID, 'Integer'),
437 );
438 $dao = CRM_Core_DAO::executeQuery($query, $p);
439 }
440 else {
441 //else insert a new email record
353ffa53 442 $email = new CRM_Core_DAO_Email();
6a488035
TO
443 $email->contact_id = $contactId;
444 $email->is_primary = 1;
353ffa53 445 $email->email = $emailAddress;
6a488035
TO
446 $email->save();
447 $emailID = $email->id;
448 }
449
450 CRM_Core_BAO_Log::register($contactId,
451 'civicrm_email',
452 $emailID
453 );
454 }
455 }
456
457 /**
fe482240 458 * Delete the object records that are associated with this cms user.
6a488035 459 *
6a0b768e
TO
460 * @param int $ufID
461 * Id of the user to delete.
6a488035 462 */
00be9182 463 public static function deleteUser($ufID) {
6a488035
TO
464 $ufmatch = new CRM_Core_DAO_UFMatch();
465
466 $ufmatch->uf_id = $ufID;
467 $ufmatch->domain_id = CRM_Core_Config::domainID();
468 $ufmatch->delete();
469 }
470
471 /**
fe482240 472 * Get the contact_id given a uf_id.
6a488035 473 *
6a0b768e
TO
474 * @param int $ufID
475 * Id of UF for which related contact_id is required.
6a488035 476 *
a6c01b45
CW
477 * @return int
478 * contact_id on success, null otherwise
6a488035 479 */
00be9182 480 public static function getContactId($ufID) {
6a488035
TO
481 if (!isset($ufID)) {
482 return NULL;
483 }
484
485 $ufmatch = new CRM_Core_DAO_UFMatch();
486
487 $ufmatch->uf_id = $ufID;
488 $ufmatch->domain_id = CRM_Core_Config::domainID();
489 if ($ufmatch->find(TRUE)) {
490 return (int ) $ufmatch->contact_id;
491 }
492 return NULL;
493 }
494
495 /**
fe482240 496 * Get the uf_id given a contact_id.
6a488035 497 *
6a0b768e
TO
498 * @param int $contactID
499 * ID of the contact for which related uf_id is required.
6a488035 500 *
a6c01b45
CW
501 * @return int
502 * uf_id of the given contact_id on success, null otherwise
6a488035 503 */
00be9182 504 public static function getUFId($contactID) {
6a488035
TO
505 if (!isset($contactID)) {
506 return NULL;
507 }
508 $domain = CRM_Core_BAO_Domain::getDomain();
509 $ufmatch = new CRM_Core_DAO_UFMatch();
510
511 $ufmatch->contact_id = $contactID;
512 $ufmatch->domain_id = $domain->id;
513 if ($ufmatch->find(TRUE)) {
514 return $ufmatch->uf_id;
515 }
516 return NULL;
517 }
518
b5c2afd0
EM
519 /**
520 * @return bool
521 */
00be9182 522 public static function isEmptyTable() {
6a488035
TO
523 $sql = "SELECT count(id) FROM civicrm_uf_match";
524 return CRM_Core_DAO::singleValueQuery($sql) > 0 ? FALSE : TRUE;
525 }
526
527 /**
fe482240 528 * Get the list of contact_id.
6a488035
TO
529 *
530 *
a6c01b45
CW
531 * @return int
532 * contact_id on success, null otherwise
6a488035 533 */
00be9182 534 public static function getContactIDs() {
6a488035
TO
535 $id = array();
536 $dao = new CRM_Core_DAO_UFMatch();
537 $dao->find();
538 while ($dao->fetch()) {
539 $id[] = $dao->contact_id;
540 }
541 return $id;
542 }
543
544 /**
100fef9d 545 * See if this user exists, and if so, if they're allowed to login
6a488035
TO
546 *
547 *
100fef9d 548 * @param int $openId
2a6da8d7 549 *
a6c01b45
CW
550 * @return bool
551 * true if allowed to login, false otherwise
6a488035 552 */
00be9182 553 public static function getAllowedToLogin($openId) {
6a488035
TO
554 $ufmatch = new CRM_Core_DAO_UFMatch();
555 $ufmatch->uf_name = $openId;
556 $ufmatch->allowed_to_login = 1;
557 if ($ufmatch->find(TRUE)) {
558 return TRUE;
559 }
560 return FALSE;
561 }
562
563 /**
100fef9d 564 * Get the next unused uf_id value, since the standalone UF doesn't
6a488035
TO
565 * have id's (it uses OpenIDs, which go in a different field)
566 *
567 *
a6c01b45
CW
568 * @return int
569 * next highest unused value for uf_id
6a488035 570 */
00be9182 571 public static function getNextUfIdValue() {
6a488035
TO
572 $query = "SELECT MAX(uf_id)+1 AS next_uf_id FROM civicrm_uf_match";
573 $dao = CRM_Core_DAO::executeQuery($query);
574 if ($dao->fetch()) {
575 $ufId = $dao->next_uf_id;
576 }
577
578 if (!isset($ufId)) {
579 $ufId = 1;
580 }
581 return $ufId;
582 }
583
b5c2afd0
EM
584 /**
585 * @param $email
586 *
587 * @return bool
588 */
00be9182 589 public static function isDuplicateUser($email) {
6a488035
TO
590 $session = CRM_Core_Session::singleton();
591 $contactID = $session->get('userID');
592 if (!empty($email) && isset($contactID)) {
593 $dao = new CRM_Core_DAO_UFMatch();
594 $dao->uf_name = $email;
595 if ($dao->find(TRUE) && $contactID != $dao->contact_id) {
596 return TRUE;
597 }
598 }
599 return FALSE;
600 }
601
602 /**
603 * Get uf match values for given uf id or logged in user.
604 *
6a0b768e
TO
605 * @param int $ufID
606 * Uf id.
6a488035 607 *
77b97be7 608 * @return array
76e7a76c 609 * uf values.
77b97be7 610 */
00be9182 611 public static function getUFValues($ufID = NULL) {
6a488035
TO
612 if (!$ufID) {
613 //get logged in user uf id.
614 $ufID = CRM_Utils_System::getLoggedInUfID();
615 }
616 if (!$ufID) {
617 return array();
618 }
619
620 static $ufValues;
621 if ($ufID && !isset($ufValues[$ufID])) {
353ffa53
TO
622 $ufmatch = new CRM_Core_DAO_UFMatch();
623 $ufmatch->uf_id = $ufID;
6a488035
TO
624 $ufmatch->domain_id = CRM_Core_Config::domainID();
625 if ($ufmatch->find(TRUE)) {
626 $ufValues[$ufID] = array(
627 'uf_id' => $ufmatch->uf_id,
628 'uf_name' => $ufmatch->uf_name,
629 'contact_id' => $ufmatch->contact_id,
630 'domain_id' => $ufmatch->domain_id,
631 );
632 }
633 }
634 return $ufValues[$ufID];
635 }
96025800 636
d343069c
CW
637 /**
638 * @inheritDoc
639 */
20e41014 640 public function addSelectWhereClause() {
d343069c 641 // Prevent default behavior of joining ACLs onto the contact_id field
032346cc
CW
642 $clauses = array();
643 CRM_Utils_Hook::selectWhereClause($this, $clauses);
644 return $clauses;
d343069c
CW
645 }
646
6a488035 647}