3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Drupal specific stuff goes here
39 class CRM_Utils_System_Drupal8
extends CRM_Utils_System_DrupalBase
{
42 * Create a user in Drupal.
44 * @param array $params
46 * Email id for cms user.
49 * uid if user exists, false otherwise
51 public function createUser(&$params, $mail) {
52 $user = \Drupal
::currentUser();
53 $user_register_conf = \Drupal
::config('user.settings')->get('register');
54 $verify_mail_conf = \Drupal
::config('user.settings')->get('verify_mail');
56 // Don't create user if we don't have permission to.
57 if (!$user->hasPermission('administer users') && $user_register_conf == 'admin_only') {
61 $account = entity_create('user');
62 $account->setUsername($params['cms_name'])->setEmail($params[$mail]);
64 // Allow user to set password only if they are an admin or if
65 // the site settings don't require email verification.
66 if (!$verify_mail_conf ||
$user->hasPermission('administer users')) {
67 // @Todo: do we need to check that passwords match or assume this has already been done for us?
68 $account->setPassword($params['cms_pass']);
71 // Only activate account if we're admin or if anonymous users don't require
72 // approval to create accounts.
73 if ($user_register_conf != 'visitors' && !$user->hasPermission('administer users')) {
77 // Validate the user object
78 $violations = $account->validate();
79 if (count($violations)) {
86 catch (\Drupal\Core\Entity\EntityStorageException
$e) {
90 // Send off any emails as required.
91 // Possible values for $op:
92 // - 'register_admin_created': Welcome message for user created by the admin.
93 // - 'register_no_approval_required': Welcome message when user
95 // - 'register_pending_approval': Welcome message, user pending admin
97 // @Todo: Should we only send off emails if $params['notify'] is set?
99 case $user_register_conf == 'admin_only' ||
$user->isAuthenticated():
100 _user_mail_notify('register_admin_created', $account);
103 case $user_register_conf == 'visitors':
104 _user_mail_notify('register_no_approval_required', $account);
107 case 'visitors_admin_approval':
108 _user_mail_notify('register_pending_approval', $account);
112 return $account->id();
116 * Update the Drupal user's email address.
120 * @param string $email
121 * Primary contact email address.
123 public function updateCMSName($ufID, $email) {
124 $user = user_load($ufID);
125 if ($user && $user->getEmail() != $email) {
126 $user->setEmail($email);
128 if (!count($user->validate())) {
135 * Check if username and email exists in the drupal db
137 * @param array $params
138 * Array of name and mail values.
139 * @param array $errors
141 * @param string $emailName
142 * Field label for the 'email'.
147 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
148 // If we are given a name, let's check to see if it already exists.
149 if (!empty($params['name'])) {
150 $name = $params['name'];
152 $user = entity_create('user');
153 $user->setUsername($name);
155 // This checks for both username uniqueness and validity.
156 $violations = iterator_to_array($user->validate());
157 // We only care about violations on the username field; discard the rest.
158 $violations = array_filter($violations, function ($v) {
159 return $v->getPropertyPath() == 'name.0.value';
161 if (count($violations) > 0) {
162 $errors['cms_name'] = $violations[0]->getMessage();
166 // And if we are given an email address, let's check to see if it already exists.
167 if (!empty($params[$emailName])) {
168 $mail = $params[$emailName];
170 $user = entity_create('user');
171 $user->setEmail($mail);
173 // This checks for both email uniqueness.
174 $violations = iterator_to_array($user->validate());
175 // We only care about violations on the email field; discard the rest.
176 $violations = array_filter($violations, function ($v) {
177 return $v->getPropertyPath() == 'mail.0.value';
179 if (count($violations) > 0) {
180 $errors[$emailName] = $violations[0]->getMessage();
186 * Get the drupal destination string. When this is passed in the
187 * URL the user will be directed to it after filling in the drupal form
189 * @param CRM_Core_Form $form
190 * Form object representing the 'current' form - to which the user will be returned.
192 * destination value for URL
194 public function getLoginDestination(&$form) {
197 $id = $form->get('id');
202 $gid = $form->get('gid');
204 $args .= "&gid=$gid";
207 // Setup Personal Campaign Page link uses pageId
208 $pageId = $form->get('pageId');
210 $component = $form->get('component');
211 $args .= "&pageId=$pageId&component=$component&action=add";
218 // append destination so user is returned to form they came from after login
219 $destination = CRM_Utils_System
::currentPath() . '?reset=1' . $args;
225 * Get user login URL for hosting CMS (method declared in each CMS system class)
227 * @param string $destination
228 * If present, add destination to querystring (works for Drupal only).
231 * loginURL for the current CMS
233 public function getLoginURL($destination = '') {
234 $query = $destination ?
array('destination' => $destination) : array();
235 return \Drupal
::url('user.page', array(), array('query' => $query));
240 * Sets the title of the page
242 * @param string $title
243 * @param string $pageTitle
247 public function setTitle($title, $pageTitle = NULL) {
252 \Drupal
::service('civicrm.page_state')->setTitle($pageTitle);
256 * Append an additional breadcrumb tag to the existing breadcrumb
258 * @param $breadcrumbs
260 * @internal param string $title
261 * @internal param string $url
265 public function appendBreadCrumb($breadcrumbs) {
266 $civicrmPageState = \Drupal
::service('civicrm.page_state');
267 foreach ($breadcrumbs as $breadcrumb) {
268 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
273 * Reset an additional breadcrumb tag to the existing breadcrumb
277 public function resetBreadCrumb() {
278 \Drupal
::service('civicrm.page_state')->resetBreadcrumbs();
282 * Append a string to the head of the html file
284 * @param string $header
285 * The new string to be appended.
289 public function addHTMLHead($header) {
290 \Drupal
::service('civicrm.page_state')->addHtmlHeader($header);
296 * @param $url : string, absolute path to file
297 * @param string $region
298 * location within the document: 'html-header', 'page-header', 'page-footer'.
300 * Note: This function is not to be called directly
301 * @see CRM_Core_Region::render()
304 * TRUE if we support this operation in this CMS, FALSE otherwise
306 public function addScriptUrl($url, $region) {
307 $options = array('group' => JS_LIBRARY
, 'weight' => 10);
311 $options['scope'] = substr($region, 5);
317 // If the path is within the drupal directory we can use the more efficient 'file' setting
318 $options['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
319 \Drupal
::service('civicrm.page_state')->addJS($url, $options);
324 * Add an inline script
326 * @param $code : string, javascript code
327 * @param string $region
328 * location within the document: 'html-header', 'page-header', 'page-footer'.
330 * Note: This function is not to be called directly
331 * @see CRM_Core_Region::render()
334 * TRUE if we support this operation in this CMS, FALSE otherwise
336 public function addScript($code, $region) {
337 $options = array('type' => 'inline', 'group' => JS_LIBRARY
, 'weight' => 10);
341 $options['scope'] = substr($region, 5);
347 \Drupal
::service('civicrm.page_state')->addJS($code, $options);
354 * @param $url : string, absolute path to file
355 * @param string $region
356 * location within the document: 'html-header', 'page-header', 'page-footer'.
358 * Note: This function is not to be called directly
359 * @see CRM_Core_Region::render()
362 * TRUE if we support this operation in this CMS, FALSE otherwise
364 public function addStyleUrl($url, $region) {
365 if ($region != 'html-header') {
369 // If the path is within the drupal directory we can use the more efficient 'file' setting
370 $options['type'] = $this->formatResourceUrl($url) ?
'file' : 'external';
371 \Drupal
::service('civicrm.page_state')->addCSS($url, $options);
376 * Add an inline style
378 * @param $code : string, css code
379 * @param string $region
380 * location within the document: 'html-header', 'page-header', 'page-footer'.
382 * Note: This function is not to be called directly
383 * @see CRM_Core_Region::render()
386 * TRUE if we support this operation in this CMS, FALSE otherwise
388 public function addStyle($code, $region) {
389 if ($region != 'html-header') {
392 $options = array('type' => 'inline');
393 \Drupal
::service('civicrm.page_state')->addCSS($code, $options);
398 * Check if a resource url is within the drupal directory and format appropriately
400 * This seems to be a legacy function. We assume all resources are within the drupal
401 * directory and always return TRUE. As well, we clean up the $url.
407 public function formatResourceUrl(&$url) {
408 // Remove leading slash if present.
409 $url = ltrim($url, '/');
411 // Remove query string — presumably added to stop intermediary caching.
412 if (($pos = strpos($url, '?')) !== FALSE) {
413 $url = substr($url, 0, $pos);
420 * Rewrite various system urls to https
422 * This function does nothing in Drupal 8. Changes to the base_url should be made
423 * in settings.php directly.
427 public function mapConfigToSSL() {
431 * @param string $path
432 * The base path (eg. civicrm/search/contact).
433 * @param string $query
434 * The query string (eg. reset=1&cid=66) but html encoded(?) (optional).
435 * @param bool $absolute
436 * Produce an absolute including domain and protocol (optional).
437 * @param string $fragment
438 * A named anchor (optional).
439 * @param bool $htmlize
440 * Produce a html encoded url (optional).
441 * @param bool $frontend
442 * A joomla hack (unused).
443 * @param bool $forceBackend
444 * A joomla jack (unused).
447 public function url($path = '', $query = '', $absolute = FALSE, $fragment = '', $htmlize = FALSE, $frontend = FALSE, $forceBackend = FALSE) {
448 $query = html_entity_decode($query);
449 $url = \Drupal\civicrm\CivicrmHelper
::parseURL("{$path}?{$query}");
452 $url = \Drupal
::url($url['route_name'], array(), array(
453 'query' => $url['query'],
454 'absolute' => $absolute,
455 'fragment' => $fragment,
458 catch (Exception
$e) {
463 $url = htmlentities($url);
470 * Authenticate the user against the drupal db
472 * @param string $name
474 * @param string $password
475 * The password for the above user name.
476 * @param bool $loadCMSBootstrap
477 * Load cms bootstrap?.
478 * @param NULL|string $realPath filename of script
481 * [contactID, ufID, uniqueString] if success else false if no auth
483 * This always bootstraps Drupal
485 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
486 (new CRM_Utils_System_Drupal8())->loadBootStrap(array(), FALSE);
488 $uid = \Drupal
::service('user.auth')->authenticate($name, $password);
489 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
491 return array($contact_id, $uid, mt_rand());
495 * Load user into session
497 public function loadUser($username) {
498 $user = user_load_by_name($username);
503 // Set Drupal's current user to the loaded user.
504 \Drupal
::currentUser()->setAccount($user);
507 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
509 // Store the contact id and user id in the session
510 $session = CRM_Core_Session
::singleton();
511 $session->set('ufID', $uid);
512 $session->set('userID', $contact_id);
517 * Determine the native ID of the CMS user
519 * @param string $username
522 public function getUfId($username) {
523 if ($id = user_load_by_name($username)->id()) {
529 * Set a message in the UF to display to a user
531 * @param string $message
532 * The message to set.
534 public function setMessage($message) {
535 drupal_set_message($message);
538 public function permissionDenied() {
539 \Drupal
::service('civicrm.page_state')->setAccessDenied();
543 * In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
544 * to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
546 public function logout() {
551 * Load drupal bootstrap
553 * @param array $params
554 * Either uid, or name & pass.
555 * @param bool $loadUser
556 * Boolean Require CMS user load.
557 * @param bool $throwError
558 * If true, print error on failure and exit.
559 * @param bool|string $realPath path to script
562 * @Todo Handle setting cleanurls configuration for CiviCRM?
564 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
565 static $run_once = FALSE;
573 if (!($root = $this->cmsRootPath())) {
578 // Create a mock $request object
579 $autoloader = require_once $root . '/core/vendor/autoload.php';
580 // @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
581 $request = new \Symfony\Component\HttpFoundation\
Request(array(), array(), array(), array(), array(), $_SERVER);
583 // Create a kernel and boot it.
584 \Drupal\Core\DrupalKernel
::createFromRequest($request, $autoloader, 'prod')->prepareLegacyRequest($request);
586 // Initialize Civicrm
587 \Drupal
::service('civicrm');
589 // We need to call the config hook again, since we now know
590 // all the modules that are listening on it (CRM-8655).
591 CRM_Utils_Hook
::config($config);
594 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User
::load($uid)->getUsername()) {
595 $this->loadUser($username);
597 elseif (!empty($params['name']) && !empty($params['pass']) && $this->authenticate($params['name'], $params['pass'])) {
598 $this->loadUser($params['name']);
605 * Determine the location of the CMS root.
608 * @return NULL|string
610 public function cmsRootPath($path = NULL) {
611 if (defined('DRUPAL_ROOT')) {
615 // It looks like Drupal hasn't been bootstrapped.
616 // We're going to attempt to discover the root Drupal path
617 // by climbing out of the folder hierarchy and looking around to see
618 // if we've found the Drupal root directory.
620 $path = $_SERVER['SCRIPT_FILENAME'];
623 // Normalize and explode path into its component paths.
624 $paths = explode(DIRECTORY_SEPARATOR
, realpath($path));
626 // Remove script filename from array of directories.
629 while (count($paths)) {
630 $candidate = implode('/', $paths);
631 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
640 * Check if user is logged in.
644 public function isUserLoggedIn() {
645 return \Drupal
::currentUser()->isAuthenticated();
649 * Get currently logged in user uf id.
652 * $userID logged in user uf id.
654 public function getLoggedInUfID() {
655 if ($id = \Drupal
::currentUser()->id()) {
661 * Get the default location for CiviCRM blocks
665 public function getDefaultBlockLocation() {
666 return 'sidebar_first';