MediaWiki REL1_30
Command.php
Go to the documentation of this file.
1<?php
22
23use Exception;
27use Psr\Log\LoggerAwareTrait;
28use Psr\Log\NullLogger;
29
35class Command {
36 use LoggerAwareTrait;
37
39 private $command = '';
40
42 private $limits = [
43 // seconds
44 'time' => 180,
45 // seconds
46 'walltime' => 180,
47 // KB
48 'memory' => 307200,
49 // KB
50 'filesize' => 102400,
51 ];
52
54 private $env = [];
55
57 private $method;
58
60 private $useStderr = false;
61
63 private $everExecuted = false;
64
66 private $cgroup = false;
67
73 public function __construct() {
74 if ( Shell::isDisabled() ) {
75 throw new ShellDisabledError();
76 }
77
78 $this->setLogger( new NullLogger() );
79 }
80
84 public function __destruct() {
85 if ( !$this->everExecuted ) {
86 $context = [ 'command' => $this->command ];
87 $message = __CLASS__ . " was instantiated, but execute() was never called.";
88 if ( $this->method ) {
89 $message .= ' Calling method: {method}.';
90 $context['method'] = $this->method;
91 }
92 $message .= ' Command: {command}';
93 $this->logger->warning( $message, $context );
94 }
95 }
96
104 public function params( /* ... */ ) {
105 $args = func_get_args();
106 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
107 // If only one argument has been passed, and that argument is an array,
108 // treat it as a list of arguments
109 $args = reset( $args );
110 }
111 $this->command = trim( $this->command . ' ' . Shell::escape( $args ) );
112
113 return $this;
114 }
115
123 public function unsafeParams( /* ... */ ) {
124 $args = func_get_args();
125 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
126 // If only one argument has been passed, and that argument is an array,
127 // treat it as a list of arguments
128 $args = reset( $args );
129 }
130 $args = array_filter( $args,
131 function ( $value ) {
132 return $value !== null;
133 }
134 );
135 $this->command = trim( $this->command . ' ' . implode( ' ', $args ) );
136
137 return $this;
138 }
139
147 public function limits( array $limits ) {
148 if ( !isset( $limits['walltime'] ) && isset( $limits['time'] ) ) {
149 // Emulate the behavior of old wfShellExec() where walltime fell back on time
150 // if the latter was overridden and the former wasn't
151 $limits['walltime'] = $limits['time'];
152 }
153 $this->limits = $limits + $this->limits;
154
155 return $this;
156 }
157
164 public function environment( array $env ) {
165 $this->env = $env;
166
167 return $this;
168 }
169
176 public function profileMethod( $method ) {
177 $this->method = $method;
178
179 return $this;
180 }
181
189 public function includeStderr( $yesno = true ) {
190 $this->useStderr = $yesno;
191
192 return $this;
193 }
194
201 public function cgroup( $cgroup ) {
202 $this->cgroup = $cgroup;
203
204 return $this;
205 }
206
216 public function execute() {
217 $this->everExecuted = true;
218
219 $profileMethod = $this->method ?: wfGetCaller();
220
221 $envcmd = '';
222 foreach ( $this->env as $k => $v ) {
223 if ( wfIsWindows() ) {
224 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
225 * appear in the environment variable, so we must use carat escaping as documented in
226 * https://technet.microsoft.com/en-us/library/cc723564.aspx
227 * Note however that the quote isn't listed there, but is needed, and the parentheses
228 * are listed there but doesn't appear to need it.
229 */
230 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
231 } else {
232 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
233 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
234 */
235 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
236 }
237 }
238
239 $cmd = $envcmd . trim( $this->command );
240
241 $useLogPipe = false;
242 if ( is_executable( '/bin/bash' ) ) {
243 $time = intval( $this->limits['time'] );
244 $wallTime = intval( $this->limits['walltime'] );
245 $mem = intval( $this->limits['memory'] );
246 $filesize = intval( $this->limits['filesize'] );
247
248 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
249 $cmd = '/bin/bash ' . escapeshellarg( __DIR__ . '/limit.sh' ) . ' ' .
250 escapeshellarg( $cmd ) . ' ' .
251 escapeshellarg(
252 "MW_INCLUDE_STDERR=" . ( $this->useStderr ? '1' : '' ) . ';' .
253 "MW_CPU_LIMIT=$time; " .
254 'MW_CGROUP=' . escapeshellarg( $this->cgroup ) . '; ' .
255 "MW_MEM_LIMIT=$mem; " .
256 "MW_FILE_SIZE_LIMIT=$filesize; " .
257 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
258 "MW_USE_LOG_PIPE=yes"
259 );
260 $useLogPipe = true;
261 } elseif ( $this->useStderr ) {
262 $cmd .= ' 2>&1';
263 }
264 } elseif ( $this->useStderr ) {
265 $cmd .= ' 2>&1';
266 }
267 wfDebug( __METHOD__ . ": $cmd\n" );
268
269 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
270 // Other platforms may be more accomodating, but we don't want to be
271 // accomodating, because very long commands probably include user
272 // input. See T129506.
273 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN ) {
274 throw new Exception( __METHOD__ .
275 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
276 }
277
278 $desc = [
279 0 => [ 'file', 'php://stdin', 'r' ],
280 1 => [ 'pipe', 'w' ],
281 2 => [ 'file', 'php://stderr', 'w' ],
282 ];
283 if ( $useLogPipe ) {
284 $desc[3] = [ 'pipe', 'w' ];
285 }
286 $pipes = null;
287 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
288 $proc = proc_open( $cmd, $desc, $pipes );
289 if ( !$proc ) {
290 $this->logger->error( "proc_open() failed: {command}", [ 'command' => $cmd ] );
291 throw new ProcOpenError();
292 }
293 $outBuffer = $logBuffer = '';
294 $emptyArray = [];
295 $status = false;
296 $logMsg = false;
297
298 /* According to the documentation, it is possible for stream_select()
299 * to fail due to EINTR. I haven't managed to induce this in testing
300 * despite sending various signals. If it did happen, the error
301 * message would take the form:
302 *
303 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
304 *
305 * where [4] is the value of the macro EINTR and "Interrupted system
306 * call" is string which according to the Linux manual is "possibly"
307 * localised according to LC_MESSAGES.
308 */
309 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
310 $eintrMessage = "stream_select(): unable to select [$eintr]";
311
312 $running = true;
313 $timeout = null;
314 $numReadyPipes = 0;
315
316 while ( $running === true || $numReadyPipes !== 0 ) {
317 if ( $running ) {
318 $status = proc_get_status( $proc );
319 // If the process has terminated, switch to nonblocking selects
320 // for getting any data still waiting to be read.
321 if ( !$status['running'] ) {
322 $running = false;
323 $timeout = 0;
324 }
325 }
326
327 $readyPipes = $pipes;
328
329 \MediaWiki\suppressWarnings();
330 trigger_error( '' );
331 $numReadyPipes = stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
332 \MediaWiki\restoreWarnings();
333
334 if ( $numReadyPipes === false ) {
335 // @codingStandardsIgnoreEnd
336 $error = error_get_last();
337 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
338 continue;
339 } else {
340 trigger_error( $error['message'], E_USER_WARNING );
341 $logMsg = $error['message'];
342 break;
343 }
344 }
345 foreach ( $readyPipes as $fd => $pipe ) {
346 $block = fread( $pipe, 65536 );
347 if ( $block === '' ) {
348 // End of file
349 fclose( $pipes[$fd] );
350 unset( $pipes[$fd] );
351 if ( !$pipes ) {
352 break 2;
353 }
354 } elseif ( $block === false ) {
355 // Read error
356 $logMsg = "Error reading from pipe";
357 break 2;
358 } elseif ( $fd == 1 ) {
359 // From stdout
360 $outBuffer .= $block;
361 } elseif ( $fd == 3 ) {
362 // From log FD
363 $logBuffer .= $block;
364 if ( strpos( $block, "\n" ) !== false ) {
365 $lines = explode( "\n", $logBuffer );
366 $logBuffer = array_pop( $lines );
367 foreach ( $lines as $line ) {
368 $this->logger->info( $line );
369 }
370 }
371 }
372 }
373 }
374
375 foreach ( $pipes as $pipe ) {
376 fclose( $pipe );
377 }
378
379 // Use the status previously collected if possible, since proc_get_status()
380 // just calls waitpid() which will not return anything useful the second time.
381 if ( $running ) {
382 $status = proc_get_status( $proc );
383 }
384
385 if ( $logMsg !== false ) {
386 // Read/select error
387 $retval = -1;
388 proc_close( $proc );
389 } elseif ( $status['signaled'] ) {
390 $logMsg = "Exited with signal {$status['termsig']}";
391 $retval = 128 + $status['termsig'];
392 proc_close( $proc );
393 } else {
394 if ( $status['running'] ) {
395 $retval = proc_close( $proc );
396 } else {
397 $retval = $status['exitcode'];
398 proc_close( $proc );
399 }
400 if ( $retval == 127 ) {
401 $logMsg = "Possibly missing executable file";
402 } elseif ( $retval >= 129 && $retval <= 192 ) {
403 $logMsg = "Probably exited with signal " . ( $retval - 128 );
404 }
405 }
406
407 if ( $logMsg !== false ) {
408 $this->logger->warning( "$logMsg: {command}", [ 'command' => $cmd ] );
409 }
410
411 return new Result( $retval, $outBuffer );
412 }
413}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfIsWindows()
Check if the operating system is Windows.
$line
Definition cdb.php:58
if( $line===false) $args
Definition cdb.php:63
Class used for executing shell commands.
Definition Command.php:35
profileMethod( $method)
Sets calling function for profiler.
Definition Command.php:176
unsafeParams()
Adds unsafe parameters to the command.
Definition Command.php:123
limits(array $limits)
Sets execution limits.
Definition Command.php:147
environment(array $env)
Sets environment variables which should be added to the executed command environment.
Definition Command.php:164
includeStderr( $yesno=true)
Controls whether stderr should be included in stdout, including errors from limit....
Definition Command.php:189
__construct()
Constructor.
Definition Command.php:73
execute()
Executes command.
Definition Command.php:216
params()
Adds parameters to the command.
Definition Command.php:104
string false $cgroup
Definition Command.php:66
__destruct()
Destructor.
Definition Command.php:84
cgroup( $cgroup)
Sets cgroup for this command.
Definition Command.php:201
Returned by MediaWiki\Shell\Command::execute()
Definition Result.php:28
static escape()
Version of escapeshellarg() that works better on Windows.
Definition Shell.php:96
static isDisabled()
Check if this class is effectively disabled via php.ini config.
Definition Shell.php:70
Profiler base class that defines the interface and some trivial functionality.
Definition Profiler.php:33
static instance()
Singleton.
Definition Profiler.php:62
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const SHELL_MAX_ARG_STRLEN
Definition Defines.php:271
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1245
the array() calling protocol came about after MediaWiki 1.4rc1.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1778
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2780
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$lines
Definition router.php:61