Merge pull request #2916 from NileemaJadhav/HR-13-fix
[civicrm-core.git] / CRM / Utils / System / Joomla.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 $user = NULL;
460
461 if ($loadCMSBootstrap) {
462 $bootStrapParams = array();
463 if ($name && $password) {
464 $bootStrapParams = array(
465 'name' => $name,
466 'pass' => $password,
467 );
468 }
469 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
470 }
471
472 jimport('joomla.application.component.helper');
473 jimport('joomla.database.table');
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 }
490
491 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
492 if ( !defined('JVERSION') ) {
493 require $joomlaBase . '/libraries/cms/version/version.php';
494 $jversion = new JVersion;
495 define('JVERSION', $jversion->getShortVersion());
496 }
497
498 if (!empty($row)) {
499 $dbPassword = $row->password;
500 $dbId = $row->id;
501 $dbEmail = $row->email;
502
503 if ( version_compare(JVERSION, '2.5.18', 'lt') ||
504 ( version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt') )
505 ) {
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 }
518 }
519 }
520 else {
521 if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) return FALSE;
522
523 //include additional files required by Joomla 3.2.1+
524 if ( version_compare(JVERSION, '3.2.1', 'ge') ) {
525 require $joomlaBase . '/libraries/cms/application/helper.php';
526 require $joomlaBase . '/libraries/cms/application/cms.php';
527 require $joomlaBase . '/libraries/cms/application/administrator.php';
528 }
529 }
530
531 CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
532 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
533 if (!$contactID) {
534 return FALSE;
535 }
536 return array($contactID, $dbId, mt_rand());
537 }
538
539 return FALSE;
540 }
541
542 /**
543 * Set a init session with user object
544 *
545 * @param array $data array with user specific data
546 *
547 * @access public
548 */
549 function setUserSession($data) {
550 list($userID, $ufID) = $data;
551 $user = new JUser( $ufID );
552 $session = JFactory::getSession();
553 $session->set('user', $user);
554
555 parent::setUserSession($data);
556 }
557
558 /**
559 * Set a message in the UF to display to a user
560 *
561 * @param string $message the message to set
562 *
563 * @access public
564 */
565 function setMessage($message) {
566 return;
567 }
568
569 function loadUser($user) {
570 return TRUE;
571 }
572
573 function permissionDenied() {
574 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
575 }
576
577 function logout() {
578 session_destroy();
579 header("Location:index.php");
580 }
581
582 /**
583 * Get the locale set in the hosting CMS
584 *
585 * @return string the used locale or null for none
586 */
587 function getUFLocale() {
588 if (defined('_JEXEC')) {
589 $conf = JFactory::getConfig();
590 $locale = $conf->get('language');
591 return str_replace('-', '_', $locale);
592 }
593 return NULL;
594 }
595
596 function getVersion() {
597 if (class_exists('JVersion')) {
598 $version = new JVersion;
599 return $version->getShortVersion();
600 }
601 else {
602 return 'Unknown';
603 }
604 }
605
606 /*
607 * load joomla bootstrap
608 *
609 * @param $params array with uid or name and password
610 * @param $loadUser boolean load cms user?
611 * @param $throwError throw error on failure?
612 */
613 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
614 // Setup the base path related constant.
615 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
616
617 // load BootStrap here if needed
618 // We are a valid Joomla entry point.
619 if ( ! defined( '_JEXEC' ) && $loadDefines ) {
620 define('_JEXEC', 1);
621 define('DS', DIRECTORY_SEPARATOR);
622 define('JPATH_BASE', $joomlaBase . '/administrator');
623 require $joomlaBase . '/administrator/includes/defines.php';
624 }
625
626 // Get the framework.
627 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
628 require $joomlaBase . '/libraries/import.legacy.php';
629 }
630 require $joomlaBase . '/libraries/import.php';
631 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
632 require $joomlaBase . '/configuration.php';
633
634 // Files may be in different places depending on Joomla version
635 if ( !defined('JVERSION') ) {
636 require $joomlaBase . '/libraries/cms/version/version.php';
637 $jversion = new JVersion;
638 define('JVERSION', $jversion->getShortVersion());
639 }
640
641 if( version_compare(JVERSION, '3.0', 'lt') ) {
642 require $joomlaBase . '/libraries/joomla/environment/uri.php';
643 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
644 }
645 else {
646 require $joomlaBase . '/libraries/joomla/uri/uri.php';
647 }
648
649 jimport('joomla.application.cli');
650
651 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
652 $config = CRM_Core_Config::singleton();
653 CRM_Utils_Hook::config($config);
654
655 return TRUE;
656 }
657
658 /**
659 * check is user logged in.
660 *
661 * @return boolean true/false.
662 */
663 public function isUserLoggedIn() {
664 $user = JFactory::getUser();
665 return ($user->guest) ? FALSE : TRUE;
666 }
667
668 /**
669 * Get currently logged in user uf id.
670 *
671 * @return int logged in user uf id.
672 */
673 public function getLoggedInUfID() {
674 $user = JFactory::getUser();
675 return ($user->guest) ? NULL : $user->id;
676 }
677
678 /**
679 * Get currently logged in user unique identifier - this tends to be the email address or user name.
680 *
681 * @return string $userID logged in user unique identifier
682 */
683 function getLoggedInUniqueIdentifier() {
684 $user = JFactory::getUser();
685 return $this->getUniqueIdentifierFromUserObject($user);
686 }
687 /**
688 * Get User ID from UserFramework system (Joomla)
689 * @param object $user object as described by the CMS
690 * @return mixed <NULL, number>
691 */
692 function getUserIDFromUserObject($user) {
693 return !empty($user->id) ? $user->id : NULL;
694 }
695
696 /**
697 * Get Unique Identifier from UserFramework system (CMS)
698 * @param object $user object as described by the User Framework
699 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
700 *
701 */
702 function getUniqueIdentifierFromUserObject($user) {
703 return ($user->guest) ? NULL : $user->email;
704 }
705
706 /**
707 * Get a list of all installed modules, including enabled and disabled ones
708 *
709 * @return array CRM_Core_Module
710 */
711 function getModules() {
712 $result = array();
713
714 $db = JFactory::getDbo();
715 $query = $db->getQuery(true);
716 $query->select('type, folder, element, enabled')
717 ->from('#__extensions')
718 ->where('type =' . $db->Quote('plugin'));
719 $plugins = $db->setQuery($query)->loadAssocList();
720 foreach ($plugins as $plugin) {
721 // question: is the folder really a critical part of the plugin's name?
722 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
723 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
724 }
725
726 return $result;
727 }
728
729 /**
730 * Get user login URL for hosting CMS (method declared in each CMS system class)
731 *
732 * @param string $destination - if present, add destination to querystring (works for Drupal only)
733 *
734 * @return string - loginURL for the current CMS
735 * @static
736 */
737 public function getLoginURL($destination = '') {
738 $config = CRM_Core_Config::singleton();
739 $loginURL = $config->userFrameworkBaseURL;
740 $loginURL = str_replace('administrator/', '', $loginURL);
741 $loginURL .= 'index.php?option=com_users&view=login';
742 return $loginURL;
743 }
744
745 public function getLoginDestination(&$form) {
746 return;
747 }
748
749 /**
750 * Return default Site Settings
751 * @return array array
752 * - $url, (Joomla - non admin url)
753 * - $siteName,
754 * - $siteRoot
755 */
756 function getDefaultSiteSettings($dir){
757 $config = CRM_Core_Config::singleton();
758 $url = preg_replace(
759 '|/administrator|',
760 '',
761 $config->userFrameworkBaseURL
762 );
763 $siteRoot = preg_replace(
764 '|/media/civicrm/.*$|',
765 '',
766 $config->imageUploadDir
767 );
768 return array($url, NULL, $siteRoot);
769 }
770 }
771