CRM-19811 fix one instance of referring to LOWER() & comment others.
[civicrm-core.git] / CRM / Utils / System / Drupal6.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/**
b8c71ffa 35 * Drupal specific stuff goes here.
6a488035 36 */
9977c6f5 37class CRM_Utils_System_Drupal6 extends CRM_Utils_System_DrupalBase {
6a488035
TO
38
39 /**
b8c71ffa 40 * Theme output.
41 *
42 * If we are using a theming system, invoke theme, else just print the content.
6a488035 43 *
77855840
TO
44 * @param string $content
45 * The content that will be themed.
46 * @param bool $print
47 * Are we displaying to the screen or bypassing theming?.
48 * @param bool $maintenance
49 * For maintenance mode.
6a488035 50 *
b8c71ffa 51 * @return null|string
a6c01b45 52 * prints content on stdout
6a488035 53 */
00be9182 54 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
6a488035
TO
55 // TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
56 if (function_exists('theme') && !$print) {
57 if ($maintenance) {
58 drupal_set_breadcrumb('');
59 drupal_maintenance_theme();
60 }
61
62 // Arg 3 for D6 theme() is "show_blocks". Previously, we passed
63 // through a badly named variable ("$args") which was almost always
64 // TRUE (except on fatal error screen). However, this feature is
65 // non-functional on D6 default themes, was purposefully removed from
66 // D7, has no analog in other our other CMS's, and clutters the code.
67 // Hard-wiring to TRUE should be OK.
68 $out = theme('page', $content, TRUE);
69 }
70 else {
71 $out = $content;
72 }
73
74 print $out;
b8c71ffa 75 return NULL;
6a488035
TO
76 }
77
78 /**
b8c71ffa 79 * Create user.
80 *
17f443df 81 * @inheritDoc
6a488035 82 */
00be9182 83 public function createUser(&$params, $mail) {
6a488035
TO
84 $form_state = array();
85 $form_state['values'] = array(
86 'name' => $params['cms_name'],
87 'mail' => $params[$mail],
88 'op' => 'Create new account',
89 );
a57957f7
KJ
90
91 $admin = user_access('administer users');
92 if (!variable_get('user_email_verification', TRUE) || $admin) {
6a488035
TO
93 $form_state['values']['pass']['pass1'] = $params['cms_pass'];
94 $form_state['values']['pass']['pass2'] = $params['cms_pass'];
95 }
96
97 $config = CRM_Core_Config::singleton();
98
99 // we also need to redirect b
100 $config->inCiviCRM = TRUE;
101
102 $form = drupal_retrieve_form('user_register', $form_state);
103 $form['#post'] = $form_state['values'];
104 drupal_prepare_form('user_register', $form, $form_state);
105
106 // remove the captcha element from the form prior to processing
107 unset($form['captcha']);
108
109 drupal_process_form('user_register', $form, $form_state);
110
111 $config->inCiviCRM = FALSE;
112
113 if (form_get_errors() || !isset($form_state['user'])) {
114 return FALSE;
115 }
6a488035 116 return $form_state['user']->uid;
6a488035
TO
117 }
118
bb3a214a 119 /**
17f443df 120 * @inheritDoc
bb3a214a 121 */
00be9182 122 public function updateCMSName($ufID, $ufName) {
6a488035
TO
123 // CRM-5555
124 if (function_exists('user_load')) {
125 $user = user_load(array('uid' => $ufID));
126 if ($user->mail != $ufName) {
127 user_save($user, array('mail' => $ufName));
128 $user = user_load(array('uid' => $ufID));
129 }
130 }
131 }
132
133 /**
fe482240 134 * Check if username and email exists in the drupal db.
6a488035 135 *
77855840
TO
136 * @param array $params
137 * Array of name and mail values.
138 * @param array $errors
139 * Array of errors.
140 * @param string $emailName
141 * Field label for the 'email'.
6a488035 142 */
00be9182 143 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
144 $config = CRM_Core_Config::singleton();
145
353ffa53
TO
146 $dao = new CRM_Core_DAO();
147 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
6a488035
TO
148 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
149 _user_edit_validate(NULL, $params);
150 $errors = form_get_errors();
6a488035 151 if ($errors) {
a7488080 152 if (!empty($errors['name'])) {
6a488035
TO
153 $errors['cms_name'] = $errors['name'];
154 }
a7488080 155 if (!empty($errors['mail'])) {
6a488035
TO
156 $errors[$emailName] = $errors['mail'];
157 }
158 // also unset drupal messages to avoid twice display of errors
159 unset($_SESSION['messages']);
160 }
161
a5ecff8d 162 // Do the name check manually.
6a488035
TO
163 $nameError = user_validate_name($params['name']);
164 if ($nameError) {
165 $errors['cms_name'] = $nameError;
166 }
167
168 $sql = "
b67a6d82
E
169 SELECT name, mail
170 FROM {users}
171 WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
172 ";
b67a6d82 173
48f12f07 174 $result = db_query($sql);
8982d5f8
EM
175 $row = db_fetch_array($result);
176 if (!$row) {
b67a6d82 177 return;
6a488035 178 }
5a604d61 179
b67a6d82
E
180 $user = NULL;
181
6a488035 182 if (!empty($row)) {
b67a6d82
E
183 $dbName = CRM_Utils_Array::value('name', $row);
184 $dbEmail = CRM_Utils_Array::value('mail', $row);
6a488035
TO
185 if (strtolower($dbName) == strtolower($name)) {
186 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
187 array(1 => $name)
188 );
189 }
190 if (strtolower($dbEmail) == strtolower($email)) {
22e263ad 191 if (empty($email)) {
b67a6d82
E
192 $errors[$emailName] = ts('You cannot create an email account for a contact with no email',
193 array(1 => $email)
194 );
195 }
92e4c2a5 196 else {
161f725c 197 $errors[$emailName] = ts('This email %1 already has an account associated with it. Please select another email.',
b67a6d82
E
198 array(1 => $email)
199 );
200 }
6a488035
TO
201 }
202 }
203 }
204
f4aaa82a 205 /**
17f443df 206 * @inheritDoc
6a488035 207 */
00be9182 208 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
209 if (!$pageTitle) {
210 $pageTitle = $title;
211 }
212 if (arg(0) == 'civicrm') {
213 //set drupal title
214 drupal_set_title($pageTitle);
215 }
216 }
217
218 /**
17f443df 219 * @inheritDoc
6a488035 220 */
00be9182 221 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
222 $breadCrumb = drupal_get_breadcrumb();
223
224 if (is_array($breadCrumbs)) {
225 foreach ($breadCrumbs as $crumbs) {
226 if (stripos($crumbs['url'], 'id%%')) {
227 $args = array('cid', 'mid');
228 foreach ($args as $a) {
229 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
230 FALSE, NULL, $_GET
231 );
232 if ($val) {
233 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
234 }
235 }
236 }
237 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
238 }
239 }
240 drupal_set_breadcrumb($breadCrumb);
241 }
242
243 /**
17f443df 244 * @inheritDoc
6a488035 245 */
00be9182 246 public function resetBreadCrumb() {
6a488035
TO
247 $bc = array();
248 drupal_set_breadcrumb($bc);
249 }
250
251 /**
fe482240 252 * Append a string to the head of the html file.
6a488035 253 *
77855840
TO
254 * @param string $head
255 * The new string to be appended.
6a488035 256 */
00be9182 257 public function addHTMLHead($head) {
6a488035
TO
258 drupal_set_html_head($head);
259 }
260
6a488035 261 /**
fe482240 262 * Add a css file.
6a488035 263 *
353ffa53 264 * @param $url : string, absolute path to file
5a4f6742
CW
265 * @param string $region
266 * location within the document: 'html-header', 'page-header', 'page-footer'.
6a488035
TO
267 *
268 * Note: This function is not to be called directly
269 * @see CRM_Core_Region::render()
270 *
a6c01b45
CW
271 * @return bool
272 * TRUE if we support this operation in this CMS, FALSE otherwise
6a488035
TO
273 */
274 public function addStyleUrl($url, $region) {
42e1a97c 275 if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
6a488035
TO
276 return FALSE;
277 }
278 drupal_add_css($url);
279 return TRUE;
280 }
281
282 /**
17f443df 283 * @inheritDoc
6a488035 284 */
00be9182 285 public function mapConfigToSSL() {
6a488035
TO
286 global $base_url;
287 $base_url = str_replace('http://', 'https://', $base_url);
288 }
4f4a85f8 289
19f0072b 290 protected function getUsersTableName() {
76eeb935
LG
291 $userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
292 if (empty($userFrameworkUsersTableName)) {
293 $userFrameworkUsersTableName = 'users';
294 }
295 return $userFrameworkUsersTableName;
296 }
6a488035
TO
297
298 /**
17f443df 299 * @inheritDoc
6a488035 300 */
00be9182 301 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
e7292422
TO
302 //@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
303 // if ever now.
304 // probably if bootstrap is loaded this call
305 // CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
306 // sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
307 // safe in the unknown situation where authenticate might be called & it is important that
308 // false is returned
6a488035
TO
309 require_once 'DB.php';
310
311 $config = CRM_Core_Config::singleton();
312
313 $dbDrupal = DB::connect($config->userFrameworkDSN);
314 if (DB::isError($dbDrupal)) {
315 CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
316 }
317
318 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
353ffa53
TO
319 $dbpassword = md5($password);
320 $name = $dbDrupal->escapeSimple($strtolower($name));
348754d5
TO
321 $userFrameworkUsersTableName = $this->getUsersTableName();
322 $sql = 'SELECT u.* FROM ' . $userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
353ffa53 323 $query = $dbDrupal->query($sql);
6a488035
TO
324
325 $user = NULL;
326 // need to change this to make sure we matched only one row
327 while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
328 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
329 $contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
330 if (!$contactID) {
331 return FALSE;
332 }
ae5ffbb7
TO
333 else {
334 //success
6a488035
TO
335 if ($loadCMSBootstrap) {
336 $bootStrapParams = array();
337 if ($name && $password) {
338 $bootStrapParams = array(
353ffa53
TO
339 'name' => $name,
340 'pass' => $password,
6a488035
TO
341 );
342 }
343 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
344 }
a5ecff8d
CB
345 return array($contactID, $row['uid'], mt_rand());
346 }
6a488035
TO
347 }
348 return FALSE;
349 }
350
f4aaa82a 351 /**
17f443df 352 * @inheritDoc
6a488035 353 */
00be9182 354 public function loadUser($username) {
6a488035
TO
355 global $user;
356 $user = user_load(array('name' => $username));
357 if (empty($user->uid)) {
358 return FALSE;
359 }
360
361 $uid = $user->uid;
362 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
363
364 // lets store contact id and user id in session
365 $session = CRM_Core_Session::singleton();
366 $session->set('ufID', $uid);
367 $session->set('userID', $contact_id);
368 return TRUE;
369 }
370
82d9c21e 371 /**
53980972 372 * Perform any post login activities required by the UF -
373 * e.g. for drupal : records a watchdog message about the new session,
374 * saves the login timestamp, calls hook_user op 'login' and generates a new session.
e43cc689 375 *
ae5ffbb7 376 * @param array $params
95d68223
TO
377 *
378 * FIXME: Document values accepted/required by $params
53980972 379 */
00be9182 380 public function userLoginFinalize($params = array()) {
53980972 381 user_authenticate_finalize($params);
82d9c21e 382 }
383
46b6363c 384 /**
fe482240 385 * Determine the native ID of the CMS user.
46b6363c 386 *
100fef9d 387 * @param string $username
46b6363c
TO
388 * @return int|NULL
389 */
00be9182 390 public function getUfId($username) {
46b6363c
TO
391 $user = user_load(array('name' => $username));
392 if (empty($user->uid)) {
393 return NULL;
394 }
395 return $user->uid;
396 }
397
6a488035 398 /**
17f443df 399 * @inheritDoc
5bc392e6 400 */
00be9182 401 public function logout() {
6a488035
TO
402 module_load_include('inc', 'user', 'user.pages');
403 return user_logout();
404 }
405
6a488035 406 /**
fe482240 407 * Load drupal bootstrap.
6a488035 408 *
77855840
TO
409 * @param array $params
410 * Either uid, or name & pass.
411 * @param bool $loadUser
412 * Boolean Require CMS user load.
413 * @param bool $throwError
414 * If true, print error on failure and exit.
415 * @param bool|string $realPath path to script
f4aaa82a
EM
416 *
417 * @return bool
6a488035 418 */
00be9182 419 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
6a488035
TO
420 //take the cms root path.
421 $cmsPath = $this->cmsRootPath($realPath);
4459cd26 422
6a488035 423 if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
4459cd26
CB
424 if ($throwError) {
425 echo '<br />Sorry, could not locate bootstrap.inc\n';
426 exit();
427 }
428 return FALSE;
6a488035 429 }
4459cd26 430 // load drupal bootstrap
6a488035 431 chdir($cmsPath);
4459cd26
CB
432 define('DRUPAL_ROOT', $cmsPath);
433
434 // For drupal multi-site CRM-11313
435 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
436 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
437 if (!empty($matches[1])) {
438 $_SERVER['HTTP_HOST'] = $matches[1];
439 }
440 }
6a488035 441 require_once 'includes/bootstrap.inc';
38507482 442 // @ to suppress notices eg 'DRUPALFOO already defined'.
6a488035
TO
443 @drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
444
4459cd26
CB
445 // explicitly setting error reporting, since we cannot handle drupal related notices
446 error_reporting(1);
a5ecff8d 447 if (!function_exists('module_exists') || !module_exists('civicrm')) {
4459cd26
CB
448 if ($throwError) {
449 echo '<br />Sorry, could not load drupal bootstrap.';
450 exit();
451 }
452 return FALSE;
6a488035 453 }
a5ecff8d 454
4459cd26
CB
455 // seems like we've bootstrapped drupal
456 $config = CRM_Core_Config::singleton();
457
6a488035
TO
458 // lets also fix the clean url setting
459 // CRM-6948
460 $config->cleanURL = (int) variable_get('clean_url', '0');
461
462 // we need to call the config hook again, since we now know
463 // all the modules that are listening on it, does not apply
464 // to J! and WP as yet
465 // CRM-8655
466 CRM_Utils_Hook::config($config);
467
468 if (!$loadUser) {
469 return TRUE;
470 }
95915c38 471 global $user;
4459cd26
CB
472 // If $uid is passed in, authentication has been done already.
473 $uid = CRM_Utils_Array::value('uid', $params);
474 if (!$uid) {
475 //load user, we need to check drupal permissions.
476 $name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
477 $pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
478
479 if ($name) {
95915c38
E
480 $user = user_authenticate(array('name' => $name, 'pass' => $pass));
481 if (!$user->uid) {
4459cd26
CB
482 if ($throwError) {
483 echo '<br />Sorry, unrecognized username or password.';
484 exit();
485 }
486 return FALSE;
487 }
95915c38
E
488 else {
489 return TRUE;
490 }
6a488035
TO
491 }
492 }
4459cd26
CB
493
494 if ($uid) {
495 $account = user_load($uid);
496 if ($account && $account->uid) {
6a488035 497 $user = $account;
4459cd26 498 return TRUE;
6a488035
TO
499 }
500 }
4459cd26
CB
501
502 if ($throwError) {
503 echo '<br />Sorry, can not load CMS user account.';
504 exit();
505 }
506
507 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
508 // which means that define(CIVICRM_CLEANURL) was correctly set.
509 // So we correct it
510 $config = CRM_Core_Config::singleton();
e7292422 511 $config->cleanURL = (int) variable_get('clean_url', '0');
4459cd26
CB
512
513 // CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
514 CRM_Utils_Hook::config($config);
515
516 return FALSE;
6a488035
TO
517 }
518
a5ecff8d 519 /**
ea3ddccf 520 * Get CMS root path.
521 *
522 * @param string $scriptFilename
523 *
524 * @return null|string
a5ecff8d 525 */
00be9182 526 public function cmsRootPath($scriptFilename = NULL) {
6a488035
TO
527 $cmsRoot = $valid = NULL;
528
529 if (!is_null($scriptFilename)) {
530 $path = $scriptFilename;
531 }
532 else {
533 $path = $_SERVER['SCRIPT_FILENAME'];
534 }
a5ecff8d 535
6a488035
TO
536 if (function_exists('drush_get_context')) {
537 // drush anyway takes care of multisite install etc
538 return drush_get_context('DRUSH_DRUPAL_ROOT');
539 }
540 // CRM-7582
541 $pathVars = explode('/',
542 str_replace('//', '/',
543 str_replace('\\', '/', $path)
544 )
545 );
546
547 //lets store first var,
548 //need to get back for windows.
549 $firstVar = array_shift($pathVars);
550
551 //lets remove sript name to reduce one iteration.
552 array_pop($pathVars);
553
554 //CRM-7429 --do check for upper most 'includes' dir,
555 //which would effectually work for multisite installation.
556 do {
557 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
558 $cmsIncludePath = "$cmsRoot/includes";
948d11bf 559 // Stop if we found bootstrap.
f81c7606 560 if (file_exists("$cmsIncludePath/bootstrap.inc")) {
6a488035
TO
561 $valid = TRUE;
562 break;
563 }
564 //remove one directory level.
565 array_pop($pathVars);
566 } while (count($pathVars));
567
568 return ($valid) ? $cmsRoot : NULL;
569 }
570
571 /**
17f443df 572 * @inheritDoc
6a488035
TO
573 */
574 public function isUserLoggedIn() {
575 $isloggedIn = FALSE;
576 if (function_exists('user_is_logged_in')) {
577 $isloggedIn = user_is_logged_in();
578 }
579
580 return $isloggedIn;
581 }
582
583 /**
17f443df 584 * @inheritDoc
6a488035
TO
585 */
586 public function getLoggedInUfID() {
587 $ufID = NULL;
588 if (function_exists('user_is_logged_in') &&
589 user_is_logged_in() &&
590 function_exists('user_uid_optional_to_arg')
591 ) {
592 $ufID = user_uid_optional_to_arg(array());
593 }
594
595 return $ufID;
596 }
597
598 /**
17f443df 599 * @inheritDoc
6a488035 600 */
00be9182 601 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
6a488035
TO
602 if (empty($url)) {
603 return $url;
604 }
605
b44e3f84 606 //up to d6 only, already we have code in place for d7
6a488035
TO
607 $config = CRM_Core_Config::singleton();
608 if (function_exists('variable_get') &&
609 module_exists('locale')
610 ) {
611 global $language;
612
613 //get the mode.
614 $mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
615
616 //url prefix / path.
617 if (isset($language->prefix) &&
618 $language->prefix &&
619 in_array($mode, array(
620 LANGUAGE_NEGOTIATION_PATH,
353ffa53
TO
621 LANGUAGE_NEGOTIATION_PATH_DEFAULT,
622 ))
6a488035
TO
623 ) {
624
625 if ($addLanguagePart) {
626 $url .= $language->prefix . '/';
627 }
628 if ($removeLanguagePart) {
629 $url = str_replace("/{$language->prefix}/", '/', $url);
630 }
631 }
632 if (isset($language->domain) &&
633 $language->domain &&
634 $mode == LANGUAGE_NEGOTIATION_DOMAIN
635 ) {
636
637 if ($addLanguagePart) {
638 $url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
639 }
640 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
641 $url = str_replace('\\', '/', $url);
642 $parseUrl = parse_url($url);
643
644 //kinda hackish but not sure how to do it right
645 //hope http_build_url() will help at some point.
646 if (is_array($parseUrl) && !empty($parseUrl)) {
353ffa53
TO
647 $urlParts = explode('/', $url);
648 $hostKey = array_search($parseUrl['host'], $urlParts);
649 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
6a488035 650 $urlParts[$hostKey] = $ufUrlParts['host'];
353ffa53 651 $url = implode('/', $urlParts);
6a488035
TO
652 }
653 }
654 }
655 }
656
657 return $url;
658 }
659
660 /**
661 * Find any users/roles/security-principals with the given permission
662 * and replace it with one or more permissions.
663 *
5a4f6742
CW
664 * @param string $oldPerm
665 * @param array $newPerms
77855840 666 * Array, strings.
6a488035 667 */
00be9182 668 public function replacePermission($oldPerm, $newPerms) {
6a488035
TO
669 $roles = user_roles(FALSE, $oldPerm);
670 foreach ($roles as $rid => $roleName) {
671 $permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
672 $perms = drupal_map_assoc(explode(', ', $permList));
673 unset($perms[$oldPerm]);
674 $perms = $perms + drupal_map_assoc($newPerms);
675 $permList = implode(', ', $perms);
676 db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
e70a7fc0 677 /* @codingStandardsIgnoreStart
6a488035
TO
678 if ( ! empty( $roles ) ) {
679 $rids = implode(',', array_keys($roles));
680 db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
681 db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
e70a7fc0
TO
682 $oldPerm, implode(', ', $newPerms) );
683 @codingStandardsIgnoreEnd */
6a488035
TO
684 }
685 }
686
687 /**
66e42142 688 * @inheritDoc
6a488035 689 */
00be9182 690 public function getModules() {
6a488035
TO
691 $result = array();
692 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
693 while ($row = db_fetch_object($q)) {
694 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
695 }
696 return $result;
697 }
698
699 /**
17f443df 700 * @inheritDoc
6a488035
TO
701 */
702 public function getLoginURL($destination = '') {
703 $config = CRM_Core_Config::singleton();
704 $loginURL = $config->userFrameworkBaseURL;
705 $loginURL .= 'user';
706 if (!empty($destination)) {
707 // append destination so user is returned to form they came from after login
708 $loginURL .= '?destination=' . urlencode($destination);
709 }
710 return $loginURL;
711 }
712
d761c4d8 713 /**
fe482240 714 * Wrapper for og_membership creation.
d761c4d8 715 *
77855840
TO
716 * @param int $ogID
717 * Organic Group ID.
718 * @param int $drupalID
719 * Drupal User ID.
6a488035 720 */
9b873358 721 public function og_membership_create($ogID, $drupalID) {
481a74f4 722 og_save_subscription($ogID, $drupalID, array('is_active' => 1));
6a488035
TO
723 }
724
725 /**
fe482240 726 * Wrapper for og_membership deletion.
d761c4d8 727 *
77855840
TO
728 * @param int $ogID
729 * Organic Group ID.
730 * @param int $drupalID
731 * Drupal User ID.
6a488035 732 */
00be9182 733 public function og_membership_delete($ogID, $drupalID) {
481a74f4 734 og_delete_subscription($ogID, $drupalID);
6a488035
TO
735 }
736
5a604d61 737 /**
17f443df 738 * @inheritDoc
5a604d61 739 */
00be9182 740 public function getTimeZoneString() {
5a604d61 741 global $user;
e41775f6 742 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
743 if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
5a604d61 744 $timezone = $user->timezone;
0db6c3e1
TO
745 }
746 else {
e7292422 747 $timezone = variable_get('date_default_timezone', NULL);
5a604d61 748 }
48ec57ab
TO
749 if (!$timezone) {
750 $timezone = parent::getTimeZoneString();
5a604d61 751 }
48ec57ab 752 return $timezone;
5a604d61
E
753 }
754
d42a224c
CW
755 /**
756 * @inheritDoc
757 */
758 public function setHttpHeader($name, $value) {
759 drupal_set_header("$name: $value");
760 }
761
03d5592a
CW
762 /**
763 * @inheritDoc
764 */
765 public function synchronizeUsers() {
766 $config = CRM_Core_Config::singleton();
767 if (PHP_SAPI != 'cli') {
768 set_time_limit(300);
769 }
770 $rows = array();
771 $id = 'uid';
772 $mail = 'mail';
773 $name = 'name';
774
775 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
776
777 while ($row = db_fetch_array($result)) {
778 $rows[] = $row;
779 }
780
781 $user = new StdClass();
782 $uf = $config->userFramework;
783 $contactCount = 0;
784 $contactCreated = 0;
785 $contactMatching = 0;
786 foreach ($rows as $row) {
787 $user->$id = $row[$id];
788 $user->$mail = $row[$mail];
789 $user->$name = $row[$name];
790 $contactCount++;
791 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1, 'Individual', TRUE)) {
792 $contactCreated++;
793 }
794 else {
795 $contactMatching++;
796 }
797 if (is_object($match)) {
798 $match->free();
799 }
800 }
801
802 return array(
803 'contactCount' => $contactCount,
804 'contactMatching' => $contactMatching,
805 'contactCreated' => $contactCreated,
806 );
807 }
808
6a488035 809}