Merge pull request #15989 from seamuslee001/dev_core_523
[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)) {
136 $dbName = CRM_Utils_Array::value('username', $row);
137 $dbEmail = CRM_Utils_Array::value('email', $row);
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
CW
241 $frontend = FALSE,
242 $forceBackend = FALSE
6a488035 243 ) {
353ffa53 244 $config = CRM_Core_Config::singleton();
c80e2dbf 245 $separator = '&';
353ffa53
TO
246 $Itemid = '';
247 $script = '';
248 $path = CRM_Utils_String::stripPathChars($path);
6a488035
TO
249
250 if ($config->userFrameworkFrontend) {
251 $script = 'index.php';
92b78d1d
AT
252
253 // Get Itemid using JInput::get()
254 $input = Joomla\CMS\Factory::getApplication()->input;
255 $itemIdNum = $input->get("Itemid");
256 if ($itemIdNum && (strpos($path, 'civicrm/payment/ipn') === FALSE)) {
257 $Itemid = "{$separator}Itemid=" . $itemIdNum;
6a488035
TO
258 }
259 }
260
261 if (isset($fragment)) {
262 $fragment = '#' . $fragment;
263 }
264
6a488035
TO
265 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
266
267 if (!empty($query)) {
268 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
269 }
270 else {
271 $url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
272 }
273
274 // gross hack for joomla, we are in the backend and want to send a frontend url
275 if ($frontend && $config->userFramework == 'Joomla') {
276 // handle both joomla v1.5 and v1.6, CRM-7939
277 $url = str_replace('/administrator/index2.php', '/index.php', $url);
278 $url = str_replace('/administrator/index.php', '/index.php', $url);
279
280 // CRM-8215
281 $url = str_replace('/administrator/', '/index.php', $url);
282 }
283 elseif ($forceBackend) {
284 if (defined('JVERSION')) {
285 $joomlaVersion = JVERSION;
0db6c3e1
TO
286 }
287 else {
e7483cbe 288 $jversion = new JVersion();
6a488035
TO
289 $joomlaVersion = $jversion->getShortVersion();
290 }
291
292 if (version_compare($joomlaVersion, '1.6') >= 0) {
293 $url = str_replace('/index.php', '/administrator/index.php', $url);
294 }
295 }
296 return $url;
297 }
298
6a488035 299 /**
fe482240 300 * Set the email address of the user.
6a488035 301 *
77855840
TO
302 * @param object $user
303 * Handle to the user object.
6a488035 304 */
00be9182 305 public function setEmail(&$user) {
6a488035 306 global $database;
94f9f81a
EW
307 $query = $db->getQuery(TRUE);
308 $query->select($db->quoteName('email'))
6714d8d2
SL
309 ->from($db->quoteName('#__users'))
310 ->where($db->quoteName('id') . ' = ' . $user->id);
6a488035
TO
311 $database->setQuery($query);
312 $user->email = $database->loadResult();
313 }
314
315 /**
17f443df 316 * @inheritDoc
6a488035 317 */
17f443df 318 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
319 require_once 'DB.php';
320
321 $config = CRM_Core_Config::singleton();
ebc28bab 322 $user = NULL;
6a488035
TO
323
324 if ($loadCMSBootstrap) {
be2fb01f 325 $bootStrapParams = [];
6a488035 326 if ($name && $password) {
be2fb01f 327 $bootStrapParams = [
6a488035
TO
328 'name' => $name,
329 'pass' => $password,
be2fb01f 330 ];
6a488035 331 }
bec3fc7c 332 CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
6a488035
TO
333 }
334
335 jimport('joomla.application.component.helper');
336 jimport('joomla.database.table');
c1f3c6da
BS
337 jimport('joomla.user.helper');
338
339 $JUserTable = JTable::getInstance('User', 'JTable');
340
341 $db = $JUserTable->getDbo();
342 $query = $db->getQuery(TRUE);
343 $query->select('id, name, username, email, password');
344 $query->from($JUserTable->getTableName());
345 $query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
346 $db->setQuery($query, 0, 0);
347 $users = $db->loadObjectList();
348
be2fb01f 349 $row = [];
c1f3c6da
BS
350 if (count($users)) {
351 $row = $users[0];
352 }
6a488035 353
e1d37cef
MW
354 $joomlaBase = self::getBasePath();
355 self::getJVersion($joomlaBase);
6a488035 356
c1f3c6da
BS
357 if (!empty($row)) {
358 $dbPassword = $row->password;
359 $dbId = $row->id;
360 $dbEmail = $row->email;
6a488035 361
481a74f4
TO
362 if (version_compare(JVERSION, '2.5.18', 'lt') ||
363 (version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt'))
c1f3c6da 364 ) {
ebc28bab 365 // now check password
009eff21
EW
366 list($hash, $salt) = explode(':', $dbPassword);
367 $cryptpass = md5($password . $salt);
368 if ($hash != $cryptpass) {
01c77fa9
EW
369 return FALSE;
370 }
6a488035 371 }
c1f3c6da 372 else {
4f99ca55
TO
373 if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) {
374 return FALSE;
e7292422 375 }
9d735153 376
3a8c9bb6
MW
377 if (version_compare(JVERSION, '3.8.0', 'ge')) {
378 jimport('joomla.application.helper');
379 jimport('joomla.application.cms');
380 jimport('joomla.application.administrator');
381 }
9d735153 382 //include additional files required by Joomla 3.2.1+
3a8c9bb6 383 elseif (version_compare(JVERSION, '3.2.1', 'ge')) {
90eac10a
BS
384 require_once $joomlaBase . '/libraries/cms/application/helper.php';
385 require_once $joomlaBase . '/libraries/cms/application/cms.php';
386 require_once $joomlaBase . '/libraries/cms/application/administrator.php';
9d735153 387 }
6a488035
TO
388 }
389
c1f3c6da 390 CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
6a488035
TO
391 $contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
392 if (!$contactID) {
393 return FALSE;
394 }
be2fb01f 395 return [$contactID, $dbId, mt_rand()];
6a488035 396 }
c1f3c6da 397
6a488035
TO
398 return FALSE;
399 }
400
bec3fc7c 401 /**
fe482240 402 * Set a init session with user object.
bec3fc7c 403 *
77855840
TO
404 * @param array $data
405 * Array with user specific data.
bec3fc7c 406 */
00be9182 407 public function setUserSession($data) {
bec3fc7c 408 list($userID, $ufID) = $data;
481a74f4 409 $user = new JUser($ufID);
2d8f9c75 410 $session = JFactory::getSession();
bec3fc7c
BS
411 $session->set('user', $user);
412
cb0e36de 413 parent::setUserSession($data);
bec3fc7c
BS
414 }
415
6a488035 416 /**
17f443df 417 * FIXME: Do something
ea3ddccf 418 *
419 * @param string $message
6a488035 420 */
00be9182 421 public function setMessage($message) {
6a488035
TO
422 }
423
bb3a214a 424 /**
b596c3e9 425 * @param \string $username
426 * @param \string $password
ea3ddccf 427 *
428 * @return bool
bb3a214a 429 */
b596c3e9 430 public function loadUser($username, $password = NULL) {
431 $uid = JUserHelper::getUserId($username);
432 if (empty($uid)) {
433 return FALSE;
434 }
435 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
436 if (!empty($password)) {
437 $instance = JFactory::getApplication('site');
be2fb01f 438 $params = [
b596c3e9 439 'username' => $username,
440 'password' => $password,
be2fb01f 441 ];
b596c3e9 442 //perform the login action
443 $instance->login($params);
444 }
445
8f407be0
AS
446 // Save details in Joomla session
447 $user = JFactory::getUser($uid);
448 $jsession = JFactory::getSession();
449 $jsession->set('user', $user);
450
451 // Save details in Civi session
b596c3e9 452 $session = CRM_Core_Session::singleton();
453 $session->set('ufID', $uid);
454 $session->set('userID', $contactID);
6a488035
TO
455 return TRUE;
456 }
457
17f443df
CW
458 /**
459 * FIXME: Use CMS-native approach
309310bf 460 * @throws \CRM_Core_Exception.
17f443df 461 */
00be9182 462 public function permissionDenied() {
309310bf 463 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
6a488035
TO
464 }
465
17f443df
CW
466 /**
467 * @inheritDoc
468 */
00be9182 469 public function logout() {
6a488035 470 session_destroy();
d42a224c 471 CRM_Utils_System::setHttpHeader("Location", "index.php");
6a488035
TO
472 }
473
474 /**
17f443df 475 * @inheritDoc
6a488035 476 */
00be9182 477 public function getUFLocale() {
6a488035
TO
478 if (defined('_JEXEC')) {
479 $conf = JFactory::getConfig();
4965d8e9 480 $locale = $conf->get('language');
6a488035
TO
481 return str_replace('-', '_', $locale);
482 }
483 return NULL;
484 }
485
fd1f3a26
SV
486 /**
487 * @inheritDoc
488 */
489 public function setUFLocale($civicrm_language) {
490 // TODO
491 return TRUE;
492 }
493
bb3a214a 494 /**
17f443df 495 * @inheritDoc
bb3a214a 496 */
00be9182 497 public function getVersion() {
6a488035 498 if (class_exists('JVersion')) {
e7483cbe 499 $version = new JVersion();
6a488035
TO
500 return $version->getShortVersion();
501 }
502 else {
503 return 'Unknown';
504 }
505 }
506
e1d37cef
MW
507 public function getJVersion($joomlaBase) {
508 // Files may be in different places depending on Joomla version
509 if (!defined('JVERSION')) {
510 // Joomla 3.8.0+
511 $versionPhp = $joomlaBase . '/libraries/src/Version.php';
512 if (!file_exists($versionPhp)) {
513 // Joomla < 3.8.0
514 $versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
515 }
516 require $versionPhp;
517 $jversion = new JVersion();
518 define('JVERSION', $jversion->getShortVersion());
519 }
520 }
521
f3884007
MW
522 /**
523 * Setup the base path related constant.
524 * @return mixed
525 */
e1d37cef 526 public function getBasePath() {
f3884007 527 global $civicrm_root;
e23eb52f 528 $joomlaPath = explode(DIRECTORY_SEPARATOR . 'administrator', $civicrm_root);
f3884007
MW
529 $joomlaBase = $joomlaPath[0];
530 return $joomlaBase;
e1d37cef
MW
531 }
532
f4aaa82a 533 /**
fe482240 534 * Load joomla bootstrap.
6a488035 535 *
5a4f6742
CW
536 * @param array $params
537 * with uid or name and password.
538 * @param bool $loadUser
539 * load cms user?.
f4aaa82a
EM
540 * @param bool|\throw $throwError throw error on failure?
541 * @param null $realPath
542 * @param bool $loadDefines
543 *
544 * @return bool
6a488035 545 */
be2fb01f 546 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
e1d37cef 547 $joomlaBase = self::getBasePath();
6a488035
TO
548
549 // load BootStrap here if needed
550 // We are a valid Joomla entry point.
53e972a8 551 // dev/core#1384 Use DS to ensure a correct JPATH_BASE in Windows
353ffa53 552 if (!defined('_JEXEC') && $loadDefines) {
6a488035
TO
553 define('_JEXEC', 1);
554 define('DS', DIRECTORY_SEPARATOR);
53e972a8 555 define('JPATH_BASE', $joomlaBase . DS . 'administrator');
6a488035
TO
556 require $joomlaBase . '/administrator/includes/defines.php';
557 }
558
559 // Get the framework.
2cb7adde 560 if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
2efcf0c2 561 require $joomlaBase . '/libraries/import.legacy.php';
2cb7adde 562 }
3a8c9bb6 563 require $joomlaBase . '/libraries/cms.php';
e1d37cef 564 self::getJVersion($joomlaBase);
6fde79f5 565
8421b502 566 if (version_compare(JVERSION, '3.8', 'lt')) {
567 require $joomlaBase . '/libraries/import.php';
568 require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
569 }
570
571 require_once $joomlaBase . '/configuration.php';
572
481a74f4 573 if (version_compare(JVERSION, '3.0', 'lt')) {
6fde79f5
BS
574 require $joomlaBase . '/libraries/joomla/environment/uri.php';
575 require $joomlaBase . '/libraries/joomla/application/component/helper.php';
576 }
8421b502 577 elseif (version_compare(JVERSION, '3.8', 'lt')) {
3a8c9bb6 578 jimport('joomla.environment.uri');
6fde79f5
BS
579 }
580
8421b502 581 if (version_compare(JVERSION, '3.8', 'lt')) {
582 jimport('joomla.application.cli');
583 }
f4aaa82a 584
a5291777
TO
585 if (!defined('JDEBUG')) {
586 define('JDEBUG', FALSE);
587 }
26915930
MWMC
588
589 // Set timezone for Joomla on Cron
590 $config = JFactory::getConfig();
591 $timezone = $config->get('offset');
592 if ($timezone) {
593 date_default_timezone_set($timezone);
594 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
595 }
a5291777 596
182f835d 597 // CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
598 $config = CRM_Core_Config::singleton();
599 CRM_Utils_Hook::config($config);
6a488035
TO
600
601 return TRUE;
602 }
603
604 /**
17f443df 605 * @inheritDoc
6a488035
TO
606 */
607 public function isUserLoggedIn() {
608 $user = JFactory::getUser();
609 return ($user->guest) ? FALSE : TRUE;
610 }
611
8caad0ce 612 /**
613 * @inheritDoc
614 */
615 public function isUserRegistrationPermitted() {
616 $userParams = JComponentHelper::getParams('com_users');
617 if (!$userParams->get('allowUserRegistration')) {
618 return FALSE;
619 }
620 return TRUE;
621 }
622
63df6889
HD
623 /**
624 * @inheritDoc
625 */
1a6630be 626 public function isPasswordUserGenerated() {
63df6889
HD
627 return TRUE;
628 }
629
6a488035 630 /**
17f443df 631 * @inheritDoc
6a488035
TO
632 */
633 public function getLoggedInUfID() {
634 $user = JFactory::getUser();
635 return ($user->guest) ? NULL : $user->id;
636 }
637
2b617cb0 638 /**
17f443df 639 * @inheritDoc
2b617cb0 640 */
00be9182 641 public function getLoggedInUniqueIdentifier() {
2b617cb0
EM
642 $user = JFactory::getUser();
643 return $this->getUniqueIdentifierFromUserObject($user);
644 }
353ffa53 645
cff0c9aa
DS
646 /**
647 * @inheritDoc
648 */
649 public function getUser($contactID) {
650 $user_details = parent::getUser($contactID);
651 $user = JFactory::getUser($user_details['id']);
652 $user_details['name'] = $user->name;
653 return $user_details;
654 }
655
32998c82 656 /**
17f443df 657 * @inheritDoc
32998c82 658 */
00be9182 659 public function getUserIDFromUserObject($user) {
32998c82
EM
660 return !empty($user->id) ? $user->id : NULL;
661 }
662
2b617cb0 663 /**
17f443df 664 * @inheritDoc
2b617cb0 665 */
00be9182 666 public function getUniqueIdentifierFromUserObject($user) {
2b617cb0
EM
667 return ($user->guest) ? NULL : $user->email;
668 }
669
29864da4 670 /**
671 * @inheritDoc
672 */
673 public function getTimeZoneString() {
674 $timezone = JFactory::getConfig()->get('offset');
675 return !$timezone ? date_default_timezone_get() : $timezone;
676 }
677
6a488035
TO
678 /**
679 * Get a list of all installed modules, including enabled and disabled ones
680 *
a6c01b45
CW
681 * @return array
682 * CRM_Core_Module
6a488035 683 */
00be9182 684 public function getModules() {
be2fb01f 685 $result = [];
6a488035
TO
686
687 $db = JFactory::getDbo();
e7292422 688 $query = $db->getQuery(TRUE);
6a488035
TO
689 $query->select('type, folder, element, enabled')
690 ->from('#__extensions')
691 ->where('type =' . $db->Quote('plugin'));
692 $plugins = $db->setQuery($query)->loadAssocList();
693 foreach ($plugins as $plugin) {
694 // question: is the folder really a critical part of the plugin's name?
be2fb01f 695 $name = implode('.', ['joomla', $plugin['type'], $plugin['folder'], $plugin['element']]);
6a488035
TO
696 $result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
697 }
698
699 return $result;
700 }
701
702 /**
17f443df 703 * @inheritDoc
6a488035
TO
704 */
705 public function getLoginURL($destination = '') {
706 $config = CRM_Core_Config::singleton();
707 $loginURL = $config->userFrameworkBaseURL;
708 $loginURL = str_replace('administrator/', '', $loginURL);
709 $loginURL .= 'index.php?option=com_users&view=login';
091412ab
BS
710
711 //CRM-14872 append destination
481a74f4 712 if (!empty($destination)) {
92fcb95f 713 $loginURL .= '&return=' . urlencode(base64_encode($destination));
091412ab 714 }
6a488035
TO
715 return $loginURL;
716 }
f813f78e 717
bb3a214a 718 /**
17f443df 719 * @inheritDoc
bb3a214a 720 */
6a488035 721 public function getLoginDestination(&$form) {
091412ab
BS
722 $args = NULL;
723
724 $id = $form->get('id');
725 if ($id) {
726 $args .= "&id=$id";
727 }
728 else {
729 $gid = $form->get('gid');
730 if ($gid) {
731 $args .= "&gid=$gid";
732 }
733 else {
734 // Setup Personal Campaign Page link uses pageId
735 $pageId = $form->get('pageId');
736 if ($pageId) {
737 $component = $form->get('component');
738 $args .= "&pageId=$pageId&component=$component&action=add";
739 }
740 }
741 }
742
743 $destination = NULL;
744 if ($args) {
745 // append destination so user is returned to form they came from after login
92fcb95f 746 $args = 'reset=1' . $args;
48341e06 747 $destination = CRM_Utils_System::url(CRM_Utils_System::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
091412ab
BS
748 }
749
750 return $destination;
6a488035 751 }
9977c6f5 752
214fbc2c 753 /**
754 * Determine the location of the CMS root.
755 *
756 * @return string|NULL
757 * local file system path to CMS root, or NULL if it cannot be determined
758 */
759 public function cmsRootPath() {
a93a0366
TO
760 global $civicrm_paths;
761 if (!empty($civicrm_paths['cms.root']['path'])) {
762 return $civicrm_paths['cms.root']['path'];
763 }
764
214fbc2c 765 list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
e1d37cef 766 if (file_exists("$siteRoot/administrator/index.php")) {
214fbc2c 767 return $siteRoot;
768 }
769 return NULL;
770 }
771
9977c6f5 772 /**
17f443df 773 * @inheritDoc
9977c6f5 774 */
70e8beda 775 public function getDefaultSiteSettings($dir = NULL) {
9977c6f5 776 $config = CRM_Core_Config::singleton();
777 $url = preg_replace(
778 '|/administrator|',
779 '',
780 $config->userFrameworkBaseURL
781 );
ad2d96ba 782 // CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
783 // This is the original pattern, but it doesn't work under Windows.
784 // By setting the pattern to the one used before the change first and only
785 // changing it means that the change code only affects Windows users.
786 $pattern = '|/media/civicrm/.*$|';
787 if (DIRECTORY_SEPARATOR == '\\') {
788 // This regular expression will handle Windows as well as Linux
789 // and any combination of forward and back slashes in directory
790 // separators. We only apply it if the directory separator is the one
791 // used by Windows.
792 $pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
793 }
9977c6f5 794 $siteRoot = preg_replace(
ad2d96ba 795 $pattern,
9977c6f5 796 '',
797 $config->imageUploadDir
798 );
be2fb01f 799 return [$url, NULL, $siteRoot];
9977c6f5 800 }
59f97da6
EM
801
802 /**
17f443df 803 * @inheritDoc
59f97da6 804 */
00be9182 805 public function getUserRecordUrl($contactID) {
59f97da6
EM
806 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
807 $userRecordUrl = NULL;
55904b50 808 // if logged in user has user edit access, then allow link to other users joomla profile
a8e5af2a 809 if (JFactory::getUser()->authorise('core.edit', 'com_users')) {
59f97da6
EM
810 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
811 }
812 elseif (CRM_Core_Session::singleton()->get('userID') == $contactID) {
813 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
814 }
815 }
816
817 /**
17f443df 818 * @inheritDoc
59f97da6 819 */
00be9182 820 public function checkPermissionAddUser() {
59f97da6
EM
821 if (JFactory::getUser()->authorise('core.create', 'com_users')) {
822 return TRUE;
823 }
824 }
f85b1d20 825
03d5592a
CW
826 /**
827 * @inheritDoc
828 */
829 public function synchronizeUsers() {
830 $config = CRM_Core_Config::singleton();
831 if (PHP_SAPI != 'cli') {
832 set_time_limit(300);
833 }
834 $id = 'id';
835 $mail = 'email';
836 $name = 'name';
837
838 $JUserTable = &JTable::getInstance('User', 'JTable');
839
840 $db = $JUserTable->getDbo();
841 $query = $db->getQuery(TRUE);
842 $query->select($id . ', ' . $mail . ', ' . $name);
843 $query->from($JUserTable->getTableName());
844 $query->where($mail != '');
845
846 $db->setQuery($query);
847 $users = $db->loadObjectList();
848
849 $user = new StdClass();
850 $uf = $config->userFramework;
851 $contactCount = 0;
852 $contactCreated = 0;
853 $contactMatching = 0;
854 for ($i = 0; $i < count($users); $i++) {
855 $user->$id = $users[$i]->$id;
856 $user->$mail = $users[$i]->$mail;
857 $user->$name = $users[$i]->$name;
858 $contactCount++;
859 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user,
860 $users[$i]->$id,
861 $users[$i]->$mail,
862 $uf,
863 1,
864 'Individual',
865 TRUE
866 )
867 ) {
868 $contactCreated++;
869 }
870 else {
871 $contactMatching++;
872 }
03d5592a
CW
873 }
874
be2fb01f 875 return [
03d5592a
CW
876 'contactCount' => $contactCount,
877 'contactMatching' => $contactMatching,
878 'contactCreated' => $contactCreated,
be2fb01f 879 ];
03d5592a
CW
880 }
881
6a488035 882}