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
85 // @Todo: Should we only send off emails if $params['notify'] is set?
87 case $user_register_conf == 'admin_only' ||
$user->isAuthenticated():
88 _user_mail_notify('register_admin_created', $account);
91 case $user_register_conf == 'visitors':
92 _user_mail_notify('register_no_approval_required', $account);
95 case 'visitors_admin_approval':
96 _user_mail_notify('register_pending_approval', $account);
100 // If this is a user creating their own account, login them in!
101 if (!$verify_mail_conf && $account->isActive() && $user->isAnonymous()) {
102 \
user_login_finalize($account);
105 return $account->id();
111 public function updateCMSName($ufID, $email) {
112 $user = \Drupal
::entityTypeManager()->getStorage('user')->load($ufID);
113 if ($user && $user->getEmail() != $email) {
114 $user->setEmail($email);
116 if (!count($user->validate())) {
123 * Check if username and email exists in the drupal db.
125 * @param array $params
126 * Array of name and mail values.
127 * @param array $errors
129 * @param string $emailName
130 * Field label for the 'email'.
132 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
133 // If we are given a name, let's check to see if it already exists.
134 if (!empty($params['name'])) {
135 $name = $params['name'];
137 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
138 $user->setUsername($name);
140 // This checks for both username uniqueness and validity.
141 $violations = iterator_to_array($user->validate());
142 // We only care about violations on the username field; discard the rest.
143 $violations = array_values(array_filter($violations, function ($v) {
144 return $v->getPropertyPath() == 'name';
146 if (count($violations) > 0) {
147 $errors['cms_name'] = (string) $violations[0]->getMessage();
151 // And if we are given an email address, let's check to see if it already exists.
152 if (!empty($params['mail'])) {
153 $mail = $params['mail'];
155 $user = \Drupal
::entityTypeManager()->getStorage('user')->create();
156 $user->setEmail($mail);
158 // This checks for both email uniqueness.
159 $violations = iterator_to_array($user->validate());
160 // We only care about violations on the email field; discard the rest.
161 $violations = array_values(array_filter($violations, function ($v) {
162 return $v->getPropertyPath() == 'mail';
164 if (count($violations) > 0) {
165 $errors[$emailName] = (string) $violations[0]->getMessage();
173 public function getLoginURL($destination = '') {
174 $query = $destination ?
['destination' => $destination] : [];
175 return \Drupal\Core\Url
::fromRoute('user.login', [], ['query' => $query])->toString();
181 public function setTitle($title, $pageTitle = NULL) {
185 \Drupal
::service('civicrm.page_state')->setTitle($pageTitle);
191 public function appendBreadCrumb($breadcrumbs) {
192 $civicrmPageState = \Drupal
::service('civicrm.page_state');
193 foreach ($breadcrumbs as $breadcrumb) {
194 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
201 public function resetBreadCrumb() {
202 \Drupal
::service('civicrm.page_state')->resetBreadcrumbs();
208 public function addHTMLHead($header) {
209 \Drupal
::service('civicrm.page_state')->addHtmlHeader($header);
215 public function addStyleUrl($url, $region) {
216 if ($region != 'html-header') {
223 'rel' => 'stylesheet',
226 \Drupal
::service('civicrm.page_state')->addCSS($css);
233 public function addStyle($code, $region) {
234 if ($region != 'html-header') {
241 \Drupal
::service('civicrm.page_state')->addCSS($css);
246 * Check if a resource url is within the drupal directory and format appropriately.
248 * This seems to be a legacy function. We assume all resources are within the drupal
249 * directory and always return TRUE. As well, we clean up the $url.
251 * FIXME: This is not a legacy function and the above is not a safe assumption.
252 * External urls are allowed by CRM_Core_Resources and this needs to return the correct value.
258 public function formatResourceUrl(&$url) {
259 // Remove leading slash if present.
260 $url = ltrim($url, '/');
262 // Remove query string — presumably added to stop intermediary caching.
263 if (($pos = strpos($url, '?')) !== FALSE) {
264 $url = substr($url, 0, $pos);
266 // FIXME: Should not unconditionally return true
271 * This function does nothing in Drupal 8. Changes to the base_url should be made
272 * in settings.php directly.
274 public function mapConfigToSSL() {
286 $forceBackend = FALSE,
289 $query = html_entity_decode($query);
291 $config = CRM_Core_Config
::singleton();
292 $base = $absolute ?
$config->userFrameworkBaseURL
: 'internal:/';
294 $url = $this->parseURL("{$path}?{$query}");
296 // Not all links that CiviCRM generates are Drupal routes, so we use the weaker ::fromUri method.
298 $url = \Drupal\Core\Url
::fromUri("{$base}{$url['path']}", array(
299 'query' => $url['query'],
300 'fragment' => $fragment,
301 'absolute' => $absolute,
304 catch (Exception
$e) {
305 \Drupal
::logger('civicrm')->error($e->getMessage());
314 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
315 $system = new CRM_Utils_System_Drupal8();
316 $system->loadBootStrap([], FALSE);
318 $uid = \Drupal
::service('user.auth')->authenticate($name, $password);
320 if ($this->loadUser($name)) {
321 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
322 return [$contact_id, $uid, mt_rand()];
332 public function loadUser($username) {
333 $user = user_load_by_name($username);
338 // Set Drupal's current user to the loaded user.
339 \Drupal
::currentUser()->setAccount($user);
342 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
344 // Store the contact id and user id in the session
345 $session = CRM_Core_Session
::singleton();
346 $session->set('ufID', $uid);
347 $session->set('userID', $contact_id);
352 * Determine the native ID of the CMS user.
354 * @param string $username
357 public function getUfId($username) {
358 if ($id = user_load_by_name($username)->id()) {
366 public function permissionDenied() {
367 \Drupal
::service('civicrm.page_state')->setAccessDenied();
371 * In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
372 * to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
374 public function logout() {
379 * Load drupal bootstrap.
381 * @param array $params
382 * Either uid, or name & pass.
383 * @param bool $loadUser
384 * Boolean Require CMS user load.
385 * @param bool $throwError
386 * If true, print error on failure and exit.
387 * @param bool|string $realPath path to script
390 * @Todo Handle setting cleanurls configuration for CiviCRM?
392 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
393 static $run_once = FALSE;
401 if (!($root = $this->cmsRootPath())) {
406 // Create a mock $request object
407 $autoloader = require_once $root . '/autoload.php';
408 if ($autoloader === TRUE) {
409 $autoloader = ComposerAutoloaderInitDrupal8
::getLoader();
411 // @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
412 $request = new \Symfony\Component\HttpFoundation\
Request([], [], [], [], [], $_SERVER);
414 // Create a kernel and boot it.
415 $kernel = \Drupal\Core\DrupalKernel
::createFromRequest($request, $autoloader, 'prod');
417 $kernel->preHandle($request);
418 $container = $kernel->rebuildContainer();
419 // Add our request to the stack and route context.
420 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_OBJECT
, new \Symfony\Component\Routing\
Route('<none>'));
421 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_NAME
, '<none>');
422 $container->get('request_stack')->push($request);
423 $container->get('router.request_context')->fromRequest($request);
425 // Initialize Civicrm
426 \Drupal
::service('civicrm')->initialize();
428 // We need to call the config hook again, since we now know
429 // all the modules that are listening on it (CRM-8655).
430 CRM_Utils_Hook
::config($config);
433 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User
::load($params['uid'])->getAccountName()) {
434 $this->loadUser($username);
436 elseif (!empty($params['name']) && !empty($params['pass']) && \Drupal
::service('user.auth')->authenticate($params['name'], $params['pass'])) {
437 $this->loadUser($params['name']);
444 * Determine the location of the CMS root.
446 * @param string $path
448 * @return NULL|string
450 public function cmsRootPath($path = NULL) {
451 global $civicrm_paths;
452 if (!empty($civicrm_paths['cms.root']['path'])) {
453 return $civicrm_paths['cms.root']['path'];
456 if (defined('DRUPAL_ROOT')) {
460 // It looks like Drupal hasn't been bootstrapped.
461 // We're going to attempt to discover the root Drupal path
462 // by climbing out of the folder hierarchy and looking around to see
463 // if we've found the Drupal root directory.
465 $path = $_SERVER['SCRIPT_FILENAME'];
468 // Normalize and explode path into its component paths.
469 $paths = explode(DIRECTORY_SEPARATOR
, realpath($path));
471 // Remove script filename from array of directories.
474 while (count($paths)) {
475 $candidate = implode('/', $paths);
476 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
487 public function isUserLoggedIn() {
488 return \Drupal
::currentUser()->isAuthenticated();
494 public function isUserRegistrationPermitted() {
495 if (\Drupal
::config('user.settings')->get('register') == 'admin_only') {
504 public function isPasswordUserGenerated() {
505 if (\Drupal
::config('user.settings')->get('verify_mail') == TRUE) {
514 public function updateCategories() {
515 // @todo Is anything necessary?
521 public function getLoggedInUfID() {
522 if ($id = \Drupal
::currentUser()->id()) {
530 public function getDefaultBlockLocation() {
531 return 'sidebar_first';
537 public function flush() {
538 // CiviCRM and Drupal both provide (different versions of) Symfony (and possibly share other classes too).
539 // If we call drupal_flush_all_caches(), Drupal will attempt to rediscover all of its classes, use Civicrm's
540 // alternatives instead and then die. Instead, we only clear cache bins and no more.
541 foreach (Drupal\Core\Cache\Cache
::getBins() as $service_id => $cache_backend) {
542 $cache_backend->deleteAll();
549 public function getModules() {
552 $module_data = \Drupal
::service('extension.list.module')->reset()->getList();
553 foreach ($module_data as $module_name => $extension) {
554 if (!isset($extension->info
['hidden']) && $extension->origin
!= 'core') {
555 $extension->schema_version
= drupal_get_installed_schema_version($module_name);
556 $modules[] = new CRM_Core_Module('drupal.' . $module_name, ($extension->status
== 1));
565 public function getUser($contactID) {
566 $user_details = parent
::getUser($contactID);
567 $user_details['name'] = $user_details['name']->value
;
568 $user_details['email'] = $user_details['email']->value
;
569 return $user_details;
575 public function getUniqueIdentifierFromUserObject($user) {
576 return $user->get('mail')->value
;
582 public function getUserIDFromUserObject($user) {
583 return $user->get('uid')->value
;
589 public function synchronizeUsers() {
590 $config = CRM_Core_Config
::singleton();
591 if (PHP_SAPI
!= 'cli') {
596 $users = \Drupal
::entityTypeManager()->getStorage('user')->loadByProperties();
598 $uf = $config->userFramework
;
601 $contactMatching = 0;
602 foreach ($users as $user) {
603 $mail = $user->get('mail')->value
;
607 $uid = $user->get('uid')->value
;
609 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $uid, $mail, $uf, 1, 'Individual', TRUE)) {
618 'contactCount' => $contactCount,
619 'contactMatching' => $contactMatching,
620 'contactCreated' => $contactCreated,
627 public function setMessage($message) {
628 // CiviCRM sometimes includes markup in messages (ex: Event Cart)
629 // it needs to be rendered before being displayed.
630 $message = \Drupal\Core\Render\Markup
::create($message);
631 \Drupal
::messenger()->addMessage($message);
635 * Drupal 8 has a different function to get current path, hence
636 * overriding the postURL function
638 * @param string $action
642 public function postURL($action) {
643 if (!empty($action)) {
646 $current_path = \Drupal
::service('path.current')->getPath();
647 return $this->url($current_path);
651 * Function to return current language of Drupal8
655 public function getCurrentLanguage() {
656 // Drupal might not be bootstrapped if being called by the REST API.
657 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
661 return \Drupal
::languageManager()->getConfigOverrideLanguage()->getId();
665 * Helper function to extract path, query and route name from Civicrm URLs.
667 * For example, 'civicrm/contact/view?reset=1&cid=66' will be returned as:
671 * 'path' => 'civicrm/contact/view',
672 * 'route' => 'civicrm.civicrm_contact_view',
673 * 'query' => array('reset' => '1', 'cid' => '66'),
681 * The parsed url parts, containing 'path', 'route' and 'query'.
683 public function parseUrl($url) {
684 $processed = ['path' => '', 'route_name' => '', 'query' => []];
686 // Remove leading '/' if it exists.
687 $url = ltrim($url, '/');
689 // Separate out the url into its path and query components.
690 $url = parse_url($url);
691 if (empty($url['path'])) {
694 $processed['path'] = $url['path'];
696 // Create a route name by replacing the forward slashes in the path with
697 // underscores, civicrm/contact/search => civicrm.civicrm_contact_search.
698 $processed['route_name'] = 'civicrm.' . implode('_', explode('/', $url['path']));
700 // Turn the query string (if it exists) into an associative array.
701 if (!empty($url['query'])) {
702 parse_str($url['query'], $processed['query']);
709 * Append Drupal8 js to coreResourcesList.
711 * @param \Civi\Core\Event\GenericHookEvent $e
713 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
714 $e->list[] = 'js/crm.drupal8.js';
720 public function getTimeZoneString() {
721 $timezone = date_default_timezone_get();
728 public function setUFLocale($civicrm_language) {
729 $langcode = substr(str_replace('_', '', $civicrm_language), 0, 2);
730 $languageManager = \Drupal
::languageManager();
731 $languages = $languageManager->getLanguages();
733 if (isset($languages[$langcode])) {
734 $languageManager->setConfigOverrideLanguage($languages[$langcode]);
736 // Config must be re-initialized to reset the base URL
737 // otherwise links will have the wrong language prefix/domain.
738 $config = CRM_Core_Config
::singleton();
750 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
755 // Drupal might not be bootstrapped if being called by the REST API.
756 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
760 $language = $this->getCurrentLanguage();
761 if (\Drupal
::service('module_handler')->moduleExists('language')) {
762 $config = \Drupal
::config('language.negotiation')->get('url');
764 //does user configuration allow language
765 //support from the URL (Path prefix or domain)
766 $enabledLanguageMethods = \Drupal
::config('language.types')->get('negotiation.language_interface.enabled') ?
: [];
767 if (array_key_exists(\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::METHOD_ID
, $enabledLanguageMethods)) {
768 $urlType = $config['source'];
771 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_PATH_PREFIX
) {
772 if (!empty($language)) {
773 if ($addLanguagePart && !empty($config['prefixes'][$language])) {
774 $url .= $config['prefixes'][$language] . '/';
776 if ($removeLanguagePart && !empty($config['prefixes'][$language])) {
777 $url = str_replace("/" . $config['prefixes'][$language] . "/", '/', $url);
782 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_DOMAIN
) {
783 if (isset($language->domain
) && $language->domain
) {
784 if ($addLanguagePart) {
785 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $config['domains'][$language] . base_path();
787 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
788 $url = str_replace('\\', '/', $url);
789 $parseUrl = parse_url($url);
791 //kinda hackish but not sure how to do it right
792 //hope http_build_url() will help at some point.
793 if (is_array($parseUrl) && !empty($parseUrl)) {
794 $urlParts = explode('/', $url);
795 $hostKey = array_search($parseUrl['host'], $urlParts);
796 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
797 $urlParts[$hostKey] = $ufUrlParts['host'];
798 $url = implode('/', $urlParts);
814 public function getRoleNames() {
815 return user_role_names();
819 * Determine if the Views module exists.
823 public function viewsExists() {
824 if (\Drupal
::moduleHandler()->moduleExists('views')) {
831 * Return the CMS-specific url for its permissions page
834 public function getCMSPermissionsUrlParams() {
835 return ['ufAccessURL' => \Drupal\Core\Url
::fromRoute('user.admin_permissions')->toString()];
839 * Start a new session.
841 public function sessionStart() {
842 if (\Drupal
::hasContainer()) {
843 $session = \Drupal
::service('session');
844 if (!$session->isStarted()) {
851 * Load the user object.
857 public function getUserObject($userID) {
858 return \Drupal
::entityTypeManager()->getStorage('user')->load($userID);
862 * Helper function to rebuild the Drupal 8 or 9 dynamic routing cache.
863 * We need to do this after enabling extensions that add routes and it's worth doing when we reset Civi paths.
865 public function invalidateRouteCache() {
866 if (class_exists('\Drupal') && \Drupal
::hasContainer()) {
867 \Drupal
::service('router.builder')->rebuild();