3f99ae6af942548dc075e029f8d8481a44c338cf
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 var $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 var $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 var $is_wordpress = FALSE;
41 * Does this CMS / UF support a CMS specific logging mechanism?
42 * @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
45 var $supports_UF_Logging = FALSE;
49 * TRUE, if the CMS allows CMS forms to be extended by hooks.
51 var $supports_form_extensions = FALSE;
53 public function initialize() {
54 if (\CRM_Utils_System
::isSSL()) {
55 $this->mapConfigToSSL();
59 public abstract 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
156 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
161 * Set a message in the CMS to display to a user.
163 * @param string $message
164 * The message to set.
166 public function setMessage($message) {
170 * Load user into session.
176 public function loadUser($user) {
181 * Immediately stop script execution and display a 401 "Access Denied" page.
183 public function permissionDenied() {
184 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
188 * Immediately stop script execution, log out the user and redirect to the home page.
191 * This function should be removed in favor of linking to the CMS's logout page
193 public function logout() {
197 * Clear CMS caches related to the user registration/profile forms.
198 * Used when updating/embedding profiles on CMS user forms.
201 public function updateCategories() {
205 * Get the locale set in the CMS.
207 * @return string|null
208 * Locale or null for none
210 public function getUFLocale() {
215 * If we are using a theming system, invoke theme, else just print the content.
217 * @param string $content
218 * The content that will be themed.
220 * Are we displaying to the screen or bypassing theming?.
221 * @param bool $maintenance
222 * For maintenance mode.
225 * @return string|null
226 * NULL, If $print is FALSE, and some other criteria match up.
227 * The themed string, otherwise.
229 * @todo The return value is inconsistent.
230 * @todo Better to always return, and never print.
232 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
235 // TODO: Split up; this was copied verbatim from CiviCRM 4.0's multi-UF theming function
236 // but the parts should be copied into cleaner subclass implementations
237 $config = CRM_Core_Config
::singleton();
239 $config->userSystem
->is_drupal
&&
240 function_exists('theme') &&
244 drupal_set_breadcrumb('');
245 drupal_maintenance_theme();
246 if ($region = CRM_Core_Region
::instance('html-header', FALSE)) {
247 CRM_Utils_System
::addHTMLHead($region->render(''));
249 print theme('maintenance_page', ['content' => $content]);
252 // TODO: Figure out why D7 returns but everyone else prints
257 $config = &CRM_Core_Config
::singleton();
260 $config->userFramework
== 'WordPress'
262 if (!function_exists('is_admin')) {
263 throw new \
Exception('Function "is_admin()" is missing, even though WordPress is the user framework.');
265 if (!defined('ABSPATH')) {
266 throw new \
Exception('Constant "ABSPATH" is not defined, even though WordPress is the user framework.');
269 require_once ABSPATH
. 'wp-admin/admin-header.php';
272 // FIXME: we need to figure out to replace civicrm content on the frontend pages
288 public function getDefaultBlockLocation() {
293 * Get the absolute path to the site's base url.
295 * @return bool|mixed|string
297 public function getAbsoluteBaseURL() {
298 if (!defined('CIVICRM_UF_BASEURL')) {
302 $url = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
304 //format url for language negotiation, CRM-7803
305 $url = $this->languageNegotiationURL($url);
307 if (CRM_Utils_System
::isSSL()) {
308 $url = str_replace('http://', 'https://', $url);
315 * Get the relative path to the sites base url.
319 public function getRelativeBaseURL() {
320 $absoluteBaseURL = $this->getAbsoluteBaseURL();
321 if ($absoluteBaseURL === FALSE) {
324 $parts = parse_url($absoluteBaseURL);
325 return $parts['path'];
326 //$this->useFrameworkRelativeBase = empty($base['path']) ? '/' : $base['path'];
334 public function getVersion() {
339 * Format the url as per language Negotiation.
342 * @param bool $addLanguagePart
343 * @param bool $removeLanguagePart
348 public function languageNegotiationURL(
350 $addLanguagePart = TRUE,
351 $removeLanguagePart = FALSE
357 * Determine the location of the CMS root.
359 * @return string|null
360 * Local file system path to CMS root, or NULL if it cannot be determined
362 public function cmsRootPath() {
367 * Create a user in the CMS.
369 * @param array $params
370 * @param string $mail
371 * Email id for cms user.
374 * uid if user exists, false otherwise
376 public function createUser(&$params, $mail) {
381 * Update a user's email address in the CMS.
385 * @param string $email
386 * Primary contact email address.
388 public function updateCMSName($ufID, $email) {
392 * Check if user is logged in to the CMS.
396 public function isUserLoggedIn() {
401 * Check if user registration is permitted.
405 public function isUserRegistrationPermitted() {
410 * Check if user can create passwords or is initially assigned a system-generated one.
414 public function isPasswordUserGenerated() {
419 * Get user login URL for hosting CMS (method declared in each CMS system class)
421 * @param string $destination
422 * If present, add destination to querystring (works for Drupal only).
425 * loginURL for the current CMS
427 public abstract function getLoginURL($destination = '');
430 * Get the login destination string.
432 * When this is passed in the URL the user will be directed to it after filling in the CMS form.
434 * @param CRM_Core_Form $form
435 * Form object representing the 'current' form - to which the user will be returned.
437 * @return string|NULL
438 * destination value for URL
440 public function getLoginDestination(&$form) {
445 * Determine the native ID of the CMS user.
447 * @param string $username
449 * @throws CRM_Core_Exception
451 public function getUfId($username) {
452 $className = get_class($this);
453 throw new CRM_Core_Exception("Not implemented: {$className}->getUfId");
457 * Set the localisation from the user framework.
459 * @param string $civicrm_language
463 public function setUFLocale($civicrm_language) {
468 * Set a init session with user object.
471 * Array with user specific data
473 public function setUserSession($data) {
474 list($userID, $ufID) = $data;
475 $session = CRM_Core_Session
::singleton();
476 $session->set('ufID', $ufID);
477 $session->set('userID', $userID);
481 * Reset any system caches that may be required for proper CiviCRM integration.
483 public function flush() {
488 * Flush css/js caches.
490 public function clearResourceCache() {
497 * Note: This function is not to be called directly
498 * @see CRM_Core_Region::render()
500 * @param string $url absolute path to file
501 * @param string $region
502 * location within the document: 'html-header', 'page-header', 'page-footer'.
505 * TRUE if we support this operation in this CMS, FALSE otherwise
507 public function addScriptUrl($url, $region) {
512 * Add an inline script.
514 * Note: This function is not to be called directly
515 * @see CRM_Core_Region::render()
517 * @param string $code javascript code
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 addScript($code, $region) {
531 * Note: This function is not to be called directly
532 * @see CRM_Core_Region::render()
534 * @param string $url absolute path to file
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 addStyleUrl($url, $region) {
546 * Add an inline style.
548 * Note: This function is not to be called directly
549 * @see CRM_Core_Region::render()
551 * @param string $code css code
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 addStyle($code, $region) {
563 * Sets the title of the page.
565 * @param string $title
566 * Title to set in html header
567 * @param string|null $pageTitle
568 * Title to set in html body (if different)
570 public function setTitle($title, $pageTitle = NULL) {
574 * Return default Site Settings.
579 * - $url, (Joomla - non admin url)
583 public function getDefaultSiteSettings($dir) {
584 $config = CRM_Core_Config
::singleton();
585 $url = $config->userFrameworkBaseURL
;
586 return [$url, NULL, NULL];
590 * Determine the default location for file storage.
593 * 1. This was pulled out from a bigger function. It should be split
594 * into even smaller pieces and marked abstract.
595 * 2. This would be easier to compute by a calling a CMS API, but
596 * for whatever reason Civi gets it from config data.
599 * - url: string. ex: "http://example.com/sites/foo.com/files/civicrm"
600 * - path: string. ex: "/var/www/sites/foo.com/files/civicrm"
602 public function getDefaultFileStorage() {
603 global $civicrm_root;
604 $config = CRM_Core_Config
::singleton();
605 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
610 if ($config->userFramework
== 'Joomla') {
612 // we need to remove the administrator/ from the end
613 $tempURL = str_replace("/administrator/", "/", $baseURL);
614 $filesURL = $tempURL . "media/civicrm/";
616 elseif ($config->userFramework
== 'UnitTests') {
617 $filesURL = $baseURL . "sites/default/files/civicrm/";
620 throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
625 'path' => CRM_Utils_File
::baseFilePath(),
630 * Determine the location of the CiviCRM source tree.
633 * 1. This was pulled out from a bigger function. It should be split
634 * into even smaller pieces and marked abstract.
635 * 2. This would be easier to compute by a calling a CMS API, but
636 * for whatever reason we take the hard way.
639 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
640 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
642 public function getCiviSourceStorage() {
643 global $civicrm_root;
644 $config = CRM_Core_Config
::singleton();
646 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
647 // More generally, w shouldn't be using $config here.
648 if (!defined('CIVICRM_UF_BASEURL')) {
649 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
651 $baseURL = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
652 if (CRM_Utils_System
::isSSL()) {
653 $baseURL = str_replace('http://', 'https://', $baseURL);
656 if ($config->userFramework
== 'Joomla') {
657 $userFrameworkResourceURL = $baseURL . "components/com_civicrm/civicrm/";
659 elseif ($config->userFramework
== 'WordPress') {
660 $userFrameworkResourceURL = CIVICRM_PLUGIN_URL
. "civicrm/";
662 elseif ($this->is_drupal
) {
664 // check and see if we are installed in sites/all (for D5 and above)
665 // we dont use checkURL since drupal generates an error page and throws
666 // the system for a loop on lobo's macosx box
668 $cmsPath = $config->userSystem
->cmsRootPath();
669 $userFrameworkResourceURL = $baseURL . str_replace("$cmsPath/", '',
670 str_replace('\\', '/', $civicrm_root)
673 $siteName = $config->userSystem
->parseDrupalSiteNameFromRoot($civicrm_root);
675 $civicrmDirName = trim(basename($civicrm_root));
676 $userFrameworkResourceURL = $baseURL . "sites/$siteName/modules/$civicrmDirName/";
680 $userFrameworkResourceURL = NULL;
684 'url' => CRM_Utils_File
::addTrailingSlash($userFrameworkResourceURL),
685 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
690 * Perform any post login activities required by the CMS.
692 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
693 * calls hook_user op 'login' and generates a new session.
695 * @param array $params
697 * FIXME: Document values accepted/required by $params
699 public function userLoginFinalize($params = []) {
703 * Set timezone in mysql so that timestamp fields show the correct time.
705 public function setMySQLTimeZone() {
706 $timeZoneOffset = $this->getTimeZoneOffset();
707 if ($timeZoneOffset) {
708 $sql = "SET time_zone = '$timeZoneOffset'";
709 CRM_Core_DAO
::executequery($sql);
715 * Get timezone from CMS.
717 * @return string|false|null
719 public function getTimeZoneOffset() {
720 $timezone = $this->getTimeZoneString();
722 if ($timezone == 'UTC' ||
$timezone == 'Etc/UTC') {
723 // CRM-17072 Let's short-circuit all the zero handling & return it here!
726 $tzObj = new DateTimeZone($timezone);
727 $dateTime = new DateTime("now", $tzObj);
728 $tz = $tzObj->getOffset($dateTime);
739 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz / 60) %
60));
741 if ($timeZoneOffset > 0) {
742 $timeZoneOffset = '+' . $timeZoneOffset;
744 return $timeZoneOffset;
750 * Get timezone as a string.
752 * Timezone string e.g. 'America/Los_Angeles'
754 public function getTimeZoneString() {
755 return date_default_timezone_get();
759 * Get Unique Identifier from UserFramework system (CMS).
761 * @param object $user
762 * Object as described by the User Framework.
765 * Unique identifier from the user Framework system
767 public function getUniqueIdentifierFromUserObject($user) {
772 * Get User ID from UserFramework system (CMS).
774 * @param object $user
776 * Object as described by the User Framework.
779 public function getUserIDFromUserObject($user) {
784 * Get an array of user details for a contact, containing at minimum the user ID & name.
786 * @param int $contactID
789 * CMS user details including
791 * - name (ie the system user name.
793 public function getUser($contactID) {
794 $ufMatch = civicrm_api3('UFMatch', 'getsingle', [
795 'contact_id' => $contactID,
796 'domain_id' => CRM_Core_Config
::domainID(),
799 'id' => $ufMatch['uf_id'],
800 'name' => $ufMatch['uf_name'],
805 * Get currently logged in user uf id.
808 * logged in user uf id.
810 public function getLoggedInUfID() {
815 * Get currently logged in user unique identifier - this tends to be the email address or user name.
817 * @return string|null
818 * logged in user unique identifier
820 public function getLoggedInUniqueIdentifier() {
825 * Return a UFID (user account ID from the UserFramework / CMS system.
827 * ID is based on the user object passed, defaulting to the logged in user if not passed.
829 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would
830 * seem to be resolving the user id before calling the function.
832 * Note there is already a function getUFId which takes $username as a param - we could add $user
833 * as a second param to it but it seems messy - just overloading it because the name is taken.
835 * @param object $user
838 * User ID of UF System
840 public function getBestUFID($user = NULL) {
842 return $this->getUserIDFromUserObject($user);
844 return $this->getLoggedInUfID();
848 * Return a unique identifier (usually an email address or username) from the UserFramework / CMS system.
850 * This is based on the user object passed, defaulting to the logged in user if not passed.
852 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would seem to be
853 * resolving the unique identifier before calling the function.
855 * @param object $user
858 * unique identifier from the UF System
860 public function getBestUFUniqueIdentifier($user = NULL) {
862 return $this->getUniqueIdentifierFromUserObject($user);
864 return $this->getLoggedInUniqueIdentifier();
868 * List modules installed in the CMS, including enabled and disabled ones.
873 public function getModules() {
878 * Get Url to view user record.
880 * @param int $contactID
883 * @return string|null
885 public function getUserRecordUrl($contactID) {
890 * Is the current user permitted to add a user.
894 public function checkPermissionAddUser() {
899 * Output code from error function.
901 * @param string $content
903 public function outputError($content) {
904 echo CRM_Utils_System
::theme($content);
910 * @param string $message
912 public function logger($message) {
916 * Append to coreResourcesList.
920 public function appendCoreResources(&$list) {
924 * @param string $name
925 * @param string $value
927 public function setHttpHeader($name, $value) {
928 header("$name: $value");
932 * Create CRM contacts for all existing CMS users
937 public function synchronizeUsers() {
938 throw new Exception('CMS user creation not supported for this framework');