4 * Base class for UF system integrations
6 abstract class CRM_Utils_System_Base
{
9 * Deprecated property to check if this is a drupal install.
11 * The correct method is to have functions on the UF classes for all UF specific
12 * functions and leave the codebase oblivious to the type of CMS
16 * TRUE, if the CMS is Drupal.
18 public $is_drupal = FALSE;
21 * Deprecated property to check if this is a joomla install. The correct method is to have functions on the UF classes for all UF specific
22 * functions and leave the codebase oblivious to the type of CMS
26 * TRUE, if the CMS is Joomla!.
28 public $is_joomla = FALSE;
31 * deprecated property to check if this is a wordpress install. The correct method is to have functions on the UF classes for all UF specific
32 * functions and leave the codebase oblivious to the type of CMS
36 * TRUE, if the CMS is WordPress.
38 public $is_wordpress = FALSE;
41 * Does this CMS / UF support a CMS specific logging mechanism?
43 * @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
45 public $supports_UF_Logging = FALSE;
49 * TRUE, if the CMS allows CMS forms to be extended by hooks.
51 public $supports_form_extensions = FALSE;
53 public function initialize() {
54 if (\CRM_Utils_System
::isSSL()) {
55 $this->mapConfigToSSL();
59 abstract public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL);
62 * Append an additional breadcrumb tag to the existing breadcrumb.
64 * @param array $breadCrumbs
66 public function appendBreadCrumb($breadCrumbs) {
70 * Reset an additional breadcrumb tag to the existing breadcrumb.
72 public function resetBreadCrumb() {
76 * Append a string to the head of the html file.
79 * The new string to be appended.
81 public function addHTMLHead($head) {
85 * Rewrite various system urls to https.
87 public function mapConfigToSSL() {
88 // dont need to do anything, let CMS handle their own switch to SSL
92 * Figure out the post url for QuickForm.
94 * @param string $action
95 * The default url if one is pre-specified.
98 * The url to post the form.
100 public function postURL($action) {
101 $config = CRM_Core_Config
::singleton();
102 if (!empty($action)) {
106 return $this->url(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET),
107 NULL, TRUE, NULL, FALSE
112 * Generate the url string to a CiviCRM path.
114 * @param string $path
115 * The path being linked to, such as "civicrm/add".
116 * @param string $query
117 * A query string to append to the link.
118 * @param bool $absolute
119 * Whether to force the output to be an absolute link (beginning with http).
120 * Useful for links that will be displayed outside the site, such as in an RSS feed.
121 * @param string $fragment
122 * A fragment identifier (named anchor) to append to the link.
123 * @param bool $frontend
124 * This link should be to the CMS front end (applies to WP & Joomla).
125 * @param bool $forceBackend
126 * This link should be to the CMS back end (applies to WP & Joomla).
136 $forceBackend = FALSE
142 * Authenticate the user against the CMS db.
144 * @param string $name
146 * @param string $password
147 * The password for the above user.
148 * @param bool $loadCMSBootstrap
149 * Load cms bootstrap?.
150 * @param string $realPath
154 * [contactID, ufID, unique string] else false if no auth
155 * @throws \CRM_Core_Exception.
157 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
162 * Set a message in the CMS to display to a user.
164 * @param string $message
165 * The message to set.
167 public function setMessage($message) {
171 * Load user into session.
177 public function loadUser($user) {
182 * Immediately stop script execution and display a 401 "Access Denied" page.
183 * @throws \CRM_Core_Exception
185 public function permissionDenied() {
186 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
190 * Immediately stop script execution, log out the user and redirect to the home page.
193 * This function should be removed in favor of linking to the CMS's logout page
195 public function logout() {
199 * Clear CMS caches related to the user registration/profile forms.
200 * Used when updating/embedding profiles on CMS user forms.
203 public function updateCategories() {
207 * Get the locale set in the CMS.
209 * @return string|null
210 * Locale or null for none
212 public function getUFLocale() {
217 * If we are using a theming system, invoke theme, else just print the content.
219 * @param string $content
220 * The content that will be themed.
222 * Are we displaying to the screen or bypassing theming?.
223 * @param bool $maintenance
224 * For maintenance mode.
227 * @return string|null
228 * NULL, If $print is FALSE, and some other criteria match up.
229 * The themed string, otherwise.
231 * @todo The return value is inconsistent.
232 * @todo Better to always return, and never print.
234 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
237 // TODO: Split up; this was copied verbatim from CiviCRM 4.0's multi-UF theming function
238 // but the parts should be copied into cleaner subclass implementations
239 $config = CRM_Core_Config
::singleton();
241 $config->userSystem
->is_drupal
&&
242 function_exists('theme') &&
246 drupal_set_breadcrumb('');
247 drupal_maintenance_theme();
248 if ($region = CRM_Core_Region
::instance('html-header', FALSE)) {
249 CRM_Utils_System
::addHTMLHead($region->render(''));
251 print theme('maintenance_page', ['content' => $content]);
254 // TODO: Figure out why D7 returns but everyone else prints
261 CRM_Core_Config
::singleton()->userFramework
== 'WordPress'
263 if (!function_exists('is_admin')) {
264 throw new \
Exception('Function "is_admin()" is missing, even though WordPress is the user framework.');
266 if (!defined('ABSPATH')) {
267 throw new \
Exception('Constant "ABSPATH" is not defined, even though WordPress is the user framework.');
270 require_once ABSPATH
. 'wp-admin/admin-header.php';
273 // FIXME: we need to figure out to replace civicrm content on the frontend pages
289 public function getDefaultBlockLocation() {
294 * Get the absolute path to the site's base url.
296 * @return bool|mixed|string
298 public function getAbsoluteBaseURL() {
299 if (!defined('CIVICRM_UF_BASEURL')) {
303 $url = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
305 //format url for language negotiation, CRM-7803
306 $url = $this->languageNegotiationURL($url);
308 if (CRM_Utils_System
::isSSL()) {
309 $url = str_replace('http://', 'https://', $url);
316 * Get the relative path to the sites base url.
320 public function getRelativeBaseURL() {
321 $absoluteBaseURL = $this->getAbsoluteBaseURL();
322 if ($absoluteBaseURL === FALSE) {
325 $parts = parse_url($absoluteBaseURL);
326 return $parts['path'];
327 //$this->useFrameworkRelativeBase = empty($base['path']) ? '/' : $base['path'];
335 public function getVersion() {
340 * Format the url as per language Negotiation.
343 * @param bool $addLanguagePart
344 * @param bool $removeLanguagePart
349 public function languageNegotiationURL(
351 $addLanguagePart = TRUE,
352 $removeLanguagePart = FALSE
358 * Determine the location of the CMS root.
360 * @return string|null
361 * Local file system path to CMS root, or NULL if it cannot be determined
363 public function cmsRootPath() {
368 * Create a user in the CMS.
370 * @param array $params
371 * @param string $mail
372 * Email id for cms user.
375 * uid if user exists, false otherwise
377 public function createUser(&$params, $mail) {
382 * Update a user's email address in the CMS.
386 * @param string $email
387 * Primary contact email address.
389 public function updateCMSName($ufID, $email) {
393 * Check if user is logged in to the CMS.
397 public function isUserLoggedIn() {
402 * Check if user registration is permitted.
406 public function isUserRegistrationPermitted() {
411 * Check if user can create passwords or is initially assigned a system-generated one.
415 public function isPasswordUserGenerated() {
420 * Is a front end page being accessed.
422 * Generally this would be a contribution form or other public page as opposed to a backoffice page (like contact edit).
424 * @todo Drupal uses the is_public setting - clarify & rationalise. See https://github.com/civicrm/civicrm-drupal/pull/546/files
428 public function isFrontEndPage() {
429 return CRM_Core_Config
::singleton()->userFrameworkFrontend
;
433 * Get user login URL for hosting CMS (method declared in each CMS system class)
435 * @param string $destination
436 * If present, add destination to querystring (works for Drupal only).
439 * loginURL for the current CMS
441 abstract public function getLoginURL($destination = '');
444 * Get the login destination string.
446 * When this is passed in the URL the user will be directed to it after filling in the CMS form.
448 * @param CRM_Core_Form $form
449 * Form object representing the 'current' form - to which the user will be returned.
451 * @return string|NULL
452 * destination value for URL
454 public function getLoginDestination(&$form) {
459 * Determine the native ID of the CMS user.
461 * @param string $username
463 * @throws CRM_Core_Exception
465 public function getUfId($username) {
466 $className = get_class($this);
467 throw new CRM_Core_Exception("Not implemented: {$className}->getUfId");
471 * Set the localisation from the user framework.
473 * @param string $civicrm_language
477 public function setUFLocale($civicrm_language) {
482 * Set a init session with user object.
485 * Array with user specific data
487 public function setUserSession($data) {
488 list($userID, $ufID) = $data;
489 $session = CRM_Core_Session
::singleton();
490 $session->set('ufID', $ufID);
491 $session->set('userID', $userID);
495 * Reset any system caches that may be required for proper CiviCRM integration.
497 public function flush() {
502 * Flush css/js caches.
504 public function clearResourceCache() {
511 * Note: This function is not to be called directly
512 * @see CRM_Core_Region::render()
514 * @param string $url absolute path to file
515 * @param string $region
516 * location within the document: 'html-header', 'page-header', 'page-footer'.
519 * TRUE if we support this operation in this CMS, FALSE otherwise
521 public function addScriptUrl($url, $region) {
526 * Add an inline script.
528 * Note: This function is not to be called directly
529 * @see CRM_Core_Region::render()
531 * @param string $code javascript code
532 * @param string $region
533 * location within the document: 'html-header', 'page-header', 'page-footer'.
536 * TRUE if we support this operation in this CMS, FALSE otherwise
538 public function addScript($code, $region) {
545 * Note: This function is not to be called directly
546 * @see CRM_Core_Region::render()
548 * @param string $url absolute path to file
549 * @param string $region
550 * location within the document: 'html-header', 'page-header', 'page-footer'.
553 * TRUE if we support this operation in this CMS, FALSE otherwise
555 public function addStyleUrl($url, $region) {
560 * Add an inline style.
562 * Note: This function is not to be called directly
563 * @see CRM_Core_Region::render()
565 * @param string $code css code
566 * @param string $region
567 * location within the document: 'html-header', 'page-header', 'page-footer'.
570 * TRUE if we support this operation in this CMS, FALSE otherwise
572 public function addStyle($code, $region) {
577 * Sets the title of the page.
579 * @param string $title
580 * Title to set in html header
581 * @param string|null $pageTitle
582 * Title to set in html body (if different)
584 public function setTitle($title, $pageTitle = NULL) {
588 * Return default Site Settings.
593 * - $url, (Joomla - non admin url)
597 public function getDefaultSiteSettings($dir) {
598 $config = CRM_Core_Config
::singleton();
599 $url = $config->userFrameworkBaseURL
;
600 return [$url, NULL, NULL];
604 * Determine the default location for file storage.
607 * 1. This was pulled out from a bigger function. It should be split
608 * into even smaller pieces and marked abstract.
609 * 2. This would be easier to compute by a calling a CMS API, but
610 * for whatever reason Civi gets it from config data.
613 * - url: string. ex: "http://example.com/sites/foo.com/files/civicrm"
614 * - path: string. ex: "/var/www/sites/foo.com/files/civicrm"
616 public function getDefaultFileStorage() {
617 global $civicrm_root;
618 $config = CRM_Core_Config
::singleton();
619 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
624 if ($config->userFramework
== 'Joomla') {
626 // we need to remove the administrator/ from the end
627 $tempURL = str_replace("/administrator/", "/", $baseURL);
628 $filesURL = $tempURL . "media/civicrm/";
630 elseif ($config->userFramework
== 'UnitTests') {
631 $filesURL = $baseURL . "sites/default/files/civicrm/";
634 throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
639 'path' => CRM_Utils_File
::baseFilePath(),
644 * Determine the location of the CiviCRM source tree.
647 * 1. This was pulled out from a bigger function. It should be split
648 * into even smaller pieces and marked abstract.
649 * 2. This would be easier to compute by a calling a CMS API, but
650 * for whatever reason we take the hard way.
653 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
654 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
656 public function getCiviSourceStorage() {
657 global $civicrm_root;
658 $config = CRM_Core_Config
::singleton();
660 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
661 // More generally, w shouldn't be using $config here.
662 if (!defined('CIVICRM_UF_BASEURL')) {
663 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
665 $baseURL = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
666 if (CRM_Utils_System
::isSSL()) {
667 $baseURL = str_replace('http://', 'https://', $baseURL);
670 // @todo this function is only called / code is only reached when is_drupal is true - move this to the drupal classes
671 // and don't implement here.
672 if ($this->is_drupal
) {
674 // check and see if we are installed in sites/all (for D5 and above)
675 // we dont use checkURL since drupal generates an error page and throws
676 // the system for a loop on lobo's macosx box
678 $cmsPath = $config->userSystem
->cmsRootPath();
679 $userFrameworkResourceURL = $baseURL . str_replace("$cmsPath/", '',
680 str_replace('\\', '/', $civicrm_root)
683 $siteName = $config->userSystem
->parseDrupalSiteNameFromRoot($civicrm_root);
685 $civicrmDirName = trim(basename($civicrm_root));
686 $userFrameworkResourceURL = $baseURL . "sites/$siteName/modules/$civicrmDirName/";
690 $userFrameworkResourceURL = NULL;
694 'url' => CRM_Utils_File
::addTrailingSlash($userFrameworkResourceURL, '/'),
695 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
700 * Perform any post login activities required by the CMS.
702 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
703 * calls hook_user op 'login' and generates a new session.
705 * @param array $params
707 * FIXME: Document values accepted/required by $params
709 public function userLoginFinalize($params = []) {
713 * Set timezone in mysql so that timestamp fields show the correct time.
715 public function setMySQLTimeZone() {
716 $timeZoneOffset = $this->getTimeZoneOffset();
717 if ($timeZoneOffset) {
718 $sql = "SET time_zone = '$timeZoneOffset'";
719 CRM_Core_DAO
::executequery($sql);
724 * Get timezone from CMS.
726 * @return string|false|null
728 public function getTimeZoneOffset() {
729 $timezone = $this->getTimeZoneString();
731 if ($timezone == 'UTC' ||
$timezone == 'Etc/UTC') {
732 // CRM-17072 Let's short-circuit all the zero handling & return it here!
735 $tzObj = new DateTimeZone($timezone);
736 $dateTime = new DateTime("now", $tzObj);
737 $tz = $tzObj->getOffset($dateTime);
748 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz / 60) %
60));
750 if ($timeZoneOffset > 0) {
751 $timeZoneOffset = '+' . $timeZoneOffset;
753 return $timeZoneOffset;
759 * Get timezone as a string.
761 * Timezone string e.g. 'America/Los_Angeles'
763 public function getTimeZoneString() {
764 return date_default_timezone_get();
768 * Get Unique Identifier from UserFramework system (CMS).
770 * @param object $user
771 * Object as described by the User Framework.
774 * Unique identifier from the user Framework system
776 public function getUniqueIdentifierFromUserObject($user) {
781 * Get User ID from UserFramework system (CMS).
783 * @param object $user
785 * Object as described by the User Framework.
788 public function getUserIDFromUserObject($user) {
793 * Get an array of user details for a contact, containing at minimum the user ID & name.
795 * @param int $contactID
798 * CMS user details including
800 * - name (ie the system user name.
802 public function getUser($contactID) {
803 $ufMatch = civicrm_api3('UFMatch', 'getsingle', [
804 'contact_id' => $contactID,
805 'domain_id' => CRM_Core_Config
::domainID(),
808 'id' => $ufMatch['uf_id'],
809 'name' => $ufMatch['uf_name'],
814 * Get currently logged in user uf id.
817 * logged in user uf id.
819 public function getLoggedInUfID() {
824 * Get currently logged in user unique identifier - this tends to be the email address or user name.
826 * @return string|null
827 * logged in user unique identifier
829 public function getLoggedInUniqueIdentifier() {
834 * Return a UFID (user account ID from the UserFramework / CMS system.
836 * ID is based on the user object passed, defaulting to the logged in user if not passed.
838 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would
839 * seem to be resolving the user id before calling the function.
841 * Note there is already a function getUFId which takes $username as a param - we could add $user
842 * as a second param to it but it seems messy - just overloading it because the name is taken.
844 * @param object $user
847 * User ID of UF System
849 public function getBestUFID($user = NULL) {
851 return $this->getUserIDFromUserObject($user);
853 return $this->getLoggedInUfID();
857 * Return a unique identifier (usually an email address or username) from the UserFramework / CMS system.
859 * This is based on the user object passed, defaulting to the logged in user if not passed.
861 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would seem to be
862 * resolving the unique identifier before calling the function.
864 * @param object $user
867 * unique identifier from the UF System
869 public function getBestUFUniqueIdentifier($user = NULL) {
871 return $this->getUniqueIdentifierFromUserObject($user);
873 return $this->getLoggedInUniqueIdentifier();
877 * List modules installed in the CMS, including enabled and disabled ones.
882 public function getModules() {
887 * Get Url to view user record.
889 * @param int $contactID
892 * @return string|null
894 public function getUserRecordUrl($contactID) {
899 * Is the current user permitted to add a user.
903 public function checkPermissionAddUser() {
908 * Output code from error function.
910 * @param string $content
912 public function outputError($content) {
913 echo CRM_Utils_System
::theme($content);
919 * @param string $message
921 public function logger($message) {
925 * Append to coreResourcesList.
927 * @param \Civi\Core\Event\GenericHookEvent $e
929 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
933 * Modify dynamic assets.
935 * @param \Civi\Core\Event\GenericHookEvent $e
937 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
941 * @param string $name
942 * @param string $value
944 public function setHttpHeader($name, $value) {
945 header("$name: $value");
949 * Create CRM contacts for all existing CMS users
954 public function synchronizeUsers() {
955 throw new Exception('CMS user creation not supported for this framework');
960 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
962 * @param \Psr\Http\Message\ResponseInterface $response
964 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
965 http_response_code($response->getStatusCode());
966 foreach ($response->getHeaders() as $name => $values) {
967 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
969 echo $response->getBody();
970 CRM_Utils_System
::civiExit();
974 * Start a new session.
976 public function sessionStart() {
985 public function getRoleNames() {
990 * Determine if the Views module exists.
994 public function viewsExists() {