Merge pull request #6160 from eileenmcnaughton/CRM-16737
[civicrm-core.git] / CRM / Utils / System / Joomla.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36/**
37 * Joomla specific stuff goes here
38 */
39class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
40 /**
41 */
42 public function __construct() {
43 /**
44 * 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
45 * functions and leave the codebase oblivious to the type of CMS
46 * @deprecated
47 * @var bool
48 */
49 $this->is_drupal = FALSE;
50 }
51
52 /**
53 * @inheritDoc
54 */
55 public function createUser(&$params, $mail) {
56 $baseDir = JPATH_SITE;
57 require_once $baseDir . '/components/com_users/models/registration.php';
58
59 $userParams = JComponentHelper::getParams('com_users');
60 $model = new UsersModelRegistration();
61 $ufID = NULL;
62
63 // get the default usertype
64 $userType = $userParams->get('new_usertype');
65 if (!$userType) {
66 $userType = 2;
67 }
68
69 if (isset($params['name'])) {
70 $fullname = trim($params['name']);
71 }
72 elseif (isset($params['contactID'])) {
73 $fullname = trim(CRM_Contact_BAO_Contact::displayName($params['contactID']));
74 }
75 else {
76 $fullname = trim($params['cms_name']);
77 }
78
79 // Prepare the values for a new Joomla user.
80 $values = array();
81 $values['name'] = $fullname;
82 $values['username'] = trim($params['cms_name']);
83 $values['password1'] = $values['password2'] = $params['cms_pass'];
84 $values['email1'] = $values['email2'] = trim($params[$mail]);
85
86 $lang = JFactory::getLanguage();
87 $lang->load('com_users', $baseDir);
88
89 $register = $model->register($values);
90
91 $ufID = JUserHelper::getUserId($values['username']);
92 return $ufID;
93 }
94
95 /**
96 * @inheritDoc
97 */
98 public function updateCMSName($ufID, $ufName) {
99 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
100 $ufName = CRM_Utils_Type::escape($ufName, 'String');
101
102 $values = array();
103 $user = JUser::getInstance($ufID);
104
105 $values['email'] = $ufName;
106 $user->bind($values);
107
108 $user->save();
109 }
110
111 /**
112 * Check if username and email exists in the drupal db.
113 *
114 * @param array $params
115 * Array of name and mail values.
116 * @param array $errors
117 * Array of errors.
118 * @param string $emailName
119 * Field label for the 'email'.
120 *
121 * @return void
122 */
123 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
124 $config = CRM_Core_Config::singleton();
125
126 $dao = new CRM_Core_DAO();
127 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
128 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
129 //don't allow the special characters and min. username length is two
130 //regex \\ to match a single backslash would become '/\\\\/'
131 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
132 if ($isNotValid || strlen($name) < 2) {
133 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
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 * @inheritDoc
170 */
171 public function setTitle($title, $pageTitle = NULL) {
172 if (!$pageTitle) {
173 $pageTitle = $title;
174 }
175
176 $template = CRM_Core_Smarty::singleton();
177 $template->assign('pageTitle', $pageTitle);
178
179 $document = JFactory::getDocument();
180 $document->setTitle($title);
181 }
182
183 /**
184 * @inheritDoc
185 */
186 public function appendBreadCrumb($breadCrumbs) {
187 $template = CRM_Core_Smarty::singleton();
188 $bc = $template->get_template_vars('breadcrumb');
189
190 if (is_array($breadCrumbs)) {
191 foreach ($breadCrumbs as $crumbs) {
192 if (stripos($crumbs['url'], 'id%%')) {
193 $args = array('cid', 'mid');
194 foreach ($args as $a) {
195 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
196 FALSE, NULL, $_GET
197 );
198 if ($val) {
199 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
200 }
201 }
202 }
203 $bc[] = $crumbs;
204 }
205 }
206 $template->assign_by_ref('breadcrumb', $bc);
207 }
208
209 /**
210 * @inheritDoc
211 */
212 public function resetBreadCrumb() {
213 }
214
215 /**
216 * @inheritDoc
217 */
218 public function addHTMLHead($string = NULL) {
219 if ($string) {
220 $document = JFactory::getDocument();
221 $document->addCustomTag($string);
222 }
223 }
224
225 /**
226 * @inheritDoc
227 */
228 public function addStyleUrl($url, $region) {
229 if ($region == 'html-header') {
230 $document = JFactory::getDocument();
231 $document->addStyleSheet($url);
232 return TRUE;
233 }
234 return FALSE;
235 }
236
237 /**
238 * @inheritDoc
239 */
240 public function addStyle($code, $region) {
241 if ($region == 'html-header') {
242 $document = JFactory::getDocument();
243 $document->addStyleDeclaration($code);
244 return TRUE;
245 }
246 return FALSE;
247 }
248
249 /**
250 * @inheritDoc
251 */
252 public function url(
253 $path = NULL,
254 $query = NULL,
255 $absolute = FALSE,
256 $fragment = NULL,
257 $htmlize = TRUE,
258 $frontend = FALSE,
259 $forceBackend = FALSE
260 ) {
261 $config = CRM_Core_Config::singleton();
262 $separator = $htmlize ? '&amp;' : '&';
263 $Itemid = '';
264 $script = '';
265 $path = CRM_Utils_String::stripPathChars($path);
266
267 if ($config->userFrameworkFrontend) {
268 $script = 'index.php';
269 if (JRequest::getVar("Itemid")) {
270 $Itemid = "{$separator}Itemid=" . JRequest::getVar("Itemid");
271 }
272 }
273
274 if (isset($fragment)) {
275 $fragment = '#' . $fragment;
276 }
277
278 if (!isset($config->useFrameworkRelativeBase)) {
279 $base = parse_url($config->userFrameworkBaseURL);
280 $config->useFrameworkRelativeBase = $base['path'];
281 }
282 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
283
284 if (!empty($query)) {
285 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
286 }
287 else {
288 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
289 }
290
291 // gross hack for joomla, we are in the backend and want to send a frontend url
292 if ($frontend && $config->userFramework == 'Joomla') {
293 // handle both joomla v1.5 and v1.6, CRM-7939
294 $url = str_replace('/administrator/index2.php', '/index.php', $url);
295 $url = str_replace('/administrator/index.php', '/index.php', $url);
296
297 // CRM-8215
298 $url = str_replace('/administrator/', '/index.php', $url);
299 }
300 elseif ($forceBackend) {
301 if (defined('JVERSION')) {
302 $joomlaVersion = JVERSION;
303 }
304 else {
305 $jversion = new JVersion();
306 $joomlaVersion = $jversion->getShortVersion();
307 }
308
309 if (version_compare($joomlaVersion, '1.6') >= 0) {
310 $url = str_replace('/index.php', '/administrator/index.php', $url);
311 }
312 }
313 return $url;
314 }
315
316 /**
317 * Set the email address of the user.
318 *
319 * @param object $user
320 * Handle to the user object.
321 *
322 * @return void
323 */
324 public function setEmail(&$user) {
325 global $database;
326 $query = "SELECT email FROM #__users WHERE id='$user->id'";
327 $database->setQuery($query);
328 $user->email = $database->loadResult();
329 }
330
331 /**
332 * @inheritDoc
333 */
334 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
335 require_once 'DB.php';
336
337 $config = CRM_Core_Config::singleton();
338 $user = NULL;
339
340 if ($loadCMSBootstrap) {
341 $bootStrapParams = array();
342 if ($name && $password) {
343 $bootStrapParams = array(
344 'name' => $name,
345 'pass' => $password,
346 );
347 }
348 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
349 }
350
351 jimport('joomla.application.component.helper');
352 jimport('joomla.database.table');
353 jimport('joomla.user.helper');
354
355 $JUserTable = JTable::getInstance('User', 'JTable');
356
357 $db = $JUserTable->getDbo();
358 $query = $db->getQuery(TRUE);
359 $query->select('id, name, username, email, password');
360 $query->from($JUserTable->getTableName());
361 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
362 $db->setQuery($query, 0, 0);
363 $users = $db->loadObjectList();
364
365 $row = array();
366 if (count($users)) {
367 $row = $users[0];
368 }
369
370 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
371 if (!defined('JVERSION')) {
372 require $joomlaBase . '/libraries/cms/version/version.php';
373 $jversion = new JVersion();
374 define('JVERSION', $jversion->getShortVersion());
375 }
376
377 if (!empty($row)) {
378 $dbPassword = $row->password;
379 $dbId = $row->id;
380 $dbEmail = $row->email;
381
382 if (version_compare(JVERSION, '2.5.18', 'lt') ||
383 (version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt'))
384 ) {
385 // now check password
386 if (strpos($dbPassword, ':') === FALSE) {
387 if ($dbPassword != md5($password)) {
388 return FALSE;
389 }
390 }
391 else {
392 list($hash, $salt) = explode(':', $dbPassword);
393 $cryptpass = md5($password . $salt);
394 if ($hash != $cryptpass) {
395 return FALSE;
396 }
397 }
398 }
399 else {
400 if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) {
401 return FALSE;
402 }
403
404 //include additional files required by Joomla 3.2.1+
405 if (version_compare(JVERSION, '3.2.1', 'ge')) {
406 require_once $joomlaBase . '/libraries/cms/application/helper.php';
407 require_once $joomlaBase . '/libraries/cms/application/cms.php';
408 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
409 }
410 }
411
412 CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
413 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
414 if (!$contactID) {
415 return FALSE;
416 }
417 return array($contactID, $dbId, mt_rand());
418 }
419
420 return FALSE;
421 }
422
423 /**
424 * Set a init session with user object.
425 *
426 * @param array $data
427 * Array with user specific data.
428 */
429 public function setUserSession($data) {
430 list($userID, $ufID) = $data;
431 $user = new JUser($ufID);
432 $session = JFactory::getSession();
433 $session->set('user', $user);
434
435 parent::setUserSession($data);
436 }
437
438 /**
439 * FIXME: Do something
440 */
441 public function setMessage($message) {
442 }
443
444 /**
445 * FIXME: Do something
446 */
447 public function loadUser($user) {
448 return TRUE;
449 }
450
451 /**
452 * FIXME: Use CMS-native approach
453 */
454 public function permissionDenied() {
455 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
456 }
457
458 /**
459 * @inheritDoc
460 */
461 public function logout() {
462 session_destroy();
463 header("Location:index.php");
464 }
465
466 /**
467 * @inheritDoc
468 */
469 public function getUFLocale() {
470 if (defined('_JEXEC')) {
471 $conf = JFactory::getConfig();
472 $locale = $conf->get('language');
473 return str_replace('-', '_', $locale);
474 }
475 return NULL;
476 }
477
478 /**
479 * @inheritDoc
480 */
481 public function getVersion() {
482 if (class_exists('JVersion')) {
483 $version = new JVersion();
484 return $version->getShortVersion();
485 }
486 else {
487 return 'Unknown';
488 }
489 }
490
491 /**
492 * Load joomla bootstrap.
493 *
494 * @param array $params
495 * with uid or name and password.
496 * @param bool $loadUser
497 * load cms user?.
498 * @param bool|\throw $throwError throw error on failure?
499 * @param null $realPath
500 * @param bool $loadDefines
501 *
502 * @return bool
503 */
504 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
505 // Setup the base path related constant.
506 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
507
508 // load BootStrap here if needed
509 // We are a valid Joomla entry point.
510 if (!defined('_JEXEC') && $loadDefines) {
511 define('_JEXEC', 1);
512 define('DS', DIRECTORY_SEPARATOR);
513 define('JPATH_BASE', $joomlaBase . '/administrator');
514 require $joomlaBase . '/administrator/includes/defines.php';
515 }
516
517 // Get the framework.
518 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
519 require $joomlaBase . '/libraries/import.legacy.php';
520 }
521 require $joomlaBase . '/libraries/import.php';
522 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
523 require $joomlaBase . '/configuration.php';
524
525 // Files may be in different places depending on Joomla version
526 if (!defined('JVERSION')) {
527 require $joomlaBase . '/libraries/cms/version/version.php';
528 $jversion = new JVersion();
529 define('JVERSION', $jversion->getShortVersion());
530 }
531
532 if (version_compare(JVERSION, '3.0', 'lt')) {
533 require $joomlaBase . '/libraries/joomla/environment/uri.php';
534 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
535 }
536 else {
537 require $joomlaBase . '/libraries/cms.php';
538 require $joomlaBase . '/libraries/joomla/uri/uri.php';
539 }
540
541 jimport('joomla.application.cli');
542
543 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
544 $config = CRM_Core_Config::singleton();
545 CRM_Utils_Hook::config($config);
546
547 return TRUE;
548 }
549
550 /**
551 * @inheritDoc
552 */
553 public function isUserLoggedIn() {
554 $user = JFactory::getUser();
555 return ($user->guest) ? FALSE : TRUE;
556 }
557
558 /**
559 * @inheritDoc
560 */
561 public function getLoggedInUfID() {
562 $user = JFactory::getUser();
563 return ($user->guest) ? NULL : $user->id;
564 }
565
566 /**
567 * @inheritDoc
568 */
569 public function getLoggedInUniqueIdentifier() {
570 $user = JFactory::getUser();
571 return $this->getUniqueIdentifierFromUserObject($user);
572 }
573
574 /**
575 * @inheritDoc
576 */
577 public function getUserIDFromUserObject($user) {
578 return !empty($user->id) ? $user->id : NULL;
579 }
580
581 /**
582 * @inheritDoc
583 */
584 public function getUniqueIdentifierFromUserObject($user) {
585 return ($user->guest) ? NULL : $user->email;
586 }
587
588 /**
589 * Get a list of all installed modules, including enabled and disabled ones
590 *
591 * @return array
592 * CRM_Core_Module
593 */
594 public function getModules() {
595 $result = array();
596
597 $db = JFactory::getDbo();
598 $query = $db->getQuery(TRUE);
599 $query->select('type, folder, element, enabled')
600 ->from('#__extensions')
601 ->where('type =' . $db->Quote('plugin'));
602 $plugins = $db->setQuery($query)->loadAssocList();
603 foreach ($plugins as $plugin) {
604 // question: is the folder really a critical part of the plugin's name?
605 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
606 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
607 }
608
609 return $result;
610 }
611
612 /**
613 * @inheritDoc
614 */
615 public function getLoginURL($destination = '') {
616 $config = CRM_Core_Config::singleton();
617 $loginURL = $config->userFrameworkBaseURL;
618 $loginURL = str_replace('administrator/', '', $loginURL);
619 $loginURL .= 'index.php?option=com_users&view=login';
620
621 //CRM-14872 append destination
622 if (!empty($destination)) {
623 $loginURL .= '&return=' . urlencode(base64_encode($destination));
624 }
625 return $loginURL;
626 }
627
628 /**
629 * @inheritDoc
630 */
631 public function getLoginDestination(&$form) {
632 $args = NULL;
633
634 $id = $form->get('id');
635 if ($id) {
636 $args .= "&id=$id";
637 }
638 else {
639 $gid = $form->get('gid');
640 if ($gid) {
641 $args .= "&gid=$gid";
642 }
643 else {
644 // Setup Personal Campaign Page link uses pageId
645 $pageId = $form->get('pageId');
646 if ($pageId) {
647 $component = $form->get('component');
648 $args .= "&pageId=$pageId&component=$component&action=add";
649 }
650 }
651 }
652
653 $destination = NULL;
654 if ($args) {
655 // append destination so user is returned to form they came from after login
656 $args = 'reset=1' . $args;
657 $destination = CRM_Utils_System::url(CRM_Utils_System::currentPath(), $args, TRUE, NULL, TRUE, TRUE);
658 }
659
660 return $destination;
661 }
662
663 /**
664 * @inheritDoc
665 */
666 public function getDefaultSiteSettings($dir) {
667 $config = CRM_Core_Config::singleton();
668 $url = preg_replace(
669 '|/administrator|',
670 '',
671 $config->userFrameworkBaseURL
672 );
673 $siteRoot = preg_replace(
674 '|/media/civicrm/.*$|',
675 '',
676 $config->imageUploadDir
677 );
678 return array($url, NULL, $siteRoot);
679 }
680
681 /**
682 * @inheritDoc
683 */
684 public function getUserRecordUrl($contactID) {
685 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
686 $userRecordUrl = NULL;
687 // if logged in user is super user, then he can view other users joomla profile
688 if (JFactory::getUser()->authorise('core.admin')) {
689 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
690 }
691 elseif (CRM_Core_Session::singleton()->get('userID') == $contactID) {
692 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
693 }
694 }
695
696 /**
697 * @inheritDoc
698 */
699 public function checkPermissionAddUser() {
700 if (JFactory::getUser()->authorise('core.create', 'com_users')) {
701 return TRUE;
702 }
703 }
704
705 /**
706 * Output code from error function.
707 * @param string $content
708 */
709 public function outputError($content) {
710 if (class_exists('JErrorPage')) {
711 $error = new Exception($content);
712 JErrorPage::render($error);
713 }
714 elseif (class_exists('JError')) {
715 JError::raiseError('CiviCRM-001', $content);
716 }
717 else {
718 parent::outputError($content);
719 }
720 }
721
722 /**
723 * Append Joomla js to coreResourcesList.
724 */
725 public function appendCoreResources(&$list) {
726 $list[] = 'js/crm.joomla.js';
727 }
728
729}