This repository has been archived by the owner on Dec 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.php
604 lines (558 loc) · 16.1 KB
/
App.php
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
<?php
namespace Pweb;
require_once 'string-functions.php';
require_once 'error-functions.php';
/**
* @brief The application class.
*
* @author Niccolò Scatena <speedjack95@gmail.com>
* @copyright GNU General Public License, version 3
*/
class App extends AbstractSingleton
{
// Public Properties {{{
/**
* @var string APP_ROOT
* The application root directory.
*/
const APP_ROOT = __DIR__;
/**
* @var string $serverName
* The name of the server host under which this application is running.
*/
public $serverName;
/**
* @var int $serverPort
* The port on the server machine being used by the web server for
* communication.
*/
public $serverPort;
/**
* @var bool $isHttps
* TRUE if using HTTPS, FALSE otherwise.
*/
public $isHttps;
/**
* @var Pages::AbstractPage $pageClass
* The class of the loaded page.
*/
public $pageClass;
/**
* @var string $actionName
* The name of the action being executed.
*/
public $actionName;
/**
* @var array $config
* The application configuration.
*/
public $config = [];
// }}}
// Protected Properties {{{
/**
* @var Entity::Visitor $_visitor
* The visitor instance.
*/
protected $_visitor;
/**
* @var Db::AbstractAdapter $_db
* The database adapter.
*/
protected $_db;
/**
* @var Entity::EntityManager $_em
* The EntityManager instance.
*/
protected $_em;
// }}}
/**
* @brief Creates the application.
*
* This class must be instantiated using getInstance().
*
* @param[in] array $config The user provided configuration.
* @return The App instance.
*/
protected function __construct(array $config = [])
{
$this->_setConfig($config);
$this->_setServerInfos();
$this->_setLanguage();
$this->_em = Entity\EntityManager::getInstance();
@set_exception_handler(array($this, 'exception_handler'));
@set_error_handler(array($this, 'error_handler'));
}
// Public Methods {{{
/** @brief Initializes the visitor instance. */
public function init()
{
$this->_visitor = $this->_em->create('Visitor');
}
/**
* @brief Returns the database instance.
*
* @throws Exception If neither PDO nor mysqli is supported.
*
* This function creates a new database instance if it is not already
* created.
*
* @retval Db::AbstractAdapter The database instance.
*/
public function getDb()
{
if (isset($this->_db))
return $this->_db;
if (!$this->config['db']['prefer_mysqli_over_pdo'] &&
extension_loaded('pdo') && extension_loaded('pdo_mysql'))
$this->_db = Db\PdoAdapter::getInstance($this->config['db']);
else if (extension_loaded('mysqli'))
$this->_db = Db\MysqliAdapter::getInstance($this->config['db']);
else
throw new \Exception(
__("No database extension loaded: PDO or MySQLi is required."),
500
);
return $this->_db;
}
// Routing {{{
/**
* @brief Routes the user to the selected page and action.
*
* This method does not return.
*
* @throws InvalidRouteException If the selected page or action
* can not be found.
*
* @param[in] array $getParams Associative array of key-value pairs of
* GET parameters.
* @param[in] array $postParams Associative array of key-value pairs of
* POST parameters.
* @param[in] bool $resetParams If TRUE, previous GET and POST
* parameters are reset.
*/
public function route(array $getParams = [], array $postParams = [],
$resetParams = false)
{
if ($resetParams)
$this->_visitor->clearParams();
$this->_visitor->setGetParams($getParams);
$this->_visitor->setPostParams($postParams);
$page = str_replace('_', '\\', $this->_visitor->page);
$action = $this->_visitor->action;
$page = "Pweb\\Pages\\$page";
$this->actionName = $action;
$pageClass = new $page();
$this->pageClass = $pageClass;
if (!method_exists($pageClass, $action))
throw new InvalidRouteException($page, $action);
$pageClass->$action();
die();
}
/**
* @brief Reroutes the user to a new page and action.
*
* This method does not return.
*
* @throws InvalidRouteException If the selected page or action
* can not be found.
*
* @param[in] string $page The page where the user should
* be routed.
* @param[in] string|null $action The action where the user should
* be routed. If null, it defaults
* to actionIndex.
* @param[in] array $getParams Associative array of key-value
* pairs of GET parameters.
* @param[in] array $postParams Associative array of key-value
* pairs of POST parameters.
* @param[in] bool $resetParams If TRUE, previous GET and POST
* parameters are reset.
*/
public function reroute($page, $action = null,
array $getParams = [], $postParams = [], $resetParams = true)
{
$this->_visitor->setRoute($page, $action);
$this->route($getParams, $postParams, $resetParams);
}
/**
* @brief Redirects the user to an external resource.
*
* @param[in] string $link The link to the external resource.
* @param[in] bool $permanent If TRUE, does a permanent (301)
* redirect. If FALSE, does a temporary
* (302) redirect.
*/
public function externalRedirect($link, $permanent = false)
{
header("Location: $link", true, $permanent ? 301 : 302);
die();
}
/**
* @brief Redirects the user to the specified page and action.
*
* @param[in] string $page The page where the user should
* be redirected. If NULL,
* redirects to index.php.
* @param[in] string|null $action The action where the user should
* be redirected. If NULL, it
* defaults to actionIndex.
* @param[in] array $params Associative array of key-value
* pairs of GET parameters.
* @param[in] bool $permanent If TRUE, does a permanent (301)
* redirect. If FALSE, does a
* temporary (302) redirect.
*/
public function redirect($page, $action = null, array $params = [],
$permanent = false)
{
$link = $this->buildAbsoluteLink($page, $action, $params);
$this->externalRedirect($link, $permanent);
}
/**
* @brief Redirects the user to the home page.
*
* @param[in] array $params Associative array of key-value pairs of
* GET parameters.
* @param[in] bool $permanent If TRUE, does a permanent (301)
* redirect. If FALSE, does a temporary
* (302) redirect.
*/
public function redirectHome(array $params = [], $permanent = false)
{
$this->redirect(null, null, $params, $permanent);
}
/**
* @brief Reroute the user to the home page.
*/
public function rerouteHome()
{
$this->reroute(null);
}
// }}}
// Link Building {{{
/**
* @brief Generates a relative link to a page.
*
* @param[in] string|null $page The page name. If NULL, returns
* a link to index.php. The special
* value '__current' can be used to
* refer to the current page.
* @param[in] string|null $action The action name. If NULL,
* defaults to actionIndex. The
* special value '__current' can be
* used to refer to the current
* action.
* @param[in] array $params Associative array of key-value
* pairs of GET parameters.
* @retval string The generated link.
*/
public function buildLink($page = null, $action = null, array $params = [])
{
if (empty($page))
return 'index.php';
$rawAction = '';
$page = $page === '__current' ?
trim_suffix($this->_visitor->page, 'Page') : $page;
$rawPage = "?page=$page";
if ($this->config['use_url_rewrite'])
$rawPage = "/$page";
if (!empty($action)) {
$action = $action === '__current' ?
trim_prefix($this->_visitor->action, 'action') : $action;
if ($this->config['use_url_rewrite'])
$rawAction = "/$action";
else
$rawAction = "&action=$action";
}
$rawParams = $this->_getRawParams($params, true);
return "index.php$rawPage$rawAction$rawParams";
}
/**
* @brief Generates an absolute link to an external resource.
*
* @param[in] string $link Base URL.
* @param[in] bool $https Set to TRUE to generate an https link,
* FALSE for a http link.
* @param[in] array $params Associative array of key-value pairs of
* GET parameters.
* @param[in] int $port The port to append to the domain name.
* @retval string The generated link.
*/
public function buildExternalLink($link, $https = true, array $params = [],
$port = 80)
{
$link = trim($link);
$link = trim_prefix($link, 'https://');
$link = trim_prefix($link, 'http://');
$portStr = ":$port";
if ($port === 80)
$portStr = '';
$portPos = strpos($link, '/');
if ($portPos === false) {
$portPos = strlen($link);
$portStr .= '/';
}
$link = substr_replace($link, $portStr, $portPos, 0);
return 'http' . ($https ? 's' : '') . "://$link"
. $this->_getRawParams($params);
}
/**
* @brief Generates an absolute link to an internal (this website)
* resource.
*
* @param[in] string|null $page The page name. If NULL, returns
* a link to index.php.
* @param[in] string|null $action The action name. If NULL, no
* action is specified (defaults to
* actionIndex).
* @param[in] array $params Associative array of key-value
* pairs of GET parameters.
* @retval string The generated link.
*/
public function buildAbsoluteLink($page = null, $action = null, array $params = [])
{
$link = $this->serverName .
(isset($this->config['website_subfolder']) ?
$this->config['website_subfolder'] : '');
if ($this->config['use_url_rewrite']) {
if (isset($page))
$link .= "/$page" . (isset($action) ? "/$action" : '');
else
$link .= '/index.php';
} else {
$link .= '/index.php';
if (!empty($page))
$params['page'] = $page;
if (!empty($action))
$params['action'] = $action;
}
return $this->buildExternalLink($link, $this->isHttps, $params,
$this->serverPort);
}
// }}}
// Error Handlers {{{
/**
* @brief Generic error handler.
*
* This handler throws an ErrorException, triggering the exception
* handler.
*
* @throws ErrorException
*
* @param[in] int $severity Severity of the error.
* @param[in] string $message The error message.
* @param[in] string $file File name that triggered the error.
* @param[in] int $line Line where the error was thrown.
*/
public function error_handler($severity, $message, $file, $line)
{
if (!(error_reporting() & $severity))
return;
throw new \ErrorException($message, 0, $severity, $file, $line);
}
/**
* @brief Generic exception handler.
*
* @param[in] Throwable $e The exception thrown.
*/
public function exception_handler($e)
{
panic(500, __("Unhandled Exception: %s\n",
addslashes($e->getMessage())), $e);
}
// }}}
// }}}
//Private Methods {{{
/**
* @internal
* @brief Sets up the configuration, replacing empty fields with default
* values.
* @param[in] array $config User provided configuration.
*/
private function _setConfig(array $config = [])
{
$this->config = array_replace_recursive([
'app_name' => '> CTF',
'header_motd' => 'A platform for Jeopardy style CTFs.',
'website_subfolder' => '',
'super_admin_ids' => [ 1 ],
'db' => [
'host' => 'localhost',
'port' => 3306,
'username' => 'root',
'password' => '',
'dbname' => 'pweb_ctf',
'charset' => 'utf8',
'prefer_mysqli_over_pdo' => false
],
'use_url_rewrite' => false,
'fallback_server_name' => 'localhost',
'fallback_server_port' => 80,
'default_per_page' => 15,
'session_canary_lifetime' => 60*5,
'auth_token_length' => 20,
'auth_token_duration' => 60*60*24*365,
'min_password_length' => 8,
'username_regex' => '/^[a-zA-Z0-9._-]{5,32}$/',
'flag_regex' => '/^(?:f|F)(?:l|L)(?:a|A)(?:g|G)\{[ -z|~]{1,249}\}$/',
'form_validation' => [
'username_regex' => '^[a-zA-Z0-9._-]{5,32}$',
'username_maxlength' => 32,
'flag_regex' => '^(?:f|F)(?:l|L)(?:a|A)(?:g|G)\{[ -z|~]+\}$',
'flag_maxlength' => 255
],
'locales' => [
'/^en/i' => 'en_US.UTF-8',
'/^it/i' => 'it_IT.UTF-8'
],
'default_locale' => 'en',
'selector_languages' => [ 'en', 'it' ],
'social_names' => [
'facebook' => '',
'instagram' => '',
'twitter' => '',
'youtube' => ''
],
'debug' => false,
'show_all_exceptions' => false,
'use_fallback_server_infos' => false,
'error_log' => null
], $config);
}
/**
* @internal
* @brief Returns the canonical IETF BCP 47 locale string.
*
* @param[in] string $lang The locale string.
* @retval string The IETF BCP 47 language tag.
*/
private function _getCanonicalLocale($lang)
{
$lang = trim($lang);
foreach ($this->config['locales'] as $pattern => $locale)
if (preg_match($pattern, $lang))
return $locale;
return false;
}
/**
* @internal
* @brief Checks if $lang is a valid locale string.
*
* @param[in] string $lang The string to check.
* @retval bool TRUE if $lang is a valid locale, FALSE
* otherwise.
*/
private function _isValidLanguage($lang)
{
return $this->_getCanonicalLocale($lang) !== false;
}
/**
* @internal
* @brief Sets the current locale to the user selection.
*
* This function also sets the LANG environment variable and a cookie
* to remember the user's selection.
* Used by gettext for internationalization.
*/
private function _setLanguage()
{
if (!extension_loaded('gettext') || php_sapi_name() === 'cli')
return;
if (!empty($_GET['lang'])
&& $this->_isValidLanguage($_GET['lang'])) {
$lang = $_GET['lang'];
} else if (!empty($_COOKIE['lang'])
&& $this->_isValidLanguage($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$acceptLang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
if (extension_loaded('intl')) {
\Locale::setDefault($this->config['default_locale']);
$lang = \Locale::acceptFromHttp($acceptLang);
} else if (!empty($acceptLang)) {
$langs = explode(',', $acceptLang);
array_walk($langs, function (&$lang) {
$lang = strtr(strtok($lang, ';'), '-', '_');
});
foreach ($langs as $elem)
if ($this->_isValidLanguage($elem)) {
$lang = $elem;
break;
}
}
}
/* always use default locale for easier debugging */
$lang = (!empty($lang) && !$this->config['debug'])
? trim($lang) : $this->config['default_locale'];
$lang = $this->_getCanonicalLocale($lang) ?: $lang;
/* NOTE: on Windows may not work. Seems a PHP bug. Works when
* run from cmd.exe with:
* > set LANG=en
* > xampp-control.exe
*/
@putenv("LANG=$lang");
@putenv("LANGUAGE=$lang");
@putenv("LC_MESSAGES=$lang");
@putenv("LC_ALL=$lang");
if (@setlocale(LC_ALL, $lang) === false) {
$lang = $this->_getCanonicalLocale($this->config['default_locale']);
@putenv("LANG=$lang");
@putenv("LANGUAGE=$lang");
@putenv("LC_MESSAGES=$lang");
@putenv("LC_ALL=$lang");
@setlocale(LC_ALL, $lang);
}
if (!isset($_COOKIE['lang']) || $lang !== $_COOKIE['lang'])
setcookie('lang', $lang, time()+60*60*24*365*10,
'/', $this->serverName);
}
/**
* @internal
* @brief Reads and caches the server name and port.
*/
private function _setServerInfos()
{
$this->isHttps = !empty($_SERVER['HTTPS']);
if ($this->config['use_fallback_server_infos']
|| php_sapi_name() === 'cli') {
$this->serverName = $this->config['fallback_server_name'];
$this->serverPort = $this->config['fallback_server_port'];
return;
}
if (!empty($_SERVER['SERVER_NAME']))
$this->serverName = trim($_SERVER['SERVER_NAME']);
else
$this->serverName = $this->config['fallback_server_name'];
if (!empty($_SERVER['SERVER_PORT']))
$this->serverPort = $_SERVER['SERVER_PORT'];
else
$this->serverPort = $this->config['fallback_server_port'];
}
/**
* @internal
* @brief Creates a string of parameters that can be appended to a URL.
*
* @param[in] array $params The parameter(s).
* @param[in] bool $append Set to TRUE to generate a string
* that starts with & instead of ?.
* @retval string The generated urlencoded string.
*/
private function _getRawParams(array $params, $append = false)
{
$rawParams = '';
$i = 0;
if (empty($params))
return '';
foreach ($params as $name => $value) {
if ($i == 0 && !$append)
$rawParams .= '?';
else
$rawParams .= '&';
$rawParams .= urlencode($name) . '=' . urlencode($value);
$i++;
}
return $rawParams;
}
// }}}
}