3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Joomla specific stuff goes here
39 class CRM_Utils_System_Joomla
extends CRM_Utils_System_Base
{
43 function __construct() {
44 $this->is_drupal
= FALSE;
48 * Function to create a user of Joomla.
50 * @param array $params associated array
51 * @param string $mail email id for cms user
53 * @return uid if user exists, false otherwise
57 function createUser(&$params, $mail) {
58 $baseDir = JPATH_SITE
;
59 require_once $baseDir . '/components/com_users/models/registration.php';
61 $userParams = JComponentHelper
::getParams('com_users');
62 $model = new UsersModelRegistration();
65 // get the default usertype
66 $userType = $userParams->get('new_usertype');
71 if (isset($params['name'])) {
72 $fullname = trim($params['name']);
74 elseif (isset($params['contactID'])) {
75 $fullname = trim(CRM_Contact_BAO_Contact
::displayName($params['contactID']));
78 $fullname = trim($params['cms_name']);
81 // Prepare the values for a new Joomla user.
83 $values['name'] = $fullname;
84 $values['username'] = trim($params['cms_name']);
85 $values['password1'] = $values['password2'] = $params['cms_pass'];
86 $values['email1'] = $values['email2'] = trim($params[$mail]);
88 $lang = JFactory
::getLanguage();
89 $lang->load('com_users', $baseDir);
91 $register = $model->register($values);
93 $ufID = JUserHelper
::getUserId($values['username']);
98 * Change user name in host CMS
100 * @param integer $ufID User ID in CMS
101 * @param string $ufName User name
103 function updateCMSName($ufID, $ufName) {
104 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
105 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
108 $user = &JUser
::getInstance($ufID);
110 $values['email'] = $ufName;
111 $user->bind($values);
117 * Check if username and email exists in the Joomla! db
119 * @params $params array array of name and mail values
120 * @params $errors array array of errors
121 * @params $emailName string field label for the 'email'
125 * @param string $emailName
129 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
130 $config = CRM_Core_Config
::singleton();
132 $dao = new CRM_Core_DAO();
133 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
134 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
135 //don't allow the special characters and min. username length is two
136 //regex \\ to match a single backslash would become '/\\\\/'
137 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
138 if ($isNotValid ||
strlen($name) < 2) {
139 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
143 $JUserTable = &JTable
::getInstance('User', 'JTable');
145 $db = $JUserTable->getDbo();
146 $query = $db->getQuery(TRUE);
147 $query->select('username, email');
148 $query->from($JUserTable->getTableName());
149 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
150 $db->setQuery($query, 0, 10);
151 $users = $db->loadAssocList();
159 $dbName = CRM_Utils_Array
::value('username', $row);
160 $dbEmail = CRM_Utils_Array
::value('email', $row);
161 if (strtolower($dbName) == strtolower($name)) {
162 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
166 if (strtolower($dbEmail) == strtolower($email)) {
167 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL
) . 'index.php?option=com_users&view=reset';
168 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
169 array(1 => $email, 2 => $resetUrl)
176 * sets the title of the page
178 * @param string $title title to set
179 * @param string $pageTitle
184 function setTitle($title, $pageTitle = NULL) {
189 $template = CRM_Core_Smarty
::singleton();
190 $template->assign('pageTitle', $pageTitle);
192 $document = JFactory
::getDocument();
193 $document->setTitle($title);
199 * Append an additional breadcrumb tag to the existing breadcrumb
201 * @param $breadCrumbs
203 * @internal param string $title
204 * @internal param string $url
209 function appendBreadCrumb($breadCrumbs) {
210 $template = CRM_Core_Smarty
::singleton();
211 $bc = $template->get_template_vars('breadcrumb');
213 if (is_array($breadCrumbs)) {
214 foreach ($breadCrumbs as $crumbs) {
215 if (stripos($crumbs['url'], 'id%%')) {
216 $args = array('cid', 'mid');
217 foreach ($args as $a) {
218 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
222 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
229 $template->assign_by_ref('breadcrumb', $bc);
234 * Reset an additional breadcrumb tag to the existing breadcrumb
236 * @internal param string $bc the new breadcrumb to be appended
241 function resetBreadCrumb() {
246 * Append a string to the head of the html file
248 * @param null $string
250 * @internal param string $head the new string to be appended
255 static function addHTMLHead($string = NULL) {
257 $document = JFactory
::getDocument();
258 $document->addCustomTag($string);
265 * @param $url: string, absolute path to file
266 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
268 * Note: This function is not to be called directly
269 * @see CRM_Core_Region::render()
271 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
274 public function addScriptUrl($url, $region) {
279 * Add an inline script
281 * @param $code: string, javascript code
282 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
284 * Note: This function is not to be called directly
285 * @see CRM_Core_Region::render()
287 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
290 public function addScript($code, $region) {
297 * @param $url: string, absolute path to file
298 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
300 * Note: This function is not to be called directly
301 * @see CRM_Core_Region::render()
303 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
306 public function addStyleUrl($url, $region) {
307 if ($region == 'html-header') {
308 $document = JFactory
::getDocument();
309 $document->addStyleSheet($url);
316 * Add an inline style
318 * @param $code: string, css code
319 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
321 * Note: This function is not to be called directly
322 * @see CRM_Core_Region::render()
324 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
327 public function addStyle($code, $region) {
328 if ($region == 'html-header') {
329 $document = JFactory
::getDocument();
330 $document->addStyleDeclaration($code);
337 * Generate an internal CiviCRM URL
339 * @param $path string The path being linked to, such as "civicrm/add"
340 * @param $query string A query string to append to the link.
341 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
342 * Useful for links that will be displayed outside the site, such as in an
344 * @param $fragment string A fragment identifier (named anchor) to append to the link.
345 * @param $htmlize boolean whether to convert to html eqivalant
346 * @param $frontend boolean a gross joomla hack
348 * @param bool $forceBackend
350 * @return string an HTML string containing a link to the given path.
353 function url($path = NULL, $query = NULL, $absolute = TRUE,
354 $fragment = NULL, $htmlize = TRUE,
355 $frontend = FALSE, $forceBackend = FALSE
357 $config = CRM_Core_Config
::singleton();
358 $separator = $htmlize ?
'&' : '&';
361 $path = CRM_Utils_String
::stripPathChars($path);
363 if ($config->userFrameworkFrontend
) {
364 $script = 'index.php';
365 if (JRequest
::getVar("Itemid")) {
366 $Itemid = "{$separator}Itemid=" . JRequest
::getVar("Itemid");
370 if (isset($fragment)) {
371 $fragment = '#' . $fragment;
374 if (!isset($config->useFrameworkRelativeBase
)) {
375 $base = parse_url($config->userFrameworkBaseURL
);
376 $config->useFrameworkRelativeBase
= $base['path'];
378 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
380 if (!empty($query)) {
381 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
384 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
387 // gross hack for joomla, we are in the backend and want to send a frontend url
388 if ($frontend && $config->userFramework
== 'Joomla') {
389 // handle both joomla v1.5 and v1.6, CRM-7939
390 $url = str_replace('/administrator/index2.php', '/index.php', $url);
391 $url = str_replace('/administrator/index.php', '/index.php', $url);
394 $url = str_replace('/administrator/', '/index.php', $url);
396 elseif ($forceBackend) {
397 if (defined('JVERSION')) {
398 $joomlaVersion = JVERSION
;
400 $jversion = new JVersion
;
401 $joomlaVersion = $jversion->getShortVersion();
404 if (version_compare($joomlaVersion, '1.6') >= 0) {
405 $url = str_replace('/index.php', '/administrator/index.php', $url);
412 * rewrite various system urls to https
417 function mapConfigToSSL() {
418 // dont need to do anything, let CMS handle their own switch to SSL
423 * figure out the post url for the form
425 * @param $action the default action if one is pre-specified
427 * @return string the url to post the form
430 function postURL($action) {
431 if (!empty($action)) {
435 return $this->url(CRM_Utils_Array
::value('task', $_GET),
436 NULL, TRUE, NULL, FALSE
441 * Function to set the email address of the user
443 * @param object $user handle to the user object
448 function setEmail(&$user) {
450 $query = "SELECT email FROM #__users WHERE id='$user->id'";
451 $database->setQuery($query);
452 $user->email
= $database->loadResult();
456 * Authenticate the user against the joomla db
458 * @param string $name the user name
459 * @param string $password the password for the above user name
460 * @param $loadCMSBootstrap boolean load cms bootstrap?
462 * @return mixed false if no auth
464 contactID, ufID, unique string ) if success
467 function authenticate($name, $password, $loadCMSBootstrap = FALSE) {
468 require_once 'DB.php';
470 $config = CRM_Core_Config
::singleton();
473 if ($loadCMSBootstrap) {
474 $bootStrapParams = array();
475 if ($name && $password) {
476 $bootStrapParams = array(
481 CRM_Utils_System
::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
484 jimport('joomla.application.component.helper');
485 jimport('joomla.database.table');
486 jimport('joomla.user.helper');
488 $JUserTable = JTable
::getInstance('User', 'JTable');
490 $db = $JUserTable->getDbo();
491 $query = $db->getQuery(TRUE);
492 $query->select('id, name, username, email, password');
493 $query->from($JUserTable->getTableName());
494 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
495 $db->setQuery($query, 0, 0);
496 $users = $db->loadObjectList();
503 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__
))))))));
504 if ( !defined('JVERSION') ) {
505 require $joomlaBase . '/libraries/cms/version/version.php';
506 $jversion = new JVersion
;
507 define('JVERSION', $jversion->getShortVersion());
511 $dbPassword = $row->password
;
513 $dbEmail = $row->email
;
515 if ( version_compare(JVERSION
, '2.5.18', 'lt') ||
516 ( version_compare(JVERSION
, '3.0', 'ge') && version_compare(JVERSION
, '3.2.1', 'lt') )
518 // now check password
519 if (strpos($dbPassword, ':') === FALSE) {
520 if ($dbPassword != md5($password)) {
525 list($hash, $salt) = explode(':', $dbPassword);
526 $cryptpass = md5($password . $salt);
527 if ($hash != $cryptpass) {
533 if (!JUserHelper
::verifyPassword($password, $dbPassword, $dbId)) return FALSE;
535 //include additional files required by Joomla 3.2.1+
536 if ( version_compare(JVERSION
, '3.2.1', 'ge') ) {
537 require $joomlaBase . '/libraries/cms/application/helper.php';
538 require $joomlaBase . '/libraries/cms/application/cms.php';
539 require $joomlaBase . '/libraries/cms/application/administrator.php';
543 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
544 $contactID = CRM_Core_BAO_UFMatch
::getContactId($dbId);
548 return array($contactID, $dbId, mt_rand());
555 * Set a init session with user object
557 * @param array $data array with user specific data
561 function setUserSession($data) {
562 list($userID, $ufID) = $data;
563 $user = new JUser( $ufID );
564 $session = JFactory
::getSession();
565 $session->set('user', $user);
567 parent
::setUserSession($data);
571 * Set a message in the UF to display to a user
573 * @param string $message the message to set
577 function setMessage($message) {
586 function loadUser($user) {
590 function permissionDenied() {
591 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
596 header("Location:index.php");
600 * Get the locale set in the hosting CMS
602 * @return string the used locale or null for none
604 function getUFLocale() {
605 if (defined('_JEXEC')) {
606 $conf = JFactory
::getConfig();
607 $locale = $conf->get('language');
608 return str_replace('-', '_', $locale);
616 function getVersion() {
617 if (class_exists('JVersion')) {
618 $version = new JVersion
;
619 return $version->getShortVersion();
627 * load joomla bootstrap
629 * @param $params array with uid or name and password
630 * @param $loadUser boolean load cms user?
631 * @param bool|\throw $throwError throw error on failure?
632 * @param null $realPath
633 * @param bool $loadDefines
637 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
638 // Setup the base path related constant.
639 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__
))))))));
641 // load BootStrap here if needed
642 // We are a valid Joomla entry point.
643 if ( ! defined( '_JEXEC' ) && $loadDefines ) {
645 define('DS', DIRECTORY_SEPARATOR
);
646 define('JPATH_BASE', $joomlaBase . '/administrator');
647 require $joomlaBase . '/administrator/includes/defines.php';
650 // Get the framework.
651 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
652 require $joomlaBase . '/libraries/import.legacy.php';
654 require $joomlaBase . '/libraries/import.php';
655 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
656 require $joomlaBase . '/configuration.php';
658 // Files may be in different places depending on Joomla version
659 if ( !defined('JVERSION') ) {
660 require $joomlaBase . '/libraries/cms/version/version.php';
661 $jversion = new JVersion
;
662 define('JVERSION', $jversion->getShortVersion());
665 if( version_compare(JVERSION
, '3.0', 'lt') ) {
666 require $joomlaBase . '/libraries/joomla/environment/uri.php';
667 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
670 require $joomlaBase . '/libraries/cms.php';
671 require $joomlaBase . '/libraries/joomla/uri/uri.php';
674 jimport('joomla.application.cli');
676 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
677 $config = CRM_Core_Config
::singleton();
678 CRM_Utils_Hook
::config($config);
684 * check is user logged in.
686 * @return boolean true/false.
688 public function isUserLoggedIn() {
689 $user = JFactory
::getUser();
690 return ($user->guest
) ?
FALSE : TRUE;
694 * Get currently logged in user uf id.
696 * @return int logged in user uf id.
698 public function getLoggedInUfID() {
699 $user = JFactory
::getUser();
700 return ($user->guest
) ?
NULL : $user->id
;
704 * Get currently logged in user unique identifier - this tends to be the email address or user name.
706 * @return string $userID logged in user unique identifier
708 function getLoggedInUniqueIdentifier() {
709 $user = JFactory
::getUser();
710 return $this->getUniqueIdentifierFromUserObject($user);
713 * Get User ID from UserFramework system (Joomla)
714 * @param object $user object as described by the CMS
715 * @return mixed <NULL, number>
717 function getUserIDFromUserObject($user) {
718 return !empty($user->id
) ?
$user->id
: NULL;
722 * Get Unique Identifier from UserFramework system (CMS)
723 * @param object $user object as described by the User Framework
724 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
727 function getUniqueIdentifierFromUserObject($user) {
728 return ($user->guest
) ?
NULL : $user->email
;
732 * Get a list of all installed modules, including enabled and disabled ones
734 * @return array CRM_Core_Module
736 function getModules() {
739 $db = JFactory
::getDbo();
740 $query = $db->getQuery(true);
741 $query->select('type, folder, element, enabled')
742 ->from('#__extensions')
743 ->where('type =' . $db->Quote('plugin'));
744 $plugins = $db->setQuery($query)->loadAssocList();
745 foreach ($plugins as $plugin) {
746 // question: is the folder really a critical part of the plugin's name?
747 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
748 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ?
TRUE : FALSE);
755 * Get user login URL for hosting CMS (method declared in each CMS system class)
757 * @param string $destination - if present, add destination to querystring (works for Drupal only)
759 * @return string - loginURL for the current CMS
762 public function getLoginURL($destination = '') {
763 $config = CRM_Core_Config
::singleton();
764 $loginURL = $config->userFrameworkBaseURL
;
765 $loginURL = str_replace('administrator/', '', $loginURL);
766 $loginURL .= 'index.php?option=com_users&view=login';
773 public function getLoginDestination(&$form) {
778 * Return default Site Settings
782 * @return array array
783 * - $url, (Joomla - non admin url)
787 function getDefaultSiteSettings($dir){
788 $config = CRM_Core_Config
::singleton();
792 $config->userFrameworkBaseURL
794 $siteRoot = preg_replace(
795 '|/media/civicrm/.*$|',
797 $config->imageUploadDir
799 return array($url, NULL, $siteRoot);