CRM-12075 make recurring contrib links frontend flagged
[civicrm-core.git] / CRM / Utils / System / Joomla.php
CommitLineData
6a488035
TO
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 */
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) {
264 if ($region == 'html-header') {
265 $document = JFactory::getDocument();
266 $document->addScript($url);
267 return TRUE;
268 }
269 return FALSE;
270 }
271
272 /**
273 * Add an inline script
274 *
275 * @param $code: string, javascript code
276 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
277 *
278 * Note: This function is not to be called directly
279 * @see CRM_Core_Region::render()
280 *
281 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
282 * @access public
283 */
284 public function addScript($code, $region) {
285 if ($region == 'html-header') {
286 $document = JFactory::getDocument();
287 $document->addScriptDeclaration($code);
288 return TRUE;
289 }
290 return FALSE;
291 }
292
293 /**
294 * Add a css file
295 *
296 * @param $url: string, absolute path to file
297 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
298 *
299 * Note: This function is not to be called directly
300 * @see CRM_Core_Region::render()
301 *
302 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
303 * @access public
304 */
305 public function addStyleUrl($url, $region) {
306 if ($region == 'html-header') {
307 $document = JFactory::getDocument();
308 $document->addStyleSheet($url);
309 return TRUE;
310 }
311 return FALSE;
312 }
313
314 /**
315 * Add an inline style
316 *
317 * @param $code: string, css code
318 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
319 *
320 * Note: This function is not to be called directly
321 * @see CRM_Core_Region::render()
322 *
323 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
324 * @access public
325 */
326 public function addStyle($code, $region) {
327 if ($region == 'html-header') {
328 $document = JFactory::getDocument();
329 $document->addStyleDeclaration($code);
330 return TRUE;
331 }
332 return FALSE;
333 }
334
335 /**
336 * Generate an internal CiviCRM URL
337 *
338 * @param $path string The path being linked to, such as "civicrm/add"
339 * @param $query string A query string to append to the link.
340 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
341 * Useful for links that will be displayed outside the site, such as in an
342 * RSS feed.
343 * @param $fragment string A fragment identifier (named anchor) to append to the link.
344 * @param $htmlize boolean whether to convert to html eqivalant
345 * @param $frontend boolean a gross joomla hack
346 *
347 * @return string an HTML string containing a link to the given path.
348 * @access public
349 *
350 */
351 function url($path = NULL, $query = NULL, $absolute = TRUE,
352 $fragment = NULL, $htmlize = TRUE,
353 $frontend = FALSE, $forceBackend = FALSE
354 ) {
355 $config = CRM_Core_Config::singleton();
356 $separator = $htmlize ? '&amp;' : '&';
357 $Itemid = '';
358 $script = '';
359 $path = CRM_Utils_String::stripPathChars($path);
360
361 if ($config->userFrameworkFrontend) {
362 $script = 'index.php';
363 if (JRequest::getVar("Itemid")) {
364 $Itemid = "{$separator}Itemid=" . JRequest::getVar("Itemid");
365 }
366 }
367
368 if (isset($fragment)) {
369 $fragment = '#' . $fragment;
370 }
371
372 if (!isset($config->useFrameworkRelativeBase)) {
373 $base = parse_url($config->userFrameworkBaseURL);
374 $config->useFrameworkRelativeBase = $base['path'];
375 }
376 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
377
378 if (!empty($query)) {
379 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
380 }
381 else {
382 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
383 }
384
385 // gross hack for joomla, we are in the backend and want to send a frontend url
386 if ($frontend && $config->userFramework == 'Joomla') {
387 // handle both joomla v1.5 and v1.6, CRM-7939
388 $url = str_replace('/administrator/index2.php', '/index.php', $url);
389 $url = str_replace('/administrator/index.php', '/index.php', $url);
390
391 // CRM-8215
392 $url = str_replace('/administrator/', '/index.php', $url);
393 }
394 elseif ($forceBackend) {
395 if (defined('JVERSION')) {
396 $joomlaVersion = JVERSION;
397 } else {
398 $jversion = new JVersion;
399 $joomlaVersion = $jversion->getShortVersion();
400 }
401
402 if (version_compare($joomlaVersion, '1.6') >= 0) {
403 $url = str_replace('/index.php', '/administrator/index.php', $url);
404 }
405 }
406 return $url;
407 }
408
409 /**
410 * rewrite various system urls to https
411 *
412 * @return void
413 * access public
414 */
415 function mapConfigToSSL() {
416 // dont need to do anything, let CMS handle their own switch to SSL
417 return;
418 }
419
420 /**
421 * figure out the post url for the form
422 *
423 * @param $action the default action if one is pre-specified
424 *
425 * @return string the url to post the form
426 * @access public
427 */
428 function postURL($action) {
429 if (!empty($action)) {
430 return $action;
431 }
432
433 return $this->url(CRM_Utils_Array::value('task', $_GET),
434 NULL, TRUE, NULL, FALSE
435 );
436 }
437
438 /**
439 * Function to set the email address of the user
440 *
441 * @param object $user handle to the user object
442 *
443 * @return void
444 * @access public
445 */
446 function setEmail(&$user) {
447 global $database;
448 $query = "SELECT email FROM #__users WHERE id='$user->id'";
449 $database->setQuery($query);
450 $user->email = $database->loadResult();
451 }
452
453 /**
454 * Authenticate the user against the joomla db
455 *
456 * @param string $name the user name
457 * @param string $password the password for the above user name
458 * @param $loadCMSBootstrap boolean load cms bootstrap?
459 *
460 * @return mixed false if no auth
461 * array(
462 contactID, ufID, unique string ) if success
463 * @access public
464 */
465 function authenticate($name, $password, $loadCMSBootstrap = FALSE) {
466 require_once 'DB.php';
467
468 $config = CRM_Core_Config::singleton();
469
470 if ($loadCMSBootstrap) {
471 $bootStrapParams = array();
472 if ($name && $password) {
473 $bootStrapParams = array(
474 'name' => $name,
475 'pass' => $password,
476 );
477 }
478 CRM_Utils_System::loadBootStrap($bootStrapParams);
479 }
480
481 jimport('joomla.application.component.helper');
482 jimport('joomla.database.table');
483
484 $JUserTable = &JTable::getInstance('User', 'JTable');
485
486 $db = $JUserTable->getDbo();
487 $query = $db->getQuery(TRUE);
488 $query->select('id, username, email, password');
489 $query->from($JUserTable->getTableName());
490 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
491 $db->setQuery($query, 0, 0);
492 $users = $db->loadAssocList();
493
494 $row = array();;
495 if (count($users)) {
496 $row = $users[0];
497 }
498
499 $user = NULL;
500 if (!empty($row)) {
501 $dbPassword = CRM_Utils_Array::value('password', $row);
502 $dbId = CRM_Utils_Array::value('id', $row);
503 $dbEmail = CRM_Utils_Array::value('email', $row);
504
505 // now check password
506 if (strpos($dbPassword, ':') === FALSE) {
507 if ($dbPassword != md5($password)) {
508 return FALSE;
509 }
510 }
511 else {
512 list($hash, $salt) = explode(':', $dbPassword);
513 $cryptpass = md5($password . $salt);
514 if ($hash != $cryptpass) {
515 return FALSE;
516 }
517 }
518
519 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $dbId, $dbEmail, 'Joomla');
520 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
521 if (!$contactID) {
522 return FALSE;
523 }
524 return array($contactID, $dbId, mt_rand());
525 }
526 return FALSE;
527 }
528
529 /**
530 * Set a message in the UF to display to a user
531 *
532 * @param string $message the message to set
533 *
534 * @access public
535 */
536 function setMessage($message) {
537 return;
538 }
539
540 function loadUser($user) {
541 return TRUE;
542 }
543
544 function permissionDenied() {
545 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
546 }
547
548 function logout() {
549 session_destroy();
550 header("Location:index.php");
551 }
552
553 /**
554 * Get the locale set in the hosting CMS
555 *
556 * @return string the used locale or null for none
557 */
558 function getUFLocale() {
559 if (defined('_JEXEC')) {
560 $conf = JFactory::getConfig();
561 $locale = $conf->getValue('config.language');
562 return str_replace('-', '_', $locale);
563 }
564 return NULL;
565 }
566
567 function getVersion() {
568 if (class_exists('JVersion')) {
569 $version = new JVersion;
570 return $version->getShortVersion();
571 }
572 else {
573 return 'Unknown';
574 }
575 }
576
577 /*
578 * load joomla bootstrap
579 *
580 * @param $params array with uid or name and password
581 * @param $loadUser boolean load cms user?
582 * @param $throwError throw error on failure?
583 */
584 function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE) {
585 // Setup the base path related constant.
586 $joomlaBase = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
587
588 // load BootStrap here if needed
589 // We are a valid Joomla entry point.
590 if ( ! defined( '_JEXEC' ) ) {
591 define('_JEXEC', 1);
592 define('DS', DIRECTORY_SEPARATOR);
593 define('JPATH_BASE', $joomlaBase . '/administrator');
594 require $joomlaBase . '/administrator/includes/defines.php';
595 }
596
597 // Get the framework.
598 require $joomlaBase . '/libraries/import.php';
599 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
600 require $joomlaBase . '/libraries/joomla/environment/uri.php';
601 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
602 require $joomlaBase . '/configuration.php';
603
604 jimport('joomla.application.cli');
605
606 return TRUE;
607 }
608
609 /**
610 * check is user logged in.
611 *
612 * @return boolean true/false.
613 */
614 public function isUserLoggedIn() {
615 $user = JFactory::getUser();
616 return ($user->guest) ? FALSE : TRUE;
617 }
618
619 /**
620 * Get currently logged in user uf id.
621 *
622 * @return int logged in user uf id.
623 */
624 public function getLoggedInUfID() {
625 $user = JFactory::getUser();
626 return ($user->guest) ? NULL : $user->id;
627 }
628
629 /**
630 * Get a list of all installed modules, including enabled and disabled ones
631 *
632 * @return array CRM_Core_Module
633 */
634 function getModules() {
635 $result = array();
636
637 $db = JFactory::getDbo();
638 $query = $db->getQuery(true);
639 $query->select('type, folder, element, enabled')
640 ->from('#__extensions')
641 ->where('type =' . $db->Quote('plugin'));
642 $plugins = $db->setQuery($query)->loadAssocList();
643 foreach ($plugins as $plugin) {
644 // question: is the folder really a critical part of the plugin's name?
645 $name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
646 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
647 }
648
649 return $result;
650 }
651
652 /**
653 * Get user login URL for hosting CMS (method declared in each CMS system class)
654 *
655 * @param string $destination - if present, add destination to querystring (works for Drupal only)
656 *
657 * @return string - loginURL for the current CMS
658 * @static
659 */
660 public function getLoginURL($destination = '') {
661 $config = CRM_Core_Config::singleton();
662 $loginURL = $config->userFrameworkBaseURL;
663 $loginURL = str_replace('administrator/', '', $loginURL);
664 $loginURL .= 'index.php?option=com_users&view=login';
665 return $loginURL;
666 }
667
668 public function getLoginDestination(&$form) {
669 return;
670 }
671}
672