966d28f4a90c7e7c2b47b5bdb5dff421d932cf6b
3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * Joomla specific stuff goes here.
37 class CRM_Utils_System_Joomla
extends CRM_Utils_System_Base
{
42 public function __construct() {
44 * 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
45 * functions and leave the codebase oblivious to the type of CMS
49 $this->is_drupal
= FALSE;
55 public function createUser(&$params, $mail) {
56 $baseDir = JPATH_SITE
;
57 require_once $baseDir . '/components/com_users/models/registration.php';
59 $userParams = JComponentHelper
::getParams('com_users');
60 $model = new UsersModelRegistration();
63 // get the default usertype
64 $userType = $userParams->get('new_usertype');
69 if (isset($params['name'])) {
70 $fullname = trim($params['name']);
72 elseif (isset($params['contactID'])) {
73 $fullname = trim(CRM_Contact_BAO_Contact
::displayName($params['contactID']));
76 $fullname = trim($params['cms_name']);
79 // Prepare the values for a new Joomla user.
81 $values['name'] = $fullname;
82 $values['username'] = trim($params['cms_name']);
83 $values['password1'] = $values['password2'] = $params['cms_pass'];
84 $values['email1'] = $values['email2'] = trim($params[$mail]);
86 $lang = JFactory
::getLanguage();
87 $lang->load('com_users', $baseDir);
89 $register = $model->register($values);
91 $ufID = JUserHelper
::getUserId($values['username']);
98 public function updateCMSName($ufID, $ufName) {
99 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
100 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
103 $user = JUser
::getInstance($ufID);
105 $values['email'] = $ufName;
106 $user->bind($values);
112 * Check if username and email exists in the Joomla db.
114 * @param array $params
115 * Array of name and mail values.
116 * @param array $errors
118 * @param string $emailName
119 * Field label for the 'email'.
121 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
122 $config = CRM_Core_Config
::singleton();
124 $dao = new CRM_Core_DAO();
125 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
126 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
127 //don't allow the special characters and min. username length is two
128 //regex \\ to match a single backslash would become '/\\\\/'
129 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
130 if ($isNotValid ||
strlen($name) < 2) {
131 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
134 $JUserTable = &JTable
::getInstance('User', 'JTable');
136 $db = $JUserTable->getDbo();
137 $query = $db->getQuery(TRUE);
138 $query->select('username, email');
139 $query->from($JUserTable->getTableName());
141 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
142 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
143 $db->setQuery($query, 0, 10);
144 $users = $db->loadAssocList();
152 $dbName = CRM_Utils_Array
::value('username', $row);
153 $dbEmail = CRM_Utils_Array
::value('email', $row);
154 if (strtolower($dbName) == strtolower($name)) {
155 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
159 if (strtolower($dbEmail) == strtolower($email)) {
160 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL
) . 'index.php?option=com_users&view=reset';
161 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
162 [1 => $email, 2 => $resetUrl]
171 public function setTitle($title, $pageTitle = NULL) {
176 $template = CRM_Core_Smarty
::singleton();
177 $template->assign('pageTitle', $pageTitle);
179 $document = JFactory
::getDocument();
180 $document->setTitle($title);
186 public function appendBreadCrumb($breadCrumbs) {
187 $template = CRM_Core_Smarty
::singleton();
188 $bc = $template->get_template_vars('breadcrumb');
190 if (is_array($breadCrumbs)) {
191 foreach ($breadCrumbs as $crumbs) {
192 if (stripos($crumbs['url'], 'id%%')) {
193 $args = ['cid', 'mid'];
194 foreach ($args as $a) {
195 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
199 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
206 $template->assign_by_ref('breadcrumb', $bc);
212 public function resetBreadCrumb() {
218 public function addHTMLHead($string = NULL) {
220 $document = JFactory
::getDocument();
221 $document->addCustomTag($string);
228 public function addStyleUrl($url, $region) {
229 if ($region == 'html-header') {
230 $document = JFactory
::getDocument();
231 $document->addStyleSheet($url);
240 public function addStyle($code, $region) {
241 if ($region == 'html-header') {
242 $document = JFactory
::getDocument();
243 $document->addStyleDeclaration($code);
258 $forceBackend = FALSE
260 $config = CRM_Core_Config
::singleton();
264 $path = CRM_Utils_String
::stripPathChars($path);
266 if ($config->userFrameworkFrontend
) {
267 $script = 'index.php';
269 // Get Itemid using JInput::get()
270 $input = Joomla\CMS\Factory
::getApplication()->input
;
271 $itemIdNum = $input->get("Itemid");
272 if ($itemIdNum && (strpos($path, 'civicrm/payment/ipn') === FALSE)) {
273 $Itemid = "{$separator}Itemid=" . $itemIdNum;
277 if (isset($fragment)) {
278 $fragment = '#' . $fragment;
281 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
283 if (!empty($query)) {
284 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
287 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
290 // gross hack for joomla, we are in the backend and want to send a frontend url
291 if ($frontend && $config->userFramework
== 'Joomla') {
292 // handle both joomla v1.5 and v1.6, CRM-7939
293 $url = str_replace('/administrator/index2.php', '/index.php', $url);
294 $url = str_replace('/administrator/index.php', '/index.php', $url);
297 $url = str_replace('/administrator/', '/index.php', $url);
299 elseif ($forceBackend) {
300 if (defined('JVERSION')) {
301 $joomlaVersion = JVERSION
;
304 $jversion = new JVersion();
305 $joomlaVersion = $jversion->getShortVersion();
308 if (version_compare($joomlaVersion, '1.6') >= 0) {
309 $url = str_replace('/index.php', '/administrator/index.php', $url);
316 * Set the email address of the user.
318 * @param object $user
319 * Handle to the user object.
321 public function setEmail(&$user) {
323 $query = $db->getQuery(TRUE);
324 $query->select($db->quoteName('email'))
325 ->from($db->quoteName('#__users'))
326 ->where($db->quoteName('id') . ' = ' . $user->id
);
327 $database->setQuery($query);
328 $user->email
= $database->loadResult();
334 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
335 require_once 'DB.php';
337 $config = CRM_Core_Config
::singleton();
340 if ($loadCMSBootstrap) {
341 $bootStrapParams = [];
342 if ($name && $password) {
348 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
351 jimport('joomla.application.component.helper');
352 jimport('joomla.database.table');
353 jimport('joomla.user.helper');
355 $JUserTable = JTable
::getInstance('User', 'JTable');
357 $db = $JUserTable->getDbo();
358 $query = $db->getQuery(TRUE);
359 $query->select('id, name, username, email, password');
360 $query->from($JUserTable->getTableName());
361 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
362 $db->setQuery($query, 0, 0);
363 $users = $db->loadObjectList();
370 $joomlaBase = self
::getBasePath();
371 self
::getJVersion($joomlaBase);
374 $dbPassword = $row->password
;
376 $dbEmail = $row->email
;
378 if (version_compare(JVERSION
, '2.5.18', 'lt') ||
379 (version_compare(JVERSION
, '3.0', 'ge') && version_compare(JVERSION
, '3.2.1', 'lt'))
381 // now check password
382 list($hash, $salt) = explode(':', $dbPassword);
383 $cryptpass = md5($password . $salt);
384 if ($hash != $cryptpass) {
389 if (!JUserHelper
::verifyPassword($password, $dbPassword, $dbId)) {
393 if (version_compare(JVERSION
, '3.8.0', 'ge')) {
394 jimport('joomla.application.helper');
395 jimport('joomla.application.cms');
396 jimport('joomla.application.administrator');
398 //include additional files required by Joomla 3.2.1+
399 elseif (version_compare(JVERSION
, '3.2.1', 'ge')) {
400 require_once $joomlaBase . '/libraries/cms/application/helper.php';
401 require_once $joomlaBase . '/libraries/cms/application/cms.php';
402 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
406 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
407 $contactID = CRM_Core_BAO_UFMatch
::getContactId($dbId);
411 return [$contactID, $dbId, mt_rand()];
418 * Set a init session with user object.
421 * Array with user specific data.
423 public function setUserSession($data) {
424 list($userID, $ufID) = $data;
425 $user = new JUser($ufID);
426 $session = JFactory
::getSession();
427 $session->set('user', $user);
429 parent
::setUserSession($data);
433 * FIXME: Do something
435 * @param string $message
437 public function setMessage($message) {
441 * @param \string $username
442 * @param \string $password
446 public function loadUser($username, $password = NULL) {
447 $uid = JUserHelper
::getUserId($username);
451 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
452 if (!empty($password)) {
453 $instance = JFactory
::getApplication('site');
455 'username' => $username,
456 'password' => $password,
458 //perform the login action
459 $instance->login($params);
462 // Save details in Joomla session
463 $user = JFactory
::getUser($uid);
464 $jsession = JFactory
::getSession();
465 $jsession->set('user', $user);
467 // Save details in Civi session
468 $session = CRM_Core_Session
::singleton();
469 $session->set('ufID', $uid);
470 $session->set('userID', $contactID);
475 * FIXME: Use CMS-native approach
477 public function permissionDenied() {
478 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
484 public function logout() {
486 CRM_Utils_System
::setHttpHeader("Location", "index.php");
492 public function getUFLocale() {
493 if (defined('_JEXEC')) {
494 $conf = JFactory
::getConfig();
495 $locale = $conf->get('language');
496 return str_replace('-', '_', $locale);
504 public function setUFLocale($civicrm_language) {
512 public function getVersion() {
513 if (class_exists('JVersion')) {
514 $version = new JVersion();
515 return $version->getShortVersion();
522 public function getJVersion($joomlaBase) {
523 // Files may be in different places depending on Joomla version
524 if (!defined('JVERSION')) {
526 $versionPhp = $joomlaBase . '/libraries/src/Version.php';
527 if (!file_exists($versionPhp)) {
529 $versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
532 $jversion = new JVersion();
533 define('JVERSION', $jversion->getShortVersion());
538 * Setup the base path related constant.
541 public function getBasePath() {
542 global $civicrm_root;
543 $joomlaPath = explode(DIRECTORY_SEPARATOR
. 'administrator', $civicrm_root);
544 $joomlaBase = $joomlaPath[0];
549 * Load joomla bootstrap.
551 * @param array $params
552 * with uid or name and password.
553 * @param bool $loadUser
555 * @param bool|\throw $throwError throw error on failure?
556 * @param null $realPath
557 * @param bool $loadDefines
561 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
562 $joomlaBase = self
::getBasePath();
564 // load BootStrap here if needed
565 // We are a valid Joomla entry point.
566 if (!defined('_JEXEC') && $loadDefines) {
568 define('DS', DIRECTORY_SEPARATOR
);
569 define('JPATH_BASE', $joomlaBase . '/administrator');
570 require $joomlaBase . '/administrator/includes/defines.php';
573 // Get the framework.
574 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
575 require $joomlaBase . '/libraries/import.legacy.php';
577 require $joomlaBase . '/libraries/cms.php';
578 self
::getJVersion($joomlaBase);
580 if (version_compare(JVERSION
, '3.8', 'lt')) {
581 require $joomlaBase . '/libraries/import.php';
582 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
585 require_once $joomlaBase . '/configuration.php';
587 if (version_compare(JVERSION
, '3.0', 'lt')) {
588 require $joomlaBase . '/libraries/joomla/environment/uri.php';
589 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
591 elseif (version_compare(JVERSION
, '3.8', 'lt')) {
592 jimport('joomla.environment.uri');
595 if (version_compare(JVERSION
, '3.8', 'lt')) {
596 jimport('joomla.application.cli');
599 if (!defined('JDEBUG')) {
600 define('JDEBUG', FALSE);
603 // Set timezone for Joomla on Cron
604 $config = JFactory
::getConfig();
605 $timezone = $config->get('offset');
607 date_default_timezone_set($timezone);
608 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
611 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
612 $config = CRM_Core_Config
::singleton();
613 CRM_Utils_Hook
::config($config);
621 public function isUserLoggedIn() {
622 $user = JFactory
::getUser();
623 return ($user->guest
) ?
FALSE : TRUE;
629 public function isUserRegistrationPermitted() {
630 $userParams = JComponentHelper
::getParams('com_users');
631 if (!$userParams->get('allowUserRegistration')) {
640 public function isPasswordUserGenerated() {
647 public function getLoggedInUfID() {
648 $user = JFactory
::getUser();
649 return ($user->guest
) ?
NULL : $user->id
;
655 public function getLoggedInUniqueIdentifier() {
656 $user = JFactory
::getUser();
657 return $this->getUniqueIdentifierFromUserObject($user);
663 public function getUser($contactID) {
664 $user_details = parent
::getUser($contactID);
665 $user = JFactory
::getUser($user_details['id']);
666 $user_details['name'] = $user->name
;
667 return $user_details;
673 public function getUserIDFromUserObject($user) {
674 return !empty($user->id
) ?
$user->id
: NULL;
680 public function getUniqueIdentifierFromUserObject($user) {
681 return ($user->guest
) ?
NULL : $user->email
;
687 public function getTimeZoneString() {
688 $timezone = JFactory
::getConfig()->get('offset');
689 return !$timezone ?
date_default_timezone_get() : $timezone;
693 * Get a list of all installed modules, including enabled and disabled ones
698 public function getModules() {
701 $db = JFactory
::getDbo();
702 $query = $db->getQuery(TRUE);
703 $query->select('type, folder, element, enabled')
704 ->from('#__extensions')
705 ->where('type =' . $db->Quote('plugin'));
706 $plugins = $db->setQuery($query)->loadAssocList();
707 foreach ($plugins as $plugin) {
708 // question: is the folder really a critical part of the plugin's name?
709 $name = implode('.', ['joomla', $plugin['type'], $plugin['folder'], $plugin['element']]);
710 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ?
TRUE : FALSE);
719 public function getLoginURL($destination = '') {
720 $config = CRM_Core_Config
::singleton();
721 $loginURL = $config->userFrameworkBaseURL
;
722 $loginURL = str_replace('administrator/', '', $loginURL);
723 $loginURL .= 'index.php?option=com_users&view=login';
725 //CRM-14872 append destination
726 if (!empty($destination)) {
727 $loginURL .= '&return=' . urlencode(base64_encode($destination));
735 public function getLoginDestination(&$form) {
738 $id = $form->get('id');
743 $gid = $form->get('gid');
745 $args .= "&gid=$gid";
748 // Setup Personal Campaign Page link uses pageId
749 $pageId = $form->get('pageId');
751 $component = $form->get('component');
752 $args .= "&pageId=$pageId&component=$component&action=add";
759 // append destination so user is returned to form they came from after login
760 $args = 'reset=1' . $args;
761 $destination = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
768 * Determine the location of the CMS root.
770 * @return string|NULL
771 * local file system path to CMS root, or NULL if it cannot be determined
773 public function cmsRootPath() {
774 global $civicrm_paths;
775 if (!empty($civicrm_paths['cms.root']['path'])) {
776 return $civicrm_paths['cms.root']['path'];
779 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
780 if (file_exists("$siteRoot/administrator/index.php")) {
789 public function getDefaultSiteSettings($dir = NULL) {
790 $config = CRM_Core_Config
::singleton();
794 $config->userFrameworkBaseURL
796 // CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
797 // This is the original pattern, but it doesn't work under Windows.
798 // By setting the pattern to the one used before the change first and only
799 // changing it means that the change code only affects Windows users.
800 $pattern = '|/media/civicrm/.*$|';
801 if (DIRECTORY_SEPARATOR
== '\\') {
802 // This regular expression will handle Windows as well as Linux
803 // and any combination of forward and back slashes in directory
804 // separators. We only apply it if the directory separator is the one
806 $pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
808 $siteRoot = preg_replace(
811 $config->imageUploadDir
813 return [$url, NULL, $siteRoot];
819 public function getUserRecordUrl($contactID) {
820 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
821 $userRecordUrl = NULL;
822 // if logged in user has user edit access, then allow link to other users joomla profile
823 if (JFactory
::getUser()->authorise('core.edit', 'com_users')) {
824 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
826 elseif (CRM_Core_Session
::singleton()->get('userID') == $contactID) {
827 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
834 public function checkPermissionAddUser() {
835 if (JFactory
::getUser()->authorise('core.create', 'com_users')) {
841 * Output code from error function.
842 * @param string $content
844 public function outputError($content) {
845 if (class_exists('JErrorPage')) {
846 $error = new Exception($content);
847 JErrorPage
::render($error);
849 elseif (class_exists('JError')) {
850 JError
::raiseError('CiviCRM-001', $content);
853 parent
::outputError($content);
860 public function synchronizeUsers() {
861 $config = CRM_Core_Config
::singleton();
862 if (PHP_SAPI
!= 'cli') {
869 $JUserTable = &JTable
::getInstance('User', 'JTable');
871 $db = $JUserTable->getDbo();
872 $query = $db->getQuery(TRUE);
873 $query->select($id . ', ' . $mail . ', ' . $name);
874 $query->from($JUserTable->getTableName());
875 $query->where($mail != '');
877 $db->setQuery($query);
878 $users = $db->loadObjectList();
880 $user = new StdClass();
881 $uf = $config->userFramework
;
884 $contactMatching = 0;
885 for ($i = 0; $i < count($users); $i++
) {
886 $user->$id = $users[$i]->$id;
887 $user->$mail = $users[$i]->$mail;
888 $user->$name = $users[$i]->$name;
890 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user,
907 'contactCount' => $contactCount,
908 'contactMatching' => $contactMatching,
909 'contactCreated' => $contactCreated,