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
|
<?php
/**
* Used to render the header of PMA's pages
*/
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Navigation\Navigation;
use function array_merge;
use function defined;
use function gmdate;
use function header;
use function htmlspecialchars;
use function implode;
use function ini_get;
use function is_bool;
use function sprintf;
use function strlen;
use function strtolower;
use function urlencode;
/**
* Class used to output the HTTP and HTML headers
*/
class Header
{
/**
* Scripts instance
*
* @var Scripts
*/
private $scripts;
/**
* PhpMyAdmin\Console instance
*
* @var Console
*/
private $console;
/**
* Menu instance
*
* @var Menu
*/
private $menu;
/**
* The page title
*
* @var string
*/
private $title;
/**
* The value for the id attribute for the body tag
*
* @var string
*/
private $bodyId;
/**
* Whether to show the top menu
*
* @var bool
*/
private $menuEnabled;
/**
* Whether to show the warnings
*
* @var bool
*/
private $warningsEnabled;
/**
* Whether we are servicing an ajax request.
*
* @var bool
*/
private $isAjax;
/**
* Whether to display anything
*
* @var bool
*/
private $isEnabled;
/**
* Whether the HTTP headers (and possibly some HTML)
* have already been sent to the browser
*
* @var bool
*/
private $headerIsSent;
/** @var UserPreferences */
private $userPreferences;
/** @var Template */
private $template;
/** @var bool */
private $isTransformationWrapper = false;
/**
* Creates a new class instance
*/
public function __construct()
{
$this->template = new Template();
$this->isEnabled = true;
$this->isAjax = false;
$this->bodyId = '';
$this->title = '';
$this->console = new Console();
$this->menu = new Menu($GLOBALS['dbi'], $GLOBALS['db'] ?? '', $GLOBALS['table'] ?? '');
$this->menuEnabled = true;
$this->warningsEnabled = true;
$this->scripts = new Scripts();
$this->addDefaultScripts();
$this->headerIsSent = false;
$this->userPreferences = new UserPreferences();
}
/**
* Loads common scripts
*/
private function addDefaultScripts(): void
{
$this->scripts->addFile('runtime.js');
$this->scripts->addFile('vendor/jquery/jquery.min.js');
$this->scripts->addFile('vendor/jquery/jquery-migrate.js');
$this->scripts->addFile('vendor/sprintf.js');
$this->scripts->addFile('ajax.js');
$this->scripts->addFile('keyhandler.js');
$this->scripts->addFile('vendor/jquery/jquery-ui.min.js');
$this->scripts->addFile('name-conflict-fixes.js');
$this->scripts->addFile('vendor/bootstrap/bootstrap.bundle.min.js');
$this->scripts->addFile('vendor/js.cookie.js');
$this->scripts->addFile('vendor/jquery/jquery.validate.js');
$this->scripts->addFile('vendor/jquery/jquery-ui-timepicker-addon.js');
$this->scripts->addFile('menu_resizer.js');
$this->scripts->addFile('cross_framing_protection.js');
$this->scripts->addFile('messages.php', ['l' => $GLOBALS['lang']]);
$this->scripts->addFile('config.js');
$this->scripts->addFile('doclinks.js');
$this->scripts->addFile('functions.js');
$this->scripts->addFile('navigation.js');
$this->scripts->addFile('indexes.js');
$this->scripts->addFile('common.js');
$this->scripts->addFile('page_settings.js');
$this->scripts->addFile('main.js');
$this->scripts->addCode($this->getJsParamsCode());
}
/**
* Returns, as an array, a list of parameters
* used on the client side
*
* @return array
*/
public function getJsParams(): array
{
$pftext = $_SESSION['tmpval']['pftext'] ?? '';
$params = [
// Do not add any separator, JS code will decide
'common_query' => Url::getCommonRaw([], ''),
'opendb_url' => Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database'),
'lang' => $GLOBALS['lang'],
'server' => $GLOBALS['server'],
'table' => $GLOBALS['table'] ?? '',
'db' => $GLOBALS['db'] ?? '',
'token' => $_SESSION[' PMA_token '],
'text_dir' => $GLOBALS['text_dir'],
'LimitChars' => $GLOBALS['cfg']['LimitChars'],
'pftext' => $pftext,
'confirm' => $GLOBALS['cfg']['Confirm'],
'LoginCookieValidity' => $GLOBALS['cfg']['LoginCookieValidity'],
'session_gc_maxlifetime' => (int) ini_get('session.gc_maxlifetime'),
'logged_in' => isset($GLOBALS['dbi']) ? $GLOBALS['dbi']->isConnected() : false,
'is_https' => $GLOBALS['config']->isHttps(),
'rootPath' => $GLOBALS['config']->getRootPath(),
'arg_separator' => Url::getArgSeparator(),
'version' => Version::VERSION,
];
if (isset($GLOBALS['cfg']['Server'], $GLOBALS['cfg']['Server']['auth_type'])) {
$params['auth_type'] = $GLOBALS['cfg']['Server']['auth_type'];
if (isset($GLOBALS['cfg']['Server']['user'])) {
$params['user'] = $GLOBALS['cfg']['Server']['user'];
}
}
return $params;
}
/**
* Returns, as a string, a list of parameters
* used on the client side
*/
public function getJsParamsCode(): string
{
$params = $this->getJsParams();
foreach ($params as $key => $value) {
if (is_bool($value)) {
$params[$key] = $key . ':' . ($value ? 'true' : 'false') . '';
} else {
$params[$key] = $key . ':"' . Sanitize::escapeJsString($value) . '"';
}
}
return 'window.CommonParams.setAll({' . implode(',', $params) . '});';
}
/**
* Disables the rendering of the header
*/
public function disable(): void
{
$this->isEnabled = false;
}
/**
* Set the ajax flag to indicate whether
* we are servicing an ajax request
*
* @param bool $isAjax Whether we are servicing an ajax request
*/
public function setAjax(bool $isAjax): void
{
$this->isAjax = $isAjax;
$this->console->setAjax($isAjax);
}
/**
* Returns the Scripts object
*
* @return Scripts object
*/
public function getScripts(): Scripts
{
return $this->scripts;
}
/**
* Returns the Menu object
*
* @return Menu object
*/
public function getMenu(): Menu
{
return $this->menu;
}
/**
* Setter for the ID attribute in the BODY tag
*
* @param string $id Value for the ID attribute
*/
public function setBodyId(string $id): void
{
$this->bodyId = htmlspecialchars($id);
}
/**
* Setter for the title of the page
*
* @param string $title New title
*/
public function setTitle(string $title): void
{
$this->title = htmlspecialchars($title);
}
/**
* Disables the display of the top menu
*/
public function disableMenuAndConsole(): void
{
$this->menuEnabled = false;
$this->console->disable();
}
/**
* Disables the display of the top menu
*/
public function disableWarnings(): void
{
$this->warningsEnabled = false;
}
/**
* Generates the header
*
* @return string The header
*/
public function getDisplay(): string
{
$GLOBALS['theme'] = $GLOBALS['theme'] ?? null;
if ($this->headerIsSent || ! $this->isEnabled) {
return '';
}
$recentTable = '';
if (empty($_REQUEST['recent_table'])) {
$recentTable = $this->addRecentTable($GLOBALS['db'], $GLOBALS['table']);
}
if ($this->isAjax) {
return $recentTable;
}
$this->sendHttpHeaders();
$baseDir = defined('PMA_PATH_TO_BASEDIR') ? PMA_PATH_TO_BASEDIR : '';
$themePath = $GLOBALS['theme'] instanceof Theme ? $GLOBALS['theme']->getPath() : '';
$version = self::getVersionParameter();
// The user preferences have been merged at this point
// so we can conditionally add CodeMirror, other scripts and settings
if ($GLOBALS['cfg']['CodemirrorEnable']) {
$this->scripts->addFile('vendor/codemirror/lib/codemirror.js');
$this->scripts->addFile('vendor/codemirror/mode/sql/sql.js');
$this->scripts->addFile('vendor/codemirror/addon/runmode/runmode.js');
$this->scripts->addFile('vendor/codemirror/addon/hint/show-hint.js');
$this->scripts->addFile('vendor/codemirror/addon/hint/sql-hint.js');
if ($GLOBALS['cfg']['LintEnable']) {
$this->scripts->addFile('vendor/codemirror/addon/lint/lint.js');
$this->scripts->addFile('codemirror/addon/lint/sql-lint.js');
}
}
if ($GLOBALS['cfg']['SendErrorReports'] !== 'never') {
$this->scripts->addFile('vendor/tracekit.js');
$this->scripts->addFile('error_report.js');
}
if ($GLOBALS['cfg']['enable_drag_drop_import'] === true) {
$this->scripts->addFile('drag_drop_import.js');
}
if (! $GLOBALS['config']->get('DisableShortcutKeys')) {
$this->scripts->addFile('shortcuts_handler.js');
}
$this->scripts->addCode($this->getVariablesForJavaScript());
$this->scripts->addCode('ConsoleEnterExecutes=' . ($GLOBALS['cfg']['ConsoleEnterExecutes'] ? 'true' : 'false'));
$this->scripts->addFiles($this->console->getScripts());
// if database storage for user preferences is transient,
// offer to load exported settings from localStorage
// (detection will be done in JavaScript)
$userprefsOfferImport = false;
if (
$GLOBALS['config']->get('user_preferences') === 'session'
&& ! isset($_SESSION['userprefs_autoload'])
) {
$userprefsOfferImport = true;
}
if ($userprefsOfferImport) {
$this->scripts->addFile('config.js');
}
if ($this->menuEnabled && $GLOBALS['server'] > 0) {
$nav = new Navigation(
$this->template,
new Relation($GLOBALS['dbi']),
$GLOBALS['dbi']
);
$navigation = $nav->getDisplay();
}
$customHeader = Config::renderHeader();
// offer to load user preferences from localStorage
if ($userprefsOfferImport) {
$loadUserPreferences = $this->userPreferences->autoloadGetHeader();
}
if ($this->menuEnabled && $GLOBALS['server'] > 0) {
$menu = $this->menu->getDisplay();
}
$console = $this->console->getDisplay();
$messages = $this->getMessage();
$this->scripts->addFile('datetimepicker.js');
$this->scripts->addFile('validator-messages.js');
return $this->template->render('header', [
'lang' => $GLOBALS['lang'],
'allow_third_party_framing' => $GLOBALS['cfg']['AllowThirdPartyFraming'],
'base_dir' => $baseDir,
'theme_path' => $themePath,
'version' => $version,
'text_dir' => $GLOBALS['text_dir'],
'server' => $GLOBALS['server'] ?? null,
'title' => $this->getPageTitle(),
'scripts' => $this->scripts->getDisplay(),
'body_id' => $this->bodyId,
'navigation' => $navigation ?? '',
'custom_header' => $customHeader,
'load_user_preferences' => $loadUserPreferences ?? '',
'show_hint' => $GLOBALS['cfg']['ShowHint'],
'is_warnings_enabled' => $this->warningsEnabled,
'is_menu_enabled' => $this->menuEnabled,
'menu' => $menu ?? '',
'console' => $console,
'messages' => $messages,
'recent_table' => $recentTable,
]);
}
/**
* Returns the message to be displayed at the top of
* the page, including the executed SQL query, if any.
*/
public function getMessage(): string
{
$retval = '';
$message = '';
if (! empty($GLOBALS['message'])) {
$message = $GLOBALS['message'];
unset($GLOBALS['message']);
} elseif (! empty($_REQUEST['message'])) {
$message = $_REQUEST['message'];
}
if (! empty($message)) {
if (isset($GLOBALS['buffer_message'])) {
$bufferMessage = $GLOBALS['buffer_message'];
}
$retval .= Generator::getMessage($message);
if (isset($bufferMessage)) {
$GLOBALS['buffer_message'] = $bufferMessage;
}
}
return $retval;
}
/**
* Sends out the HTTP headers
*/
public function sendHttpHeaders(): void
{
if (defined('TESTSUITE')) {
return;
}
/**
* Sends http headers
*/
$GLOBALS['now'] = gmdate('D, d M Y H:i:s') . ' GMT';
$headers = $this->getHttpHeaders();
foreach ($headers as $name => $value) {
header(sprintf('%s: %s', $name, $value));
}
$this->headerIsSent = true;
}
/**
* @return array<string, string>
*/
private function getHttpHeaders(): array
{
$headers = [];
/* Prevent against ClickJacking by disabling framing */
if (strtolower((string) $GLOBALS['cfg']['AllowThirdPartyFraming']) === 'sameorigin') {
$headers['X-Frame-Options'] = 'SAMEORIGIN';
} elseif ($GLOBALS['cfg']['AllowThirdPartyFraming'] !== true) {
$headers['X-Frame-Options'] = 'DENY';
}
$headers['Referrer-Policy'] = 'no-referrer';
$headers = array_merge($headers, $this->getCspHeaders());
/**
* Re-enable possible disabled XSS filters.
*
* @see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
*/
$headers['X-XSS-Protection'] = '1; mode=block';
/**
* "nosniff", prevents Internet Explorer and Google Chrome from MIME-sniffing
* a response away from the declared content-type.
*
* @see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
*/
$headers['X-Content-Type-Options'] = 'nosniff';
/**
* Adobe cross-domain-policies.
*
* @see https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
*/
$headers['X-Permitted-Cross-Domain-Policies'] = 'none';
/**
* Robots meta tag.
*
* @see https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
*/
$headers['X-Robots-Tag'] = 'noindex, nofollow';
$headers = array_merge($headers, Core::getNoCacheHeaders());
/**
* A different Content-Type is set in {@see \PhpMyAdmin\Controllers\Transformation\WrapperController}.
*/
if (! $this->isTransformationWrapper) {
// Define the charset to be used
$headers['Content-Type'] = 'text/html; charset=utf-8';
}
return $headers;
}
/**
* If the page is missing the title, this function
* will set it to something reasonable
*/
public function getPageTitle(): string
{
if (strlen($this->title) == 0) {
if ($GLOBALS['server'] > 0) {
if (strlen($GLOBALS['table'])) {
$tempTitle = $GLOBALS['cfg']['TitleTable'];
} elseif (strlen($GLOBALS['db'])) {
$tempTitle = $GLOBALS['cfg']['TitleDatabase'];
} elseif (strlen($GLOBALS['cfg']['Server']['host'])) {
$tempTitle = $GLOBALS['cfg']['TitleServer'];
} else {
$tempTitle = $GLOBALS['cfg']['TitleDefault'];
}
$this->title = htmlspecialchars(
Util::expandUserString($tempTitle)
);
} else {
$this->title = 'phpMyAdmin';
}
}
return $this->title;
}
/**
* Get all the CSP allow policy headers
*
* @return array<string, string>
*/
private function getCspHeaders(): array
{
$mapTileUrls = ' *.tile.openstreetmap.org';
$captchaUrl = '';
$cspAllow = $GLOBALS['cfg']['CSPAllow'];
if (
! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey'])
&& ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey'])
&& ! empty($GLOBALS['cfg']['CaptchaApi'])
&& ! empty($GLOBALS['cfg']['CaptchaRequestParam'])
&& ! empty($GLOBALS['cfg']['CaptchaResponseParam'])
) {
$captchaUrl = ' ' . $GLOBALS['cfg']['CaptchaCsp'] . ' ';
}
$headers = [];
$headers['Content-Security-Policy'] = sprintf(
'default-src \'self\' %s%s;script-src \'self\' \'unsafe-inline\' \'unsafe-eval\' %s%s;'
. 'style-src \'self\' \'unsafe-inline\' %s%s;img-src \'self\' data: %s%s%s;object-src \'none\';',
$captchaUrl,
$cspAllow,
$captchaUrl,
$cspAllow,
$captchaUrl,
$cspAllow,
$cspAllow,
$mapTileUrls,
$captchaUrl
);
$headers['X-Content-Security-Policy'] = sprintf(
'default-src \'self\' %s%s;options inline-script eval-script;'
. 'referrer no-referrer;img-src \'self\' data: %s%s%s;object-src \'none\';',
$captchaUrl,
$cspAllow,
$cspAllow,
$mapTileUrls,
$captchaUrl
);
$headers['X-WebKit-CSP'] = sprintf(
'default-src \'self\' %s%s;script-src \'self\' %s%s \'unsafe-inline\' \'unsafe-eval\';'
. 'referrer no-referrer;style-src \'self\' \'unsafe-inline\' %s;'
. 'img-src \'self\' data: %s%s%s;object-src \'none\';',
$captchaUrl,
$cspAllow,
$captchaUrl,
$cspAllow,
$captchaUrl,
$cspAllow,
$mapTileUrls,
$captchaUrl
);
return $headers;
}
/**
* Add recently used table and reload the navigation.
*
* @param string $db Database name where the table is located.
* @param string $table The table name
*/
private function addRecentTable(string $db, string $table): string
{
$retval = '';
if ($this->menuEnabled && strlen($table) > 0 && $GLOBALS['cfg']['NumRecentTables'] > 0) {
$tmpResult = RecentFavoriteTable::getInstance('recent')->add($db, $table);
if ($tmpResult === true) {
$retval = RecentFavoriteTable::getHtmlUpdateRecentTables();
} else {
$error = $tmpResult;
$retval = $error->getDisplay();
}
}
return $retval;
}
/**
* Returns the phpMyAdmin version to be appended to the url to avoid caching
* between versions
*
* @return string urlencoded pma version as a parameter
*/
public static function getVersionParameter(): string
{
return 'v=' . urlencode(Version::VERSION);
}
private function getVariablesForJavaScript(): string
{
$maxInputVars = ini_get('max_input_vars');
$maxInputVarsValue = $maxInputVars === false || $maxInputVars === '' ? 'false' : (int) $maxInputVars;
return $this->template->render('javascript/variables', [
'first_day_of_calendar' => $GLOBALS['cfg']['FirstDayOfCalendar'] ?? 0,
'max_input_vars' => $maxInputVarsValue,
]);
}
public function setIsTransformationWrapper(bool $isTransformationWrapper): void
{
$this->isTransformationWrapper = $isTransformationWrapper;
}
}
|