PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/OutputPage.php

https://bitbucket.org/brunodefraine/mediawiki
PHP | 3506 lines | 1809 code | 399 blank | 1298 comment | 309 complexity | bead357dfa806c0fa23a5034c56272ad MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. if ( !defined( 'MEDIAWIKI' ) ) {
  3. die( 1 );
  4. }
  5. /**
  6. * This class should be covered by a general architecture document which does
  7. * not exist as of January 2011. This is one of the Core classes and should
  8. * be read at least once by any new developers.
  9. *
  10. * This class is used to prepare the final rendering. A skin is then
  11. * applied to the output parameters (links, javascript, html, categories ...).
  12. *
  13. * @todo FIXME: Another class handles sending the whole page to the client.
  14. *
  15. * Some comments comes from a pairing session between Zak Greant and Antoine Musso
  16. * in November 2010.
  17. *
  18. * @todo document
  19. */
  20. class OutputPage extends ContextSource {
  21. /// Should be private. Used with addMeta() which adds <meta>
  22. var $mMetatags = array();
  23. /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
  24. var $mKeywords = array();
  25. var $mLinktags = array();
  26. /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
  27. var $mExtStyles = array();
  28. /// Should be private - has getter and setter. Contains the HTML title
  29. var $mPagetitle = '';
  30. /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
  31. var $mBodytext = '';
  32. /**
  33. * Holds the debug lines that will be output as comments in page source if
  34. * $wgDebugComments is enabled. See also $wgShowDebug.
  35. * TODO: make a getter method for this
  36. */
  37. public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
  38. /// Should be private. Stores contents of <title> tag
  39. var $mHTMLtitle = '';
  40. /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
  41. var $mIsarticle = false;
  42. /**
  43. * Should be private. Has get/set methods properly documented.
  44. * Stores "article flag" toggle.
  45. */
  46. var $mIsArticleRelated = true;
  47. /**
  48. * Should be private. We have to set isPrintable(). Some pages should
  49. * never be printed (ex: redirections).
  50. */
  51. var $mPrintable = false;
  52. /**
  53. * Should be private. We have set/get/append methods.
  54. *
  55. * Contains the page subtitle. Special pages usually have some links here.
  56. * Don't confuse with site subtitle added by skins.
  57. */
  58. private $mSubtitle = array();
  59. var $mRedirect = '';
  60. var $mStatusCode;
  61. /**
  62. * mLastModified and mEtag are used for sending cache control.
  63. * The whole caching system should probably be moved into its own class.
  64. */
  65. var $mLastModified = '';
  66. /**
  67. * Should be private. No getter but used in sendCacheControl();
  68. * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
  69. * as a unique identifier for the content. It is later used by the client
  70. * to compare its cached version with the server version. Client sends
  71. * headers If-Match and If-None-Match containing its locally cached ETAG value.
  72. *
  73. * To get more information, you will have to look at HTTP/1.1 protocol which
  74. * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
  75. */
  76. var $mETag = false;
  77. var $mCategoryLinks = array();
  78. var $mCategories = array();
  79. /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
  80. var $mLanguageLinks = array();
  81. /**
  82. * Should be private. Used for JavaScript (pre resource loader)
  83. * We should split js / css.
  84. * mScripts content is inserted as is in <head> by Skin. This might contains
  85. * either a link to a stylesheet or inline css.
  86. */
  87. var $mScripts = '';
  88. /**
  89. * Inline CSS styles. Use addInlineStyle() sparsingly
  90. */
  91. var $mInlineStyles = '';
  92. //
  93. var $mLinkColours;
  94. /**
  95. * Used by skin template.
  96. * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
  97. */
  98. var $mPageLinkTitle = '';
  99. /// Array of elements in <head>. Parser might add its own headers!
  100. var $mHeadItems = array();
  101. // @todo FIXME: Next variables probably comes from the resource loader
  102. var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
  103. var $mResourceLoader;
  104. var $mJsConfigVars = array();
  105. /** @todo FIXME: Is this still used ?*/
  106. var $mInlineMsg = array();
  107. var $mTemplateIds = array();
  108. var $mImageTimeKeys = array();
  109. var $mRedirectCode = '';
  110. var $mFeedLinksAppendQuery = null;
  111. # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
  112. # @see ResourceLoaderModule::$origin
  113. # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
  114. protected $mAllowedModules = array(
  115. ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
  116. );
  117. /**
  118. * @EasterEgg I just love the name for this self documenting variable.
  119. * @todo document
  120. */
  121. var $mDoNothing = false;
  122. // Parser related.
  123. var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
  124. /**
  125. * lazy initialised, use parserOptions()
  126. * @var ParserOptions
  127. */
  128. protected $mParserOptions = null;
  129. /**
  130. * Handles the atom / rss links.
  131. * We probably only support atom in 2011.
  132. * Looks like a private variable.
  133. * @see $wgAdvertisedFeedTypes
  134. */
  135. var $mFeedLinks = array();
  136. // Gwicke work on squid caching? Roughly from 2003.
  137. var $mEnableClientCache = true;
  138. /**
  139. * Flag if output should only contain the body of the article.
  140. * Should be private.
  141. */
  142. var $mArticleBodyOnly = false;
  143. var $mNewSectionLink = false;
  144. var $mHideNewSectionLink = false;
  145. /**
  146. * Comes from the parser. This was probably made to load CSS/JS only
  147. * if we had <gallery>. Used directly in CategoryPage.php
  148. * Looks like resource loader can replace this.
  149. */
  150. var $mNoGallery = false;
  151. // should be private.
  152. var $mPageTitleActionText = '';
  153. var $mParseWarnings = array();
  154. // Cache stuff. Looks like mEnableClientCache
  155. var $mSquidMaxage = 0;
  156. // @todo document
  157. var $mPreventClickjacking = true;
  158. /// should be private. To include the variable {{REVISIONID}}
  159. var $mRevisionId = null;
  160. private $mRevisionTimestamp = null;
  161. var $mFileVersion = null;
  162. /**
  163. * An array of stylesheet filenames (relative from skins path), with options
  164. * for CSS media, IE conditions, and RTL/LTR direction.
  165. * For internal use; add settings in the skin via $this->addStyle()
  166. *
  167. * Style again! This seems like a code duplication since we already have
  168. * mStyles. This is what makes OpenSource amazing.
  169. */
  170. var $styles = array();
  171. /**
  172. * Whether jQuery is already handled.
  173. */
  174. protected $mJQueryDone = false;
  175. private $mIndexPolicy = 'index';
  176. private $mFollowPolicy = 'follow';
  177. private $mVaryHeader = array(
  178. 'Accept-Encoding' => array( 'list-contains=gzip' ),
  179. 'Cookie' => null
  180. );
  181. /**
  182. * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
  183. * of the redirect.
  184. *
  185. * @var Title
  186. */
  187. private $mRedirectedFrom = null;
  188. /**
  189. * Constructor for OutputPage. This should not be called directly.
  190. * Instead a new RequestContext should be created and it will implicitly create
  191. * a OutputPage tied to that context.
  192. */
  193. function __construct( IContextSource $context = null ) {
  194. if ( $context === null ) {
  195. # Extensions should use `new RequestContext` instead of `new OutputPage` now.
  196. wfDeprecated( __METHOD__ );
  197. } else {
  198. $this->setContext( $context );
  199. }
  200. }
  201. /**
  202. * Redirect to $url rather than displaying the normal page
  203. *
  204. * @param $url String: URL
  205. * @param $responsecode String: HTTP status code
  206. */
  207. public function redirect( $url, $responsecode = '302' ) {
  208. # Strip newlines as a paranoia check for header injection in PHP<5.1.2
  209. $this->mRedirect = str_replace( "\n", '', $url );
  210. $this->mRedirectCode = $responsecode;
  211. }
  212. /**
  213. * Get the URL to redirect to, or an empty string if not redirect URL set
  214. *
  215. * @return String
  216. */
  217. public function getRedirect() {
  218. return $this->mRedirect;
  219. }
  220. /**
  221. * Set the HTTP status code to send with the output.
  222. *
  223. * @param $statusCode Integer
  224. */
  225. public function setStatusCode( $statusCode ) {
  226. $this->mStatusCode = $statusCode;
  227. }
  228. /**
  229. * Add a new <meta> tag
  230. * To add an http-equiv meta tag, precede the name with "http:"
  231. *
  232. * @param $name String tag name
  233. * @param $val String tag value
  234. */
  235. function addMeta( $name, $val ) {
  236. array_push( $this->mMetatags, array( $name, $val ) );
  237. }
  238. /**
  239. * Add a keyword or a list of keywords in the page header
  240. *
  241. * @param $text String or array of strings
  242. */
  243. function addKeyword( $text ) {
  244. if( is_array( $text ) ) {
  245. $this->mKeywords = array_merge( $this->mKeywords, $text );
  246. } else {
  247. array_push( $this->mKeywords, $text );
  248. }
  249. }
  250. /**
  251. * Add a new \<link\> tag to the page header
  252. *
  253. * @param $linkarr Array: associative array of attributes.
  254. */
  255. function addLink( $linkarr ) {
  256. array_push( $this->mLinktags, $linkarr );
  257. }
  258. /**
  259. * Add a new \<link\> with "rel" attribute set to "meta"
  260. *
  261. * @param $linkarr Array: associative array mapping attribute names to their
  262. * values, both keys and values will be escaped, and the
  263. * "rel" attribute will be automatically added
  264. */
  265. function addMetadataLink( $linkarr ) {
  266. $linkarr['rel'] = $this->getMetadataAttribute();
  267. $this->addLink( $linkarr );
  268. }
  269. /**
  270. * Get the value of the "rel" attribute for metadata links
  271. *
  272. * @return String
  273. */
  274. public function getMetadataAttribute() {
  275. # note: buggy CC software only reads first "meta" link
  276. static $haveMeta = false;
  277. if ( $haveMeta ) {
  278. return 'alternate meta';
  279. } else {
  280. $haveMeta = true;
  281. return 'meta';
  282. }
  283. }
  284. /**
  285. * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
  286. *
  287. * @param $script String: raw HTML
  288. */
  289. function addScript( $script ) {
  290. $this->mScripts .= $script . "\n";
  291. }
  292. /**
  293. * Register and add a stylesheet from an extension directory.
  294. *
  295. * @param $url String path to sheet. Provide either a full url (beginning
  296. * with 'http', etc) or a relative path from the document root
  297. * (beginning with '/'). Otherwise it behaves identically to
  298. * addStyle() and draws from the /skins folder.
  299. */
  300. public function addExtensionStyle( $url ) {
  301. array_push( $this->mExtStyles, $url );
  302. }
  303. /**
  304. * Get all styles added by extensions
  305. *
  306. * @return Array
  307. */
  308. function getExtStyle() {
  309. return $this->mExtStyles;
  310. }
  311. /**
  312. * Add a JavaScript file out of skins/common, or a given relative path.
  313. *
  314. * @param $file String: filename in skins/common or complete on-server path
  315. * (/foo/bar.js)
  316. * @param $version String: style version of the file. Defaults to $wgStyleVersion
  317. */
  318. public function addScriptFile( $file, $version = null ) {
  319. global $wgStylePath, $wgStyleVersion;
  320. // See if $file parameter is an absolute URL or begins with a slash
  321. if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
  322. $path = $file;
  323. } else {
  324. $path = "{$wgStylePath}/common/{$file}";
  325. }
  326. if ( is_null( $version ) )
  327. $version = $wgStyleVersion;
  328. $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
  329. }
  330. /**
  331. * Add a self-contained script tag with the given contents
  332. *
  333. * @param $script String: JavaScript text, no <script> tags
  334. */
  335. public function addInlineScript( $script ) {
  336. $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
  337. }
  338. /**
  339. * Get all registered JS and CSS tags for the header.
  340. *
  341. * @return String
  342. */
  343. function getScript() {
  344. return $this->mScripts . $this->getHeadItems();
  345. }
  346. /**
  347. * Filter an array of modules to remove insufficiently trustworthy members, and modules
  348. * which are no longer registered (eg a page is cached before an extension is disabled)
  349. * @param $modules Array
  350. * @param $position String if not null, only return modules with this position
  351. * @param $type string
  352. * @return Array
  353. */
  354. protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ){
  355. $resourceLoader = $this->getResourceLoader();
  356. $filteredModules = array();
  357. foreach( $modules as $val ){
  358. $module = $resourceLoader->getModule( $val );
  359. if( $module instanceof ResourceLoaderModule
  360. && $module->getOrigin() <= $this->getAllowedModules( $type )
  361. && ( is_null( $position ) || $module->getPosition() == $position ) )
  362. {
  363. $filteredModules[] = $val;
  364. }
  365. }
  366. return $filteredModules;
  367. }
  368. /**
  369. * Get the list of modules to include on this page
  370. *
  371. * @param $filter Bool whether to filter out insufficiently trustworthy modules
  372. * @param $position String if not null, only return modules with this position
  373. * @param $param string
  374. * @return Array of module names
  375. */
  376. public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
  377. $modules = array_values( array_unique( $this->$param ) );
  378. return $filter
  379. ? $this->filterModules( $modules, $position )
  380. : $modules;
  381. }
  382. /**
  383. * Add one or more modules recognized by the resource loader. Modules added
  384. * through this function will be loaded by the resource loader when the
  385. * page loads.
  386. *
  387. * @param $modules Mixed: module name (string) or array of module names
  388. */
  389. public function addModules( $modules ) {
  390. $this->mModules = array_merge( $this->mModules, (array)$modules );
  391. }
  392. /**
  393. * Get the list of module JS to include on this page
  394. *
  395. * @param $filter
  396. * @param $position
  397. *
  398. * @return array of module names
  399. */
  400. public function getModuleScripts( $filter = false, $position = null ) {
  401. return $this->getModules( $filter, $position, 'mModuleScripts' );
  402. }
  403. /**
  404. * Add only JS of one or more modules recognized by the resource loader. Module
  405. * scripts added through this function will be loaded by the resource loader when
  406. * the page loads.
  407. *
  408. * @param $modules Mixed: module name (string) or array of module names
  409. */
  410. public function addModuleScripts( $modules ) {
  411. $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
  412. }
  413. /**
  414. * Get the list of module CSS to include on this page
  415. *
  416. * @param $filter
  417. * @param $position
  418. *
  419. * @return Array of module names
  420. */
  421. public function getModuleStyles( $filter = false, $position = null ) {
  422. return $this->getModules( $filter, $position, 'mModuleStyles' );
  423. }
  424. /**
  425. * Add only CSS of one or more modules recognized by the resource loader. Module
  426. * styles added through this function will be loaded by the resource loader when
  427. * the page loads.
  428. *
  429. * @param $modules Mixed: module name (string) or array of module names
  430. */
  431. public function addModuleStyles( $modules ) {
  432. $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
  433. }
  434. /**
  435. * Get the list of module messages to include on this page
  436. *
  437. * @param $filter
  438. * @param $position
  439. *
  440. * @return Array of module names
  441. */
  442. public function getModuleMessages( $filter = false, $position = null ) {
  443. return $this->getModules( $filter, $position, 'mModuleMessages' );
  444. }
  445. /**
  446. * Add only messages of one or more modules recognized by the resource loader.
  447. * Module messages added through this function will be loaded by the resource
  448. * loader when the page loads.
  449. *
  450. * @param $modules Mixed: module name (string) or array of module names
  451. */
  452. public function addModuleMessages( $modules ) {
  453. $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
  454. }
  455. /**
  456. * Get an array of head items
  457. *
  458. * @return Array
  459. */
  460. function getHeadItemsArray() {
  461. return $this->mHeadItems;
  462. }
  463. /**
  464. * Get all header items in a string
  465. *
  466. * @return String
  467. */
  468. function getHeadItems() {
  469. $s = '';
  470. foreach ( $this->mHeadItems as $item ) {
  471. $s .= $item;
  472. }
  473. return $s;
  474. }
  475. /**
  476. * Add or replace an header item to the output
  477. *
  478. * @param $name String: item name
  479. * @param $value String: raw HTML
  480. */
  481. public function addHeadItem( $name, $value ) {
  482. $this->mHeadItems[$name] = $value;
  483. }
  484. /**
  485. * Check if the header item $name is already set
  486. *
  487. * @param $name String: item name
  488. * @return Boolean
  489. */
  490. public function hasHeadItem( $name ) {
  491. return isset( $this->mHeadItems[$name] );
  492. }
  493. /**
  494. * Set the value of the ETag HTTP header, only used if $wgUseETag is true
  495. *
  496. * @param $tag String: value of "ETag" header
  497. */
  498. function setETag( $tag ) {
  499. $this->mETag = $tag;
  500. }
  501. /**
  502. * Set whether the output should only contain the body of the article,
  503. * without any skin, sidebar, etc.
  504. * Used e.g. when calling with "action=render".
  505. *
  506. * @param $only Boolean: whether to output only the body of the article
  507. */
  508. public function setArticleBodyOnly( $only ) {
  509. $this->mArticleBodyOnly = $only;
  510. }
  511. /**
  512. * Return whether the output will contain only the body of the article
  513. *
  514. * @return Boolean
  515. */
  516. public function getArticleBodyOnly() {
  517. return $this->mArticleBodyOnly;
  518. }
  519. /**
  520. * checkLastModified tells the client to use the client-cached page if
  521. * possible. If sucessful, the OutputPage is disabled so that
  522. * any future call to OutputPage->output() have no effect.
  523. *
  524. * Side effect: sets mLastModified for Last-Modified header
  525. *
  526. * @param $timestamp string
  527. *
  528. * @return Boolean: true iff cache-ok headers was sent.
  529. */
  530. public function checkLastModified( $timestamp ) {
  531. global $wgCachePages, $wgCacheEpoch;
  532. if ( !$timestamp || $timestamp == '19700101000000' ) {
  533. wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
  534. return false;
  535. }
  536. if( !$wgCachePages ) {
  537. wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
  538. return false;
  539. }
  540. if( $this->getUser()->getOption( 'nocache' ) ) {
  541. wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
  542. return false;
  543. }
  544. $timestamp = wfTimestamp( TS_MW, $timestamp );
  545. $modifiedTimes = array(
  546. 'page' => $timestamp,
  547. 'user' => $this->getUser()->getTouched(),
  548. 'epoch' => $wgCacheEpoch
  549. );
  550. wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
  551. $maxModified = max( $modifiedTimes );
  552. $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
  553. if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  554. wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
  555. return false;
  556. }
  557. # Make debug info
  558. $info = '';
  559. foreach ( $modifiedTimes as $name => $value ) {
  560. if ( $info !== '' ) {
  561. $info .= ', ';
  562. }
  563. $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
  564. }
  565. # IE sends sizes after the date like this:
  566. # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
  567. # this breaks strtotime().
  568. $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
  569. wfSuppressWarnings(); // E_STRICT system time bitching
  570. $clientHeaderTime = strtotime( $clientHeader );
  571. wfRestoreWarnings();
  572. if ( !$clientHeaderTime ) {
  573. wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
  574. return false;
  575. }
  576. $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
  577. wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
  578. wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
  579. wfDebug( __METHOD__ . ": effective Last-Modified: " .
  580. wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
  581. if( $clientHeaderTime < $maxModified ) {
  582. wfDebug( __METHOD__ . ": STALE, $info\n", false );
  583. return false;
  584. }
  585. # Not modified
  586. # Give a 304 response code and disable body output
  587. wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
  588. ini_set( 'zlib.output_compression', 0 );
  589. $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
  590. $this->sendCacheControl();
  591. $this->disable();
  592. // Don't output a compressed blob when using ob_gzhandler;
  593. // it's technically against HTTP spec and seems to confuse
  594. // Firefox when the response gets split over two packets.
  595. wfClearOutputBuffers();
  596. return true;
  597. }
  598. /**
  599. * Override the last modified timestamp
  600. *
  601. * @param $timestamp String: new timestamp, in a format readable by
  602. * wfTimestamp()
  603. */
  604. public function setLastModified( $timestamp ) {
  605. $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
  606. }
  607. /**
  608. * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
  609. *
  610. * @param $policy String: the literal string to output as the contents of
  611. * the meta tag. Will be parsed according to the spec and output in
  612. * standardized form.
  613. * @return null
  614. */
  615. public function setRobotPolicy( $policy ) {
  616. $policy = Article::formatRobotPolicy( $policy );
  617. if( isset( $policy['index'] ) ) {
  618. $this->setIndexPolicy( $policy['index'] );
  619. }
  620. if( isset( $policy['follow'] ) ) {
  621. $this->setFollowPolicy( $policy['follow'] );
  622. }
  623. }
  624. /**
  625. * Set the index policy for the page, but leave the follow policy un-
  626. * touched.
  627. *
  628. * @param $policy string Either 'index' or 'noindex'.
  629. * @return null
  630. */
  631. public function setIndexPolicy( $policy ) {
  632. $policy = trim( $policy );
  633. if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
  634. $this->mIndexPolicy = $policy;
  635. }
  636. }
  637. /**
  638. * Set the follow policy for the page, but leave the index policy un-
  639. * touched.
  640. *
  641. * @param $policy String: either 'follow' or 'nofollow'.
  642. * @return null
  643. */
  644. public function setFollowPolicy( $policy ) {
  645. $policy = trim( $policy );
  646. if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
  647. $this->mFollowPolicy = $policy;
  648. }
  649. }
  650. /**
  651. * Set the new value of the "action text", this will be added to the
  652. * "HTML title", separated from it with " - ".
  653. *
  654. * @param $text String: new value of the "action text"
  655. */
  656. public function setPageTitleActionText( $text ) {
  657. $this->mPageTitleActionText = $text;
  658. }
  659. /**
  660. * Get the value of the "action text"
  661. *
  662. * @return String
  663. */
  664. public function getPageTitleActionText() {
  665. if ( isset( $this->mPageTitleActionText ) ) {
  666. return $this->mPageTitleActionText;
  667. }
  668. }
  669. /**
  670. * "HTML title" means the contents of <title>.
  671. * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
  672. *
  673. * @param $name string
  674. */
  675. public function setHTMLTitle( $name ) {
  676. if ( $name instanceof Message ) {
  677. $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
  678. } else {
  679. $this->mHTMLtitle = $name;
  680. }
  681. }
  682. /**
  683. * Return the "HTML title", i.e. the content of the <title> tag.
  684. *
  685. * @return String
  686. */
  687. public function getHTMLTitle() {
  688. return $this->mHTMLtitle;
  689. }
  690. /**
  691. * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
  692. *
  693. * param @t Title
  694. */
  695. public function setRedirectedFrom( $t ) {
  696. $this->mRedirectedFrom = $t;
  697. }
  698. /**
  699. * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
  700. * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
  701. * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
  702. * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
  703. *
  704. * @param $name string|Message
  705. */
  706. public function setPageTitle( $name ) {
  707. if ( $name instanceof Message ) {
  708. $name = $name->setContext( $this->getContext() )->text();
  709. }
  710. # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
  711. # but leave "<i>foobar</i>" alone
  712. $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
  713. $this->mPagetitle = $nameWithTags;
  714. # change "<i>foo&amp;bar</i>" to "foo&bar"
  715. $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) ) );
  716. }
  717. /**
  718. * Return the "page title", i.e. the content of the \<h1\> tag.
  719. *
  720. * @return String
  721. */
  722. public function getPageTitle() {
  723. return $this->mPagetitle;
  724. }
  725. /**
  726. * Set the Title object to use
  727. *
  728. * @param $t Title object
  729. */
  730. public function setTitle( Title $t ) {
  731. $this->getContext()->setTitle( $t );
  732. }
  733. /**
  734. * Replace the subtile with $str
  735. *
  736. * @param $str String|Message: new value of the subtitle
  737. */
  738. public function setSubtitle( $str ) {
  739. $this->clearSubtitle();
  740. $this->addSubtitle( $str );
  741. }
  742. /**
  743. * Add $str to the subtitle
  744. *
  745. * @deprecated in 1.19; use addSubtitle() instead
  746. * @param $str String|Message to add to the subtitle
  747. */
  748. public function appendSubtitle( $str ) {
  749. $this->addSubtitle( $str );
  750. }
  751. /**
  752. * Add $str to the subtitle
  753. *
  754. * @param $str String|Message to add to the subtitle
  755. */
  756. public function addSubtitle( $str ) {
  757. if ( $str instanceof Message ) {
  758. $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
  759. } else {
  760. $this->mSubtitle[] = $str;
  761. }
  762. }
  763. /**
  764. * Add a subtitle containing a backlink to a page
  765. *
  766. * @param $title Title to link to
  767. */
  768. public function addBacklinkSubtitle( Title $title ) {
  769. $query = array();
  770. if ( $title->isRedirect() ) {
  771. $query['redirect'] = 'no';
  772. }
  773. $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker::link( $title, null, array(), $query ) ) );
  774. }
  775. /**
  776. * Clear the subtitles
  777. */
  778. public function clearSubtitle() {
  779. $this->mSubtitle = array();
  780. }
  781. /**
  782. * Get the subtitle
  783. *
  784. * @return String
  785. */
  786. public function getSubtitle() {
  787. return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
  788. }
  789. /**
  790. * Set the page as printable, i.e. it'll be displayed with with all
  791. * print styles included
  792. */
  793. public function setPrintable() {
  794. $this->mPrintable = true;
  795. }
  796. /**
  797. * Return whether the page is "printable"
  798. *
  799. * @return Boolean
  800. */
  801. public function isPrintable() {
  802. return $this->mPrintable;
  803. }
  804. /**
  805. * Disable output completely, i.e. calling output() will have no effect
  806. */
  807. public function disable() {
  808. $this->mDoNothing = true;
  809. }
  810. /**
  811. * Return whether the output will be completely disabled
  812. *
  813. * @return Boolean
  814. */
  815. public function isDisabled() {
  816. return $this->mDoNothing;
  817. }
  818. /**
  819. * Show an "add new section" link?
  820. *
  821. * @return Boolean
  822. */
  823. public function showNewSectionLink() {
  824. return $this->mNewSectionLink;
  825. }
  826. /**
  827. * Forcibly hide the new section link?
  828. *
  829. * @return Boolean
  830. */
  831. public function forceHideNewSectionLink() {
  832. return $this->mHideNewSectionLink;
  833. }
  834. /**
  835. * Add or remove feed links in the page header
  836. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  837. * for the new version
  838. * @see addFeedLink()
  839. *
  840. * @param $show Boolean: true: add default feeds, false: remove all feeds
  841. */
  842. public function setSyndicated( $show = true ) {
  843. if ( $show ) {
  844. $this->setFeedAppendQuery( false );
  845. } else {
  846. $this->mFeedLinks = array();
  847. }
  848. }
  849. /**
  850. * Add default feeds to the page header
  851. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  852. * for the new version
  853. * @see addFeedLink()
  854. *
  855. * @param $val String: query to append to feed links or false to output
  856. * default links
  857. */
  858. public function setFeedAppendQuery( $val ) {
  859. global $wgAdvertisedFeedTypes;
  860. $this->mFeedLinks = array();
  861. foreach ( $wgAdvertisedFeedTypes as $type ) {
  862. $query = "feed=$type";
  863. if ( is_string( $val ) ) {
  864. $query .= '&' . $val;
  865. }
  866. $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
  867. }
  868. }
  869. /**
  870. * Add a feed link to the page header
  871. *
  872. * @param $format String: feed type, should be a key of $wgFeedClasses
  873. * @param $href String: URL
  874. */
  875. public function addFeedLink( $format, $href ) {
  876. global $wgAdvertisedFeedTypes;
  877. if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
  878. $this->mFeedLinks[$format] = $href;
  879. }
  880. }
  881. /**
  882. * Should we output feed links for this page?
  883. * @return Boolean
  884. */
  885. public function isSyndicated() {
  886. return count( $this->mFeedLinks ) > 0;
  887. }
  888. /**
  889. * Return URLs for each supported syndication format for this page.
  890. * @return array associating format keys with URLs
  891. */
  892. public function getSyndicationLinks() {
  893. return $this->mFeedLinks;
  894. }
  895. /**
  896. * Will currently always return null
  897. *
  898. * @return null
  899. */
  900. public function getFeedAppendQuery() {
  901. return $this->mFeedLinksAppendQuery;
  902. }
  903. /**
  904. * Set whether the displayed content is related to the source of the
  905. * corresponding article on the wiki
  906. * Setting true will cause the change "article related" toggle to true
  907. *
  908. * @param $v Boolean
  909. */
  910. public function setArticleFlag( $v ) {
  911. $this->mIsarticle = $v;
  912. if ( $v ) {
  913. $this->mIsArticleRelated = $v;
  914. }
  915. }
  916. /**
  917. * Return whether the content displayed page is related to the source of
  918. * the corresponding article on the wiki
  919. *
  920. * @return Boolean
  921. */
  922. public function isArticle() {
  923. return $this->mIsarticle;
  924. }
  925. /**
  926. * Set whether this page is related an article on the wiki
  927. * Setting false will cause the change of "article flag" toggle to false
  928. *
  929. * @param $v Boolean
  930. */
  931. public function setArticleRelated( $v ) {
  932. $this->mIsArticleRelated = $v;
  933. if ( !$v ) {
  934. $this->mIsarticle = false;
  935. }
  936. }
  937. /**
  938. * Return whether this page is related an article on the wiki
  939. *
  940. * @return Boolean
  941. */
  942. public function isArticleRelated() {
  943. return $this->mIsArticleRelated;
  944. }
  945. /**
  946. * Add new language links
  947. *
  948. * @param $newLinkArray Associative array mapping language code to the page
  949. * name
  950. */
  951. public function addLanguageLinks( $newLinkArray ) {
  952. $this->mLanguageLinks += $newLinkArray;
  953. }
  954. /**
  955. * Reset the language links and add new language links
  956. *
  957. * @param $newLinkArray Associative array mapping language code to the page
  958. * name
  959. */
  960. public function setLanguageLinks( $newLinkArray ) {
  961. $this->mLanguageLinks = $newLinkArray;
  962. }
  963. /**
  964. * Get the list of language links
  965. *
  966. * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
  967. */
  968. public function getLanguageLinks() {
  969. return $this->mLanguageLinks;
  970. }
  971. /**
  972. * Add an array of categories, with names in the keys
  973. *
  974. * @param $categories Array mapping category name => sort key
  975. */
  976. public function addCategoryLinks( $categories ) {
  977. global $wgContLang;
  978. if ( !is_array( $categories ) || count( $categories ) == 0 ) {
  979. return;
  980. }
  981. # Add the links to a LinkBatch
  982. $arr = array( NS_CATEGORY => $categories );
  983. $lb = new LinkBatch;
  984. $lb->setArray( $arr );
  985. # Fetch existence plus the hiddencat property
  986. $dbr = wfGetDB( DB_SLAVE );
  987. $res = $dbr->select( array( 'page', 'page_props' ),
  988. array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
  989. $lb->constructSet( 'page', $dbr ),
  990. __METHOD__,
  991. array(),
  992. array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
  993. );
  994. # Add the results to the link cache
  995. $lb->addResultToCache( LinkCache::singleton(), $res );
  996. # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
  997. $categories = array_combine(
  998. array_keys( $categories ),
  999. array_fill( 0, count( $categories ), 'normal' )
  1000. );
  1001. # Mark hidden categories
  1002. foreach ( $res as $row ) {
  1003. if ( isset( $row->pp_value ) ) {
  1004. $categories[$row->page_title] = 'hidden';
  1005. }
  1006. }
  1007. # Add the remaining categories to the skin
  1008. if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
  1009. foreach ( $categories as $category => $type ) {
  1010. $origcategory = $category;
  1011. $title = Title::makeTitleSafe( NS_CATEGORY, $category );
  1012. $wgContLang->findVariantLink( $category, $title, true );
  1013. if ( $category != $origcategory ) {
  1014. if ( array_key_exists( $category, $categories ) ) {
  1015. continue;
  1016. }
  1017. }
  1018. $text = $wgContLang->convertHtml( $title->getText() );
  1019. $this->mCategories[] = $title->getText();
  1020. $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
  1021. }
  1022. }
  1023. }
  1024. /**
  1025. * Reset the category links (but not the category list) and add $categories
  1026. *
  1027. * @param $categories Array mapping category name => sort key
  1028. */
  1029. public function setCategoryLinks( $categories ) {
  1030. $this->mCategoryLinks = array();
  1031. $this->addCategoryLinks( $categories );
  1032. }
  1033. /**
  1034. * Get the list of category links, in a 2-D array with the following format:
  1035. * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
  1036. * hidden categories) and $link a HTML fragment with a link to the category
  1037. * page
  1038. *
  1039. * @return Array
  1040. */
  1041. public function getCategoryLinks() {
  1042. return $this->mCategoryLinks;
  1043. }
  1044. /**
  1045. * Get the list of category names this page belongs to
  1046. *
  1047. * @return Array of strings
  1048. */
  1049. public function getCategories() {
  1050. return $this->mCategories;
  1051. }
  1052. /**
  1053. * Do not allow scripts which can be modified by wiki users to load on this page;
  1054. * only allow scripts bundled with, or generated by, the software.
  1055. */
  1056. public function disallowUserJs() {
  1057. $this->reduceAllowedModules(
  1058. ResourceLoaderModule::TYPE_SCRIPTS,
  1059. ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
  1060. );
  1061. }
  1062. /**
  1063. * Return whether user JavaScript is allowed for this page
  1064. * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
  1065. * trustworthiness is identified and enforced automagically.
  1066. * Will be removed in 1.20.
  1067. * @return Boolean
  1068. */
  1069. public function isUserJsAllowed() {
  1070. wfDeprecated( __METHOD__, '1.18' );
  1071. return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
  1072. }
  1073. /**
  1074. * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
  1075. * @see ResourceLoaderModule::$origin
  1076. * @param $type String ResourceLoaderModule TYPE_ constant
  1077. * @return Int ResourceLoaderModule ORIGIN_ class constant
  1078. */
  1079. public function getAllowedModules( $type ){
  1080. if( $type == ResourceLoaderModule::TYPE_COMBINED ){
  1081. return min( array_values( $this->mAllowedModules ) );
  1082. } else {
  1083. return isset( $this->mAllowedModules[$type] )
  1084. ? $this->mAllowedModules[$type]
  1085. : ResourceLoaderModule::ORIGIN_ALL;
  1086. }
  1087. }
  1088. /**
  1089. * Set the highest level of CSS/JS untrustworthiness allowed
  1090. * @param $type String ResourceLoaderModule TYPE_ constant
  1091. * @param $level Int ResourceLoaderModule class constant
  1092. */
  1093. public function setAllowedModules( $type, $level ){
  1094. $this->mAllowedModules[$type] = $level;
  1095. }
  1096. /**
  1097. * As for setAllowedModules(), but don't inadvertantly make the page more accessible
  1098. * @param $type String
  1099. * @param $level Int ResourceLoaderModule class constant
  1100. */
  1101. public function reduceAllowedModules( $type, $level ){
  1102. $this->mAllowedModules[$type] = min( $this->getAllowedModules($type), $level );
  1103. }
  1104. /**
  1105. * Prepend $text to the body HTML
  1106. *
  1107. * @param $text String: HTML
  1108. */
  1109. public function prependHTML( $text ) {
  1110. $this->mBodytext = $text . $this->mBodytext;
  1111. }
  1112. /**
  1113. * Append $text to the body HTML
  1114. *
  1115. * @param $text String: HTML
  1116. */
  1117. public function addHTML( $text ) {
  1118. $this->mBodytext .= $text;
  1119. }
  1120. /**
  1121. * Shortcut for adding an Html::element via addHTML.
  1122. *
  1123. * @since 1.19
  1124. *
  1125. * @param $element string
  1126. * @param $attribs array
  1127. * @param $contents string
  1128. */
  1129. public function addElement( $element, $attribs = array(), $contents = '' ) {
  1130. $this->addHTML( Html::element( $element, $attribs, $contents ) );
  1131. }
  1132. /**
  1133. * Clear the body HTML
  1134. */
  1135. public function clearHTML() {
  1136. $this->mBodytext = '';
  1137. }
  1138. /**
  1139. * Get the body HTML
  1140. *
  1141. * @return String: HTML
  1142. */
  1143. public function getHTML() {
  1144. return $this->mBodytext;
  1145. }
  1146. /**
  1147. * Add $text to the debug output
  1148. *
  1149. * @param $text String: debug text
  1150. */
  1151. public function debug( $text ) {
  1152. $this->mDebugtext .= $text;
  1153. }
  1154. /**
  1155. * Get/set the ParserOptions object to use for wikitext parsing
  1156. *
  1157. * @param $options either the ParserOption to use or null to only get the
  1158. * current ParserOption object
  1159. * @return ParserOptions object
  1160. */
  1161. public function parserOptions( $options = null ) {
  1162. if ( !$this->mParserOptions ) {
  1163. $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
  1164. $this->mParserOptions->setEditSection( false );
  1165. }
  1166. return wfSetVar( $this->mParserOptions, $options );
  1167. }
  1168. /**
  1169. * Set the revision ID which will be seen by the wiki text parser
  1170. * for things such as embedded {{REVISIONID}} variable use.
  1171. *
  1172. * @param $revid Mixed: an positive integer, or null
  1173. * @return Mixed: previous value
  1174. */
  1175. public function setRevisionId( $revid ) {
  1176. $val = is_null( $revid ) ? null : intval( $revid );
  1177. return wfSetVar( $this->mRevisionId, $val );
  1178. }
  1179. /**
  1180. * Get the displayed revision ID
  1181. *
  1182. * @return Integer
  1183. */
  1184. public function getRevisionId() {
  1185. return $this->mRevisionId;
  1186. }
  1187. /**
  1188. * Set the timestamp of the revision which will be displayed. This is used
  1189. * to avoid a extra DB call in Skin::lastModified().
  1190. *
  1191. * @param $revid Mixed: string, or null
  1192. * @return Mixed: previous value
  1193. */
  1194. public function setRevisionTimestamp( $timestmap ) {
  1195. return wfSetVar( $this->mRevisionTimestamp, $timestmap );
  1196. }
  1197. /**
  1198. * Get the timestamp of displayed revision.
  1199. * This will be null if not filled by setRevisionTimestamp().
  1200. *
  1201. * @return String or null
  1202. */
  1203. public function getRevisionTimestamp() {
  1204. return $this->mRevisionTimestamp;
  1205. }
  1206. /**
  1207. * Set the displayed file version
  1208. *
  1209. * @param $file File|false
  1210. * @return Mixed: previous value
  1211. */
  1212. public function setFileVersion( $file ) {
  1213. $val = null;
  1214. if ( $file instanceof File && $file->exists() ) {
  1215. $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
  1216. }
  1217. return wfSetVar( $this->mFileVersion, $val, true );
  1218. }
  1219. /**
  1220. * Get the displayed file version
  1221. *
  1222. * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
  1223. */
  1224. public function getFileVersion() {
  1225. return $this->mFileVersion;
  1226. }
  1227. /**
  1228. * Get the templates used on this page
  1229. *
  1230. * @return Array (namespace => dbKey => revId)
  1231. * @since 1.18
  1232. */
  1233. public function getTemplateIds() {
  1234. return $this->mTemplateIds;
  1235. }
  1236. /**
  1237. * Get the files used on this page
  1238. *
  1239. * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
  1240. * @since 1.18
  1241. */
  1242. public function getFileSearchOptions() {
  1243. return $this->mImageTimeKeys;
  1244. }
  1245. /**
  1246. * Convert wikitext to HTML and add it to the buffer
  1247. * Default assumes that the current page title will be used.
  1248. *
  1249. * @param $text String
  1250. * @param $linestart Boolean: is this the start of a line?
  1251. * @param $interface Boolean: is this text in the user interface language?
  1252. */
  1253. public function addWikiText( $text, $linestart = true, $interface = true ) {
  1254. $title = $this->getTitle(); // Work arround E_STRICT
  1255. $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
  1256. }
  1257. /**
  1258. * Add wikitext with a custom Title object
  1259. *
  1260. * @param $text String: wikitext
  1261. * @param $title Title object
  1262. * @param $linestart Boolean: is this the start of a line?
  1263. */
  1264. public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
  1265. $this->addWikiTextTitle( $text, $title, $linestart );
  1266. }
  1267. /**
  1268. * Add wikitext with a custom Title object and tidy enabled.
  1269. *
  1270. * @param $text String: wikitext
  1271. * @param $title Title object
  1272. * @param $linestart Boolean: is this the start of a line?
  1273. */
  1274. function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
  1275. $this->addWikiTextTitle( $text, $title, $linestart, true );
  1276. }
  1277. /**
  1278. * Add wikitext with tidy enabled
  1279. *
  1280. * @param $text String: wikitext
  1281. * @param $linestart Boolean: is this the start of a line?
  1282. */
  1283. public function addWikiTextTidy( $text, $linestart = true ) {
  1284. $title = $this->getTitle();
  1285. $this->addWikiTextTitleTidy( $text, $title, $linestart );
  1286. }
  1287. /**
  1288. * Add wikitext with a custom Title object
  1289. *
  1290. * @param $text String: wikitext
  1291. * @param $title Title object
  1292. * @param $linestart Boolean: is this the start of a line?
  1293. * @param $tidy Boolean: whether to use tidy
  1294. * @param $interface Boolean: whether it is an interface message
  1295. * (for example disables conversion)
  1296. */
  1297. public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
  1298. global $wgParser;
  1299. wfProfileIn( __METHOD__ );
  1300. $popts = $this->parserOptions();
  1301. $oldTidy = $popts->setTidy( $tidy );
  1302. $popts->setInterfaceMessage( (bool) $interface );
  1303. $parserOutput = $wgParser->parse(
  1304. $text, $title, $popts,
  1305. $linestart, true, $this->mRevisionId
  1306. );
  1307. $popts->setTidy( $oldTidy );
  1308. $this->addParserOutput( $parserOutput );
  1309. wfProfileOut( __METHOD__ );
  1310. }
  1311. /**
  1312. * Add a ParserOutput object, but without Html
  1313. *
  1314. * @param $parserOutput ParserOutput object
  1315. */
  1316. public function addParserOutputNoText( &$parserOutput ) {
  1317. $this->mLanguageLinks += $parserOutput->getLanguageLinks();
  1318. $this->addCategoryLinks( $parserOutput->getCategories() );
  1319. $this->mNewSectionLink = $parserOutput->getNewSection();
  1320. $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
  1321. $this->mParseWarnings = $parserOutput->getWarnings();
  1322. if ( !$parserOutput->isCacheable() ) {
  1323. $this->enableClientCache( false );
  1324. }
  1325. $this->mNoGallery = $parserOutput->getNoGallery();
  1326. $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
  1327. $this->addModules( $parserOutput->getModules() );
  1328. $this->addModuleScripts( $parserOutput->getModuleScripts() );
  1329. $this->addModuleStyles( $parserOutput->getModuleStyles() );
  1330. $this->addModuleMessages( $parserOutput->getModuleMessages() );
  1331. // Template versioning...
  1332. foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
  1333. if ( isset( $this->mTemplateIds[$ns] ) ) {
  1334. $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
  1335. } else {
  1336. $this->mTemplateIds[$ns] = $dbks;
  1337. }
  1338. }
  1339. // File versioning...
  1340. foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
  1341. $this->mImageTimeKeys[$dbk] = $data;
  1342. }
  1343. // Hooks registered in the object
  1344. global $wgParserOutputHooks;
  1345. foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
  1346. list( $hookName, $data ) = $hookInfo;
  1347. if ( isset( $wgParserOutputHooks[$hookName] ) ) {
  1348. call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
  1349. }
  1350. }
  1351. wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
  1352. }
  1353. /**
  1354. * Add a ParserOutput object
  1355. *
  1356. * @param $parserOutput ParserOutput
  1357. */
  1358. function addParserOutput( &$parserOutput ) {
  1359. $this->addParserOutputNoText( $parserOutput );
  1360. $text = $parserOutput->getText();
  1361. wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
  1362. $this->addHTML( $text );
  1363. }
  1364. /**
  1365. * Add the output of a QuickTemplate to the output buffer
  1366. *
  1367. * @param $template QuickTemplate
  1368. */
  1369. public function addTemplate( &$template ) {
  1370. ob_start();
  1371. $template->execute();
  1372. $this->addHTML( ob_get_contents() );
  1373. ob_end_clean();
  1374. }
  1375. /**
  1376. * Parse wikitext and return the HTML.
  1377. *
  1378. * @param $text String
  1379. * @param $linestart Boolean: is this the start of a line?
  1380. * @param $interface Boolean: use interface language ($wgLang instead of
  1381. * $wgContLang) while parsing language sensitive magic
  1382. * words like GRAMMAR and PLURAL. This also disables
  1383. * LanguageConverter.
  1384. * @param $language Language object: target language object, will override
  1385. * $interface
  1386. * @return String: HTML
  1387. */
  1388. public function parse( $text, $linestart = true, $interface = false, $language = null ) {
  1389. global $wgParser;
  1390. if( is_null( $this->getTitle() ) ) {
  1391. throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
  1392. }
  1393. $popts = $this->parserOptions();
  1394. if ( $interface ) {
  1395. $popts->setInterfaceMessage( true );
  1396. }
  1397. if ( $language !== null ) {
  1398. $oldLang = $popts->setTargetLanguage( $language );
  1399. }
  1400. $parserOutput = $wgParser->parse(
  1401. $text, $this->getTitle(), $popts,
  1402. $linestart, true, $this->mRevisionId
  1403. );
  1404. if ( $interface ) {
  1405. $popts->setInterfaceMessage( false );
  1406. }
  1407. if ( $language !== null ) {
  1408. $popts->setTargetLanguage( $oldLang );
  1409. }
  1410. return $parserOutput->getText();
  1411. }
  1412. /**
  1413. * Parse wikitext, strip paragraphs, and return the HTML.
  1414. *
  1415. * @param $text String
  1416. * @param $linestart Boolean: is this the start of a line?
  1417. * @param $interface Boolean: use interface language ($wgLang instead of
  1418. * $wgContLang) while parsing language sensitive magic
  1419. * words like GRAMMAR and PLURAL
  1420. * @return String: HTML
  1421. */
  1422. public function parseInline( $text, $linestart = true, $interface = false ) {
  1423. $parsed = $this->parse( $text, $linestart, $interface );
  1424. $m = array();
  1425. if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
  1426. $parsed = $m[1];
  1427. }
  1428. return $parsed;
  1429. }
  1430. /**
  1431. * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
  1432. *
  1433. * @param $maxage Integer: maximum cache time on the Squid, in seconds.
  1434. */
  1435. public function setSquidMaxage( $maxage ) {
  1436. $this->mSquidMaxage = $maxage;
  1437. }
  1438. /**
  1439. * Use enableClientCache(false) to force it to send nocache headers
  1440. *
  1441. * @param $state bool
  1442. *
  1443. * @return bool
  1444. */
  1445. public function enableClientCache( $state ) {
  1446. return wfSetVar( $this->mEnableClientCache, $state );
  1447. }
  1448. /**
  1449. * Get the list of cookies that will influence on the cache
  1450. *
  1451. * @return Array
  1452. */
  1453. function getCacheVaryCookies() {
  1454. global $wgCookiePrefix, $wgCacheVaryCookies;
  1455. static $cookies;
  1456. if ( $cookies === null ) {
  1457. $cookies = array_merge(
  1458. array(
  1459. "{$wgCookiePrefix}Token",
  1460. "{$wgCookiePrefix}LoggedOut",
  1461. session_name()
  1462. ),
  1463. $wgCacheVaryCookies
  1464. );
  1465. wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
  1466. }
  1467. return $cookies;
  1468. }
  1469. /**
  1470. * Return whether this page is not cacheable because "useskin" or "uselang"
  1471. * URL parameters were passed.
  1472. *
  1473. * @return Boolean
  1474. */
  1475. function uncacheableBecauseRequestVars() {
  1476. $request = $this->getRequest();
  1477. return $request->getText( 'useskin', false ) === false
  1478. && $request->getText( 'uselang', false ) === false;
  1479. }
  1480. /**
  1481. * Check if the request has a cache-varying cookie header
  1482. * If it does, it's very important that we don't allow public caching
  1483. *
  1484. * @return Boolean
  1485. */
  1486. function haveCacheVaryCookies() {
  1487. $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
  1488. if ( $cookieHeader === false ) {
  1489. return false;
  1490. }
  1491. $cvCookies = $this->getCacheVaryCookies();
  1492. foreach ( $cvCookies as $cookieName ) {
  1493. # Check for a simple string match, like the way squid does it
  1494. if ( strpos( $cookieHeader, $cookieName ) !== false ) {
  1495. wfDebug( __METHOD__ . ": found $cookieName\n" );
  1496. return true;
  1497. }
  1498. }
  1499. wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
  1500. return false;
  1501. }
  1502. /**
  1503. * Add an HTTP header that will influence on the cache
  1504. *
  1505. * @param $header String: header name
  1506. * @param $option Array|null
  1507. * @todo FIXME: Document the $option parameter; it appears to be for
  1508. * X-Vary-Options but what format is acceptable?
  1509. */
  1510. public function addVaryHeader( $header, $option = null ) {
  1511. if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
  1512. $this->mVaryHeader[$header] = (array)$option;
  1513. } elseif( is_array( $option ) ) {
  1514. if( is_array( $this->mVaryHeader[$header] ) ) {
  1515. $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
  1516. } else {
  1517. $this->mVaryHeader[$header] = $option;
  1518. }
  1519. }
  1520. $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
  1521. }
  1522. /**
  1523. * Get a complete X-Vary-Options header
  1524. *
  1525. * @return String
  1526. */
  1527. public function getXVO() {
  1528. $cvCookies = $this->getCacheVaryCookies();
  1529. $cookiesOption = array();
  1530. foreach ( $cvCookies as $cookieName ) {
  1531. $cookiesOption[] = 'string-contains=' . $cookieName;
  1532. }
  1533. $this->addVaryHeader( 'Cookie', $cookiesOption );
  1534. $headers = array();
  1535. foreach( $this->mVaryHeader as $header => $option ) {
  1536. $newheader = $header;
  1537. if( is_array( $option ) ) {
  1538. $newheader .= ';' . implode( ';', $option );
  1539. }
  1540. $headers[] = $newheader;
  1541. }
  1542. $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
  1543. return $xvo;
  1544. }
  1545. /**
  1546. * bug 21672: Add Accept-Language to Vary and XVO headers
  1547. * if there's no 'variant' parameter existed in GET.
  1548. *
  1549. * For example:
  1550. * /w/index.php?title=Main_page should always be served; but
  1551. * /w/index.php?title=Main_page&variant=zh-cn should never be served.
  1552. */
  1553. function addAcceptLanguage() {
  1554. $lang = $this->getTitle()->getPageLanguage();
  1555. if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
  1556. $variants = $lang->getVariants();
  1557. $aloption = array();
  1558. foreach ( $variants as $variant ) {
  1559. if( $variant === $lang->getCode() ) {
  1560. continue;
  1561. } else {
  1562. $aloption[] = 'string-contains=' . $variant;
  1563. // IE and some other browsers use another form of language code
  1564. // in their Accept-Language header, like "zh-CN" or "zh-TW".
  1565. // We should handle these too.
  1566. $ievariant = explode( '-', $variant );
  1567. if ( count( $ievariant ) == 2 ) {
  1568. $ievariant[1] = strtoupper( $ievariant[1] );
  1569. $ievariant = implode( '-', $ievariant );
  1570. $aloption[] = 'string-contains=' . $ievariant;
  1571. }
  1572. }
  1573. }
  1574. $this->addVaryHeader( 'Accept-Language', $aloption );
  1575. }
  1576. }
  1577. /**
  1578. * Set a flag which will cause an X-Frame-Options header appropriate for
  1579. * edit pages to be sent. The header value is controlled by
  1580. * $wgEditPageFrameOptions.
  1581. *
  1582. * This is the default for special pages. If you display a CSRF-protected
  1583. * form on an ordinary view page, then you need to call this function.
  1584. *
  1585. * @param $enable bool
  1586. */
  1587. public function preventClickjacking( $enable = true ) {
  1588. $this->mPreventClickjacking = $enable;
  1589. }
  1590. /**
  1591. * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
  1592. * This can be called from pages which do not contain any CSRF-protected
  1593. * HTML form.
  1594. */
  1595. public function allowClickjacking() {
  1596. $this->mPreventClickjacking = false;
  1597. }
  1598. /**
  1599. * Get the X-Frame-Options header value (without the name part), or false
  1600. * if there isn't one. This is used by Skin to determine whether to enable
  1601. * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
  1602. *
  1603. * @return string
  1604. */
  1605. public function getFrameOptions() {
  1606. global $wgBreakFrames, $wgEditPageFrameOptions;
  1607. if

Large files files are truncated, but you can click here to view the full file