Merge pull request #869 from totten/cms-perms
[civicrm-core.git] / CRM / Utils / System / Joomla.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 */
39 class 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) {
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) {
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();
459
460 if ($loadCMSBootstrap) {
461 $bootStrapParams = array();
462 if ($name && $password) {
463 $bootStrapParams = array(
464 'name' => $name,
465 'pass' => $password,
466 );
467 }
468 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
469 }
470
471 jimport('joomla.application.component.helper');
472 jimport('joomla.database.table');
473
474 $JUserTable = &JTable::getInstance('User', 'JTable');
475
476 $db = $JUserTable->getDbo();
477 $query = $db->getQuery(TRUE);
478 $query->select('id, username, email, password');
479 $query->from($JUserTable->getTableName());
480 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
481 $db->setQuery($query, 0, 0);
482 $users = $db->loadAssocList();
483
484 $row = array();;
485 if (count($users)) {
486 $row = $users[0];
487 }
488
489 $user = NULL;
490 if (!empty($row)) {
491 $dbPassword = CRM_Utils_Array::value('password', $row);
492 $dbId = CRM_Utils_Array::value('id', $row);
493 $dbEmail = CRM_Utils_Array::value('email', $row);
494
495 // now check password
496 if (strpos($dbPassword, ':') === FALSE) {
497 if ($dbPassword != md5($password)) {
498 return FALSE;
499 }
500 }
501 else {
502 list($hash, $salt) = explode(':', $dbPassword);
503 $cryptpass = md5($password . $salt);
504 if ($hash != $cryptpass) {
505 return FALSE;
506 }
507 }
508
509 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $dbId, $dbEmail, 'Joomla');
510 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
511 if (!$contactID) {
512 return FALSE;
513 }
514 return array($contactID, $dbId, mt_rand());
515 }
516 return FALSE;
517 }
518
519 /**
520 * Set a init session with user object
521 *
522 * @param array $data array with user specific data
523 *
524 * @access public
525 */
526 function setUserSession($data) {
527 list($userID, $ufID) = $data;
528 $user = new JUser( $ufID );
529 $session = &JFactory::getSession();
530 $session->set('user', $user);
531
532 parent::setUserSession($data);
533 }
534
535 /**
536 * Set a message in the UF to display to a user
537 *
538 * @param string $message the message to set
539 *
540 * @access public
541 */
542 function setMessage($message) {
543 return;
544 }
545
546 function loadUser($user) {
547 return TRUE;
548 }
549
550 function permissionDenied() {
551 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
552 }
553
554 function logout() {
555 session_destroy();
556 header("Location:index.php");
557 }
558
559 /**
560 * Get the locale set in the hosting CMS
561 *
562 * @return string the used locale or null for none
563 */
564 function getUFLocale() {
565 if (defined('_JEXEC')) {
566 $conf = JFactory::getConfig();
567 $locale = $conf->getValue('config.language');
568 return str_replace('-', '_', $locale);
569 }
570 return NULL;
571 }
572
573 function getVersion() {
574 if (class_exists('JVersion')) {
575 $version = new JVersion;
576 return $version->getShortVersion();
577 }
578 else {
579 return 'Unknown';
580 }
581 }
582
583 /*
584 * load joomla bootstrap
585 *
586 * @param $params array with uid or name and password
587 * @param $loadUser boolean load cms user?
588 * @param $throwError throw error on failure?
589 */
590 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $loadDefines = TRUE) {
591 // Setup the base path related constant.
592 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
593
594 // load BootStrap here if needed
595 // We are a valid Joomla entry point.
596 if ( ! defined( '_JEXEC' ) && $loadDefines ) {
597 define('_JEXEC', 1);
598 define('DS', DIRECTORY_SEPARATOR);
599 define('JPATH_BASE', $joomlaBase . '/administrator');
600 require $joomlaBase . '/administrator/includes/defines.php';
601 }
602
603 // Get the framework.
604 require $joomlaBase . '/libraries/import.php';
605 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
606 require $joomlaBase . '/configuration.php';
607
608 // Files may be in different places depending on Joomla version
609 if ( !defined('JVERSION') ) {
610 require $joomlaBase . '/libraries/cms/version/version.php';
611 $jversion = new JVersion;
612 define('JVERSION', $jversion->getShortVersion());
613 }
614
615 if( version_compare(JVERSION, '3.0', 'lt') ) {
616 require $joomlaBase . '/libraries/joomla/environment/uri.php';
617 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
618 }
619 else {
620 require $joomlaBase . '/libraries/joomla/uri/uri.php';
621 require $joomlaBase . '/libraries/legacy/component/helper.php';
622 }
623
624 jimport('joomla.application.cli');
625
626 return TRUE;
627 }
628
629 /**
630 * check is user logged in.
631 *
632 * @return boolean true/false.
633 */
634 public function isUserLoggedIn() {
635 $user = JFactory::getUser();
636 return ($user->guest) ? FALSE : TRUE;
637 }
638
639 /**
640 * Get currently logged in user uf id.
641 *
642 * @return int logged in user uf id.
643 */
644 public function getLoggedInUfID() {
645 $user = JFactory::getUser();
646 return ($user->guest) ? NULL : $user->id;
647 }
648
649 /**
650 * Get a list of all installed modules, including enabled and disabled ones
651 *
652 * @return array CRM_Core_Module
653 */
654 function getModules() {
655 $result = array();
656
657 $db = JFactory::getDbo();
658 $query = $db->getQuery(true);
659 $query->select('type, folder, element, enabled')
660 ->from('#__extensions')
661 ->where('type =' . $db->Quote('plugin'));
662 $plugins = $db->setQuery($query)->loadAssocList();
663 foreach ($plugins as $plugin) {
664 // question: is the folder really a critical part of the plugin's name?
665 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
666 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
667 }
668
669 return $result;
670 }
671
672 /**
673 * Get user login URL for hosting CMS (method declared in each CMS system class)
674 *
675 * @param string $destination - if present, add destination to querystring (works for Drupal only)
676 *
677 * @return string - loginURL for the current CMS
678 * @static
679 */
680 public function getLoginURL($destination = '') {
681 $config = CRM_Core_Config::singleton();
682 $loginURL = $config->userFrameworkBaseURL;
683 $loginURL = str_replace('administrator/', '', $loginURL);
684 $loginURL .= 'index.php?option=com_users&view=login';
685 return $loginURL;
686 }
687
688 public function getLoginDestination(&$form) {
689 return;
690 }
691 }
692