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);
407 * Determine the native ID of the CMS user.
409 * @param string $username
412 public function getUfId($username) {
413 $user = user_load_by_name($username);
414 if (empty($user->uid
)) {
423 public function logout() {
424 module_load_include('inc', 'user', 'user.pages');
429 * Get the default location for CiviCRM blocks.
433 public function getDefaultBlockLocation() {
434 return 'sidebar_first';
438 * Load Backdrop bootstrap.
440 * @param array $params
441 * Either uid, or name & pass.
442 * @param bool $loadUser
443 * Boolean Require CMS user load.
444 * @param bool $throwError
445 * If true, print error on failure and exit.
446 * @param bool|string $realPath path to script
450 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
451 $cmsPath = $this->cmsRootPath($realPath);
453 if (!file_exists("$cmsPath/core/includes/bootstrap.inc")) {
455 echo '<br />Sorry, could not locate bootstrap.inc\n';
460 // load drupal bootstrap
462 define('BACKDROP_ROOT', $cmsPath);
464 // For drupal multi-site CRM-11313
465 if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
466 preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
467 if (!empty($matches[1])) {
468 $_SERVER['HTTP_HOST'] = $matches[1];
471 require_once "$cmsPath/core/includes/bootstrap.inc";
472 backdrop_bootstrap(BACKDROP_BOOTSTRAP_FULL
);
474 // Explicitly setting error reporting, since we cannot handle Backdrop
477 if (!function_exists('module_exists') ||
!module_exists('civicrm')) {
479 echo '<br />Sorry, could not load Backdrop bootstrap.';
485 // Backdrop successfully bootstrapped.
486 $config = CRM_Core_Config
::singleton();
488 // lets also fix the clean url setting
490 $config->cleanURL
= (int) config_get('system.core', 'clean_url');
492 // we need to call the config hook again, since we now know
493 // all the modules that are listening on it, does not apply
494 // to J! and WP as yet
496 CRM_Utils_Hook
::config($config);
502 $uid = CRM_Utils_Array
::value('uid', $params);
504 // Load the user we need to check Backdrop permissions.
505 $name = CRM_Utils_Array
::value('name', $params, FALSE) ?
$params['name'] : trim(CRM_Utils_Array
::value('name', $_REQUEST));
506 $pass = CRM_Utils_Array
::value('pass', $params, FALSE) ?
$params['pass'] : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
509 $uid = user_authenticate($name, $pass);
512 echo '<br />Sorry, unrecognized username or password.';
521 $account = user_load($uid);
522 if ($account && $account->uid
) {
530 echo '<br />Sorry, can not load CMS user account.';
534 // CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
535 // which means that define(CIVICRM_CLEANURL) was correctly set.
537 $config = CRM_Core_Config
::singleton();
538 $config->cleanURL
= (int) config_get('system.core', 'clean_url');
540 // CRM-8655: Backdrop wasn't available during bootstrap, so
541 // hook_civicrm_config() never executes.
542 CRM_Utils_Hook
::config($config);
550 public function cmsRootPath($scriptFilename = NULL) {
554 if (!is_null($scriptFilename)) {
555 $path = $scriptFilename;
558 $path = $_SERVER['SCRIPT_FILENAME'];
562 $pathVars = explode('/',
563 str_replace('//', '/',
564 str_replace('\\', '/', $path)
568 // Keep the first directory name for later.
569 $firstVar = array_shift($pathVars);
571 // Remove script name to reduce one iteration.
572 array_pop($pathVars);
574 // CRM-7429 -- do check for uppermost 'includes' dir, which would
575 // work for multisite installation.
577 $cmsRoot = $firstVar . '/' . implode('/', $pathVars);
578 // Stop if we find backdrop signature file.
579 if (file_exists("$cmsRoot/core/misc/backdrop.js")) {
583 // Remove one directory level.
584 array_pop($pathVars);
585 } while (count($pathVars));
587 return ($valid) ?
$cmsRoot : NULL;
593 public function isUserLoggedIn() {
595 if (function_exists('user_is_logged_in')) {
596 $isloggedIn = user_is_logged_in();
605 public function getLoggedInUfID() {
607 if (function_exists('user_is_logged_in') &&
608 user_is_logged_in() &&
609 function_exists('user_uid_optional_to_arg')
611 $ufID = user_uid_optional_to_arg(array());
620 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
625 if (function_exists('config_get') &&
626 module_exists('locale') &&
627 function_exists('language_negotiation_get')
631 // Check if language support from the URL (Path prefix or domain) is set.
632 if (language_negotiation_get('language') == 'locale-url') {
633 $urlType = config_get('locale.settings', 'locale_language_negotiation_url_part');
635 // URL prefix negotiation.
636 if ($urlType == LANGUAGE_NEGOTIATION_URL_PREFIX
) {
637 if (isset($language->prefix
) && $language->prefix
) {
638 if ($addLanguagePart) {
639 $url .= $language->prefix
. '/';
641 if ($removeLanguagePart) {
642 $url = str_replace("/{$language->prefix}/", '/', $url);
646 // Domain negotiation.
647 if ($urlType == LANGUAGE_NEGOTIATION_URL_DOMAIN
) {
648 if (isset($language->domain
) && $language->domain
) {
649 if ($addLanguagePart) {
650 $cleanedUrl = preg_replace('#^https?://#', '', $language->domain
);
651 // Backdrop function base_path() adds a "/" to the beginning and
652 // end of the returned path.
653 if (substr($cleanedUrl, -1) == '/') {
654 $cleanedUrl = substr($cleanedUrl, 0, -1);
656 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $cleanedUrl . base_path();
658 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
659 $url = str_replace('\\', '/', $url);
660 $parseUrl = parse_url($url);
662 //kinda hackish but not sure how to do it right
663 //hope http_build_url() will help at some point.
664 if (is_array($parseUrl) && !empty($parseUrl)) {
665 $urlParts = explode('/', $url);
666 $hostKey = array_search($parseUrl['host'], $urlParts);
667 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
668 $urlParts[$hostKey] = $ufUrlParts['host'];
669 $url = implode('/', $urlParts);
681 * Find any users/roles/security-principals with the given permission
682 * and replace it with one or more permissions.
684 * @param string $oldPerm
685 * @param array $newPerms
688 public function replacePermission($oldPerm, $newPerms) {
689 $roles = user_roles(FALSE, $oldPerm);
690 if (!empty($roles)) {
691 foreach (array_keys($roles) as $rid) {
692 user_role_revoke_permissions($rid, array($oldPerm));
693 user_role_grant_permissions($rid, $newPerms);
699 * Wrapper for og_membership creation.
706 public function og_membership_create($ogID, $userID) {
707 if (function_exists('og_entity_query_alter')) {
708 // sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
710 // @TODO Find more solid way to check - try system_get_info('module', 'og').
712 // Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
713 og_group('node', $ogID, array('entity' => user_load($userID)));
716 // Works for the OG 7.x-1.x branch
717 og_group($ogID, array('entity' => user_load($userID)));
722 * Wrapper for og_membership deletion.
729 public function og_membership_delete($ogID, $userID) {
730 if (function_exists('og_entity_query_alter')) {
731 // sort-of-randomly chose a function that only exists in the 7.x-2.x branch
732 // TODO: Find a more solid way to make this test
733 // Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
734 og_ungroup('node', $ogID, 'user', user_load($userID));
737 // Works for the OG 7.x-1.x branch
738 og_ungroup($ogID, 'user', user_load($userID));
745 public function getTimeZoneString() {
747 // Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
748 if (config_get('system.date', 'user_configurable_timezones') && $user->uid
&& isset($user->timezone
) && strlen($user->timezone
)) {
749 $timezone = $user->timezone
;
752 $timezone = config_get('system.date', 'default_timezone');
755 $timezone = parent
::getTimeZoneString();
763 public function setHttpHeader($name, $value) {
764 backdrop_add_http_header($name, $value);
770 public function synchronizeUsers() {
771 $config = CRM_Core_Config
::singleton();
772 if (PHP_SAPI
!= 'cli') {
779 $result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
781 $user = new StdClass();
782 $uf = $config->userFramework
;
785 $contactMatching = 0;
786 foreach ($result as $row) {
787 $user->$id = $row->$id;
788 $user->$mail = $row->$mail;
789 $user->$name = $row->$name;
791 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
797 if (is_object($match)) {
803 'contactCount' => $contactCount,
804 'contactMatching' => $contactMatching,
805 'contactCreated' => $contactCreated,
812 public function clearResourceCache() {
813 _backdrop_flush_css_js();
817 * Get all the contact emails for users that have a specific permission.
819 * @param string $permissionName
820 * Name of the permission we are interested in.
823 * a comma separated list of email addresses
825 public function permissionEmails($permissionName) {