Merge pull request #15936 from seamuslee001/advanced_search_metadata
[civicrm-core.git] / CRM / Utils / System / Drupal.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 * Drupal specific stuff goes here
20 */
21 class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
22
23 /**
24 * @inheritDoc
25 */
26 public function createUser(&$params, $mail) {
27 $form_state = form_state_defaults();
28
29 $form_state['input'] = [
30 'name' => $params['cms_name'],
31 'mail' => $params[$mail],
32 'op' => 'Create new account',
33 ];
34
35 $admin = user_access('administer users');
36 if (!variable_get('user_email_verification', TRUE) || $admin) {
37 $form_state['input']['pass'] = ['pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']];
38 }
39
40 if (!empty($params['notify'])) {
41 $form_state['input']['notify'] = $params['notify'];
42 }
43
44 $form_state['rebuild'] = FALSE;
45 $form_state['programmed'] = TRUE;
46 $form_state['complete form'] = FALSE;
47 $form_state['method'] = 'post';
48 $form_state['build_info']['args'] = [];
49 /*
50 * if we want to submit this form more than once in a process (e.g. create more than one user)
51 * we must force it to validate each time for this form. Otherwise it will not validate
52 * subsequent submissions and the manner in which the password is passed in will be invalid
53 */
54 $form_state['must_validate'] = TRUE;
55 $config = CRM_Core_Config::singleton();
56
57 // we also need to redirect b
58 $config->inCiviCRM = TRUE;
59
60 $form = drupal_retrieve_form('user_register_form', $form_state);
61 $form_state['process_input'] = 1;
62 $form_state['submitted'] = 1;
63 $form['#array_parents'] = [];
64 $form['#tree'] = FALSE;
65 drupal_process_form('user_register_form', $form, $form_state);
66
67 $config->inCiviCRM = FALSE;
68
69 if (form_get_errors()) {
70 return FALSE;
71 }
72 return $form_state['user']->uid;
73 }
74
75 /**
76 * @inheritDoc
77 */
78 public function updateCMSName($ufID, $ufName) {
79 // CRM-5555
80 if (function_exists('user_load')) {
81 $user = user_load($ufID);
82 if ($user->mail != $ufName) {
83 user_save($user, ['mail' => $ufName]);
84 $user = user_load($ufID);
85 }
86 }
87 }
88
89 /**
90 * Check if username and email exists in the drupal db.
91 *
92 * @param array $params
93 * Array of name and mail values.
94 * @param array $errors
95 * Array of errors.
96 * @param string $emailName
97 * Field label for the 'email'.
98 */
99 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
100 $config = CRM_Core_Config::singleton();
101
102 $dao = new CRM_Core_DAO();
103 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
104 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
105 $errors = form_get_errors();
106 if ($errors) {
107 // unset drupal messages to avoid twice display of errors
108 unset($_SESSION['messages']);
109 }
110
111 if (!empty($params['name'])) {
112 if ($nameError = user_validate_name($params['name'])) {
113 $errors['cms_name'] = $nameError;
114 }
115 else {
116 $uid = db_query(
117 "SELECT uid FROM {users} WHERE name = :name",
118 [':name' => $params['name']]
119 )->fetchField();
120 if ((bool) $uid) {
121 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
122 }
123 }
124 }
125
126 if (!empty($params['mail'])) {
127 if ($emailError = user_validate_mail($params['mail'])) {
128 $errors[$emailName] = $emailError;
129 }
130 else {
131 $uid = db_query(
132 "SELECT uid FROM {users} WHERE mail = :mail",
133 [':mail' => $params['mail']]
134 )->fetchField();
135 if ((bool) $uid) {
136 $resetUrl = url('user/password');
137 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
138 [1 => $params['mail'], 2 => $resetUrl]
139 );
140 }
141 }
142 }
143 }
144
145 /**
146 * @inheritDoc
147 */
148 public function getLoginURL($destination = '') {
149 $query = $destination ? ['destination' => $destination] : NULL;
150 return CRM_Utils_System::url('user', $query, TRUE);
151 }
152
153 /**
154 * @inheritDoc
155 */
156 public function setTitle($title, $pageTitle = NULL) {
157 if (arg(0) == 'civicrm') {
158 if (!$pageTitle) {
159 $pageTitle = $title;
160 }
161
162 drupal_set_title($pageTitle, PASS_THROUGH);
163 }
164 }
165
166 /**
167 * @inheritDoc
168 */
169 public function appendBreadCrumb($breadCrumbs) {
170 $breadCrumb = drupal_get_breadcrumb();
171
172 if (is_array($breadCrumbs)) {
173 foreach ($breadCrumbs as $crumbs) {
174 if (stripos($crumbs['url'], 'id%%')) {
175 $args = ['cid', 'mid'];
176 foreach ($args as $a) {
177 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
178 FALSE, NULL, $_GET
179 );
180 if ($val) {
181 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
182 }
183 }
184 }
185 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
186 }
187 }
188 drupal_set_breadcrumb($breadCrumb);
189 }
190
191 /**
192 * @inheritDoc
193 */
194 public function resetBreadCrumb() {
195 $bc = [];
196 drupal_set_breadcrumb($bc);
197 }
198
199 /**
200 * @inheritDoc
201 */
202 public function addHTMLHead($header) {
203 static $count = 0;
204 if (!empty($header)) {
205 $key = 'civi_' . ++$count;
206 $data = [
207 '#type' => 'markup',
208 '#markup' => $header,
209 ];
210 drupal_add_html_head($data, $key);
211 }
212 }
213
214 /**
215 * @inheritDoc
216 */
217 public function addScriptUrl($url, $region) {
218 $params = ['group' => JS_LIBRARY, 'weight' => 10];
219 switch ($region) {
220 case 'html-header':
221 case 'page-footer':
222 $params['scope'] = substr($region, 5);
223 break;
224
225 default:
226 return FALSE;
227 }
228 // If the path is within the drupal directory we can use the more efficient 'file' setting
229 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
230 drupal_add_js($url, $params);
231 return TRUE;
232 }
233
234 /**
235 * @inheritDoc
236 */
237 public function addScript($code, $region) {
238 $params = ['type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10];
239 switch ($region) {
240 case 'html-header':
241 case 'page-footer':
242 $params['scope'] = substr($region, 5);
243 break;
244
245 default:
246 return FALSE;
247 }
248 drupal_add_js($code, $params);
249 return TRUE;
250 }
251
252 /**
253 * @inheritDoc
254 */
255 public function addStyleUrl($url, $region) {
256 if ($region != 'html-header') {
257 return FALSE;
258 }
259 $params = [];
260 // If the path is within the drupal directory we can use the more efficient 'file' setting
261 $params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
262 drupal_add_css($url, $params);
263 return TRUE;
264 }
265
266 /**
267 * @inheritDoc
268 */
269 public function addStyle($code, $region) {
270 if ($region != 'html-header') {
271 return FALSE;
272 }
273 $params = ['type' => 'inline'];
274 drupal_add_css($code, $params);
275 return TRUE;
276 }
277
278 /**
279 * @inheritDoc
280 */
281 public function mapConfigToSSL() {
282 global $base_url;
283 $base_url = str_replace('http://', 'https://', $base_url);
284 }
285
286 /**
287 * Get the name of the users table.
288 *
289 * @return string
290 */
291 protected function getUsersTableName() {
292 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
293 if (empty($userFrameworkUsersTableName)) {
294 $userFrameworkUsersTableName = 'users';
295 }
296 return $userFrameworkUsersTableName;
297 }
298
299 /**
300 * @inheritDoc
301 */
302 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
303 require_once 'DB.php';
304
305 $config = CRM_Core_Config::singleton();
306
307 $dbDrupal = DB::connect($config->userFrameworkDSN);
308 if (DB::isError($dbDrupal)) {
309 throw new CRM_Core_Exception("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
310 }
311
312 $account = $userUid = $userMail = NULL;
313 if ($loadCMSBootstrap) {
314 $bootStrapParams = [];
315 if ($name && $password) {
316 $bootStrapParams = [
317 'name' => $name,
318 'pass' => $password,
319 ];
320 }
321 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
322
323 global $user;
324 if ($user) {
325 $userUid = $user->uid;
326 $userMail = $user->mail;
327 }
328 }
329 else {
330 // CRM-8638
331 // SOAP cannot load drupal bootstrap and hence we do it the old way
332 // Contact CiviSMTP folks if we run into issues with this :)
333 $cmsPath = $config->userSystem->cmsRootPath($realPath);
334
335 require_once "$cmsPath/includes/bootstrap.inc";
336 require_once "$cmsPath/includes/password.inc";
337
338 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
339 $name = $dbDrupal->escapeSimple($strtolower($name));
340 $userFrameworkUsersTableName = $this->getUsersTableName();
341
342 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
343 $sql = "
344 SELECT u.*
345 FROM {$userFrameworkUsersTableName} u
346 WHERE LOWER(u.name) = '$name'
347 AND u.status = 1
348 ";
349
350 $query = $dbDrupal->query($sql);
351 $row = $query->fetchRow(DB_FETCHMODE_ASSOC);
352
353 if ($row) {
354 $fakeDrupalAccount = drupal_anonymous_user();
355 $fakeDrupalAccount->name = $name;
356 $fakeDrupalAccount->pass = $row['pass'];
357 $passwordCheck = user_check_password($password, $fakeDrupalAccount);
358 if ($passwordCheck) {
359 $userUid = $row['uid'];
360 $userMail = $row['mail'];
361 }
362 }
363 }
364
365 if ($userUid && $userMail) {
366 CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
367 $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
368 if (!$contactID) {
369 return FALSE;
370 }
371 return [$contactID, $userUid, mt_rand()];
372 }
373 return FALSE;
374 }
375
376 /**
377 * @inheritDoc
378 */
379 public function loadUser($username) {
380 global $user;
381
382 $user = user_load_by_name($username);
383
384 if (empty($user->uid)) {
385 return FALSE;
386 }
387
388 $uid = $user->uid;
389 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
390
391 // lets store contact id and user id in session
392 $session = CRM_Core_Session::singleton();
393 $session->set('ufID', $uid);
394 $session->set('userID', $contact_id);
395 return TRUE;
396 }
397
398 /**
399 * Perform any post login activities required by the UF -
400 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
401 * calls hook_user op 'login' and generates a new session.
402 *
403 * @param array $params
404 *
405 * FIXME: Document values accepted/required by $params
406 */
407 public function userLoginFinalize($params = []) {
408 user_login_finalize($params);
409 }
410
411 /**
412 * Determine the native ID of the CMS user.
413 *
414 * @param string $username
415 * @return int|null
416 */
417 public function getUfId($username) {
418 $user = user_load_by_name($username);
419 if (empty($user->uid)) {
420 return NULL;
421 }
422 return $user->uid;
423 }
424
425 /**
426 * @inheritDoc
427 */
428 public function logout() {
429 module_load_include('inc', 'user', 'user.pages');
430 return user_logout();
431 }
432
433 /**
434 * Get the default location for CiviCRM blocks.
435 *
436 * @return string
437 */
438 public function getDefaultBlockLocation() {
439 return 'sidebar_first';
440 }
441
442 /**
443 * Load drupal bootstrap.
444 *
445 * @param array $params
446 * Either uid, or name & pass.
447 * @param bool $loadUser
448 * Boolean Require CMS user load.
449 * @param bool $throwError
450 * If true, print error on failure and exit.
451 * @param bool|string $realPath path to script
452 *
453 * @return bool
454 */
455 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
456 //take the cms root path.
457 $cmsPath = $this->cmsRootPath($realPath);
458
459 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
460 if ($throwError) {
461 throw new Exception('Sorry, could not locate bootstrap.inc');
462 }
463 return FALSE;
464 }
465 // load drupal bootstrap
466 chdir($cmsPath);
467 define('DRUPAL_ROOT', $cmsPath);
468
469 // For drupal multi-site CRM-11313
470 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
471 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
472 if (!empty($matches[1])) {
473 $_SERVER['HTTP_HOST'] = $matches[1];
474 }
475 }
476 require_once 'includes/bootstrap.inc';
477 // @ to suppress notices eg 'DRUPALFOO already defined'.
478 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
479
480 // explicitly setting error reporting, since we cannot handle drupal related notices
481 // @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
482 // causes grief with debugging scripts
483 error_reporting(1);
484 if (!function_exists('module_exists')) {
485 if ($throwError) {
486 throw new Exception('Sorry, could not load drupal bootstrap.');
487 }
488 return FALSE;
489 }
490 if (!module_exists('civicrm')) {
491 if ($throwError) {
492 throw new Exception('Sorry, drupal cannot find CiviCRM');
493 }
494 return FALSE;
495 }
496
497 // seems like we've bootstrapped drupal
498 $config = CRM_Core_Config::singleton();
499
500 // lets also fix the clean url setting
501 // CRM-6948
502 $config->cleanURL = (int) variable_get('clean_url', '0');
503
504 // we need to call the config hook again, since we now know
505 // all the modules that are listening on it, does not apply
506 // to J! and WP as yet
507 // CRM-8655
508 CRM_Utils_Hook::config($config);
509
510 if (!$loadUser) {
511 return TRUE;
512 }
513
514 $uid = CRM_Utils_Array::value('uid', $params);
515 if (!$uid) {
516 //load user, we need to check drupal permissions.
517 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
518 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
519
520 if ($name) {
521 $uid = user_authenticate($name, $pass);
522 if (!$uid) {
523 if ($throwError) {
524 throw new Exception('Sorry, unrecognized username or password.');
525 }
526 return FALSE;
527 }
528 }
529 }
530
531 if ($uid) {
532 $account = user_load($uid);
533 if ($account && $account->uid) {
534 global $user;
535 $user = $account;
536 return TRUE;
537 }
538 }
539
540 if ($throwError) {
541 throw new Exception('Sorry, can not load CMS user account.');
542 }
543
544 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
545 // which means that define(CIVICRM_CLEANURL) was correctly set.
546 // So we correct it
547 $config = CRM_Core_Config::singleton();
548 $config->cleanURL = (int) variable_get('clean_url', '0');
549
550 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
551 CRM_Utils_Hook::config($config);
552
553 return FALSE;
554 }
555
556 /**
557 * Get CMS root path.
558 *
559 * @param string $scriptFilename
560 *
561 * @return null|string
562 */
563 public function cmsRootPath($scriptFilename = NULL) {
564 $cmsRoot = $valid = NULL;
565
566 if (!is_null($scriptFilename)) {
567 $path = $scriptFilename;
568 }
569 else {
570 $path = $_SERVER['SCRIPT_FILENAME'];
571 }
572
573 if (function_exists('drush_get_context')) {
574 // drush anyway takes care of multisite install etc
575 return drush_get_context('DRUSH_DRUPAL_ROOT');
576 }
577
578 global $civicrm_paths;
579 if (!empty($civicrm_paths['cms.root']['path'])) {
580 return $civicrm_paths['cms.root']['path'];
581 }
582
583 // CRM-7582
584 $pathVars = explode('/',
585 str_replace('//', '/',
586 str_replace('\\', '/', $path)
587 )
588 );
589
590 //lets store first var,
591 //need to get back for windows.
592 $firstVar = array_shift($pathVars);
593
594 // Remove the script name to remove an necessary iteration of the loop.
595 array_pop($pathVars);
596
597 // CRM-7429 -- do check for uppermost 'includes' dir, which would
598 // work for multisite installation.
599 do {
600 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
601 $cmsIncludePath = "$cmsRoot/includes";
602 // Stop if we find bootstrap.
603 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
604 $valid = TRUE;
605 break;
606 }
607 //remove one directory level.
608 array_pop($pathVars);
609 } while (count($pathVars));
610
611 return ($valid) ? $cmsRoot : NULL;
612 }
613
614 /**
615 * @inheritDoc
616 */
617 public function isUserLoggedIn() {
618 $isloggedIn = FALSE;
619 if (function_exists('user_is_logged_in')) {
620 $isloggedIn = user_is_logged_in();
621 }
622
623 return $isloggedIn;
624 }
625
626 /**
627 * @inheritDoc
628 */
629 public function getLoggedInUfID() {
630 $ufID = NULL;
631 if (function_exists('user_is_logged_in') &&
632 user_is_logged_in() &&
633 function_exists('user_uid_optional_to_arg')
634 ) {
635 $ufID = user_uid_optional_to_arg([]);
636 }
637
638 return $ufID;
639 }
640
641 /**
642 * @inheritDoc
643 */
644 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
645 if (empty($url)) {
646 return $url;
647 }
648
649 //CRM-7803 -from d7 onward.
650 $config = CRM_Core_Config::singleton();
651 if (function_exists('variable_get') &&
652 module_exists('locale') &&
653 function_exists('language_negotiation_get')
654 ) {
655 global $language;
656
657 //does user configuration allow language
658 //support from the URL (Path prefix or domain)
659 if (language_negotiation_get('language') == 'locale-url') {
660 $urlType = variable_get('locale_language_negotiation_url_part');
661
662 //url prefix
663 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
664 if (isset($language->prefix) && $language->prefix) {
665 if ($addLanguagePart) {
666 $url .= $language->prefix . '/';
667 }
668 if ($removeLanguagePart) {
669 $url = str_replace("/{$language->prefix}/", '/', $url);
670 }
671 }
672 }
673 //domain
674 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
675 if (isset($language->domain) && $language->domain) {
676 if ($addLanguagePart) {
677 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
678 // drupal function base_path() adds a "/" to the beginning and end of the returned path
679 if (substr($cleanedUrl, -1) == '/') {
680 $cleanedUrl = substr($cleanedUrl, 0, -1);
681 }
682 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
683 }
684 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
685 $url = str_replace('\\', '/', $url);
686 $parseUrl = parse_url($url);
687
688 //kinda hackish but not sure how to do it right
689 //hope http_build_url() will help at some point.
690 if (is_array($parseUrl) && !empty($parseUrl)) {
691 $urlParts = explode('/', $url);
692 $hostKey = array_search($parseUrl['host'], $urlParts);
693 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
694 $urlParts[$hostKey] = $ufUrlParts['host'];
695 $url = implode('/', $urlParts);
696 }
697 }
698 }
699 }
700 }
701 }
702
703 return $url;
704 }
705
706 /**
707 * Find any users/roles/security-principals with the given permission
708 * and replace it with one or more permissions.
709 *
710 * @param string $oldPerm
711 * @param array $newPerms
712 * Array, strings.
713 */
714 public function replacePermission($oldPerm, $newPerms) {
715 $roles = user_roles(FALSE, $oldPerm);
716 if (!empty($roles)) {
717 foreach (array_keys($roles) as $rid) {
718 user_role_revoke_permissions($rid, [$oldPerm]);
719 user_role_grant_permissions($rid, $newPerms);
720 }
721 }
722 }
723
724 /**
725 * Wrapper for og_membership creation.
726 *
727 * @param int $ogID
728 * Organic Group ID.
729 * @param int $drupalID
730 * Drupal User ID.
731 */
732 public function og_membership_create($ogID, $drupalID) {
733 if (function_exists('og_entity_query_alter')) {
734 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
735 //
736 // @TODO Find more solid way to check - try system_get_info('module', 'og').
737 //
738 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
739 og_group('node', $ogID, ['entity' => user_load($drupalID)]);
740 }
741 else {
742 // Works for the OG 7.x-1.x branch
743 og_group($ogID, ['entity' => user_load($drupalID)]);
744 }
745 }
746
747 /**
748 * Wrapper for og_membership deletion.
749 *
750 * @param int $ogID
751 * Organic Group ID.
752 * @param int $drupalID
753 * Drupal User ID.
754 */
755 public function og_membership_delete($ogID, $drupalID) {
756 if (function_exists('og_entity_query_alter')) {
757 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
758 // TODO: Find a more solid way to make this test
759 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
760 og_ungroup('node', $ogID, 'user', user_load($drupalID));
761 }
762 else {
763 // Works for the OG 7.x-1.x branch
764 og_ungroup($ogID, 'user', user_load($drupalID));
765 }
766 }
767
768 /**
769 * @inheritDoc
770 */
771 public function getTimeZoneString() {
772 global $user;
773 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
774 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
775 $timezone = $user->timezone;
776 }
777 else {
778 $timezone = variable_get('date_default_timezone', NULL);
779 }
780 if (!$timezone) {
781 $timezone = parent::getTimeZoneString();
782 }
783 return $timezone;
784 }
785
786 /**
787 * @inheritDoc
788 */
789 public function setHttpHeader($name, $value) {
790 drupal_add_http_header($name, $value);
791 }
792
793 /**
794 * @inheritDoc
795 */
796 public function synchronizeUsers() {
797 $config = CRM_Core_Config::singleton();
798 if (PHP_SAPI != 'cli') {
799 set_time_limit(300);
800 }
801 $id = 'uid';
802 $mail = 'mail';
803 $name = 'name';
804
805 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
806
807 $user = new StdClass();
808 $uf = $config->userFramework;
809 $contactCount = 0;
810 $contactCreated = 0;
811 $contactMatching = 0;
812 foreach ($result as $row) {
813 $user->$id = $row->$id;
814 $user->$mail = $row->$mail;
815 $user->$name = $row->$name;
816 $contactCount++;
817 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
818 $contactCreated++;
819 }
820 else {
821 $contactMatching++;
822 }
823 }
824
825 return [
826 'contactCount' => $contactCount,
827 'contactMatching' => $contactMatching,
828 'contactCreated' => $contactCreated,
829 ];
830 }
831
832 /**
833 * Commit the session before exiting.
834 * Similar to drupal_exit().
835 */
836 public function onCiviExit() {
837 if (function_exists('module_invoke_all')) {
838 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
839 module_invoke_all('exit');
840 }
841 drupal_session_commit();
842 }
843 }
844
845 }