3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Drupal specific stuff goes here.
21 class CRM_Utils_System_Drupal8
extends CRM_Utils_System_DrupalBase
{
26 public function createUser(&$params, $mail) {
27 $user = \Drupal
::currentUser();
28 $user_register_conf = \Drupal
::config('user.settings')->get('register');
29 $verify_mail_conf = \Drupal
::config('user.settings')->get('verify_mail');
31 // Don't create user if we don't have permission to.
32 if (!$user->hasPermission('administer users') && $user_register_conf == 'admin_only') {
36 /** @var \Drupal\user\Entity\User $account */
37 $account = \Drupal
::entityTypeManager()->getStorage('user')->create();
38 $account->setUsername($params['cms_name'])->setEmail($params[$mail]);
40 // Allow user to set password only if they are an admin or if
41 // the site settings don't require email verification.
42 if (!$verify_mail_conf ||
$user->hasPermission('administer users')) {
43 // @Todo: do we need to check that passwords match or assume this has already been done for us?
44 $account->setPassword($params['cms_pass']);
47 // Only activate account if we're admin or if anonymous users don't require
48 // approval to create accounts.
49 if ($user_register_conf != 'visitors' && !$user->hasPermission('administer users')) {
56 // Validate the user object
57 $violations = $account->validate();
58 if (count($violations)) {
59 foreach ($violations as $violation) {
60 CRM_Core_Session
::setStatus($violation->getPropertyPath() . ': ' . $violation->getMessage(), '', 'alert');
65 // Let the Drupal module know we're already in CiviCRM.
66 $config = CRM_Core_Config
::singleton();
67 $config->inCiviCRM
= TRUE;
71 $config->inCiviCRM
= FALSE;
73 catch (\Drupal\Core\Entity\EntityStorageException
$e) {
74 $config->inCiviCRM
= FALSE;
78 // Send off any emails as required.
79 // Possible values for $op:
80 // - 'register_admin_created': Welcome message for user created by the admin.
81 // - 'register_no_approval_required': Welcome message when user
83 // - 'register_pending_approval': Welcome message, user pending admin
86 case $user_register_conf == 'admin_only' ||
$user->isAuthenticated():
87 if (!empty($params['notify'])) {
88 _user_mail_notify('register_admin_created', $account);
92 case $user_register_conf == 'visitors':
93 _user_mail_notify('register_no_approval_required', $account);
96 case 'visitors_admin_approval':
97 _user_mail_notify('register_pending_approval', $account);
101 // If this is a user creating their own account, login them in!
102 if (!$verify_mail_conf && $account->isActive() && $user->isAnonymous()) {
103 \
user_login_finalize($account);
106 return $account->id();
112 public function updateCMSName($ufID, $email) {
113 $user = \Drupal
::entityTypeManager()->getStorage('user')->load($ufID);
114 if ($user && $user->getEmail() != $email) {
115 $user->setEmail($email);
117 // Skip requirement for password when changing the current user fields
118 $user->_skipProtectedUserFieldConstraint
= TRUE;
120 if (!count($user->validate())) {
127 * Check if username and email exists in the drupal db.
129 * @param array $params
130 * Array of name and mail values.
131 * @param array $errors
133 * @param string $emailName
134 * Field label for the 'email'.
136 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
137 // If we are given a name, let's check to see if it already exists.
138 if (!empty($params['name'])) {
139 $name = $params['name'];
141 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
142 $user->setUsername($name);
144 // This checks for both username uniqueness and validity.
145 $violations = iterator_to_array($user->validate());
146 // We only care about violations on the username field; discard the rest.
147 $violations = array_values(array_filter($violations, function ($v) {
148 return $v->getPropertyPath() == 'name';
150 if (count($violations) > 0) {
151 $errors['cms_name'] = (string) $violations[0]->getMessage();
155 // And if we are given an email address, let's check to see if it already exists.
156 if (!empty($params['mail'])) {
157 $mail = $params['mail'];
159 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
160 $user->setEmail($mail);
162 // This checks for both email uniqueness.
163 $violations = iterator_to_array($user->validate());
164 // We only care about violations on the email field; discard the rest.
165 $violations = array_values(array_filter($violations, function ($v) {
166 return $v->getPropertyPath() == 'mail';
168 if (count($violations) > 0) {
169 $errors[$emailName] = (string) $violations[0]->getMessage();
177 public function getLoginURL($destination = '') {
178 $query = $destination ?
['destination' => $destination] : [];
179 return \Drupal\Core\Url
::fromRoute('user.login', [], ['query' => $query])->toString();
185 public function setTitle($title, $pageTitle = NULL) {
189 \Drupal
::service('civicrm.page_state')->setTitle($pageTitle);
195 public function appendBreadCrumb($breadcrumbs) {
196 $civicrmPageState = \Drupal
::service('civicrm.page_state');
197 foreach ($breadcrumbs as $breadcrumb) {
198 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
205 public function resetBreadCrumb() {
206 \Drupal
::service('civicrm.page_state')->resetBreadcrumbs();
212 public function addHTMLHead($header) {
213 \Drupal
::service('civicrm.page_state')->addHtmlHeader($header);
219 public function addStyleUrl($url, $region) {
220 if ($region != 'html-header') {
227 'rel' => 'stylesheet',
230 \Drupal
::service('civicrm.page_state')->addCSS($css);
237 public function addStyle($code, $region) {
238 if ($region != 'html-header') {
245 \Drupal
::service('civicrm.page_state')->addCSS($css);
250 * Check if a resource url is within the drupal directory and format appropriately.
252 * This seems to be a legacy function. We assume all resources are within the drupal
253 * directory and always return TRUE. As well, we clean up the $url.
255 * FIXME: This is not a legacy function and the above is not a safe assumption.
256 * External urls are allowed by CRM_Core_Resources and this needs to return the correct value.
262 public function formatResourceUrl(&$url) {
263 // Remove leading slash if present.
264 $url = ltrim($url, '/');
266 // Remove query string — presumably added to stop intermediary caching.
267 if (($pos = strpos($url, '?')) !== FALSE) {
268 $url = substr($url, 0, $pos);
270 // FIXME: Should not unconditionally return true
275 * This function does nothing in Drupal 8. Changes to the base_url should be made
276 * in settings.php directly.
278 public function mapConfigToSSL() {
290 $forceBackend = FALSE,
293 $query = html_entity_decode($query);
295 $config = CRM_Core_Config
::singleton();
296 $base = $absolute ?
$config->userFrameworkBaseURL
: 'internal:/';
298 $url = $this->parseURL("{$path}?{$query}");
300 // Not all links that CiviCRM generates are Drupal routes, so we use the weaker ::fromUri method.
302 $url = \Drupal\Core\Url
::fromUri("{$base}{$url['path']}", array(
303 'query' => $url['query'],
304 'fragment' => $fragment,
305 'absolute' => $absolute,
308 catch (Exception
$e) {
309 \Drupal
::logger('civicrm')->error($e->getMessage());
318 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
319 /* Before we do any loading, let's start the session and write to it.
320 * We typically call authenticate only when we need to bootstrap the CMS
321 * directly via Civi and hence bypass the normal CMS auth and bootstrap
322 * process typically done in CLI and cron scripts. See: CRM-12648
324 $session = CRM_Core_Session
::singleton();
325 $session->set('civicrmInitSession', TRUE);
327 $system = new CRM_Utils_System_Drupal8();
328 $system->loadBootStrap([], FALSE);
330 $uid = \Drupal
::service('user.auth')->authenticate($name, $password);
332 if ($this->loadUser($name)) {
333 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
334 return [$contact_id, $uid, mt_rand()];
344 public function loadUser($username) {
345 $user = user_load_by_name($username);
350 // Set Drupal's current user to the loaded user.
351 \Drupal
::currentUser()->setAccount($user);
354 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
356 // Store the contact id and user id in the session
357 $session = CRM_Core_Session
::singleton();
358 $session->set('ufID', $uid);
359 $session->set('userID', $contact_id);
364 * Determine the native ID of the CMS user.
366 * @param string $username
369 public function getUfId($username) {
370 $user = user_load_by_name($username);
371 if ($user && $id = $user->id()) {
379 public function permissionDenied() {
380 \Drupal
::service('civicrm.page_state')->setAccessDenied();
384 * In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
385 * to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
387 public function logout() {
392 * Load drupal bootstrap.
394 * @param array $params
395 * Either uid, or name & pass.
396 * @param bool $loadUser
397 * Boolean Require CMS user load.
398 * @param bool $throwError
399 * If true, print error on failure and exit.
400 * @param bool|string $realPath path to script
403 * @Todo Handle setting cleanurls configuration for CiviCRM?
405 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
406 static $run_once = FALSE;
414 if (!($root = $this->cmsRootPath())) {
419 // Create a mock $request object
420 $autoloader = require_once $root . '/autoload.php';
421 if ($autoloader === TRUE) {
422 $autoloader = ComposerAutoloaderInitDrupal8
::getLoader();
424 // @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
425 $request = new \Symfony\Component\HttpFoundation\
Request([], [], [], [], [], $_SERVER);
427 // Create a kernel and boot it.
428 $kernel = \Drupal\Core\DrupalKernel
::createFromRequest($request, $autoloader, 'prod');
430 $kernel->preHandle($request);
431 $container = $kernel->rebuildContainer();
432 // Add our request to the stack and route context.
433 $routeInterface = class_exists('\Drupal\Core\Routing\RouteObjectInterface')
434 ?
'\Drupal\Core\Routing\RouteObjectInterface'
435 : '\Symfony\Cmf\Component\Routing\RouteObjectInterface';
436 $request->attributes
->set($routeInterface::ROUTE_OBJECT
, new \Symfony\Component\Routing\
Route('<none>'));
437 $request->attributes
->set($routeInterface::ROUTE_NAME
, '<none>');
438 $container->get('request_stack')->push($request);
439 $container->get('router.request_context')->fromRequest($request);
441 // Initialize Civicrm
442 \Drupal
::service('civicrm')->initialize();
444 // We need to call the config hook again, since we now know
445 // all the modules that are listening on it (CRM-8655).
446 CRM_Utils_Hook
::config($config);
449 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User
::load($params['uid'])->getAccountName()) {
450 $this->loadUser($username);
452 elseif (!empty($params['name']) && !empty($params['pass']) && \Drupal
::service('user.auth')->authenticate($params['name'], $params['pass'])) {
453 $this->loadUser($params['name']);
460 * Determine the location of the CMS root.
462 * @param string $path
464 * @return NULL|string
466 public function cmsRootPath($path = NULL) {
467 global $civicrm_paths;
468 if (!empty($civicrm_paths['cms.root']['path'])) {
469 return $civicrm_paths['cms.root']['path'];
472 if (defined('DRUPAL_ROOT')) {
476 // It looks like Drupal hasn't been bootstrapped.
477 // We're going to attempt to discover the root Drupal path
478 // by climbing out of the folder hierarchy and looking around to see
479 // if we've found the Drupal root directory.
481 $path = $_SERVER['SCRIPT_FILENAME'];
484 // Normalize and explode path into its component paths.
485 $paths = explode(DIRECTORY_SEPARATOR
, realpath($path));
487 // Remove script filename from array of directories.
490 while (count($paths)) {
491 $candidate = implode('/', $paths);
492 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
503 public function isUserLoggedIn() {
504 return \Drupal
::currentUser()->isAuthenticated();
510 public function isUserRegistrationPermitted() {
511 if (\Drupal
::config('user.settings')->get('register') == 'admin_only') {
520 public function isPasswordUserGenerated() {
521 if (\Drupal
::config('user.settings')->get('verify_mail') == TRUE) {
530 public function updateCategories() {
531 // @todo Is anything necessary?
537 public function getLoggedInUfID() {
538 if ($id = \Drupal
::currentUser()->id()) {
546 public function getDefaultBlockLocation() {
547 return 'sidebar_first';
553 public function flush() {
554 // CiviCRM and Drupal both provide (different versions of) Symfony (and possibly share other classes too).
555 // If we call drupal_flush_all_caches(), Drupal will attempt to rediscover all of its classes, use Civicrm's
556 // alternatives instead and then die. Instead, we only clear cache bins and no more.
557 foreach (Drupal\Core\Cache\Cache
::getBins() as $service_id => $cache_backend) {
558 $cache_backend->deleteAll();
565 public function getModules() {
568 $module_data = \Drupal
::service('extension.list.module')->reset()->getList();
569 foreach ($module_data as $module_name => $extension) {
570 if (!isset($extension->info
['hidden']) && $extension->origin
!= 'core' && $extension->status
== 1) {
571 $modules[] = new CRM_Core_Module('drupal.' . $module_name, TRUE);
580 public function getUser($contactID) {
581 $user_details = parent
::getUser($contactID);
582 $user_details['name'] = $user_details['name']->value
;
583 $user_details['email'] = $user_details['email']->value
;
584 return $user_details;
590 public function getUniqueIdentifierFromUserObject($user) {
591 return $user->get('mail')->value
;
597 public function getUserIDFromUserObject($user) {
598 return $user->get('uid')->value
;
604 public function synchronizeUsers() {
605 $config = CRM_Core_Config
::singleton();
606 if (PHP_SAPI
!= 'cli') {
611 $users = \Drupal
::entityTypeManager()->getStorage('user')->loadByProperties();
613 $uf = $config->userFramework
;
616 $contactMatching = 0;
617 foreach ($users as $user) {
618 $mail = $user->get('mail')->value
;
622 $uid = $user->get('uid')->value
;
624 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $uid, $mail, $uf, 1, 'Individual', TRUE)) {
633 'contactCount' => $contactCount,
634 'contactMatching' => $contactMatching,
635 'contactCreated' => $contactCreated,
642 public function setMessage($message) {
643 // CiviCRM sometimes includes markup in messages (ex: Event Cart)
644 // it needs to be rendered before being displayed.
645 $message = \Drupal\Core\Render\Markup
::create($message);
646 \Drupal
::messenger()->addMessage($message);
650 * Drupal 8 has a different function to get current path, hence
651 * overriding the postURL function
653 * @param string $action
657 public function postURL($action) {
658 if (!empty($action)) {
661 $current_path = \Drupal
::service('path.current')->getPath();
662 return $this->url($current_path);
666 * Function to return current language of Drupal8
670 public function getCurrentLanguage() {
671 // Drupal might not be bootstrapped if being called by the REST API.
672 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
676 return \Drupal
::languageManager()->getConfigOverrideLanguage()->getId();
680 * Helper function to extract path, query and route name from Civicrm URLs.
682 * For example, 'civicrm/contact/view?reset=1&cid=66' will be returned as:
686 * 'path' => 'civicrm/contact/view',
687 * 'route' => 'civicrm.civicrm_contact_view',
688 * 'query' => array('reset' => '1', 'cid' => '66'),
696 * The parsed url parts, containing 'path', 'route' and 'query'.
698 public function parseUrl($url) {
699 $processed = ['path' => '', 'route_name' => '', 'query' => []];
701 // Remove leading '/' if it exists.
702 $url = ltrim($url, '/');
704 // Separate out the url into its path and query components.
705 $url = parse_url($url);
706 if (empty($url['path'])) {
709 $processed['path'] = $url['path'];
711 // Create a route name by replacing the forward slashes in the path with
712 // underscores, civicrm/contact/search => civicrm.civicrm_contact_search.
713 $processed['route_name'] = 'civicrm.' . implode('_', explode('/', $url['path']));
715 // Turn the query string (if it exists) into an associative array.
716 if (!empty($url['query'])) {
717 parse_str($url['query'], $processed['query']);
724 * Append Drupal8 js to coreResourcesList.
726 * @param \Civi\Core\Event\GenericHookEvent $e
728 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
729 $e->list[] = 'js/crm.drupal8.js';
735 public function getTimeZoneString() {
736 $timezone = date_default_timezone_get();
743 public function setUFLocale($civicrm_language) {
744 $langcode = substr(str_replace('_', '', $civicrm_language), 0, 2);
745 $languageManager = \Drupal
::languageManager();
746 $languages = $languageManager->getLanguages();
748 if (isset($languages[$langcode])) {
749 $languageManager->setConfigOverrideLanguage($languages[$langcode]);
751 // Config must be re-initialized to reset the base URL
752 // otherwise links will have the wrong language prefix/domain.
753 $config = CRM_Core_Config
::singleton();
765 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
770 // Drupal might not be bootstrapped if being called by the REST API.
771 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
775 $language = $this->getCurrentLanguage();
776 if (\Drupal
::service('module_handler')->moduleExists('language')) {
777 $config = \Drupal
::config('language.negotiation')->get('url');
779 //does user configuration allow language
780 //support from the URL (Path prefix or domain)
781 $enabledLanguageMethods = \Drupal
::config('language.types')->get('negotiation.language_interface.enabled') ?
: [];
782 if (array_key_exists(\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::METHOD_ID
, $enabledLanguageMethods)) {
783 $urlType = $config['source'];
786 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_PATH_PREFIX
) {
787 if (!empty($language)) {
788 if ($addLanguagePart && !empty($config['prefixes'][$language])) {
789 $url .= $config['prefixes'][$language] . '/';
791 if ($removeLanguagePart && !empty($config['prefixes'][$language])) {
792 $url = str_replace("/" . $config['prefixes'][$language] . "/", '/', $url);
797 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_DOMAIN
) {
798 if (isset($language->domain
) && $language->domain
) {
799 if ($addLanguagePart) {
800 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $config['domains'][$language] . base_path();
802 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
803 $url = str_replace('\\', '/', $url);
804 $parseUrl = parse_url($url);
806 //kinda hackish but not sure how to do it right
807 //hope http_build_url() will help at some point.
808 if (is_array($parseUrl) && !empty($parseUrl)) {
809 $urlParts = explode('/', $url);
810 $hostKey = array_search($parseUrl['host'], $urlParts);
811 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
812 $urlParts[$hostKey] = $ufUrlParts['host'];
813 $url = implode('/', $urlParts);
829 public function getRoleNames() {
830 return user_role_names();
834 * Determine if the Views module exists.
838 public function viewsExists() {
839 if (\Drupal
::moduleHandler()->moduleExists('views')) {
846 * Return the CMS-specific url for its permissions page
849 public function getCMSPermissionsUrlParams() {
850 return ['ufAccessURL' => \Drupal\Core\Url
::fromRoute('user.admin_permissions')->toString()];
854 * Start a new session.
856 public function sessionStart() {
857 if (\Drupal
::hasContainer()) {
858 $session = \Drupal
::service('session');
859 if (!$session->isStarted()) {
868 public function getSessionId() {
869 if (\Drupal
::hasContainer()) {
870 $session = \Drupal
::service('session');
871 if (!$session->has('civicrm.tempstore.sessionid')) {
872 $session->set('civicrm.tempstore.sessionid', \Drupal\Component\Utility\Crypt
::randomBytesBase64());
874 return $session->get('civicrm.tempstore.sessionid');
880 * Load the user object.
886 public function getUserObject($userID) {
887 return \Drupal
::entityTypeManager()->getStorage('user')->load($userID);
891 * Helper function to rebuild the Drupal 8 or 9 dynamic routing cache.
892 * We need to do this after enabling extensions that add routes and it's worth doing when we reset Civi paths.
894 public function invalidateRouteCache() {
895 if (class_exists('\Drupal') && \Drupal
::hasContainer()) {
896 \Drupal
::service('router.builder')->rebuild();
900 public function getVersion() {
901 if (class_exists('\Drupal')) {
902 return \Drupal
::VERSION
;