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