Merge pull request #2843 from kurund/CRM-14427
[civicrm-core.git] / CRM / Utils / System / Joomla.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36/**
37 * Joomla specific stuff goes here
38 */
39class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
40 function __construct() {
41 $this->is_drupal = FALSE;
42 }
43
44 /**
45 * Function to create a user of Joomla.
46 *
47 * @param array $params associated array
48 * @param string $mail email id for cms user
49 *
50 * @return uid if user exists, false otherwise
51 *
52 * @access public
53 */
54 function createUser(&$params, $mail) {
55 $baseDir = JPATH_SITE;
56 require_once $baseDir . '/components/com_users/models/registration.php';
57
58 $userParams = JComponentHelper::getParams('com_users');
59 $model = new UsersModelRegistration();
60 $ufID = NULL;
61
62 // get the default usertype
63 $userType = $userParams->get('new_usertype');
64 if (!$userType) {
65 $userType = 2;
66 }
67
68 if (isset($params['name'])) {
69 $fullname = trim($params['name']);
70 }
71 elseif (isset($params['contactID'])) {
72 $fullname = trim(CRM_Contact_BAO_Contact::displayName($params['contactID']));
73 }
74 else {
75 $fullname = trim($params['cms_name']);
76 }
77
78 // Prepare the values for a new Joomla user.
79 $values = array();
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]);
84
85 $lang = JFactory::getLanguage();
86 $lang->load('com_users', $baseDir);
87
88 $register = $model->register($values);
89
90 $ufID = JUserHelper::getUserId($values['username']);
91 return $ufID;
92 }
93
94 /*
95 * Change user name in host CMS
96 *
97 * @param integer $ufID User ID in CMS
98 * @param string $ufName User name
99 */
100 function updateCMSName($ufID, $ufName) {
101 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
102 $ufName = CRM_Utils_Type::escape($ufName, 'String');
103
104 $values = array();
105 $user = &JUser::getInstance($ufID);
106
107 $values['email'] = $ufName;
108 $user->bind($values);
109
110 $user->save();
111 }
112
113 /**
114 * Check if username and email exists in the Joomla! db
115 *
116 * @params $params array array of name and mail values
117 * @params $errors array array of errors
118 * @params $emailName string field label for the 'email'
119 *
120 * @return void
121 */
122 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
123 $config = CRM_Core_Config::singleton();
124
125 $dao = new CRM_Core_DAO();
126 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
127 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
128 //don't allow the special characters and min. username length is two
129 //regex \\ to match a single backslash would become '/\\\\/'
130 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
131 if ($isNotValid || strlen($name) < 2) {
132 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
133 }
134
135
136 $JUserTable = &JTable::getInstance('User', 'JTable');
137
138 $db = $JUserTable->getDbo();
139 $query = $db->getQuery(TRUE);
140 $query->select('username, email');
141 $query->from($JUserTable->getTableName());
142 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
143 $db->setQuery($query, 0, 10);
144 $users = $db->loadAssocList();
145
146 $row = array();;
147 if (count($users)) {
148 $row = $users[0];
149 }
150
151 if (!empty($row)) {
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.',
156 array(1 => $name)
157 );
158 }
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 is already registered. <a href="%2">Have you forgotten your password?</a>',
162 array(1 => $email, 2 => $resetUrl)
163 );
164 }
165 }
166 }
167
168 /**
169 * sets the title of the page
170 *
171 * @param string $title title to set
172 * @param string $pageTitle
173 *
174 * @return void
175 * @access public
176 */
177 function setTitle($title, $pageTitle = NULL) {
178 if (!$pageTitle) {
179 $pageTitle = $title;
180 }
181
182 $template = CRM_Core_Smarty::singleton();
183 $template->assign('pageTitle', $pageTitle);
184
185 $document = JFactory::getDocument();
186 $document->setTitle($title);
187
188 return;
189 }
190
191 /**
192 * Append an additional breadcrumb tag to the existing breadcrumb
193 *
194 * @param string $title
195 * @param string $url
196 *
197 * @return void
198 * @access public
199 */
200 function appendBreadCrumb($breadCrumbs) {
201 $template = CRM_Core_Smarty::singleton();
202 $bc = $template->get_template_vars('breadcrumb');
203
204 if (is_array($breadCrumbs)) {
205 foreach ($breadCrumbs as $crumbs) {
206 if (stripos($crumbs['url'], 'id%%')) {
207 $args = array('cid', 'mid');
208 foreach ($args as $a) {
209 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
210 FALSE, NULL, $_GET
211 );
212 if ($val) {
213 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
214 }
215 }
216 }
217 $bc[] = $crumbs;
218 }
219 }
220 $template->assign_by_ref('breadcrumb', $bc);
221 return;
222 }
223
224 /**
225 * Reset an additional breadcrumb tag to the existing breadcrumb
226 *
227 * @param string $bc the new breadcrumb to be appended
228 *
229 * @return void
230 * @access public
231 */
232 function resetBreadCrumb() {
233 return;
234 }
235
236 /**
237 * Append a string to the head of the html file
238 *
239 * @param string $head the new string to be appended
240 *
241 * @return void
242 * @access public
243 */
244 static function addHTMLHead($string = NULL) {
245 if ($string) {
246 $document = JFactory::getDocument();
247 $document->addCustomTag($string);
248 }
249 }
250
251 /**
252 * Add a script file
253 *
254 * @param $url: string, absolute path to file
255 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
256 *
257 * Note: This function is not to be called directly
258 * @see CRM_Core_Region::render()
259 *
260 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
261 * @access public
262 */
263 public function addScriptUrl($url, $region) {
6a488035
TO
264 return FALSE;
265 }
266
267 /**
268 * Add an inline script
269 *
270 * @param $code: string, javascript code
271 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
272 *
273 * Note: This function is not to be called directly
274 * @see CRM_Core_Region::render()
275 *
276 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
277 * @access public
278 */
279 public function addScript($code, $region) {
6a488035
TO
280 return FALSE;
281 }
282
283 /**
284 * Add a css file
285 *
286 * @param $url: string, absolute path to file
287 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
288 *
289 * Note: This function is not to be called directly
290 * @see CRM_Core_Region::render()
291 *
292 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
293 * @access public
294 */
295 public function addStyleUrl($url, $region) {
296 if ($region == 'html-header') {
297 $document = JFactory::getDocument();
298 $document->addStyleSheet($url);
299 return TRUE;
300 }
301 return FALSE;
302 }
303
304 /**
305 * Add an inline style
306 *
307 * @param $code: string, css code
308 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
309 *
310 * Note: This function is not to be called directly
311 * @see CRM_Core_Region::render()
312 *
313 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
314 * @access public
315 */
316 public function addStyle($code, $region) {
317 if ($region == 'html-header') {
318 $document = JFactory::getDocument();
319 $document->addStyleDeclaration($code);
320 return TRUE;
321 }
322 return FALSE;
323 }
324
325 /**
326 * Generate an internal CiviCRM URL
327 *
328 * @param $path string The path being linked to, such as "civicrm/add"
329 * @param $query string A query string to append to the link.
330 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
331 * Useful for links that will be displayed outside the site, such as in an
332 * RSS feed.
333 * @param $fragment string A fragment identifier (named anchor) to append to the link.
334 * @param $htmlize boolean whether to convert to html eqivalant
335 * @param $frontend boolean a gross joomla hack
336 *
337 * @return string an HTML string containing a link to the given path.
338 * @access public
339 *
340 */
341 function url($path = NULL, $query = NULL, $absolute = TRUE,
342 $fragment = NULL, $htmlize = TRUE,
343 $frontend = FALSE, $forceBackend = FALSE
344 ) {
345 $config = CRM_Core_Config::singleton();
346 $separator = $htmlize ? '&amp;' : '&';
347 $Itemid = '';
348 $script = '';
349 $path = CRM_Utils_String::stripPathChars($path);
350
351 if ($config->userFrameworkFrontend) {
352 $script = 'index.php';
353 if (JRequest::getVar("Itemid")) {
354 $Itemid = "{$separator}Itemid=" . JRequest::getVar("Itemid");
355 }
356 }
357
358 if (isset($fragment)) {
359 $fragment = '#' . $fragment;
360 }
361
362 if (!isset($config->useFrameworkRelativeBase)) {
363 $base = parse_url($config->userFrameworkBaseURL);
364 $config->useFrameworkRelativeBase = $base['path'];
365 }
366 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
367
368 if (!empty($query)) {
369 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
370 }
371 else {
372 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
373 }
374
375 // gross hack for joomla, we are in the backend and want to send a frontend url
376 if ($frontend && $config->userFramework == 'Joomla') {
377 // handle both joomla v1.5 and v1.6, CRM-7939
378 $url = str_replace('/administrator/index2.php', '/index.php', $url);
379 $url = str_replace('/administrator/index.php', '/index.php', $url);
380
381 // CRM-8215
382 $url = str_replace('/administrator/', '/index.php', $url);
383 }
384 elseif ($forceBackend) {
385 if (defined('JVERSION')) {
386 $joomlaVersion = JVERSION;
387 } else {
388 $jversion = new JVersion;
389 $joomlaVersion = $jversion->getShortVersion();
390 }
391
392 if (version_compare($joomlaVersion, '1.6') >= 0) {
393 $url = str_replace('/index.php', '/administrator/index.php', $url);
394 }
395 }
396 return $url;
397 }
398
399 /**
400 * rewrite various system urls to https
401 *
402 * @return void
403 * access public
404 */
405 function mapConfigToSSL() {
406 // dont need to do anything, let CMS handle their own switch to SSL
407 return;
408 }
409
410 /**
411 * figure out the post url for the form
412 *
413 * @param $action the default action if one is pre-specified
414 *
415 * @return string the url to post the form
416 * @access public
417 */
418 function postURL($action) {
419 if (!empty($action)) {
420 return $action;
421 }
422
423 return $this->url(CRM_Utils_Array::value('task', $_GET),
424 NULL, TRUE, NULL, FALSE
425 );
426 }
427
428 /**
429 * Function to set the email address of the user
430 *
431 * @param object $user handle to the user object
432 *
433 * @return void
434 * @access public
435 */
436 function setEmail(&$user) {
437 global $database;
438 $query = "SELECT email FROM #__users WHERE id='$user->id'";
439 $database->setQuery($query);
440 $user->email = $database->loadResult();
441 }
442
443 /**
444 * Authenticate the user against the joomla db
445 *
446 * @param string $name the user name
447 * @param string $password the password for the above user name
448 * @param $loadCMSBootstrap boolean load cms bootstrap?
449 *
450 * @return mixed false if no auth
451 * array(
452 contactID, ufID, unique string ) if success
453 * @access public
454 */
455 function authenticate($name, $password, $loadCMSBootstrap = FALSE) {
456 require_once 'DB.php';
457
458 $config = CRM_Core_Config::singleton();
ebc28bab 459 $user = NULL;
6a488035
TO
460
461 if ($loadCMSBootstrap) {
462 $bootStrapParams = array();
463 if ($name && $password) {
464 $bootStrapParams = array(
465 'name' => $name,
466 'pass' => $password,
467 );
468 }
bec3fc7c 469 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
6a488035
TO
470 }
471
472 jimport('joomla.application.component.helper');
473 jimport('joomla.database.table');
c1f3c6da
BS
474 jimport('joomla.user.helper');
475
476 $JUserTable = JTable::getInstance('User', 'JTable');
477
478 $db = $JUserTable->getDbo();
479 $query = $db->getQuery(TRUE);
480 $query->select('id, name, username, email, password');
481 $query->from($JUserTable->getTableName());
482 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
483 $db->setQuery($query, 0, 0);
484 $users = $db->loadObjectList();
485
486 $row = array();
487 if (count($users)) {
488 $row = $users[0];
489 }
6a488035 490
ebc28bab
BS
491 if ( !defined('JVERSION') ) {
492 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
493 require $joomlaBase . '/libraries/cms/version/version.php';
494 $jversion = new JVersion;
495 define('JVERSION', $jversion->getShortVersion());
496 }
6a488035 497
c1f3c6da
BS
498 if (!empty($row)) {
499 $dbPassword = $row->password;
500 $dbId = $row->id;
501 $dbEmail = $row->email;
6a488035 502
c1f3c6da
BS
503 if ( version_compare(JVERSION, '2.5.18', 'lt') ||
504 ( version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt') )
505 ) {
ebc28bab
BS
506 // now check password
507 if (strpos($dbPassword, ':') === FALSE) {
508 if ($dbPassword != md5($password)) {
509 return FALSE;
510 }
511 }
512 else {
513 list($hash, $salt) = explode(':', $dbPassword);
514 $cryptpass = md5($password . $salt);
515 if ($hash != $cryptpass) {
516 return FALSE;
517 }
6a488035
TO
518 }
519 }
c1f3c6da
BS
520 else {
521 if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) return FALSE;
6a488035
TO
522 }
523
c1f3c6da 524 CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
6a488035
TO
525 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
526 if (!$contactID) {
527 return FALSE;
528 }
529 return array($contactID, $dbId, mt_rand());
530 }
c1f3c6da 531
6a488035
TO
532 return FALSE;
533 }
534
bec3fc7c
BS
535 /**
536 * Set a init session with user object
537 *
538 * @param array $data array with user specific data
539 *
540 * @access public
541 */
542 function setUserSession($data) {
543 list($userID, $ufID) = $data;
544 $user = new JUser( $ufID );
2d8f9c75 545 $session = JFactory::getSession();
bec3fc7c
BS
546 $session->set('user', $user);
547
cb0e36de 548 parent::setUserSession($data);
bec3fc7c
BS
549 }
550
6a488035
TO
551 /**
552 * Set a message in the UF to display to a user
553 *
554 * @param string $message the message to set
555 *
556 * @access public
557 */
558 function setMessage($message) {
559 return;
560 }
561
562 function loadUser($user) {
563 return TRUE;
564 }
565
566 function permissionDenied() {
567 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
568 }
569
570 function logout() {
571 session_destroy();
572 header("Location:index.php");
573 }
574
575 /**
576 * Get the locale set in the hosting CMS
577 *
578 * @return string the used locale or null for none
579 */
580 function getUFLocale() {
581 if (defined('_JEXEC')) {
582 $conf = JFactory::getConfig();
4965d8e9 583 $locale = $conf->get('language');
6a488035
TO
584 return str_replace('-', '_', $locale);
585 }
586 return NULL;
587 }
588
589 function getVersion() {
590 if (class_exists('JVersion')) {
591 $version = new JVersion;
592 return $version->getShortVersion();
593 }
594 else {
595 return 'Unknown';
596 }
597 }
598
599 /*
600 * load joomla bootstrap
601 *
602 * @param $params array with uid or name and password
603 * @param $loadUser boolean load cms user?
604 * @param $throwError throw error on failure?
605 */
2cb7adde 606 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
6a488035
TO
607 // Setup the base path related constant.
608 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
609
610 // load BootStrap here if needed
611 // We are a valid Joomla entry point.
bec3fc7c 612 if ( ! defined( '_JEXEC' ) && $loadDefines ) {
6a488035
TO
613 define('_JEXEC', 1);
614 define('DS', DIRECTORY_SEPARATOR);
615 define('JPATH_BASE', $joomlaBase . '/administrator');
616 require $joomlaBase . '/administrator/includes/defines.php';
617 }
618
619 // Get the framework.
2cb7adde 620 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
2efcf0c2 621 require $joomlaBase . '/libraries/import.legacy.php';
2cb7adde 622 }
6a488035
TO
623 require $joomlaBase . '/libraries/import.php';
624 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
6a488035
TO
625 require $joomlaBase . '/configuration.php';
626
6fde79f5
BS
627 // Files may be in different places depending on Joomla version
628 if ( !defined('JVERSION') ) {
629 require $joomlaBase . '/libraries/cms/version/version.php';
630 $jversion = new JVersion;
631 define('JVERSION', $jversion->getShortVersion());
632 }
633
634 if( version_compare(JVERSION, '3.0', 'lt') ) {
635 require $joomlaBase . '/libraries/joomla/environment/uri.php';
636 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
637 }
638 else {
639 require $joomlaBase . '/libraries/joomla/uri/uri.php';
6fde79f5
BS
640 }
641
6a488035
TO
642 jimport('joomla.application.cli');
643
644 return TRUE;
645 }
646
647 /**
648 * check is user logged in.
649 *
650 * @return boolean true/false.
651 */
652 public function isUserLoggedIn() {
653 $user = JFactory::getUser();
654 return ($user->guest) ? FALSE : TRUE;
655 }
656
657 /**
658 * Get currently logged in user uf id.
659 *
660 * @return int logged in user uf id.
661 */
662 public function getLoggedInUfID() {
663 $user = JFactory::getUser();
664 return ($user->guest) ? NULL : $user->id;
665 }
666
667 /**
668 * Get a list of all installed modules, including enabled and disabled ones
669 *
670 * @return array CRM_Core_Module
671 */
672 function getModules() {
673 $result = array();
674
675 $db = JFactory::getDbo();
676 $query = $db->getQuery(true);
677 $query->select('type, folder, element, enabled')
678 ->from('#__extensions')
679 ->where('type =' . $db->Quote('plugin'));
680 $plugins = $db->setQuery($query)->loadAssocList();
681 foreach ($plugins as $plugin) {
682 // question: is the folder really a critical part of the plugin's name?
683 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
684 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
685 }
686
687 return $result;
688 }
689
690 /**
691 * Get user login URL for hosting CMS (method declared in each CMS system class)
692 *
693 * @param string $destination - if present, add destination to querystring (works for Drupal only)
694 *
695 * @return string - loginURL for the current CMS
696 * @static
697 */
698 public function getLoginURL($destination = '') {
699 $config = CRM_Core_Config::singleton();
700 $loginURL = $config->userFrameworkBaseURL;
701 $loginURL = str_replace('administrator/', '', $loginURL);
702 $loginURL .= 'index.php?option=com_users&view=login';
703 return $loginURL;
704 }
f813f78e 705
6a488035
TO
706 public function getLoginDestination(&$form) {
707 return;
708 }
9977c6f5 709
710 /**
711 * Return default Site Settings
712 * @return array array
713 * - $url, (Joomla - non admin url)
714 * - $siteName,
715 * - $siteRoot
716 */
717 function getDefaultSiteSettings($dir){
718 $config = CRM_Core_Config::singleton();
719 $url = preg_replace(
720 '|/administrator|',
721 '',
722 $config->userFrameworkBaseURL
723 );
724 $siteRoot = preg_replace(
725 '|/media/civicrm/.*$|',
726 '',
727 $config->imageUploadDir
728 );
729 return array($url, NULL, $siteRoot);
730 }
6a488035
TO
731}
732