Merge pull request #17526 from mattwire/frontendrequiredpaymentfrequency
[civicrm-core.git] / CRM / Utils / System / Joomla.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
b8c71ffa 19 * Joomla specific stuff goes here.
6a488035
TO
20 */
21class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
6714d8d2 22
bb3a214a 23 /**
b8c71ffa 24 * Class constructor.
bb3a214a 25 */
00be9182 26 public function __construct() {
4caaa696
EM
27 /**
28 * 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
29 * functions and leave the codebase oblivious to the type of CMS
30 * @deprecated
31 * @var bool
32 */
6a488035
TO
33 $this->is_drupal = FALSE;
34 }
35
36 /**
17f443df 37 * @inheritDoc
6a488035 38 */
00be9182 39 public function createUser(&$params, $mail) {
6a488035
TO
40 $baseDir = JPATH_SITE;
41 require_once $baseDir . '/components/com_users/models/registration.php';
42
43 $userParams = JComponentHelper::getParams('com_users');
353ffa53
TO
44 $model = new UsersModelRegistration();
45 $ufID = NULL;
6a488035
TO
46
47 // get the default usertype
48 $userType = $userParams->get('new_usertype');
49 if (!$userType) {
50 $userType = 2;
51 }
52
53 if (isset($params['name'])) {
54 $fullname = trim($params['name']);
55 }
56 elseif (isset($params['contactID'])) {
57 $fullname = trim(CRM_Contact_BAO_Contact::displayName($params['contactID']));
58 }
59 else {
60 $fullname = trim($params['cms_name']);
61 }
62
63 // Prepare the values for a new Joomla user.
be2fb01f 64 $values = [];
353ffa53
TO
65 $values['name'] = $fullname;
66 $values['username'] = trim($params['cms_name']);
6a488035 67 $values['password1'] = $values['password2'] = $params['cms_pass'];
353ffa53 68 $values['email1'] = $values['email2'] = trim($params[$mail]);
6a488035
TO
69
70 $lang = JFactory::getLanguage();
71 $lang->load('com_users', $baseDir);
72
73 $register = $model->register($values);
74
75 $ufID = JUserHelper::getUserId($values['username']);
76 return $ufID;
77 }
78
f4aaa82a 79 /**
17f443df 80 * @inheritDoc
6a488035 81 */
00be9182 82 public function updateCMSName($ufID, $ufName) {
6a488035
TO
83 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
84 $ufName = CRM_Utils_Type::escape($ufName, 'String');
85
be2fb01f 86 $values = [];
e851ce06 87 $user = JUser::getInstance($ufID);
6a488035
TO
88
89 $values['email'] = $ufName;
90 $user->bind($values);
91
92 $user->save();
93 }
94
95 /**
94f9f81a 96 * Check if username and email exists in the Joomla db.
6a488035 97 *
77855840
TO
98 * @param array $params
99 * Array of name and mail values.
100 * @param array $errors
101 * Array of errors.
102 * @param string $emailName
103 * Field label for the 'email'.
6a488035 104 */
00be9182 105 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
106 $config = CRM_Core_Config::singleton();
107
353ffa53
TO
108 $dao = new CRM_Core_DAO();
109 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
6a488035
TO
110 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
111 //don't allow the special characters and min. username length is two
112 //regex \\ to match a single backslash would become '/\\\\/'
113 $isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
114 if ($isNotValid || strlen($name) < 2) {
115 $errors['cms_name'] = ts('Your username contains invalid characters or is too short');
116 }
117
6a488035
TO
118 $JUserTable = &JTable::getInstance('User', 'JTable');
119
120 $db = $JUserTable->getDbo();
121 $query = $db->getQuery(TRUE);
122 $query->select('username, email');
123 $query->from($JUserTable->getTableName());
b27d1855 124
125 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
6a488035
TO
126 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
127 $db->setQuery($query, 0, 10);
128 $users = $db->loadAssocList();
129
be2fb01f 130 $row = [];
6a488035
TO
131 if (count($users)) {
132 $row = $users[0];
133 }
134
135 if (!empty($row)) {
9c1bc317
CW
136 $dbName = $row['username'] ?? NULL;
137 $dbEmail = $row['email'] ?? NULL;
6a488035
TO
138 if (strtolower($dbName) == strtolower($name)) {
139 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
be2fb01f 140 [1 => $name]
6a488035
TO
141 );
142 }
143 if (strtolower($dbEmail) == strtolower($email)) {
144 $resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL) . 'index.php?option=com_users&view=reset';
89374eb2 145 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
be2fb01f 146 [1 => $email, 2 => $resetUrl]
6a488035
TO
147 );
148 }
149 }
150 }
151
152 /**
17f443df 153 * @inheritDoc
6a488035 154 */
00be9182 155 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
156 if (!$pageTitle) {
157 $pageTitle = $title;
158 }
159
160 $template = CRM_Core_Smarty::singleton();
161 $template->assign('pageTitle', $pageTitle);
162
163 $document = JFactory::getDocument();
164 $document->setTitle($title);
6a488035
TO
165 }
166
167 /**
17f443df 168 * @inheritDoc
6a488035 169 */
00be9182 170 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
171 $template = CRM_Core_Smarty::singleton();
172 $bc = $template->get_template_vars('breadcrumb');
173
174 if (is_array($breadCrumbs)) {
175 foreach ($breadCrumbs as $crumbs) {
176 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 177 $args = ['cid', 'mid'];
6a488035
TO
178 foreach ($args as $a) {
179 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
180 FALSE, NULL, $_GET
181 );
182 if ($val) {
183 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
184 }
185 }
186 }
187 $bc[] = $crumbs;
188 }
189 }
190 $template->assign_by_ref('breadcrumb', $bc);
6a488035
TO
191 }
192
193 /**
17f443df 194 * @inheritDoc
6a488035 195 */
00be9182 196 public function resetBreadCrumb() {
6a488035
TO
197 }
198
199 /**
17f443df 200 * @inheritDoc
6a488035 201 */
17f443df 202 public function addHTMLHead($string = NULL) {
6a488035
TO
203 if ($string) {
204 $document = JFactory::getDocument();
205 $document->addCustomTag($string);
206 }
207 }
208
209 /**
17f443df 210 * @inheritDoc
6a488035
TO
211 */
212 public function addStyleUrl($url, $region) {
213 if ($region == 'html-header') {
214 $document = JFactory::getDocument();
215 $document->addStyleSheet($url);
216 return TRUE;
217 }
218 return FALSE;
219 }
220
221 /**
17f443df 222 * @inheritDoc
6a488035
TO
223 */
224 public function addStyle($code, $region) {
225 if ($region == 'html-header') {
226 $document = JFactory::getDocument();
227 $document->addStyleDeclaration($code);
228 return TRUE;
229 }
230 return FALSE;
231 }
232
233 /**
17f443df 234 * @inheritDoc
6a488035 235 */
e7483cbe 236 public function url(
17f443df
CW
237 $path = NULL,
238 $query = NULL,
239 $absolute = FALSE,
240 $fragment = NULL,
17f443df 241 $frontend = FALSE,
8de2a34e
SL
242 $forceBackend = FALSE,
243 $htmlize = TRUE
6a488035 244 ) {
353ffa53 245 $config = CRM_Core_Config::singleton();
c80e2dbf 246 $separator = '&';
353ffa53
TO
247 $Itemid = '';
248 $script = '';
249 $path = CRM_Utils_String::stripPathChars($path);
6a488035
TO
250
251 if ($config->userFrameworkFrontend) {
252 $script = 'index.php';
92b78d1d
AT
253
254 // Get Itemid using JInput::get()
255 $input = Joomla\CMS\Factory::getApplication()->input;
256 $itemIdNum = $input->get("Itemid");
257 if ($itemIdNum && (strpos($path, 'civicrm/payment/ipn') === FALSE)) {
258 $Itemid = "{$separator}Itemid=" . $itemIdNum;
6a488035
TO
259 }
260 }
261
262 if (isset($fragment)) {
263 $fragment = '#' . $fragment;
264 }
265
6a488035
TO
266 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
267
268 if (!empty($query)) {
269 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
270 }
271 else {
272 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
273 }
274
275 // gross hack for joomla, we are in the backend and want to send a frontend url
276 if ($frontend && $config->userFramework == 'Joomla') {
277 // handle both joomla v1.5 and v1.6, CRM-7939
278 $url = str_replace('/administrator/index2.php', '/index.php', $url);
279 $url = str_replace('/administrator/index.php', '/index.php', $url);
280
281 // CRM-8215
282 $url = str_replace('/administrator/', '/index.php', $url);
283 }
284 elseif ($forceBackend) {
285 if (defined('JVERSION')) {
286 $joomlaVersion = JVERSION;
0db6c3e1
TO
287 }
288 else {
e7483cbe 289 $jversion = new JVersion();
6a488035
TO
290 $joomlaVersion = $jversion->getShortVersion();
291 }
292
293 if (version_compare($joomlaVersion, '1.6') >= 0) {
294 $url = str_replace('/index.php', '/administrator/index.php', $url);
295 }
296 }
297 return $url;
298 }
299
6a488035 300 /**
fe482240 301 * Set the email address of the user.
6a488035 302 *
77855840
TO
303 * @param object $user
304 * Handle to the user object.
6a488035 305 */
00be9182 306 public function setEmail(&$user) {
6a488035 307 global $database;
94f9f81a
EW
308 $query = $db->getQuery(TRUE);
309 $query->select($db->quoteName('email'))
6714d8d2
SL
310 ->from($db->quoteName('#__users'))
311 ->where($db->quoteName('id') . ' = ' . $user->id);
6a488035
TO
312 $database->setQuery($query);
313 $user->email = $database->loadResult();
314 }
315
316 /**
17f443df 317 * @inheritDoc
6a488035 318 */
17f443df 319 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
320 require_once 'DB.php';
321
322 $config = CRM_Core_Config::singleton();
ebc28bab 323 $user = NULL;
6a488035
TO
324
325 if ($loadCMSBootstrap) {
be2fb01f 326 $bootStrapParams = [];
6a488035 327 if ($name && $password) {
be2fb01f 328 $bootStrapParams = [
6a488035
TO
329 'name' => $name,
330 'pass' => $password,
be2fb01f 331 ];
6a488035 332 }
bec3fc7c 333 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
6a488035
TO
334 }
335
336 jimport('joomla.application.component.helper');
337 jimport('joomla.database.table');
c1f3c6da
BS
338 jimport('joomla.user.helper');
339
340 $JUserTable = JTable::getInstance('User', 'JTable');
341
342 $db = $JUserTable->getDbo();
343 $query = $db->getQuery(TRUE);
344 $query->select('id, name, username, email, password');
345 $query->from($JUserTable->getTableName());
346 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
347 $db->setQuery($query, 0, 0);
348 $users = $db->loadObjectList();
349
be2fb01f 350 $row = [];
c1f3c6da
BS
351 if (count($users)) {
352 $row = $users[0];
353 }
6a488035 354
e1d37cef
MW
355 $joomlaBase = self::getBasePath();
356 self::getJVersion($joomlaBase);
6a488035 357
c1f3c6da
BS
358 if (!empty($row)) {
359 $dbPassword = $row->password;
360 $dbId = $row->id;
361 $dbEmail = $row->email;
6a488035 362
481a74f4
TO
363 if (version_compare(JVERSION, '2.5.18', 'lt') ||
364 (version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt'))
c1f3c6da 365 ) {
ebc28bab 366 // now check password
009eff21
EW
367 list($hash, $salt) = explode(':', $dbPassword);
368 $cryptpass = md5($password . $salt);
369 if ($hash != $cryptpass) {
01c77fa9
EW
370 return FALSE;
371 }
6a488035 372 }
c1f3c6da 373 else {
4f99ca55
TO
374 if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) {
375 return FALSE;
e7292422 376 }
9d735153 377
3a8c9bb6
MW
378 if (version_compare(JVERSION, '3.8.0', 'ge')) {
379 jimport('joomla.application.helper');
380 jimport('joomla.application.cms');
381 jimport('joomla.application.administrator');
382 }
9d735153 383 //include additional files required by Joomla 3.2.1+
3a8c9bb6 384 elseif (version_compare(JVERSION, '3.2.1', 'ge')) {
90eac10a
BS
385 require_once $joomlaBase . '/libraries/cms/application/helper.php';
386 require_once $joomlaBase . '/libraries/cms/application/cms.php';
387 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
9d735153 388 }
6a488035
TO
389 }
390
c1f3c6da 391 CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
6a488035
TO
392 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
393 if (!$contactID) {
394 return FALSE;
395 }
be2fb01f 396 return [$contactID, $dbId, mt_rand()];
6a488035 397 }
c1f3c6da 398
6a488035
TO
399 return FALSE;
400 }
401
bec3fc7c 402 /**
fe482240 403 * Set a init session with user object.
bec3fc7c 404 *
77855840
TO
405 * @param array $data
406 * Array with user specific data.
bec3fc7c 407 */
00be9182 408 public function setUserSession($data) {
bec3fc7c 409 list($userID, $ufID) = $data;
481a74f4 410 $user = new JUser($ufID);
2d8f9c75 411 $session = JFactory::getSession();
bec3fc7c
BS
412 $session->set('user', $user);
413
cb0e36de 414 parent::setUserSession($data);
bec3fc7c
BS
415 }
416
6a488035 417 /**
17f443df 418 * FIXME: Do something
ea3ddccf 419 *
420 * @param string $message
6a488035 421 */
00be9182 422 public function setMessage($message) {
6a488035
TO
423 }
424
bb3a214a 425 /**
b596c3e9 426 * @param \string $username
427 * @param \string $password
ea3ddccf 428 *
429 * @return bool
bb3a214a 430 */
b596c3e9 431 public function loadUser($username, $password = NULL) {
432 $uid = JUserHelper::getUserId($username);
433 if (empty($uid)) {
434 return FALSE;
435 }
436 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
437 if (!empty($password)) {
438 $instance = JFactory::getApplication('site');
be2fb01f 439 $params = [
b596c3e9 440 'username' => $username,
441 'password' => $password,
be2fb01f 442 ];
b596c3e9 443 //perform the login action
444 $instance->login($params);
445 }
446
8f407be0
AS
447 // Save details in Joomla session
448 $user = JFactory::getUser($uid);
449 $jsession = JFactory::getSession();
450 $jsession->set('user', $user);
451
452 // Save details in Civi session
b596c3e9 453 $session = CRM_Core_Session::singleton();
454 $session->set('ufID', $uid);
455 $session->set('userID', $contactID);
6a488035
TO
456 return TRUE;
457 }
458
17f443df
CW
459 /**
460 * FIXME: Use CMS-native approach
309310bf 461 * @throws \CRM_Core_Exception.
17f443df 462 */
00be9182 463 public function permissionDenied() {
309310bf 464 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
6a488035
TO
465 }
466
17f443df
CW
467 /**
468 * @inheritDoc
469 */
00be9182 470 public function logout() {
6a488035 471 session_destroy();
d42a224c 472 CRM_Utils_System::setHttpHeader("Location", "index.php");
6a488035
TO
473 }
474
475 /**
17f443df 476 * @inheritDoc
6a488035 477 */
00be9182 478 public function getUFLocale() {
6a488035
TO
479 if (defined('_JEXEC')) {
480 $conf = JFactory::getConfig();
4965d8e9 481 $locale = $conf->get('language');
6a488035
TO
482 return str_replace('-', '_', $locale);
483 }
484 return NULL;
485 }
486
fd1f3a26
SV
487 /**
488 * @inheritDoc
489 */
490 public function setUFLocale($civicrm_language) {
491 // TODO
492 return TRUE;
493 }
494
bb3a214a 495 /**
17f443df 496 * @inheritDoc
bb3a214a 497 */
00be9182 498 public function getVersion() {
6a488035 499 if (class_exists('JVersion')) {
e7483cbe 500 $version = new JVersion();
6a488035
TO
501 return $version->getShortVersion();
502 }
503 else {
504 return 'Unknown';
505 }
506 }
507
e1d37cef
MW
508 public function getJVersion($joomlaBase) {
509 // Files may be in different places depending on Joomla version
510 if (!defined('JVERSION')) {
511 // Joomla 3.8.0+
512 $versionPhp = $joomlaBase . '/libraries/src/Version.php';
513 if (!file_exists($versionPhp)) {
514 // Joomla < 3.8.0
515 $versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
516 }
517 require $versionPhp;
518 $jversion = new JVersion();
519 define('JVERSION', $jversion->getShortVersion());
520 }
521 }
522
f3884007
MW
523 /**
524 * Setup the base path related constant.
525 * @return mixed
526 */
e1d37cef 527 public function getBasePath() {
f3884007 528 global $civicrm_root;
e23eb52f 529 $joomlaPath = explode(DIRECTORY_SEPARATOR . 'administrator', $civicrm_root);
f3884007
MW
530 $joomlaBase = $joomlaPath[0];
531 return $joomlaBase;
e1d37cef
MW
532 }
533
f4aaa82a 534 /**
fe482240 535 * Load joomla bootstrap.
6a488035 536 *
5a4f6742
CW
537 * @param array $params
538 * with uid or name and password.
539 * @param bool $loadUser
540 * load cms user?.
f4aaa82a
EM
541 * @param bool|\throw $throwError throw error on failure?
542 * @param null $realPath
543 * @param bool $loadDefines
544 *
545 * @return bool
6a488035 546 */
be2fb01f 547 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
e1d37cef 548 $joomlaBase = self::getBasePath();
6a488035
TO
549
550 // load BootStrap here if needed
551 // We are a valid Joomla entry point.
53e972a8 552 // dev/core#1384 Use DS to ensure a correct JPATH_BASE in Windows
353ffa53 553 if (!defined('_JEXEC') && $loadDefines) {
6a488035
TO
554 define('_JEXEC', 1);
555 define('DS', DIRECTORY_SEPARATOR);
53e972a8 556 define('JPATH_BASE', $joomlaBase . DS . 'administrator');
6a488035
TO
557 require $joomlaBase . '/administrator/includes/defines.php';
558 }
559
560 // Get the framework.
2cb7adde 561 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
2efcf0c2 562 require $joomlaBase . '/libraries/import.legacy.php';
2cb7adde 563 }
3a8c9bb6 564 require $joomlaBase . '/libraries/cms.php';
e1d37cef 565 self::getJVersion($joomlaBase);
6fde79f5 566
8421b502 567 if (version_compare(JVERSION, '3.8', 'lt')) {
568 require $joomlaBase . '/libraries/import.php';
569 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
570 }
571
572 require_once $joomlaBase . '/configuration.php';
573
481a74f4 574 if (version_compare(JVERSION, '3.0', 'lt')) {
6fde79f5
BS
575 require $joomlaBase . '/libraries/joomla/environment/uri.php';
576 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
577 }
8421b502 578 elseif (version_compare(JVERSION, '3.8', 'lt')) {
3a8c9bb6 579 jimport('joomla.environment.uri');
6fde79f5
BS
580 }
581
8421b502 582 if (version_compare(JVERSION, '3.8', 'lt')) {
583 jimport('joomla.application.cli');
584 }
f4aaa82a 585
a5291777
TO
586 if (!defined('JDEBUG')) {
587 define('JDEBUG', FALSE);
588 }
26915930
MWMC
589
590 // Set timezone for Joomla on Cron
591 $config = JFactory::getConfig();
592 $timezone = $config->get('offset');
593 if ($timezone) {
594 date_default_timezone_set($timezone);
595 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
596 }
a5291777 597
182f835d 598 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
599 $config = CRM_Core_Config::singleton();
600 CRM_Utils_Hook::config($config);
6a488035
TO
601
602 return TRUE;
603 }
604
605 /**
17f443df 606 * @inheritDoc
6a488035
TO
607 */
608 public function isUserLoggedIn() {
609 $user = JFactory::getUser();
91768280 610 return !$user->guest;
6a488035
TO
611 }
612
8caad0ce 613 /**
614 * @inheritDoc
615 */
616 public function isUserRegistrationPermitted() {
617 $userParams = JComponentHelper::getParams('com_users');
618 if (!$userParams->get('allowUserRegistration')) {
619 return FALSE;
620 }
621 return TRUE;
622 }
623
63df6889
HD
624 /**
625 * @inheritDoc
626 */
1a6630be 627 public function isPasswordUserGenerated() {
63df6889
HD
628 return TRUE;
629 }
630
6a488035 631 /**
17f443df 632 * @inheritDoc
6a488035
TO
633 */
634 public function getLoggedInUfID() {
635 $user = JFactory::getUser();
636 return ($user->guest) ? NULL : $user->id;
637 }
638
2b617cb0 639 /**
17f443df 640 * @inheritDoc
2b617cb0 641 */
00be9182 642 public function getLoggedInUniqueIdentifier() {
2b617cb0
EM
643 $user = JFactory::getUser();
644 return $this->getUniqueIdentifierFromUserObject($user);
645 }
353ffa53 646
cff0c9aa
DS
647 /**
648 * @inheritDoc
649 */
650 public function getUser($contactID) {
651 $user_details = parent::getUser($contactID);
652 $user = JFactory::getUser($user_details['id']);
653 $user_details['name'] = $user->name;
654 return $user_details;
655 }
656
32998c82 657 /**
17f443df 658 * @inheritDoc
32998c82 659 */
00be9182 660 public function getUserIDFromUserObject($user) {
32998c82
EM
661 return !empty($user->id) ? $user->id : NULL;
662 }
663
2b617cb0 664 /**
17f443df 665 * @inheritDoc
2b617cb0 666 */
00be9182 667 public function getUniqueIdentifierFromUserObject($user) {
2b617cb0
EM
668 return ($user->guest) ? NULL : $user->email;
669 }
670
29864da4 671 /**
672 * @inheritDoc
673 */
674 public function getTimeZoneString() {
675 $timezone = JFactory::getConfig()->get('offset');
676 return !$timezone ? date_default_timezone_get() : $timezone;
677 }
678
6a488035
TO
679 /**
680 * Get a list of all installed modules, including enabled and disabled ones
681 *
a6c01b45
CW
682 * @return array
683 * CRM_Core_Module
6a488035 684 */
00be9182 685 public function getModules() {
be2fb01f 686 $result = [];
6a488035
TO
687
688 $db = JFactory::getDbo();
e7292422 689 $query = $db->getQuery(TRUE);
6a488035
TO
690 $query->select('type, folder, element, enabled')
691 ->from('#__extensions')
692 ->where('type =' . $db->Quote('plugin'));
693 $plugins = $db->setQuery($query)->loadAssocList();
694 foreach ($plugins as $plugin) {
695 // question: is the folder really a critical part of the plugin's name?
be2fb01f 696 $name = implode('.', ['joomla', $plugin['type'], $plugin['folder'], $plugin['element']]);
fe0dbeda 697 $result[] = new CRM_Core_Module($name, !empty($plugin['enabled']));
6a488035
TO
698 }
699
700 return $result;
701 }
702
703 /**
17f443df 704 * @inheritDoc
6a488035
TO
705 */
706 public function getLoginURL($destination = '') {
707 $config = CRM_Core_Config::singleton();
708 $loginURL = $config->userFrameworkBaseURL;
709 $loginURL = str_replace('administrator/', '', $loginURL);
710 $loginURL .= 'index.php?option=com_users&view=login';
091412ab
BS
711
712 //CRM-14872 append destination
481a74f4 713 if (!empty($destination)) {
92fcb95f 714 $loginURL .= '&return=' . urlencode(base64_encode($destination));
091412ab 715 }
6a488035
TO
716 return $loginURL;
717 }
f813f78e 718
bb3a214a 719 /**
17f443df 720 * @inheritDoc
bb3a214a 721 */
6a488035 722 public function getLoginDestination(&$form) {
091412ab
BS
723 $args = NULL;
724
725 $id = $form->get('id');
726 if ($id) {
727 $args .= "&id=$id";
728 }
729 else {
730 $gid = $form->get('gid');
731 if ($gid) {
732 $args .= "&gid=$gid";
733 }
734 else {
735 // Setup Personal Campaign Page link uses pageId
736 $pageId = $form->get('pageId');
737 if ($pageId) {
738 $component = $form->get('component');
739 $args .= "&pageId=$pageId&component=$component&action=add";
740 }
741 }
742 }
743
744 $destination = NULL;
745 if ($args) {
746 // append destination so user is returned to form they came from after login
92fcb95f 747 $args = 'reset=1' . $args;
48341e06 748 $destination = CRM_Utils_System::url(CRM_Utils_System::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
091412ab
BS
749 }
750
751 return $destination;
6a488035 752 }
9977c6f5 753
214fbc2c 754 /**
755 * Determine the location of the CMS root.
756 *
757 * @return string|NULL
758 * local file system path to CMS root, or NULL if it cannot be determined
759 */
760 public function cmsRootPath() {
a93a0366
TO
761 global $civicrm_paths;
762 if (!empty($civicrm_paths['cms.root']['path'])) {
763 return $civicrm_paths['cms.root']['path'];
764 }
765
214fbc2c 766 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
e1d37cef 767 if (file_exists("$siteRoot/administrator/index.php")) {
214fbc2c 768 return $siteRoot;
769 }
770 return NULL;
771 }
772
9977c6f5 773 /**
17f443df 774 * @inheritDoc
9977c6f5 775 */
70e8beda 776 public function getDefaultSiteSettings($dir = NULL) {
9977c6f5 777 $config = CRM_Core_Config::singleton();
778 $url = preg_replace(
779 '|/administrator|',
780 '',
781 $config->userFrameworkBaseURL
782 );
ad2d96ba 783 // CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
784 // This is the original pattern, but it doesn't work under Windows.
785 // By setting the pattern to the one used before the change first and only
786 // changing it means that the change code only affects Windows users.
787 $pattern = '|/media/civicrm/.*$|';
788 if (DIRECTORY_SEPARATOR == '\\') {
789 // This regular expression will handle Windows as well as Linux
790 // and any combination of forward and back slashes in directory
791 // separators. We only apply it if the directory separator is the one
792 // used by Windows.
793 $pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
794 }
9977c6f5 795 $siteRoot = preg_replace(
ad2d96ba 796 $pattern,
9977c6f5 797 '',
798 $config->imageUploadDir
799 );
be2fb01f 800 return [$url, NULL, $siteRoot];
9977c6f5 801 }
59f97da6
EM
802
803 /**
17f443df 804 * @inheritDoc
59f97da6 805 */
00be9182 806 public function getUserRecordUrl($contactID) {
59f97da6
EM
807 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
808 $userRecordUrl = NULL;
55904b50 809 // if logged in user has user edit access, then allow link to other users joomla profile
a8e5af2a 810 if (JFactory::getUser()->authorise('core.edit', 'com_users')) {
59f97da6
EM
811 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
812 }
813 elseif (CRM_Core_Session::singleton()->get('userID') == $contactID) {
814 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
815 }
816 }
817
818 /**
17f443df 819 * @inheritDoc
59f97da6 820 */
00be9182 821 public function checkPermissionAddUser() {
59f97da6
EM
822 if (JFactory::getUser()->authorise('core.create', 'com_users')) {
823 return TRUE;
824 }
825 }
f85b1d20 826
03d5592a
CW
827 /**
828 * @inheritDoc
829 */
830 public function synchronizeUsers() {
831 $config = CRM_Core_Config::singleton();
832 if (PHP_SAPI != 'cli') {
833 set_time_limit(300);
834 }
835 $id = 'id';
836 $mail = 'email';
837 $name = 'name';
838
839 $JUserTable = &JTable::getInstance('User', 'JTable');
840
841 $db = $JUserTable->getDbo();
842 $query = $db->getQuery(TRUE);
843 $query->select($id . ', ' . $mail . ', ' . $name);
844 $query->from($JUserTable->getTableName());
845 $query->where($mail != '');
846
847 $db->setQuery($query);
848 $users = $db->loadObjectList();
849
850 $user = new StdClass();
851 $uf = $config->userFramework;
852 $contactCount = 0;
853 $contactCreated = 0;
854 $contactMatching = 0;
855 for ($i = 0; $i < count($users); $i++) {
856 $user->$id = $users[$i]->$id;
857 $user->$mail = $users[$i]->$mail;
858 $user->$name = $users[$i]->$name;
859 $contactCount++;
860 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user,
861 $users[$i]->$id,
862 $users[$i]->$mail,
863 $uf,
864 1,
865 'Individual',
866 TRUE
867 )
868 ) {
869 $contactCreated++;
870 }
871 else {
872 $contactMatching++;
873 }
03d5592a
CW
874 }
875
be2fb01f 876 return [
03d5592a
CW
877 'contactCount' => $contactCount,
878 'contactMatching' => $contactMatching,
879 'contactCreated' => $contactCreated,
be2fb01f 880 ];
03d5592a
CW
881 }
882
38dab72a 883 /**
884 * Determine the location of the CiviCRM source tree.
885 *
886 * FIXME:
887 * 1. This was pulled out from a bigger function. It should be split
888 * into even smaller pieces and marked abstract.
889 * 2. This would be easier to compute by a calling a CMS API, but
890 * for whatever reason we take the hard way.
891 *
892 * @return array
893 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
894 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
895 */
896 public function getCiviSourceStorage() {
897 global $civicrm_root;
898 if (!defined('CIVICRM_UF_BASEURL')) {
899 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
900 }
901 $baseURL = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/');
902 if (CRM_Utils_System::isSSL()) {
903 $baseURL = str_replace('http://', 'https://', $baseURL);
904 }
905
906 // For Joomla CiviCRM Core files always live within the admistrator folder and $base_url is different on the frontend compared to the backend.
907 if (strpos($baseURL, 'administrator') === FALSE) {
908 $userFrameworkResourceURL = $baseURL . "administrator/components/com_civicrm/civicrm/";
909 }
910 else {
911 $userFrameworkResourceURL = $baseURL . "components/com_civicrm/civicrm/";
912 }
913
914 return [
915 'url' => CRM_Utils_File::addTrailingSlash($userFrameworkResourceURL, '/'),
916 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
917 ];
918 }
919
6a488035 920}