Merge pull request #9599 from colemanw/CRM-19812
[civicrm-core.git] / CRM / Core / BAO / UFMatch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 if (!$dao->find(TRUE)) {
55 $dao->save();
56 }
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 *
67 * @param Object $user
68 * The drupal user object.
69 * @param bool $update
70 * Has the user object been edited.
71 * @param $uf
72 *
73 * @param $ctype
74 * @param bool $isLogin
75 */
76 public static function synchronize(&$user, $update, $uf, $ctype, $isLogin = FALSE) {
77 $userSystem = CRM_Core_Config::singleton()->userSystem;
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
84 $userSystemID = $userSystem->getBestUFID($user);
85 $uniqId = $userSystem->getBestUFUniqueIdentifier($user);
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
93 if (!$update && $ufID == $userSystemID) {
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
101 if ($ufID && $ufID != $userSystemID) {
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
114 if ($userSystemID == 0) {
115 return;
116 }
117
118 $ufmatch = self::synchronizeUFMatch($user, $userSystemID, $uniqId, $uf, NULL, $ctype, $isLogin);
119 if (!$ufmatch) {
120 return;
121 }
122
123 //make sure we have session w/ consistent ids.
124 $ufID = $ufmatch->uf_id;
125 $userID = $ufmatch->contact_id;
126 $ufUniqID = '';
127 if ($isUserLoggedIn) {
128 $loggedInUserUfID = CRM_Utils_System::getLoggedInUfID();
129 //are we processing logged in user.
130 if ($loggedInUserUfID && $loggedInUserUfID != $ufID) {
131 $userIds = self::getUFValues($loggedInUserUfID);
132 $ufID = CRM_Utils_Array::value('uf_id', $userIds, '');
133 $userID = CRM_Utils_Array::value('contact_id', $userIds, '');
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) {
145 list($displayName, $contactImage, $contactType, $contactSubtype, $contactImageUrl)
146 = CRM_Contact_BAO_Contact::getDisplayAndImage($ufmatch->contact_id, TRUE, TRUE);
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 *
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).
179 * @param string $ctype
180 * contact type
181 * @param bool $isLogin
182 *
183 * @return CRM_Core_DAO_UFMatch|bool
184 */
185 public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = NULL, $ctype = NULL, $isLogin = FALSE) {
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
196 $ufmatch = new CRM_Core_DAO_UFMatch();
197 $ufmatch->domain_id = CRM_Core_Config::domainID();
198 $ufmatch->uf_id = $userKey;
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
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 (!$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.
372 $ufmatch = new CRM_Core_DAO_UFMatch();
373 $ufmatch->contact_id = $contactId;
374 $ufmatch->domain_id = CRM_Core_Config::domainID();
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 /**
404 * Update the email value for the contact and user profile.
405 *
406 * @param int $contactId
407 * Contact ID of the user.
408 * @param string $emailAddress
409 * Email to be modified for the user.
410 */
411 public static function updateContactEmail($contactId, $emailAddress) {
412 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
413 $emailAddress = $strtolower($emailAddress);
414
415 $ufmatch = new CRM_Core_DAO_UFMatch();
416 $ufmatch->contact_id = $contactId;
417 $ufmatch->domain_id = CRM_Core_Config::domainID();
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
442 $email = new CRM_Core_DAO_Email();
443 $email->contact_id = $contactId;
444 $email->is_primary = 1;
445 $email->email = $emailAddress;
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 /**
458 * Delete the object records that are associated with this cms user.
459 *
460 * @param int $ufID
461 * Id of the user to delete.
462 */
463 public static function deleteUser($ufID) {
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 /**
472 * Get the contact_id given a uf_id.
473 *
474 * @param int $ufID
475 * Id of UF for which related contact_id is required.
476 *
477 * @return int
478 * contact_id on success, null otherwise
479 */
480 public static function getContactId($ufID) {
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 /**
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
502 * uf_id of the given contact_id on success, null otherwise
503 */
504 public static function getUFId($contactID) {
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
519 /**
520 * @return bool
521 */
522 public static function isEmptyTable() {
523 $sql = "SELECT count(id) FROM civicrm_uf_match";
524 return CRM_Core_DAO::singleValueQuery($sql) > 0 ? FALSE : TRUE;
525 }
526
527 /**
528 * Get the list of contact_id.
529 *
530 *
531 * @return int
532 * contact_id on success, null otherwise
533 */
534 public static function getContactIDs() {
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 /**
545 * See if this user exists, and if so, if they're allowed to login
546 *
547 *
548 * @param int $openId
549 *
550 * @return bool
551 * true if allowed to login, false otherwise
552 */
553 public static function getAllowedToLogin($openId) {
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 /**
564 * Get the next unused uf_id value, since the standalone UF doesn't
565 * have id's (it uses OpenIDs, which go in a different field)
566 *
567 *
568 * @return int
569 * next highest unused value for uf_id
570 */
571 public static function getNextUfIdValue() {
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
584 /**
585 * @param $email
586 *
587 * @return bool
588 */
589 public static function isDuplicateUser($email) {
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 *
605 * @param int $ufID
606 * Uf id.
607 *
608 * @return array
609 * uf values.
610 */
611 public static function getUFValues($ufID = NULL) {
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])) {
622 $ufmatch = new CRM_Core_DAO_UFMatch();
623 $ufmatch->uf_id = $ufID;
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 }
636
637 /**
638 * @inheritDoc
639 */
640 public function addSelectWhereClause() {
641 // Prevent default behavior of joining ACLs onto the contact_id field
642 $clauses = array();
643 CRM_Utils_Hook::selectWhereClause($this, $clauses);
644 return $clauses;
645 }
646
647 }