PageRenderTime 36ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/OutputPage.php

https://bitbucket.org/kgrashad/thawrapedia
PHP | 2950 lines | 1633 code | 324 blank | 993 comment | 241 complexity | 28aee3690ca556557592a7a442ecfcc3 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. if ( !defined( 'MEDIAWIKI' ) ) {
  3. die( 1 );
  4. }
  5. /**
  6. * @todo document
  7. */
  8. class OutputPage {
  9. var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
  10. var $mExtStyles = array();
  11. var $mPagetitle = '', $mBodytext = '';
  12. /**
  13. * Holds the debug lines that will be outputted as comments in page source if
  14. * $wgDebugComments is enabled. See also $wgShowDebug.
  15. * TODO: make a getter method for this
  16. */
  17. public $mDebugtext = '';
  18. var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
  19. var $mSubtitle = '', $mRedirect = '', $mStatusCode;
  20. var $mLastModified = '', $mETag = false;
  21. var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
  22. var $mScripts = '', $mInlineStyles = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
  23. var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
  24. var $mResourceLoader;
  25. var $mInlineMsg = array();
  26. var $mTemplateIds = array();
  27. var $mAllowUserJs;
  28. var $mSuppressQuickbar = false;
  29. var $mDoNothing = false;
  30. var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
  31. var $mIsArticleRelated = true;
  32. protected $mParserOptions = null; // lazy initialised, use parserOptions()
  33. var $mFeedLinks = array();
  34. var $mEnableClientCache = true;
  35. var $mArticleBodyOnly = false;
  36. var $mNewSectionLink = false;
  37. var $mHideNewSectionLink = false;
  38. var $mNoGallery = false;
  39. var $mPageTitleActionText = '';
  40. var $mParseWarnings = array();
  41. var $mSquidMaxage = 0;
  42. var $mPreventClickjacking = true;
  43. var $mRevisionId = null;
  44. protected $mTitle = null;
  45. /**
  46. * An array of stylesheet filenames (relative from skins path), with options
  47. * for CSS media, IE conditions, and RTL/LTR direction.
  48. * For internal use; add settings in the skin via $this->addStyle()
  49. */
  50. var $styles = array();
  51. /**
  52. * Whether to load jQuery core.
  53. */
  54. protected $mJQueryDone = false;
  55. private $mIndexPolicy = 'index';
  56. private $mFollowPolicy = 'follow';
  57. private $mVaryHeader = array(
  58. 'Accept-Encoding' => array( 'list-contains=gzip' ),
  59. 'Cookie' => null
  60. );
  61. /**
  62. * Constructor
  63. * Initialise private variables
  64. */
  65. function __construct() {
  66. global $wgAllowUserJs;
  67. $this->mAllowUserJs = $wgAllowUserJs;
  68. }
  69. /**
  70. * Redirect to $url rather than displaying the normal page
  71. *
  72. * @param $url String: URL
  73. * @param $responsecode String: HTTP status code
  74. */
  75. public function redirect( $url, $responsecode = '302' ) {
  76. # Strip newlines as a paranoia check for header injection in PHP<5.1.2
  77. $this->mRedirect = str_replace( "\n", '', $url );
  78. $this->mRedirectCode = $responsecode;
  79. }
  80. /**
  81. * Get the URL to redirect to, or an empty string if not redirect URL set
  82. *
  83. * @return String
  84. */
  85. public function getRedirect() {
  86. return $this->mRedirect;
  87. }
  88. /**
  89. * Set the HTTP status code to send with the output.
  90. *
  91. * @param $statusCode Integer
  92. * @return nothing
  93. */
  94. public function setStatusCode( $statusCode ) {
  95. $this->mStatusCode = $statusCode;
  96. }
  97. /**
  98. * Add a new <meta> tag
  99. * To add an http-equiv meta tag, precede the name with "http:"
  100. *
  101. * @param $name tag name
  102. * @param $val tag value
  103. */
  104. function addMeta( $name, $val ) {
  105. array_push( $this->mMetatags, array( $name, $val ) );
  106. }
  107. /**
  108. * Add a keyword or a list of keywords in the page header
  109. *
  110. * @param $text String or array of strings
  111. */
  112. function addKeyword( $text ) {
  113. if( is_array( $text ) ) {
  114. $this->mKeywords = array_merge( $this->mKeywords, $text );
  115. } else {
  116. array_push( $this->mKeywords, $text );
  117. }
  118. }
  119. /**
  120. * Add a new \<link\> tag to the page header
  121. *
  122. * @param $linkarr Array: associative array of attributes.
  123. */
  124. function addLink( $linkarr ) {
  125. array_push( $this->mLinktags, $linkarr );
  126. }
  127. /**
  128. * Add a new \<link\> with "rel" attribute set to "meta"
  129. *
  130. * @param $linkarr Array: associative array mapping attribute names to their
  131. * values, both keys and values will be escaped, and the
  132. * "rel" attribute will be automatically added
  133. */
  134. function addMetadataLink( $linkarr ) {
  135. # note: buggy CC software only reads first "meta" link
  136. static $haveMeta = false;
  137. $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
  138. $this->addLink( $linkarr );
  139. $haveMeta = true;
  140. }
  141. /**
  142. * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
  143. *
  144. * @param $script String: raw HTML
  145. */
  146. function addScript( $script ) {
  147. $this->mScripts .= $script . "\n";
  148. }
  149. /**
  150. * Register and add a stylesheet from an extension directory.
  151. *
  152. * @param $url String path to sheet. Provide either a full url (beginning
  153. * with 'http', etc) or a relative path from the document root
  154. * (beginning with '/'). Otherwise it behaves identically to
  155. * addStyle() and draws from the /skins folder.
  156. */
  157. public function addExtensionStyle( $url ) {
  158. array_push( $this->mExtStyles, $url );
  159. }
  160. /**
  161. * Get all links added by extensions
  162. *
  163. * @return Array
  164. */
  165. function getExtStyle() {
  166. return $this->mExtStyles;
  167. }
  168. /**
  169. * Add a JavaScript file out of skins/common, or a given relative path.
  170. *
  171. * @param $file String: filename in skins/common or complete on-server path
  172. * (/foo/bar.js)
  173. * @param $version String: style version of the file. Defaults to $wgStyleVersion
  174. */
  175. public function addScriptFile( $file, $version = null ) {
  176. global $wgStylePath, $wgStyleVersion;
  177. // See if $file parameter is an absolute URL or begins with a slash
  178. if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
  179. $path = $file;
  180. } else {
  181. $path = "{$wgStylePath}/common/{$file}";
  182. }
  183. if ( is_null( $version ) )
  184. $version = $wgStyleVersion;
  185. $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
  186. }
  187. /**
  188. * Add a self-contained script tag with the given contents
  189. *
  190. * @param $script String: JavaScript text, no <script> tags
  191. */
  192. public function addInlineScript( $script ) {
  193. $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
  194. }
  195. /**
  196. * Get all registered JS and CSS tags for the header.
  197. *
  198. * @return String
  199. */
  200. function getScript() {
  201. return $this->mScripts . $this->getHeadItems();
  202. }
  203. /**
  204. * Get the list of modules to include on this page
  205. *
  206. * @return Array of module names
  207. */
  208. public function getModules() {
  209. return array_values( array_unique( $this->mModules ) );
  210. }
  211. /**
  212. * Add one or more modules recognized by the resource loader. Modules added
  213. * through this function will be loaded by the resource loader when the
  214. * page loads.
  215. *
  216. * @param $modules Mixed: module name (string) or array of module names
  217. */
  218. public function addModules( $modules ) {
  219. $this->mModules = array_merge( $this->mModules, (array)$modules );
  220. }
  221. /**
  222. * Get the list of module JS to include on this page
  223. * @return array of module names
  224. */
  225. public function getModuleScripts() {
  226. return array_values( array_unique( $this->mModuleScripts ) );
  227. }
  228. /**
  229. * Add only JS of one or more modules recognized by the resource loader. Module
  230. * scripts added through this function will be loaded by the resource loader when
  231. * the page loads.
  232. *
  233. * @param $modules Mixed: module name (string) or array of module names
  234. */
  235. public function addModuleScripts( $modules ) {
  236. $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
  237. }
  238. /**
  239. * Get the list of module CSS to include on this page
  240. *
  241. * @return Array of module names
  242. */
  243. public function getModuleStyles() {
  244. return array_values( array_unique( $this->mModuleStyles ) );
  245. }
  246. /**
  247. * Add only CSS of one or more modules recognized by the resource loader. Module
  248. * styles added through this function will be loaded by the resource loader when
  249. * the page loads.
  250. *
  251. * @param $modules Mixed: module name (string) or array of module names
  252. */
  253. public function addModuleStyles( $modules ) {
  254. $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
  255. }
  256. /**
  257. * Get the list of module messages to include on this page
  258. *
  259. * @return Array of module names
  260. */
  261. public function getModuleMessages() {
  262. return array_values( array_unique( $this->mModuleMessages ) );
  263. }
  264. /**
  265. * Add only messages of one or more modules recognized by the resource loader.
  266. * Module messages added through this function will be loaded by the resource
  267. * loader when the page loads.
  268. *
  269. * @param $modules Mixed: module name (string) or array of module names
  270. */
  271. public function addModuleMessages( $modules ) {
  272. $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
  273. }
  274. /**
  275. * Get all header items in a string
  276. *
  277. * @return String
  278. */
  279. function getHeadItems() {
  280. $s = '';
  281. foreach ( $this->mHeadItems as $item ) {
  282. $s .= $item;
  283. }
  284. return $s;
  285. }
  286. /**
  287. * Add or replace an header item to the output
  288. *
  289. * @param $name String: item name
  290. * @param $value String: raw HTML
  291. */
  292. public function addHeadItem( $name, $value ) {
  293. $this->mHeadItems[$name] = $value;
  294. }
  295. /**
  296. * Check if the header item $name is already set
  297. *
  298. * @param $name String: item name
  299. * @return Boolean
  300. */
  301. public function hasHeadItem( $name ) {
  302. return isset( $this->mHeadItems[$name] );
  303. }
  304. /**
  305. * Set the value of the ETag HTTP header, only used if $wgUseETag is true
  306. *
  307. * @param $tag String: value of "ETag" header
  308. */
  309. function setETag( $tag ) {
  310. $this->mETag = $tag;
  311. }
  312. /**
  313. * Set whether the output should only contain the body of the article,
  314. * without any skin, sidebar, etc.
  315. * Used e.g. when calling with "action=render".
  316. *
  317. * @param $only Boolean: whether to output only the body of the article
  318. */
  319. public function setArticleBodyOnly( $only ) {
  320. $this->mArticleBodyOnly = $only;
  321. }
  322. /**
  323. * Return whether the output will contain only the body of the article
  324. *
  325. * @return Boolean
  326. */
  327. public function getArticleBodyOnly() {
  328. return $this->mArticleBodyOnly;
  329. }
  330. /**
  331. * checkLastModified tells the client to use the client-cached page if
  332. * possible. If sucessful, the OutputPage is disabled so that
  333. * any future call to OutputPage->output() have no effect.
  334. *
  335. * Side effect: sets mLastModified for Last-Modified header
  336. *
  337. * @return Boolean: true iff cache-ok headers was sent.
  338. */
  339. public function checkLastModified( $timestamp ) {
  340. global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
  341. if ( !$timestamp || $timestamp == '19700101000000' ) {
  342. wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
  343. return false;
  344. }
  345. if( !$wgCachePages ) {
  346. wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
  347. return false;
  348. }
  349. if( $wgUser->getOption( 'nocache' ) ) {
  350. wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
  351. return false;
  352. }
  353. $timestamp = wfTimestamp( TS_MW, $timestamp );
  354. $modifiedTimes = array(
  355. 'page' => $timestamp,
  356. 'user' => $wgUser->getTouched(),
  357. 'epoch' => $wgCacheEpoch
  358. );
  359. wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
  360. $maxModified = max( $modifiedTimes );
  361. $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
  362. if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  363. wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
  364. return false;
  365. }
  366. # Make debug info
  367. $info = '';
  368. foreach ( $modifiedTimes as $name => $value ) {
  369. if ( $info !== '' ) {
  370. $info .= ', ';
  371. }
  372. $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
  373. }
  374. # IE sends sizes after the date like this:
  375. # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
  376. # this breaks strtotime().
  377. $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
  378. wfSuppressWarnings(); // E_STRICT system time bitching
  379. $clientHeaderTime = strtotime( $clientHeader );
  380. wfRestoreWarnings();
  381. if ( !$clientHeaderTime ) {
  382. wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
  383. return false;
  384. }
  385. $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
  386. wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
  387. wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
  388. wfDebug( __METHOD__ . ": effective Last-Modified: " .
  389. wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
  390. if( $clientHeaderTime < $maxModified ) {
  391. wfDebug( __METHOD__ . ": STALE, $info\n", false );
  392. return false;
  393. }
  394. # Not modified
  395. # Give a 304 response code and disable body output
  396. wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
  397. ini_set( 'zlib.output_compression', 0 );
  398. $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
  399. $this->sendCacheControl();
  400. $this->disable();
  401. // Don't output a compressed blob when using ob_gzhandler;
  402. // it's technically against HTTP spec and seems to confuse
  403. // Firefox when the response gets split over two packets.
  404. wfClearOutputBuffers();
  405. return true;
  406. }
  407. /**
  408. * Override the last modified timestamp
  409. *
  410. * @param $timestamp String: new timestamp, in a format readable by
  411. * wfTimestamp()
  412. */
  413. public function setLastModified( $timestamp ) {
  414. $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
  415. }
  416. /**
  417. * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
  418. *
  419. * @param $policy String: the literal string to output as the contents of
  420. * the meta tag. Will be parsed according to the spec and output in
  421. * standardized form.
  422. * @return null
  423. */
  424. public function setRobotPolicy( $policy ) {
  425. $policy = Article::formatRobotPolicy( $policy );
  426. if( isset( $policy['index'] ) ) {
  427. $this->setIndexPolicy( $policy['index'] );
  428. }
  429. if( isset( $policy['follow'] ) ) {
  430. $this->setFollowPolicy( $policy['follow'] );
  431. }
  432. }
  433. /**
  434. * Set the index policy for the page, but leave the follow policy un-
  435. * touched.
  436. *
  437. * @param $policy string Either 'index' or 'noindex'.
  438. * @return null
  439. */
  440. public function setIndexPolicy( $policy ) {
  441. $policy = trim( $policy );
  442. if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
  443. $this->mIndexPolicy = $policy;
  444. }
  445. }
  446. /**
  447. * Set the follow policy for the page, but leave the index policy un-
  448. * touched.
  449. *
  450. * @param $policy String: either 'follow' or 'nofollow'.
  451. * @return null
  452. */
  453. public function setFollowPolicy( $policy ) {
  454. $policy = trim( $policy );
  455. if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
  456. $this->mFollowPolicy = $policy;
  457. }
  458. }
  459. /**
  460. * Set the new value of the "action text", this will be added to the
  461. * "HTML title", separated from it with " - ".
  462. *
  463. * @param $text String: new value of the "action text"
  464. */
  465. public function setPageTitleActionText( $text ) {
  466. $this->mPageTitleActionText = $text;
  467. }
  468. /**
  469. * Get the value of the "action text"
  470. *
  471. * @return String
  472. */
  473. public function getPageTitleActionText() {
  474. if ( isset( $this->mPageTitleActionText ) ) {
  475. return $this->mPageTitleActionText;
  476. }
  477. }
  478. /**
  479. * "HTML title" means the contents of <title>.
  480. * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
  481. */
  482. public function setHTMLTitle( $name ) {
  483. $this->mHTMLtitle = $name;
  484. }
  485. /**
  486. * Return the "HTML title", i.e. the content of the <title> tag.
  487. *
  488. * @return String
  489. */
  490. public function getHTMLTitle() {
  491. return $this->mHTMLtitle;
  492. }
  493. /**
  494. * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
  495. * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
  496. * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
  497. * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
  498. */
  499. public function setPageTitle( $name ) {
  500. # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
  501. # but leave "<i>foobar</i>" alone
  502. $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
  503. $this->mPagetitle = $nameWithTags;
  504. # change "<i>foo&amp;bar</i>" to "foo&bar"
  505. $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
  506. }
  507. /**
  508. * Return the "page title", i.e. the content of the \<h1\> tag.
  509. *
  510. * @return String
  511. */
  512. public function getPageTitle() {
  513. return $this->mPagetitle;
  514. }
  515. /**
  516. * Set the Title object to use
  517. *
  518. * @param $t Title object
  519. */
  520. public function setTitle( $t ) {
  521. $this->mTitle = $t;
  522. }
  523. /**
  524. * Get the Title object used in this instance
  525. *
  526. * @return Title
  527. */
  528. public function getTitle() {
  529. if ( $this->mTitle instanceof Title ) {
  530. return $this->mTitle;
  531. } else {
  532. wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
  533. global $wgTitle;
  534. return $wgTitle;
  535. }
  536. }
  537. /**
  538. * Replace the subtile with $str
  539. *
  540. * @param $str String: new value of the subtitle
  541. */
  542. public function setSubtitle( $str ) {
  543. $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
  544. }
  545. /**
  546. * Add $str to the subtitle
  547. *
  548. * @param $str String to add to the subtitle
  549. */
  550. public function appendSubtitle( $str ) {
  551. $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
  552. }
  553. /**
  554. * Get the subtitle
  555. *
  556. * @return String
  557. */
  558. public function getSubtitle() {
  559. return $this->mSubtitle;
  560. }
  561. /**
  562. * Set the page as printable, i.e. it'll be displayed with with all
  563. * print styles included
  564. */
  565. public function setPrintable() {
  566. $this->mPrintable = true;
  567. }
  568. /**
  569. * Return whether the page is "printable"
  570. *
  571. * @return Boolean
  572. */
  573. public function isPrintable() {
  574. return $this->mPrintable;
  575. }
  576. /**
  577. * Disable output completely, i.e. calling output() will have no effect
  578. */
  579. public function disable() {
  580. $this->mDoNothing = true;
  581. }
  582. /**
  583. * Return whether the output will be completely disabled
  584. *
  585. * @return Boolean
  586. */
  587. public function isDisabled() {
  588. return $this->mDoNothing;
  589. }
  590. /**
  591. * Show an "add new section" link?
  592. *
  593. * @return Boolean
  594. */
  595. public function showNewSectionLink() {
  596. return $this->mNewSectionLink;
  597. }
  598. /**
  599. * Forcibly hide the new section link?
  600. *
  601. * @return Boolean
  602. */
  603. public function forceHideNewSectionLink() {
  604. return $this->mHideNewSectionLink;
  605. }
  606. /**
  607. * Add or remove feed links in the page header
  608. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  609. * for the new version
  610. * @see addFeedLink()
  611. *
  612. * @param $show Boolean: true: add default feeds, false: remove all feeds
  613. */
  614. public function setSyndicated( $show = true ) {
  615. if ( $show ) {
  616. $this->setFeedAppendQuery( false );
  617. } else {
  618. $this->mFeedLinks = array();
  619. }
  620. }
  621. /**
  622. * Add default feeds to the page header
  623. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  624. * for the new version
  625. * @see addFeedLink()
  626. *
  627. * @param $val String: query to append to feed links or false to output
  628. * default links
  629. */
  630. public function setFeedAppendQuery( $val ) {
  631. global $wgAdvertisedFeedTypes;
  632. $this->mFeedLinks = array();
  633. foreach ( $wgAdvertisedFeedTypes as $type ) {
  634. $query = "feed=$type";
  635. if ( is_string( $val ) ) {
  636. $query .= '&' . $val;
  637. }
  638. $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
  639. }
  640. }
  641. /**
  642. * Add a feed link to the page header
  643. *
  644. * @param $format String: feed type, should be a key of $wgFeedClasses
  645. * @param $href String: URL
  646. */
  647. public function addFeedLink( $format, $href ) {
  648. global $wgAdvertisedFeedTypes;
  649. if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
  650. $this->mFeedLinks[$format] = $href;
  651. }
  652. }
  653. /**
  654. * Should we output feed links for this page?
  655. * @return Boolean
  656. */
  657. public function isSyndicated() {
  658. return count( $this->mFeedLinks ) > 0;
  659. }
  660. /**
  661. * Return URLs for each supported syndication format for this page.
  662. * @return array associating format keys with URLs
  663. */
  664. public function getSyndicationLinks() {
  665. return $this->mFeedLinks;
  666. }
  667. /**
  668. * Will currently always return null
  669. *
  670. * @return null
  671. */
  672. public function getFeedAppendQuery() {
  673. return $this->mFeedLinksAppendQuery;
  674. }
  675. /**
  676. * Set whether the displayed content is related to the source of the
  677. * corresponding article on the wiki
  678. * Setting true will cause the change "article related" toggle to true
  679. *
  680. * @param $v Boolean
  681. */
  682. public function setArticleFlag( $v ) {
  683. $this->mIsarticle = $v;
  684. if ( $v ) {
  685. $this->mIsArticleRelated = $v;
  686. }
  687. }
  688. /**
  689. * Return whether the content displayed page is related to the source of
  690. * the corresponding article on the wiki
  691. *
  692. * @return Boolean
  693. */
  694. public function isArticle() {
  695. return $this->mIsarticle;
  696. }
  697. /**
  698. * Set whether this page is related an article on the wiki
  699. * Setting false will cause the change of "article flag" toggle to false
  700. *
  701. * @param $v Boolean
  702. */
  703. public function setArticleRelated( $v ) {
  704. $this->mIsArticleRelated = $v;
  705. if ( !$v ) {
  706. $this->mIsarticle = false;
  707. }
  708. }
  709. /**
  710. * Return whether this page is related an article on the wiki
  711. *
  712. * @return Boolean
  713. */
  714. public function isArticleRelated() {
  715. return $this->mIsArticleRelated;
  716. }
  717. /**
  718. * Add new language links
  719. *
  720. * @param $newLinkArray Associative array mapping language code to the page
  721. * name
  722. */
  723. public function addLanguageLinks( $newLinkArray ) {
  724. $this->mLanguageLinks += $newLinkArray;
  725. }
  726. /**
  727. * Reset the language links and add new language links
  728. *
  729. * @param $newLinkArray Associative array mapping language code to the page
  730. * name
  731. */
  732. public function setLanguageLinks( $newLinkArray ) {
  733. $this->mLanguageLinks = $newLinkArray;
  734. }
  735. /**
  736. * Get the list of language links
  737. *
  738. * @return Associative array mapping language code to the page name
  739. */
  740. public function getLanguageLinks() {
  741. return $this->mLanguageLinks;
  742. }
  743. /**
  744. * Add an array of categories, with names in the keys
  745. *
  746. * @param $categories Associative array mapping category name to its sort key
  747. */
  748. public function addCategoryLinks( $categories ) {
  749. global $wgUser, $wgContLang;
  750. if ( !is_array( $categories ) || count( $categories ) == 0 ) {
  751. return;
  752. }
  753. # Add the links to a LinkBatch
  754. $arr = array( NS_CATEGORY => $categories );
  755. $lb = new LinkBatch;
  756. $lb->setArray( $arr );
  757. # Fetch existence plus the hiddencat property
  758. $dbr = wfGetDB( DB_SLAVE );
  759. $pageTable = $dbr->tableName( 'page' );
  760. $where = $lb->constructSet( 'page', $dbr );
  761. $propsTable = $dbr->tableName( 'page_props' );
  762. $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
  763. FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
  764. $res = $dbr->query( $sql, __METHOD__ );
  765. # Add the results to the link cache
  766. $lb->addResultToCache( LinkCache::singleton(), $res );
  767. # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
  768. $categories = array_combine(
  769. array_keys( $categories ),
  770. array_fill( 0, count( $categories ), 'normal' )
  771. );
  772. # Mark hidden categories
  773. foreach ( $res as $row ) {
  774. if ( isset( $row->pp_value ) ) {
  775. $categories[$row->page_title] = 'hidden';
  776. }
  777. }
  778. # Add the remaining categories to the skin
  779. if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
  780. $sk = $wgUser->getSkin();
  781. foreach ( $categories as $category => $type ) {
  782. $origcategory = $category;
  783. $title = Title::makeTitleSafe( NS_CATEGORY, $category );
  784. $wgContLang->findVariantLink( $category, $title, true );
  785. if ( $category != $origcategory ) {
  786. if ( array_key_exists( $category, $categories ) ) {
  787. continue;
  788. }
  789. }
  790. $text = $wgContLang->convertHtml( $title->getText() );
  791. $this->mCategories[] = $title->getText();
  792. $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
  793. }
  794. }
  795. }
  796. /**
  797. * Reset the category links (but not the category list) and add $categories
  798. *
  799. * @param $categories Associative array mapping category name to its sort key
  800. */
  801. public function setCategoryLinks( $categories ) {
  802. $this->mCategoryLinks = array();
  803. $this->addCategoryLinks( $categories );
  804. }
  805. /**
  806. * Get the list of category links, in a 2-D array with the following format:
  807. * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
  808. * hidden categories) and $link a HTML fragment with a link to the category
  809. * page
  810. *
  811. * @return Array
  812. */
  813. public function getCategoryLinks() {
  814. return $this->mCategoryLinks;
  815. }
  816. /**
  817. * Get the list of category names this page belongs to
  818. *
  819. * @return Array of strings
  820. */
  821. public function getCategories() {
  822. return $this->mCategories;
  823. }
  824. /**
  825. * Suppress the quickbar from the output, only for skin supporting
  826. * the quickbar
  827. */
  828. public function suppressQuickbar() {
  829. $this->mSuppressQuickbar = true;
  830. }
  831. /**
  832. * Return whether the quickbar should be suppressed from the output
  833. *
  834. * @return Boolean
  835. */
  836. public function isQuickbarSuppressed() {
  837. return $this->mSuppressQuickbar;
  838. }
  839. /**
  840. * Remove user JavaScript from scripts to load
  841. */
  842. public function disallowUserJs() {
  843. $this->mAllowUserJs = false;
  844. }
  845. /**
  846. * Return whether user JavaScript is allowed for this page
  847. *
  848. * @return Boolean
  849. */
  850. public function isUserJsAllowed() {
  851. return $this->mAllowUserJs;
  852. }
  853. /**
  854. * Prepend $text to the body HTML
  855. *
  856. * @param $text String: HTML
  857. */
  858. public function prependHTML( $text ) {
  859. $this->mBodytext = $text . $this->mBodytext;
  860. }
  861. /**
  862. * Append $text to the body HTML
  863. *
  864. * @param $text String: HTML
  865. */
  866. public function addHTML( $text ) {
  867. $this->mBodytext .= $text;
  868. }
  869. /**
  870. * Clear the body HTML
  871. */
  872. public function clearHTML() {
  873. $this->mBodytext = '';
  874. }
  875. /**
  876. * Get the body HTML
  877. *
  878. * @return String: HTML
  879. */
  880. public function getHTML() {
  881. return $this->mBodytext;
  882. }
  883. /**
  884. * Add $text to the debug output
  885. *
  886. * @param $text String: debug text
  887. */
  888. public function debug( $text ) {
  889. $this->mDebugtext .= $text;
  890. }
  891. /**
  892. * @deprecated use parserOptions() instead
  893. */
  894. public function setParserOptions( $options ) {
  895. wfDeprecated( __METHOD__ );
  896. return $this->parserOptions( $options );
  897. }
  898. /**
  899. * Get/set the ParserOptions object to use for wikitext parsing
  900. *
  901. * @param $options either the ParserOption to use or null to only get the
  902. * current ParserOption object
  903. * @return current ParserOption object
  904. */
  905. public function parserOptions( $options = null ) {
  906. if ( !$this->mParserOptions ) {
  907. $this->mParserOptions = new ParserOptions;
  908. }
  909. return wfSetVar( $this->mParserOptions, $options );
  910. }
  911. /**
  912. * Set the revision ID which will be seen by the wiki text parser
  913. * for things such as embedded {{REVISIONID}} variable use.
  914. *
  915. * @param $revid Mixed: an positive integer, or null
  916. * @return Mixed: previous value
  917. */
  918. public function setRevisionId( $revid ) {
  919. $val = is_null( $revid ) ? null : intval( $revid );
  920. return wfSetVar( $this->mRevisionId, $val );
  921. }
  922. /**
  923. * Get the current revision ID
  924. *
  925. * @return Integer
  926. */
  927. public function getRevisionId() {
  928. return $this->mRevisionId;
  929. }
  930. /**
  931. * Convert wikitext to HTML and add it to the buffer
  932. * Default assumes that the current page title will be used.
  933. *
  934. * @param $text String
  935. * @param $linestart Boolean: is this the start of a line?
  936. */
  937. public function addWikiText( $text, $linestart = true ) {
  938. $title = $this->getTitle(); // Work arround E_STRICT
  939. $this->addWikiTextTitle( $text, $title, $linestart );
  940. }
  941. /**
  942. * Add wikitext with a custom Title object
  943. *
  944. * @param $text String: wikitext
  945. * @param $title Title object
  946. * @param $linestart Boolean: is this the start of a line?
  947. */
  948. public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
  949. $this->addWikiTextTitle( $text, $title, $linestart );
  950. }
  951. /**
  952. * Add wikitext with a custom Title object and
  953. *
  954. * @param $text String: wikitext
  955. * @param $title Title object
  956. * @param $linestart Boolean: is this the start of a line?
  957. */
  958. function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
  959. $this->addWikiTextTitle( $text, $title, $linestart, true );
  960. }
  961. /**
  962. * Add wikitext with tidy enabled
  963. *
  964. * @param $text String: wikitext
  965. * @param $linestart Boolean: is this the start of a line?
  966. */
  967. public function addWikiTextTidy( $text, $linestart = true ) {
  968. $title = $this->getTitle();
  969. $this->addWikiTextTitleTidy( $text, $title, $linestart );
  970. }
  971. /**
  972. * Add wikitext with a custom Title object
  973. *
  974. * @param $text String: wikitext
  975. * @param $title Title object
  976. * @param $linestart Boolean: is this the start of a line?
  977. * @param $tidy Boolean: whether to use tidy
  978. */
  979. public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
  980. global $wgParser;
  981. wfProfileIn( __METHOD__ );
  982. wfIncrStats( 'pcache_not_possible' );
  983. $popts = $this->parserOptions();
  984. $oldTidy = $popts->setTidy( $tidy );
  985. $parserOutput = $wgParser->parse(
  986. $text, $title, $popts,
  987. $linestart, true, $this->mRevisionId
  988. );
  989. $popts->setTidy( $oldTidy );
  990. $this->addParserOutput( $parserOutput );
  991. wfProfileOut( __METHOD__ );
  992. }
  993. /**
  994. * Add wikitext to the buffer, assuming that this is the primary text for a page view
  995. * Saves the text into the parser cache if possible.
  996. *
  997. * @param $text String: wikitext
  998. * @param $article Article object
  999. * @param $cache Boolean
  1000. * @deprecated Use Article::outputWikitext
  1001. */
  1002. public function addPrimaryWikiText( $text, $article, $cache = true ) {
  1003. global $wgParser;
  1004. wfDeprecated( __METHOD__ );
  1005. $popts = $this->parserOptions();
  1006. $popts->setTidy( true );
  1007. $parserOutput = $wgParser->parse(
  1008. $text, $article->mTitle,
  1009. $popts, true, true, $this->mRevisionId
  1010. );
  1011. $popts->setTidy( false );
  1012. if ( $cache && $article && $parserOutput->isCacheable() ) {
  1013. $parserCache = ParserCache::singleton();
  1014. $parserCache->save( $parserOutput, $article, $popts );
  1015. }
  1016. $this->addParserOutput( $parserOutput );
  1017. }
  1018. /**
  1019. * @deprecated use addWikiTextTidy()
  1020. */
  1021. public function addSecondaryWikiText( $text, $linestart = true ) {
  1022. wfDeprecated( __METHOD__ );
  1023. $this->addWikiTextTitleTidy( $text, $this->getTitle(), $linestart );
  1024. }
  1025. /**
  1026. * Add a ParserOutput object, but without Html
  1027. *
  1028. * @param $parserOutput ParserOutput object
  1029. */
  1030. public function addParserOutputNoText( &$parserOutput ) {
  1031. $this->mLanguageLinks += $parserOutput->getLanguageLinks();
  1032. $this->addCategoryLinks( $parserOutput->getCategories() );
  1033. $this->mNewSectionLink = $parserOutput->getNewSection();
  1034. $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
  1035. $this->mParseWarnings = $parserOutput->getWarnings();
  1036. if ( !$parserOutput->isCacheable() ) {
  1037. $this->enableClientCache( false );
  1038. }
  1039. $this->mNoGallery = $parserOutput->getNoGallery();
  1040. $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
  1041. $this->addModules( $parserOutput->getModules() );
  1042. // Versioning...
  1043. foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
  1044. if ( isset( $this->mTemplateIds[$ns] ) ) {
  1045. $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
  1046. } else {
  1047. $this->mTemplateIds[$ns] = $dbks;
  1048. }
  1049. }
  1050. // Hooks registered in the object
  1051. global $wgParserOutputHooks;
  1052. foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
  1053. list( $hookName, $data ) = $hookInfo;
  1054. if ( isset( $wgParserOutputHooks[$hookName] ) ) {
  1055. call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
  1056. }
  1057. }
  1058. wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
  1059. }
  1060. /**
  1061. * Add a ParserOutput object
  1062. *
  1063. * @param $parserOutput ParserOutput
  1064. */
  1065. function addParserOutput( &$parserOutput ) {
  1066. $this->addParserOutputNoText( $parserOutput );
  1067. $text = $parserOutput->getText();
  1068. wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
  1069. $this->addHTML( $text );
  1070. }
  1071. /**
  1072. * Add the output of a QuickTemplate to the output buffer
  1073. *
  1074. * @param $template QuickTemplate
  1075. */
  1076. public function addTemplate( &$template ) {
  1077. ob_start();
  1078. $template->execute();
  1079. $this->addHTML( ob_get_contents() );
  1080. ob_end_clean();
  1081. }
  1082. /**
  1083. * Parse wikitext and return the HTML.
  1084. *
  1085. * @param $text String
  1086. * @param $linestart Boolean: is this the start of a line?
  1087. * @param $interface Boolean: use interface language ($wgLang instead of
  1088. * $wgContLang) while parsing language sensitive magic
  1089. * words like GRAMMAR and PLURAL
  1090. * @return String: HTML
  1091. */
  1092. public function parse( $text, $linestart = true, $interface = false ) {
  1093. global $wgParser;
  1094. if( is_null( $this->getTitle() ) ) {
  1095. throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
  1096. }
  1097. $popts = $this->parserOptions();
  1098. if ( $interface ) {
  1099. $popts->setInterfaceMessage( true );
  1100. }
  1101. $parserOutput = $wgParser->parse(
  1102. $text, $this->getTitle(), $popts,
  1103. $linestart, true, $this->mRevisionId
  1104. );
  1105. if ( $interface ) {
  1106. $popts->setInterfaceMessage( false );
  1107. }
  1108. return $parserOutput->getText();
  1109. }
  1110. /**
  1111. * Parse wikitext, strip paragraphs, and return the HTML.
  1112. *
  1113. * @param $text String
  1114. * @param $linestart Boolean: is this the start of a line?
  1115. * @param $interface Boolean: use interface language ($wgLang instead of
  1116. * $wgContLang) while parsing language sensitive magic
  1117. * words like GRAMMAR and PLURAL
  1118. * @return String: HTML
  1119. */
  1120. public function parseInline( $text, $linestart = true, $interface = false ) {
  1121. $parsed = $this->parse( $text, $linestart, $interface );
  1122. $m = array();
  1123. if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
  1124. $parsed = $m[1];
  1125. }
  1126. return $parsed;
  1127. }
  1128. /**
  1129. * @deprecated
  1130. *
  1131. * @param $article Article
  1132. * @return Boolean: true if successful, else false.
  1133. */
  1134. public function tryParserCache( &$article ) {
  1135. wfDeprecated( __METHOD__ );
  1136. $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
  1137. if ( $parserOutput !== false ) {
  1138. $this->addParserOutput( $parserOutput );
  1139. return true;
  1140. } else {
  1141. return false;
  1142. }
  1143. }
  1144. /**
  1145. * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
  1146. *
  1147. * @param $maxage Integer: maximum cache time on the Squid, in seconds.
  1148. */
  1149. public function setSquidMaxage( $maxage ) {
  1150. $this->mSquidMaxage = $maxage;
  1151. }
  1152. /**
  1153. * Use enableClientCache(false) to force it to send nocache headers
  1154. *
  1155. * @param $state ??
  1156. */
  1157. public function enableClientCache( $state ) {
  1158. return wfSetVar( $this->mEnableClientCache, $state );
  1159. }
  1160. /**
  1161. * Get the list of cookies that will influence on the cache
  1162. *
  1163. * @return Array
  1164. */
  1165. function getCacheVaryCookies() {
  1166. global $wgCookiePrefix, $wgCacheVaryCookies;
  1167. static $cookies;
  1168. if ( $cookies === null ) {
  1169. $cookies = array_merge(
  1170. array(
  1171. "{$wgCookiePrefix}Token",
  1172. "{$wgCookiePrefix}LoggedOut",
  1173. session_name()
  1174. ),
  1175. $wgCacheVaryCookies
  1176. );
  1177. wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
  1178. }
  1179. return $cookies;
  1180. }
  1181. /**
  1182. * Return whether this page is not cacheable because "useskin" or "uselang"
  1183. * URL parameters were passed.
  1184. *
  1185. * @return Boolean
  1186. */
  1187. function uncacheableBecauseRequestVars() {
  1188. global $wgRequest;
  1189. return $wgRequest->getText( 'useskin', false ) === false
  1190. && $wgRequest->getText( 'uselang', false ) === false;
  1191. }
  1192. /**
  1193. * Check if the request has a cache-varying cookie header
  1194. * If it does, it's very important that we don't allow public caching
  1195. *
  1196. * @return Boolean
  1197. */
  1198. function haveCacheVaryCookies() {
  1199. global $wgRequest;
  1200. $cookieHeader = $wgRequest->getHeader( 'cookie' );
  1201. if ( $cookieHeader === false ) {
  1202. return false;
  1203. }
  1204. $cvCookies = $this->getCacheVaryCookies();
  1205. foreach ( $cvCookies as $cookieName ) {
  1206. # Check for a simple string match, like the way squid does it
  1207. if ( strpos( $cookieHeader, $cookieName ) !== false ) {
  1208. wfDebug( __METHOD__ . ": found $cookieName\n" );
  1209. return true;
  1210. }
  1211. }
  1212. wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
  1213. return false;
  1214. }
  1215. /**
  1216. * Add an HTTP header that will influence on the cache
  1217. *
  1218. * @param $header String: header name
  1219. * @param $option either an Array or null
  1220. * @fixme Document the $option parameter; it appears to be for
  1221. * X-Vary-Options but what format is acceptable?
  1222. */
  1223. public function addVaryHeader( $header, $option = null ) {
  1224. if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
  1225. $this->mVaryHeader[$header] = (array)$option;
  1226. } elseif( is_array( $option ) ) {
  1227. if( is_array( $this->mVaryHeader[$header] ) ) {
  1228. $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
  1229. } else {
  1230. $this->mVaryHeader[$header] = $option;
  1231. }
  1232. }
  1233. $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
  1234. }
  1235. /**
  1236. * Get a complete X-Vary-Options header
  1237. *
  1238. * @return String
  1239. */
  1240. public function getXVO() {
  1241. $cvCookies = $this->getCacheVaryCookies();
  1242. $cookiesOption = array();
  1243. foreach ( $cvCookies as $cookieName ) {
  1244. $cookiesOption[] = 'string-contains=' . $cookieName;
  1245. }
  1246. $this->addVaryHeader( 'Cookie', $cookiesOption );
  1247. $headers = array();
  1248. foreach( $this->mVaryHeader as $header => $option ) {
  1249. $newheader = $header;
  1250. if( is_array( $option ) ) {
  1251. $newheader .= ';' . implode( ';', $option );
  1252. }
  1253. $headers[] = $newheader;
  1254. }
  1255. $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
  1256. return $xvo;
  1257. }
  1258. /**
  1259. * bug 21672: Add Accept-Language to Vary and XVO headers
  1260. * if there's no 'variant' parameter existed in GET.
  1261. *
  1262. * For example:
  1263. * /w/index.php?title=Main_page should always be served; but
  1264. * /w/index.php?title=Main_page&variant=zh-cn should never be served.
  1265. */
  1266. function addAcceptLanguage() {
  1267. global $wgRequest, $wgContLang;
  1268. if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
  1269. $variants = $wgContLang->getVariants();
  1270. $aloption = array();
  1271. foreach ( $variants as $variant ) {
  1272. if( $variant === $wgContLang->getCode() ) {
  1273. continue;
  1274. } else {
  1275. $aloption[] = 'string-contains=' . $variant;
  1276. // IE and some other browsers use another form of language code
  1277. // in their Accept-Language header, like "zh-CN" or "zh-TW".
  1278. // We should handle these too.
  1279. $ievariant = explode( '-', $variant );
  1280. if ( count( $ievariant ) == 2 ) {
  1281. $ievariant[1] = strtoupper( $ievariant[1] );
  1282. $ievariant = implode( '-', $ievariant );
  1283. $aloption[] = 'string-contains=' . $ievariant;
  1284. }
  1285. }
  1286. }
  1287. $this->addVaryHeader( 'Accept-Language', $aloption );
  1288. }
  1289. }
  1290. /**
  1291. * Set a flag which will cause an X-Frame-Options header appropriate for
  1292. * edit pages to be sent. The header value is controlled by
  1293. * $wgEditPageFrameOptions.
  1294. *
  1295. * This is the default for special pages. If you display a CSRF-protected
  1296. * form on an ordinary view page, then you need to call this function.
  1297. */
  1298. public function preventClickjacking( $enable = true ) {
  1299. $this->mPreventClickjacking = $enable;
  1300. }
  1301. /**
  1302. * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
  1303. * This can be called from pages which do not contain any CSRF-protected
  1304. * HTML form.
  1305. */
  1306. public function allowClickjacking() {
  1307. $this->mPreventClickjacking = false;
  1308. }
  1309. /**
  1310. * Get the X-Frame-Options header value (without the name part), or false
  1311. * if there isn't one. This is used by Skin to determine whether to enable
  1312. * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
  1313. */
  1314. public function getFrameOptions() {
  1315. global $wgBreakFrames, $wgEditPageFrameOptions;
  1316. if ( $wgBreakFrames ) {
  1317. return 'DENY';
  1318. } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
  1319. return $wgEditPageFrameOptions;
  1320. }
  1321. }
  1322. /**
  1323. * Send cache control HTTP headers
  1324. */
  1325. public function sendCacheControl() {
  1326. global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
  1327. $response = $wgRequest->response();
  1328. if ( $wgUseETag && $this->mETag ) {
  1329. $response->header( "ETag: $this->mETag" );
  1330. }
  1331. $this->addAcceptLanguage();
  1332. # don't serve compressed data to clients who can't handle it
  1333. # maintain different caches for logged-in users and non-logged in ones
  1334. $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
  1335. if ( $wgUseXVO ) {
  1336. # Add an X-Vary-Options header for Squid with Wikimedia patches
  1337. $response->header( $this->getXVO() );
  1338. }
  1339. if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
  1340. if(
  1341. $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
  1342. $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
  1343. )
  1344. {
  1345. if ( $wgUseESI ) {
  1346. # We'll purge the proxy cache explicitly, but require end user agents
  1347. # to revalidate against the proxy on each visit.
  1348. # Surrogate-Control controls our Squid, Cache-Control downstream caches
  1349. wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
  1350. # start with a shorter timeout for initial testing
  1351. # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
  1352. $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
  1353. $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
  1354. } else {
  1355. # We'll purge the proxy cache for anons explicitly, but require end user agents
  1356. # to revalidate against the proxy on each visit.
  1357. # IMPORTANT! The Squid needs to replace the Cache-Control header with
  1358. # Cache-Control: s-maxage=0, must-revalidate, max-age=0
  1359. wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
  1360. # start with a shorter timeout for initial testing
  1361. # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
  1362. $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
  1363. }
  1364. } else {
  1365. # We do want clients to cache if they can, but they *must* check for updates
  1366. # on revisiting the page.
  1367. wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
  1368. $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  1369. $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
  1370. }
  1371. if($this->mLastModified) {
  1372. $response->header( "Last-Modified: {$this->mLastModified}" );
  1373. }
  1374. } else {
  1375. wfDebug( __METHOD__ . ": no caching **\n", false );
  1376. # In general, the absence of a last modified header should be enough to prevent
  1377. # the client from using its cache. We send a few other things just to make sure.
  1378. $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  1379. $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
  1380. $response->header( 'Pragma: no-cache' );
  1381. }
  1382. }
  1383. /**
  1384. * Get the message associed with the HTTP response code $code
  1385. *
  1386. * @param $code Integer: status code
  1387. * @return String or null: message or null if $code is not in the list of
  1388. * messages
  1389. */
  1390. public static function getStatusMessage( $code ) {
  1391. static $statusMessage = array(
  1392. 100 => 'Continue',
  1393. 101 => 'Switching Protocols',
  1394. 102 => 'Processing',
  1395. 200 => 'OK',
  1396. 201 => 'Created',
  1397. 202 => 'Accepted',
  1398. 203 => 'Non-Authoritative Information',
  1399. 204 => 'No Content',
  1400. 205 => 'Reset Content',
  1401. 206 => 'Partial Content',
  1402. 207 => 'Multi-Status',
  1403. 300 => 'Multiple Choices',
  1404. 301 => 'Moved Permanently',
  1405. 302 => 'Found',
  1406. 303 => 'See Other',
  1407. 304 => 'Not Modified',
  1408. 305 => 'Use Proxy',
  1409. 307 => 'Temporary Redirect',
  1410. 400 => 'Bad Request',
  1411. 401 => 'Unauthorized',
  1412. 402 => 'Payment Required',
  1413. 403 => 'Forbidden',
  1414. 404 => 'Not Found',
  1415. 405 => 'Method Not Allowed',
  1416. 406 => 'Not Acceptable',
  1417. 407 => 'Proxy Authentication Required',
  1418. 408 => 'Request Timeout',
  1419. 409 => 'Conflict',
  1420. 410 => 'Gone',
  1421. 411 => 'Length Required',
  1422. 412 => 'Precondition Failed',
  1423. 413 => 'Request Entity Too Large',
  1424. 414 => 'Request-URI Too Large',
  1425. 415 => 'Unsupported Media Type',
  1426. 416 => 'Request Range Not Satisfiable',
  1427. 417 => 'Expectation Failed',
  1428. 422 => 'Unprocessable Entity',
  1429. 423 => 'Locked',
  1430. 424 => 'Failed Dependency',
  1431. 500 => 'Internal Server Error',
  1432. 501 => 'Not Implemented',
  1433. 502 => 'Bad Gateway',
  1434. 503 => 'Service Unavailable',
  1435. 504 => 'Gateway Timeout',
  1436. 505 => 'HTTP Version Not Supported',
  1437. 507 => 'Insufficient Storage'
  1438. );
  1439. return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
  1440. }
  1441. /**
  1442. * Finally, all the text has been munged and accumulated into
  1443. * the object, let's actually output it:
  1444. */
  1445. public function output() {
  1446. global $wgUser, $wgOutputEncoding, $wgRequest;
  1447. global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
  1448. global $wgUseAjax, $wgAjaxWatch;
  1449. global $wgEnableMWSuggest, $wgUniversalEditButton;
  1450. global $wgArticle;
  1451. if( $this->mDoNothing ) {
  1452. return;
  1453. }
  1454. wfProfileIn( __METHOD__ );
  1455. if ( $this->mRedirect != '' ) {
  1456. # Standards require redirect URLs to be absolute
  1457. $this->mRedirect = wfExpandUrl( $this->mRedirect );
  1458. if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
  1459. if( !$wgDebugRedirects ) {
  1460. $message = self::getStatusMessage( $this->mRedirectCode );
  1461. $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
  1462. }
  1463. $this->mLastModified = wfTimestamp( TS_RFC2822 );
  1464. }
  1465. $this->sendCacheControl();
  1466. $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
  1467. if( $wgDebugRedirects ) {
  1468. $url = htmlspecialchars( $this->mRedirect );
  1469. print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
  1470. print "<p>Location: <a href=\"$url\">$url</a></p>\n";
  1471. print "</body>\n</html>\n";
  1472. } else {
  1473. $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
  1474. }
  1475. wfProfileOut( __METHOD__ );
  1476. return;
  1477. } elseif ( $this->mStatusCode ) {
  1478. $message = self::getStatusMessage( $this->mStatusCode );
  1479. if ( $message ) {
  1480. $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
  1481. }
  1482. }
  1483. $sk = $wgUser->getSkin();
  1484. // Add base resources
  1485. $this->addModules( 'mediawiki.util' );
  1486. global $wgIncludeLegacyJavaScript;
  1487. if( $wgIncludeLegacyJavaScript ){
  1488. $this->addModules( 'mediawiki.legacy.wikibits' );
  1489. }
  1490. // Add various resources if required
  1491. if ( $wgUseAjax ) {
  1492. $this->addModules( 'mediawiki.legacy.ajax' );
  1493. wfRunHooks( 'AjaxAddScript', array( &$this ) );
  1494. if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
  1495. $this->addModules( 'mediawiki.legacy.ajaxwatch' );
  1496. }
  1497. if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
  1498. $this->addModules( 'mediawiki.legacy.mwsuggest' );
  1499. }
  1500. }
  1501. if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
  1502. $this->addModules( 'mediawiki.action.view.rightClickEdit' );
  1503. }
  1504. if( $wgUniversalEditButton ) {
  1505. if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
  1506. && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
  1507. // Original UniversalEditButton
  1508. $msg = wfMsg( 'edit' );
  1509. $this->addLink( array(
  1510. 'rel' => 'alternate',
  1511. 'type' => 'application/x-wiki',
  1512. 'title' => $msg,
  1513. 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
  1514. ) );
  1515. // Alternate edit link
  1516. $this->addLink( array(
  1517. 'rel' => 'edit',
  1518. 'title' => $msg,
  1519. 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
  1520. ) );
  1521. }
  1522. }
  1523. # Buffer output; final headers may depend on later processing
  1524. ob_start();
  1525. $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
  1526. $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
  1527. // Prevent framing, if requested
  1528. $frameOptions = $this->getFrameOptions();
  1529. if ( $frameOptions ) {
  1530. $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
  1531. }
  1532. if ( $this->mArticleBodyOnly ) {
  1533. $this->out( $this->mBodytext );
  1534. } else {
  1535. // Hook that allows last minute changes to the output page, e.g.
  1536. // adding of CSS or Javascript by extensions.
  1537. wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
  1538. wfProfileIn( 'Output-skin' );
  1539. $sk->outputPage( $this );
  1540. wfProfileOut( 'Output-skin' );
  1541. }
  1542. $this->sendCacheControl();
  1543. ob_end_flush();
  1544. wfProfileOut( __METHOD__ );
  1545. }
  1546. /**
  1547. * Actually output something with print(). Performs an iconv to the
  1548. * output encoding, if needed.
  1549. *
  1550. * @param $ins String: the string to output
  1551. */
  1552. public function out( $ins ) {
  1553. global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
  1554. if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
  1555. $outs = $ins;
  1556. } else {
  1557. $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
  1558. if ( false === $outs ) {
  1559. $outs = $ins;
  1560. }
  1561. }
  1562. print $outs;
  1563. }
  1564. /**
  1565. * @todo document
  1566. */
  1567. public static function setEncodings() {
  1568. global $wgInputEncoding, $wgOutputEncoding;
  1569. $wgInputEncoding = strtolower( $wgInputEncoding );
  1570. if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
  1571. $wgOutputEncoding = strtolower( $wgOutputEncoding );
  1572. return;
  1573. }
  1574. $wgOutputEncoding = $wgInputEncoding;
  1575. }
  1576. /**
  1577. * @deprecated use wfReportTime() instead.
  1578. *
  1579. * @return String
  1580. */
  1581. public function reportTime() {
  1582. wfDeprecated( __METHOD__ );
  1583. $time = wfReportTime();
  1584. return $time;
  1585. }
  1586. /**
  1587. * Produce a "user is blocked" page.
  1588. *
  1589. * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
  1590. * @return nothing
  1591. */
  1592. function blockedPage( $return = true ) {
  1593. global $wgUser, $wgContLang, $wgLang;
  1594. $this->setPageTitle( wfMsg( 'blockedtitle' ) );
  1595. $this->setRobotPolicy( 'noindex,nofollow' );
  1596. $this->setArticleRelated( false );
  1597. $name = User::whoIs( $wgUser->blockedBy() );
  1598. $reason = $wgUser->blockedFor();
  1599. if( $reason == '' ) {
  1600. $reason = wfMsg( 'blockednoreason' );
  1601. }
  1602. $blockTimestamp = $wgLang->timeanddate(
  1603. wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
  1604. );
  1605. $ip = wfGetIP();
  1606. $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
  1607. $blockid = $wgUser->mBlock->mId;
  1608. $blockExpiry = $wgUser->mBlock->mExpiry;
  1609. if ( $blockExpiry == 'infinity' ) {
  1610. // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
  1611. // Search for localization in 'ipboptions'
  1612. $scBlockExpiryOptions = wfMsg( 'ipboptions' );
  1613. foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
  1614. if ( strpos( $option, ':' ) === false ) {
  1615. continue;
  1616. }
  1617. list( $show, $value ) = explode( ':', $option );
  1618. if ( $value == 'infinite' || $value == 'indefinite' ) {
  1619. $blockExpiry = $show;
  1620. break;
  1621. }
  1622. }
  1623. } else {
  1624. $blockExpiry = $wgLang->timeanddate(
  1625. wfTimestamp( TS_MW, $blockExpiry ),
  1626. true
  1627. );
  1628. }
  1629. if ( $wgUser->mBlock->mAuto ) {
  1630. $msg = 'autoblockedtext';
  1631. } else {
  1632. $msg = 'blockedtext';
  1633. }
  1634. /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
  1635. * This could be a username, an IP range, or a single IP. */
  1636. $intended = $wgUser->mBlock->mAddress;
  1637. $this->addWikiMsg(
  1638. $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
  1639. $intended, $blockTimestamp
  1640. );
  1641. # Don't auto-return to special pages
  1642. if( $return ) {
  1643. $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
  1644. $this->returnToMain( null, $return );
  1645. }
  1646. }
  1647. /**
  1648. * Output a standard error page
  1649. *
  1650. * @param $title String: message key for page title
  1651. * @param $msg String: message key for page text
  1652. * @param $params Array: message parameters
  1653. */
  1654. public function showErrorPage( $title, $msg, $params = array() ) {
  1655. if ( $this->getTitle() ) {
  1656. $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
  1657. }
  1658. $this->setPageTitle( wfMsg( $title ) );
  1659. $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
  1660. $this->setRobotPolicy( 'noindex,nofollow' );
  1661. $this->setArticleRelated( false );
  1662. $this->enableClientCache( false );
  1663. $this->mRedirect = '';
  1664. $this->mBodytext = '';
  1665. array_unshift( $params, 'parse' );
  1666. array_unshift( $params, $msg );
  1667. $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
  1668. $this->returnToMain();
  1669. }
  1670. /**
  1671. * Output a standard permission error page
  1672. *
  1673. * @param $errors Array: error message keys
  1674. * @param $action String: action that was denied or null if unknown
  1675. */
  1676. public function showPermissionsErrorPage( $errors, $action = null ) {
  1677. $this->mDebugtext .= 'Original title: ' .
  1678. $this->getTitle()->getPrefixedText() . "\n";
  1679. $this->setPageTitle( wfMsg( 'permissionserrors' ) );
  1680. $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
  1681. $this->setRobotPolicy( 'noindex,nofollow' );
  1682. $this->setArticleRelated( false );
  1683. $this->enableClientCache( false );
  1684. $this->mRedirect = '';
  1685. $this->mBodytext = '';
  1686. $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
  1687. }
  1688. /**
  1689. * Display an error page indicating that a given version of MediaWiki is
  1690. * required to use it
  1691. *
  1692. * @param $version Mixed: the version of MediaWiki needed to use the page
  1693. */
  1694. public function versionRequired( $version ) {
  1695. $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
  1696. $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
  1697. $this->setRobotPolicy( 'noindex,nofollow' );
  1698. $this->setArticleRelated( false );
  1699. $this->mBodytext = '';
  1700. $this->addWikiMsg( 'versionrequiredtext', $version );
  1701. $this->returnToMain();
  1702. }
  1703. /**
  1704. * Display an error page noting that a given permission bit is required.
  1705. *
  1706. * @param $permission String: key required
  1707. */
  1708. public function permissionRequired( $permission ) {
  1709. global $wgLang;
  1710. $this->setPageTitle( wfMsg( 'badaccess' ) );
  1711. $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
  1712. $this->setRobotPolicy( 'noindex,nofollow' );
  1713. $this->setArticleRelated( false );
  1714. $this->mBodytext = '';
  1715. $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
  1716. User::getGroupsWithPermission( $permission ) );
  1717. if( $groups ) {
  1718. $this->addWikiMsg(
  1719. 'badaccess-groups',
  1720. $wgLang->commaList( $groups ),
  1721. count( $groups )
  1722. );
  1723. } else {
  1724. $this->addWikiMsg( 'badaccess-group0' );
  1725. }
  1726. $this->returnToMain();
  1727. }
  1728. /**
  1729. * Produce the stock "please login to use the wiki" page
  1730. */
  1731. public function loginToUse() {
  1732. global $wgUser;
  1733. if( $wgUser->isLoggedIn() ) {
  1734. $this->permissionRequired( 'read' );
  1735. return;
  1736. }
  1737. $skin = $wgUser->getSkin();
  1738. $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
  1739. $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
  1740. $this->setRobotPolicy( 'noindex,nofollow' );
  1741. $this->setArticleFlag( false );
  1742. $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
  1743. $loginLink = $skin->link(
  1744. $loginTitle,
  1745. wfMsgHtml( 'loginreqlink' ),
  1746. array(),
  1747. array( 'returnto' => $this->getTitle()->getPrefixedText() ),
  1748. array( 'known', 'noclasses' )
  1749. );
  1750. $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
  1751. $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
  1752. # Don't return to the main page if the user can't read it
  1753. # otherwise we'll end up in a pointless loop
  1754. $mainPage = Title::newMainPage();
  1755. if( $mainPage->userCanRead() ) {
  1756. $this->returnToMain( null, $mainPage );
  1757. }
  1758. }
  1759. /**
  1760. * Format a list of error messages
  1761. *
  1762. * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
  1763. * @param $action String: action that was denied or null if unknown
  1764. * @return String: the wikitext error-messages, formatted into a list.
  1765. */
  1766. public function formatPermissionsErrorMessage( $errors, $action = null ) {
  1767. if ( $action == null ) {
  1768. $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
  1769. } else {
  1770. $action_desc = wfMsgNoTrans( "action-$action" );
  1771. $text = wfMsgNoTrans(
  1772. 'permissionserrorstext-withaction',
  1773. count( $errors ),
  1774. $action_desc
  1775. ) . "\n\n";
  1776. }
  1777. if ( count( $errors ) > 1 ) {
  1778. $text .= '<ul class="permissions-errors">' . "\n";
  1779. foreach( $errors as $error ) {
  1780. $text .= '<li>';
  1781. $text .= call_user_func_array( 'wfMsgNoTrans', $error );
  1782. $text .= "</li>\n";
  1783. }
  1784. $text .= '</ul>';
  1785. } else {
  1786. $text .= "<div class=\"permissions-errors\">\n" .
  1787. call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
  1788. "\n</div>";
  1789. }
  1790. return $text;
  1791. }
  1792. /**
  1793. * Display a page stating that the Wiki is in read-only mode,
  1794. * and optionally show the source of the page that the user
  1795. * was trying to edit. Should only be called (for this
  1796. * purpose) after wfReadOnly() has returned true.
  1797. *
  1798. * For historical reasons, this function is _also_ used to
  1799. * show the error message when a user tries to edit a page
  1800. * they are not allowed to edit. (Unless it's because they're
  1801. * blocked, then we show blockedPage() instead.) In this
  1802. * case, the second parameter should be set to true and a list
  1803. * of reasons supplied as the third parameter.
  1804. *
  1805. * @todo Needs to be split into multiple functions.
  1806. *
  1807. * @param $source String: source code to show (or null).
  1808. * @param $protected Boolean: is this a permissions error?
  1809. * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
  1810. * @param $action String: action that was denied or null if unknown
  1811. */
  1812. public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
  1813. global $wgUser;
  1814. $skin = $wgUser->getSkin();
  1815. $this->setRobotPolicy( 'noindex,nofollow' );
  1816. $this->setArticleRelated( false );
  1817. // If no reason is given, just supply a default "I can't let you do
  1818. // that, Dave" message. Should only occur if called by legacy code.
  1819. if ( $protected && empty( $reasons ) ) {
  1820. $reasons[] = array( 'badaccess-group0' );
  1821. }
  1822. if ( !empty( $reasons ) ) {
  1823. // Permissions error
  1824. if( $source ) {
  1825. $this->setPageTitle( wfMsg( 'viewsource' ) );
  1826. $this->setSubtitle(
  1827. wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
  1828. );
  1829. } else {
  1830. $this->setPageTitle( wfMsg( 'badaccess' ) );
  1831. }
  1832. $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
  1833. } else {
  1834. // Wiki is read only
  1835. $this->setPageTitle( wfMsg( 'readonly' ) );
  1836. $reason = wfReadOnlyReason();
  1837. $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
  1838. }
  1839. // Show source, if supplied
  1840. if( is_string( $source ) ) {
  1841. $this->addWikiMsg( 'viewsourcetext' );
  1842. $params = array(
  1843. 'id' => 'wpTextbox1',
  1844. 'name' => 'wpTextbox1',
  1845. 'cols' => $wgUser->getOption( 'cols' ),
  1846. 'rows' => $wgUser->getOption( 'rows' ),
  1847. 'readonly' => 'readonly'
  1848. );
  1849. $this->addHTML( Html::element( 'textarea', $params, $source ) );
  1850. // Show templates used by this article
  1851. $skin = $wgUser->getSkin();
  1852. $article = new Article( $this->getTitle() );
  1853. $this->addHTML( "<div class='templatesUsed'>
  1854. {$skin->formatTemplates( $article->getUsedTemplates() )}
  1855. </div>
  1856. " );
  1857. }
  1858. # If the title doesn't exist, it's fairly pointless to print a return
  1859. # link to it. After all, you just tried editing it and couldn't, so
  1860. # what's there to do there?
  1861. if( $this->getTitle()->exists() ) {
  1862. $this->returnToMain( null, $this->getTitle() );
  1863. }
  1864. }
  1865. /** @deprecated */
  1866. public function errorpage( $title, $msg ) {
  1867. wfDeprecated( __METHOD__ );
  1868. throw new ErrorPageError( $title, $msg );
  1869. }
  1870. /** @deprecated */
  1871. public function databaseError( $fname, $sql, $error, $errno ) {
  1872. throw new MWException( "OutputPage::databaseError is obsolete\n" );
  1873. }
  1874. /** @deprecated */
  1875. public function fatalError( $message ) {
  1876. wfDeprecated( __METHOD__ );
  1877. throw new FatalError( $message );
  1878. }
  1879. /** @deprecated */
  1880. public function unexpectedValueError( $name, $val ) {
  1881. wfDeprecated( __METHOD__ );
  1882. throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
  1883. }
  1884. /** @deprecated */
  1885. public function fileCopyError( $old, $new ) {
  1886. wfDeprecated( __METHOD__ );
  1887. throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
  1888. }
  1889. /** @deprecated */
  1890. public function fileRenameError( $old, $new ) {
  1891. wfDeprecated( __METHOD__ );
  1892. throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
  1893. }
  1894. /** @deprecated */
  1895. public function fileDeleteError( $name ) {
  1896. wfDeprecated( __METHOD__ );
  1897. throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
  1898. }
  1899. /** @deprecated */
  1900. public function fileNotFoundError( $name ) {
  1901. wfDeprecated( __METHOD__ );
  1902. throw new FatalError( wfMsg( 'filenotfound', $name ) );
  1903. }
  1904. public function showFatalError( $message ) {
  1905. $this->setPageTitle( wfMsg( 'internalerror' ) );
  1906. $this->setRobotPolicy( 'noindex,nofollow' );
  1907. $this->setArticleRelated( false );
  1908. $this->enableClientCache( false );
  1909. $this->mRedirect = '';
  1910. $this->mBodytext = $message;
  1911. }
  1912. public function showUnexpectedValueError( $name, $val ) {
  1913. $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
  1914. }
  1915. public function showFileCopyError( $old, $new ) {
  1916. $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
  1917. }
  1918. public function showFileRenameError( $old, $new ) {
  1919. $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
  1920. }
  1921. public function showFileDeleteError( $name ) {
  1922. $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
  1923. }
  1924. public function showFileNotFoundError( $name ) {
  1925. $this->showFatalError( wfMsg( 'filenotfound', $name ) );
  1926. }
  1927. /**
  1928. * Add a "return to" link pointing to a specified title
  1929. *
  1930. * @param $title Title to link
  1931. * @param $query String: query string
  1932. * @param $text String text of the link (input is not escaped)
  1933. */
  1934. public function addReturnTo( $title, $query = array(), $text = null ) {
  1935. global $wgUser;
  1936. $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
  1937. $link = wfMsgHtml(
  1938. 'returnto',
  1939. $wgUser->getSkin()->link( $title, $text, array(), $query )
  1940. );
  1941. $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
  1942. }
  1943. /**
  1944. * Add a "return to" link pointing to a specified title,
  1945. * or the title indicated in the request, or else the main page
  1946. *
  1947. * @param $unused No longer used
  1948. * @param $returnto Title or String to return to
  1949. * @param $returntoquery String: query string for the return to link
  1950. */
  1951. public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
  1952. global $wgRequest;
  1953. if ( $returnto == null ) {
  1954. $returnto = $wgRequest->getText( 'returnto' );
  1955. }
  1956. if ( $returntoquery == null ) {
  1957. $returntoquery = $wgRequest->getText( 'returntoquery' );
  1958. }
  1959. if ( $returnto === '' ) {
  1960. $returnto = Title::newMainPage();
  1961. }
  1962. if ( is_object( $returnto ) ) {
  1963. $titleObj = $returnto;
  1964. } else {
  1965. $titleObj = Title::newFromText( $returnto );
  1966. }
  1967. if ( !is_object( $titleObj ) ) {
  1968. $titleObj = Title::newMainPage();
  1969. }
  1970. $this->addReturnTo( $titleObj, $returntoquery );
  1971. }
  1972. /**
  1973. * @param $sk Skin The given Skin
  1974. * @param $includeStyle Boolean: unused
  1975. * @return String: The doctype, opening <html>, and head element.
  1976. */
  1977. public function headElement( Skin $sk, $includeStyle = true ) {
  1978. global $wgOutputEncoding, $wgMimeType;
  1979. global $wgUseTrackbacks, $wgHtml5;
  1980. global $wgUser, $wgRequest, $wgLang;
  1981. if ( $sk->commonPrintStylesheet() ) {
  1982. $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
  1983. }
  1984. $sk->setupUserCss( $this );
  1985. $lang = wfUILang();
  1986. $ret = Html::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
  1987. if ( $this->getHTMLTitle() == '' ) {
  1988. $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
  1989. }
  1990. $openHead = Html::openElement( 'head' );
  1991. if ( $openHead ) {
  1992. # Don't bother with the newline if $head == ''
  1993. $ret .= "$openHead\n";
  1994. }
  1995. if ( $wgHtml5 ) {
  1996. # More succinct than <meta http-equiv=Content-Type>, has the
  1997. # same effect
  1998. $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
  1999. } else {
  2000. $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
  2001. }
  2002. $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
  2003. $ret .= implode( "\n", array(
  2004. $this->getHeadLinks( $sk ),
  2005. $this->buildCssLinks( $sk ),
  2006. $this->getHeadItems()
  2007. ) );
  2008. if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
  2009. $ret .= $this->getTitle()->trackbackRDF();
  2010. }
  2011. $closeHead = Html::closeElement( 'head' );
  2012. if ( $closeHead ) {
  2013. $ret .= "$closeHead\n";
  2014. }
  2015. $bodyAttrs = array();
  2016. # Crazy edit-on-double-click stuff
  2017. $action = $wgRequest->getVal( 'action', 'view' );
  2018. if (
  2019. $this->getTitle()->getNamespace() != NS_SPECIAL &&
  2020. !in_array( $action, array( 'edit', 'submit' ) ) &&
  2021. $wgUser->getOption( 'editondblclick' )
  2022. )
  2023. {
  2024. $editUrl = $this->getTitle()->getLocalUrl( $sk->editUrlOptions() );
  2025. $bodyAttrs['ondblclick'] = "document.location = '" .
  2026. Xml::escapeJsString( $editUrl ) . "'";
  2027. }
  2028. # Class bloat
  2029. $dir = wfUILang()->getDir();
  2030. $bodyAttrs['class'] = "mediawiki $dir";
  2031. if ( $wgLang->capitalizeAllNouns() ) {
  2032. # A <body> class is probably not the best way to do this . . .
  2033. $bodyAttrs['class'] .= ' capitalize-all-nouns';
  2034. }
  2035. $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
  2036. if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
  2037. $bodyAttrs['class'] .= ' ns-special';
  2038. } elseif ( $this->getTitle()->isTalkPage() ) {
  2039. $bodyAttrs['class'] .= ' ns-talk';
  2040. } else {
  2041. $bodyAttrs['class'] .= ' ns-subject';
  2042. }
  2043. $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
  2044. $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
  2045. $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
  2046. wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
  2047. $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
  2048. return $ret;
  2049. }
  2050. /**
  2051. * Get a ResourceLoader object associated with this OutputPage
  2052. */
  2053. public function getResourceLoader() {
  2054. if ( is_null( $this->mResourceLoader ) ) {
  2055. $this->mResourceLoader = new ResourceLoader();
  2056. }
  2057. return $this->mResourceLoader;
  2058. }
  2059. /**
  2060. * TODO: Document
  2061. * @param $skin Skin
  2062. * @param $modules Array/string with the module name
  2063. * @param $only string May be styles, messages or scripts
  2064. * @param $useESI boolean
  2065. * @return string html <script> and <style> tags
  2066. */
  2067. protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
  2068. global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
  2069. $wgResourceLoaderInlinePrivateModules, $wgRequest;
  2070. // Lazy-load ResourceLoader
  2071. // TODO: Should this be a static function of ResourceLoader instead?
  2072. $baseQuery = array(
  2073. 'lang' => $wgLang->getCode(),
  2074. 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
  2075. 'skin' => $skin->getSkinName(),
  2076. 'only' => $only,
  2077. );
  2078. // Propagate printable and handheld parameters if present
  2079. if ( $wgRequest->getBool( 'printable' ) ) {
  2080. $baseQuery['printable'] = 1;
  2081. }
  2082. if ( $wgRequest->getBool( 'handheld' ) ) {
  2083. $baseQuery['handheld'] = 1;
  2084. }
  2085. if ( !count( $modules ) ) {
  2086. return '';
  2087. }
  2088. if ( count( $modules ) > 1 ) {
  2089. // Remove duplicate module requests
  2090. $modules = array_unique( (array) $modules );
  2091. // Sort module names so requests are more uniform
  2092. sort( $modules );
  2093. if ( ResourceLoader::inDebugMode() ) {
  2094. // Recursively call us for every item
  2095. $links = '';
  2096. foreach ( $modules as $name ) {
  2097. $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
  2098. }
  2099. return $links;
  2100. }
  2101. }
  2102. // Create keyed-by-group list of module objects from modules list
  2103. $groups = array();
  2104. $resourceLoader = $this->getResourceLoader();
  2105. foreach ( (array) $modules as $name ) {
  2106. $module = $resourceLoader->getModule( $name );
  2107. $group = $module->getGroup();
  2108. if ( !isset( $groups[$group] ) ) {
  2109. $groups[$group] = array();
  2110. }
  2111. $groups[$group][$name] = $module;
  2112. }
  2113. $links = '';
  2114. foreach ( $groups as $group => $modules ) {
  2115. $query = $baseQuery;
  2116. // Special handling for user-specific groups
  2117. if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
  2118. $query['user'] = $wgUser->getName();
  2119. }
  2120. // Create a fake request based on the one we are about to make so modules return
  2121. // correct timestamp and emptiness data
  2122. $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
  2123. // Drop modules that know they're empty
  2124. foreach ( $modules as $key => $module ) {
  2125. if ( $module->isKnownEmpty( $context ) ) {
  2126. unset( $modules[$key] );
  2127. }
  2128. }
  2129. // If there are no modules left, skip this group
  2130. if ( $modules === array() ) {
  2131. continue;
  2132. }
  2133. $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $modules ) );
  2134. // Support inlining of private modules if configured as such
  2135. if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
  2136. if ( $only == 'styles' ) {
  2137. $links .= Html::inlineStyle(
  2138. $resourceLoader->makeModuleResponse( $context, $modules )
  2139. );
  2140. } else {
  2141. $links .= Html::inlineScript(
  2142. ResourceLoader::makeLoaderConditionalScript(
  2143. $resourceLoader->makeModuleResponse( $context, $modules )
  2144. )
  2145. );
  2146. }
  2147. continue;
  2148. }
  2149. // Special handling for the user group; because users might change their stuff
  2150. // on-wiki like user pages, or user preferences; we need to find the highest
  2151. // timestamp of these user-changable modules so we can ensure cache misses on change
  2152. // This should NOT be done for the site group (bug 27564) because anons get that too
  2153. // and we shouldn't be putting timestamps in Squid-cached HTML
  2154. if ( $group === 'user' ) {
  2155. // Get the maximum timestamp
  2156. $timestamp = 1;
  2157. foreach ( $modules as $module ) {
  2158. $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
  2159. }
  2160. // Add a version parameter so cache will break when things change
  2161. $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
  2162. }
  2163. // Make queries uniform in order
  2164. ksort( $query );
  2165. $url = wfAppendQuery( $wgLoadScript, $query );
  2166. // Prevent the IE6 extension check from being triggered (bug 28840)
  2167. // by appending a character that's invalid in Windows extensions ('*')
  2168. $url .= '&*';
  2169. if ( $useESI && $wgResourceLoaderUseESI ) {
  2170. $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
  2171. if ( $only == 'styles' ) {
  2172. $links .= Html::inlineStyle( $esi );
  2173. } else {
  2174. $links .= Html::inlineScript( $esi );
  2175. }
  2176. } else {
  2177. // Automatically select style/script elements
  2178. if ( $only === 'styles' ) {
  2179. $links .= Html::linkedStyle( $url ) . "\n";
  2180. } else {
  2181. $links .= Html::linkedScript( $url ) . "\n";
  2182. }
  2183. }
  2184. }
  2185. return $links;
  2186. }
  2187. /**
  2188. * Gets the global variables and mScripts; also adds userjs to the end if
  2189. * enabled. Despite the name, these scripts are no longer put in the
  2190. * <head> but at the bottom of the <body>
  2191. *
  2192. * @param $sk Skin object to use
  2193. * @return String: HTML fragment
  2194. */
  2195. function getHeadScripts( Skin $sk ) {
  2196. global $wgUser, $wgRequest, $wgUseSiteJs;
  2197. // Startup - this will immediately load jquery and mediawiki modules
  2198. $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
  2199. // Configuration -- This could be merged together with the load and go, but
  2200. // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
  2201. $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
  2202. // Script and Messages "only" requests
  2203. $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
  2204. $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
  2205. // Modules requests - let the client calculate dependencies and batch requests as it likes
  2206. if ( $this->getModules() ) {
  2207. $scripts .= Html::inlineScript(
  2208. ResourceLoader::makeLoaderConditionalScript(
  2209. Xml::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
  2210. Xml::encodeJsCall( 'mediaWiki.loader.go', array() )
  2211. )
  2212. ) . "\n";
  2213. }
  2214. // Legacy Scripts
  2215. $scripts .= "\n" . $this->mScripts;
  2216. // Add site JS if enabled
  2217. if ( $wgUseSiteJs ) {
  2218. $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
  2219. }
  2220. // Add user JS if enabled - trying to load user.options as a bundle if possible
  2221. $userOptionsAdded = false;
  2222. if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
  2223. $action = $wgRequest->getVal( 'action', 'view' );
  2224. if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
  2225. # XXX: additional security check/prompt?
  2226. $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
  2227. } else {
  2228. $scripts .= $this->makeResourceLoaderLink(
  2229. $sk, array( 'user', 'user.options' ), 'scripts'
  2230. );
  2231. $userOptionsAdded = true;
  2232. }
  2233. }
  2234. if ( !$userOptionsAdded ) {
  2235. $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
  2236. }
  2237. return $scripts;
  2238. }
  2239. /**
  2240. * Add default \<meta\> tags
  2241. */
  2242. protected function addDefaultMeta() {
  2243. global $wgVersion, $wgHtml5;
  2244. static $called = false;
  2245. if ( $called ) {
  2246. # Don't run this twice
  2247. return;
  2248. }
  2249. $called = true;
  2250. if ( !$wgHtml5 ) {
  2251. $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
  2252. }
  2253. $this->addMeta( 'generator', "MediaWiki $wgVersion" );
  2254. $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
  2255. if( $p !== 'index,follow' ) {
  2256. // http://www.robotstxt.org/wc/meta-user.html
  2257. // Only show if it's different from the default robots policy
  2258. $this->addMeta( 'robots', $p );
  2259. }
  2260. if ( count( $this->mKeywords ) > 0 ) {
  2261. $strip = array(
  2262. "/<.*?" . ">/" => '',
  2263. "/_/" => ' '
  2264. );
  2265. $this->addMeta(
  2266. 'keywords',
  2267. preg_replace(
  2268. array_keys( $strip ),
  2269. array_values( $strip ),
  2270. implode( ',', $this->mKeywords )
  2271. )
  2272. );
  2273. }
  2274. }
  2275. /**
  2276. * @return string HTML tag links to be put in the header.
  2277. */
  2278. public function getHeadLinks( Skin $sk ) {
  2279. global $wgFeed;
  2280. // Ideally this should happen earlier, somewhere. :P
  2281. $this->addDefaultMeta();
  2282. $tags = array();
  2283. foreach ( $this->mMetatags as $tag ) {
  2284. if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
  2285. $a = 'http-equiv';
  2286. $tag[0] = substr( $tag[0], 5 );
  2287. } else {
  2288. $a = 'name';
  2289. }
  2290. $tags[] = Html::element( 'meta',
  2291. array(
  2292. $a => $tag[0],
  2293. 'content' => $tag[1]
  2294. )
  2295. );
  2296. }
  2297. foreach ( $this->mLinktags as $tag ) {
  2298. $tags[] = Html::element( 'link', $tag );
  2299. }
  2300. if( $wgFeed ) {
  2301. foreach( $this->getSyndicationLinks() as $format => $link ) {
  2302. # Use the page name for the title (accessed through $wgTitle since
  2303. # there's no other way). In principle, this could lead to issues
  2304. # with having the same name for different feeds corresponding to
  2305. # the same page, but we can't avoid that at this low a level.
  2306. $tags[] = $this->feedLink(
  2307. $format,
  2308. $link,
  2309. # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
  2310. wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
  2311. );
  2312. }
  2313. # Recent changes feed should appear on every page (except recentchanges,
  2314. # that would be redundant). Put it after the per-page feed to avoid
  2315. # changing existing behavior. It's still available, probably via a
  2316. # menu in your browser. Some sites might have a different feed they'd
  2317. # like to promote instead of the RC feed (maybe like a "Recent New Articles"
  2318. # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
  2319. # If so, use it instead.
  2320. global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
  2321. $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
  2322. if ( $wgOverrideSiteFeed ) {
  2323. foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
  2324. $tags[] = $this->feedLink(
  2325. $type,
  2326. htmlspecialchars( $feedUrl ),
  2327. wfMsg( "site-{$type}-feed", $wgSitename )
  2328. );
  2329. }
  2330. } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
  2331. foreach ( $wgAdvertisedFeedTypes as $format ) {
  2332. $tags[] = $this->feedLink(
  2333. $format,
  2334. $rctitle->getLocalURL( "feed={$format}" ),
  2335. wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
  2336. );
  2337. }
  2338. }
  2339. }
  2340. return implode( "\n", $tags );
  2341. }
  2342. /**
  2343. * Generate a <link rel/> for a feed.
  2344. *
  2345. * @param $type String: feed type
  2346. * @param $url String: URL to the feed
  2347. * @param $text String: value of the "title" attribute
  2348. * @return String: HTML fragment
  2349. */
  2350. private function feedLink( $type, $url, $text ) {
  2351. return Html::element( 'link', array(
  2352. 'rel' => 'alternate',
  2353. 'type' => "application/$type+xml",
  2354. 'title' => $text,
  2355. 'href' => $url )
  2356. );
  2357. }
  2358. /**
  2359. * Add a local or specified stylesheet, with the given media options.
  2360. * Meant primarily for internal use...
  2361. *
  2362. * @param $style String: URL to the file
  2363. * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
  2364. * @param $condition String: for IE conditional comments, specifying an IE version
  2365. * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
  2366. */
  2367. public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
  2368. $options = array();
  2369. // Even though we expect the media type to be lowercase, but here we
  2370. // force it to lowercase to be safe.
  2371. if( $media ) {
  2372. $options['media'] = $media;
  2373. }
  2374. if( $condition ) {
  2375. $options['condition'] = $condition;
  2376. }
  2377. if( $dir ) {
  2378. $options['dir'] = $dir;
  2379. }
  2380. $this->styles[$style] = $options;
  2381. }
  2382. /**
  2383. * Adds inline CSS styles
  2384. * @param $style_css Mixed: inline CSS
  2385. */
  2386. public function addInlineStyle( $style_css ){
  2387. $this->mInlineStyles .= Html::inlineStyle( $style_css );
  2388. }
  2389. /**
  2390. * Build a set of <link>s for the stylesheets specified in the $this->styles array.
  2391. * These will be applied to various media & IE conditionals.
  2392. * @param $sk Skin object
  2393. */
  2394. public function buildCssLinks( $sk ) {
  2395. $ret = '';
  2396. // Add ResourceLoader styles
  2397. // Split the styles into four groups
  2398. $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array() );
  2399. $resourceLoader = $this->getResourceLoader();
  2400. foreach ( $this->getModuleStyles() as $name ) {
  2401. $group = $resourceLoader->getModule( $name )->getGroup();
  2402. // Modules in groups named "other" or anything different than "user", "site" or "private"
  2403. // will be placed in the "other" group
  2404. $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
  2405. }
  2406. // We want site, private and user styles to override dynamically added styles from modules, but we want
  2407. // dynamically added styles to override statically added styles from other modules. So the order
  2408. // has to be other, dynamic, site, private, user
  2409. // Add statically added styles for other modules
  2410. $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
  2411. // Add normal styles added through addStyle()/addInlineStyle() here
  2412. $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
  2413. // Add marker tag to mark the place where the client-side loader should inject dynamic styles
  2414. // We use a <meta> tag with a made-up name for this because that's valid HTML
  2415. $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
  2416. // Add site, private and user styles
  2417. // 'private' at present only contains user.options, so put that before 'user'
  2418. // Any future private modules will likely have a similar user-specific character
  2419. foreach ( array( 'site', 'private', 'user' ) as $group ) {
  2420. $ret .= $this->makeResourceLoaderLink(
  2421. $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
  2422. );
  2423. }
  2424. return $ret;
  2425. }
  2426. public function buildCssLinksArray() {
  2427. $links = array();
  2428. foreach( $this->styles as $file => $options ) {
  2429. $link = $this->styleLink( $file, $options );
  2430. if( $link ) {
  2431. $links[$file] = $link;
  2432. }
  2433. }
  2434. return $links;
  2435. }
  2436. /**
  2437. * Generate \<link\> tags for stylesheets
  2438. *
  2439. * @param $style String: URL to the file
  2440. * @param $options Array: option, can contain 'condition', 'dir', 'media'
  2441. * keys
  2442. * @return String: HTML fragment
  2443. */
  2444. protected function styleLink( $style, $options ) {
  2445. if( isset( $options['dir'] ) ) {
  2446. $siteDir = wfUILang()->getDir();
  2447. if( $siteDir != $options['dir'] ) {
  2448. return '';
  2449. }
  2450. }
  2451. if( isset( $options['media'] ) ) {
  2452. $media = self::transformCssMedia( $options['media'] );
  2453. if( is_null( $media ) ) {
  2454. return '';
  2455. }
  2456. } else {
  2457. $media = 'all';
  2458. }
  2459. if( substr( $style, 0, 1 ) == '/' ||
  2460. substr( $style, 0, 5 ) == 'http:' ||
  2461. substr( $style, 0, 6 ) == 'https:' ) {
  2462. $url = $style;
  2463. } else {
  2464. global $wgStylePath, $wgStyleVersion;
  2465. $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
  2466. }
  2467. $link = Html::linkedStyle( $url, $media );
  2468. if( isset( $options['condition'] ) ) {
  2469. $condition = htmlspecialchars( $options['condition'] );
  2470. $link = "<!--[if $condition]>$link<![endif]-->";
  2471. }
  2472. return $link;
  2473. }
  2474. /**
  2475. * Transform "media" attribute based on request parameters
  2476. *
  2477. * @param $media String: current value of the "media" attribute
  2478. * @return String: modified value of the "media" attribute
  2479. */
  2480. public static function transformCssMedia( $media ) {
  2481. global $wgRequest, $wgHandheldForIPhone;
  2482. // Switch in on-screen display for media testing
  2483. $switches = array(
  2484. 'printable' => 'print',
  2485. 'handheld' => 'handheld',
  2486. );
  2487. foreach( $switches as $switch => $targetMedia ) {
  2488. if( $wgRequest->getBool( $switch ) ) {
  2489. if( $media == $targetMedia ) {
  2490. $media = '';
  2491. } elseif( $media == 'screen' ) {
  2492. return null;
  2493. }
  2494. }
  2495. }
  2496. // Expand longer media queries as iPhone doesn't grok 'handheld'
  2497. if( $wgHandheldForIPhone ) {
  2498. $mediaAliases = array(
  2499. 'screen' => 'screen and (min-device-width: 481px)',
  2500. 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
  2501. );
  2502. if( isset( $mediaAliases[$media] ) ) {
  2503. $media = $mediaAliases[$media];
  2504. }
  2505. }
  2506. return $media;
  2507. }
  2508. /**
  2509. * Turn off regular page output and return an error reponse
  2510. * for when rate limiting has triggered.
  2511. */
  2512. public function rateLimited() {
  2513. $this->setPageTitle( wfMsg( 'actionthrottled' ) );
  2514. $this->setRobotPolicy( 'noindex,follow' );
  2515. $this->setArticleRelated( false );
  2516. $this->enableClientCache( false );
  2517. $this->mRedirect = '';
  2518. $this->clearHTML();
  2519. $this->setStatusCode( 503 );
  2520. $this->addWikiMsg( 'actionthrottledtext' );
  2521. $this->returnToMain( null, $this->getTitle() );
  2522. }
  2523. /**
  2524. * Show a warning about slave lag
  2525. *
  2526. * If the lag is higher than $wgSlaveLagCritical seconds,
  2527. * then the warning is a bit more obvious. If the lag is
  2528. * lower than $wgSlaveLagWarning, then no warning is shown.
  2529. *
  2530. * @param $lag Integer: slave lag
  2531. */
  2532. public function showLagWarning( $lag ) {
  2533. global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
  2534. if( $lag >= $wgSlaveLagWarning ) {
  2535. $message = $lag < $wgSlaveLagCritical
  2536. ? 'lag-warn-normal'
  2537. : 'lag-warn-high';
  2538. $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
  2539. $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
  2540. }
  2541. }
  2542. /**
  2543. * Add a wikitext-formatted message to the output.
  2544. * This is equivalent to:
  2545. *
  2546. * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
  2547. */
  2548. public function addWikiMsg( /*...*/ ) {
  2549. $args = func_get_args();
  2550. $name = array_shift( $args );
  2551. $this->addWikiMsgArray( $name, $args );
  2552. }
  2553. /**
  2554. * Add a wikitext-formatted message to the output.
  2555. * Like addWikiMsg() except the parameters are taken as an array
  2556. * instead of a variable argument list.
  2557. *
  2558. * $options is passed through to wfMsgExt(), see that function for details.
  2559. */
  2560. public function addWikiMsgArray( $name, $args, $options = array() ) {
  2561. $options[] = 'parse';
  2562. $text = wfMsgExt( $name, $options, $args );
  2563. $this->addHTML( $text );
  2564. }
  2565. /**
  2566. * This function takes a number of message/argument specifications, wraps them in
  2567. * some overall structure, and then parses the result and adds it to the output.
  2568. *
  2569. * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
  2570. * on. The subsequent arguments may either be strings, in which case they are the
  2571. * message names, or arrays, in which case the first element is the message name,
  2572. * and subsequent elements are the parameters to that message.
  2573. *
  2574. * The special named parameter 'options' in a message specification array is passed
  2575. * through to the $options parameter of wfMsgExt().
  2576. *
  2577. * Don't use this for messages that are not in users interface language.
  2578. *
  2579. * For example:
  2580. *
  2581. * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
  2582. *
  2583. * Is equivalent to:
  2584. *
  2585. * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
  2586. *
  2587. * The newline after opening div is needed in some wikitext. See bug 19226.
  2588. */
  2589. public function wrapWikiMsg( $wrap /*, ...*/ ) {
  2590. $msgSpecs = func_get_args();
  2591. array_shift( $msgSpecs );
  2592. $msgSpecs = array_values( $msgSpecs );
  2593. $s = $wrap;
  2594. foreach ( $msgSpecs as $n => $spec ) {
  2595. $options = array();
  2596. if ( is_array( $spec ) ) {
  2597. $args = $spec;
  2598. $name = array_shift( $args );
  2599. if ( isset( $args['options'] ) ) {
  2600. $options = $args['options'];
  2601. unset( $args['options'] );
  2602. }
  2603. } else {
  2604. $args = array();
  2605. $name = $spec;
  2606. }
  2607. $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
  2608. }
  2609. $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
  2610. }
  2611. /**
  2612. * Include jQuery core. Use this to avoid loading it multiple times
  2613. * before we get a usable script loader.
  2614. *
  2615. * @param $modules Array: list of jQuery modules which should be loaded
  2616. * @return Array: the list of modules which were not loaded.
  2617. * @since 1.16
  2618. * @deprecated No longer needed as of 1.17
  2619. */
  2620. public function includeJQuery( $modules = array() ) {
  2621. return array();
  2622. }
  2623. }