dispatcher.php
17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
<?php
/**
* @package FrameworkOnFramework
* @subpackage dispatcher
* @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @note This file has been modified by the Joomla! Project in 2019 in order to ensure compatibility with PHP 7.3+ versions.
*/
// Protect from unauthorized access
defined('FOF_INCLUDED') or die;
/**
* FrameworkOnFramework dispatcher class
*
* FrameworkOnFramework is a set of classes which extend Joomla! 1.5 and later's
* MVC framework with features making maintaining complex software much easier,
* without tedious repetitive copying of the same code over and over again.
*
* @package FrameworkOnFramework
* @since 1.0
*/
class FOFDispatcher extends FOFUtilsObject
{
/** @var array Configuration variables */
protected $config = array();
/** @var FOFInput Input variables */
protected $input = array();
/** @var string The name of the default view, in case none is specified */
public $defaultView = 'cpanel';
// Variables for FOF's transparent user authentication. You can override them
// in your Dispatcher's __construct() method.
/** @var int The Time Step for the TOTP used in FOF's transparent user authentication */
protected $fofAuth_timeStep = 6;
/** @var string The key for the TOTP, Base32 encoded (watch out; Base32, NOT Base64!) */
protected $fofAuth_Key = null;
/** @var array Which formats to be handled by transparent authentication */
protected $fofAuth_Formats = array('json', 'csv', 'xml', 'raw');
/**
* Should I logout the transparently authenticated user on logout?
* Recommended to leave it on in order to avoid crashing the sessions table.
*
* @var boolean
*/
protected $fofAuth_LogoutOnReturn = true;
/** @var array Which methods to use to fetch authentication credentials and in which order */
protected $fofAuth_AuthMethods = array(
/* HTTP Basic Authentication using encrypted information protected
* with a TOTP (the username must be "_fof_auth") */
'HTTPBasicAuth_TOTP',
/* Encrypted information protected with a TOTP passed in the
* _fofauthentication query string parameter */
'QueryString_TOTP',
/* HTTP Basic Authentication using a username and password pair in plain text */
'HTTPBasicAuth_Plaintext',
/* Plaintext, JSON-encoded username and password pair passed in the
* _fofauthentication query string parameter */
'QueryString_Plaintext',
/* Plaintext username and password in the _fofauthentication_username
* and _fofauthentication_username query string parameters */
'SplitQueryString_Plaintext',
);
/** @var bool Did we successfully and transparently logged in a user? */
private $_fofAuth_isLoggedIn = false;
/** @var string The calculated encryption key for the _TOTP methods, used if we have to encrypt the reply */
private $_fofAuth_CryptoKey = '';
/**
* Get a static (Singleton) instance of a particular Dispatcher
*
* @param string $option The component name
* @param string $view The View name
* @param array $config Configuration data
*
* @staticvar array $instances Holds the array of Dispatchers FOF knows about
*
* @return FOFDispatcher
*/
public static function &getAnInstance($option = null, $view = null, $config = array())
{
static $instances = array();
$hash = $option . $view;
if (!array_key_exists($hash, $instances))
{
$instances[$hash] = self::getTmpInstance($option, $view, $config);
}
return $instances[$hash];
}
/**
* Gets a temporary instance of a Dispatcher
*
* @param string $option The component name
* @param string $view The View name
* @param array $config Configuration data
*
* @return FOFDispatcher
*/
public static function &getTmpInstance($option = null, $view = null, $config = array())
{
if (array_key_exists('input', $config))
{
if ($config['input'] instanceof FOFInput)
{
$input = $config['input'];
}
else
{
if (!is_array($config['input']))
{
$config['input'] = (array) $config['input'];
}
$config['input'] = array_merge($_REQUEST, $config['input']);
$input = new FOFInput($config['input']);
}
}
else
{
$input = new FOFInput;
}
$config['option'] = !is_null($option) ? $option : $input->getCmd('option', 'com_foobar');
$config['view'] = !is_null($view) ? $view : $input->getCmd('view', '');
$input->set('option', $config['option']);
$input->set('view', $config['view']);
$config['input'] = $input;
$className = ucfirst(str_replace('com_', '', $config['option'])) . 'Dispatcher';
if (!class_exists($className))
{
$componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']);
$searchPaths = array(
$componentPaths['main'],
$componentPaths['main'] . '/dispatchers',
$componentPaths['admin'],
$componentPaths['admin'] . '/dispatchers'
);
if (array_key_exists('searchpath', $config))
{
array_unshift($searchPaths, $config['searchpath']);
}
$filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem');
$path = $filesystem->pathFind(
$searchPaths, 'dispatcher.php'
);
if ($path)
{
require_once $path;
}
}
if (!class_exists($className))
{
$className = 'FOFDispatcher';
}
$instance = new $className($config);
return $instance;
}
/**
* Public constructor
*
* @param array $config The configuration variables
*/
public function __construct($config = array())
{
// Cache the config
$this->config = $config;
// Get the input for this MVC triad
if (array_key_exists('input', $config))
{
$this->input = $config['input'];
}
else
{
$this->input = new FOFInput;
}
// Get the default values for the component name
$this->component = $this->input->getCmd('option', 'com_foobar');
// Load the component's fof.xml configuration file
$configProvider = new FOFConfigProvider;
$this->defaultView = $configProvider->get($this->component . '.dispatcher.default_view', $this->defaultView);
// Get the default values for the view name
$this->view = $this->input->getCmd('view', null);
if (empty($this->view))
{
// Do we have a task formatted as controller.task?
$task = $this->input->getCmd('task', '');
if (!empty($task) && (strstr($task, '.') !== false))
{
list($this->view, $task) = explode('.', $task, 2);
$this->input->set('task', $task);
}
}
if (empty($this->view))
{
$this->view = $this->defaultView;
}
$this->layout = $this->input->getCmd('layout', null);
// Overrides from the config
if (array_key_exists('option', $config))
{
$this->component = $config['option'];
}
if (array_key_exists('view', $config))
{
$this->view = empty($config['view']) ? $this->view : $config['view'];
}
if (array_key_exists('layout', $config))
{
$this->layout = $config['layout'];
}
$this->input->set('option', $this->component);
$this->input->set('view', $this->view);
$this->input->set('layout', $this->layout);
if (array_key_exists('authTimeStep', $config))
{
$this->fofAuth_timeStep = empty($config['authTimeStep']) ? 6 : $config['authTimeStep'];
}
}
/**
* The main code of the Dispatcher. It spawns the necessary controller and
* runs it.
*
* @throws Exception
*
* @return void|Exception
*/
public function dispatch()
{
$platform = FOFPlatform::getInstance();
if (!$platform->authorizeAdmin($this->input->getCmd('option', 'com_foobar')))
{
return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
}
$this->transparentAuthentication();
// Merge English and local translations
$platform->loadTranslations($this->component);
$canDispatch = true;
if ($platform->isCli())
{
$canDispatch = $canDispatch && $this->onBeforeDispatchCLI();
}
$canDispatch = $canDispatch && $this->onBeforeDispatch();
if (!$canDispatch)
{
// We can set header only if we're not in CLI
if(!$platform->isCli())
{
$platform->setHeader('Status', '403 Forbidden', true);
}
return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
}
// Get and execute the controller
$option = $this->input->getCmd('option', 'com_foobar');
$view = $this->input->getCmd('view', $this->defaultView);
$task = $this->input->getCmd('task', null);
if (empty($task))
{
$task = $this->getTask($view);
}
// Pluralise/sungularise the view name for typical tasks
if (in_array($task, array('edit', 'add', 'read')))
{
$view = FOFInflector::singularize($view);
}
elseif (in_array($task, array('browse')))
{
$view = FOFInflector::pluralize($view);
}
$this->input->set('view', $view);
$this->input->set('task', $task);
$config = $this->config;
$config['input'] = $this->input;
$controller = FOFController::getTmpInstance($option, $view, $config);
$status = $controller->execute($task);
if (!$this->onAfterDispatch())
{
// We can set header only if we're not in CLI
if(!$platform->isCli())
{
$platform->setHeader('Status', '403 Forbidden', true);
}
return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'));
}
$format = $this->input->get('format', 'html', 'cmd');
$format = empty($format) ? 'html' : $format;
if ($controller->hasRedirect())
{
$controller->redirect();
}
}
/**
* Tries to guess the controller task to execute based on the view name and
* the HTTP request method.
*
* @param string $view The name of the view
*
* @return string The best guess of the task to execute
*/
protected function getTask($view)
{
// Get a default task based on plural/singular view
$request_task = $this->input->getCmd('task', null);
$task = FOFInflector::isPlural($view) ? 'browse' : 'edit';
// Get a potential ID, we might need it later
$id = $this->input->get('id', null, 'int');
if ($id == 0)
{
$ids = $this->input->get('ids', array(), 'array');
if (!empty($ids))
{
$id = array_shift($ids);
}
}
// Check the request method
if (!isset($_SERVER['REQUEST_METHOD']))
{
$_SERVER['REQUEST_METHOD'] = 'GET';
}
$requestMethod = strtoupper($_SERVER['REQUEST_METHOD']);
switch ($requestMethod)
{
case 'POST':
case 'PUT':
if (!is_null($id))
{
$task = 'save';
}
break;
case 'DELETE':
if ($id != 0)
{
$task = 'delete';
}
break;
case 'GET':
default:
// If it's an edit without an ID or ID=0, it's really an add
if (($task == 'edit') && ($id == 0))
{
$task = 'add';
}
// If it's an edit in the frontend, it's really a read
elseif (($task == 'edit') && FOFPlatform::getInstance()->isFrontend())
{
$task = 'read';
}
break;
}
return $task;
}
/**
* Executes right before the dispatcher tries to instantiate and run the
* controller.
*
* @return boolean Return false to abort
*/
public function onBeforeDispatch()
{
return true;
}
/**
* Sets up some environment variables, so we can work as usually on CLI, too.
*
* @return boolean Return false to abort
*/
public function onBeforeDispatchCLI()
{
JLoader::import('joomla.environment.uri');
JLoader::import('joomla.application.component.helper');
// Trick to create a valid url used by JURI
$this->_originalPhpScript = '';
// We have no Application Helper (there is no Application!), so I have to define these constants manually
$option = $this->input->get('option', '', 'cmd');
if ($option)
{
$componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($option);
if (!defined('JPATH_COMPONENT'))
{
define('JPATH_COMPONENT', $componentPaths['main']);
}
if (!defined('JPATH_COMPONENT_SITE'))
{
define('JPATH_COMPONENT_SITE', $componentPaths['site']);
}
if (!defined('JPATH_COMPONENT_ADMINISTRATOR'))
{
define('JPATH_COMPONENT_ADMINISTRATOR', $componentPaths['admin']);
}
}
return true;
}
/**
* Executes right after the dispatcher runs the controller.
*
* @return boolean Return false to abort
*/
public function onAfterDispatch()
{
// If we have to log out the user, please do so now
if ($this->fofAuth_LogoutOnReturn && $this->_fofAuth_isLoggedIn)
{
FOFPlatform::getInstance()->logoutUser();
}
return true;
}
/**
* Transparently authenticates a user
*
* @return void
*/
public function transparentAuthentication()
{
// Only run when there is no logged in user
if (!FOFPlatform::getInstance()->getUser()->guest)
{
return;
}
// @todo Check the format
$format = $this->input->getCmd('format', 'html');
if (!in_array($format, $this->fofAuth_Formats))
{
return;
}
foreach ($this->fofAuth_AuthMethods as $method)
{
// If we're already logged in, don't bother
if ($this->_fofAuth_isLoggedIn)
{
continue;
}
// This will hold our authentication data array (username, password)
$authInfo = null;
switch ($method)
{
case 'HTTPBasicAuth_TOTP':
if (empty($this->fofAuth_Key))
{
continue 2;
}
if (!isset($_SERVER['PHP_AUTH_USER']))
{
continue 2;
}
if (!isset($_SERVER['PHP_AUTH_PW']))
{
continue 2;
}
if ($_SERVER['PHP_AUTH_USER'] != '_fof_auth')
{
continue 2;
}
$encryptedData = $_SERVER['PHP_AUTH_PW'];
$authInfo = $this->_decryptWithTOTP($encryptedData);
break;
case 'QueryString_TOTP':
$encryptedData = $this->input->get('_fofauthentication', '', 'raw');
if (empty($encryptedData))
{
continue 2;
}
$authInfo = $this->_decryptWithTOTP($encryptedData);
break;
case 'HTTPBasicAuth_Plaintext':
if (!isset($_SERVER['PHP_AUTH_USER']))
{
continue 2;
}
if (!isset($_SERVER['PHP_AUTH_PW']))
{
continue 2;
}
$authInfo = array(
'username' => $_SERVER['PHP_AUTH_USER'],
'password' => $_SERVER['PHP_AUTH_PW']
);
break;
case 'QueryString_Plaintext':
$jsonencoded = $this->input->get('_fofauthentication', '', 'raw');
if (empty($jsonencoded))
{
continue 2;
}
$authInfo = json_decode($jsonencoded, true);
if (!is_array($authInfo))
{
$authInfo = null;
}
elseif (!array_key_exists('username', $authInfo) || !array_key_exists('password', $authInfo))
{
$authInfo = null;
}
break;
case 'SplitQueryString_Plaintext':
$authInfo = array(
'username' => $this->input->get('_fofauthentication_username', '', 'raw'),
'password' => $this->input->get('_fofauthentication_password', '', 'raw'),
);
if (empty($authInfo['username']))
{
$authInfo = null;
}
break;
default:
continue 2;
break;
}
// No point trying unless we have a username and password
if (!is_array($authInfo))
{
continue;
}
$this->_fofAuth_isLoggedIn = FOFPlatform::getInstance()->loginUser($authInfo);
}
}
/**
* Decrypts a transparent authentication message using a TOTP
*
* @param string $encryptedData The encrypted data
*
* @codeCoverageIgnore
* @return array The decrypted data
*/
private function _decryptWithTOTP($encryptedData)
{
if (empty($this->fofAuth_Key))
{
$this->_fofAuth_CryptoKey = null;
return null;
}
$totp = new FOFEncryptTotp($this->fofAuth_timeStep);
$period = $totp->getPeriod();
$period--;
for ($i = 0; $i <= 2; $i++)
{
$time = ($period + $i) * $this->fofAuth_timeStep;
$otp = $totp->getCode($this->fofAuth_Key, $time);
$this->_fofAuth_CryptoKey = hash('sha256', $this->fofAuth_Key . $otp);
$aes = new FOFEncryptAes($this->_fofAuth_CryptoKey);
$ret = $aes->decryptString($encryptedData);
$ret = rtrim($ret, "\000");
$ret = json_decode($ret, true);
if (!is_array($ret))
{
continue;
}
if (!array_key_exists('username', $ret))
{
continue;
}
if (!array_key_exists('password', $ret))
{
continue;
}
// Successful decryption!
return $ret;
}
// Obviously if we're here we could not decrypt anything. Bail out.
$this->_fofAuth_CryptoKey = null;
return null;
}
/**
* Creates a decryption key for use with the TOTP decryption method
*
* @param integer $time The timestamp used for TOTP calculation, leave empty to use current timestamp
*
* @codeCoverageIgnore
* @return string THe encryption key
*/
private function _createDecryptionKey($time = null)
{
$totp = new FOFEncryptTotp($this->fofAuth_timeStep);
$otp = $totp->getCode($this->fofAuth_Key, $time);
$key = hash('sha256', $this->fofAuth_Key . $otp);
return $key;
}
/**
* Main function to detect if we're running in a CLI environment and we're admin
*
* @return array isCLI and isAdmin. It's not an associtive array, so we can use list.
*/
public static function isCliAdmin()
{
static $isCLI = null;
static $isAdmin = null;
if (is_null($isCLI) && is_null($isAdmin))
{
$isCLI = FOFPlatform::getInstance()->isCli();
$isAdmin = FOFPlatform::getInstance()->isBackend();
}
return array($isCLI, $isAdmin);
}
}