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();
60 * Append an additional breadcrumb tag to the existing breadcrumb.
62 * @param array $breadCrumbs
64 public function appendBreadCrumb($breadCrumbs) {
68 * Reset an additional breadcrumb tag to the existing breadcrumb.
70 public function resetBreadCrumb() {
74 * Append a string to the head of the html file.
77 * The new string to be appended.
79 public function addHTMLHead($head) {
83 * Rewrite various system urls to https.
85 public function mapConfigToSSL() {
86 // dont need to do anything, let CMS handle their own switch to SSL
90 * Figure out the post url for QuickForm.
92 * @param string $action
93 * The default url if one is pre-specified.
96 * The url to post the form.
98 public function postURL($action) {
99 $config = CRM_Core_Config
::singleton();
100 if (!empty($action)) {
104 return $this->url(CRM_Utils_Array
::value($config->userFrameworkURLVar
, $_GET),
105 NULL, TRUE, NULL, FALSE
110 * Generate the url string to a CiviCRM path.
112 * @param string $path
113 * The path being linked to, such as "civicrm/add".
114 * @param string $query
115 * A query string to append to the link.
116 * @param bool $absolute
117 * Whether to force the output to be an absolute link (beginning with http).
118 * Useful for links that will be displayed outside the site, such as in an RSS feed.
119 * @param string $fragment
120 * A fragment identifier (named anchor) to append to the link.
121 * @param bool $frontend
122 * This link should be to the CMS front end (applies to WP & Joomla).
123 * @param bool $forceBackend
124 * This link should be to the CMS back end (applies to WP & Joomla).
134 $forceBackend = FALSE
140 * Authenticate the user against the CMS db.
142 * @param string $name
144 * @param string $password
145 * The password for the above user.
146 * @param bool $loadCMSBootstrap
147 * Load cms bootstrap?.
148 * @param string $realPath
152 * [contactID, ufID, unique string] else false if no auth
154 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
159 * Set a message in the CMS to display to a user.
161 * @param string $message
162 * The message to set.
164 public function setMessage($message) {
168 * Load user into session.
174 public function loadUser($user) {
179 * Immediately stop script execution and display a 401 "Access Denied" page.
181 public function permissionDenied() {
182 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
186 * Immediately stop script execution, log out the user and redirect to the home page.
189 * This function should be removed in favor of linking to the CMS's logout page
191 public function logout() {
195 * Clear CMS caches related to the user registration/profile forms.
196 * Used when updating/embedding profiles on CMS user forms.
199 public function updateCategories() {
203 * Get the locale set in the CMS.
205 * @return string|null
206 * Locale or null for none
208 public function getUFLocale() {
213 * If we are using a theming system, invoke theme, else just print the content.
215 * @param string $content
216 * The content that will be themed.
218 * Are we displaying to the screen or bypassing theming?.
219 * @param bool $maintenance
220 * For maintenance mode.
223 * @return string|null
224 * NULL, If $print is FALSE, and some other criteria match up.
225 * The themed string, otherwise.
227 * @todo The return value is inconsistent.
228 * @todo Better to always return, and never print.
230 public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
233 // TODO: Split up; this was copied verbatim from CiviCRM 4.0's multi-UF theming function
234 // but the parts should be copied into cleaner subclass implementations
235 $config = CRM_Core_Config
::singleton();
237 $config->userSystem
->is_drupal
&&
238 function_exists('theme') &&
242 drupal_set_breadcrumb('');
243 drupal_maintenance_theme();
244 if ($region = CRM_Core_Region
::instance('html-header', FALSE)) {
245 CRM_Utils_System
::addHTMLHead($region->render(''));
247 print theme('maintenance_page', array('content' => $content));
250 // TODO: Figure out why D7 returns but everyone else prints
255 $config = &CRM_Core_Config
::singleton();
258 $config->userFramework
== 'WordPress'
260 if (!function_exists('is_admin')) {
261 throw new \
Exception('Function "is_admin()" is missing, even though WordPress is the user framework.');
263 if (!defined('ABSPATH')) {
264 throw new \
Exception('Constant "ABSPATH" is not defined, even though WordPress is the user framework.');
267 require_once ABSPATH
. 'wp-admin/admin-header.php';
270 // FIXME: we need to figure out to replace civicrm content on the frontend pages
286 public function getDefaultBlockLocation() {
291 * Get the absolute path to the site's base url.
293 * @return bool|mixed|string
295 public function getAbsoluteBaseURL() {
296 if (!defined('CIVICRM_UF_BASEURL')) {
300 $url = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
302 //format url for language negotiation, CRM-7803
303 $url = $this->languageNegotiationURL($url);
305 if (CRM_Utils_System
::isSSL()) {
306 $url = str_replace('http://', 'https://', $url);
313 * Get the relative path to the sites base url.
317 public function getRelativeBaseURL() {
318 $absoluteBaseURL = $this->getAbsoluteBaseURL();
319 if ($absoluteBaseURL === FALSE) {
322 $parts = parse_url($absoluteBaseURL);
323 return $parts['path'];
324 //$this->useFrameworkRelativeBase = empty($base['path']) ? '/' : $base['path'];
332 public function getVersion() {
337 * Format the url as per language Negotiation.
340 * @param bool $addLanguagePart
341 * @param bool $removeLanguagePart
346 public function languageNegotiationURL(
348 $addLanguagePart = TRUE,
349 $removeLanguagePart = FALSE
355 * Determine the location of the CMS root.
357 * @return string|null
358 * Local file system path to CMS root, or NULL if it cannot be determined
360 public function cmsRootPath() {
365 * Create a user in the CMS.
367 * @param array $params
368 * @param string $mail
369 * Email id for cms user.
372 * uid if user exists, false otherwise
374 public function createUser(&$params, $mail) {
379 * Update a user's email address in the CMS.
383 * @param string $email
384 * Primary contact email address.
386 public function updateCMSName($ufID, $email) {
390 * Check if user is logged in to the CMS.
394 public function isUserLoggedIn() {
399 * Check if user registration is permitted.
403 public function isUserRegistrationPermitted() {
408 * Check if user can create passwords or is initially assigned a system-generated one.
412 public function isPasswordUserGenerated() {
417 * Get user login URL for hosting CMS (method declared in each CMS system class)
419 * @param string $destination
420 * If present, add destination to querystring (works for Drupal only).
423 * loginURL for the current CMS
425 public abstract function getLoginURL($destination = '');
428 * Get the login destination string.
430 * When this is passed in the URL the user will be directed to it after filling in the CMS form.
432 * @param CRM_Core_Form $form
433 * Form object representing the 'current' form - to which the user will be returned.
435 * @return string|NULL
436 * destination value for URL
438 public function getLoginDestination(&$form) {
443 * Determine the native ID of the CMS user.
445 * @param string $username
447 * @throws CRM_Core_Exception
449 public function getUfId($username) {
450 $className = get_class($this);
451 throw new CRM_Core_Exception("Not implemented: {$className}->getUfId");
455 * Set the localisation from the user framework.
457 * @param string $civicrm_language
461 public function setUFLocale($civicrm_language) {
466 * Set a init session with user object.
469 * Array with user specific data
471 public function setUserSession($data) {
472 list($userID, $ufID) = $data;
473 $session = CRM_Core_Session
::singleton();
474 $session->set('ufID', $ufID);
475 $session->set('userID', $userID);
479 * Reset any system caches that may be required for proper CiviCRM integration.
481 public function flush() {
486 * Flush css/js caches.
488 public function clearResourceCache() {
495 * Note: This function is not to be called directly
496 * @see CRM_Core_Region::render()
498 * @param string $url absolute path to file
499 * @param string $region
500 * location within the document: 'html-header', 'page-header', 'page-footer'.
503 * TRUE if we support this operation in this CMS, FALSE otherwise
505 public function addScriptUrl($url, $region) {
510 * Add an inline script.
512 * Note: This function is not to be called directly
513 * @see CRM_Core_Region::render()
515 * @param string $code javascript code
516 * @param string $region
517 * location within the document: 'html-header', 'page-header', 'page-footer'.
520 * TRUE if we support this operation in this CMS, FALSE otherwise
522 public function addScript($code, $region) {
529 * Note: This function is not to be called directly
530 * @see CRM_Core_Region::render()
532 * @param string $url absolute path to file
533 * @param string $region
534 * location within the document: 'html-header', 'page-header', 'page-footer'.
537 * TRUE if we support this operation in this CMS, FALSE otherwise
539 public function addStyleUrl($url, $region) {
544 * Add an inline style.
546 * Note: This function is not to be called directly
547 * @see CRM_Core_Region::render()
549 * @param string $code css code
550 * @param string $region
551 * location within the document: 'html-header', 'page-header', 'page-footer'.
554 * TRUE if we support this operation in this CMS, FALSE otherwise
556 public function addStyle($code, $region) {
561 * Sets the title of the page.
563 * @param string $title
564 * Title to set in html header
565 * @param string|null $pageTitle
566 * Title to set in html body (if different)
568 public function setTitle($title, $pageTitle = NULL) {
572 * Return default Site Settings.
577 * - $url, (Joomla - non admin url)
581 public function getDefaultSiteSettings($dir) {
582 $config = CRM_Core_Config
::singleton();
583 $url = $config->userFrameworkBaseURL
;
584 return array($url, NULL, NULL);
588 * Determine the default location for file storage.
591 * 1. This was pulled out from a bigger function. It should be split
592 * into even smaller pieces and marked abstract.
593 * 2. This would be easier to compute by a calling a CMS API, but
594 * for whatever reason Civi gets it from config data.
597 * - url: string. ex: "http://example.com/sites/foo.com/files/civicrm"
598 * - path: string. ex: "/var/www/sites/foo.com/files/civicrm"
600 public function getDefaultFileStorage() {
601 global $civicrm_root;
602 $config = CRM_Core_Config
::singleton();
603 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
608 if ($config->userFramework
== 'Joomla') {
610 // we need to remove the administrator/ from the end
611 $tempURL = str_replace("/administrator/", "/", $baseURL);
612 $filesURL = $tempURL . "media/civicrm/";
614 elseif ($config->userFramework
== 'UnitTests') {
615 $filesURL = $baseURL . "sites/default/files/civicrm/";
618 throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
623 'path' => CRM_Utils_File
::baseFilePath(),
628 * Determine the location of the CiviCRM source tree.
631 * 1. This was pulled out from a bigger function. It should be split
632 * into even smaller pieces and marked abstract.
633 * 2. This would be easier to compute by a calling a CMS API, but
634 * for whatever reason we take the hard way.
637 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
638 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
640 public function getCiviSourceStorage() {
641 global $civicrm_root;
642 $config = CRM_Core_Config
::singleton();
644 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
645 // More generally, w shouldn't be using $config here.
646 if (!defined('CIVICRM_UF_BASEURL')) {
647 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
649 $baseURL = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
650 if (CRM_Utils_System
::isSSL()) {
651 $baseURL = str_replace('http://', 'https://', $baseURL);
654 if ($config->userFramework
== 'Joomla') {
655 $userFrameworkResourceURL = $baseURL . "components/com_civicrm/civicrm/";
657 elseif ($config->userFramework
== 'WordPress') {
658 $userFrameworkResourceURL = CIVICRM_PLUGIN_URL
. "civicrm/";
660 elseif ($this->is_drupal
) {
662 // check and see if we are installed in sites/all (for D5 and above)
663 // we dont use checkURL since drupal generates an error page and throws
664 // the system for a loop on lobo's macosx box
666 $cmsPath = $config->userSystem
->cmsRootPath();
667 $userFrameworkResourceURL = $baseURL . str_replace("$cmsPath/", '',
668 str_replace('\\', '/', $civicrm_root)
671 $siteName = $config->userSystem
->parseDrupalSiteNameFromRoot($civicrm_root);
673 $civicrmDirName = trim(basename($civicrm_root));
674 $userFrameworkResourceURL = $baseURL . "sites/$siteName/modules/$civicrmDirName/";
678 $userFrameworkResourceURL = NULL;
682 'url' => CRM_Utils_File
::addTrailingSlash($userFrameworkResourceURL),
683 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
688 * Perform any post login activities required by the CMS.
690 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
691 * calls hook_user op 'login' and generates a new session.
693 * @param array $params
695 * FIXME: Document values accepted/required by $params
697 public function userLoginFinalize($params = array()) {
701 * Set timezone in mysql so that timestamp fields show the correct time.
703 public function setMySQLTimeZone() {
704 $timeZoneOffset = $this->getTimeZoneOffset();
705 if ($timeZoneOffset) {
706 $sql = "SET time_zone = '$timeZoneOffset'";
707 CRM_Core_DAO
::executequery($sql);
713 * Get timezone from CMS.
715 * @return string|false|null
717 public function getTimeZoneOffset() {
718 $timezone = $this->getTimeZoneString();
720 if ($timezone == 'UTC' ||
$timezone == 'Etc/UTC') {
721 // CRM-17072 Let's short-circuit all the zero handling & return it here!
724 $tzObj = new DateTimeZone($timezone);
725 $dateTime = new DateTime("now", $tzObj);
726 $tz = $tzObj->getOffset($dateTime);
737 $timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz / 60) %
60));
739 if ($timeZoneOffset > 0) {
740 $timeZoneOffset = '+' . $timeZoneOffset;
742 return $timeZoneOffset;
748 * Get timezone as a string.
750 * Timezone string e.g. 'America/Los_Angeles'
752 public function getTimeZoneString() {
753 return date_default_timezone_get();
757 * Get Unique Identifier from UserFramework system (CMS).
759 * @param object $user
760 * Object as described by the User Framework.
763 * Unique identifier from the user Framework system
765 public function getUniqueIdentifierFromUserObject($user) {
770 * Get User ID from UserFramework system (CMS).
772 * @param object $user
774 * Object as described by the User Framework.
777 public function getUserIDFromUserObject($user) {
782 * Get an array of user details for a contact, containing at minimum the user ID & name.
784 * @param int $contactID
787 * CMS user details including
789 * - name (ie the system user name.
791 public function getUser($contactID) {
792 $ufMatch = civicrm_api3('UFMatch', 'getsingle', array(
793 'contact_id' => $contactID,
794 'domain_id' => CRM_Core_Config
::domainID(),
797 'id' => $ufMatch['uf_id'],
798 'name' => $ufMatch['uf_name'],
803 * Get currently logged in user uf id.
806 * logged in user uf id.
808 public function getLoggedInUfID() {
813 * Get currently logged in user unique identifier - this tends to be the email address or user name.
815 * @return string|null
816 * logged in user unique identifier
818 public function getLoggedInUniqueIdentifier() {
823 * Return a UFID (user account ID from the UserFramework / CMS system.
825 * ID is based on the user object passed, defaulting to the logged in user if not passed.
827 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would
828 * seem to be resolving the user id before calling the function.
830 * Note there is already a function getUFId which takes $username as a param - we could add $user
831 * as a second param to it but it seems messy - just overloading it because the name is taken.
833 * @param object $user
836 * User ID of UF System
838 public function getBestUFID($user = NULL) {
840 return $this->getUserIDFromUserObject($user);
842 return $this->getLoggedInUfID();
846 * Return a unique identifier (usually an email address or username) from the UserFramework / CMS system.
848 * This is based on the user object passed, defaulting to the logged in user if not passed.
850 * Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would seem to be
851 * resolving the unique identifier before calling the function.
853 * @param object $user
856 * unique identifier from the UF System
858 public function getBestUFUniqueIdentifier($user = NULL) {
860 return $this->getUniqueIdentifierFromUserObject($user);
862 return $this->getLoggedInUniqueIdentifier();
866 * List modules installed in the CMS, including enabled and disabled ones.
871 public function getModules() {
876 * Get Url to view user record.
878 * @param int $contactID
881 * @return string|null
883 public function getUserRecordUrl($contactID) {
888 * Is the current user permitted to add a user.
892 public function checkPermissionAddUser() {
897 * Output code from error function.
899 * @param string $content
901 public function outputError($content) {
902 echo CRM_Utils_System
::theme($content);
908 * @param string $message
910 public function logger($message) {
914 * Append to coreResourcesList.
918 public function appendCoreResources(&$list) {
922 * @param string $name
923 * @param string $value
925 public function setHttpHeader($name, $value) {
926 header("$name: $value");
930 * Create CRM contacts for all existing CMS users
935 public function synchronizeUsers() {
936 throw new Exception('CMS user creation not supported for this framework');