MediaWiki  1.23.12
Go to the documentation of this file.
1 <?php
32 abstract class ApiFormatBase extends ApiBase {
34  private $mBufferResult = false, $mBuffer, $mDisabled = false;
42  public function __construct( $main, $format ) {
43  parent::__construct( $main, $format );
45  $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
46  if ( $this->mIsHtml ) {
47  $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
48  } else {
49  $this->mFormat = $format;
50  }
51  $this->mFormat = strtoupper( $this->mFormat );
52  $this->mCleared = false;
53  }
60  abstract public function getMimeType();
66  public function getNeedsRawData() {
67  return false;
68  }
74  public function getFormat() {
75  return $this->mFormat;
76  }
87  public function setUnescapeAmps( $b ) {
88  $this->mUnescapeAmps = $b;
89  }
97  public function getIsHtml() {
98  return $this->mIsHtml;
99  }
107  public function getWantsHelp() {
108  return $this->getIsHtml();
109  }
115  public function disable() {
116  $this->mDisabled = true;
117  }
119  public function isDisabled() {
120  return $this->mDisabled;
121  }
129  public function canPrintErrors() {
130  return true;
131  }
141  function initPrinter( $isHelpScreen ) {
142  if ( $this->mDisabled ) {
143  return;
144  }
145  $isHtml = $this->getIsHtml();
146  $mime = $isHtml ? 'text/html' : $this->getMimeType();
147  $script = wfScript( 'api' );
149  // Some printers (ex. Feed) do their own header settings,
150  // in which case $mime will be set to null
151  if ( is_null( $mime ) ) {
152  return; // skip any initialization
153  }
155  $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
157  //Set X-Frame-Options API results (bug 39180)
158  global $wgApiFrameOptions;
159  if ( $wgApiFrameOptions ) {
160  $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $wgApiFrameOptions" );
161  }
163  if ( $isHtml ) {
164 ?>
166 <html>
167 <head>
168 <?php
169  if ( $this->mUnescapeAmps ) {
170 ?> <title>MediaWiki API</title>
171 <?php
172  } else {
173 ?> <title>MediaWiki API Result</title>
174 <?php
175  }
176 ?>
177 </head>
178 <body>
179 <?php
180  if ( !$isHelpScreen ) {
181 // @codingStandardsIgnoreStart Exclude long line from CodeSniffer checks
182 ?>
183 <br />
184 <small>
185 You are looking at the HTML representation of the <?php echo $this->mFormat; ?> format.<br />
186 HTML is good for debugging, but is unsuitable for application use.<br />
187 Specify the format parameter to change the output format.<br />
188 To see the non HTML representation of the <?php echo $this->mFormat; ?> format, set format=<?php echo strtolower( $this->mFormat ); ?>.<br />
189 See the <a href=''>complete documentation</a>, or
190 <a href='<?php echo $script; ?>'>API help</a> for more information.
191 </small>
192 <pre style='white-space: pre-wrap;'>
193 <?php
194 // @codingStandardsIgnoreEnd
195  // don't wrap the contents of the <pre> for help screens
196  // because these are actually formatted to rely on
197  // the monospaced font for layout purposes
198  } else {
199 ?>
200 <pre>
201 <?php
202  }
203  }
204  }
209  public function closePrinter() {
210  if ( $this->mDisabled ) {
211  return;
212  }
213  if ( $this->getIsHtml() ) {
214 ?>
216 </pre>
217 </body>
218 </html>
219 <?php
220  }
221  }
229  public function printText( $text ) {
230  if ( $this->mDisabled ) {
231  return;
232  }
233  if ( $this->mBufferResult ) {
234  $this->mBuffer = $text;
235  } elseif ( $this->getIsHtml() ) {
236  echo $this->formatHTML( $text );
237  } else {
238  // For non-HTML output, clear all errors that might have been
239  // displayed if display_errors=On
240  // Do this only once, of course
241  if ( !$this->mCleared ) {
242  ob_clean();
243  $this->mCleared = true;
244  }
245  echo $text;
246  }
247  }
252  public function getBuffer() {
253  return $this->mBuffer;
254  }
260  public function setBufferResult( $value ) {
261  $this->mBufferResult = $value;
262  }
268  public function setHelp( $help = true ) {
269  $this->mHelp = $help;
270  }
278  protected function formatHTML( $text ) {
279  // Escape everything first for full coverage
280  $text = htmlspecialchars( $text );
281  // encode all comments or tags as safe blue strings
282  $text = str_replace( '&lt;', '<span style="color:blue;">&lt;', $text );
283  $text = str_replace( '&gt;', '&gt;</span>', $text );
285  // identify requests to api.php
286  $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
287  if ( $this->mHelp ) {
288  // make lines inside * bold
289  $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
290  }
292  // Armor links (bug 61362)
293  $masked = array();
294  $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
295  $sha = sha1( $matches[0] );
296  $masked[$sha] = $matches[0];
297  return "<$sha>";
298  }, $text );
300  // identify URLs
301  $protos = wfUrlProtocolsWithoutProtRel();
302  // This regex hacks around bug 13218 (&quot; included in the URL)
303  $text = preg_replace(
304  "#(((?i)$protos).*?)(&quot;)?([ \\'\"<>\n]|&lt;|&gt;|&quot;)#",
305  '<a href="\\1">\\1</a>\\3\\4',
306  $text
307  );
309  // Unarmor links
310  $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
311  $sha = $matches[1];
312  return isset( $masked[$sha] ) ? $masked[$sha] : $matches[0];
313  }, $text );
321  if ( $this->mUnescapeAmps ) {
322  $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
323  }
325  return $text;
326  }
328  public function getExamples() {
329  return array(
330  'api.php?action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
331  => "Format the query result in the {$this->getModuleName()} format",
332  );
333  }
335  public function getHelpUrls() {
336  return '';
337  }
339  public function getDescription() {
340  return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
341  }
342 }
350  public function __construct( $main ) {
351  parent::__construct( $main, 'feed' );
352  }
360  public static function setResult( $result, $feed, $feedItems ) {
361  // Store output in the Result data.
362  // This way we can check during execution if any error has occurred
363  // Disable size checking for this because we can't continue
364  // cleanly; size checking would cause more problems than it'd
365  // solve
366  $result->disableSizeCheck();
367  $result->addValue( null, '_feed', $feed );
368  $result->addValue( null, '_feeditems', $feedItems );
369  $result->enableSizeCheck();
370  }
377  public function getMimeType() {
378  return null;
379  }
386  public function getNeedsRawData() {
387  return true;
388  }
395  public function canPrintErrors() {
396  return false;
397  }
404  public function execute() {
405  $data = $this->getResultData();
406  if ( isset( $data['_feed'] ) && isset( $data['_feeditems'] ) ) {
407  $feed = $data['_feed'];
408  $items = $data['_feeditems'];
410  $feed->outHeader();
411  foreach ( $items as & $item ) {
412  $feed->outItem( $item );
413  }
414  $feed->outFooter();
415  } else {
416  // Error has occurred, print something useful
417  ApiBase::dieDebug( __METHOD__, 'Invalid feed class/item' );
418  }
419  }
420 }
Whether this formatter needs raw data such as _element tags.
Definition: ApiFormatBase.php:66
__construct( $main, $format)
Constructor If $format ends with 'fm', pretty-print the output in HTML.
Definition: ApiFormatBase.php:42
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. $title:Title object for the current page $request:WebRequest $ignoreRedirect:boolean to skip redirect check $target:Title/string of redirect target $article:Article object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) $article:article(object) being checked 'IsTrustedProxy':Override the result of wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1528
formatHTML( $text)
Pretty-print various elements in HTML format, such as xml tags and URLs.
Definition: ApiFormatBase.php:278
Definition: ApiFormatBase.php:34
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
Definition: globals.txt:10
Definition: ApiFormatBase.php:119
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
Whether this formatter can format the help message in a nice way.
Definition: ApiFormatBase.php:107
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead where the first element is the message key and the remaining elements are used as parameters to the message based on mime etc Preferred in most cases over UploadVerification object with all info about the upload string $mime
Definition: hooks.txt:2578
Definition: ApiFormatBase.php:33
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
Returns usage examples for this module.
Definition: ApiFormatBase.php:328
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:32
setUnescapeAmps( $b)
Specify whether or not sequences like &quot; should be unescaped to " .
Definition: ApiFormatBase.php:87
</p > ! end ! test Empty pre
Definition: parserTests.txt:1579
Overriding class returns the mime type that should be sent to the client.
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:42
to move a page</td >< td > &*You are moving the page across *A non empty talk page already exists under the new or *You uncheck the box below In those you will have to move or merge the page manually if desired</td >< td > be sure to &You are responsible for making sure that links continue to point where they are supposed to go Note that the page will &a page at the new title
Definition: All_system_messages.txt:2703
setHelp( $help=true)
Sets whether the pretty-printer should format bold
Definition: ApiFormatBase.php:268
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3786
This printer is used to wrap an instance of the Feed class.
Definition: ApiFormatBase.php:348
Like wfUrlProtocols(), but excludes '//' from the protocol list.
Definition: GlobalFunctions.php:787
Disable the formatter completely.
Definition: ApiFormatBase.php:115
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
else closePrinter()
Finish printing.
Definition: ApiFormatBase.php:209
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
Definition: ApiFormatBase.php:33
Get the contents of the buffer.
Definition: ApiFormatBase.php:252
Definition: ApiFormatBase.php:335
Definition: ApiFormatBase.php:34
Returns the description string for this module.
Definition: ApiFormatBase.php:339
Some information about database access in MediaWiki By Tim January Database layout For information about the MediaWiki database such as a description of the tables and their please see
Definition: database.txt:2
if(!defined( 'MEDIAWIKI')) if(!isset( $wgVersion)) $matches
Definition: NoLocalSettings.php:33
Definition: styleTest.css.php:45
Get the result data array (read-only)
Definition: ApiBase.php:219
Optimization - no need to sanitize data that will not be needed.
Definition: ApiFormatBase.php:386
Definition: ApiFormatBase.php:34
printText( $text)
The main format printing function.
Definition: ApiFormatBase.php:229
setBufferResult( $value)
Set the flag to buffer the result instead of printing it.
Definition: ApiFormatBase.php:260
Whether this formatter can handle printing API errors.
Definition: ApiFormatBase.php:129
This class expects the result data to be in a custom format set by self::setResult() $result['_feed']...
Definition: ApiFormatBase.php:404
Definition: ApiFormatBase.php:33
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling output() to send it all. It could be easily changed to send incrementally if that becomes useful
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of and so on Built in content types are
Definition: contenthandler.txt:5
__construct( $main)
Definition: ApiFormatBase.php:350
if the prop value should be in the metadata multi language array format
Definition: hooks.txt:1230
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
Definition: distributors.txt:9
Get the name of the module being executed by this instance.
Definition: ApiBase.php:148
Get the internal format name.
Definition: ApiFormatBase.php:74
Definition: mcc.php:31
Get the main module.
Definition: ApiBase.php:188
Returns true when the HTML pretty-printer should be used.
Definition: ApiFormatBase.php:97
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 change
Definition: distributors.txt:9
Returning false makes less sense for events where the action is complete
Definition: hooks.txt:198
Definition: ApiFormatBase.php:33
Feed does its own headers.
Definition: ApiFormatBase.php:377
ChannelFeed doesn't give us a method to print errors in a friendly manner, so just punt errors to the...
Definition: ApiFormatBase.php:395
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2010
initPrinter( $isHelpScreen)
Initialize the printer function and prepare the output headers, etc.
Definition: ApiFormatBase.php:141
shown</td >< td > a href
Definition: All_system_messages.txt:2674
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
Definition: ApiFormatBase.php:360
Definition: ApiFormatBase.php:33