3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Joomla specific stuff goes here.
21 class CRM_Utils_System_Joomla
extends CRM_Utils_System_Base
{
26 public function __construct() {
28 * deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
29 * functions and leave the codebase oblivious to the type of CMS
33 $this->is_drupal
= FALSE;
39 public function createUser(&$params, $mail) {
40 $baseDir = JPATH_SITE
;
41 require_once $baseDir . '/components/com_users/models/registration.php';
43 $userParams = JComponentHelper
::getParams('com_users');
44 $model = new UsersModelRegistration();
47 // get the default usertype
48 $userType = $userParams->get('new_usertype');
53 if (isset($params['name'])) {
54 $fullname = trim($params['name']);
56 elseif (isset($params['contactID'])) {
57 $fullname = trim(CRM_Contact_BAO_Contact
::displayName($params['contactID']));
60 $fullname = trim($params['cms_name']);
63 // Prepare the values for a new Joomla user.
65 $values['name'] = $fullname;
66 $values['username'] = trim($params['cms_name']);
67 $values['password1'] = $values['password2'] = $params['cms_pass'];
68 $values['email1'] = $values['email2'] = trim($params[$mail]);
70 $lang = JFactory
::getLanguage();
71 $lang->load('com_users', $baseDir);
73 $register = $model->register($values);
75 $ufID = JUserHelper
::getUserId($values['username']);
82 public function updateCMSName($ufID, $ufName) {
83 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
84 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
87 $user = JUser
::getInstance($ufID);
89 $values['email'] = $ufName;
96 * Check if username and email exists in the Joomla db.
98 * @param array $params
99 * Array of name and mail values.
100 * @param array $errors
102 * @param string $emailName
103 * Field label for the 'email'.
105 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
106 $config = CRM_Core_Config
::singleton();
108 $dao = new CRM_Core_DAO();
109 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
110 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
111 //don't allow the special characters and min. username length is two
112 //regex \\ to match a single backslash would become '/\\\\/'
113 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
114 if ($isNotValid ||
strlen($name) < 2) {
115 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
118 $JUserTable = &JTable
::getInstance('User', 'JTable');
120 $db = $JUserTable->getDbo();
121 $query = $db->getQuery(TRUE);
122 $query->select('username, email');
123 $query->from($JUserTable->getTableName());
125 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
126 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
127 $db->setQuery($query, 0, 10);
128 $users = $db->loadAssocList();
136 $dbName = $row['username'] ??
NULL;
137 $dbEmail = $row['email'] ??
NULL;
138 if (strtolower($dbName) == strtolower($name)) {
139 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
143 if (strtolower($dbEmail) == strtolower($email)) {
144 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL
) . 'index.php?option=com_users&view=reset';
145 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
146 [1 => $email, 2 => $resetUrl]
155 public function setTitle($title, $pageTitle = NULL) {
160 $template = CRM_Core_Smarty
::singleton();
161 $template->assign('pageTitle', $pageTitle);
163 $document = JFactory
::getDocument();
164 $document->setTitle($title);
170 public function appendBreadCrumb($breadCrumbs) {
171 $template = CRM_Core_Smarty
::singleton();
172 $bc = $template->get_template_vars('breadcrumb');
174 if (is_array($breadCrumbs)) {
175 foreach ($breadCrumbs as $crumbs) {
176 if (stripos($crumbs['url'], 'id%%')) {
177 $args = ['cid', 'mid'];
178 foreach ($args as $a) {
179 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
183 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
190 $template->assign_by_ref('breadcrumb', $bc);
196 public function resetBreadCrumb() {
202 public function addHTMLHead($string = NULL) {
204 $document = JFactory
::getDocument();
205 $document->addCustomTag($string);
212 public function addStyleUrl($url, $region) {
213 if ($region == 'html-header') {
214 $document = JFactory
::getDocument();
215 $document->addStyleSheet($url);
224 public function addStyle($code, $region) {
225 if ($region == 'html-header') {
226 $document = JFactory
::getDocument();
227 $document->addStyleDeclaration($code);
242 $forceBackend = FALSE,
245 $config = CRM_Core_Config
::singleton();
249 $path = CRM_Utils_String
::stripPathChars($path);
251 if ($config->userFrameworkFrontend
) {
252 $script = 'index.php';
254 // Get Itemid using JInput::get()
255 $input = Joomla\CMS\Factory
::getApplication()->input
;
256 $itemIdNum = $input->get("Itemid");
257 if ($itemIdNum && (strpos($path, 'civicrm/payment/ipn') === FALSE)) {
258 $Itemid = "{$separator}Itemid=" . $itemIdNum;
262 if (isset($fragment)) {
263 $fragment = '#' . $fragment;
266 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
268 if (!empty($query)) {
269 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
272 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
275 // gross hack for joomla, we are in the backend and want to send a frontend url
276 if ($frontend && $config->userFramework
== 'Joomla') {
277 // handle both joomla v1.5 and v1.6, CRM-7939
278 $url = str_replace('/administrator/index2.php', '/index.php', $url);
279 $url = str_replace('/administrator/index.php', '/index.php', $url);
282 $url = str_replace('/administrator/', '/index.php', $url);
284 elseif ($forceBackend) {
285 if (defined('JVERSION')) {
286 $joomlaVersion = JVERSION
;
289 $jversion = new JVersion();
290 $joomlaVersion = $jversion->getShortVersion();
293 if (version_compare($joomlaVersion, '1.6') >= 0) {
294 $url = str_replace('/index.php', '/administrator/index.php', $url);
301 * Set the email address of the user.
303 * @param object $user
304 * Handle to the user object.
306 public function setEmail(&$user) {
308 $query = $db->getQuery(TRUE);
309 $query->select($db->quoteName('email'))
310 ->from($db->quoteName('#__users'))
311 ->where($db->quoteName('id') . ' = ' . $user->id
);
312 $database->setQuery($query);
313 $user->email
= $database->loadResult();
319 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
320 require_once 'DB.php';
322 $config = CRM_Core_Config
::singleton();
325 if ($loadCMSBootstrap) {
326 $bootStrapParams = [];
327 if ($name && $password) {
333 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
336 jimport('joomla.application.component.helper');
337 jimport('joomla.database.table');
338 jimport('joomla.user.helper');
340 $JUserTable = JTable
::getInstance('User', 'JTable');
342 $db = $JUserTable->getDbo();
343 $query = $db->getQuery(TRUE);
344 $query->select('id, name, username, email, password');
345 $query->from($JUserTable->getTableName());
346 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
347 $db->setQuery($query, 0, 0);
348 $users = $db->loadObjectList();
355 $joomlaBase = self
::getBasePath();
356 self
::getJVersion($joomlaBase);
359 $dbPassword = $row->password
;
361 $dbEmail = $row->email
;
363 if (version_compare(JVERSION
, '2.5.18', 'lt') ||
364 (version_compare(JVERSION
, '3.0', 'ge') && version_compare(JVERSION
, '3.2.1', 'lt'))
366 // now check password
367 list($hash, $salt) = explode(':', $dbPassword);
368 $cryptpass = md5($password . $salt);
369 if ($hash != $cryptpass) {
374 if (!JUserHelper
::verifyPassword($password, $dbPassword, $dbId)) {
378 if (version_compare(JVERSION
, '3.8.0', 'ge')) {
379 jimport('joomla.application.helper');
380 jimport('joomla.application.cms');
381 jimport('joomla.application.administrator');
383 //include additional files required by Joomla 3.2.1+
384 elseif (version_compare(JVERSION
, '3.2.1', 'ge')) {
385 require_once $joomlaBase . '/libraries/cms/application/helper.php';
386 require_once $joomlaBase . '/libraries/cms/application/cms.php';
387 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
391 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
392 $contactID = CRM_Core_BAO_UFMatch
::getContactId($dbId);
396 return [$contactID, $dbId, mt_rand()];
403 * Set a init session with user object.
406 * Array with user specific data.
408 public function setUserSession($data) {
409 list($userID, $ufID) = $data;
410 $user = new JUser($ufID);
411 $session = JFactory
::getSession();
412 $session->set('user', $user);
414 parent
::setUserSession($data);
418 * FIXME: Do something
420 * @param string $message
422 public function setMessage($message) {
426 * @param \string $username
427 * @param \string $password
431 public function loadUser($username, $password = NULL) {
432 $uid = JUserHelper
::getUserId($username);
436 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
437 if (!empty($password)) {
438 $instance = JFactory
::getApplication('site');
440 'username' => $username,
441 'password' => $password,
443 //perform the login action
444 $instance->login($params);
447 // Save details in Joomla session
448 $user = JFactory
::getUser($uid);
449 $jsession = JFactory
::getSession();
450 $jsession->set('user', $user);
452 // Save details in Civi session
453 $session = CRM_Core_Session
::singleton();
454 $session->set('ufID', $uid);
455 $session->set('userID', $contactID);
460 * FIXME: Use CMS-native approach
461 * @throws \CRM_Core_Exception.
463 public function permissionDenied() {
464 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
470 public function logout() {
472 CRM_Utils_System
::setHttpHeader("Location", "index.php");
478 public function getUFLocale() {
479 if (defined('_JEXEC')) {
480 $conf = JFactory
::getConfig();
481 $locale = $conf->get('language');
482 return str_replace('-', '_', $locale);
490 public function setUFLocale($civicrm_language) {
498 public function getVersion() {
499 if (class_exists('JVersion')) {
500 $version = new JVersion();
501 return $version->getShortVersion();
508 public function getJVersion($joomlaBase) {
509 // Files may be in different places depending on Joomla version
510 if (!defined('JVERSION')) {
512 $versionPhp = $joomlaBase . '/libraries/src/Version.php';
513 if (!file_exists($versionPhp)) {
515 $versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
518 $jversion = new JVersion();
519 define('JVERSION', $jversion->getShortVersion());
524 * Setup the base path related constant.
527 public function getBasePath() {
528 global $civicrm_root;
529 $joomlaPath = explode(DIRECTORY_SEPARATOR
. 'administrator', $civicrm_root);
530 $joomlaBase = $joomlaPath[0];
535 * Load joomla bootstrap.
537 * @param array $params
538 * with uid or name and password.
539 * @param bool $loadUser
541 * @param bool|\throw $throwError throw error on failure?
542 * @param null $realPath
543 * @param bool $loadDefines
547 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
548 $joomlaBase = self
::getBasePath();
550 // load BootStrap here if needed
551 // We are a valid Joomla entry point.
552 // dev/core#1384 Use DS to ensure a correct JPATH_BASE in Windows
553 if (!defined('_JEXEC') && $loadDefines) {
555 define('DS', DIRECTORY_SEPARATOR
);
556 define('JPATH_BASE', $joomlaBase . DS
. 'administrator');
557 require $joomlaBase . '/administrator/includes/defines.php';
560 // Get the framework.
561 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
562 require $joomlaBase . '/libraries/import.legacy.php';
564 require $joomlaBase . '/libraries/cms.php';
565 self
::getJVersion($joomlaBase);
567 if (version_compare(JVERSION
, '3.8', 'lt')) {
568 require $joomlaBase . '/libraries/import.php';
569 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
572 require_once $joomlaBase . '/configuration.php';
574 if (version_compare(JVERSION
, '3.0', 'lt')) {
575 require $joomlaBase . '/libraries/joomla/environment/uri.php';
576 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
578 elseif (version_compare(JVERSION
, '3.8', 'lt')) {
579 jimport('joomla.environment.uri');
582 if (version_compare(JVERSION
, '3.8', 'lt')) {
583 jimport('joomla.application.cli');
586 if (!defined('JDEBUG')) {
587 define('JDEBUG', FALSE);
590 // Set timezone for Joomla on Cron
591 $config = JFactory
::getConfig();
592 $timezone = $config->get('offset');
594 date_default_timezone_set($timezone);
595 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
598 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
599 $config = CRM_Core_Config
::singleton();
600 CRM_Utils_Hook
::config($config);
608 public function isUserLoggedIn() {
609 $user = JFactory
::getUser();
610 return !$user->guest
;
616 public function isUserRegistrationPermitted() {
617 $userParams = JComponentHelper
::getParams('com_users');
618 if (!$userParams->get('allowUserRegistration')) {
627 public function isPasswordUserGenerated() {
634 public function getLoggedInUfID() {
635 $user = JFactory
::getUser();
636 return ($user->guest
) ?
NULL : $user->id
;
642 public function getLoggedInUniqueIdentifier() {
643 $user = JFactory
::getUser();
644 return $this->getUniqueIdentifierFromUserObject($user);
650 public function getUser($contactID) {
651 $user_details = parent
::getUser($contactID);
652 $user = JFactory
::getUser($user_details['id']);
653 $user_details['name'] = $user->name
;
654 return $user_details;
660 public function getUserIDFromUserObject($user) {
661 return !empty($user->id
) ?
$user->id
: NULL;
667 public function getUniqueIdentifierFromUserObject($user) {
668 return ($user->guest
) ?
NULL : $user->email
;
674 public function getTimeZoneString() {
675 $timezone = JFactory
::getConfig()->get('offset');
676 return !$timezone ?
date_default_timezone_get() : $timezone;
680 * Get a list of all installed modules, including enabled and disabled ones
685 public function getModules() {
688 $db = JFactory
::getDbo();
689 $query = $db->getQuery(TRUE);
690 $query->select('type, folder, element, enabled')
691 ->from('#__extensions')
692 ->where('type =' . $db->Quote('plugin'));
693 $plugins = $db->setQuery($query)->loadAssocList();
694 foreach ($plugins as $plugin) {
695 // question: is the folder really a critical part of the plugin's name?
696 $name = implode('.', ['joomla', $plugin['type'], $plugin['folder'], $plugin['element']]);
697 $result[] = new CRM_Core_Module($name, !empty($plugin['enabled']));
706 public function getLoginURL($destination = '') {
707 $config = CRM_Core_Config
::singleton();
708 $loginURL = $config->userFrameworkBaseURL
;
709 $loginURL = str_replace('administrator/', '', $loginURL);
710 $loginURL .= 'index.php?option=com_users&view=login';
712 //CRM-14872 append destination
713 if (!empty($destination)) {
714 $loginURL .= '&return=' . urlencode(base64_encode($destination));
722 public function getLoginDestination(&$form) {
725 $id = $form->get('id');
730 $gid = $form->get('gid');
732 $args .= "&gid=$gid";
735 // Setup Personal Campaign Page link uses pageId
736 $pageId = $form->get('pageId');
738 $component = $form->get('component');
739 $args .= "&pageId=$pageId&component=$component&action=add";
746 // append destination so user is returned to form they came from after login
747 $args = 'reset=1' . $args;
748 $destination = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
755 * Determine the location of the CMS root.
757 * @return string|NULL
758 * local file system path to CMS root, or NULL if it cannot be determined
760 public function cmsRootPath() {
761 global $civicrm_paths;
762 if (!empty($civicrm_paths['cms.root']['path'])) {
763 return $civicrm_paths['cms.root']['path'];
766 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
767 if (file_exists("$siteRoot/administrator/index.php")) {
776 public function getDefaultSiteSettings($dir = NULL) {
777 $config = CRM_Core_Config
::singleton();
781 $config->userFrameworkBaseURL
783 // CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
784 // This is the original pattern, but it doesn't work under Windows.
785 // By setting the pattern to the one used before the change first and only
786 // changing it means that the change code only affects Windows users.
787 $pattern = '|/media/civicrm/.*$|';
788 if (DIRECTORY_SEPARATOR
== '\\') {
789 // This regular expression will handle Windows as well as Linux
790 // and any combination of forward and back slashes in directory
791 // separators. We only apply it if the directory separator is the one
793 $pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
795 $siteRoot = preg_replace(
798 $config->imageUploadDir
800 return [$url, NULL, $siteRoot];
806 public function getUserRecordUrl($contactID) {
807 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
808 $userRecordUrl = NULL;
809 // if logged in user has user edit access, then allow link to other users joomla profile
810 if (JFactory
::getUser()->authorise('core.edit', 'com_users')) {
811 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
813 elseif (CRM_Core_Session
::singleton()->get('userID') == $contactID) {
814 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
821 public function checkPermissionAddUser() {
822 if (JFactory
::getUser()->authorise('core.create', 'com_users')) {
830 public function synchronizeUsers() {
831 $config = CRM_Core_Config
::singleton();
832 if (PHP_SAPI
!= 'cli') {
839 $JUserTable = &JTable
::getInstance('User', 'JTable');
841 $db = $JUserTable->getDbo();
842 $query = $db->getQuery(TRUE);
843 $query->select($id . ', ' . $mail . ', ' . $name);
844 $query->from($JUserTable->getTableName());
845 $query->where($mail != '');
847 $db->setQuery($query);
848 $users = $db->loadObjectList();
850 $user = new StdClass();
851 $uf = $config->userFramework
;
854 $contactMatching = 0;
855 for ($i = 0; $i < count($users); $i++
) {
856 $user->$id = $users[$i]->$id;
857 $user->$mail = $users[$i]->$mail;
858 $user->$name = $users[$i]->$name;
860 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user,
877 'contactCount' => $contactCount,
878 'contactMatching' => $contactMatching,
879 'contactCreated' => $contactCreated,
884 * Determine the location of the CiviCRM source tree.
887 * 1. This was pulled out from a bigger function. It should be split
888 * into even smaller pieces and marked abstract.
889 * 2. This would be easier to compute by a calling a CMS API, but
890 * for whatever reason we take the hard way.
893 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
894 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
896 public function getCiviSourceStorage() {
897 global $civicrm_root;
898 if (!defined('CIVICRM_UF_BASEURL')) {
899 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
901 $baseURL = CRM_Utils_File
::addTrailingSlash(CIVICRM_UF_BASEURL
, '/');
902 if (CRM_Utils_System
::isSSL()) {
903 $baseURL = str_replace('http://', 'https://', $baseURL);
906 // For Joomla CiviCRM Core files always live within the admistrator folder and $base_url is different on the frontend compared to the backend.
907 if (strpos($baseURL, 'administrator') === FALSE) {
908 $userFrameworkResourceURL = $baseURL . "administrator/components/com_civicrm/civicrm/";
911 $userFrameworkResourceURL = $baseURL . "components/com_civicrm/civicrm/";
915 'url' => CRM_Utils_File
::addTrailingSlash($userFrameworkResourceURL, '/'),
916 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),