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 = entity_create('user');
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')) {
52 elseif (!$verify_mail_conf) {
56 // Validate the user object
57 $violations = $account->validate();
58 if (count($violations)) {
62 // Let the Drupal module know we're already in CiviCRM.
63 $config = CRM_Core_Config
::singleton();
64 $config->inCiviCRM
= TRUE;
68 $config->inCiviCRM
= FALSE;
70 catch (\Drupal\Core\Entity\EntityStorageException
$e) {
71 $config->inCiviCRM
= FALSE;
75 // Send off any emails as required.
76 // Possible values for $op:
77 // - 'register_admin_created': Welcome message for user created by the admin.
78 // - 'register_no_approval_required': Welcome message when user
80 // - 'register_pending_approval': Welcome message, user pending admin
82 // @Todo: Should we only send off emails if $params['notify'] is set?
84 case $user_register_conf == 'admin_only' ||
$user->isAuthenticated():
85 _user_mail_notify('register_admin_created', $account);
88 case $user_register_conf == 'visitors':
89 _user_mail_notify('register_no_approval_required', $account);
92 case 'visitors_admin_approval':
93 _user_mail_notify('register_pending_approval', $account);
97 // If this is a user creating their own account, login them in!
98 if ($account->isActive() && $user->isAnonymous()) {
99 \
user_login_finalize($account);
102 return $account->id();
108 public function updateCMSName($ufID, $email) {
109 $user = entity_load('user', $ufID);
110 if ($user && $user->getEmail() != $email) {
111 $user->setEmail($email);
113 if (!count($user->validate())) {
120 * Check if username and email exists in the drupal db.
122 * @param array $params
123 * Array of name and mail values.
124 * @param array $errors
126 * @param string $emailName
127 * Field label for the 'email'.
129 public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
130 // If we are given a name, let's check to see if it already exists.
131 if (!empty($params['name'])) {
132 $name = $params['name'];
134 $user = entity_create('user');
135 $user->setUsername($name);
137 // This checks for both username uniqueness and validity.
138 $violations = iterator_to_array($user->validate());
139 // We only care about violations on the username field; discard the rest.
140 $violations = array_values(array_filter($violations, function ($v) {
141 return $v->getPropertyPath() == 'name';
143 if (count($violations) > 0) {
144 $errors['cms_name'] = (string) $violations[0]->getMessage();
148 // And if we are given an email address, let's check to see if it already exists.
149 if (!empty($params['mail'])) {
150 $mail = $params['mail'];
152 $user = entity_create('user');
153 $user->setEmail($mail);
155 // This checks for both email uniqueness.
156 $violations = iterator_to_array($user->validate());
157 // We only care about violations on the email field; discard the rest.
158 $violations = array_values(array_filter($violations, function ($v) {
159 return $v->getPropertyPath() == 'mail';
161 if (count($violations) > 0) {
162 $errors[$emailName] = (string) $violations[0]->getMessage();
170 public function getLoginURL($destination = '') {
171 $query = $destination ?
['destination' => $destination] : [];
172 return \Drupal
::url('user.login', [], ['query' => $query]);
178 public function setTitle($title, $pageTitle = NULL) {
182 \Drupal
::service('civicrm.page_state')->setTitle($pageTitle);
188 public function appendBreadCrumb($breadcrumbs) {
189 $civicrmPageState = \Drupal
::service('civicrm.page_state');
190 foreach ($breadcrumbs as $breadcrumb) {
191 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
198 public function resetBreadCrumb() {
199 \Drupal
::service('civicrm.page_state')->resetBreadcrumbs();
205 public function addHTMLHead($header) {
206 \Drupal
::service('civicrm.page_state')->addHtmlHeader($header);
212 public function addStyleUrl($url, $region) {
213 if ($region != 'html-header') {
220 'rel' => 'stylesheet',
223 \Drupal
::service('civicrm.page_state')->addCSS($css);
230 public function addStyle($code, $region) {
231 if ($region != 'html-header') {
238 \Drupal
::service('civicrm.page_state')->addCSS($css);
243 * Check if a resource url is within the drupal directory and format appropriately.
245 * This seems to be a legacy function. We assume all resources are within the drupal
246 * directory and always return TRUE. As well, we clean up the $url.
248 * FIXME: This is not a legacy function and the above is not a safe assumption.
249 * External urls are allowed by CRM_Core_Resources and this needs to return the correct value.
255 public function formatResourceUrl(&$url) {
256 // Remove leading slash if present.
257 $url = ltrim($url, '/');
259 // Remove query string — presumably added to stop intermediary caching.
260 if (($pos = strpos($url, '?')) !== FALSE) {
261 $url = substr($url, 0, $pos);
263 // FIXME: Should not unconditionally return true
268 * This function does nothing in Drupal 8. Changes to the base_url should be made
269 * in settings.php directly.
271 public function mapConfigToSSL() {
283 $forceBackend = FALSE,
286 $query = html_entity_decode($query);
288 $config = CRM_Core_Config
::singleton();
289 $base = $absolute ?
$config->userFrameworkBaseURL
: 'internal:/';
291 $url = $this->parseURL("{$path}?{$query}");
293 // Not all links that CiviCRM generates are Drupal routes, so we use the weaker ::fromUri method.
295 $url = \Drupal\Core\Url
::fromUri("{$base}{$url['path']}", array(
296 'query' => $url['query'],
297 'fragment' => $fragment,
298 'absolute' => $absolute,
301 catch (Exception
$e) {
302 \Drupal
::logger('civicrm')->error($e->getMessage());
311 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
312 $system = new CRM_Utils_System_Drupal8();
313 $system->loadBootStrap([], FALSE);
315 $uid = \Drupal
::service('user.auth')->authenticate($name, $password);
317 if ($this->loadUser($name)) {
318 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
319 return [$contact_id, $uid, mt_rand()];
329 public function loadUser($username) {
330 $user = user_load_by_name($username);
335 // Set Drupal's current user to the loaded user.
336 \Drupal
::currentUser()->setAccount($user);
339 $contact_id = CRM_Core_BAO_UFMatch
::getContactId($uid);
341 // Store the contact id and user id in the session
342 $session = CRM_Core_Session
::singleton();
343 $session->set('ufID', $uid);
344 $session->set('userID', $contact_id);
349 * Determine the native ID of the CMS user.
351 * @param string $username
354 public function getUfId($username) {
355 if ($id = user_load_by_name($username)->id()) {
363 public function permissionDenied() {
364 \Drupal
::service('civicrm.page_state')->setAccessDenied();
368 * In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
369 * to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
371 public function logout() {
376 * Load drupal bootstrap.
378 * @param array $params
379 * Either uid, or name & pass.
380 * @param bool $loadUser
381 * Boolean Require CMS user load.
382 * @param bool $throwError
383 * If true, print error on failure and exit.
384 * @param bool|string $realPath path to script
387 * @Todo Handle setting cleanurls configuration for CiviCRM?
389 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
390 static $run_once = FALSE;
398 if (!($root = $this->cmsRootPath())) {
403 // Create a mock $request object
404 $autoloader = require_once $root . '/autoload.php';
405 if ($autoloader === TRUE) {
406 $autoloader = ComposerAutoloaderInitDrupal8
::getLoader();
408 // @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
409 $request = new \Symfony\Component\HttpFoundation\
Request([], [], [], [], [], $_SERVER);
411 // Create a kernel and boot it.
412 $kernel = \Drupal\Core\DrupalKernel
::createFromRequest($request, $autoloader, 'prod');
414 $kernel->preHandle($request);
415 $container = $kernel->rebuildContainer();
416 // Add our request to the stack and route context.
417 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_OBJECT
, new \Symfony\Component\Routing\
Route('<none>'));
418 $request->attributes
->set(\Symfony\Cmf\Component\Routing\RouteObjectInterface
::ROUTE_NAME
, '<none>');
419 $container->get('request_stack')->push($request);
420 $container->get('router.request_context')->fromRequest($request);
422 // Initialize Civicrm
423 \Drupal
::service('civicrm')->initialize();
425 // We need to call the config hook again, since we now know
426 // all the modules that are listening on it (CRM-8655).
427 CRM_Utils_Hook
::config($config);
430 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User
::load($params['uid'])->getUsername()) {
431 $this->loadUser($username);
433 elseif (!empty($params['name']) && !empty($params['pass']) && \Drupal
::service('user.auth')->authenticate($params['name'], $params['pass'])) {
434 $this->loadUser($params['name']);
441 * Determine the location of the CMS root.
443 * @param string $path
445 * @return NULL|string
447 public function cmsRootPath($path = NULL) {
448 global $civicrm_paths;
449 if (!empty($civicrm_paths['cms.root']['path'])) {
450 return $civicrm_paths['cms.root']['path'];
453 if (defined('DRUPAL_ROOT')) {
457 // It looks like Drupal hasn't been bootstrapped.
458 // We're going to attempt to discover the root Drupal path
459 // by climbing out of the folder hierarchy and looking around to see
460 // if we've found the Drupal root directory.
462 $path = $_SERVER['SCRIPT_FILENAME'];
465 // Normalize and explode path into its component paths.
466 $paths = explode(DIRECTORY_SEPARATOR
, realpath($path));
468 // Remove script filename from array of directories.
471 while (count($paths)) {
472 $candidate = implode('/', $paths);
473 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
484 public function isUserLoggedIn() {
485 return \Drupal
::currentUser()->isAuthenticated();
491 public function isUserRegistrationPermitted() {
492 if (\Drupal
::config('user.settings')->get('register') == 'admin_only') {
501 public function isPasswordUserGenerated() {
502 if (\Drupal
::config('user.settings')->get('verify_mail') == TRUE) {
511 public function updateCategories() {
512 // @todo Is anything necessary?
518 public function getLoggedInUfID() {
519 if ($id = \Drupal
::currentUser()->id()) {
527 public function getDefaultBlockLocation() {
528 return 'sidebar_first';
534 public function flush() {
535 // CiviCRM and Drupal both provide (different versions of) Symfony (and possibly share other classes too).
536 // If we call drupal_flush_all_caches(), Drupal will attempt to rediscover all of its classes, use Civicrm's
537 // alternatives instead and then die. Instead, we only clear cache bins and no more.
538 foreach (Drupal\Core\Cache\Cache
::getBins() as $service_id => $cache_backend) {
539 $cache_backend->deleteAll();
546 public function getModules() {
549 $module_data = \Drupal
::service('extension.list.module')->reset()->getList();
550 foreach ($module_data as $module_name => $extension) {
551 if (!isset($extension->info
['hidden']) && $extension->origin
!= 'core') {
552 $extension->schema_version
= drupal_get_installed_schema_version($module_name);
553 $modules[] = new CRM_Core_Module('drupal.' . $module_name, ($extension->status
== 1));
562 public function getUser($contactID) {
563 $user_details = parent
::getUser($contactID);
564 $user_details['name'] = $user_details['name']->value
;
565 $user_details['email'] = $user_details['email']->value
;
566 return $user_details;
572 public function getUniqueIdentifierFromUserObject($user) {
573 return $user->get('mail')->value
;
579 public function getUserIDFromUserObject($user) {
580 return $user->get('uid')->value
;
586 public function synchronizeUsers() {
587 $config = CRM_Core_Config
::singleton();
588 if (PHP_SAPI
!= 'cli') {
593 $users = \Drupal
::entityTypeManager()->getStorage('user')->loadByProperties();
595 $uf = $config->userFramework
;
598 $contactMatching = 0;
599 foreach ($users as $user) {
600 $mail = $user->get('mail')->value
;
604 $uid = $user->get('uid')->value
;
606 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user, $uid, $mail, $uf, 1, 'Individual', TRUE)) {
615 'contactCount' => $contactCount,
616 'contactMatching' => $contactMatching,
617 'contactCreated' => $contactCreated,
624 public function setMessage($message) {
625 // CiviCRM sometimes includes markup in messages (ex: Event Cart)
626 // it needs to be rendered before being displayed.
627 $message = \Drupal\Core\Render\Markup
::create($message);
628 \Drupal
::messenger()->addMessage($message);
632 * Drupal 8 has a different function to get current path, hence
633 * overriding the postURL function
635 * @param string $action
639 public function postURL($action) {
640 if (!empty($action)) {
643 $current_path = \Drupal
::service('path.current')->getPath();
644 return $this->url($current_path);
648 * Function to return current language of Drupal8
652 public function getCurrentLanguage() {
653 // Drupal might not be bootstrapped if being called by the REST API.
654 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
658 return \Drupal
::languageManager()->getCurrentLanguage()->getId();
662 * Helper function to extract path, query and route name from Civicrm URLs.
664 * For example, 'civicrm/contact/view?reset=1&cid=66' will be returned as:
668 * 'path' => 'civicrm/contact/view',
669 * 'route' => 'civicrm.civicrm_contact_view',
670 * 'query' => array('reset' => '1', 'cid' => '66'),
678 * The parsed url parts, containing 'path', 'route' and 'query'.
680 public function parseUrl($url) {
681 $processed = ['path' => '', 'route_name' => '', 'query' => []];
683 // Remove leading '/' if it exists.
684 $url = ltrim($url, '/');
686 // Separate out the url into its path and query components.
687 $url = parse_url($url);
688 if (empty($url['path'])) {
691 $processed['path'] = $url['path'];
693 // Create a route name by replacing the forward slashes in the path with
694 // underscores, civicrm/contact/search => civicrm.civicrm_contact_search.
695 $processed['route_name'] = 'civicrm.' . implode('_', explode('/', $url['path']));
697 // Turn the query string (if it exists) into an associative array.
698 if (!empty($url['query'])) {
699 parse_str($url['query'], $processed['query']);
706 * Append Drupal8 js to coreResourcesList.
708 * @param \Civi\Core\Event\GenericHookEvent $e
710 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
711 $e->list[] = 'js/crm.drupal8.js';
717 public function getTimeZoneString() {
718 $timezone = date_default_timezone_get();
725 public function setUFLocale($civicrm_language) {
726 $langcode = substr(str_replace('_', '', $civicrm_language), 0, 2);
727 $languageManager = \Drupal
::languageManager();
728 $languages = $languageManager->getLanguages();
730 if (isset($languages[$langcode])) {
731 $languageManager->setConfigOverrideLanguage($languages[$langcode]);
733 // Config must be re-initialized to reset the base URL
734 // otherwise links will have the wrong language prefix/domain.
735 $config = CRM_Core_Config
::singleton();
747 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
752 // Drupal might not be bootstrapped if being called by the REST API.
753 if (!class_exists('Drupal') ||
!\Drupal
::hasContainer()) {
757 $language = $this->getCurrentLanguage();
758 if (\Drupal
::service('module_handler')->moduleExists('language')) {
759 $config = \Drupal
::config('language.negotiation')->get('url');
761 //does user configuration allow language
762 //support from the URL (Path prefix or domain)
763 $enabledLanguageMethods = \Drupal
::config('language.types')->get('negotiation.language_interface.enabled') ?
: [];
764 if (array_key_exists(\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::METHOD_ID
, $enabledLanguageMethods)) {
765 $urlType = $config['source'];
768 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_PATH_PREFIX
) {
769 if (!empty($language)) {
770 if ($addLanguagePart && !empty($config['prefixes'][$language])) {
771 $url .= $config['prefixes'][$language] . '/';
773 if ($removeLanguagePart && !empty($config['prefixes'][$language])) {
774 $url = str_replace("/" . $config['prefixes'][$language] . "/", '/', $url);
779 if ($urlType == \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
::CONFIG_DOMAIN
) {
780 if (isset($language->domain
) && $language->domain
) {
781 if ($addLanguagePart) {
782 $url = (CRM_Utils_System
::isSSL() ?
'https' : 'http') . '://' . $config['domains'][$language] . base_path();
784 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
785 $url = str_replace('\\', '/', $url);
786 $parseUrl = parse_url($url);
788 //kinda hackish but not sure how to do it right
789 //hope http_build_url() will help at some point.
790 if (is_array($parseUrl) && !empty($parseUrl)) {
791 $urlParts = explode('/', $url);
792 $hostKey = array_search($parseUrl['host'], $urlParts);
793 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL
);
794 $urlParts[$hostKey] = $ufUrlParts['host'];
795 $url = implode('/', $urlParts);
811 public function getRoleNames() {
812 return user_role_names();
816 * Determine if the Views module exists.
820 public function viewsExists() {
821 if (\Drupal
::moduleHandler()->moduleExists('views')) {