3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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());
139 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
140 $db->setQuery($query, 0, 10);
141 $users = $db->loadAssocList();
149 $dbName = CRM_Utils_Array
::value('username', $row);
150 $dbEmail = CRM_Utils_Array
::value('email', $row);
151 if (strtolower($dbName) == strtolower($name)) {
152 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
156 if (strtolower($dbEmail) == strtolower($email)) {
157 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL
) . 'index.php?option=com_users&view=reset';
158 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
159 array(1 => $email, 2 => $resetUrl)
168 public function setTitle($title, $pageTitle = NULL) {
173 $template = CRM_Core_Smarty
::singleton();
174 $template->assign('pageTitle', $pageTitle);
176 $document = JFactory
::getDocument();
177 $document->setTitle($title);
183 public function appendBreadCrumb($breadCrumbs) {
184 $template = CRM_Core_Smarty
::singleton();
185 $bc = $template->get_template_vars('breadcrumb');
187 if (is_array($breadCrumbs)) {
188 foreach ($breadCrumbs as $crumbs) {
189 if (stripos($crumbs['url'], 'id%%')) {
190 $args = array('cid', 'mid');
191 foreach ($args as $a) {
192 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
196 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
203 $template->assign_by_ref('breadcrumb', $bc);
209 public function resetBreadCrumb() {
215 public function addHTMLHead($string = NULL) {
217 $document = JFactory
::getDocument();
218 $document->addCustomTag($string);
225 public function addStyleUrl($url, $region) {
226 if ($region == 'html-header') {
227 $document = JFactory
::getDocument();
228 $document->addStyleSheet($url);
237 public function addStyle($code, $region) {
238 if ($region == 'html-header') {
239 $document = JFactory
::getDocument();
240 $document->addStyleDeclaration($code);
255 $forceBackend = FALSE
257 $config = CRM_Core_Config
::singleton();
261 $path = CRM_Utils_String
::stripPathChars($path);
263 if ($config->userFrameworkFrontend
) {
264 $script = 'index.php';
265 if (JRequest
::getVar("Itemid")) {
266 $Itemid = "{$separator}Itemid=" . JRequest
::getVar("Itemid");
270 if (isset($fragment)) {
271 $fragment = '#' . $fragment;
274 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
276 if (!empty($query)) {
277 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
280 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
283 // gross hack for joomla, we are in the backend and want to send a frontend url
284 if ($frontend && $config->userFramework
== 'Joomla') {
285 // handle both joomla v1.5 and v1.6, CRM-7939
286 $url = str_replace('/administrator/index2.php', '/index.php', $url);
287 $url = str_replace('/administrator/index.php', '/index.php', $url);
290 $url = str_replace('/administrator/', '/index.php', $url);
292 elseif ($forceBackend) {
293 if (defined('JVERSION')) {
294 $joomlaVersion = JVERSION
;
297 $jversion = new JVersion();
298 $joomlaVersion = $jversion->getShortVersion();
301 if (version_compare($joomlaVersion, '1.6') >= 0) {
302 $url = str_replace('/index.php', '/administrator/index.php', $url);
309 * Set the email address of the user.
311 * @param object $user
312 * Handle to the user object.
314 public function setEmail(&$user) {
316 $query = $db->getQuery(TRUE);
317 $query->select($db->quoteName('email'))
318 ->from($db->quoteName('#__users'))
319 ->where($db->quoteName('id') . ' = ' . $user->id
);
320 $database->setQuery($query);
321 $user->email
= $database->loadResult();
327 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
328 require_once 'DB.php';
330 $config = CRM_Core_Config
::singleton();
333 if ($loadCMSBootstrap) {
334 $bootStrapParams = array();
335 if ($name && $password) {
336 $bootStrapParams = array(
341 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
344 jimport('joomla.application.component.helper');
345 jimport('joomla.database.table');
346 jimport('joomla.user.helper');
348 $JUserTable = JTable
::getInstance('User', 'JTable');
350 $db = $JUserTable->getDbo();
351 $query = $db->getQuery(TRUE);
352 $query->select('id, name, username, email, password');
353 $query->from($JUserTable->getTableName());
354 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
355 $db->setQuery($query, 0, 0);
356 $users = $db->loadObjectList();
363 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__
))))))));
364 if (!defined('JVERSION')) {
365 require $joomlaBase . '/libraries/cms/version/version.php';
366 $jversion = new JVersion();
367 define('JVERSION', $jversion->getShortVersion());
371 $dbPassword = $row->password
;
373 $dbEmail = $row->email
;
375 if (version_compare(JVERSION
, '2.5.18', 'lt') ||
376 (version_compare(JVERSION
, '3.0', 'ge') && version_compare(JVERSION
, '3.2.1', 'lt'))
378 // now check password
379 list($hash, $salt) = explode(':', $dbPassword);
380 $cryptpass = md5($password . $salt);
381 if ($hash != $cryptpass) {
386 if (!JUserHelper
::verifyPassword($password, $dbPassword, $dbId)) {
390 //include additional files required by Joomla 3.2.1+
391 if (version_compare(JVERSION
, '3.2.1', 'ge')) {
392 require_once $joomlaBase . '/libraries/cms/application/helper.php';
393 require_once $joomlaBase . '/libraries/cms/application/cms.php';
394 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
398 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
399 $contactID = CRM_Core_BAO_UFMatch
::getContactId($dbId);
403 return array($contactID, $dbId, mt_rand());
410 * Set a init session with user object.
413 * Array with user specific data.
415 public function setUserSession($data) {
416 list($userID, $ufID) = $data;
417 $user = new JUser($ufID);
418 $session = JFactory
::getSession();
419 $session->set('user', $user);
421 parent
::setUserSession($data);
425 * FIXME: Do something
427 * @param string $message
429 public function setMessage($message) {
433 * @param \string $username
434 * @param \string $password
438 public function loadUser($username, $password = NULL) {
439 $uid = JUserHelper
::getUserId($username);
443 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
444 if (!empty($password)) {
445 $instance = JFactory
::getApplication('site');
447 'username' => $username,
448 'password' => $password,
450 //perform the login action
451 $instance->login($params);
454 $session = CRM_Core_Session
::singleton();
455 $session->set('ufID', $uid);
456 $session->set('userID', $contactID);
461 * FIXME: Use CMS-native approach
463 public function permissionDenied() {
464 CRM_Core_Error
::fatal(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();
509 * Load joomla bootstrap.
511 * @param array $params
512 * with uid or name and password.
513 * @param bool $loadUser
515 * @param bool|\throw $throwError throw error on failure?
516 * @param null $realPath
517 * @param bool $loadDefines
521 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
522 // Setup the base path related constant.
523 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__
))))))));
525 // load BootStrap here if needed
526 // We are a valid Joomla entry point.
527 if (!defined('_JEXEC') && $loadDefines) {
529 define('DS', DIRECTORY_SEPARATOR
);
530 define('JPATH_BASE', $joomlaBase . '/administrator');
531 require $joomlaBase . '/administrator/includes/defines.php';
534 // Get the framework.
535 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
536 require $joomlaBase . '/libraries/import.legacy.php';
538 require $joomlaBase . '/libraries/import.php';
539 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
540 require $joomlaBase . '/configuration.php';
542 // Files may be in different places depending on Joomla version
543 if (!defined('JVERSION')) {
544 require $joomlaBase . '/libraries/cms/version/version.php';
545 $jversion = new JVersion();
546 define('JVERSION', $jversion->getShortVersion());
549 if (version_compare(JVERSION
, '3.0', 'lt')) {
550 require $joomlaBase . '/libraries/joomla/environment/uri.php';
551 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
554 require $joomlaBase . '/libraries/cms.php';
555 require $joomlaBase . '/libraries/joomla/uri/uri.php';
558 jimport('joomla.application.cli');
560 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
561 $config = CRM_Core_Config
::singleton();
562 CRM_Utils_Hook
::config($config);
570 public function isUserLoggedIn() {
571 $user = JFactory
::getUser();
572 return ($user->guest
) ?
FALSE : TRUE;
578 public function getLoggedInUfID() {
579 $user = JFactory
::getUser();
580 return ($user->guest
) ?
NULL : $user->id
;
586 public function getLoggedInUniqueIdentifier() {
587 $user = JFactory
::getUser();
588 return $this->getUniqueIdentifierFromUserObject($user);
594 public function getUserIDFromUserObject($user) {
595 return !empty($user->id
) ?
$user->id
: NULL;
601 public function getUniqueIdentifierFromUserObject($user) {
602 return ($user->guest
) ?
NULL : $user->email
;
606 * Get a list of all installed modules, including enabled and disabled ones
611 public function getModules() {
614 $db = JFactory
::getDbo();
615 $query = $db->getQuery(TRUE);
616 $query->select('type, folder, element, enabled')
617 ->from('#__extensions')
618 ->where('type =' . $db->Quote('plugin'));
619 $plugins = $db->setQuery($query)->loadAssocList();
620 foreach ($plugins as $plugin) {
621 // question: is the folder really a critical part of the plugin's name?
622 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
623 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ?
TRUE : FALSE);
632 public function getLoginURL($destination = '') {
633 $config = CRM_Core_Config
::singleton();
634 $loginURL = $config->userFrameworkBaseURL
;
635 $loginURL = str_replace('administrator/', '', $loginURL);
636 $loginURL .= 'index.php?option=com_users&view=login';
638 //CRM-14872 append destination
639 if (!empty($destination)) {
640 $loginURL .= '&return=' . urlencode(base64_encode($destination));
648 public function getLoginDestination(&$form) {
651 $id = $form->get('id');
656 $gid = $form->get('gid');
658 $args .= "&gid=$gid";
661 // Setup Personal Campaign Page link uses pageId
662 $pageId = $form->get('pageId');
664 $component = $form->get('component');
665 $args .= "&pageId=$pageId&component=$component&action=add";
672 // append destination so user is returned to form they came from after login
673 $args = 'reset=1' . $args;
674 $destination = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
681 * Determine the location of the CMS root.
683 * @return string|NULL
684 * local file system path to CMS root, or NULL if it cannot be determined
686 public function cmsRootPath() {
687 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
688 $includePath = "$siteRoot/libraries/cms/version";
689 if (file_exists("$includePath/version.php")) {
698 public function getDefaultSiteSettings($dir) {
699 $config = CRM_Core_Config
::singleton();
703 $config->userFrameworkBaseURL
705 $siteRoot = preg_replace(
706 '|/media/civicrm/.*$|',
708 $config->imageUploadDir
710 return array($url, NULL, $siteRoot);
716 public function getUserRecordUrl($contactID) {
717 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
718 $userRecordUrl = NULL;
719 // if logged in user has user edit access, then allow link to other users joomla profile
720 if (JFactory
::getUser()->authorise('core.edit', 'com_users')) {
721 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
723 elseif (CRM_Core_Session
::singleton()->get('userID') == $contactID) {
724 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
731 public function checkPermissionAddUser() {
732 if (JFactory
::getUser()->authorise('core.create', 'com_users')) {
738 * Output code from error function.
739 * @param string $content
741 public function outputError($content) {
742 if (class_exists('JErrorPage')) {
743 $error = new Exception($content);
744 JErrorPage
::render($error);
746 elseif (class_exists('JError')) {
747 JError
::raiseError('CiviCRM-001', $content);
750 parent
::outputError($content);
755 * Append Joomla js to coreResourcesList.
759 public function appendCoreResources(&$list) {
760 $list[] = 'js/crm.joomla.js';
766 public function synchronizeUsers() {
767 $config = CRM_Core_Config
::singleton();
768 if (PHP_SAPI
!= 'cli') {
775 $JUserTable = &JTable
::getInstance('User', 'JTable');
777 $db = $JUserTable->getDbo();
778 $query = $db->getQuery(TRUE);
779 $query->select($id . ', ' . $mail . ', ' . $name);
780 $query->from($JUserTable->getTableName());
781 $query->where($mail != '');
783 $db->setQuery($query);
784 $users = $db->loadObjectList();
786 $user = new StdClass();
787 $uf = $config->userFramework
;
790 $contactMatching = 0;
791 for ($i = 0; $i < count($users); $i++
) {
792 $user->$id = $users[$i]->$id;
793 $user->$mail = $users[$i]->$mail;
794 $user->$name = $users[$i]->$name;
796 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user,
810 if (is_object($match)) {
816 'contactCount' => $contactCount,
817 'contactMatching' => $contactMatching,
818 'contactCreated' => $contactCreated,