Difference between revisions of "SMWIssue4785"
Jump to navigation
Jump to search
Line 2: | Line 2: | ||
__TOC__ | __TOC__ | ||
= SetupCheck.php = | = SetupCheck.php = | ||
− | <source lang='php' | + | <source lang='php' highlight="383-396,402-406"> |
<?php | <?php | ||
Line 587: | Line 587: | ||
} | } | ||
</source> | </source> | ||
+ | |||
= SetupFile.php = | = SetupFile.php = | ||
<source lang='php' line highlight='104-172,181,516-519'> | <source lang='php' line highlight='104-172,181,516-519'> |
Revision as of 20:26, 4 December 2022
Modified files for https://github.com/SemanticMediaWiki/SemanticMediaWiki/issues/4785
SetupCheck.php
<?php
namespace SMW;
use SMW\Utils\TemplateEngine;
use SMW\Utils\Logo;
use SMW\Localizer\LocalMessageProvider;
use SMW\Exception\FileNotReadableException;
use SMW\Exception\JSONFileParseException;
use RuntimeException;
/**
* @private
*
* @license GNU GPL v2+
* @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
* `enableSemantics` at the same 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';
/**
* @var []
*/
private $options = [];
/**
* @var SetupFile
*/
private $setupFile;
/**
* @var TemplateEngine
*/
private $templateEngine;
/**
* @var LocalMessageProvider
*/
private $localMessageProvider;
/**
* @var []
*/
private $definitions = [];
/**
* @var string
*/
private $languageCode = 'en';
/**
* @var string
*/
private $fallbackLanguageCode = 'en';
/**
* @var boolean
*/
private $sentHeader = true;
/**
* @var string
*/
private $errorType = '';
/**
* @var string
*/
private $errorMessage = '';
/**
* @var string
*/
private $traceString = '';
/**
* @since 3.1
*
* @param array $vars
* @param SetupFile|null $setupFile
*/
public function __construct( array $options, SetupFile $setupFile = null ) {
$this->options = $options;
$this->setupFile = $setupFile;
$this->templateEngine = new TemplateEngine();
$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 ) {
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'], // MW_VERSION may not yet be defined!!
'wgLanguageCode' => $GLOBALS['wgLanguageCode'],
'smwgUpgradeKey' => $GLOBALS['smwgUpgradeKey']
],
$setupFile
);
return $setupCheck;
}
/**
* @since 3.2
*/
public function disableHeader() {
$this->sentHeader = false;
}
/**
* @since 3.1
*
* @return boolean
*/
public function isCli() {
return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
}
/**
* @since 3.1
*
* @param string $traceString
*/
public function setTraceString( $traceString ) {
$this->traceString = $traceString;
}
/**
* @since 3.2
*
* @param string $errorMessage
*/
public function setErrorMessage( string $errorMessage ) {
$this->errorMessage = $errorMessage;
}
/**
* @since 3.2
*
* @param string $errorType
*/
public function setErrorType( string $errorType ) {
$this->errorType = $errorType;
}
/**
* @since 3.2
*
* @return boolean
*/
public function isError( string $error ) : bool {
return $this->errorType === $error;
}
/**
* @since 3.1
*
* @return boolean
*/
public function hasError() {
$this->errorType = '';
// When it is not a test run or run from the command line we expect that
// the extension is registered using `enableSemantics`
if ( !defined( 'SMW_EXTENSION_LOADED' ) && !$this->isCli() ) {
$this->errorType = self::ERROR_EXTENSION_LOAD;
} elseif ( $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() === false ) {
$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
* zxy.ms file and define the HTML code
*
* The `TemplateEngine` will replace arguments defined in the HTML hereby
* absolving this class from any direct HTML manipulation.
*
* @since 3.1
*
* @param boolean $isCli
*
* @return string
*/
public function getError( $isCli = false ) {
$error = [
'title' => '',
'content' => ''
];
$this->languageCode = $_GET['uselang'] ?? $this->options['wgLanguageCode'] ?? 'en';
// Output forms for different error types are registered with a JSON file.
$this->definitions = $this->readFromFile(
$GLOBALS['smwgDir'] . '/data/template/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();
// HTML specific formatting is contained in the following files where
// a defined group of targets correspond to types used in the JSON
$this->templateEngine->bulkLoad(
[
'/setupcheck/setupcheck.ms' => 'setupcheck-html',
'/setupcheck/setupcheck.progress.ms' => 'setupcheck-progress',
// Target specific elements
'/setupcheck/setupcheck.section.ms' => 'section',
'/setupcheck/setupcheck.version.ms' => 'version',
'/setupcheck/setupcheck.paragraph.ms' => 'paragraph',
'/setupcheck/setupcheck.errorbox.ms' => 'errorbox',
'/setupcheck/setupcheck.db.requirement.ms' => 'db-requirement',
]
);
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: none' );
$this->header( 'Pragma: no-cache' );
} 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 boolean $isCli
*/
public function showErrorAndAbort( $isCli = false ) {
echo $this->getError( $isCli );
if ( ob_get_level() ) {
ob_flush();
flush();
ob_end_clean();
}
die();
}
private function header( $text ) {
if ( $this->sentHeader ) {
header( $text );
}
}
private function schemaError() {
// get trace
// https://stackoverflow.com/a/7039409/1497139
//
$e = new \Exception;
$content ='<pre>'.$e->getTraceAsString().'</pre>';
$content .='PHP_SAPI: '.PHP_SAPI."<br>";
$isCli=$this->isCli();
$schemaState=SetupFile::getSchemaState($isCli);
$content.='Schema state: '.$schemaState."<br>";
$upgradeKeyBase=SetupFile::makeKey($GLOBALS);
$content.='upgrade key base: '.$upgradeKeyBase;
return $content;
}
private function createErrorContent( $type ) {
$indicator_title = 'Error';
$template = $this->definitions['error_types'][$type];
$content = '';
if ($type==self::ERROR_SCHEMA_INVALID_KEY) {
$content.=$this->schemaError($this->isCli());
}
/**
* 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 );
}
$args = [
'text' => $text,
'template' => $value['type']
];
$this->templateEngine->compile(
$value['type'],
$args
);
$content .= $this->templateEngine->publish( $value['type'] );
}
}
/**
* 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( $value, $type ) {
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'] );
}
$args = [
'text' => $text,
'template' => $value['type']
];
if ( $value['type'] === 'version' ) {
$args['version-title'] = $text;
$args['smw-title'] = 'Semantic MediaWiki';
$args['smw-version'] = $this->options['SMW_VERSION'] ?? 'n/a';
$args['smw-upgradekey'] = $this->options['smwgUpgradeKey'] ?? 'n/a';
$args['mw-title'] = 'MediaWiki';
$args['mw-version'] = $this->options['MW_VERSION'] ?? 'n/a';
$args['code-title'] = $this->createCopy( 'smw-setupcheck-code' );
$args['code-type'] = $type;
}
if ( $value['type'] === 'db-requirement' ) {
$requirements = $this->setupFile->get( SetupFile::DB_REQUIREMENTS );
$args['version-title'] = $text;
$args['db-title'] = $this->createCopy( 'smw-setupcheck-db-title' );
$args['db-type'] = $requirements['type'] ?? 'N/A';
$args['db-current-title'] = $this->createCopy( 'smw-setupcheck-db-current-title' );
$args['db-minimum-title'] = $this->createCopy( 'smw-setupcheck-db-minimum-title' );
$args['db-current-version'] = $requirements['latest_version'] ?? 'N/A';
$args['db-minimum-version'] = $requirements['minimum_version'] ?? 'N/A';
}
// The type is expected to match a defined target and in an event
// that those don't match an exception will be raised.
$this->templateEngine->compile(
$value['type'],
$args
);
return $this->templateEngine->publish( $value['type'] );
}
private function createProgressIndicator( $value ) {
$maintenanceMode = (array)$this->setupFile->getMaintenanceMode();
$content = '';
foreach ( $maintenanceMode as $key => $v ) {
$args = [
'label' => $key,
'value' => $v
];
if ( isset( $value['progress_keys'][$key] ) ) {
$args['label'] = $this->createCopy( $value['progress_keys'][$key] );
}
$this->templateEngine->compile(
'setupcheck-progress',
$args
);
$content .= $this->templateEngine->publish( 'setupcheck-progress' );
}
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 ) {
$args = [
'logo' => Logo::get( 'small' ),
'title' => $error['title'] ?? '',
'indicator' => $error['indicator_title'] ?? '',
'content' => $error['content'] ?? '',
'borderColor' => $error['borderColor'] ?? '#fff',
'refresh' => $error['refresh'] ?? '30',
];
$this->templateEngine->compile(
'setupcheck-html',
$args
);
$html = $this->templateEngine->publish( 'setupcheck-html' );
// 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", function( $matches ) {
// Remove space after colons
$style = str_replace( ': ', ':', $matches[0] );
// Remove whitespace
return str_replace( [ "\r\n", "\r", "\n", "\t", ' ', ' ', ' '], '', $style );
},
$html
);
return $html;
}
}
SetupFile.php
1<?php
2
3namespace SMW;
4
5use SMW\Exception\FileNotWritableException;
6use SMW\Utils\File;
7use SMW\SQLStore\Installer;
8
9/**
10 * @private
11 *
12 * @license GNU GPL v2+
13 * @since 3.1
14 *
15 * @author mwjames
16 */
17class SetupFile {
18
19 /**
20 * Describes the maintenance mode
21 */
22 const MAINTENANCE_MODE = 'maintenance_mode';
23
24 /**
25 * Describes the upgrade key
26 */
27 const UPGRADE_KEY = 'upgrade_key';
28
29 /**
30 * Describes the database requirements
31 */
32 const DB_REQUIREMENTS = 'db_requirements';
33
34 /**
35 * Describes the entity collection setting
36 */
37 const ENTITY_COLLATION = 'entity_collation';
38
39 /**
40 * Key that describes the date of the last table optimization run.
41 */
42 const LAST_OPTIMIZATION_RUN = 'last_optimization_run';
43
44 /**
45 * Describes the file name
46 */
47 const FILE_NAME = '.smw.json';
48
49 /**
50 * Describes incomplete tasks
51 */
52 const INCOMPLETE_TASKS = 'incomplete_tasks';
53
54 /**
55 * Versions
56 */
57 const LATEST_VERSION = 'latest_version';
58 const PREVIOUS_VERSION = 'previous_version';
59
60 /**
61 * @var File
62 */
63 private $file;
64
65 /**
66 * @since 3.1
67 *
68 * @param File|null $file
69 */
70 public function __construct( File $file = null ) {
71 $this->file = $file;
72
73 if ( $this->file === null ) {
74 $this->file = new File();
75 }
76 }
77
78 /**
79 * @since 3.1
80 *
81 * @param array $vars
82 */
83 public function loadSchema( &$vars = [] ) {
84
85 if ( $vars === [] ) {
86 $vars = $GLOBALS;
87 }
88
89 if ( isset( $vars['smw.json'] ) ) {
90 return;
91 }
92
93 // @see #3506
94 $file = File::dir( $vars['smwgConfigFileDir'] . '/' . self::FILE_NAME );
95
96 // Doesn't exist? The `Setup::init` will take care of it by trying to create
97 // a new file and if it fails or unable to do so wail raise an exception
98 // as we expect to have access to it.
99 if ( is_readable( $file ) ) {
100 $vars['smw.json'] = json_decode( file_get_contents( $file ), true );
101 }
102 }
103
104 /**
105 * @since 3.1
106 *
107 * @param boolean $isCli
108 *
109 * @return boolean
110 */
111 public static function isGoodSchema( $isCli = false ) {
112 // get the schema State as a human readable description
113 $schemaState=SetupFile::getSchemaState($isCli);
114 // check that it starts with "ok:" and not "error:"
115 $result=SetupFile::strStartsWith($schemaState,"ok:");
116 return $result;
117 }
118
119 /**
120 * @since 3.1.7
121 *
122 * see https://stackoverflow.com/a/6513929/1497139
123 *
124 * @param string $haystack
125 * @param string $needle
126 *
127 * return boolean
128 */
129 public static function strStartsWith($haystack, $needle) {
130 return (strpos($haystack, $needle) === 0);
131 }
132
133 /**
134 * @since 3.1.7
135 *
136 * @param boolean $isCli
137 *
138 * @return string
139 */
140 public static function getSchemaState( $isCli = false ) {
141
142 if ( $isCli && defined( 'MW_PHPUNIT_TEST' ) ) {
143 return "ok: CLI with PHP Unit Test active";
144 }
145
146 if ( $isCli === false && ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) ) {
147 return "ok: isCli is true and PHP_SAPI cli/phpdbg=".PHP_SAPI;
148 }
149
150 // #3563, Use the specific wiki-id as identifier for the instance in use
151 $id = Site::id();
152
153 if ( !isset( $GLOBALS['smw.json'][$id]['upgrade_key'] ) ) {
154 global $smwgConfigFileDir;
155 return "error: smw.json for ".$id." upgrade key missing - you might want to check \$smwgConfigFileDir:".$smwgConfigFileDir;
156 }
157
158 $upgradeKey = self::makeUpgradeKey( $GLOBALS );
159 $expected =$GLOBALS['smw.json'][$id]['upgrade_key'];
160 if ( $upgradeKey === $expected )
161 $schemaState= "ok: found upgradeKey.".$upgradeKey;
162 else
163 $schemaState= "error: expected upgradeKey ".$expected." for ".$id." but found ".$upgradeKey;
164
165 if (
166 isset( $GLOBALS['smw.json'][$id][self::MAINTENANCE_MODE] ) &&
167 $GLOBALS['smw.json'][$id][self::MAINTENANCE_MODE] !== false ) {
168 $schemaState= "error: upgradeKey ".$upgradeKey." is ok but maintainance is active";
169 }
170
171 return $schemaState;
172 }
173
174 /**
175 * @since 3.1
176 *
177 * @param array $vars
178 *
179 * @return string
180 */
181 public static function makeUpgradeKey( $vars ) {
182 return sha1( self::makeKey( $vars ) );
183 }
184
185 /**
186 * @since 3.1
187 *
188 * @param array $vars
189 *
190 * @return boolean
191 */
192 public function inMaintenanceMode( $vars = [] ) {
193
194 if ( !defined( 'MW_PHPUNIT_TEST' ) && ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) ) {
195 return false;
196 }
197
198 if ( $vars === [] ) {
199 $vars = $GLOBALS;
200 }
201
202 $id = Site::id();
203
204 if ( !isset( $vars['smw.json'][$id][self::MAINTENANCE_MODE] ) ) {
205 return false;
206 }
207
208 return $vars['smw.json'][$id][self::MAINTENANCE_MODE] !== false;
209 }
210
211 /**
212 * @since 3.1
213 *
214 * @param array $vars
215 *
216 * @return []
217 */
218 public function getMaintenanceMode( $vars = [] ) {
219
220 if ( $vars === [] ) {
221 $vars = $GLOBALS;
222 }
223
224 $id = Site::id();
225
226 if ( !isset( $vars['smw.json'][$id][self::MAINTENANCE_MODE] ) ) {
227 return [];
228 }
229
230 return $vars['smw.json'][$id][self::MAINTENANCE_MODE];
231 }
232
233 /**
234 * Tracking the latest and previous version, which allows us to decide whether
235 * current activties relate to an install (new) or upgrade.
236 *
237 * @since 3.2
238 *
239 * @param int $version
240 */
241 public function setLatestVersion( $version ) {
242
243 $latest = $this->get( SetupFile::LATEST_VERSION );
244 $previous = $this->get( SetupFile::PREVIOUS_VERSION );
245
246 if ( $latest === null && $previous === null ) {
247 $this->set(
248 [
249 SetupFile::LATEST_VERSION => $version
250 ]
251 );
252 } elseif ( $latest !== $version ) {
253 $this->set(
254 [
255 SetupFile::LATEST_VERSION => $version,
256 SetupFile::PREVIOUS_VERSION => $latest
257 ]
258 );
259 }
260 }
261
262 /**
263 * @since 3.2
264 *
265 * @param string $key
266 * @param array $args
267 */
268 public function addIncompleteTask( string $key, array $args = [] ) {
269
270 $incomplete_tasks = $this->get( self::INCOMPLETE_TASKS );
271
272 if ( $incomplete_tasks === null ) {
273 $incomplete_tasks = [];
274 }
275
276 $incomplete_tasks[$key] = $args === [] ? true : $args;
277
278 $this->set( [ self::INCOMPLETE_TASKS => $incomplete_tasks ] );
279 }
280
281 /**
282 * @since 3.2
283 *
284 * @param string $key
285 */
286 public function removeIncompleteTask( string $key ) {
287
288 $incomplete_tasks = $this->get( self::INCOMPLETE_TASKS );
289
290 if ( $incomplete_tasks === null ) {
291 $incomplete_tasks = [];
292 }
293
294 unset( $incomplete_tasks[$key] );
295
296 $this->set( [ self::INCOMPLETE_TASKS => $incomplete_tasks ] );
297 }
298
299 /**
300 * @since 3.2
301 *
302 * @param array $vars
303 *
304 * @return boolean
305 */
306 public function hasDatabaseMinRequirement( array $vars = [] ) : bool {
307
308 if ( $vars === [] ) {
309 $vars = $GLOBALS;
310 }
311
312 $id = Site::id();
313
314 // No record means, no issues!
315 if ( !isset( $vars['smw.json'][$id][self::DB_REQUIREMENTS] ) ) {
316 return true;
317 }
318
319 $requirements = $vars['smw.json'][$id][self::DB_REQUIREMENTS];
320
321 return version_compare( $requirements['latest_version'], $requirements['minimum_version'], 'ge' );
322 }
323
324 /**
325 * @since 3.1
326 *
327 * @param array $vars
328 *
329 * @return []
330 */
331 public function findIncompleteTasks( $vars = [] ) {
332
333 if ( $vars === [] ) {
334 $vars = $GLOBALS;
335 }
336
337 $id = Site::id();
338 $tasks = [];
339
340 // Key field => [ value that constitutes the `INCOMPLETE` state, error msg ]
341 $checks = [
342 \SMW\SQLStore\Installer::POPULATE_HASH_FIELD_COMPLETE => [ false, 'smw-install-incomplete-populate-hash-field' ],
343 \SMW\Elastic\ElasticStore::REBUILD_INDEX_RUN_COMPLETE => [ false, 'smw-install-incomplete-elasticstore-indexrebuild' ]
344 ];
345
346 foreach ( $checks as $key => $value ) {
347
348 if ( !isset( $vars['smw.json'][$id][$key] ) ) {
349 continue;
350 }
351
352 if ( $vars['smw.json'][$id][$key] === $value[0] ) {
353 $tasks[] = $value[1];
354 }
355 }
356
357 if ( isset( $vars['smw.json'][$id][self::INCOMPLETE_TASKS] ) ) {
358 foreach ( $vars['smw.json'][$id][self::INCOMPLETE_TASKS] as $key => $args ) {
359 if ( $args === true ) {
360 $tasks[] = $key;
361 } else {
362 $tasks[] = [ $key, $args ];
363 }
364 }
365 }
366
367 return $tasks;
368 }
369
370 /**
371 * @since 3.1
372 *
373 * @param mixed $maintenanceMode
374 */
375 public function setMaintenanceMode( $maintenanceMode, $vars = [] ) {
376
377 if ( $vars === [] ) {
378 $vars = $GLOBALS;
379 }
380
381 $this->write(
382 [
383 self::UPGRADE_KEY => self::makeUpgradeKey( $vars ),
384 self::MAINTENANCE_MODE => $maintenanceMode
385 ],
386 $vars
387 );
388 }
389
390 /**
391 * @since 3.1
392 *
393 * @param array $vars
394 */
395 public function finalize( $vars = [] ) {
396
397 if ( $vars === [] ) {
398 $vars = $GLOBALS;
399 }
400
401 // #3563, Use the specific wiki-id as identifier for the instance in use
402 $key = self::makeUpgradeKey( $vars );
403 $id = Site::id();
404
405 if (
406 isset( $vars['smw.json'][$id][self::UPGRADE_KEY] ) &&
407 $key === $vars['smw.json'][$id][self::UPGRADE_KEY] &&
408 $vars['smw.json'][$id][self::MAINTENANCE_MODE] === false ) {
409 return false;
410 }
411
412 $this->write(
413 [
414 self::UPGRADE_KEY => $key,
415 self::MAINTENANCE_MODE => false
416 ],
417 $vars
418 );
419 }
420
421 /**
422 * @since 3.1
423 *
424 * @param array $vars
425 */
426 public function reset( $vars = [] ) {
427
428 if ( $vars === [] ) {
429 $vars = $GLOBALS;
430 }
431
432 $id = Site::id();
433 $args = [];
434
435 if ( !isset( $vars['smw.json'][$id] ) ) {
436 return;
437 }
438
439 $vars['smw.json'][$id] = [];
440
441 $this->write( [], $vars );
442 }
443
444 /**
445 * @since 3.1
446 *
447 * @param array $args
448 */
449 public function set( array $args, $vars = [] ) {
450
451 if ( $vars === [] ) {
452 $vars = $GLOBALS;
453 }
454
455 $this->write( $args, $vars );
456 }
457
458 /**
459 * @since 3.1
460 *
461 * @param array $args
462 */
463 public function get( $key, $vars = [] ) {
464
465 if ( $vars === [] ) {
466 $vars = $GLOBALS;
467 }
468
469 $id = Site::id();
470
471 if ( isset( $vars['smw.json'][$id][$key] ) ) {
472 return $vars['smw.json'][$id][$key];
473 }
474
475 return null;
476 }
477
478 /**
479 * @since 3.1
480 *
481 * @param string $key
482 */
483 public function remove( $key, $vars = [] ) {
484
485 if ( $vars === [] ) {
486 $vars = $GLOBALS;
487 }
488
489 $this->write( [ $key => null ], $vars );
490 }
491
492 /**
493 * @since 3.1
494 *
495 * @param array $vars
496 * @param array $args
497 */
498 public function write( array $args, array $vars ) {
499
500 $configFile = File::dir( $vars['smwgConfigFileDir'] . '/' . self::FILE_NAME );
501 $id = Site::id();
502
503 if ( !isset( $vars['smw.json'] ) ) {
504 $vars['smw.json'] = [];
505 }
506
507 foreach ( $args as $key => $value ) {
508 // NULL means that the key key is removed
509 if ( $value === null ) {
510 unset( $vars['smw.json'][$id][$key] );
511 } else {
512 $vars['smw.json'][$id][$key] = $value;
513 }
514 }
515
516 // Log the base elements used for computing the key
517 $vars['smw.json'][$id]['upgrade_key_base'] = self::makeKey(
518 $vars
519 );
520
521 // Remove legacy
522 if ( isset( $vars['smw.json']['upgradeKey'] ) ) {
523 unset( $vars['smw.json']['upgradeKey'] );
524 }
525 if ( isset( $vars['smw.json'][$id]['in.maintenance_mode'] ) ) {
526 unset( $vars['smw.json'][$id]['in.maintenance_mode'] );
527 }
528
529 try {
530 $this->file->write(
531 $configFile,
532 json_encode( $vars['smw.json'], JSON_PRETTY_PRINT )
533 );
534 } catch( FileNotWritableException $e ) {
535 // Users may not have `wgShowExceptionDetails` enabled and would
536 // therefore not see the exception error message hence we fail hard
537 // and die
538 die(
539 "\n\nERROR: " . $e->getMessage() . "\n" .
540 "\n The \"smwgConfigFileDir\" setting should point to a" .
541 "\n directory that is persistent and writable!\n"
542 );
543 }
544 }
545
546 /**
547 * Listed keys will have a "global" impact of how data are stored, formatted,
548 * or represented in Semantic MediaWiki. In most cases it will require an action
549 * from an adminstrator when one of those keys are altered.
550 */
551 public static function makeKey( $vars ) {
552
553 // Only recognize those properties that require a fixed table
554 $pageSpecialProperties = array_intersect(
555 // Special properties enabled?
556 $vars['smwgPageSpecialProperties'],
557
558 // Any custom fixed properties require their own table?
559 TypesRegistry::getFixedProperties( 'custom_fixed' )
560 );
561
562 $pageSpecialProperties = array_unique( $pageSpecialProperties );
563
564 // Sort to ensure the key contains the same order
565 sort( $vars['smwgFixedProperties'] );
566 sort( $pageSpecialProperties );
567
568 // The following settings influence the "shape" of the tables required
569 // therefore use the content to compute a key that reflects any
570 // changes to them
571 $components = [
572 $vars['smwgUpgradeKey'],
573 $vars['smwgDefaultStore'],
574 $vars['smwgFixedProperties'],
575 $vars['smwgEnabledFulltextSearch'],
576 $pageSpecialProperties
577 ];
578
579 // Only add the key when it is different from the default setting
580 if ( $vars['smwgEntityCollation'] !== 'identity' ) {
581 $components += [ 'smwgEntityCollation' => $vars['smwgEntityCollation'] ];
582 }
583
584 if ( $vars['smwgFieldTypeFeatures'] !== false ) {
585 $components += [ 'smwgFieldTypeFeatures' => $vars['smwgFieldTypeFeatures'] ];
586 }
587
588 // Recognize when the version requirements change and force
589 // an update to be able to check the requirements
590 $components += Setup::MINIMUM_DB_VERSION;
591
592 return json_encode( $components );
593 }
594
595}