3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
35 * Backdrop-specific logic that differs from Drupal.
37 class CRM_Utils_System_Backdrop
extends CRM_Utils_System_DrupalBase
{
42 public function createUser(&$params, $mail) {
43 $form_state = form_state_defaults();
45 $form_state['input'] = array(
46 'name' => $params['cms_name'],
47 'mail' => $params[$mail],
48 'op' => 'Create new account',
51 $admin = user_access('administer users');
52 if (!config_get('system.core', 'user_email_verification') ||
$admin) {
53 $form_state['input']['pass'] = array('pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']);
56 if (!empty($params['notify'])) {
57 $form_state['input']['notify'] = $params['notify'];
60 $form_state['rebuild'] = FALSE;
61 $form_state['programmed'] = TRUE;
62 $form_state['complete form'] = FALSE;
63 $form_state['method'] = 'post';
64 $form_state['build_info']['args'] = array();
66 * if we want to submit this form more than once in a process (e.g. create more than one user)
67 * we must force it to validate each time for this form. Otherwise it will not validate
68 * subsequent submissions and the manner in which the password is passed in will be invalid
70 $form_state['must_validate'] = TRUE;
71 $config = CRM_Core_Config
::singleton();
73 // we also need to redirect b
74 $config->inCiviCRM
= TRUE;
76 $form = drupal_retrieve_form('user_register_form', $form_state);
77 $form_state['process_input'] = 1;
78 $form_state['submitted'] = 1;
79 $form['#array_parents'] = array();
80 $form['#tree'] = FALSE;
81 drupal_process_form('user_register_form', $form, $form_state);
83 $config->inCiviCRM
= FALSE;
85 if (form_get_errors()) {
88 return $form_state['user']->uid
;
94 public function updateCMSName($ufID, $email) {
96 if (function_exists('user_load')) {
97 $user = user_load($ufID);
98 if ($user->mail
!= $email) {
106 * Check if username and email exists in the drupal db.
108 * @param array $params
109 * Array of name and mail values.
110 * @param array $errors
112 * @param string $emailName
113 * Field label for the 'email'.
115 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
116 $errors = form_get_errors();
118 // unset drupal messages to avoid twice display of errors
119 unset($_SESSION['messages']);
122 if (!empty($params['name'])) {
123 if ($nameError = user_validate_name($params['name'])) {
124 $errors['cms_name'] = $nameError;
127 $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $params['name']))->fetchField();
129 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
134 if (!empty($params['mail'])) {
135 if (!valid_email_address($params['mail'])) {
136 $errors[$emailName] = ts('The e-mail address %1 is not valid.', array('%1' => $params['mail']));
139 $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => $params['mail']))->fetchField();
141 $resetUrl = url('user/password');
142 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
143 array(1 => $params['mail'], 2 => $resetUrl)
153 public function getLoginURL($destination = '') {
154 $query = $destination ?
array('destination' => $destination) : array();
155 return url('user', array('query' => $query, 'absolute' => TRUE));
161 public function setTitle($title, $pageTitle = NULL) {
162 if (arg(0) == 'civicrm') {
167 drupal_set_title($pageTitle, PASS_THROUGH
);
174 public function appendBreadCrumb($breadCrumbs) {
175 $breadCrumb = drupal_get_breadcrumb();
177 if (is_array($breadCrumbs)) {
178 foreach ($breadCrumbs as $crumbs) {
179 if (stripos($crumbs['url'], 'id%%')) {
180 $args = array('cid', 'mid');
181 foreach ($args as $a) {
182 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
186 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
190 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
193 drupal_set_breadcrumb($breadCrumb);
199 public function resetBreadCrumb() {
201 drupal_set_breadcrumb($bc);
207 public function addHTMLHead($header) {
209 if (!empty($header)) {
210 $key = 'civi_' . ++
$count;
213 '#markup' => $header,
215 drupal_add_html_head($data, $key);
222 public function addScriptUrl($url, $region) {
223 $params = array('group' => JS_LIBRARY
, 'weight' => 10);
227 $params['scope'] = substr($region, 5);
233 // If the path is within the drupal directory we can use the more efficient 'file' setting
234 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
235 drupal_add_js($url, $params);
242 public function addScript($code, $region) {
243 $params = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
247 $params['scope'] = substr($region, 5);
253 drupal_add_js($code, $params);
260 public function addStyleUrl($url, $region) {
261 if ($region != 'html-header') {
265 // If the path is within the drupal directory we can use the more efficient 'file' setting
266 $params['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
267 drupal_add_css($url, $params);
274 public function addStyle($code, $region) {
275 if ($region != 'html-header') {
278 $params = array('type' => 'inline');
279 drupal_add_css($code, $params);
286 public function mapConfigToSSL() {
288 $base_url = str_replace('http://', 'https://', $base_url);
291 protected function getUsersTableName() {
292 $userFrameworkUsersTableName = Civi
::settings()->get('userFrameworkUsersTableName');
293 if (empty($userFrameworkUsersTableName)) {
294 $userFrameworkUsersTableName = 'users';
296 return $userFrameworkUsersTableName;
302 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
303 $config = CRM_Core_Config
::singleton();
305 $dbBackdrop = DB
::connect($config->userFrameworkDSN
);
306 if (DB
::isError($dbBackdrop)) {
307 CRM_Core_Error
::fatal("Cannot connect to Backdrop database via $config->userFrameworkDSN, " . $dbBackdrop->getMessage());
310 $account = $userUid = $userMail = NULL;
311 if ($loadCMSBootstrap) {
312 $bootStrapParams = array();
313 if ($name && $password) {
314 $bootStrapParams = array(
319 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
323 $userUid = $user->uid
;
324 $userMail = $user->mail
;
329 // SOAP cannot load drupal bootstrap and hence we do it the old way
330 // Contact CiviSMTP folks if we run into issues with this :)
331 $cmsPath = $this->cmsRootPath();
333 require_once "$cmsPath/core/includes/bootstrap.inc";
334 require_once "$cmsPath/core/includes/password.inc";
336 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
337 $name = $dbBackdrop->escapeSimple($strtolower($name));
338 $userFrameworkUsersTableName = $this->getUsersTableName();
341 FROM {$userFrameworkUsersTableName} u
342 WHERE LOWER(u.name) = '$name'
346 $query = $dbBackdrop->query($sql);
347 $row = $query->fetchRow(DB_FETCHMODE_ASSOC
);
350 $fakeAccount = backdrop_anonymous_user();
351 $fakeAccount->name
= $name;
352 $fakeAccount->pass
= $row['pass'];
353 $passwordCheck = user_check_password($password, $fakeAccount);
354 if ($passwordCheck) {
355 $userUid = $row['uid'];
356 $userMail = $row['mail'];
361 if ($userUid && $userMail) {
362 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($account, $userUid, $userMail, 'Backdrop');
363 $contactID = CRM_Core_BAO_UFMatch
::getContactId($userUid);
367 return array($contactID, $userUid, mt_rand());
375 public function loadUser($username) {
378 $user = user_load_by_name($username);
380 if (empty($user->uid
)) {
385 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
387 // lets store contact id and user id in session
388 $session = CRM_Core_Session
::singleton();
389 $session->set('ufID', $uid);
390 $session->set('userID', $contact_id);
395 * Perform any post login activities required by the UF -
396 * For Backdrop this could mean recording a watchdog message about the new
397 * session, saving the login timestamp, calling hook_user_login(), etc.
399 * @param array $params
400 * The array of form values submitted by the user.
402 public function userLoginFinalize($params = array()) {
403 user_login_finalize($params);
409 public function getUFLocale() {
410 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
411 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
412 // sometimes for CLI based on order called, this might not be set and/or empty
415 if (empty($language)) {
419 if ($language->langcode
== 'zh-hans') {
423 if ($language->langcode
== 'zh-hant') {
427 if (preg_match('/^.._..$/', $language->langcode
)) {
428 return $language->langcode
;
431 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language->langcode
, 0, 2));
437 public function setUFLocale($civicrm_language) {
440 $langcode = substr($civicrm_language, 0, 2);
441 $languages = language_list(FALSE, TRUE);
443 if (isset($languages[$langcode])) {
444 $language = $languages[$langcode];
446 // Config must be re-initialized to reset the base URL
447 // otherwise links will have the wrong language prefix/domain.
448 $config = CRM_Core_Config
::singleton();
458 * Determine the native ID of the CMS user.
460 * @param string $username
463 public function getUfId($username) {
464 $user = user_load_by_name($username);
465 if (empty($user->uid
)) {
474 public function logout() {
475 module_load_include('inc', 'user', 'user.pages');
480 * Get the default location for CiviCRM blocks.
484 public function getDefaultBlockLocation() {
485 return 'sidebar_first';
489 * Load Backdrop bootstrap.
491 * @param array $params
492 * Either uid, or name & pass.
493 * @param bool $loadUser
494 * Boolean Require CMS user load.
495 * @param bool $throwError
496 * If true, print error on failure and exit.
497 * @param bool|string $realPath path to script
501 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
502 $cmsPath = $this->cmsRootPath($realPath);
504 if (!file_exists("$cmsPath/core/includes/bootstrap.inc")) {
506 echo '<br />Sorry, could not locate bootstrap.inc\n';
511 // load drupal bootstrap
513 define('BACKDROP_ROOT', $cmsPath);
515 // For drupal multi-site CRM-11313
516 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
517 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
518 if (!empty($matches[1])) {
519 $_SERVER['HTTP_HOST'] = $matches[1];
522 require_once "$cmsPath/core/includes/bootstrap.inc";
523 backdrop_bootstrap(BACKDROP_BOOTSTRAP_FULL
);
525 // Explicitly setting error reporting, since we cannot handle Backdrop
528 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
530 echo '<br />Sorry, could not load Backdrop bootstrap.';
536 // Backdrop successfully bootstrapped.
537 $config = CRM_Core_Config
::singleton();
539 // lets also fix the clean url setting
541 $config->cleanURL
= (int) config_get('system.core', 'clean_url');
543 // we need to call the config hook again, since we now know
544 // all the modules that are listening on it, does not apply
545 // to J! and WP as yet
547 CRM_Utils_Hook
::config($config);
553 $uid = CRM_Utils_Array
::value('uid', $params);
555 // Load the user we need to check Backdrop permissions.
556 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
557 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
560 $uid = user_authenticate($name, $pass);
563 echo '<br />Sorry, unrecognized username or password.';
572 $account = user_load($uid);
573 if ($account && $account->uid
) {
581 echo '<br />Sorry, can not load CMS user account.';
585 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
586 // which means that define(CIVICRM_CLEANURL) was correctly set.
588 $config = CRM_Core_Config
::singleton();
589 $config->cleanURL
= (int) config_get('system.core', 'clean_url');
591 // CRM-8655: Backdrop wasn't available during bootstrap, so
592 // hook_civicrm_config() never executes.
593 CRM_Utils_Hook
::config($config);
601 public function cmsRootPath($scriptFilename = NULL) {
605 if (!is_null($scriptFilename)) {
606 $path = $scriptFilename;
609 $path = $_SERVER['SCRIPT_FILENAME'];
613 $pathVars = explode('/',
614 str_replace('//', '/',
615 str_replace('\\', '/', $path)
619 // Keep the first directory name for later.
620 $firstVar = array_shift($pathVars);
622 // Remove script name to reduce one iteration.
623 array_pop($pathVars);
625 // CRM-7429 -- do check for uppermost 'includes' dir, which would
626 // work for multisite installation.
628 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
629 // Stop if we find backdrop signature file.
630 if (file_exists("$cmsRoot/core/misc/backdrop.js")) {
634 // Remove one directory level.
635 array_pop($pathVars);
636 } while (count($pathVars));
638 return ($valid) ?
$cmsRoot : NULL;
644 public function isUserLoggedIn() {
646 if (function_exists('user_is_logged_in')) {
647 $isloggedIn = user_is_logged_in();
656 public function getLoggedInUfID() {
658 if (function_exists('user_is_logged_in') &&
659 user_is_logged_in() &&
660 function_exists('user_uid_optional_to_arg')
662 $ufID = user_uid_optional_to_arg(array());
671 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
676 if (function_exists('config_get') &&
677 module_exists('locale') &&
678 function_exists('language_negotiation_get')
682 // Check if language support from the URL (Path prefix or domain) is set.
683 if (language_negotiation_get('language') == 'locale-url') {
684 $urlType = config_get('locale.settings', 'locale_language_negotiation_url_part');
686 // URL prefix negotiation.
687 if ($urlType == LANGUAGE_NEGOTIATION_URL_PREFIX
) {
688 if (isset($language->prefix
) && $language->prefix
) {
689 if ($addLanguagePart) {
690 $url .= $language->prefix
. '/';
692 if ($removeLanguagePart) {
693 $url = str_replace("/{$language->prefix}/", '/', $url);
697 // Domain negotiation.
698 if ($urlType == LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
699 if (isset($language->domain
) && $language->domain
) {
700 if ($addLanguagePart) {
701 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
702 // Backdrop function base_path() adds a "/" to the beginning and
703 // end of the returned path.
704 if (substr($cleanedUrl, -1) == '/') {
705 $cleanedUrl = substr($cleanedUrl, 0, -1);
707 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
709 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
710 $url = str_replace('\\', '/', $url);
711 $parseUrl = parse_url($url);
713 //kinda hackish but not sure how to do it right
714 //hope http_build_url() will help at some point.
715 if (is_array($parseUrl) && !empty($parseUrl)) {
716 $urlParts = explode('/', $url);
717 $hostKey = array_search($parseUrl['host'], $urlParts);
718 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
719 $urlParts[$hostKey] = $ufUrlParts['host'];
720 $url = implode('/', $urlParts);
732 * Find any users/roles/security-principals with the given permission
733 * and replace it with one or more permissions.
735 * @param string $oldPerm
736 * @param array $newPerms
739 public function replacePermission($oldPerm, $newPerms) {
740 $roles = user_roles(FALSE, $oldPerm);
741 if (!empty($roles)) {
742 foreach (array_keys($roles) as $rid) {
743 user_role_revoke_permissions($rid, array($oldPerm));
744 user_role_grant_permissions($rid, $newPerms);
750 * Wrapper for og_membership creation.
757 public function og_membership_create($ogID, $userID) {
758 if (function_exists('og_entity_query_alter')) {
759 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
761 // @TODO Find more solid way to check - try system_get_info('module', 'og').
763 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
764 og_group('node', $ogID, array('entity' => user_load($userID)));
767 // Works for the OG 7.x-1.x branch
768 og_group($ogID, array('entity' => user_load($userID)));
773 * Wrapper for og_membership deletion.
780 public function og_membership_delete($ogID, $userID) {
781 if (function_exists('og_entity_query_alter')) {
782 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
783 // TODO: Find a more solid way to make this test
784 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
785 og_ungroup('node', $ogID, 'user', user_load($userID));
788 // Works for the OG 7.x-1.x branch
789 og_ungroup($ogID, 'user', user_load($userID));
796 public function getTimeZoneString() {
798 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
799 if (config_get('system.date', 'user_configurable_timezones') && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
800 $timezone = $user->timezone
;
803 $timezone = config_get('system.date', 'default_timezone');
806 $timezone = parent
::getTimeZoneString();
814 public function setHttpHeader($name, $value) {
815 backdrop_add_http_header($name, $value);
821 public function synchronizeUsers() {
822 $config = CRM_Core_Config
::singleton();
823 if (PHP_SAPI
!= 'cli') {
830 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
832 $user = new StdClass();
833 $uf = $config->userFramework
;
836 $contactMatching = 0;
837 foreach ($result as $row) {
838 $user->$id = $row->$id;
839 $user->$mail = $row->$mail;
840 $user->$name = $row->$name;
842 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
848 if (is_object($match)) {
854 'contactCount' => $contactCount,
855 'contactMatching' => $contactMatching,
856 'contactCreated' => $contactCreated,
863 public function clearResourceCache() {
864 _backdrop_flush_css_js();
868 * Get all the contact emails for users that have a specific permission.
870 * @param string $permissionName
871 * Name of the permission we are interested in.
874 * a comma separated list of email addresses
876 public function permissionEmails($permissionName) {