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 if (!count($user->validate())) {
124 * Check if username and email exists in the drupal db.
126 * @param array $params
127 * Array of name and mail values.
128 * @param array $errors
130 * @param string $emailName
131 * Field label for the 'email'.
133 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
134 // If we are given a name, let's check to see if it already exists.
135 if (!empty($params['name'])) {
136 $name = $params['name'];
138 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
139 $user->setUsername($name);
141 // This checks for both username uniqueness and validity.
142 $violations = iterator_to_array($user->validate());
143 // We only care about violations on the username field; discard the rest.
144 $violations = array_values(array_filter($violations, function ($v) {
145 return $v->getPropertyPath() == 'name';
147 if (count($violations) > 0) {
148 $errors['cms_name'] = (string) $violations[0]->getMessage();
152 // And if we are given an email address, let's check to see if it already exists.
153 if (!empty($params['mail'])) {
154 $mail = $params['mail'];
156 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
157 $user->setEmail($mail);
159 // This checks for both email uniqueness.
160 $violations = iterator_to_array($user->validate());
161 // We only care about violations on the email field; discard the rest.
162 $violations = array_values(array_filter($violations, function ($v) {
163 return $v->getPropertyPath() == 'mail';
165 if (count($violations) > 0) {
166 $errors[$emailName] = (string) $violations[0]->getMessage();
174 public function getLoginURL($destination = '') {
175 $query = $destination ?
['destination' => $destination] : [];
176 return \Drupal\Core\Url
::fromRoute('user.login', [], ['query' => $query])->toString();
182 public function setTitle($title, $pageTitle = NULL) {
186 \Drupal
::service('civicrm.page_state')->setTitle($pageTitle);
192 public function appendBreadCrumb($breadcrumbs) {
193 $civicrmPageState = \Drupal
::service('civicrm.page_state');
194 foreach ($breadcrumbs as $breadcrumb) {
195 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
202 public function resetBreadCrumb() {
203 \Drupal
::service('civicrm.page_state')->resetBreadcrumbs();
209 public function addHTMLHead($header) {
210 \Drupal
::service('civicrm.page_state')->addHtmlHeader($header);
216 public function addStyleUrl($url, $region) {
217 if ($region != 'html-header') {
224 'rel' => 'stylesheet',
227 \Drupal
::service('civicrm.page_state')->addCSS($css);
234 public function addStyle($code, $region) {
235 if ($region != 'html-header') {
242 \Drupal
::service('civicrm.page_state')->addCSS($css);
247 * Check if a resource url is within the drupal directory and format appropriately.
249 * This seems to be a legacy function. We assume all resources are within the drupal
250 * directory and always return TRUE. As well, we clean up the $url.
252 * FIXME: This is not a legacy function and the above is not a safe assumption.
253 * External urls are allowed by CRM_Core_Resources and this needs to return the correct value.
259 public function formatResourceUrl(&$url) {
260 // Remove leading slash if present.
261 $url = ltrim($url, '/');
263 // Remove query string — presumably added to stop intermediary caching.
264 if (($pos = strpos($url, '?')) !== FALSE) {
265 $url = substr($url, 0, $pos);
267 // FIXME: Should not unconditionally return true
272 * This function does nothing in Drupal 8. Changes to the base_url should be made
273 * in settings.php directly.
275 public function mapConfigToSSL() {
287 $forceBackend = FALSE,
290 $query = html_entity_decode($query);
292 $config = CRM_Core_Config
::singleton();
293 $base = $absolute ?
$config->userFrameworkBaseURL
: 'internal:/';
295 $url = $this->parseURL("{$path}?{$query}");
297 // Not all links that CiviCRM generates are Drupal routes, so we use the weaker ::fromUri method.
299 $url = \Drupal\Core\Url
::fromUri("{$base}{$url['path']}", array(
300 'query' => $url['query'],
301 'fragment' => $fragment,
302 'absolute' => $absolute,
305 catch (Exception
$e) {
306 \Drupal
::logger('civicrm')->error($e->getMessage());
315 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
316 $system = new CRM_Utils_System_Drupal8();
317 $system->loadBootStrap([], FALSE);
319 $uid = \Drupal
::service('user.auth')->authenticate($name, $password);
321 if ($this->loadUser($name)) {
322 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
323 return [$contact_id, $uid, mt_rand()];
333 public function loadUser($username) {
334 $user = user_load_by_name($username);
339 // Set Drupal's current user to the loaded user.
340 \Drupal
::currentUser()->setAccount($user);
343 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
345 // Store the contact id and user id in the session
346 $session = CRM_Core_Session
::singleton();
347 $session->set('ufID', $uid);
348 $session->set('userID', $contact_id);
353 * Determine the native ID of the CMS user.
355 * @param string $username
358 public function getUfId($username) {
359 if ($id = user_load_by_name($username)->id()) {
367 public function permissionDenied() {
368 \Drupal
::service('civicrm.page_state')->setAccessDenied();
372 * In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
373 * to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
375 public function logout() {
380 * Load drupal bootstrap.
382 * @param array $params
383 * Either uid, or name & pass.
384 * @param bool $loadUser
385 * Boolean Require CMS user load.
386 * @param bool $throwError
387 * If true, print error on failure and exit.
388 * @param bool|string $realPath path to script
391 * @Todo Handle setting cleanurls configuration for CiviCRM?
393 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
394 static $run_once = FALSE;
402 if (!($root = $this->cmsRootPath())) {
407 // Create a mock $request object
408 $autoloader = require_once $root . '/autoload.php';
409 if ($autoloader === TRUE) {
410 $autoloader = ComposerAutoloaderInitDrupal8
::getLoader();
412 // @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
413 $request = new \Symfony\Component\HttpFoundation\
Request([], [], [], [], [], $_SERVER);
415 // Create a kernel and boot it.
416 $kernel = \Drupal\Core\DrupalKernel
::createFromRequest($request, $autoloader, 'prod');
418 $kernel->preHandle($request);
419 $container = $kernel->rebuildContainer();
420 // Add our request to the stack and route context.
421 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_OBJECT
, new \Symfony\Component\Routing\
Route('<none>'));
422 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_NAME
, '<none>');
423 $container->get('request_stack')->push($request);
424 $container->get('router.request_context')->fromRequest($request);
426 // Initialize Civicrm
427 \Drupal
::service('civicrm')->initialize();
429 // We need to call the config hook again, since we now know
430 // all the modules that are listening on it (CRM-8655).
431 CRM_Utils_Hook
::config($config);
434 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User
::load($params['uid'])->getAccountName()) {
435 $this->loadUser($username);
437 elseif (!empty($params['name']) && !empty($params['pass']) && \Drupal
::service('user.auth')->authenticate($params['name'], $params['pass'])) {
438 $this->loadUser($params['name']);
445 * Determine the location of the CMS root.
447 * @param string $path
449 * @return NULL|string
451 public function cmsRootPath($path = NULL) {
452 global $civicrm_paths;
453 if (!empty($civicrm_paths['cms.root']['path'])) {
454 return $civicrm_paths['cms.root']['path'];
457 if (defined('DRUPAL_ROOT')) {
461 // It looks like Drupal hasn't been bootstrapped.
462 // We're going to attempt to discover the root Drupal path
463 // by climbing out of the folder hierarchy and looking around to see
464 // if we've found the Drupal root directory.
466 $path = $_SERVER['SCRIPT_FILENAME'];
469 // Normalize and explode path into its component paths.
470 $paths = explode(DIRECTORY_SEPARATOR
, realpath($path));
472 // Remove script filename from array of directories.
475 while (count($paths)) {
476 $candidate = implode('/', $paths);
477 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
488 public function isUserLoggedIn() {
489 return \Drupal
::currentUser()->isAuthenticated();
495 public function isUserRegistrationPermitted() {
496 if (\Drupal
::config('user.settings')->get('register') == 'admin_only') {
505 public function isPasswordUserGenerated() {
506 if (\Drupal
::config('user.settings')->get('verify_mail') == TRUE) {
515 public function updateCategories() {
516 // @todo Is anything necessary?
522 public function getLoggedInUfID() {
523 if ($id = \Drupal
::currentUser()->id()) {
531 public function getDefaultBlockLocation() {
532 return 'sidebar_first';
538 public function flush() {
539 // CiviCRM and Drupal both provide (different versions of) Symfony (and possibly share other classes too).
540 // If we call drupal_flush_all_caches(), Drupal will attempt to rediscover all of its classes, use Civicrm's
541 // alternatives instead and then die. Instead, we only clear cache bins and no more.
542 foreach (Drupal\Core\Cache\Cache
::getBins() as $service_id => $cache_backend) {
543 $cache_backend->deleteAll();
550 public function getModules() {
553 $module_data = \Drupal
::service('extension.list.module')->reset()->getList();
554 foreach ($module_data as $module_name => $extension) {
555 if (!isset($extension->info
['hidden']) && $extension->origin
!= 'core') {
556 $extension->schema_version
= drupal_get_installed_schema_version($module_name);
557 $modules[] = new CRM_Core_Module('drupal.' . $module_name, ($extension->status
== 1));
566 public function getUser($contactID) {
567 $user_details = parent
::getUser($contactID);
568 $user_details['name'] = $user_details['name']->value
;
569 $user_details['email'] = $user_details['email']->value
;
570 return $user_details;
576 public function getUniqueIdentifierFromUserObject($user) {
577 return $user->get('mail')->value
;
583 public function getUserIDFromUserObject($user) {
584 return $user->get('uid')->value
;
590 public function synchronizeUsers() {
591 $config = CRM_Core_Config
::singleton();
592 if (PHP_SAPI
!= 'cli') {
597 $users = \Drupal
::entityTypeManager()->getStorage('user')->loadByProperties();
599 $uf = $config->userFramework
;
602 $contactMatching = 0;
603 foreach ($users as $user) {
604 $mail = $user->get('mail')->value
;
608 $uid = $user->get('uid')->value
;
610 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $uid, $mail, $uf, 1, 'Individual', TRUE)) {
619 'contactCount' => $contactCount,
620 'contactMatching' => $contactMatching,
621 'contactCreated' => $contactCreated,
628 public function setMessage($message) {
629 // CiviCRM sometimes includes markup in messages (ex: Event Cart)
630 // it needs to be rendered before being displayed.
631 $message = \Drupal\Core\Render\Markup
::create($message);
632 \Drupal
::messenger()->addMessage($message);
636 * Drupal 8 has a different function to get current path, hence
637 * overriding the postURL function
639 * @param string $action
643 public function postURL($action) {
644 if (!empty($action)) {
647 $current_path = \Drupal
::service('path.current')->getPath();
648 return $this->url($current_path);
652 * Function to return current language of Drupal8
656 public function getCurrentLanguage() {
657 // Drupal might not be bootstrapped if being called by the REST API.
658 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
662 return \Drupal
::languageManager()->getConfigOverrideLanguage()->getId();
666 * Helper function to extract path, query and route name from Civicrm URLs.
668 * For example, 'civicrm/contact/view?reset=1&cid=66' will be returned as:
672 * 'path' => 'civicrm/contact/view',
673 * 'route' => 'civicrm.civicrm_contact_view',
674 * 'query' => array('reset' => '1', 'cid' => '66'),
682 * The parsed url parts, containing 'path', 'route' and 'query'.
684 public function parseUrl($url) {
685 $processed = ['path' => '', 'route_name' => '', 'query' => []];
687 // Remove leading '/' if it exists.
688 $url = ltrim($url, '/');
690 // Separate out the url into its path and query components.
691 $url = parse_url($url);
692 if (empty($url['path'])) {
695 $processed['path'] = $url['path'];
697 // Create a route name by replacing the forward slashes in the path with
698 // underscores, civicrm/contact/search => civicrm.civicrm_contact_search.
699 $processed['route_name'] = 'civicrm.' . implode('_', explode('/', $url['path']));
701 // Turn the query string (if it exists) into an associative array.
702 if (!empty($url['query'])) {
703 parse_str($url['query'], $processed['query']);
710 * Append Drupal8 js to coreResourcesList.
712 * @param \Civi\Core\Event\GenericHookEvent $e
714 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
715 $e->list[] = 'js/crm.drupal8.js';
721 public function getTimeZoneString() {
722 $timezone = date_default_timezone_get();
729 public function setUFLocale($civicrm_language) {
730 $langcode = substr(str_replace('_', '', $civicrm_language), 0, 2);
731 $languageManager = \Drupal
::languageManager();
732 $languages = $languageManager->getLanguages();
734 if (isset($languages[$langcode])) {
735 $languageManager->setConfigOverrideLanguage($languages[$langcode]);
737 // Config must be re-initialized to reset the base URL
738 // otherwise links will have the wrong language prefix/domain.
739 $config = CRM_Core_Config
::singleton();
751 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
756 // Drupal might not be bootstrapped if being called by the REST API.
757 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
761 $language = $this->getCurrentLanguage();
762 if (\Drupal
::service('module_handler')->moduleExists('language')) {
763 $config = \Drupal
::config('language.negotiation')->get('url');
765 //does user configuration allow language
766 //support from the URL (Path prefix or domain)
767 $enabledLanguageMethods = \Drupal
::config('language.types')->get('negotiation.language_interface.enabled') ?
: [];
768 if (array_key_exists(\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::METHOD_ID
, $enabledLanguageMethods)) {
769 $urlType = $config['source'];
772 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_PATH_PREFIX
) {
773 if (!empty($language)) {
774 if ($addLanguagePart && !empty($config['prefixes'][$language])) {
775 $url .= $config['prefixes'][$language] . '/';
777 if ($removeLanguagePart && !empty($config['prefixes'][$language])) {
778 $url = str_replace("/" . $config['prefixes'][$language] . "/", '/', $url);
783 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_DOMAIN
) {
784 if (isset($language->domain
) && $language->domain
) {
785 if ($addLanguagePart) {
786 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $config['domains'][$language] . base_path();
788 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
789 $url = str_replace('\\', '/', $url);
790 $parseUrl = parse_url($url);
792 //kinda hackish but not sure how to do it right
793 //hope http_build_url() will help at some point.
794 if (is_array($parseUrl) && !empty($parseUrl)) {
795 $urlParts = explode('/', $url);
796 $hostKey = array_search($parseUrl['host'], $urlParts);
797 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
798 $urlParts[$hostKey] = $ufUrlParts['host'];
799 $url = implode('/', $urlParts);
815 public function getRoleNames() {
816 return user_role_names();
820 * Determine if the Views module exists.
824 public function viewsExists() {
825 if (\Drupal
::moduleHandler()->moduleExists('views')) {
832 * Return the CMS-specific url for its permissions page
835 public function getCMSPermissionsUrlParams() {
836 return ['ufAccessURL' => \Drupal\Core\Url
::fromRoute('user.admin_permissions')->toString()];
840 * Start a new session.
842 public function sessionStart() {
843 if (\Drupal
::hasContainer()) {
844 $session = \Drupal
::service('session');
845 if (!$session->isStarted()) {
852 * Load the user object.
858 public function getUserObject($userID) {
859 return \Drupal
::entityTypeManager()->getStorage('user')->load($userID);
863 * Helper function to rebuild the Drupal 8 or 9 dynamic routing cache.
864 * We need to do this after enabling extensions that add routes and it's worth doing when we reset Civi paths.
866 public function invalidateRouteCache() {
867 if (class_exists('\Drupal') && \Drupal
::hasContainer()) {
868 \Drupal
::service('router.builder')->rebuild();