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