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
{
41 public function __construct() {
43 * 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
44 * functions and leave the codebase oblivious to the type of CMS
48 $this->is_drupal
= FALSE;
54 public function createUser(&$params, $mail) {
55 $baseDir = JPATH_SITE
;
56 require_once $baseDir . '/components/com_users/models/registration.php';
58 $userParams = JComponentHelper
::getParams('com_users');
59 $model = new UsersModelRegistration();
62 // get the default usertype
63 $userType = $userParams->get('new_usertype');
68 if (isset($params['name'])) {
69 $fullname = trim($params['name']);
71 elseif (isset($params['contactID'])) {
72 $fullname = trim(CRM_Contact_BAO_Contact
::displayName($params['contactID']));
75 $fullname = trim($params['cms_name']);
78 // Prepare the values for a new Joomla user.
80 $values['name'] = $fullname;
81 $values['username'] = trim($params['cms_name']);
82 $values['password1'] = $values['password2'] = $params['cms_pass'];
83 $values['email1'] = $values['email2'] = trim($params[$mail]);
85 $lang = JFactory
::getLanguage();
86 $lang->load('com_users', $baseDir);
88 $register = $model->register($values);
90 $ufID = JUserHelper
::getUserId($values['username']);
97 public function updateCMSName($ufID, $ufName) {
98 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
99 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
102 $user = JUser
::getInstance($ufID);
104 $values['email'] = $ufName;
105 $user->bind($values);
111 * Check if username and email exists in the Joomla db.
113 * @param array $params
114 * Array of name and mail values.
115 * @param array $errors
117 * @param string $emailName
118 * Field label for the 'email'.
120 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
121 $config = CRM_Core_Config
::singleton();
123 $dao = new CRM_Core_DAO();
124 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
125 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
126 //don't allow the special characters and min. username length is two
127 //regex \\ to match a single backslash would become '/\\\\/'
128 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
129 if ($isNotValid ||
strlen($name) < 2) {
130 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
133 $JUserTable = &JTable
::getInstance('User', 'JTable');
135 $db = $JUserTable->getDbo();
136 $query = $db->getQuery(TRUE);
137 $query->select('username, email');
138 $query->from($JUserTable->getTableName());
140 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
141 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
142 $db->setQuery($query, 0, 10);
143 $users = $db->loadAssocList();
151 $dbName = CRM_Utils_Array
::value('username', $row);
152 $dbEmail = CRM_Utils_Array
::value('email', $row);
153 if (strtolower($dbName) == strtolower($name)) {
154 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
158 if (strtolower($dbEmail) == strtolower($email)) {
159 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL
) . 'index.php?option=com_users&view=reset';
160 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
161 array(1 => $email, 2 => $resetUrl)
170 public function setTitle($title, $pageTitle = NULL) {
175 $template = CRM_Core_Smarty
::singleton();
176 $template->assign('pageTitle', $pageTitle);
178 $document = JFactory
::getDocument();
179 $document->setTitle($title);
185 public function appendBreadCrumb($breadCrumbs) {
186 $template = CRM_Core_Smarty
::singleton();
187 $bc = $template->get_template_vars('breadcrumb');
189 if (is_array($breadCrumbs)) {
190 foreach ($breadCrumbs as $crumbs) {
191 if (stripos($crumbs['url'], 'id%%')) {
192 $args = array('cid', 'mid');
193 foreach ($args as $a) {
194 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
198 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
205 $template->assign_by_ref('breadcrumb', $bc);
211 public function resetBreadCrumb() {
217 public function addHTMLHead($string = NULL) {
219 $document = JFactory
::getDocument();
220 $document->addCustomTag($string);
227 public function addStyleUrl($url, $region) {
228 if ($region == 'html-header') {
229 $document = JFactory
::getDocument();
230 $document->addStyleSheet($url);
239 public function addStyle($code, $region) {
240 if ($region == 'html-header') {
241 $document = JFactory
::getDocument();
242 $document->addStyleDeclaration($code);
257 $forceBackend = FALSE
259 $config = CRM_Core_Config
::singleton();
263 $path = CRM_Utils_String
::stripPathChars($path);
265 if ($config->userFrameworkFrontend
) {
266 $script = 'index.php';
267 if (JRequest
::getVar("Itemid") && (strpos($path, 'civicrm/payment/ipn') === FALSE)) {
268 $Itemid = "{$separator}Itemid=" . JRequest
::getVar("Itemid");
272 if (isset($fragment)) {
273 $fragment = '#' . $fragment;
276 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
278 if (!empty($query)) {
279 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
282 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
285 // gross hack for joomla, we are in the backend and want to send a frontend url
286 if ($frontend && $config->userFramework
== 'Joomla') {
287 // handle both joomla v1.5 and v1.6, CRM-7939
288 $url = str_replace('/administrator/index2.php', '/index.php', $url);
289 $url = str_replace('/administrator/index.php', '/index.php', $url);
292 $url = str_replace('/administrator/', '/index.php', $url);
294 elseif ($forceBackend) {
295 if (defined('JVERSION')) {
296 $joomlaVersion = JVERSION
;
299 $jversion = new JVersion();
300 $joomlaVersion = $jversion->getShortVersion();
303 if (version_compare($joomlaVersion, '1.6') >= 0) {
304 $url = str_replace('/index.php', '/administrator/index.php', $url);
311 * Set the email address of the user.
313 * @param object $user
314 * Handle to the user object.
316 public function setEmail(&$user) {
318 $query = $db->getQuery(TRUE);
319 $query->select($db->quoteName('email'))
320 ->from($db->quoteName('#__users'))
321 ->where($db->quoteName('id') . ' = ' . $user->id
);
322 $database->setQuery($query);
323 $user->email
= $database->loadResult();
329 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
330 require_once 'DB.php';
332 $config = CRM_Core_Config
::singleton();
335 if ($loadCMSBootstrap) {
336 $bootStrapParams = array();
337 if ($name && $password) {
338 $bootStrapParams = array(
343 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
346 jimport('joomla.application.component.helper');
347 jimport('joomla.database.table');
348 jimport('joomla.user.helper');
350 $JUserTable = JTable
::getInstance('User', 'JTable');
352 $db = $JUserTable->getDbo();
353 $query = $db->getQuery(TRUE);
354 $query->select('id, name, username, email, password');
355 $query->from($JUserTable->getTableName());
356 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
357 $db->setQuery($query, 0, 0);
358 $users = $db->loadObjectList();
365 $joomlaBase = self
::getBasePath();
366 self
::getJVersion($joomlaBase);
369 $dbPassword = $row->password
;
371 $dbEmail = $row->email
;
373 if (version_compare(JVERSION
, '2.5.18', 'lt') ||
374 (version_compare(JVERSION
, '3.0', 'ge') && version_compare(JVERSION
, '3.2.1', 'lt'))
376 // now check password
377 list($hash, $salt) = explode(':', $dbPassword);
378 $cryptpass = md5($password . $salt);
379 if ($hash != $cryptpass) {
384 if (!JUserHelper
::verifyPassword($password, $dbPassword, $dbId)) {
388 if (version_compare(JVERSION
, '3.8.0', 'ge')) {
389 jimport('joomla.application.helper');
390 jimport('joomla.application.cms');
391 jimport('joomla.application.administrator');
393 //include additional files required by Joomla 3.2.1+
394 elseif (version_compare(JVERSION
, '3.2.1', 'ge')) {
395 require_once $joomlaBase . '/libraries/cms/application/helper.php';
396 require_once $joomlaBase . '/libraries/cms/application/cms.php';
397 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
401 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
402 $contactID = CRM_Core_BAO_UFMatch
::getContactId($dbId);
406 return array($contactID, $dbId, mt_rand());
413 * Set a init session with user object.
416 * Array with user specific data.
418 public function setUserSession($data) {
419 list($userID, $ufID) = $data;
420 $user = new JUser($ufID);
421 $session = JFactory
::getSession();
422 $session->set('user', $user);
424 parent
::setUserSession($data);
428 * FIXME: Do something
430 * @param string $message
432 public function setMessage($message) {
436 * @param \string $username
437 * @param \string $password
441 public function loadUser($username, $password = NULL) {
442 $uid = JUserHelper
::getUserId($username);
446 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
447 if (!empty($password)) {
448 $instance = JFactory
::getApplication('site');
450 'username' => $username,
451 'password' => $password,
453 //perform the login action
454 $instance->login($params);
457 $session = CRM_Core_Session
::singleton();
458 $session->set('ufID', $uid);
459 $session->set('userID', $contactID);
464 * FIXME: Use CMS-native approach
466 public function permissionDenied() {
467 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
473 public function logout() {
475 CRM_Utils_System
::setHttpHeader("Location", "index.php");
481 public function getUFLocale() {
482 if (defined('_JEXEC')) {
483 $conf = JFactory
::getConfig();
484 $locale = $conf->get('language');
485 return str_replace('-', '_', $locale);
493 public function setUFLocale($civicrm_language) {
501 public function getVersion() {
502 if (class_exists('JVersion')) {
503 $version = new JVersion();
504 return $version->getShortVersion();
511 public function getJVersion($joomlaBase) {
512 // Files may be in different places depending on Joomla version
513 if (!defined('JVERSION')) {
515 $versionPhp = $joomlaBase . '/libraries/src/Version.php';
516 if (!file_exists($versionPhp)) {
518 $versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
521 $jversion = new JVersion();
522 define('JVERSION', $jversion->getShortVersion());
527 * Setup the base path related constant.
530 public function getBasePath() {
531 global $civicrm_root;
532 $joomlaPath = explode(DIRECTORY_SEPARATOR
. 'administrator', $civicrm_root);
533 $joomlaBase = $joomlaPath[0];
538 * Load joomla bootstrap.
540 * @param array $params
541 * with uid or name and password.
542 * @param bool $loadUser
544 * @param bool|\throw $throwError throw error on failure?
545 * @param null $realPath
546 * @param bool $loadDefines
550 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
551 $joomlaBase = self
::getBasePath();
553 // load BootStrap here if needed
554 // We are a valid Joomla entry point.
555 if (!defined('_JEXEC') && $loadDefines) {
557 define('DS', DIRECTORY_SEPARATOR
);
558 define('JPATH_BASE', $joomlaBase . '/administrator');
559 require $joomlaBase . '/administrator/includes/defines.php';
562 // Get the framework.
563 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
564 require $joomlaBase . '/libraries/import.legacy.php';
566 require $joomlaBase . '/libraries/cms.php';
567 self
::getJVersion($joomlaBase);
569 if (version_compare(JVERSION
, '3.8', 'lt')) {
570 require $joomlaBase . '/libraries/import.php';
571 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
574 require_once $joomlaBase . '/configuration.php';
576 if (version_compare(JVERSION
, '3.0', 'lt')) {
577 require $joomlaBase . '/libraries/joomla/environment/uri.php';
578 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
580 elseif (version_compare(JVERSION
, '3.8', 'lt')) {
581 jimport('joomla.environment.uri');
584 if (version_compare(JVERSION
, '3.8', 'lt')) {
585 jimport('joomla.application.cli');
588 if (!defined('JDEBUG')) {
589 define('JDEBUG', FALSE);
592 // Set timezone for Joomla on Cron
593 $config = JFactory
::getConfig();
594 $timezone = $config->get('offset');
596 date_default_timezone_set($timezone);
597 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
600 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
601 $config = CRM_Core_Config
::singleton();
602 CRM_Utils_Hook
::config($config);
610 public function isUserLoggedIn() {
611 $user = JFactory
::getUser();
612 return ($user->guest
) ?
FALSE : TRUE;
618 public function isUserRegistrationPermitted() {
619 $userParams = JComponentHelper
::getParams('com_users');
620 if (!$userParams->get('allowUserRegistration')) {
629 public function isPasswordUserGenerated() {
636 public function getLoggedInUfID() {
637 $user = JFactory
::getUser();
638 return ($user->guest
) ?
NULL : $user->id
;
644 public function getLoggedInUniqueIdentifier() {
645 $user = JFactory
::getUser();
646 return $this->getUniqueIdentifierFromUserObject($user);
652 public function getUser($contactID) {
653 $user_details = parent
::getUser($contactID);
654 $user = JFactory
::getUser($user_details['id']);
655 $user_details['name'] = $user->name
;
656 return $user_details;
662 public function getUserIDFromUserObject($user) {
663 return !empty($user->id
) ?
$user->id
: NULL;
669 public function getUniqueIdentifierFromUserObject($user) {
670 return ($user->guest
) ?
NULL : $user->email
;
676 public function getTimeZoneString() {
677 $timezone = JFactory
::getConfig()->get('offset');
678 return !$timezone ?
date_default_timezone_get() : $timezone;
682 * Get a list of all installed modules, including enabled and disabled ones
687 public function getModules() {
690 $db = JFactory
::getDbo();
691 $query = $db->getQuery(TRUE);
692 $query->select('type, folder, element, enabled')
693 ->from('#__extensions')
694 ->where('type =' . $db->Quote('plugin'));
695 $plugins = $db->setQuery($query)->loadAssocList();
696 foreach ($plugins as $plugin) {
697 // question: is the folder really a critical part of the plugin's name?
698 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
699 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ?
TRUE : FALSE);
708 public function getLoginURL($destination = '') {
709 $config = CRM_Core_Config
::singleton();
710 $loginURL = $config->userFrameworkBaseURL
;
711 $loginURL = str_replace('administrator/', '', $loginURL);
712 $loginURL .= 'index.php?option=com_users&view=login';
714 //CRM-14872 append destination
715 if (!empty($destination)) {
716 $loginURL .= '&return=' . urlencode(base64_encode($destination));
724 public function getLoginDestination(&$form) {
727 $id = $form->get('id');
732 $gid = $form->get('gid');
734 $args .= "&gid=$gid";
737 // Setup Personal Campaign Page link uses pageId
738 $pageId = $form->get('pageId');
740 $component = $form->get('component');
741 $args .= "&pageId=$pageId&component=$component&action=add";
748 // append destination so user is returned to form they came from after login
749 $args = 'reset=1' . $args;
750 $destination = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
757 * Determine the location of the CMS root.
759 * @return string|NULL
760 * local file system path to CMS root, or NULL if it cannot be determined
762 public function cmsRootPath() {
763 global $civicrm_paths;
764 if (!empty($civicrm_paths['cms.root']['path'])) {
765 return $civicrm_paths['cms.root']['path'];
768 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
769 if (file_exists("$siteRoot/administrator/index.php")) {
778 public function getDefaultSiteSettings($dir = NULL) {
779 $config = CRM_Core_Config
::singleton();
783 $config->userFrameworkBaseURL
785 // CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
786 // This is the original pattern, but it doesn't work under Windows.
787 // By setting the pattern to the one used before the change first and only
788 // changing it means that the change code only affects Windows users.
789 $pattern = '|/media/civicrm/.*$|';
790 if (DIRECTORY_SEPARATOR
== '\\') {
791 // This regular expression will handle Windows as well as Linux
792 // and any combination of forward and back slashes in directory
793 // separators. We only apply it if the directory separator is the one
795 $pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
797 $siteRoot = preg_replace(
800 $config->imageUploadDir
802 return array($url, NULL, $siteRoot);
808 public function getUserRecordUrl($contactID) {
809 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
810 $userRecordUrl = NULL;
811 // if logged in user has user edit access, then allow link to other users joomla profile
812 if (JFactory
::getUser()->authorise('core.edit', 'com_users')) {
813 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
815 elseif (CRM_Core_Session
::singleton()->get('userID') == $contactID) {
816 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
823 public function checkPermissionAddUser() {
824 if (JFactory
::getUser()->authorise('core.create', 'com_users')) {
830 * Output code from error function.
831 * @param string $content
833 public function outputError($content) {
834 if (class_exists('JErrorPage')) {
835 $error = new Exception($content);
836 JErrorPage
::render($error);
838 elseif (class_exists('JError')) {
839 JError
::raiseError('CiviCRM-001', $content);
842 parent
::outputError($content);
847 * Append Joomla js to coreResourcesList.
851 public function appendCoreResources(&$list) {
852 $list[] = 'js/crm.joomla.js';
858 public function synchronizeUsers() {
859 $config = CRM_Core_Config
::singleton();
860 if (PHP_SAPI
!= 'cli') {
867 $JUserTable = &JTable
::getInstance('User', 'JTable');
869 $db = $JUserTable->getDbo();
870 $query = $db->getQuery(TRUE);
871 $query->select($id . ', ' . $mail . ', ' . $name);
872 $query->from($JUserTable->getTableName());
873 $query->where($mail != '');
875 $db->setQuery($query);
876 $users = $db->loadObjectList();
878 $user = new StdClass();
879 $uf = $config->userFramework
;
882 $contactMatching = 0;
883 for ($i = 0; $i < count($users); $i++
) {
884 $user->$id = $users[$i]->$id;
885 $user->$mail = $users[$i]->$mail;
886 $user->$name = $users[$i]->$name;
888 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user,
902 if (is_object($match)) {
908 'contactCount' => $contactCount,
909 'contactMatching' => $contactMatching,
910 'contactCreated' => $contactCreated,