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).
127 * @param bool $htmlize
128 * Whether to encode special html characters such as &.
138 $forceBackend = FALSE,
145 * Authenticate the user against the CMS db.
147 * @param string $name
149 * @param string $password
150 * The password for the above user.
151 * @param bool $loadCMSBootstrap
152 * Load cms bootstrap?.
153 * @param string $realPath
157 * [contactID, ufID, unique string] else false if no auth
158 * @throws \CRM_Core_Exception.
160 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
165 * Set a message in the CMS to display to a user.
167 * @param string $message
168 * The message to set.
170 public function setMessage($message) {
174 * Load user into session.
180 public function loadUser($user) {
185 * Immediately stop script execution and display a 401 "Access Denied" page.
186 * @throws \CRM_Core_Exception
188 public function permissionDenied() {
189 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
193 * Immediately stop script execution, log out the user and redirect to the home page.
196 * This function should be removed in favor of linking to the CMS's logout page
198 public function logout() {
202 * Clear CMS caches related to the user registration/profile forms.
203 * Used when updating/embedding profiles on CMS user forms.
206 public function updateCategories() {
210 * Get the locale set in the CMS.
212 * @return string|null
213 * Locale or null for none
215 public function getUFLocale() {
220 * If we are using a theming system, invoke theme, else just print the content.
222 * @param string $content
223 * The content that will be themed.
225 * Are we displaying to the screen or bypassing theming?.
226 * @param bool $maintenance
227 * For maintenance mode.
230 * @return string|null
231 * NULL, If $print is FALSE, and some other criteria match up.
232 * The themed string, otherwise.
234 * @todo The return value is inconsistent.
235 * @todo Better to always return, and never print.
237 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
240 // TODO: Split up; this was copied verbatim from CiviCRM 4.0's multi-UF theming function
241 // but the parts should be copied into cleaner subclass implementations
242 $config = CRM_Core_Config
::singleton();
244 $config->userSystem
->is_drupal
&&
245 function_exists('theme') &&
249 drupal_set_breadcrumb('');
250 drupal_maintenance_theme();
251 if ($region = CRM_Core_Region
::instance('html-header', FALSE)) {
252 CRM_Utils_System
::addHTMLHead($region->render(''));
254 print theme('maintenance_page', ['content' => $content]);
257 // TODO: Figure out why D7 returns but everyone else prints
264 CRM_Core_Config
::singleton()->userFramework
== 'WordPress'
266 if (!function_exists('is_admin')) {
267 throw new \
Exception('Function "is_admin()" is missing, even though WordPress is the user framework.');
269 if (!defined('ABSPATH')) {
270 throw new \
Exception('Constant "ABSPATH" is not defined, even though WordPress is the user framework.');
273 require_once ABSPATH
. 'wp-admin/admin-header.php';
276 // FIXME: we need to figure out to replace civicrm content on the frontend pages
292 public function getDefaultBlockLocation() {
297 * Get the absolute path to the site's base url.
299 * @return bool|mixed|string
301 public function getAbsoluteBaseURL() {
302 if (!defined('CIVICRM_UF_BASEURL')) {
306 $url = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
308 //format url for language negotiation, CRM-7803
309 $url = $this->languageNegotiationURL($url);
311 if (CRM_Utils_System
::isSSL()) {
312 $url = str_replace('http://', 'https://', $url);
319 * Get the relative path to the sites base url.
323 public function getRelativeBaseURL() {
324 $absoluteBaseURL = $this->getAbsoluteBaseURL();
325 if ($absoluteBaseURL === FALSE) {
328 $parts = parse_url($absoluteBaseURL);
329 return $parts['path'];
330 //$this->useFrameworkRelativeBase = empty($base['path']) ? '/' : $base['path'];
338 public function getVersion() {
343 * Format the url as per language Negotiation.
346 * @param bool $addLanguagePart
347 * @param bool $removeLanguagePart
352 public function languageNegotiationURL(
354 $addLanguagePart = TRUE,
355 $removeLanguagePart = FALSE
361 * Determine the location of the CMS root.
363 * @return string|null
364 * Local file system path to CMS root, or NULL if it cannot be determined
366 public function cmsRootPath() {
371 * Create a user in the CMS.
373 * @param array $params
374 * @param string $mail
375 * Email id for cms user.
378 * uid if user exists, false otherwise
380 public function createUser(&$params, $mail) {
385 * Update a user's email address in the CMS.
389 * @param string $email
390 * Primary contact email address.
392 public function updateCMSName($ufID, $email) {
396 * Check if user is logged in to the CMS.
400 public function isUserLoggedIn() {
405 * Check if user registration is permitted.
409 public function isUserRegistrationPermitted() {
414 * Check if user can create passwords or is initially assigned a system-generated one.
418 public function isPasswordUserGenerated() {
423 * Is a front end page being accessed.
425 * Generally this would be a contribution form or other public page as opposed to a backoffice page (like contact edit).
427 * @todo Drupal uses the is_public setting - clarify & rationalise. See https://github.com/civicrm/civicrm-drupal/pull/546/files
431 public function isFrontEndPage() {
432 return CRM_Core_Config
::singleton()->userFrameworkFrontend
;
436 * Get user login URL for hosting CMS (method declared in each CMS system class)
438 * @param string $destination
439 * If present, add destination to querystring (works for Drupal only).
442 * loginURL for the current CMS
444 abstract public function getLoginURL($destination = '');
447 * Get the login destination string.
449 * When this is passed in the URL the user will be directed to it after filling in the CMS form.
451 * @param CRM_Core_Form $form
452 * Form object representing the 'current' form - to which the user will be returned.
454 * @return string|NULL
455 * destination value for URL
457 public function getLoginDestination(&$form) {
462 * Determine the native ID of the CMS user.
464 * @param string $username
466 * @throws CRM_Core_Exception
468 public function getUfId($username) {
469 $className = get_class($this);
470 throw new CRM_Core_Exception("Not implemented: {$className}->getUfId");
474 * Set the localisation from the user framework.
476 * @param string $civicrm_language
480 public function setUFLocale($civicrm_language) {
485 * Set a init session with user object.
488 * Array with user specific data
490 public function setUserSession($data) {
491 list($userID, $ufID) = $data;
492 $session = CRM_Core_Session
::singleton();
493 $session->set('ufID', $ufID);
494 $session->set('userID', $userID);
498 * Reset any system caches that may be required for proper CiviCRM integration.
500 public function flush() {
505 * Flush css/js caches.
507 public function clearResourceCache() {
514 * Note: This function is not to be called directly
515 * @see CRM_Core_Region::render()
517 * @param string $url absolute path to file
518 * @param string $region
519 * location within the document: 'html-header', 'page-header', 'page-footer'.
522 * TRUE if we support this operation in this CMS, FALSE otherwise
524 public function addScriptUrl($url, $region) {
529 * Add an inline script.
531 * Note: This function is not to be called directly
532 * @see CRM_Core_Region::render()
534 * @param string $code javascript code
535 * @param string $region
536 * location within the document: 'html-header', 'page-header', 'page-footer'.
539 * TRUE if we support this operation in this CMS, FALSE otherwise
541 public function addScript($code, $region) {
548 * Note: This function is not to be called directly
549 * @see CRM_Core_Region::render()
551 * @param string $url absolute path to file
552 * @param string $region
553 * location within the document: 'html-header', 'page-header', 'page-footer'.
556 * TRUE if we support this operation in this CMS, FALSE otherwise
558 public function addStyleUrl($url, $region) {
563 * Add an inline style.
565 * Note: This function is not to be called directly
566 * @see CRM_Core_Region::render()
568 * @param string $code css code
569 * @param string $region
570 * location within the document: 'html-header', 'page-header', 'page-footer'.
573 * TRUE if we support this operation in this CMS, FALSE otherwise
575 public function addStyle($code, $region) {
580 * Sets the title of the page.
582 * @param string $title
583 * Title to set in html header
584 * @param string|null $pageTitle
585 * Title to set in html body (if different)
587 public function setTitle($title, $pageTitle = NULL) {
591 * Return default Site Settings.
596 * - $url, (Joomla - non admin url)
600 public function getDefaultSiteSettings($dir) {
601 $config = CRM_Core_Config
::singleton();
602 $url = $config->userFrameworkBaseURL
;
603 return [$url, NULL, NULL];
607 * Determine the default location for file storage.
610 * 1. This was pulled out from a bigger function. It should be split
611 * into even smaller pieces and marked abstract.
612 * 2. This would be easier to compute by a calling a CMS API, but
613 * for whatever reason Civi gets it from config data.
616 * - url: string. ex: "http://example.com/sites/foo.com/files/civicrm"
617 * - path: string. ex: "/var/www/sites/foo.com/files/civicrm"
619 public function getDefaultFileStorage() {
620 global $civicrm_root;
621 $config = CRM_Core_Config
::singleton();
622 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
627 if ($config->userFramework
== 'Joomla') {
629 // we need to remove the administrator/ from the end
630 $tempURL = str_replace("/administrator/", "/", $baseURL);
631 $filesURL = $tempURL . "media/civicrm/";
633 elseif ($config->userFramework
== 'UnitTests') {
634 $filesURL = $baseURL . "sites/default/files/civicrm/";
637 throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
642 'path' => CRM_Utils_File
::baseFilePath(),
647 * Determine the location of the CiviCRM source tree.
650 * 1. This was pulled out from a bigger function. It should be split
651 * into even smaller pieces and marked abstract.
652 * 2. This would be easier to compute by a calling a CMS API, but
653 * for whatever reason we take the hard way.
656 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
657 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
659 public function getCiviSourceStorage() {
660 global $civicrm_root;
661 $config = CRM_Core_Config
::singleton();
663 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
664 // More generally, w shouldn't be using $config here.
665 if (!defined('CIVICRM_UF_BASEURL')) {
666 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
668 $baseURL = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
669 if (CRM_Utils_System
::isSSL()) {
670 $baseURL = str_replace('http://', 'https://', $baseURL);
673 // @todo this function is only called / code is only reached when is_drupal is true - move this to the drupal classes
674 // and don't implement here.
675 if ($this->is_drupal
) {
677 // check and see if we are installed in sites/all (for D5 and above)
678 // we dont use checkURL since drupal generates an error page and throws
679 // the system for a loop on lobo's macosx box
681 $cmsPath = $config->userSystem
->cmsRootPath();
682 $userFrameworkResourceURL = $baseURL . str_replace("$cmsPath/", '',
683 str_replace('\\', '/', $civicrm_root)
686 $siteName = $config->userSystem
->parseDrupalSiteNameFromRoot($civicrm_root);
688 $civicrmDirName = trim(basename($civicrm_root));
689 $userFrameworkResourceURL = $baseURL . "sites/$siteName/modules/$civicrmDirName/";
693 $userFrameworkResourceURL = NULL;
697 'url' => CRM_Utils_File
::addTrailingSlash($userFrameworkResourceURL, '/'),
698 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
703 * Perform any post login activities required by the CMS.
705 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
706 * calls hook_user op 'login' and generates a new session.
708 * @param array $params
710 * FIXME: Document values accepted/required by $params
712 public function userLoginFinalize($params = []) {
716 * Set timezone in mysql so that timestamp fields show the correct time.
718 public function setMySQLTimeZone() {
719 $timeZoneOffset = $this->getTimeZoneOffset();
720 if ($timeZoneOffset) {
721 $sql = "SET time_zone = '$timeZoneOffset'";
722 CRM_Core_DAO
::executequery($sql);
727 * Get timezone from CMS.
729 * @return string|false|null
731 public function getTimeZoneOffset() {
732 $timezone = $this->getTimeZoneString();
734 if ($timezone == 'UTC' ||
$timezone == 'Etc/UTC') {
735 // CRM-17072 Let's short-circuit all the zero handling & return it here!
738 $tzObj = new DateTimeZone($timezone);
739 $dateTime = new DateTime("now", $tzObj);
740 $tz = $tzObj->getOffset($dateTime);
751 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz / 60) %
60));
753 if ($timeZoneOffset > 0) {
754 $timeZoneOffset = '+' . $timeZoneOffset;
756 return $timeZoneOffset;
762 * Get timezone as a string.
764 * Timezone string e.g. 'America/Los_Angeles'
766 public function getTimeZoneString() {
767 return date_default_timezone_get();
771 * Get Unique Identifier from UserFramework system (CMS).
773 * @param object $user
774 * Object as described by the User Framework.
777 * Unique identifier from the user Framework system
779 public function getUniqueIdentifierFromUserObject($user) {
784 * Get User ID from UserFramework system (CMS).
786 * @param object $user
788 * Object as described by the User Framework.
791 public function getUserIDFromUserObject($user) {
796 * Get an array of user details for a contact, containing at minimum the user ID & name.
798 * @param int $contactID
801 * CMS user details including
803 * - name (ie the system user name.
805 public function getUser($contactID) {
806 $ufMatch = civicrm_api3('UFMatch', 'getsingle', [
807 'contact_id' => $contactID,
808 'domain_id' => CRM_Core_Config
::domainID(),
811 'id' => $ufMatch['uf_id'],
812 'name' => $ufMatch['uf_name'],
817 * Get currently logged in user uf id.
820 * logged in user uf id.
822 public function getLoggedInUfID() {
827 * Get currently logged in user unique identifier - this tends to be the email address or user name.
829 * @return string|null
830 * logged in user unique identifier
832 public function getLoggedInUniqueIdentifier() {
837 * Return a UFID (user account ID from the UserFramework / CMS system.
839 * ID is based on the user object passed, defaulting to the logged in user if not passed.
841 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would
842 * seem to be resolving the user id before calling the function.
844 * Note there is already a function getUFId which takes $username as a param - we could add $user
845 * as a second param to it but it seems messy - just overloading it because the name is taken.
847 * @param object $user
850 * User ID of UF System
852 public function getBestUFID($user = NULL) {
854 return $this->getUserIDFromUserObject($user);
856 return $this->getLoggedInUfID();
860 * Return a unique identifier (usually an email address or username) from the UserFramework / CMS system.
862 * This is based on the user object passed, defaulting to the logged in user if not passed.
864 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would seem to be
865 * resolving the unique identifier before calling the function.
867 * @param object $user
870 * unique identifier from the UF System
872 public function getBestUFUniqueIdentifier($user = NULL) {
874 return $this->getUniqueIdentifierFromUserObject($user);
876 return $this->getLoggedInUniqueIdentifier();
880 * List modules installed in the CMS, including enabled and disabled ones.
885 public function getModules() {
890 * Get Url to view user record.
892 * @param int $contactID
895 * @return string|null
897 public function getUserRecordUrl($contactID) {
902 * Is the current user permitted to add a user.
906 public function checkPermissionAddUser() {
911 * Output code from error function.
913 * @param string $content
915 public function outputError($content) {
916 echo CRM_Utils_System
::theme($content);
922 * @param string $message
924 public function logger($message) {
928 * Append to coreResourcesList.
930 * @param \Civi\Core\Event\GenericHookEvent $e
932 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
936 * Modify dynamic assets.
938 * @param \Civi\Core\Event\GenericHookEvent $e
940 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
944 * @param string $name
945 * @param string $value
947 public function setHttpHeader($name, $value) {
948 header("$name: $value");
952 * Create CRM contacts for all existing CMS users
957 public function synchronizeUsers() {
958 throw new Exception('CMS user creation not supported for this framework');
963 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
965 * @param \Psr\Http\Message\ResponseInterface $response
967 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
968 http_response_code($response->getStatusCode());
969 foreach ($response->getHeaders() as $name => $values) {
970 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
972 echo $response->getBody();
973 CRM_Utils_System
::civiExit();
977 * Start a new session.
979 public function sessionStart() {
988 public function getRoleNames() {
993 * Determine if the Views module exists.
997 public function viewsExists() {