-
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathSetupCheck.php
More file actions
538 lines (450 loc) 路 14.2 KB
/
Copy pathSetupCheck.php
File metadata and controls
538 lines (450 loc) 路 14.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
<?php
namespace SMW;
use MediaWiki\Html\TemplateParser;
use RuntimeException;
use SMW\Exception\FileNotReadableException;
use SMW\Exception\JSONFileParseException;
use SMW\Localizer\LocalMessageProvider;
use SMW\Utils\Logo;
use Wikimedia\ObjectCache\HashBagOStuff;
/**
* @private
*
* @license GPL-2.0-or-later
* @since 3.1
*
* @author mwjames
*/
class SetupCheck {
/**
* Semantic MediaWiki was loaded or accessed but not correctly enabled.
*/
const ERROR_EXTENSION_LOAD = 'ERROR_EXTENSION_LOAD';
/**
* Semantic MediaWiki was loaded or accessed but not correctly enabled.
*/
const ERROR_EXTENSION_INVALID_ACCESS = 'ERROR_EXTENSION_INVALID_ACCESS';
/**
* A user tried to use `wfLoadExtension( 'SemanticMediaWiki' )` and
* the deprecated `enableSemantics` at the same time, causing the
* ExtensionRegistry to throw an "Uncaught Exception: It was attempted
* to load SemanticMediaWiki twice ..."
*/
const ERROR_EXTENSION_REGISTRY = 'ERROR_EXTENSION_REGISTRY';
/**
* A dependency (extension, MediaWiki) causes an error
*/
const ERROR_EXTENSION_DEPENDENCY = 'ERROR_EXTENSION_DEPENDENCY';
/**
* Multiple dependencies (extension, MediaWiki) caused an error
*/
const ERROR_EXTENSION_DEPENDENCY_MULTIPLE = 'ERROR_EXTENSION_DEPENDENCY_MULTIPLE';
/**
* Extension doesn't match MediaWiki or the PHP requirement.
*/
const ERROR_EXTENSION_INCOMPATIBLE = 'ERROR_EXTENSION_INCOMPATIBLE';
/**
* Extension doesn't match the DB requirement for Semantic MediaWiki.
*/
const ERROR_DB_REQUIREMENT_INCOMPATIBLE = 'ERROR_DB_REQUIREMENT_INCOMPATIBLE';
/**
* The upgrade key has change causing the schema to be invalid
*/
const ERROR_SCHEMA_INVALID_KEY = 'ERROR_SCHEMA_INVALID_KEY';
/**
* A selected default profile could not be loaded or is unknown.
*/
const ERROR_CONFIG_PROFILE_UNKNOWN = 'ERROR_CONFIG_PROFILE_UNKNOWN';
/**
* The system is currently in a maintenance window
*/
const MAINTENANCE_MODE = 'MAINTENANCE_MODE';
/**
* Maps the `type` string used in `setupcheck.json` to the PascalCase
* name of the corresponding Mustache template.
*/
private const TEMPLATE_MAP = [
'section' => 'Section',
'version' => 'Version',
'paragraph' => 'Paragraph',
'errorbox' => 'Errorbox',
'db-requirement' => 'DbRequirement',
];
private array $options;
private ?SetupFile $setupFile;
private TemplateParser $templateParser;
private LocalMessageProvider $localMessageProvider;
private array $definitions = [];
/**
* @var string
*/
private $languageCode = 'en';
private string $fallbackLanguageCode = 'en';
private bool $sentHeader = true;
private string $errorType = '';
private string $errorMessage = '';
/**
* @var string
*/
private $traceString = '';
/**
* @since 3.1
*
* @param array $options
* @param SetupFile|null $setupFile
*/
public function __construct( array $options, ?SetupFile $setupFile = null ) {
$this->options = $options;
$this->setupFile = $setupFile;
// `SetupCheck` can run very early, before MediaWiki's service container
// is bootstrapped. `TemplateParser` would call `MediaWikiServices::getInstance()`
// to obtain a cache when none is passed, which throws in that early-boot
// window. An in-process `HashBagOStuff` removes that service dependency;
// the setup-check page is shown rarely so the compiled-template cache is
// not performance-critical here.
$this->templateParser = new TemplateParser(
__DIR__ . '/../templates/SetupCheck',
new HashBagOStuff()
);
$this->localMessageProvider = new LocalMessageProvider( '/local/setupcheck.i18n.json' );
if ( $this->setupFile === null ) {
$this->setupFile = new SetupFile();
}
}
/**
* @since 3.2
*
* @param string $file
*
* @return array
* @throws RuntimeException
*/
public static function readFromFile( string $file ): array {
if ( !is_readable( $file ) ) {
throw new FileNotReadableException( $file );
}
$contents = json_decode(
file_get_contents( $file ),
true
);
if ( json_last_error() === JSON_ERROR_NONE ) {
return $contents;
}
throw new JSONFileParseException( $file );
}
/**
* @since 3.1
*
* @param SetupFile|null $setupFile
*
* @return SetupCheck
*/
public static function newFromDefaults( ?SetupFile $setupFile = null ): SetupCheck {
if ( !defined( 'SMW_VERSION' ) ) {
$version = self::readFromFile( $GLOBALS['smwgIP'] . 'extension.json' )['version'];
} else {
$version = SMW_VERSION;
}
$setupCheck = new SetupCheck(
[
'SMW_VERSION' => $version,
'MW_VERSION' => $GLOBALS['wgVersion'] ?? 'unknown', // MW_VERSION may not yet be defined!!
'smwgUpgradeKey' => $GLOBALS['smwgUpgradeKey']
],
$setupFile
);
return $setupCheck;
}
/**
* @since 3.2
*/
public function disableHeader(): void {
$this->sentHeader = false;
}
/**
* @since 3.1
*
* @return bool
*/
public function isCli(): bool {
return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
}
/**
* @since 3.1
*
* @param string $traceString
*/
public function setTraceString( $traceString ): void {
$this->traceString = $traceString;
}
/**
* @since 3.2
*
* @param string $errorMessage
*/
public function setErrorMessage( string $errorMessage ): void {
$this->errorMessage = $errorMessage;
}
/**
* @since 3.2
*
* @param string $errorType
*/
public function setErrorType( string $errorType ): void {
$this->errorType = $errorType;
}
/**
* @since 3.2
*
* @return bool
*/
public function isError( string $error ): bool {
return $this->errorType === $error;
}
/**
* @since 3.1
*
* @return bool
*/
public function hasError(): bool {
$this->errorType = '';
if ( $this->setupFile->inMaintenanceMode() ) {
$this->errorType = self::MAINTENANCE_MODE;
} elseif ( !$this->isCli() && !$this->setupFile->hasDatabaseMinRequirement() ) {
$this->errorType = self::ERROR_DB_REQUIREMENT_INCOMPATIBLE;
} elseif ( !$this->setupFile->isGoodSchema() ) {
$this->errorType = self::ERROR_SCHEMA_INVALID_KEY;
}
return $this->errorType !== '';
}
/**
* @note Adding a new error type requires to:
*
* - Define a constant to clearly identify the type of error
* - Extend the `setupcheck.json` to add a definition for the new type and
* specify which information should be displayed
* - In case the existing HTML elements aren't sufficient, create a new
* Mustache template and define the HTML code
*
* The `TemplateParser` will replace arguments defined in the HTML hereby
* absolving this class from any direct HTML manipulation.
*
* @since 3.1
*
* @param bool $isCli
*
* @return string|array|null
*/
public function getError( $isCli = false ): string|array|null {
$error = [
'title' => '',
'content' => ''
];
$this->languageCode = $_GET['uselang'] ?? 'en';
// Output forms for different error types are registered with a JSON file.
$this->definitions = $this->readFromFile(
$GLOBALS['smwgDir'] . '/data/setupcheck/setupcheck.json'
);
// Error messages are specified in a special i18n JSON file to avoid relying
// on the MW message system especially when SMW isn't fully registered
// and we are unable to access any `smw-...` message keys from the standard
// i18n files.
$this->localMessageProvider->setLanguageCode(
$this->languageCode
);
$this->localMessageProvider->loadMessages();
if ( !isset( $this->definitions['error_types'][$this->errorType] ) ) {
throw new RuntimeException( "The `{$this->errorType}` type is not defined in the `setupcheck.json`!" );
}
$error = $this->createErrorContent( $this->errorType );
if ( $isCli === false ) {
$content = $this->buildHTML( $error );
$this->header( 'Content-Type: text/html; charset=UTF-8' );
$this->header( 'Content-Length: ' . strlen( $content ) );
$this->header( 'Cache-control: no-store' );
$this->header( 'Pragma: no-cache' );
$this->header( 'HTTP/1.1 503 Service Temporarily Unavailable' );
$this->header( 'Status: 503 Service Temporarily Unavailable' );
$this->header( 'Retry-After: 10' ); // 10 seconds
} else {
$content = $error['title'] . "\n\n" . $error['content'];
$content = str_replace(
[ '<!-- ROW -->', '</h3>', '</h4>', '</p>', ' ' ],
[ "\n", "\n\n", "\n\n", "\n\n", ' ' ],
$content
);
$content = "\n" . wordwrap( strip_tags( trim( $content ) ), 73 );
}
return $content;
}
/**
* @since 3.1
*
* @param bool $isCli
*
* @return never
*/
public function showErrorAndAbort( $isCli = false ): void {
echo $this->getError( $isCli );
if ( ob_get_level() ) {
ob_flush();
flush();
ob_end_clean();
}
die();
}
private function header( string $text ): void {
if ( $this->sentHeader ) {
header( $text );
}
}
private function createErrorContent( string $type ): array {
$indicator_title = 'Error';
$template = $this->definitions['error_types'][$type];
$content = '';
/**
* Actual output form
*/
foreach ( $template['output_form'] as $value ) {
$content .= $this->createContent( $value, $type );
}
/**
* Special handling for the progress output
*/
if ( isset( $template['progress'] ) ) {
foreach ( $template['progress'] as $value ) {
$text = $this->createCopy( $value['text'] );
if ( isset( $value['progress_keys'] ) ) {
$content .= $this->createProgressIndicator( $value );
}
$content .= $this->renderElement( $value['type'], $text );
}
}
/**
* Special handling for the stack trace output
*/
if ( isset( $template['stack_trace'] ) && $this->traceString !== '' ) {
foreach ( $template['stack_trace'] as $value ) {
$content .= $this->createContent( $value, $type );
}
}
if ( isset( $template['indicator_title'] ) ) {
$indicator_title = $this->createCopy( $template['indicator_title'] );
}
$error = [
'title' => 'Semantic MediaWiki',
'indicator_title' => $indicator_title,
'content' => $content,
'borderColor' => $template['indicator_color']
];
return $error;
}
private function createContent( array $value, string $type ): string {
if ( $value['text'] === 'ERROR_TEXT' ) {
$text = str_replace( "\n", '<br>', $this->errorMessage );
} elseif ( $value['text'] === 'ERROR_TEXT_MULTIPLE' ) {
$errors = explode( "\n", $this->errorMessage );
$text = '<ul><li>' . implode( '</li><li>', array_filter( $errors ) ) . '</li></ul>';
} elseif ( $value['text'] === 'TRACE_STRING' ) {
$text = $this->traceString;
} else {
$text = $this->createCopy( $value['text'] );
}
return $this->renderElement( $value['type'], $text, $type );
}
/**
* Renders one of the element templates (`section`, `version`, `paragraph`,
* `errorbox`, `db-requirement`) for the given JSON `type`.
*/
private function renderElement( string $elementType, string $text, string $codeType = '' ): string {
// The type is expected to match a defined template and in an event
// that those don't match an exception will be raised.
if ( !isset( self::TEMPLATE_MAP[$elementType] ) ) {
throw new RuntimeException( "The `$elementType` type does not match a known template!" );
}
$viewModel = [
'data-template' => $elementType,
];
// `paragraph` and `errorbox` carry pre-rendered markup (raw); `section`
// shows a plain escaped heading.
if ( $elementType === 'paragraph' || $elementType === 'errorbox' ) {
$viewModel['html-text'] = $text;
} else {
$viewModel['text'] = $text;
}
if ( $elementType === 'version' ) {
$viewModel['version-title'] = $text;
$viewModel['smw-title'] = 'Semantic MediaWiki';
$viewModel['smw-version'] = $this->options['SMW_VERSION'] ?? 'n/a';
$viewModel['smw-upgradekey'] = $this->options['smwgUpgradeKey'] ?? 'n/a';
$viewModel['mw-title'] = 'MediaWiki';
$viewModel['mw-version'] = $this->options['MW_VERSION'] ?? 'n/a';
$viewModel['code-title'] = $this->createCopy( 'smw-setupcheck-code' );
$viewModel['code-type'] = $codeType;
}
if ( $elementType === 'db-requirement' ) {
$requirements = $this->setupFile->get( SetupFile::DB_REQUIREMENTS );
$viewModel['version-title'] = $text;
$viewModel['db-title'] = $this->createCopy( 'smw-setupcheck-db-title' );
$viewModel['db-type'] = $requirements['type'] ?? 'N/A';
$viewModel['db-current-title'] = $this->createCopy( 'smw-setupcheck-db-current-title' );
$viewModel['db-minimum-title'] = $this->createCopy( 'smw-setupcheck-db-minimum-title' );
$viewModel['db-current-version'] = $requirements['latest_version'] ?? 'N/A';
$viewModel['db-minimum-version'] = $requirements['minimum_version'] ?? 'N/A';
}
return $this->templateParser->processTemplate(
self::TEMPLATE_MAP[$elementType],
$viewModel
);
}
private function createProgressIndicator( array $value ): string {
$maintenanceMode = (array)$this->setupFile->getMaintenanceMode();
$content = '';
foreach ( $maintenanceMode as $key => $v ) {
$label = $key;
if ( isset( $value['progress_keys'][$key] ) ) {
$label = $this->createCopy( $value['progress_keys'][$key] );
}
$content .= $this->templateParser->processTemplate(
'Progress',
[
'data-template' => 'setupcheck-progress',
'label' => $label,
'value' => $v,
]
);
}
return $content;
}
private function createCopy( $value, $default = 'n/a' ) {
if ( is_string( $value ) && $this->localMessageProvider->has( $value ) ) {
return $this->localMessageProvider->msg( $value );
}
return $default;
}
private function buildHTML( array $error ): string {
$html = $this->templateParser->processTemplate(
'SetupCheck',
[
'logo' => Logo::get( 'small' ),
'title' => $error['title'] ?? '',
'indicator' => $error['indicator_title'] ?? '',
'html-content' => $error['content'] ?? '',
'borderColor' => $error['borderColor'] ?? '#fff',
'refresh' => $error['refresh'] ?? '30',
]
);
// Minify CSS rules, we keep them readable in the template to allow for
// better adaption
// @see http://manas.tungare.name/software/css-compression-in-php/
$html = preg_replace_callback( "/<style\\b[^>]*>(.*?)<\\/style>/s", static function ( array $matches ): string {
// Remove space after colons
$style = str_replace( ': ', ':', $matches[0] );
// Remove whitespace
return str_replace( [ "\r\n", "\r", "\n", "\t", ' ', ' ', ' ' ], '', $style );
},
$html
);
return $html;
}
}