Merge pull request #5038 from civicrm/CRM-15877
[civicrm-core.git] / CRM / Utils / System / Drupal8.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
39 class CRM_Utils_System_Drupal8 extends CRM_Utils_System_DrupalBase {
40
41 /**
42 * Create a user in Drupal.
43 *
44 * @param array $params
45 * @param string $mail
46 * Email id for cms user.
47 *
48 * @return int|bool
49 * uid if user exists, false otherwise
50 */
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');
55
56 // Don't create user if we don't have permission to.
57 if (!$user->hasPermission('administer users') && $user_register_conf == 'admin_only') {
58 return FALSE;
59 }
60
61 $account = entity_create('user');
62 $account->setUsername($params['cms_name'])->setEmail($params[$mail]);
63
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']);
69 }
70
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')) {
74 $account->block();
75 }
76
77 // Validate the user object
78 $violations = $account->validate();
79 if (count($violations)) {
80 return FALSE;
81 }
82
83 try {
84 $account->save();
85 }
86 catch (\Drupal\Core\Entity\EntityStorageException $e) {
87 return FALSE;
88 }
89
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
94 // self-registers.
95 // - 'register_pending_approval': Welcome message, user pending admin
96 // approval.
97 // @Todo: Should we only send off emails if $params['notify'] is set?
98 switch (TRUE) {
99 case $user_register_conf == 'admin_only' || $user->isAuthenticated():
100 _user_mail_notify('register_admin_created', $account);
101 break;
102
103 case $user_register_conf == 'visitors':
104 _user_mail_notify('register_no_approval_required', $account);
105 break;
106
107 case 'visitors_admin_approval':
108 _user_mail_notify('register_pending_approval', $account);
109 break;
110 }
111
112 return $account->id();
113 }
114
115 /**
116 * Update the Drupal user's email address.
117 *
118 * @param int $ufID
119 * User ID in CMS.
120 * @param string $email
121 * Primary contact email address.
122 */
123 public function updateCMSName($ufID, $email) {
124 $user = user_load($ufID);
125 if ($user && $user->getEmail() != $email) {
126 $user->setEmail($email);
127
128 if (!count($user->validate())) {
129 $user->save();
130 }
131 }
132 }
133
134 /**
135 * Check if username and email exists in the drupal db
136 *
137 * @param array $params
138 * Array of name and mail values.
139 * @param array $errors
140 * Errors.
141 * @param string $emailName
142 * Field label for the 'email'.
143 *
144 *
145 * @return void
146 */
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'];
151
152 $user = entity_create('user');
153 $user->setUsername($name);
154
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';
160 });
161 if (count($violations) > 0) {
162 $errors['cms_name'] = $violations[0]->getMessage();
163 }
164 }
165
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];
169
170 $user = entity_create('user');
171 $user->setEmail($mail);
172
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';
178 });
179 if (count($violations) > 0) {
180 $errors[$emailName] = $violations[0]->getMessage();
181 }
182 }
183 }
184
185 /**
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
188 *
189 * @param CRM_Core_Form $form
190 * Form object representing the 'current' form - to which the user will be returned.
191 * @return string
192 * destination value for URL
193 */
194 public function getLoginDestination(&$form) {
195 $args = NULL;
196
197 $id = $form->get('id');
198 if ($id) {
199 $args .= "&id=$id";
200 }
201 else {
202 $gid = $form->get('gid');
203 if ($gid) {
204 $args .= "&gid=$gid";
205 }
206 else {
207 // Setup Personal Campaign Page link uses pageId
208 $pageId = $form->get('pageId');
209 if ($pageId) {
210 $component = $form->get('component');
211 $args .= "&pageId=$pageId&component=$component&action=add";
212 }
213 }
214 }
215
216 $destination = NULL;
217 if ($args) {
218 // append destination so user is returned to form they came from after login
219 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
220 }
221 return $destination;
222 }
223
224 /**
225 * Get user login URL for hosting CMS (method declared in each CMS system class)
226 *
227 * @param string $destination
228 * If present, add destination to querystring (works for Drupal only).
229 *
230 * @return string
231 * loginURL for the current CMS
232 */
233 public function getLoginURL($destination = '') {
234 $query = $destination ? array('destination' => $destination) : array();
235 return \Drupal::url('user.page', array(), array('query' => $query));
236 }
237
238
239 /**
240 * Sets the title of the page
241 *
242 * @param string $title
243 * @param string $pageTitle
244 *
245 * @return void
246 */
247 public function setTitle($title, $pageTitle = NULL) {
248 if (!$pageTitle) {
249 $pageTitle = $title;
250 }
251
252 \Drupal::service('civicrm.page_state')->setTitle($pageTitle);
253 }
254
255 /**
256 * Append an additional breadcrumb tag to the existing breadcrumb
257 *
258 * @param $breadcrumbs
259 *
260 * @internal param string $title
261 * @internal param string $url
262 *
263 * @return void
264 */
265 public function appendBreadCrumb($breadcrumbs) {
266 $civicrmPageState = \Drupal::service('civicrm.page_state');
267 foreach ($breadcrumbs as $breadcrumb) {
268 $civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
269 }
270 }
271
272 /**
273 * Reset an additional breadcrumb tag to the existing breadcrumb
274 *
275 * @return void
276 */
277 public function resetBreadCrumb() {
278 \Drupal::service('civicrm.page_state')->resetBreadcrumbs();
279 }
280
281 /**
282 * Append a string to the head of the html file
283 *
284 * @param string $header
285 * The new string to be appended.
286 *
287 * @return void
288 */
289 public function addHTMLHead($header) {
290 \Drupal::service('civicrm.page_state')->addHtmlHeader($header);
291 }
292
293 /**
294 * Add a script file
295 *
296 * @param $url : string, absolute path to file
297 * @param string $region
298 * location within the document: 'html-header', 'page-header', 'page-footer'.
299 *
300 * Note: This function is not to be called directly
301 * @see CRM_Core_Region::render()
302 *
303 * @return bool
304 * TRUE if we support this operation in this CMS, FALSE otherwise
305 */
306 public function addScriptUrl($url, $region) {
307 $options = array('group' => JS_LIBRARY, 'weight' => 10);
308 switch ($region) {
309 case 'html-header':
310 case 'page-footer':
311 $options['scope'] = substr($region, 5);
312 break;
313
314 default:
315 return FALSE;
316 }
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);
320 return TRUE;
321 }
322
323 /**
324 * Add an inline script
325 *
326 * @param $code : string, javascript code
327 * @param string $region
328 * location within the document: 'html-header', 'page-header', 'page-footer'.
329 *
330 * Note: This function is not to be called directly
331 * @see CRM_Core_Region::render()
332 *
333 * @return bool
334 * TRUE if we support this operation in this CMS, FALSE otherwise
335 */
336 public function addScript($code, $region) {
337 $options = array('type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10);
338 switch ($region) {
339 case 'html-header':
340 case 'page-footer':
341 $options['scope'] = substr($region, 5);
342 break;
343
344 default:
345 return FALSE;
346 }
347 \Drupal::service('civicrm.page_state')->addJS($code, $options);
348 return TRUE;
349 }
350
351 /**
352 * Add a css file
353 *
354 * @param $url : string, absolute path to file
355 * @param string $region
356 * location within the document: 'html-header', 'page-header', 'page-footer'.
357 *
358 * Note: This function is not to be called directly
359 * @see CRM_Core_Region::render()
360 *
361 * @return bool
362 * TRUE if we support this operation in this CMS, FALSE otherwise
363 */
364 public function addStyleUrl($url, $region) {
365 if ($region != 'html-header') {
366 return FALSE;
367 }
368 $options = array();
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);
372 return TRUE;
373 }
374
375 /**
376 * Add an inline style
377 *
378 * @param $code : string, css code
379 * @param string $region
380 * location within the document: 'html-header', 'page-header', 'page-footer'.
381 *
382 * Note: This function is not to be called directly
383 * @see CRM_Core_Region::render()
384 *
385 * @return bool
386 * TRUE if we support this operation in this CMS, FALSE otherwise
387 */
388 public function addStyle($code, $region) {
389 if ($region != 'html-header') {
390 return FALSE;
391 }
392 $options = array('type' => 'inline');
393 \Drupal::service('civicrm.page_state')->addCSS($code, $options);
394 return TRUE;
395 }
396
397 /**
398 * Check if a resource url is within the drupal directory and format appropriately
399 *
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.
402 *
403 * @param $url
404 *
405 * @return bool
406 */
407 public function formatResourceUrl(&$url) {
408 // Remove leading slash if present.
409 $url = ltrim($url, '/');
410
411 // Remove query string — presumably added to stop intermediary caching.
412 if (($pos = strpos($url, '?')) !== FALSE) {
413 $url = substr($url, 0, $pos);
414 }
415
416 return TRUE;
417 }
418
419 /**
420 * Rewrite various system urls to https
421 *
422 * This function does nothing in Drupal 8. Changes to the base_url should be made
423 * in settings.php directly.
424 *
425 * @return void
426 */
427 public function mapConfigToSSL() {
428 }
429
430 /**
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).
445 * @return string
446 */
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}");
450
451 try {
452 $url = \Drupal::url($url['route_name'], array(), array(
453 'query' => $url['query'],
454 'absolute' => $absolute,
455 'fragment' => $fragment,
456 ));
457 }
458 catch (Exception $e) {
459 $url = '';
460 }
461
462 if ($htmlize) {
463 $url = htmlentities($url);
464 }
465 return $url;
466 }
467
468
469 /**
470 * Authenticate the user against the drupal db
471 *
472 * @param string $name
473 * The user 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
479 *
480 * @return array|bool
481 * [contactID, ufID, uniqueString] if success else false if no auth
482 *
483 * This always bootstraps Drupal
484 */
485 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
486 (new CRM_Utils_System_Drupal8())->loadBootStrap(array(), FALSE);
487
488 $uid = \Drupal::service('user.auth')->authenticate($name, $password);
489 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
490
491 return array($contact_id, $uid, mt_rand());
492 }
493
494 /**
495 * Load user into session
496 */
497 public function loadUser($username) {
498 $user = user_load_by_name($username);
499 if (!$user) {
500 return FALSE;
501 }
502
503 // Set Drupal's current user to the loaded user.
504 \Drupal::currentUser()->setAccount($user);
505
506 $uid = $user->id();
507 $contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
508
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);
513 return TRUE;
514 }
515
516 /**
517 * Determine the native ID of the CMS user
518 *
519 * @param string $username
520 * @return int|NULL
521 */
522 public function getUfId($username) {
523 if ($id = user_load_by_name($username)->id()) {
524 return $id;
525 }
526 }
527
528 /**
529 * Set a message in the UF to display to a user
530 *
531 * @param string $message
532 * The message to set.
533 */
534 public function setMessage($message) {
535 drupal_set_message($message);
536 }
537
538 public function permissionDenied() {
539 \Drupal::service('civicrm.page_state')->setAccessDenied();
540 }
541
542 /**
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.
545 */
546 public function logout() {
547 // Pass
548 }
549
550 /**
551 * Load drupal bootstrap
552 *
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
560 *
561 * @return bool
562 * @Todo Handle setting cleanurls configuration for CiviCRM?
563 */
564 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
565 static $run_once = FALSE;
566 if ($run_once) {
567 return TRUE;
568 }
569 else {
570 $run_once = TRUE;
571 }
572
573 if (!($root = $this->cmsRootPath())) {
574 return FALSE;
575 }
576 chdir($root);
577
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);
582
583 // Create a kernel and boot it.
584 \Drupal\Core\DrupalKernel::createFromRequest($request, $autoloader, 'prod')->prepareLegacyRequest($request);
585
586 // Initialize Civicrm
587 \Drupal::service('civicrm');
588
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);
592
593 if ($loadUser) {
594 if (!empty($params['uid']) && $username = \Drupal\user\Entity\User::load($uid)->getUsername()) {
595 $this->loadUser($username);
596 }
597 elseif (!empty($params['name']) && !empty($params['pass']) && $this->authenticate($params['name'], $params['pass'])) {
598 $this->loadUser($params['name']);
599 }
600 }
601 return TRUE;
602 }
603
604 /**
605 * Determine the location of the CMS root.
606 * @param null $path
607 *
608 * @return NULL|string
609 */
610 public function cmsRootPath($path = NULL) {
611 if (defined('DRUPAL_ROOT')) {
612 return DRUPAL_ROOT;
613 }
614
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.
619 if (!$path) {
620 $path = $_SERVER['SCRIPT_FILENAME'];
621 }
622
623 // Normalize and explode path into its component paths.
624 $paths = explode(DIRECTORY_SEPARATOR, realpath($path));
625
626 // Remove script filename from array of directories.
627 array_pop($paths);
628
629 while (count($paths)) {
630 $candidate = implode('/', $paths);
631 if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
632 return $candidate;
633 }
634
635 array_pop($paths);
636 }
637 }
638
639 /**
640 * Check if user is logged in.
641 *
642 * @return bool
643 */
644 public function isUserLoggedIn() {
645 return \Drupal::currentUser()->isAuthenticated();
646 }
647
648 /**
649 * Get currently logged in user uf id.
650 *
651 * @return int
652 * $userID logged in user uf id.
653 */
654 public function getLoggedInUfID() {
655 if ($id = \Drupal::currentUser()->id()) {
656 return $id;
657 }
658 }
659
660 /**
661 * Get the default location for CiviCRM blocks
662 *
663 * @return string
664 */
665 public function getDefaultBlockLocation() {
666 return 'sidebar_first';
667 }
668
669 }