[ Index ]

PHP Cross Reference of MediaWiki-1.24.0

title

Body

[close]

/includes/api/ -> ApiFormatBase.php (source)

   1  <?php
   2  /**
   3   *
   4   *
   5   * Created on Sep 19, 2006
   6   *
   7   * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
   8   *
   9   * This program is free software; you can redistribute it and/or modify
  10   * it under the terms of the GNU General Public License as published by
  11   * the Free Software Foundation; either version 2 of the License, or
  12   * (at your option) any later version.
  13   *
  14   * This program is distributed in the hope that it will be useful,
  15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17   * GNU General Public License for more details.
  18   *
  19   * You should have received a copy of the GNU General Public License along
  20   * with this program; if not, write to the Free Software Foundation, Inc.,
  21   * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22   * http://www.gnu.org/copyleft/gpl.html
  23   *
  24   * @file
  25   */
  26  
  27  /**
  28   * This is the abstract base class for API formatters.
  29   *
  30   * @ingroup API
  31   */
  32  abstract class ApiFormatBase extends ApiBase {
  33      private $mIsHtml, $mFormat, $mUnescapeAmps, $mHelp, $mCleared;
  34      private $mBufferResult = false, $mBuffer, $mDisabled = false;
  35  
  36      /**
  37       * If $format ends with 'fm', pretty-print the output in HTML.
  38       * @param ApiMain $main
  39       * @param string $format Format name
  40       */
  41  	public function __construct( ApiMain $main, $format ) {
  42          parent::__construct( $main, $format );
  43  
  44          $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
  45          if ( $this->mIsHtml ) {
  46              $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
  47          } else {
  48              $this->mFormat = $format;
  49          }
  50          $this->mFormat = strtoupper( $this->mFormat );
  51          $this->mCleared = false;
  52      }
  53  
  54      /**
  55       * Overriding class returns the MIME type that should be sent to the client.
  56       * This method is not called if getIsHtml() returns true.
  57       * @return string
  58       */
  59      abstract public function getMimeType();
  60  
  61      /**
  62       * Whether this formatter needs raw data such as _element tags
  63       * @return bool
  64       */
  65  	public function getNeedsRawData() {
  66          return false;
  67      }
  68  
  69      /**
  70       * Get the internal format name
  71       * @return string
  72       */
  73  	public function getFormat() {
  74          return $this->mFormat;
  75      }
  76  
  77      /**
  78       * Specify whether or not sequences like &amp;quot; should be unescaped
  79       * to &quot; . This should only be set to true for the help message
  80       * when rendered in the default (xmlfm) format. This is a temporary
  81       * special-case fix that should be removed once the help has been
  82       * reworked to use a fully HTML interface.
  83       *
  84       * @param bool $b Whether or not ampersands should be escaped.
  85       */
  86  	public function setUnescapeAmps( $b ) {
  87          $this->mUnescapeAmps = $b;
  88      }
  89  
  90      /**
  91       * Returns true when the HTML pretty-printer should be used.
  92       * The default implementation assumes that formats ending with 'fm'
  93       * should be formatted in HTML.
  94       * @return bool
  95       */
  96  	public function getIsHtml() {
  97          return $this->mIsHtml;
  98      }
  99  
 100      /**
 101       * Whether this formatter can format the help message in a nice way.
 102       * By default, this returns the same as getIsHtml().
 103       * When action=help is set explicitly, the help will always be shown
 104       * @return bool
 105       */
 106  	public function getWantsHelp() {
 107          return $this->getIsHtml();
 108      }
 109  
 110      /**
 111       * Disable the formatter completely. This causes calls to initPrinter(),
 112       * printText() and closePrinter() to be ignored.
 113       */
 114  	public function disable() {
 115          $this->mDisabled = true;
 116      }
 117  
 118  	public function isDisabled() {
 119          return $this->mDisabled;
 120      }
 121  
 122      /**
 123       * Whether this formatter can handle printing API errors. If this returns
 124       * false, then on API errors the default printer will be instantiated.
 125       * @since 1.23
 126       * @return bool
 127       */
 128  	public function canPrintErrors() {
 129          return true;
 130      }
 131  
 132      /**
 133       * Initialize the printer function and prepare the output headers, etc.
 134       * This method must be the first outputting method during execution.
 135       * A human-targeted notice about available formats is printed for the HTML-based output,
 136       * except for help screens (caused by either an error in the API parameters,
 137       * the calling of action=help, or requesting the root script api.php).
 138       * @param bool $isHelpScreen Whether a help screen is going to be shown
 139       */
 140  	function initPrinter( $isHelpScreen ) {
 141          if ( $this->mDisabled ) {
 142              return;
 143          }
 144          $isHtml = $this->getIsHtml();
 145          $mime = $isHtml ? 'text/html' : $this->getMimeType();
 146          $script = wfScript( 'api' );
 147  
 148          // Some printers (ex. Feed) do their own header settings,
 149          // in which case $mime will be set to null
 150          if ( is_null( $mime ) ) {
 151              return; // skip any initialization
 152          }
 153  
 154          $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
 155  
 156          //Set X-Frame-Options API results (bug 39180)
 157          $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
 158          if ( $apiFrameOptions ) {
 159              $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
 160          }
 161  
 162          if ( $isHtml ) {
 163  ?>
 164  <!DOCTYPE HTML>
 165  <html>
 166  <head>
 167  <?php
 168              if ( $this->mUnescapeAmps ) {
 169  ?>    <title>MediaWiki API</title>
 170  <?php
 171              } else {
 172  ?>    <title>MediaWiki API Result</title>
 173  <?php
 174              }
 175  ?>
 176  </head>
 177  <body>
 178  <?php
 179              if ( !$isHelpScreen ) {
 180  // @codingStandardsIgnoreStart Exclude long line from CodeSniffer checks
 181  ?>
 182  <br />
 183  <small>
 184  You are looking at the HTML representation of the <?php echo $this->mFormat; ?> format.<br />
 185  HTML is good for debugging, but is unsuitable for application use.<br />
 186  Specify the format parameter to change the output format.<br />
 187  To see the non HTML representation of the <?php echo $this->mFormat; ?> format, set format=<?php echo strtolower( $this->mFormat ); ?>.<br />
 188  See the <a href='https://www.mediawiki.org/wiki/API'>complete documentation</a>, or
 189  <a href='<?php echo $script; ?>'>API help</a> for more information.
 190  </small>
 191  <pre style='white-space: pre-wrap;'>
 192  <?php
 193  // @codingStandardsIgnoreEnd
 194              // don't wrap the contents of the <pre> for help screens
 195              // because these are actually formatted to rely on
 196              // the monospaced font for layout purposes
 197              } else {
 198  ?>
 199  <pre>
 200  <?php
 201              }
 202          }
 203      }
 204  
 205      /**
 206       * Finish printing. Closes HTML tags.
 207       */
 208  	public function closePrinter() {
 209          if ( $this->mDisabled ) {
 210              return;
 211          }
 212          if ( $this->getIsHtml() ) {
 213  ?>
 214  
 215  </pre>
 216  </body>
 217  </html>
 218  <?php
 219          }
 220      }
 221  
 222      /**
 223       * The main format printing function. Call it to output the result
 224       * string to the user. This function will automatically output HTML
 225       * when format name ends in 'fm'.
 226       * @param string $text
 227       */
 228  	public function printText( $text ) {
 229          if ( $this->mDisabled ) {
 230              return;
 231          }
 232          if ( $this->mBufferResult ) {
 233              $this->mBuffer = $text;
 234          } elseif ( $this->getIsHtml() ) {
 235              echo $this->formatHTML( $text );
 236          } else {
 237              // For non-HTML output, clear all errors that might have been
 238              // displayed if display_errors=On
 239              // Do this only once, of course
 240              if ( !$this->mCleared ) {
 241                  ob_clean();
 242                  $this->mCleared = true;
 243              }
 244              echo $text;
 245          }
 246      }
 247  
 248      /**
 249       * Get the contents of the buffer.
 250       * @return string
 251       */
 252  	public function getBuffer() {
 253          return $this->mBuffer;
 254      }
 255  
 256      /**
 257       * Set the flag to buffer the result instead of printing it.
 258       * @param bool $value
 259       */
 260  	public function setBufferResult( $value ) {
 261          $this->mBufferResult = $value;
 262      }
 263  
 264      /**
 265       * Sets whether the pretty-printer should format *bold*
 266       * @param bool $help
 267       */
 268  	public function setHelp( $help = true ) {
 269          $this->mHelp = $help;
 270      }
 271  
 272      /**
 273       * Pretty-print various elements in HTML format, such as xml tags and
 274       * URLs. This method also escapes characters like <
 275       * @param string $text
 276       * @return string
 277       */
 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 );
 284  
 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          }
 291  
 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 );
 299  
 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          );
 308  
 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 );
 314  
 315          /**
 316           * Temporary fix for bad links in help messages. As a special case,
 317           * XML-escaped metachars are de-escaped one level in the help message
 318           * for legibility. Should be removed once we have completed a fully-HTML
 319           * version of the help message.
 320           */
 321          if ( $this->mUnescapeAmps ) {
 322              $text = preg_replace( '/&amp;(amp|quot|lt|gt);/', '&\1;', $text );
 323          }
 324  
 325          return $text;
 326      }
 327  
 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      }
 334  
 335  	public function getHelpUrls() {
 336          return 'https://www.mediawiki.org/wiki/API:Data_formats';
 337      }
 338  
 339  	public function getDescription() {
 340          return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
 341      }
 342  
 343      /**
 344       * To avoid code duplication with the deprecation of dbg, dump, txt, wddx,
 345       * and yaml, this method is added to do the necessary work. It should be
 346       * removed when those deprecated formats are removed.
 347       */
 348  	protected function markDeprecated() {
 349          $fm = $this->getIsHtml() ? 'fm' : '';
 350          $name = $this->getModuleName();
 351          $this->logFeatureUsage( "format=$name" );
 352          $this->setWarning( "format=$name has been deprecated. Please use format=json$fm instead." );
 353      }
 354  }


Generated: Fri Nov 28 14:03:12 2014 Cross-referenced by PHPXref 0.7.1