OutputPage.php 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999
  1. <?php
  2. /**
  3. * Preparation for the final page rendering.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\Linker\LinkTarget;
  23. use MediaWiki\Logger\LoggerFactory;
  24. use MediaWiki\MediaWikiServices;
  25. use MediaWiki\Session\SessionManager;
  26. use Wikimedia\Rdbms\IResultWrapper;
  27. use Wikimedia\RelPath;
  28. use Wikimedia\WrappedString;
  29. use Wikimedia\WrappedStringList;
  30. /**
  31. * This class should be covered by a general architecture document which does
  32. * not exist as of January 2011. This is one of the Core classes and should
  33. * be read at least once by any new developers.
  34. *
  35. * This class is used to prepare the final rendering. A skin is then
  36. * applied to the output parameters (links, javascript, html, categories ...).
  37. *
  38. * @todo FIXME: Another class handles sending the whole page to the client.
  39. *
  40. * Some comments comes from a pairing session between Zak Greant and Antoine Musso
  41. * in November 2010.
  42. *
  43. * @todo document
  44. */
  45. class OutputPage extends ContextSource {
  46. /** @var array Should be private. Used with addMeta() which adds "<meta>" */
  47. protected $mMetatags = [];
  48. /** @var array */
  49. protected $mLinktags = [];
  50. /** @var bool */
  51. protected $mCanonicalUrl = false;
  52. /**
  53. * @var string The contents of <h1> */
  54. private $mPageTitle = '';
  55. /**
  56. * @var string The displayed title of the page. Different from page title
  57. * if overridden by display title magic word or hooks. Can contain safe
  58. * HTML. Different from page title which may contain messages such as
  59. * "Editing X" which is displayed in h1. This can be used for other places
  60. * where the page name is referred on the page.
  61. */
  62. private $displayTitle;
  63. /**
  64. * @var string Contains all of the "<body>" content. Should be private we
  65. * got set/get accessors and the append() method.
  66. */
  67. public $mBodytext = '';
  68. /** @var string Stores contents of "<title>" tag */
  69. private $mHTMLtitle = '';
  70. /**
  71. * @var bool Is the displayed content related to the source of the
  72. * corresponding wiki article.
  73. */
  74. private $mIsArticle = false;
  75. /** @var bool Stores "article flag" toggle. */
  76. private $mIsArticleRelated = true;
  77. /**
  78. * @var bool We have to set isPrintable(). Some pages should
  79. * never be printed (ex: redirections).
  80. */
  81. private $mPrintable = false;
  82. /**
  83. * @var array Contains the page subtitle. Special pages usually have some
  84. * links here. Don't confuse with site subtitle added by skins.
  85. */
  86. private $mSubtitle = [];
  87. /** @var string */
  88. public $mRedirect = '';
  89. /** @var int */
  90. protected $mStatusCode;
  91. /**
  92. * @var string Used for sending cache control.
  93. * The whole caching system should probably be moved into its own class.
  94. */
  95. protected $mLastModified = '';
  96. /** @var array */
  97. protected $mCategoryLinks = [];
  98. /** @var array */
  99. protected $mCategories = [
  100. 'hidden' => [],
  101. 'normal' => [],
  102. ];
  103. /** @var array */
  104. protected $mIndicators = [];
  105. /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
  106. private $mLanguageLinks = [];
  107. /**
  108. * Used for JavaScript (predates ResourceLoader)
  109. * @todo We should split JS / CSS.
  110. * mScripts content is inserted as is in "<head>" by Skin. This might
  111. * contain either a link to a stylesheet or inline CSS.
  112. */
  113. private $mScripts = '';
  114. /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
  115. protected $mInlineStyles = '';
  116. /**
  117. * @var string Used by skin template.
  118. * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
  119. */
  120. public $mPageLinkTitle = '';
  121. /** @var array Array of elements in "<head>". Parser might add its own headers! */
  122. protected $mHeadItems = [];
  123. /** @var array Additional <body> classes; there are also <body> classes from other sources */
  124. protected $mAdditionalBodyClasses = [];
  125. /** @var array */
  126. protected $mModules = [];
  127. /** @var array */
  128. protected $mModuleScripts = [];
  129. /** @var array */
  130. protected $mModuleStyles = [];
  131. /** @var ResourceLoader */
  132. protected $mResourceLoader;
  133. /** @var ResourceLoaderClientHtml */
  134. private $rlClient;
  135. /** @var ResourceLoaderContext */
  136. private $rlClientContext;
  137. /** @var array */
  138. private $rlExemptStyleModules;
  139. /** @var array */
  140. protected $mJsConfigVars = [];
  141. /** @var array */
  142. protected $mTemplateIds = [];
  143. /** @var array */
  144. protected $mImageTimeKeys = [];
  145. /** @var string */
  146. public $mRedirectCode = '';
  147. protected $mFeedLinksAppendQuery = null;
  148. /** @var array
  149. * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
  150. * @see ResourceLoaderModule::$origin
  151. * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
  152. */
  153. protected $mAllowedModules = [
  154. ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
  155. ];
  156. /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
  157. protected $mDoNothing = false;
  158. // Parser related.
  159. /** @var int */
  160. protected $mContainsNewMagic = 0;
  161. /**
  162. * lazy initialised, use parserOptions()
  163. * @var ParserOptions
  164. */
  165. protected $mParserOptions = null;
  166. /**
  167. * Handles the Atom / RSS links.
  168. * We probably only support Atom in 2011.
  169. * @see $wgAdvertisedFeedTypes
  170. */
  171. private $mFeedLinks = [];
  172. // Gwicke work on squid caching? Roughly from 2003.
  173. protected $mEnableClientCache = true;
  174. /** @var bool Flag if output should only contain the body of the article. */
  175. private $mArticleBodyOnly = false;
  176. /** @var bool */
  177. protected $mNewSectionLink = false;
  178. /** @var bool */
  179. protected $mHideNewSectionLink = false;
  180. /**
  181. * @var bool Comes from the parser. This was probably made to load CSS/JS
  182. * only if we had "<gallery>". Used directly in CategoryPage.php.
  183. * Looks like ResourceLoader can replace this.
  184. */
  185. public $mNoGallery = false;
  186. /** @var int Cache stuff. Looks like mEnableClientCache */
  187. protected $mCdnMaxage = 0;
  188. /** @var int Upper limit on mCdnMaxage */
  189. protected $mCdnMaxageLimit = INF;
  190. /**
  191. * @var bool Controls if anti-clickjacking / frame-breaking headers will
  192. * be sent. This should be done for pages where edit actions are possible.
  193. * Setters: $this->preventClickjacking() and $this->allowClickjacking().
  194. */
  195. protected $mPreventClickjacking = true;
  196. /** @var int To include the variable {{REVISIONID}} */
  197. private $mRevisionId = null;
  198. /** @var string */
  199. private $mRevisionTimestamp = null;
  200. /** @var array */
  201. protected $mFileVersion = null;
  202. /**
  203. * @var array An array of stylesheet filenames (relative from skins path),
  204. * with options for CSS media, IE conditions, and RTL/LTR direction.
  205. * For internal use; add settings in the skin via $this->addStyle()
  206. *
  207. * Style again! This seems like a code duplication since we already have
  208. * mStyles. This is what makes Open Source amazing.
  209. */
  210. protected $styles = [];
  211. private $mIndexPolicy = 'index';
  212. private $mFollowPolicy = 'follow';
  213. /**
  214. * @var array Headers that cause the cache to vary. Key is header name, value is an array of
  215. * options for the Key header.
  216. */
  217. private $mVaryHeader = [
  218. 'Accept-Encoding' => [ 'match=gzip' ],
  219. ];
  220. /**
  221. * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
  222. * of the redirect.
  223. *
  224. * @var Title
  225. */
  226. private $mRedirectedFrom = null;
  227. /**
  228. * Additional key => value data
  229. */
  230. private $mProperties = [];
  231. /**
  232. * @var string|null ResourceLoader target for load.php links. If null, will be omitted
  233. */
  234. private $mTarget = null;
  235. /**
  236. * @var bool Whether parser output contains a table of contents
  237. */
  238. private $mEnableTOC = false;
  239. /**
  240. * @var string|null The URL to send in a <link> element with rel=license
  241. */
  242. private $copyrightUrl;
  243. /** @var array Profiling data */
  244. private $limitReportJSData = [];
  245. /** @var array Map Title to Content */
  246. private $contentOverrides = [];
  247. /** @var callable[] */
  248. private $contentOverrideCallbacks = [];
  249. /**
  250. * Link: header contents
  251. */
  252. private $mLinkHeader = [];
  253. /**
  254. * @var string The nonce for Content-Security-Policy
  255. */
  256. private $CSPNonce;
  257. /**
  258. * Constructor for OutputPage. This should not be called directly.
  259. * Instead a new RequestContext should be created and it will implicitly create
  260. * a OutputPage tied to that context.
  261. * @param IContextSource $context
  262. */
  263. function __construct( IContextSource $context ) {
  264. $this->setContext( $context );
  265. }
  266. /**
  267. * Redirect to $url rather than displaying the normal page
  268. *
  269. * @param string $url
  270. * @param string $responsecode HTTP status code
  271. */
  272. public function redirect( $url, $responsecode = '302' ) {
  273. # Strip newlines as a paranoia check for header injection in PHP<5.1.2
  274. $this->mRedirect = str_replace( "\n", '', $url );
  275. $this->mRedirectCode = $responsecode;
  276. }
  277. /**
  278. * Get the URL to redirect to, or an empty string if not redirect URL set
  279. *
  280. * @return string
  281. */
  282. public function getRedirect() {
  283. return $this->mRedirect;
  284. }
  285. /**
  286. * Set the copyright URL to send with the output.
  287. * Empty string to omit, null to reset.
  288. *
  289. * @since 1.26
  290. *
  291. * @param string|null $url
  292. */
  293. public function setCopyrightUrl( $url ) {
  294. $this->copyrightUrl = $url;
  295. }
  296. /**
  297. * Set the HTTP status code to send with the output.
  298. *
  299. * @param int $statusCode
  300. */
  301. public function setStatusCode( $statusCode ) {
  302. $this->mStatusCode = $statusCode;
  303. }
  304. /**
  305. * Add a new "<meta>" tag
  306. * To add an http-equiv meta tag, precede the name with "http:"
  307. *
  308. * @param string $name Name of the meta tag
  309. * @param string $val Value of the meta tag
  310. */
  311. function addMeta( $name, $val ) {
  312. array_push( $this->mMetatags, [ $name, $val ] );
  313. }
  314. /**
  315. * Returns the current <meta> tags
  316. *
  317. * @since 1.25
  318. * @return array
  319. */
  320. public function getMetaTags() {
  321. return $this->mMetatags;
  322. }
  323. /**
  324. * Add a new \<link\> tag to the page header.
  325. *
  326. * Note: use setCanonicalUrl() for rel=canonical.
  327. *
  328. * @param array $linkarr Associative array of attributes.
  329. */
  330. function addLink( array $linkarr ) {
  331. array_push( $this->mLinktags, $linkarr );
  332. }
  333. /**
  334. * Returns the current <link> tags
  335. *
  336. * @since 1.25
  337. * @return array
  338. */
  339. public function getLinkTags() {
  340. return $this->mLinktags;
  341. }
  342. /**
  343. * Set the URL to be used for the <link rel=canonical>. This should be used
  344. * in preference to addLink(), to avoid duplicate link tags.
  345. * @param string $url
  346. */
  347. function setCanonicalUrl( $url ) {
  348. $this->mCanonicalUrl = $url;
  349. }
  350. /**
  351. * Returns the URL to be used for the <link rel=canonical> if
  352. * one is set.
  353. *
  354. * @since 1.25
  355. * @return bool|string
  356. */
  357. public function getCanonicalUrl() {
  358. return $this->mCanonicalUrl;
  359. }
  360. /**
  361. * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
  362. * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
  363. * if possible.
  364. *
  365. * @param string $script Raw HTML
  366. */
  367. function addScript( $script ) {
  368. $this->mScripts .= $script;
  369. }
  370. /**
  371. * Add a JavaScript file to be loaded as `<script>` on this page.
  372. *
  373. * Internal use only. Use OutputPage::addModules() if possible.
  374. *
  375. * @param string $file URL to file (absolute path, protocol-relative, or full url)
  376. * @param string|null $unused Previously used to change the cache-busting query parameter
  377. */
  378. public function addScriptFile( $file, $unused = null ) {
  379. if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
  380. // This is not an absolute path, protocol-relative url, or full scheme url,
  381. // presumed to be an old call intended to include a file from /w/skins/common,
  382. // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
  383. wfDeprecated( __METHOD__, '1.24' );
  384. return;
  385. }
  386. $this->addScript( Html::linkedScript( $file, $this->getCSPNonce() ) );
  387. }
  388. /**
  389. * Add a self-contained script tag with the given contents
  390. * Internal use only. Use OutputPage::addModules() if possible.
  391. *
  392. * @param string $script JavaScript text, no script tags
  393. */
  394. public function addInlineScript( $script ) {
  395. $this->mScripts .= Html::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
  396. }
  397. /**
  398. * Filter an array of modules to remove insufficiently trustworthy members, and modules
  399. * which are no longer registered (eg a page is cached before an extension is disabled)
  400. * @param array $modules
  401. * @param string|null $position Unused
  402. * @param string $type
  403. * @return array
  404. */
  405. protected function filterModules( array $modules, $position = null,
  406. $type = ResourceLoaderModule::TYPE_COMBINED
  407. ) {
  408. $resourceLoader = $this->getResourceLoader();
  409. $filteredModules = [];
  410. foreach ( $modules as $val ) {
  411. $module = $resourceLoader->getModule( $val );
  412. if ( $module instanceof ResourceLoaderModule
  413. && $module->getOrigin() <= $this->getAllowedModules( $type )
  414. ) {
  415. if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
  416. $this->warnModuleTargetFilter( $module->getName() );
  417. continue;
  418. }
  419. $filteredModules[] = $val;
  420. }
  421. }
  422. return $filteredModules;
  423. }
  424. private function warnModuleTargetFilter( $moduleName ) {
  425. static $warnings = [];
  426. if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
  427. return;
  428. }
  429. $warnings[$this->mTarget][$moduleName] = true;
  430. $this->getResourceLoader()->getLogger()->debug(
  431. 'Module "{module}" not loadable on target "{target}".',
  432. [
  433. 'module' => $moduleName,
  434. 'target' => $this->mTarget,
  435. ]
  436. );
  437. }
  438. /**
  439. * Get the list of modules to include on this page
  440. *
  441. * @param bool $filter Whether to filter out insufficiently trustworthy modules
  442. * @param string|null $position Unused
  443. * @param string $param
  444. * @param string $type
  445. * @return array Array of module names
  446. */
  447. public function getModules( $filter = false, $position = null, $param = 'mModules',
  448. $type = ResourceLoaderModule::TYPE_COMBINED
  449. ) {
  450. $modules = array_values( array_unique( $this->$param ) );
  451. return $filter
  452. ? $this->filterModules( $modules, null, $type )
  453. : $modules;
  454. }
  455. /**
  456. * Load one or more ResourceLoader modules on this page.
  457. *
  458. * @param string|array $modules Module name (string) or array of module names
  459. */
  460. public function addModules( $modules ) {
  461. $this->mModules = array_merge( $this->mModules, (array)$modules );
  462. }
  463. /**
  464. * Get the list of script-only modules to load on this page.
  465. *
  466. * @param bool $filter
  467. * @param string|null $position Unused
  468. * @return array Array of module names
  469. */
  470. public function getModuleScripts( $filter = false, $position = null ) {
  471. return $this->getModules( $filter, null, 'mModuleScripts',
  472. ResourceLoaderModule::TYPE_SCRIPTS
  473. );
  474. }
  475. /**
  476. * Load the scripts of one or more ResourceLoader modules, on this page.
  477. *
  478. * This method exists purely to provide the legacy behaviour of loading
  479. * a module's scripts in the global scope, and without dependency resolution.
  480. * See <https://phabricator.wikimedia.org/T188689>.
  481. *
  482. * @deprecated since 1.31 Use addModules() instead.
  483. * @param string|array $modules Module name (string) or array of module names
  484. */
  485. public function addModuleScripts( $modules ) {
  486. $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
  487. }
  488. /**
  489. * Get the list of style-only modules to load on this page.
  490. *
  491. * @param bool $filter
  492. * @param string|null $position Unused
  493. * @return array Array of module names
  494. */
  495. public function getModuleStyles( $filter = false, $position = null ) {
  496. return $this->getModules( $filter, null, 'mModuleStyles',
  497. ResourceLoaderModule::TYPE_STYLES
  498. );
  499. }
  500. /**
  501. * Load the styles of one or more ResourceLoader modules on this page.
  502. *
  503. * Module styles added through this function will be loaded as a stylesheet,
  504. * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
  505. * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
  506. *
  507. * @param string|array $modules Module name (string) or array of module names
  508. */
  509. public function addModuleStyles( $modules ) {
  510. $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
  511. }
  512. /**
  513. * @return null|string ResourceLoader target
  514. */
  515. public function getTarget() {
  516. return $this->mTarget;
  517. }
  518. /**
  519. * Sets ResourceLoader target for load.php links. If null, will be omitted
  520. *
  521. * @param string|null $target
  522. */
  523. public function setTarget( $target ) {
  524. $this->mTarget = $target;
  525. }
  526. /**
  527. * Add a mapping from a LinkTarget to a Content, for things like page preview.
  528. * @see self::addContentOverrideCallback()
  529. * @since 1.32
  530. * @param LinkTarget $target
  531. * @param Content $content
  532. */
  533. public function addContentOverride( LinkTarget $target, Content $content ) {
  534. if ( !$this->contentOverrides ) {
  535. // Register a callback for $this->contentOverrides on the first call
  536. $this->addContentOverrideCallback( function ( LinkTarget $target ) {
  537. $key = $target->getNamespace() . ':' . $target->getDBkey();
  538. return $this->contentOverrides[$key] ?? null;
  539. } );
  540. }
  541. $key = $target->getNamespace() . ':' . $target->getDBkey();
  542. $this->contentOverrides[$key] = $content;
  543. }
  544. /**
  545. * Add a callback for mapping from a Title to a Content object, for things
  546. * like page preview.
  547. * @see ResourceLoaderContext::getContentOverrideCallback()
  548. * @since 1.32
  549. * @param callable $callback
  550. */
  551. public function addContentOverrideCallback( callable $callback ) {
  552. $this->contentOverrideCallbacks[] = $callback;
  553. }
  554. /**
  555. * Get an array of head items
  556. *
  557. * @return array
  558. */
  559. function getHeadItemsArray() {
  560. return $this->mHeadItems;
  561. }
  562. /**
  563. * Add or replace a head item to the output
  564. *
  565. * Whenever possible, use more specific options like ResourceLoader modules,
  566. * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
  567. * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
  568. * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
  569. * This would be your very LAST fallback.
  570. *
  571. * @param string $name Item name
  572. * @param string $value Raw HTML
  573. */
  574. public function addHeadItem( $name, $value ) {
  575. $this->mHeadItems[$name] = $value;
  576. }
  577. /**
  578. * Add one or more head items to the output
  579. *
  580. * @since 1.28
  581. * @param string|string[] $values Raw HTML
  582. */
  583. public function addHeadItems( $values ) {
  584. $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
  585. }
  586. /**
  587. * Check if the header item $name is already set
  588. *
  589. * @param string $name Item name
  590. * @return bool
  591. */
  592. public function hasHeadItem( $name ) {
  593. return isset( $this->mHeadItems[$name] );
  594. }
  595. /**
  596. * Add a class to the <body> element
  597. *
  598. * @since 1.30
  599. * @param string|string[] $classes One or more classes to add
  600. */
  601. public function addBodyClasses( $classes ) {
  602. $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
  603. }
  604. /**
  605. * Set whether the output should only contain the body of the article,
  606. * without any skin, sidebar, etc.
  607. * Used e.g. when calling with "action=render".
  608. *
  609. * @param bool $only Whether to output only the body of the article
  610. */
  611. public function setArticleBodyOnly( $only ) {
  612. $this->mArticleBodyOnly = $only;
  613. }
  614. /**
  615. * Return whether the output will contain only the body of the article
  616. *
  617. * @return bool
  618. */
  619. public function getArticleBodyOnly() {
  620. return $this->mArticleBodyOnly;
  621. }
  622. /**
  623. * Set an additional output property
  624. * @since 1.21
  625. *
  626. * @param string $name
  627. * @param mixed $value
  628. */
  629. public function setProperty( $name, $value ) {
  630. $this->mProperties[$name] = $value;
  631. }
  632. /**
  633. * Get an additional output property
  634. * @since 1.21
  635. *
  636. * @param string $name
  637. * @return mixed Property value or null if not found
  638. */
  639. public function getProperty( $name ) {
  640. return $this->mProperties[$name] ?? null;
  641. }
  642. /**
  643. * checkLastModified tells the client to use the client-cached page if
  644. * possible. If successful, the OutputPage is disabled so that
  645. * any future call to OutputPage->output() have no effect.
  646. *
  647. * Side effect: sets mLastModified for Last-Modified header
  648. *
  649. * @param string $timestamp
  650. *
  651. * @return bool True if cache-ok headers was sent.
  652. */
  653. public function checkLastModified( $timestamp ) {
  654. if ( !$timestamp || $timestamp == '19700101000000' ) {
  655. wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
  656. return false;
  657. }
  658. $config = $this->getConfig();
  659. if ( !$config->get( 'CachePages' ) ) {
  660. wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
  661. return false;
  662. }
  663. $timestamp = wfTimestamp( TS_MW, $timestamp );
  664. $modifiedTimes = [
  665. 'page' => $timestamp,
  666. 'user' => $this->getUser()->getTouched(),
  667. 'epoch' => $config->get( 'CacheEpoch' )
  668. ];
  669. if ( $config->get( 'UseSquid' ) ) {
  670. $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
  671. time(),
  672. $config->get( 'SquidMaxage' )
  673. ) );
  674. }
  675. Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
  676. $maxModified = max( $modifiedTimes );
  677. $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
  678. $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
  679. if ( $clientHeader === false ) {
  680. wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
  681. return false;
  682. }
  683. # IE sends sizes after the date like this:
  684. # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
  685. # this breaks strtotime().
  686. $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
  687. Wikimedia\suppressWarnings(); // E_STRICT system time warnings
  688. $clientHeaderTime = strtotime( $clientHeader );
  689. Wikimedia\restoreWarnings();
  690. if ( !$clientHeaderTime ) {
  691. wfDebug( __METHOD__
  692. . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
  693. return false;
  694. }
  695. $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
  696. # Make debug info
  697. $info = '';
  698. foreach ( $modifiedTimes as $name => $value ) {
  699. if ( $info !== '' ) {
  700. $info .= ', ';
  701. }
  702. $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
  703. }
  704. wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
  705. wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
  706. wfDebug( __METHOD__ . ": effective Last-Modified: " .
  707. wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
  708. if ( $clientHeaderTime < $maxModified ) {
  709. wfDebug( __METHOD__ . ": STALE, $info", 'private' );
  710. return false;
  711. }
  712. # Not modified
  713. # Give a 304 Not Modified response code and disable body output
  714. wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
  715. ini_set( 'zlib.output_compression', 0 );
  716. $this->getRequest()->response()->statusHeader( 304 );
  717. $this->sendCacheControl();
  718. $this->disable();
  719. // Don't output a compressed blob when using ob_gzhandler;
  720. // it's technically against HTTP spec and seems to confuse
  721. // Firefox when the response gets split over two packets.
  722. wfClearOutputBuffers();
  723. return true;
  724. }
  725. /**
  726. * @param int $reqTime Time of request (eg. now)
  727. * @param int $maxAge Cache TTL in seconds
  728. * @return int Timestamp
  729. */
  730. private function getCdnCacheEpoch( $reqTime, $maxAge ) {
  731. // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
  732. // because even if the wiki page content hasn't changed since, static
  733. // resources may have changed (skin HTML, interface messages, urls, etc.)
  734. // and must roll-over in a timely manner (T46570)
  735. return $reqTime - $maxAge;
  736. }
  737. /**
  738. * Override the last modified timestamp
  739. *
  740. * @param string $timestamp New timestamp, in a format readable by
  741. * wfTimestamp()
  742. */
  743. public function setLastModified( $timestamp ) {
  744. $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
  745. }
  746. /**
  747. * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
  748. *
  749. * @param string $policy The literal string to output as the contents of
  750. * the meta tag. Will be parsed according to the spec and output in
  751. * standardized form.
  752. * @return null
  753. */
  754. public function setRobotPolicy( $policy ) {
  755. $policy = Article::formatRobotPolicy( $policy );
  756. if ( isset( $policy['index'] ) ) {
  757. $this->setIndexPolicy( $policy['index'] );
  758. }
  759. if ( isset( $policy['follow'] ) ) {
  760. $this->setFollowPolicy( $policy['follow'] );
  761. }
  762. }
  763. /**
  764. * Set the index policy for the page, but leave the follow policy un-
  765. * touched.
  766. *
  767. * @param string $policy Either 'index' or 'noindex'.
  768. * @return null
  769. */
  770. public function setIndexPolicy( $policy ) {
  771. $policy = trim( $policy );
  772. if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
  773. $this->mIndexPolicy = $policy;
  774. }
  775. }
  776. /**
  777. * Set the follow policy for the page, but leave the index policy un-
  778. * touched.
  779. *
  780. * @param string $policy Either 'follow' or 'nofollow'.
  781. * @return null
  782. */
  783. public function setFollowPolicy( $policy ) {
  784. $policy = trim( $policy );
  785. if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
  786. $this->mFollowPolicy = $policy;
  787. }
  788. }
  789. /**
  790. * "HTML title" means the contents of "<title>".
  791. * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
  792. *
  793. * @param string|Message $name
  794. */
  795. public function setHTMLTitle( $name ) {
  796. if ( $name instanceof Message ) {
  797. $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
  798. } else {
  799. $this->mHTMLtitle = $name;
  800. }
  801. }
  802. /**
  803. * Return the "HTML title", i.e. the content of the "<title>" tag.
  804. *
  805. * @return string
  806. */
  807. public function getHTMLTitle() {
  808. return $this->mHTMLtitle;
  809. }
  810. /**
  811. * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
  812. *
  813. * @param Title $t
  814. */
  815. public function setRedirectedFrom( $t ) {
  816. $this->mRedirectedFrom = $t;
  817. }
  818. /**
  819. * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
  820. * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
  821. * but not bad tags like \<script\>. This function automatically sets
  822. * \<title\> to the same content as \<h1\> but with all tags removed. Bad
  823. * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
  824. * good tags like \<i\> will be dropped entirely.
  825. *
  826. * @param string|Message $name
  827. */
  828. public function setPageTitle( $name ) {
  829. if ( $name instanceof Message ) {
  830. $name = $name->setContext( $this->getContext() )->text();
  831. }
  832. # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
  833. # but leave "<i>foobar</i>" alone
  834. $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
  835. $this->mPageTitle = $nameWithTags;
  836. # change "<i>foo&amp;bar</i>" to "foo&bar"
  837. $this->setHTMLTitle(
  838. $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
  839. ->inContentLanguage()
  840. );
  841. }
  842. /**
  843. * Return the "page title", i.e. the content of the \<h1\> tag.
  844. *
  845. * @return string
  846. */
  847. public function getPageTitle() {
  848. return $this->mPageTitle;
  849. }
  850. /**
  851. * Same as page title but only contains name of the page, not any other text.
  852. *
  853. * @since 1.32
  854. * @param string $html Page title text.
  855. * @see OutputPage::setPageTitle
  856. */
  857. public function setDisplayTitle( $html ) {
  858. $this->displayTitle = $html;
  859. }
  860. /**
  861. * Returns page display title.
  862. *
  863. * Performs some normalization, but this not as strict the magic word.
  864. *
  865. * @since 1.32
  866. * @return string HTML
  867. */
  868. public function getDisplayTitle() {
  869. $html = $this->displayTitle;
  870. if ( $html === null ) {
  871. $html = $this->getTitle()->getPrefixedText();
  872. }
  873. return Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $html ) );
  874. }
  875. /**
  876. * Returns page display title without namespace prefix if possible.
  877. *
  878. * @since 1.32
  879. * @return string HTML
  880. */
  881. public function getUnprefixedDisplayTitle() {
  882. $text = $this->getDisplayTitle();
  883. $nsPrefix = $this->getTitle()->getNsText() . ':';
  884. $prefix = preg_quote( $nsPrefix, '/' );
  885. return preg_replace( "/^$prefix/i", '', $text );
  886. }
  887. /**
  888. * Set the Title object to use
  889. *
  890. * @param Title $t
  891. */
  892. public function setTitle( Title $t ) {
  893. $this->getContext()->setTitle( $t );
  894. }
  895. /**
  896. * Replace the subtitle with $str
  897. *
  898. * @param string|Message $str New value of the subtitle. String should be safe HTML.
  899. */
  900. public function setSubtitle( $str ) {
  901. $this->clearSubtitle();
  902. $this->addSubtitle( $str );
  903. }
  904. /**
  905. * Add $str to the subtitle
  906. *
  907. * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
  908. */
  909. public function addSubtitle( $str ) {
  910. if ( $str instanceof Message ) {
  911. $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
  912. } else {
  913. $this->mSubtitle[] = $str;
  914. }
  915. }
  916. /**
  917. * Build message object for a subtitle containing a backlink to a page
  918. *
  919. * @param Title $title Title to link to
  920. * @param array $query Array of additional parameters to include in the link
  921. * @return Message
  922. * @since 1.25
  923. */
  924. public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
  925. if ( $title->isRedirect() ) {
  926. $query['redirect'] = 'no';
  927. }
  928. $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
  929. return wfMessage( 'backlinksubtitle' )
  930. ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
  931. }
  932. /**
  933. * Add a subtitle containing a backlink to a page
  934. *
  935. * @param Title $title Title to link to
  936. * @param array $query Array of additional parameters to include in the link
  937. */
  938. public function addBacklinkSubtitle( Title $title, $query = [] ) {
  939. $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
  940. }
  941. /**
  942. * Clear the subtitles
  943. */
  944. public function clearSubtitle() {
  945. $this->mSubtitle = [];
  946. }
  947. /**
  948. * Get the subtitle
  949. *
  950. * @return string
  951. */
  952. public function getSubtitle() {
  953. return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
  954. }
  955. /**
  956. * Set the page as printable, i.e. it'll be displayed with all
  957. * print styles included
  958. */
  959. public function setPrintable() {
  960. $this->mPrintable = true;
  961. }
  962. /**
  963. * Return whether the page is "printable"
  964. *
  965. * @return bool
  966. */
  967. public function isPrintable() {
  968. return $this->mPrintable;
  969. }
  970. /**
  971. * Disable output completely, i.e. calling output() will have no effect
  972. */
  973. public function disable() {
  974. $this->mDoNothing = true;
  975. }
  976. /**
  977. * Return whether the output will be completely disabled
  978. *
  979. * @return bool
  980. */
  981. public function isDisabled() {
  982. return $this->mDoNothing;
  983. }
  984. /**
  985. * Show an "add new section" link?
  986. *
  987. * @return bool
  988. */
  989. public function showNewSectionLink() {
  990. return $this->mNewSectionLink;
  991. }
  992. /**
  993. * Forcibly hide the new section link?
  994. *
  995. * @return bool
  996. */
  997. public function forceHideNewSectionLink() {
  998. return $this->mHideNewSectionLink;
  999. }
  1000. /**
  1001. * Add or remove feed links in the page header
  1002. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  1003. * for the new version
  1004. * @see addFeedLink()
  1005. *
  1006. * @param bool $show True: add default feeds, false: remove all feeds
  1007. */
  1008. public function setSyndicated( $show = true ) {
  1009. if ( $show ) {
  1010. $this->setFeedAppendQuery( false );
  1011. } else {
  1012. $this->mFeedLinks = [];
  1013. }
  1014. }
  1015. /**
  1016. * Add default feeds to the page header
  1017. * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
  1018. * for the new version
  1019. * @see addFeedLink()
  1020. *
  1021. * @param string $val Query to append to feed links or false to output
  1022. * default links
  1023. */
  1024. public function setFeedAppendQuery( $val ) {
  1025. $this->mFeedLinks = [];
  1026. foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
  1027. $query = "feed=$type";
  1028. if ( is_string( $val ) ) {
  1029. $query .= '&' . $val;
  1030. }
  1031. $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
  1032. }
  1033. }
  1034. /**
  1035. * Add a feed link to the page header
  1036. *
  1037. * @param string $format Feed type, should be a key of $wgFeedClasses
  1038. * @param string $href URL
  1039. */
  1040. public function addFeedLink( $format, $href ) {
  1041. if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
  1042. $this->mFeedLinks[$format] = $href;
  1043. }
  1044. }
  1045. /**
  1046. * Should we output feed links for this page?
  1047. * @return bool
  1048. */
  1049. public function isSyndicated() {
  1050. return count( $this->mFeedLinks ) > 0;
  1051. }
  1052. /**
  1053. * Return URLs for each supported syndication format for this page.
  1054. * @return array Associating format keys with URLs
  1055. */
  1056. public function getSyndicationLinks() {
  1057. return $this->mFeedLinks;
  1058. }
  1059. /**
  1060. * Will currently always return null
  1061. *
  1062. * @return null
  1063. */
  1064. public function getFeedAppendQuery() {
  1065. return $this->mFeedLinksAppendQuery;
  1066. }
  1067. /**
  1068. * Set whether the displayed content is related to the source of the
  1069. * corresponding article on the wiki
  1070. * Setting true will cause the change "article related" toggle to true
  1071. *
  1072. * @param bool $newVal
  1073. */
  1074. public function setArticleFlag( $newVal ) {
  1075. $this->mIsArticle = $newVal;
  1076. if ( $newVal ) {
  1077. $this->mIsArticleRelated = $newVal;
  1078. }
  1079. }
  1080. /**
  1081. * Return whether the content displayed page is related to the source of
  1082. * the corresponding article on the wiki
  1083. *
  1084. * @return bool
  1085. */
  1086. public function isArticle() {
  1087. return $this->mIsArticle;
  1088. }
  1089. /**
  1090. * Set whether this page is related an article on the wiki
  1091. * Setting false will cause the change of "article flag" toggle to false
  1092. *
  1093. * @param bool $newVal
  1094. */
  1095. public function setArticleRelated( $newVal ) {
  1096. $this->mIsArticleRelated = $newVal;
  1097. if ( !$newVal ) {
  1098. $this->mIsArticle = false;
  1099. }
  1100. }
  1101. /**
  1102. * Return whether this page is related an article on the wiki
  1103. *
  1104. * @return bool
  1105. */
  1106. public function isArticleRelated() {
  1107. return $this->mIsArticleRelated;
  1108. }
  1109. /**
  1110. * Add new language links
  1111. *
  1112. * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
  1113. * (e.g. 'fr:Test page')
  1114. */
  1115. public function addLanguageLinks( array $newLinkArray ) {
  1116. $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
  1117. }
  1118. /**
  1119. * Reset the language links and add new language links
  1120. *
  1121. * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
  1122. * (e.g. 'fr:Test page')
  1123. */
  1124. public function setLanguageLinks( array $newLinkArray ) {
  1125. $this->mLanguageLinks = $newLinkArray;
  1126. }
  1127. /**
  1128. * Get the list of language links
  1129. *
  1130. * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
  1131. */
  1132. public function getLanguageLinks() {
  1133. return $this->mLanguageLinks;
  1134. }
  1135. /**
  1136. * Add an array of categories, with names in the keys
  1137. *
  1138. * @param array $categories Mapping category name => sort key
  1139. */
  1140. public function addCategoryLinks( array $categories ) {
  1141. if ( !$categories ) {
  1142. return;
  1143. }
  1144. $res = $this->addCategoryLinksToLBAndGetResult( $categories );
  1145. # Set all the values to 'normal'.
  1146. $categories = array_fill_keys( array_keys( $categories ), 'normal' );
  1147. # Mark hidden categories
  1148. foreach ( $res as $row ) {
  1149. if ( isset( $row->pp_value ) ) {
  1150. $categories[$row->page_title] = 'hidden';
  1151. }
  1152. }
  1153. // Avoid PHP 7.1 warning of passing $this by reference
  1154. $outputPage = $this;
  1155. # Add the remaining categories to the skin
  1156. if ( Hooks::run(
  1157. 'OutputPageMakeCategoryLinks',
  1158. [ &$outputPage, $categories, &$this->mCategoryLinks ] )
  1159. ) {
  1160. $services = MediaWikiServices::getInstance();
  1161. $linkRenderer = $services->getLinkRenderer();
  1162. foreach ( $categories as $category => $type ) {
  1163. // array keys will cast numeric category names to ints, so cast back to string
  1164. $category = (string)$category;
  1165. $origcategory = $category;
  1166. $title = Title::makeTitleSafe( NS_CATEGORY, $category );
  1167. if ( !$title ) {
  1168. continue;
  1169. }
  1170. $services->getContentLanguage()->findVariantLink( $category, $title, true );
  1171. if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
  1172. continue;
  1173. }
  1174. $text = $services->getContentLanguage()->convertHtml( $title->getText() );
  1175. $this->mCategories[$type][] = $title->getText();
  1176. $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
  1177. }
  1178. }
  1179. }
  1180. /**
  1181. * @param array $categories
  1182. * @return bool|IResultWrapper
  1183. */
  1184. protected function addCategoryLinksToLBAndGetResult( array $categories ) {
  1185. # Add the links to a LinkBatch
  1186. $arr = [ NS_CATEGORY => $categories ];
  1187. $lb = new LinkBatch;
  1188. $lb->setArray( $arr );
  1189. # Fetch existence plus the hiddencat property
  1190. $dbr = wfGetDB( DB_REPLICA );
  1191. $fields = array_merge(
  1192. LinkCache::getSelectFields(),
  1193. [ 'page_namespace', 'page_title', 'pp_value' ]
  1194. );
  1195. $res = $dbr->select( [ 'page', 'page_props' ],
  1196. $fields,
  1197. $lb->constructSet( 'page', $dbr ),
  1198. __METHOD__,
  1199. [],
  1200. [ 'page_props' => [ 'LEFT JOIN', [
  1201. 'pp_propname' => 'hiddencat',
  1202. 'pp_page = page_id'
  1203. ] ] ]
  1204. );
  1205. # Add the results to the link cache
  1206. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  1207. $lb->addResultToCache( $linkCache, $res );
  1208. return $res;
  1209. }
  1210. /**
  1211. * Reset the category links (but not the category list) and add $categories
  1212. *
  1213. * @param array $categories Mapping category name => sort key
  1214. */
  1215. public function setCategoryLinks( array $categories ) {
  1216. $this->mCategoryLinks = [];
  1217. $this->addCategoryLinks( $categories );
  1218. }
  1219. /**
  1220. * Get the list of category links, in a 2-D array with the following format:
  1221. * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
  1222. * hidden categories) and $link a HTML fragment with a link to the category
  1223. * page
  1224. *
  1225. * @return array
  1226. */
  1227. public function getCategoryLinks() {
  1228. return $this->mCategoryLinks;
  1229. }
  1230. /**
  1231. * Get the list of category names this page belongs to.
  1232. *
  1233. * @param string $type The type of categories which should be returned. Possible values:
  1234. * * all: all categories of all types
  1235. * * hidden: only the hidden categories
  1236. * * normal: all categories, except hidden categories
  1237. * @return array Array of strings
  1238. */
  1239. public function getCategories( $type = 'all' ) {
  1240. if ( $type === 'all' ) {
  1241. $allCategories = [];
  1242. foreach ( $this->mCategories as $categories ) {
  1243. $allCategories = array_merge( $allCategories, $categories );
  1244. }
  1245. return $allCategories;
  1246. }
  1247. if ( !isset( $this->mCategories[$type] ) ) {
  1248. throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
  1249. }
  1250. return $this->mCategories[$type];
  1251. }
  1252. /**
  1253. * Add an array of indicators, with their identifiers as array
  1254. * keys and HTML contents as values.
  1255. *
  1256. * In case of duplicate keys, existing values are overwritten.
  1257. *
  1258. * @param array $indicators
  1259. * @since 1.25
  1260. */
  1261. public function setIndicators( array $indicators ) {
  1262. $this->mIndicators = $indicators + $this->mIndicators;
  1263. // Keep ordered by key
  1264. ksort( $this->mIndicators );
  1265. }
  1266. /**
  1267. * Get the indicators associated with this page.
  1268. *
  1269. * The array will be internally ordered by item keys.
  1270. *
  1271. * @return array Keys: identifiers, values: HTML contents
  1272. * @since 1.25
  1273. */
  1274. public function getIndicators() {
  1275. return $this->mIndicators;
  1276. }
  1277. /**
  1278. * Adds help link with an icon via page indicators.
  1279. * Link target can be overridden by a local message containing a wikilink:
  1280. * the message key is: lowercase action or special page name + '-helppage'.
  1281. * @param string $to Target MediaWiki.org page title or encoded URL.
  1282. * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
  1283. * @since 1.25
  1284. */
  1285. public function addHelpLink( $to, $overrideBaseUrl = false ) {
  1286. $this->addModuleStyles( 'mediawiki.helplink' );
  1287. $text = $this->msg( 'helppage-top-gethelp' )->escaped();
  1288. if ( $overrideBaseUrl ) {
  1289. $helpUrl = $to;
  1290. } else {
  1291. $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
  1292. $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
  1293. }
  1294. $link = Html::rawElement(
  1295. 'a',
  1296. [
  1297. 'href' => $helpUrl,
  1298. 'target' => '_blank',
  1299. 'class' => 'mw-helplink',
  1300. ],
  1301. $text
  1302. );
  1303. $this->setIndicators( [ 'mw-helplink' => $link ] );
  1304. }
  1305. /**
  1306. * Do not allow scripts which can be modified by wiki users to load on this page;
  1307. * only allow scripts bundled with, or generated by, the software.
  1308. * Site-wide styles are controlled by a config setting, since they can be
  1309. * used to create a custom skin/theme, but not user-specific ones.
  1310. *
  1311. * @todo this should be given a more accurate name
  1312. */
  1313. public function disallowUserJs() {
  1314. $this->reduceAllowedModules(
  1315. ResourceLoaderModule::TYPE_SCRIPTS,
  1316. ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
  1317. );
  1318. // Site-wide styles are controlled by a config setting, see T73621
  1319. // for background on why. User styles are never allowed.
  1320. if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
  1321. $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
  1322. } else {
  1323. $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
  1324. }
  1325. $this->reduceAllowedModules(
  1326. ResourceLoaderModule::TYPE_STYLES,
  1327. $styleOrigin
  1328. );
  1329. }
  1330. /**
  1331. * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
  1332. * @see ResourceLoaderModule::$origin
  1333. * @param string $type ResourceLoaderModule TYPE_ constant
  1334. * @return int ResourceLoaderModule ORIGIN_ class constant
  1335. */
  1336. public function getAllowedModules( $type ) {
  1337. if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
  1338. return min( array_values( $this->mAllowedModules ) );
  1339. } else {
  1340. return $this->mAllowedModules[$type] ?? ResourceLoaderModule::ORIGIN_ALL;
  1341. }
  1342. }
  1343. /**
  1344. * Limit the highest level of CSS/JS untrustworthiness allowed.
  1345. *
  1346. * If passed the same or a higher level than the current level of untrustworthiness set, the
  1347. * level will remain unchanged.
  1348. *
  1349. * @param string $type
  1350. * @param int $level ResourceLoaderModule class constant
  1351. */
  1352. public function reduceAllowedModules( $type, $level ) {
  1353. $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
  1354. }
  1355. /**
  1356. * Prepend $text to the body HTML
  1357. *
  1358. * @param string $text HTML
  1359. */
  1360. public function prependHTML( $text ) {
  1361. $this->mBodytext = $text . $this->mBodytext;
  1362. }
  1363. /**
  1364. * Append $text to the body HTML
  1365. *
  1366. * @param string $text HTML
  1367. */
  1368. public function addHTML( $text ) {
  1369. $this->mBodytext .= $text;
  1370. }
  1371. /**
  1372. * Shortcut for adding an Html::element via addHTML.
  1373. *
  1374. * @since 1.19
  1375. *
  1376. * @param string $element
  1377. * @param array $attribs
  1378. * @param string $contents
  1379. */
  1380. public function addElement( $element, array $attribs = [], $contents = '' ) {
  1381. $this->addHTML( Html::element( $element, $attribs, $contents ) );
  1382. }
  1383. /**
  1384. * Clear the body HTML
  1385. */
  1386. public function clearHTML() {
  1387. $this->mBodytext = '';
  1388. }
  1389. /**
  1390. * Get the body HTML
  1391. *
  1392. * @return string HTML
  1393. */
  1394. public function getHTML() {
  1395. return $this->mBodytext;
  1396. }
  1397. /**
  1398. * Get/set the ParserOptions object to use for wikitext parsing
  1399. *
  1400. * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
  1401. * current ParserOption object. This parameter is deprecated since 1.31.
  1402. * @return ParserOptions
  1403. */
  1404. public function parserOptions( $options = null ) {
  1405. if ( $options !== null ) {
  1406. wfDeprecated( __METHOD__ . ' with non-null $options', '1.31' );
  1407. }
  1408. if ( $options !== null && !empty( $options->isBogus ) ) {
  1409. // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
  1410. // been changed somehow, and keep it if so.
  1411. $anonPO = ParserOptions::newFromAnon();
  1412. $anonPO->setAllowUnsafeRawHtml( false );
  1413. if ( !$options->matches( $anonPO ) ) {
  1414. wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
  1415. $options->isBogus = false;
  1416. }
  1417. }
  1418. if ( !$this->mParserOptions ) {
  1419. if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
  1420. // $wgUser isn't unstubbable yet, so don't try to get a
  1421. // ParserOptions for it. And don't cache this ParserOptions
  1422. // either.
  1423. $po = ParserOptions::newFromAnon();
  1424. $po->setAllowUnsafeRawHtml( false );
  1425. $po->isBogus = true;
  1426. if ( $options !== null ) {
  1427. $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
  1428. }
  1429. return $po;
  1430. }
  1431. $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
  1432. $this->mParserOptions->setAllowUnsafeRawHtml( false );
  1433. }
  1434. if ( $options !== null && !empty( $options->isBogus ) ) {
  1435. // They're trying to restore the bogus pre-$wgUser PO. Do the right
  1436. // thing.
  1437. return wfSetVar( $this->mParserOptions, null, true );
  1438. } else {
  1439. return wfSetVar( $this->mParserOptions, $options );
  1440. }
  1441. }
  1442. /**
  1443. * Set the revision ID which will be seen by the wiki text parser
  1444. * for things such as embedded {{REVISIONID}} variable use.
  1445. *
  1446. * @param int|null $revid A positive integer, or null
  1447. * @return mixed Previous value
  1448. */
  1449. public function setRevisionId( $revid ) {
  1450. $val = is_null( $revid ) ? null : intval( $revid );
  1451. return wfSetVar( $this->mRevisionId, $val, true );
  1452. }
  1453. /**
  1454. * Get the displayed revision ID
  1455. *
  1456. * @return int
  1457. */
  1458. public function getRevisionId() {
  1459. return $this->mRevisionId;
  1460. }
  1461. /**
  1462. * Set the timestamp of the revision which will be displayed. This is used
  1463. * to avoid a extra DB call in Skin::lastModified().
  1464. *
  1465. * @param string|null $timestamp
  1466. * @return mixed Previous value
  1467. */
  1468. public function setRevisionTimestamp( $timestamp ) {
  1469. return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
  1470. }
  1471. /**
  1472. * Get the timestamp of displayed revision.
  1473. * This will be null if not filled by setRevisionTimestamp().
  1474. *
  1475. * @return string|null
  1476. */
  1477. public function getRevisionTimestamp() {
  1478. return $this->mRevisionTimestamp;
  1479. }
  1480. /**
  1481. * Set the displayed file version
  1482. *
  1483. * @param File|null $file
  1484. * @return mixed Previous value
  1485. */
  1486. public function setFileVersion( $file ) {
  1487. $val = null;
  1488. if ( $file instanceof File && $file->exists() ) {
  1489. $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
  1490. }
  1491. return wfSetVar( $this->mFileVersion, $val, true );
  1492. }
  1493. /**
  1494. * Get the displayed file version
  1495. *
  1496. * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
  1497. */
  1498. public function getFileVersion() {
  1499. return $this->mFileVersion;
  1500. }
  1501. /**
  1502. * Get the templates used on this page
  1503. *
  1504. * @return array (namespace => dbKey => revId)
  1505. * @since 1.18
  1506. */
  1507. public function getTemplateIds() {
  1508. return $this->mTemplateIds;
  1509. }
  1510. /**
  1511. * Get the files used on this page
  1512. *
  1513. * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
  1514. * @since 1.18
  1515. */
  1516. public function getFileSearchOptions() {
  1517. return $this->mImageTimeKeys;
  1518. }
  1519. /**
  1520. * Convert wikitext to HTML and add it to the buffer
  1521. * Default assumes that the current page title will be used.
  1522. *
  1523. * @param string $text
  1524. * @param bool $linestart Is this the start of a line?
  1525. * @param bool $interface Is this text in the user interface language?
  1526. * @throws MWException
  1527. */
  1528. public function addWikiText( $text, $linestart = true, $interface = true ) {
  1529. $title = $this->getTitle(); // Work around E_STRICT
  1530. if ( !$title ) {
  1531. throw new MWException( 'Title is null' );
  1532. }
  1533. $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
  1534. }
  1535. /**
  1536. * Add wikitext with a custom Title object
  1537. *
  1538. * @param string $text Wikitext
  1539. * @param Title $title
  1540. * @param bool $linestart Is this the start of a line?
  1541. */
  1542. public function addWikiTextWithTitle( $text, Title $title, $linestart = true ) {
  1543. $this->addWikiTextTitle( $text, $title, $linestart );
  1544. }
  1545. /**
  1546. * Add wikitext with a custom Title object and tidy enabled.
  1547. *
  1548. * @param string $text Wikitext
  1549. * @param Title $title
  1550. * @param bool $linestart Is this the start of a line?
  1551. */
  1552. function addWikiTextTitleTidy( $text, Title $title, $linestart = true ) {
  1553. $this->addWikiTextTitle( $text, $title, $linestart, true );
  1554. }
  1555. /**
  1556. * Add wikitext with tidy enabled
  1557. *
  1558. * @param string $text Wikitext
  1559. * @param bool $linestart Is this the start of a line?
  1560. */
  1561. public function addWikiTextTidy( $text, $linestart = true ) {
  1562. $title = $this->getTitle();
  1563. $this->addWikiTextTitleTidy( $text, $title, $linestart );
  1564. }
  1565. /**
  1566. * Add wikitext with a custom Title object
  1567. *
  1568. * @param string $text Wikitext
  1569. * @param Title $title
  1570. * @param bool $linestart Is this the start of a line?
  1571. * @param bool $tidy Whether to use tidy
  1572. * @param bool $interface Whether it is an interface message
  1573. * (for example disables conversion)
  1574. */
  1575. public function addWikiTextTitle( $text, Title $title, $linestart,
  1576. $tidy = false, $interface = false
  1577. ) {
  1578. global $wgParser;
  1579. $popts = $this->parserOptions();
  1580. $oldTidy = $popts->setTidy( $tidy );
  1581. $popts->setInterfaceMessage( (bool)$interface );
  1582. $parserOutput = $wgParser->getFreshParser()->parse(
  1583. $text, $title, $popts,
  1584. $linestart, true, $this->mRevisionId
  1585. );
  1586. $popts->setTidy( $oldTidy );
  1587. $this->addParserOutput( $parserOutput, [
  1588. 'enableSectionEditLinks' => false,
  1589. ] );
  1590. }
  1591. /**
  1592. * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
  1593. * includes categories, language links, ResourceLoader modules, effects of certain magic words,
  1594. * and so on.
  1595. *
  1596. * @since 1.24
  1597. * @param ParserOutput $parserOutput
  1598. */
  1599. public function addParserOutputMetadata( ParserOutput $parserOutput ) {
  1600. $this->mLanguageLinks =
  1601. array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
  1602. $this->addCategoryLinks( $parserOutput->getCategories() );
  1603. $this->setIndicators( $parserOutput->getIndicators() );
  1604. $this->mNewSectionLink = $parserOutput->getNewSection();
  1605. $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
  1606. if ( !$parserOutput->isCacheable() ) {
  1607. $this->enableClientCache( false );
  1608. }
  1609. $this->mNoGallery = $parserOutput->getNoGallery();
  1610. $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
  1611. $this->addModules( $parserOutput->getModules() );
  1612. $this->addModuleScripts( $parserOutput->getModuleScripts() );
  1613. $this->addModuleStyles( $parserOutput->getModuleStyles() );
  1614. $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
  1615. $this->mPreventClickjacking = $this->mPreventClickjacking
  1616. || $parserOutput->preventClickjacking();
  1617. // Template versioning...
  1618. foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
  1619. if ( isset( $this->mTemplateIds[$ns] ) ) {
  1620. $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
  1621. } else {
  1622. $this->mTemplateIds[$ns] = $dbks;
  1623. }
  1624. }
  1625. // File versioning...
  1626. foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
  1627. $this->mImageTimeKeys[$dbk] = $data;
  1628. }
  1629. // Hooks registered in the object
  1630. $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
  1631. foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
  1632. list( $hookName, $data ) = $hookInfo;
  1633. if ( isset( $parserOutputHooks[$hookName] ) ) {
  1634. $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
  1635. }
  1636. }
  1637. // Enable OOUI if requested via ParserOutput
  1638. if ( $parserOutput->getEnableOOUI() ) {
  1639. $this->enableOOUI();
  1640. }
  1641. // Include parser limit report
  1642. if ( !$this->limitReportJSData ) {
  1643. $this->limitReportJSData = $parserOutput->getLimitReportJSData();
  1644. }
  1645. // Link flags are ignored for now, but may in the future be
  1646. // used to mark individual language links.
  1647. $linkFlags = [];
  1648. // Avoid PHP 7.1 warning of passing $this by reference
  1649. $outputPage = $this;
  1650. Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
  1651. Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
  1652. // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
  1653. // so that extensions may modify ParserOutput to toggle TOC.
  1654. // This cannot be moved to addParserOutputText because that is not
  1655. // called by EditPage for Preview.
  1656. if ( $parserOutput->getTOCHTML() ) {
  1657. $this->mEnableTOC = true;
  1658. }
  1659. }
  1660. /**
  1661. * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
  1662. * ParserOutput object, without any other metadata.
  1663. *
  1664. * @since 1.24
  1665. * @param ParserOutput $parserOutput
  1666. * @param array $poOptions Options to ParserOutput::getText()
  1667. */
  1668. public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
  1669. $this->addParserOutputText( $parserOutput, $poOptions );
  1670. $this->addModules( $parserOutput->getModules() );
  1671. $this->addModuleScripts( $parserOutput->getModuleScripts() );
  1672. $this->addModuleStyles( $parserOutput->getModuleStyles() );
  1673. $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
  1674. }
  1675. /**
  1676. * Add the HTML associated with a ParserOutput object, without any metadata.
  1677. *
  1678. * @since 1.24
  1679. * @param ParserOutput $parserOutput
  1680. * @param array $poOptions Options to ParserOutput::getText()
  1681. */
  1682. public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
  1683. $text = $parserOutput->getText( $poOptions );
  1684. // Avoid PHP 7.1 warning of passing $this by reference
  1685. $outputPage = $this;
  1686. Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
  1687. $this->addHTML( $text );
  1688. }
  1689. /**
  1690. * Add everything from a ParserOutput object.
  1691. *
  1692. * @param ParserOutput $parserOutput
  1693. * @param array $poOptions Options to ParserOutput::getText()
  1694. */
  1695. function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
  1696. $this->addParserOutputMetadata( $parserOutput );
  1697. $this->addParserOutputText( $parserOutput, $poOptions );
  1698. }
  1699. /**
  1700. * Add the output of a QuickTemplate to the output buffer
  1701. *
  1702. * @param QuickTemplate &$template
  1703. */
  1704. public function addTemplate( &$template ) {
  1705. $this->addHTML( $template->getHTML() );
  1706. }
  1707. /**
  1708. * Parse wikitext and return the HTML.
  1709. *
  1710. * @param string $text
  1711. * @param bool $linestart Is this the start of a line?
  1712. * @param bool $interface Use interface language (instead of content language) while parsing
  1713. * language sensitive magic words like GRAMMAR and PLURAL. This also disables
  1714. * LanguageConverter.
  1715. * @param Language|null $language Target language object, will override $interface
  1716. * @throws MWException
  1717. * @return string HTML
  1718. */
  1719. public function parse( $text, $linestart = true, $interface = false, $language = null ) {
  1720. global $wgParser;
  1721. if ( is_null( $this->getTitle() ) ) {
  1722. throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
  1723. }
  1724. $popts = $this->parserOptions();
  1725. if ( $interface ) {
  1726. $popts->setInterfaceMessage( true );
  1727. }
  1728. if ( $language !== null ) {
  1729. $oldLang = $popts->setTargetLanguage( $language );
  1730. }
  1731. $parserOutput = $wgParser->getFreshParser()->parse(
  1732. $text, $this->getTitle(), $popts,
  1733. $linestart, true, $this->mRevisionId
  1734. );
  1735. if ( $interface ) {
  1736. $popts->setInterfaceMessage( false );
  1737. }
  1738. if ( $language !== null ) {
  1739. $popts->setTargetLanguage( $oldLang );
  1740. }
  1741. return $parserOutput->getText( [
  1742. 'enableSectionEditLinks' => false,
  1743. ] );
  1744. }
  1745. /**
  1746. * Parse wikitext, strip paragraphs, and return the HTML.
  1747. *
  1748. * @param string $text
  1749. * @param bool $linestart Is this the start of a line?
  1750. * @param bool $interface Use interface language (instead of content language) while parsing
  1751. * language sensitive magic words like GRAMMAR and PLURAL
  1752. * @return string HTML
  1753. */
  1754. public function parseInline( $text, $linestart = true, $interface = false ) {
  1755. $parsed = $this->parse( $text, $linestart, $interface );
  1756. return Parser::stripOuterParagraph( $parsed );
  1757. }
  1758. /**
  1759. * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
  1760. *
  1761. * @param int $maxage Maximum cache time on the CDN, in seconds.
  1762. */
  1763. public function setCdnMaxage( $maxage ) {
  1764. $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
  1765. }
  1766. /**
  1767. * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
  1768. * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
  1769. * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
  1770. * $maxage.
  1771. *
  1772. * @param int $maxage Maximum cache time on the CDN, in seconds
  1773. * @since 1.27
  1774. */
  1775. public function lowerCdnMaxage( $maxage ) {
  1776. $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
  1777. $this->setCdnMaxage( $this->mCdnMaxage );
  1778. }
  1779. /**
  1780. * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
  1781. *
  1782. * This sets and returns $minTTL if $mtime is false or null. Otherwise,
  1783. * the TTL is higher the older the $mtime timestamp is. Essentially, the
  1784. * TTL is 90% of the age of the object, subject to the min and max.
  1785. *
  1786. * @param string|int|float|bool|null $mtime Last-Modified timestamp
  1787. * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
  1788. * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
  1789. * @return int TTL in seconds passed to lowerCdnMaxage() (may not be the same as the new
  1790. * s-maxage)
  1791. * @since 1.28
  1792. */
  1793. public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
  1794. $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
  1795. $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
  1796. if ( $mtime === null || $mtime === false ) {
  1797. return $minTTL; // entity does not exist
  1798. }
  1799. $age = time() - wfTimestamp( TS_UNIX, $mtime );
  1800. $adaptiveTTL = max( 0.9 * $age, $minTTL );
  1801. $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
  1802. $this->lowerCdnMaxage( (int)$adaptiveTTL );
  1803. return $adaptiveTTL;
  1804. }
  1805. /**
  1806. * Use enableClientCache(false) to force it to send nocache headers
  1807. *
  1808. * @param bool|null $state New value, or null to not set the value
  1809. *
  1810. * @return bool Old value
  1811. */
  1812. public function enableClientCache( $state ) {
  1813. return wfSetVar( $this->mEnableClientCache, $state );
  1814. }
  1815. /**
  1816. * Get the list of cookie names that will influence the cache
  1817. *
  1818. * @return array
  1819. */
  1820. function getCacheVaryCookies() {
  1821. static $cookies;
  1822. if ( $cookies === null ) {
  1823. $config = $this->getConfig();
  1824. $cookies = array_merge(
  1825. SessionManager::singleton()->getVaryCookies(),
  1826. [
  1827. 'forceHTTPS',
  1828. ],
  1829. $config->get( 'CacheVaryCookies' )
  1830. );
  1831. Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
  1832. }
  1833. return $cookies;
  1834. }
  1835. /**
  1836. * Check if the request has a cache-varying cookie header
  1837. * If it does, it's very important that we don't allow public caching
  1838. *
  1839. * @return bool
  1840. */
  1841. function haveCacheVaryCookies() {
  1842. $request = $this->getRequest();
  1843. foreach ( $this->getCacheVaryCookies() as $cookieName ) {
  1844. if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
  1845. wfDebug( __METHOD__ . ": found $cookieName\n" );
  1846. return true;
  1847. }
  1848. }
  1849. wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
  1850. return false;
  1851. }
  1852. /**
  1853. * Add an HTTP header that will influence on the cache
  1854. *
  1855. * @param string $header Header name
  1856. * @param string[]|null $option Options for the Key header. See
  1857. * https://datatracker.ietf.org/doc/draft-fielding-http-key/
  1858. * for the list of valid options.
  1859. */
  1860. public function addVaryHeader( $header, array $option = null ) {
  1861. if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
  1862. $this->mVaryHeader[$header] = [];
  1863. }
  1864. if ( !is_array( $option ) ) {
  1865. $option = [];
  1866. }
  1867. $this->mVaryHeader[$header] =
  1868. array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
  1869. }
  1870. /**
  1871. * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
  1872. * such as Accept-Encoding or Cookie
  1873. *
  1874. * @return string
  1875. */
  1876. public function getVaryHeader() {
  1877. // If we vary on cookies, let's make sure it's always included here too.
  1878. if ( $this->getCacheVaryCookies() ) {
  1879. $this->addVaryHeader( 'Cookie' );
  1880. }
  1881. foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
  1882. $this->addVaryHeader( $header, $options );
  1883. }
  1884. return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
  1885. }
  1886. /**
  1887. * Add an HTTP Link: header
  1888. *
  1889. * @param string $header Header value
  1890. */
  1891. public function addLinkHeader( $header ) {
  1892. $this->mLinkHeader[] = $header;
  1893. }
  1894. /**
  1895. * Return a Link: header. Based on the values of $mLinkHeader.
  1896. *
  1897. * @return string
  1898. */
  1899. public function getLinkHeader() {
  1900. if ( !$this->mLinkHeader ) {
  1901. return false;
  1902. }
  1903. return 'Link: ' . implode( ',', $this->mLinkHeader );
  1904. }
  1905. /**
  1906. * Get a complete Key header
  1907. *
  1908. * @return string
  1909. */
  1910. public function getKeyHeader() {
  1911. $cvCookies = $this->getCacheVaryCookies();
  1912. $cookiesOption = [];
  1913. foreach ( $cvCookies as $cookieName ) {
  1914. $cookiesOption[] = 'param=' . $cookieName;
  1915. }
  1916. $this->addVaryHeader( 'Cookie', $cookiesOption );
  1917. foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
  1918. $this->addVaryHeader( $header, $options );
  1919. }
  1920. $headers = [];
  1921. foreach ( $this->mVaryHeader as $header => $option ) {
  1922. $newheader = $header;
  1923. if ( is_array( $option ) && count( $option ) > 0 ) {
  1924. $newheader .= ';' . implode( ';', $option );
  1925. }
  1926. $headers[] = $newheader;
  1927. }
  1928. $key = 'Key: ' . implode( ',', $headers );
  1929. return $key;
  1930. }
  1931. /**
  1932. * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
  1933. *
  1934. * For example:
  1935. * /w/index.php?title=Main_page will vary based on Accept-Language; but
  1936. * /w/index.php?title=Main_page&variant=zh-cn will not.
  1937. */
  1938. private function addAcceptLanguage() {
  1939. $title = $this->getTitle();
  1940. if ( !$title instanceof Title ) {
  1941. return;
  1942. }
  1943. $lang = $title->getPageLanguage();
  1944. if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
  1945. $variants = $lang->getVariants();
  1946. $aloption = [];
  1947. foreach ( $variants as $variant ) {
  1948. if ( $variant === $lang->getCode() ) {
  1949. continue;
  1950. }
  1951. $aloption[] = "substr=$variant";
  1952. // IE and some other browsers use BCP 47 standards in their Accept-Language header,
  1953. // like "zh-CN" or "zh-Hant". We should handle these too.
  1954. $variantBCP47 = LanguageCode::bcp47( $variant );
  1955. if ( $variantBCP47 !== $variant ) {
  1956. $aloption[] = "substr=$variantBCP47";
  1957. }
  1958. }
  1959. $this->addVaryHeader( 'Accept-Language', $aloption );
  1960. }
  1961. }
  1962. /**
  1963. * Set a flag which will cause an X-Frame-Options header appropriate for
  1964. * edit pages to be sent. The header value is controlled by
  1965. * $wgEditPageFrameOptions.
  1966. *
  1967. * This is the default for special pages. If you display a CSRF-protected
  1968. * form on an ordinary view page, then you need to call this function.
  1969. *
  1970. * @param bool $enable
  1971. */
  1972. public function preventClickjacking( $enable = true ) {
  1973. $this->mPreventClickjacking = $enable;
  1974. }
  1975. /**
  1976. * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
  1977. * This can be called from pages which do not contain any CSRF-protected
  1978. * HTML form.
  1979. */
  1980. public function allowClickjacking() {
  1981. $this->mPreventClickjacking = false;
  1982. }
  1983. /**
  1984. * Get the prevent-clickjacking flag
  1985. *
  1986. * @since 1.24
  1987. * @return bool
  1988. */
  1989. public function getPreventClickjacking() {
  1990. return $this->mPreventClickjacking;
  1991. }
  1992. /**
  1993. * Get the X-Frame-Options header value (without the name part), or false
  1994. * if there isn't one. This is used by Skin to determine whether to enable
  1995. * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
  1996. *
  1997. * @return string|false
  1998. */
  1999. public function getFrameOptions() {
  2000. $config = $this->getConfig();
  2001. if ( $config->get( 'BreakFrames' ) ) {
  2002. return 'DENY';
  2003. } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
  2004. return $config->get( 'EditPageFrameOptions' );
  2005. }
  2006. return false;
  2007. }
  2008. /**
  2009. * Send cache control HTTP headers
  2010. */
  2011. public function sendCacheControl() {
  2012. $response = $this->getRequest()->response();
  2013. $config = $this->getConfig();
  2014. $this->addVaryHeader( 'Cookie' );
  2015. $this->addAcceptLanguage();
  2016. # don't serve compressed data to clients who can't handle it
  2017. # maintain different caches for logged-in users and non-logged in ones
  2018. $response->header( $this->getVaryHeader() );
  2019. if ( $config->get( 'UseKeyHeader' ) ) {
  2020. $response->header( $this->getKeyHeader() );
  2021. }
  2022. if ( $this->mEnableClientCache ) {
  2023. if (
  2024. $config->get( 'UseSquid' ) &&
  2025. !$response->hasCookies() &&
  2026. !SessionManager::getGlobalSession()->isPersistent() &&
  2027. !$this->isPrintable() &&
  2028. $this->mCdnMaxage != 0 &&
  2029. !$this->haveCacheVaryCookies()
  2030. ) {
  2031. if ( $config->get( 'UseESI' ) ) {
  2032. # We'll purge the proxy cache explicitly, but require end user agents
  2033. # to revalidate against the proxy on each visit.
  2034. # Surrogate-Control controls our CDN, Cache-Control downstream caches
  2035. wfDebug( __METHOD__ .
  2036. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
  2037. # start with a shorter timeout for initial testing
  2038. # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
  2039. $response->header(
  2040. "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
  2041. "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
  2042. );
  2043. $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
  2044. } else {
  2045. # We'll purge the proxy cache for anons explicitly, but require end user agents
  2046. # to revalidate against the proxy on each visit.
  2047. # IMPORTANT! The CDN needs to replace the Cache-Control header with
  2048. # Cache-Control: s-maxage=0, must-revalidate, max-age=0
  2049. wfDebug( __METHOD__ .
  2050. ": local proxy caching; {$this->mLastModified} **", 'private' );
  2051. # start with a shorter timeout for initial testing
  2052. # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
  2053. $response->header( "Cache-Control: " .
  2054. "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
  2055. }
  2056. } else {
  2057. # We do want clients to cache if they can, but they *must* check for updates
  2058. # on revisiting the page.
  2059. wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
  2060. $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  2061. $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
  2062. }
  2063. if ( $this->mLastModified ) {
  2064. $response->header( "Last-Modified: {$this->mLastModified}" );
  2065. }
  2066. } else {
  2067. wfDebug( __METHOD__ . ": no caching **", 'private' );
  2068. # In general, the absence of a last modified header should be enough to prevent
  2069. # the client from using its cache. We send a few other things just to make sure.
  2070. $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
  2071. $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
  2072. $response->header( 'Pragma: no-cache' );
  2073. }
  2074. }
  2075. /**
  2076. * Transfer styles and JavaScript modules from skin.
  2077. *
  2078. * @param Skin $sk to load modules for
  2079. */
  2080. public function loadSkinModules( $sk ) {
  2081. foreach ( $sk->getDefaultModules() as $group => $modules ) {
  2082. if ( $group === 'styles' ) {
  2083. foreach ( $modules as $key => $moduleMembers ) {
  2084. $this->addModuleStyles( $moduleMembers );
  2085. }
  2086. } else {
  2087. $this->addModules( $modules );
  2088. }
  2089. }
  2090. }
  2091. /**
  2092. * Finally, all the text has been munged and accumulated into
  2093. * the object, let's actually output it:
  2094. *
  2095. * @param bool $return Set to true to get the result as a string rather than sending it
  2096. * @return string|null
  2097. * @throws Exception
  2098. * @throws FatalError
  2099. * @throws MWException
  2100. */
  2101. public function output( $return = false ) {
  2102. if ( $this->mDoNothing ) {
  2103. return $return ? '' : null;
  2104. }
  2105. $response = $this->getRequest()->response();
  2106. $config = $this->getConfig();
  2107. if ( $this->mRedirect != '' ) {
  2108. # Standards require redirect URLs to be absolute
  2109. $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
  2110. $redirect = $this->mRedirect;
  2111. $code = $this->mRedirectCode;
  2112. if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
  2113. if ( $code == '301' || $code == '303' ) {
  2114. if ( !$config->get( 'DebugRedirects' ) ) {
  2115. $response->statusHeader( $code );
  2116. }
  2117. $this->mLastModified = wfTimestamp( TS_RFC2822 );
  2118. }
  2119. if ( $config->get( 'VaryOnXFP' ) ) {
  2120. $this->addVaryHeader( 'X-Forwarded-Proto' );
  2121. }
  2122. $this->sendCacheControl();
  2123. $response->header( "Content-Type: text/html; charset=utf-8" );
  2124. if ( $config->get( 'DebugRedirects' ) ) {
  2125. $url = htmlspecialchars( $redirect );
  2126. print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
  2127. print "<p>Location: <a href=\"$url\">$url</a></p>\n";
  2128. print "</body>\n</html>\n";
  2129. } else {
  2130. $response->header( 'Location: ' . $redirect );
  2131. }
  2132. }
  2133. return $return ? '' : null;
  2134. } elseif ( $this->mStatusCode ) {
  2135. $response->statusHeader( $this->mStatusCode );
  2136. }
  2137. # Buffer output; final headers may depend on later processing
  2138. ob_start();
  2139. $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
  2140. $response->header( 'Content-language: ' .
  2141. MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
  2142. if ( !$this->mArticleBodyOnly ) {
  2143. $sk = $this->getSkin();
  2144. }
  2145. $linkHeader = $this->getLinkHeader();
  2146. if ( $linkHeader ) {
  2147. $response->header( $linkHeader );
  2148. }
  2149. // Prevent framing, if requested
  2150. $frameOptions = $this->getFrameOptions();
  2151. if ( $frameOptions ) {
  2152. $response->header( "X-Frame-Options: $frameOptions" );
  2153. }
  2154. ContentSecurityPolicy::sendHeaders( $this );
  2155. if ( $this->mArticleBodyOnly ) {
  2156. echo $this->mBodytext;
  2157. } else {
  2158. // Enable safe mode if requested (T152169)
  2159. if ( $this->getRequest()->getBool( 'safemode' ) ) {
  2160. $this->disallowUserJs();
  2161. }
  2162. $sk = $this->getSkin();
  2163. $this->loadSkinModules( $sk );
  2164. MWDebug::addModules( $this );
  2165. // Avoid PHP 7.1 warning of passing $this by reference
  2166. $outputPage = $this;
  2167. // Hook that allows last minute changes to the output page, e.g.
  2168. // adding of CSS or Javascript by extensions.
  2169. Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
  2170. try {
  2171. $sk->outputPage();
  2172. } catch ( Exception $e ) {
  2173. ob_end_clean(); // bug T129657
  2174. throw $e;
  2175. }
  2176. }
  2177. try {
  2178. // This hook allows last minute changes to final overall output by modifying output buffer
  2179. Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
  2180. } catch ( Exception $e ) {
  2181. ob_end_clean(); // bug T129657
  2182. throw $e;
  2183. }
  2184. $this->sendCacheControl();
  2185. if ( $return ) {
  2186. return ob_get_clean();
  2187. } else {
  2188. ob_end_flush();
  2189. return null;
  2190. }
  2191. }
  2192. /**
  2193. * Prepare this object to display an error page; disable caching and
  2194. * indexing, clear the current text and redirect, set the page's title
  2195. * and optionally an custom HTML title (content of the "<title>" tag).
  2196. *
  2197. * @param string|Message $pageTitle Will be passed directly to setPageTitle()
  2198. * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
  2199. * optional, if not passed the "<title>" attribute will be
  2200. * based on $pageTitle
  2201. */
  2202. public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
  2203. $this->setPageTitle( $pageTitle );
  2204. if ( $htmlTitle !== false ) {
  2205. $this->setHTMLTitle( $htmlTitle );
  2206. }
  2207. $this->setRobotPolicy( 'noindex,nofollow' );
  2208. $this->setArticleRelated( false );
  2209. $this->enableClientCache( false );
  2210. $this->mRedirect = '';
  2211. $this->clearSubtitle();
  2212. $this->clearHTML();
  2213. }
  2214. /**
  2215. * Output a standard error page
  2216. *
  2217. * showErrorPage( 'titlemsg', 'pagetextmsg' );
  2218. * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
  2219. * showErrorPage( 'titlemsg', $messageObject );
  2220. * showErrorPage( $titleMessageObject, $messageObject );
  2221. *
  2222. * @param string|Message $title Message key (string) for page title, or a Message object
  2223. * @param string|Message $msg Message key (string) for page text, or a Message object
  2224. * @param array $params Message parameters; ignored if $msg is a Message object
  2225. */
  2226. public function showErrorPage( $title, $msg, $params = [] ) {
  2227. if ( !$title instanceof Message ) {
  2228. $title = $this->msg( $title );
  2229. }
  2230. $this->prepareErrorPage( $title );
  2231. if ( $msg instanceof Message ) {
  2232. if ( $params !== [] ) {
  2233. trigger_error( 'Argument ignored: $params. The message parameters argument '
  2234. . 'is discarded when the $msg argument is a Message object instead of '
  2235. . 'a string.', E_USER_NOTICE );
  2236. }
  2237. $this->addHTML( $msg->parseAsBlock() );
  2238. } else {
  2239. $this->addWikiMsgArray( $msg, $params );
  2240. }
  2241. $this->returnToMain();
  2242. }
  2243. /**
  2244. * Output a standard permission error page
  2245. *
  2246. * @param array $errors Error message keys or [key, param...] arrays
  2247. * @param string|null $action Action that was denied or null if unknown
  2248. */
  2249. public function showPermissionsErrorPage( array $errors, $action = null ) {
  2250. foreach ( $errors as $key => $error ) {
  2251. $errors[$key] = (array)$error;
  2252. }
  2253. // For some action (read, edit, create and upload), display a "login to do this action"
  2254. // error if all of the following conditions are met:
  2255. // 1. the user is not logged in
  2256. // 2. the only error is insufficient permissions (i.e. no block or something else)
  2257. // 3. the error can be avoided simply by logging in
  2258. if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
  2259. && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
  2260. && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
  2261. && ( User::groupHasPermission( 'user', $action )
  2262. || User::groupHasPermission( 'autoconfirmed', $action ) )
  2263. ) {
  2264. $displayReturnto = null;
  2265. # Due to T34276, if a user does not have read permissions,
  2266. # $this->getTitle() will just give Special:Badtitle, which is
  2267. # not especially useful as a returnto parameter. Use the title
  2268. # from the request instead, if there was one.
  2269. $request = $this->getRequest();
  2270. $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
  2271. if ( $action == 'edit' ) {
  2272. $msg = 'whitelistedittext';
  2273. $displayReturnto = $returnto;
  2274. } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
  2275. $msg = 'nocreatetext';
  2276. } elseif ( $action == 'upload' ) {
  2277. $msg = 'uploadnologintext';
  2278. } else { # Read
  2279. $msg = 'loginreqpagetext';
  2280. $displayReturnto = Title::newMainPage();
  2281. }
  2282. $query = [];
  2283. if ( $returnto ) {
  2284. $query['returnto'] = $returnto->getPrefixedText();
  2285. if ( !$request->wasPosted() ) {
  2286. $returntoquery = $request->getValues();
  2287. unset( $returntoquery['title'] );
  2288. unset( $returntoquery['returnto'] );
  2289. unset( $returntoquery['returntoquery'] );
  2290. $query['returntoquery'] = wfArrayToCgi( $returntoquery );
  2291. }
  2292. }
  2293. $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
  2294. $loginLink = $linkRenderer->makeKnownLink(
  2295. SpecialPage::getTitleFor( 'Userlogin' ),
  2296. $this->msg( 'loginreqlink' )->text(),
  2297. [],
  2298. $query
  2299. );
  2300. $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
  2301. $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
  2302. # Don't return to a page the user can't read otherwise
  2303. # we'll end up in a pointless loop
  2304. if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
  2305. $this->returnToMain( null, $displayReturnto );
  2306. }
  2307. } else {
  2308. $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
  2309. $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
  2310. }
  2311. }
  2312. /**
  2313. * Display an error page indicating that a given version of MediaWiki is
  2314. * required to use it
  2315. *
  2316. * @param mixed $version The version of MediaWiki needed to use the page
  2317. */
  2318. public function versionRequired( $version ) {
  2319. $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
  2320. $this->addWikiMsg( 'versionrequiredtext', $version );
  2321. $this->returnToMain();
  2322. }
  2323. /**
  2324. * Format a list of error messages
  2325. *
  2326. * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
  2327. * @param string|null $action Action that was denied or null if unknown
  2328. * @return string The wikitext error-messages, formatted into a list.
  2329. */
  2330. public function formatPermissionsErrorMessage( array $errors, $action = null ) {
  2331. if ( $action == null ) {
  2332. $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
  2333. } else {
  2334. $action_desc = $this->msg( "action-$action" )->plain();
  2335. $text = $this->msg(
  2336. 'permissionserrorstext-withaction',
  2337. count( $errors ),
  2338. $action_desc
  2339. )->plain() . "\n\n";
  2340. }
  2341. if ( count( $errors ) > 1 ) {
  2342. $text .= '<ul class="permissions-errors">' . "\n";
  2343. foreach ( $errors as $error ) {
  2344. $text .= '<li>';
  2345. $text .= $this->msg( ...$error )->plain();
  2346. $text .= "</li>\n";
  2347. }
  2348. $text .= '</ul>';
  2349. } else {
  2350. $text .= "<div class=\"permissions-errors\">\n" .
  2351. $this->msg( ...reset( $errors ) )->plain() .
  2352. "\n</div>";
  2353. }
  2354. return $text;
  2355. }
  2356. /**
  2357. * Show a warning about replica DB lag
  2358. *
  2359. * If the lag is higher than $wgSlaveLagCritical seconds,
  2360. * then the warning is a bit more obvious. If the lag is
  2361. * lower than $wgSlaveLagWarning, then no warning is shown.
  2362. *
  2363. * @param int $lag Slave lag
  2364. */
  2365. public function showLagWarning( $lag ) {
  2366. $config = $this->getConfig();
  2367. if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
  2368. $lag = floor( $lag ); // floor to avoid nano seconds to display
  2369. $message = $lag < $config->get( 'SlaveLagCritical' )
  2370. ? 'lag-warn-normal'
  2371. : 'lag-warn-high';
  2372. $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
  2373. $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
  2374. }
  2375. }
  2376. /**
  2377. * Output an error page
  2378. *
  2379. * @note FatalError exception class provides an alternative.
  2380. * @param string $message Error to output. Must be escaped for HTML.
  2381. */
  2382. public function showFatalError( $message ) {
  2383. $this->prepareErrorPage( $this->msg( 'internalerror' ) );
  2384. $this->addHTML( $message );
  2385. }
  2386. /**
  2387. * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
  2388. */
  2389. public function showUnexpectedValueError( $name, $val ) {
  2390. wfDeprecated( __METHOD__, '1.32' );
  2391. $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
  2392. }
  2393. /**
  2394. * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
  2395. */
  2396. public function showFileCopyError( $old, $new ) {
  2397. wfDeprecated( __METHOD__, '1.32' );
  2398. $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
  2399. }
  2400. /**
  2401. * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
  2402. */
  2403. public function showFileRenameError( $old, $new ) {
  2404. wfDeprecated( __METHOD__, '1.32' );
  2405. $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
  2406. }
  2407. /**
  2408. * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
  2409. */
  2410. public function showFileDeleteError( $name ) {
  2411. wfDeprecated( __METHOD__, '1.32' );
  2412. $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
  2413. }
  2414. /**
  2415. * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
  2416. */
  2417. public function showFileNotFoundError( $name ) {
  2418. wfDeprecated( __METHOD__, '1.32' );
  2419. $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
  2420. }
  2421. /**
  2422. * Add a "return to" link pointing to a specified title
  2423. *
  2424. * @param Title $title Title to link
  2425. * @param array $query Query string parameters
  2426. * @param string|null $text Text of the link (input is not escaped)
  2427. * @param array $options Options array to pass to Linker
  2428. */
  2429. public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
  2430. $linkRenderer = MediaWikiServices::getInstance()
  2431. ->getLinkRendererFactory()->createFromLegacyOptions( $options );
  2432. $link = $this->msg( 'returnto' )->rawParams(
  2433. $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
  2434. $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
  2435. }
  2436. /**
  2437. * Add a "return to" link pointing to a specified title,
  2438. * or the title indicated in the request, or else the main page
  2439. *
  2440. * @param mixed|null $unused
  2441. * @param Title|string|null $returnto Title or String to return to
  2442. * @param string|null $returntoquery Query string for the return to link
  2443. */
  2444. public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
  2445. if ( $returnto == null ) {
  2446. $returnto = $this->getRequest()->getText( 'returnto' );
  2447. }
  2448. if ( $returntoquery == null ) {
  2449. $returntoquery = $this->getRequest()->getText( 'returntoquery' );
  2450. }
  2451. if ( $returnto === '' ) {
  2452. $returnto = Title::newMainPage();
  2453. }
  2454. if ( is_object( $returnto ) ) {
  2455. $titleObj = $returnto;
  2456. } else {
  2457. $titleObj = Title::newFromText( $returnto );
  2458. }
  2459. // We don't want people to return to external interwiki. That
  2460. // might potentially be used as part of a phishing scheme
  2461. if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
  2462. $titleObj = Title::newMainPage();
  2463. }
  2464. $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
  2465. }
  2466. private function getRlClientContext() {
  2467. if ( !$this->rlClientContext ) {
  2468. $query = ResourceLoader::makeLoaderQuery(
  2469. [], // modules; not relevant
  2470. $this->getLanguage()->getCode(),
  2471. $this->getSkin()->getSkinName(),
  2472. $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
  2473. null, // version; not relevant
  2474. ResourceLoader::inDebugMode(),
  2475. null, // only; not relevant
  2476. $this->isPrintable(),
  2477. $this->getRequest()->getBool( 'handheld' )
  2478. );
  2479. $this->rlClientContext = new ResourceLoaderContext(
  2480. $this->getResourceLoader(),
  2481. new FauxRequest( $query )
  2482. );
  2483. if ( $this->contentOverrideCallbacks ) {
  2484. $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
  2485. $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
  2486. foreach ( $this->contentOverrideCallbacks as $callback ) {
  2487. $content = $callback( $title );
  2488. if ( $content !== null ) {
  2489. $text = ContentHandler::getContentText( $content );
  2490. if ( strpos( $text, '</script>' ) !== false ) {
  2491. // Proactively replace this so that we can display a message
  2492. // to the user, instead of letting it go to Html::inlineScript(),
  2493. // where it would be considered a server-side issue.
  2494. $titleFormatted = $title->getPrefixedText();
  2495. $content = new JavaScriptContent(
  2496. Xml::encodeJsCall( 'mw.log.error', [
  2497. "Cannot preview $titleFormatted due to script-closing tag."
  2498. ] )
  2499. );
  2500. }
  2501. return $content;
  2502. }
  2503. }
  2504. return null;
  2505. } );
  2506. }
  2507. }
  2508. return $this->rlClientContext;
  2509. }
  2510. /**
  2511. * Call this to freeze the module queue and JS config and create a formatter.
  2512. *
  2513. * Depending on the Skin, this may get lazy-initialised in either headElement() or
  2514. * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
  2515. * cause unexpected side-effects since disallowUserJs() may be called at any time to change
  2516. * the module filters retroactively. Skins and extension hooks may also add modules until very
  2517. * late in the request lifecycle.
  2518. *
  2519. * @return ResourceLoaderClientHtml
  2520. */
  2521. public function getRlClient() {
  2522. if ( !$this->rlClient ) {
  2523. $context = $this->getRlClientContext();
  2524. $rl = $this->getResourceLoader();
  2525. $this->addModules( [
  2526. 'user',
  2527. 'user.options',
  2528. 'user.tokens',
  2529. ] );
  2530. $this->addModuleStyles( [
  2531. 'site.styles',
  2532. 'noscript',
  2533. 'user.styles',
  2534. ] );
  2535. $this->getSkin()->setupSkinUserCss( $this );
  2536. // Prepare exempt modules for buildExemptModules()
  2537. $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
  2538. $exemptStates = [];
  2539. $moduleStyles = $this->getModuleStyles( /*filter*/ true );
  2540. // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
  2541. // Separate user-specific batch for improved cache-hit ratio.
  2542. $userBatch = [ 'user.styles', 'user' ];
  2543. $siteBatch = array_diff( $moduleStyles, $userBatch );
  2544. $dbr = wfGetDB( DB_REPLICA );
  2545. ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
  2546. ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
  2547. // Filter out modules handled by buildExemptModules()
  2548. $moduleStyles = array_filter( $moduleStyles,
  2549. function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
  2550. $module = $rl->getModule( $name );
  2551. if ( $module ) {
  2552. $group = $module->getGroup();
  2553. if ( isset( $exemptGroups[$group] ) ) {
  2554. $exemptStates[$name] = 'ready';
  2555. if ( !$module->isKnownEmpty( $context ) ) {
  2556. // E.g. Don't output empty <styles>
  2557. $exemptGroups[$group][] = $name;
  2558. }
  2559. return false;
  2560. }
  2561. }
  2562. return true;
  2563. }
  2564. );
  2565. $this->rlExemptStyleModules = $exemptGroups;
  2566. $rlClient = new ResourceLoaderClientHtml( $context, [
  2567. 'target' => $this->getTarget(),
  2568. 'nonce' => $this->getCSPNonce(),
  2569. // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
  2570. // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
  2571. // modules enqueud for loading on this page is filtered to just those.
  2572. // However, to make sure we also apply the restriction to dynamic dependencies and
  2573. // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
  2574. // StartupModule so that the client-side registry will not contain any restricted
  2575. // modules either. (T152169, T185303)
  2576. 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
  2577. <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
  2578. ) ? '1' : null,
  2579. ] );
  2580. $rlClient->setConfig( $this->getJSVars() );
  2581. $rlClient->setModules( $this->getModules( /*filter*/ true ) );
  2582. $rlClient->setModuleStyles( $moduleStyles );
  2583. $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
  2584. $rlClient->setExemptStates( $exemptStates );
  2585. $this->rlClient = $rlClient;
  2586. }
  2587. return $this->rlClient;
  2588. }
  2589. /**
  2590. * @param Skin $sk The given Skin
  2591. * @param bool $includeStyle Unused
  2592. * @return string The doctype, opening "<html>", and head element.
  2593. */
  2594. public function headElement( Skin $sk, $includeStyle = true ) {
  2595. $userdir = $this->getLanguage()->getDir();
  2596. $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
  2597. $pieces = [];
  2598. $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
  2599. $this->getRlClient()->getDocumentAttributes(),
  2600. $sk->getHtmlElementAttributes()
  2601. ) );
  2602. $pieces[] = Html::openElement( 'head' );
  2603. if ( $this->getHTMLTitle() == '' ) {
  2604. $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
  2605. }
  2606. if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
  2607. // Add <meta charset="UTF-8">
  2608. // This should be before <title> since it defines the charset used by
  2609. // text including the text inside <title>.
  2610. // The spec recommends defining XHTML5's charset using the XML declaration
  2611. // instead of meta.
  2612. // Our XML declaration is output by Html::htmlHeader.
  2613. // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
  2614. // https://html.spec.whatwg.org/multipage/semantics.html#charset
  2615. $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
  2616. }
  2617. $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
  2618. $pieces[] = $this->getRlClient()->getHeadHtml();
  2619. $pieces[] = $this->buildExemptModules();
  2620. $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
  2621. $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
  2622. // Use an IE conditional comment to serve the script only to old IE
  2623. $pieces[] = '<!--[if lt IE 9]>' .
  2624. ResourceLoaderClientHtml::makeLoad(
  2625. ResourceLoaderContext::newDummyContext(),
  2626. [ 'html5shiv' ],
  2627. ResourceLoaderModule::TYPE_SCRIPTS,
  2628. [ 'sync' => true ],
  2629. $this->getCSPNonce()
  2630. ) .
  2631. '<![endif]-->';
  2632. $pieces[] = Html::closeElement( 'head' );
  2633. $bodyClasses = $this->mAdditionalBodyClasses;
  2634. $bodyClasses[] = 'mediawiki';
  2635. # Classes for LTR/RTL directionality support
  2636. $bodyClasses[] = $userdir;
  2637. $bodyClasses[] = "sitedir-$sitedir";
  2638. $underline = $this->getUser()->getOption( 'underline' );
  2639. if ( $underline < 2 ) {
  2640. // The following classes can be used here:
  2641. // * mw-underline-always
  2642. // * mw-underline-never
  2643. $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
  2644. }
  2645. if ( $this->getLanguage()->capitalizeAllNouns() ) {
  2646. # A <body> class is probably not the best way to do this . . .
  2647. $bodyClasses[] = 'capitalize-all-nouns';
  2648. }
  2649. // Parser feature migration class
  2650. // The idea is that this will eventually be removed, after the wikitext
  2651. // which requires it is cleaned up.
  2652. $bodyClasses[] = 'mw-hide-empty-elt';
  2653. $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
  2654. $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
  2655. $bodyClasses[] =
  2656. 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
  2657. $bodyAttrs = [];
  2658. // While the implode() is not strictly needed, it's used for backwards compatibility
  2659. // (this used to be built as a string and hooks likely still expect that).
  2660. $bodyAttrs['class'] = implode( ' ', $bodyClasses );
  2661. // Allow skins and extensions to add body attributes they need
  2662. $sk->addToBodyAttributes( $this, $bodyAttrs );
  2663. Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
  2664. $pieces[] = Html::openElement( 'body', $bodyAttrs );
  2665. return self::combineWrappedStrings( $pieces );
  2666. }
  2667. /**
  2668. * Get a ResourceLoader object associated with this OutputPage
  2669. *
  2670. * @return ResourceLoader
  2671. */
  2672. public function getResourceLoader() {
  2673. if ( is_null( $this->mResourceLoader ) ) {
  2674. $this->mResourceLoader = new ResourceLoader(
  2675. $this->getConfig(),
  2676. LoggerFactory::getInstance( 'resourceloader' )
  2677. );
  2678. }
  2679. return $this->mResourceLoader;
  2680. }
  2681. /**
  2682. * Explicily load or embed modules on a page.
  2683. *
  2684. * @param array|string $modules One or more module names
  2685. * @param string $only ResourceLoaderModule TYPE_ class constant
  2686. * @param array $extraQuery [optional] Array with extra query parameters for the request
  2687. * @return string|WrappedStringList HTML
  2688. */
  2689. public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
  2690. // Apply 'target' and 'origin' filters
  2691. $modules = $this->filterModules( (array)$modules, null, $only );
  2692. return ResourceLoaderClientHtml::makeLoad(
  2693. $this->getRlClientContext(),
  2694. $modules,
  2695. $only,
  2696. $extraQuery,
  2697. $this->getCSPNonce()
  2698. );
  2699. }
  2700. /**
  2701. * Combine WrappedString chunks and filter out empty ones
  2702. *
  2703. * @param array $chunks
  2704. * @return string|WrappedStringList HTML
  2705. */
  2706. protected static function combineWrappedStrings( array $chunks ) {
  2707. // Filter out empty values
  2708. $chunks = array_filter( $chunks, 'strlen' );
  2709. return WrappedString::join( "\n", $chunks );
  2710. }
  2711. /**
  2712. * JS stuff to put at the bottom of the `<body>`.
  2713. * These are legacy scripts ($this->mScripts), and user JS.
  2714. *
  2715. * @return string|WrappedStringList HTML
  2716. */
  2717. public function getBottomScripts() {
  2718. $chunks = [];
  2719. $chunks[] = $this->getRlClient()->getBodyHtml();
  2720. // Legacy non-ResourceLoader scripts
  2721. $chunks[] = $this->mScripts;
  2722. if ( $this->limitReportJSData ) {
  2723. $chunks[] = ResourceLoader::makeInlineScript(
  2724. ResourceLoader::makeConfigSetScript(
  2725. [ 'wgPageParseReport' => $this->limitReportJSData ]
  2726. ),
  2727. $this->getCSPNonce()
  2728. );
  2729. }
  2730. return self::combineWrappedStrings( $chunks );
  2731. }
  2732. /**
  2733. * Get the javascript config vars to include on this page
  2734. *
  2735. * @return array Array of javascript config vars
  2736. * @since 1.23
  2737. */
  2738. public function getJsConfigVars() {
  2739. return $this->mJsConfigVars;
  2740. }
  2741. /**
  2742. * Add one or more variables to be set in mw.config in JavaScript
  2743. *
  2744. * @param string|array $keys Key or array of key/value pairs
  2745. * @param mixed|null $value [optional] Value of the configuration variable
  2746. */
  2747. public function addJsConfigVars( $keys, $value = null ) {
  2748. if ( is_array( $keys ) ) {
  2749. foreach ( $keys as $key => $value ) {
  2750. $this->mJsConfigVars[$key] = $value;
  2751. }
  2752. return;
  2753. }
  2754. $this->mJsConfigVars[$keys] = $value;
  2755. }
  2756. /**
  2757. * Get an array containing the variables to be set in mw.config in JavaScript.
  2758. *
  2759. * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
  2760. * - in other words, page-independent/site-wide variables (without state).
  2761. * You will only be adding bloat to the html page and causing page caches to
  2762. * have to be purged on configuration changes.
  2763. * @return array
  2764. */
  2765. public function getJSVars() {
  2766. $curRevisionId = 0;
  2767. $articleId = 0;
  2768. $canonicalSpecialPageName = false; # T23115
  2769. $services = MediaWikiServices::getInstance();
  2770. $title = $this->getTitle();
  2771. $ns = $title->getNamespace();
  2772. $canonicalNamespace = MWNamespace::exists( $ns )
  2773. ? MWNamespace::getCanonicalName( $ns )
  2774. : $title->getNsText();
  2775. $sk = $this->getSkin();
  2776. // Get the relevant title so that AJAX features can use the correct page name
  2777. // when making API requests from certain special pages (T36972).
  2778. $relevantTitle = $sk->getRelevantTitle();
  2779. $relevantUser = $sk->getRelevantUser();
  2780. if ( $ns == NS_SPECIAL ) {
  2781. list( $canonicalSpecialPageName, /*...*/ ) =
  2782. $services->getSpecialPageFactory()->
  2783. resolveAlias( $title->getDBkey() );
  2784. } elseif ( $this->canUseWikiPage() ) {
  2785. $wikiPage = $this->getWikiPage();
  2786. $curRevisionId = $wikiPage->getLatest();
  2787. $articleId = $wikiPage->getId();
  2788. }
  2789. $lang = $title->getPageViewLanguage();
  2790. // Pre-process information
  2791. $separatorTransTable = $lang->separatorTransformTable();
  2792. $separatorTransTable = $separatorTransTable ?: [];
  2793. $compactSeparatorTransTable = [
  2794. implode( "\t", array_keys( $separatorTransTable ) ),
  2795. implode( "\t", $separatorTransTable ),
  2796. ];
  2797. $digitTransTable = $lang->digitTransformTable();
  2798. $digitTransTable = $digitTransTable ?: [];
  2799. $compactDigitTransTable = [
  2800. implode( "\t", array_keys( $digitTransTable ) ),
  2801. implode( "\t", $digitTransTable ),
  2802. ];
  2803. $user = $this->getUser();
  2804. $vars = [
  2805. 'wgCanonicalNamespace' => $canonicalNamespace,
  2806. 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
  2807. 'wgNamespaceNumber' => $title->getNamespace(),
  2808. 'wgPageName' => $title->getPrefixedDBkey(),
  2809. 'wgTitle' => $title->getText(),
  2810. 'wgCurRevisionId' => $curRevisionId,
  2811. 'wgRevisionId' => (int)$this->getRevisionId(),
  2812. 'wgArticleId' => $articleId,
  2813. 'wgIsArticle' => $this->isArticle(),
  2814. 'wgIsRedirect' => $title->isRedirect(),
  2815. 'wgAction' => Action::getActionName( $this->getContext() ),
  2816. 'wgUserName' => $user->isAnon() ? null : $user->getName(),
  2817. 'wgUserGroups' => $user->getEffectiveGroups(),
  2818. 'wgCategories' => $this->getCategories(),
  2819. 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
  2820. 'wgPageContentLanguage' => $lang->getCode(),
  2821. 'wgPageContentModel' => $title->getContentModel(),
  2822. 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
  2823. 'wgDigitTransformTable' => $compactDigitTransTable,
  2824. 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
  2825. 'wgMonthNames' => $lang->getMonthNamesArray(),
  2826. 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
  2827. 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
  2828. 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
  2829. 'wgRequestId' => WebRequest::getRequestId(),
  2830. 'wgCSPNonce' => $this->getCSPNonce(),
  2831. ];
  2832. if ( $user->isLoggedIn() ) {
  2833. $vars['wgUserId'] = $user->getId();
  2834. $vars['wgUserEditCount'] = $user->getEditCount();
  2835. $userReg = $user->getRegistration();
  2836. $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
  2837. // Get the revision ID of the oldest new message on the user's talk
  2838. // page. This can be used for constructing new message alerts on
  2839. // the client side.
  2840. $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
  2841. }
  2842. $contLang = $services->getContentLanguage();
  2843. if ( $contLang->hasVariants() ) {
  2844. $vars['wgUserVariant'] = $contLang->getPreferredVariant();
  2845. }
  2846. // Same test as SkinTemplate
  2847. $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
  2848. && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
  2849. $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
  2850. && $relevantTitle->quickUserCan( 'edit', $user )
  2851. && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
  2852. foreach ( $title->getRestrictionTypes() as $type ) {
  2853. // Following keys are set in $vars:
  2854. // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
  2855. $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
  2856. }
  2857. if ( $title->isMainPage() ) {
  2858. $vars['wgIsMainPage'] = true;
  2859. }
  2860. if ( $this->mRedirectedFrom ) {
  2861. $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
  2862. }
  2863. if ( $relevantUser ) {
  2864. $vars['wgRelevantUserName'] = $relevantUser->getName();
  2865. }
  2866. // Allow extensions to add their custom variables to the mw.config map.
  2867. // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
  2868. // page-dependant but site-wide (without state).
  2869. // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
  2870. Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
  2871. // Merge in variables from addJsConfigVars last
  2872. return array_merge( $vars, $this->getJsConfigVars() );
  2873. }
  2874. /**
  2875. * To make it harder for someone to slip a user a fake
  2876. * JavaScript or CSS preview, a random token
  2877. * is associated with the login session. If it's not
  2878. * passed back with the preview request, we won't render
  2879. * the code.
  2880. *
  2881. * @return bool
  2882. */
  2883. public function userCanPreview() {
  2884. $request = $this->getRequest();
  2885. if (
  2886. $request->getVal( 'action' ) !== 'submit' ||
  2887. !$request->wasPosted()
  2888. ) {
  2889. return false;
  2890. }
  2891. $user = $this->getUser();
  2892. if ( !$user->isLoggedIn() ) {
  2893. // Anons have predictable edit tokens
  2894. return false;
  2895. }
  2896. if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
  2897. return false;
  2898. }
  2899. $title = $this->getTitle();
  2900. $errors = $title->getUserPermissionsErrors( 'edit', $user );
  2901. if ( count( $errors ) !== 0 ) {
  2902. return false;
  2903. }
  2904. return true;
  2905. }
  2906. /**
  2907. * @return array Array in format "link name or number => 'link html'".
  2908. */
  2909. public function getHeadLinksArray() {
  2910. global $wgVersion;
  2911. $tags = [];
  2912. $config = $this->getConfig();
  2913. $canonicalUrl = $this->mCanonicalUrl;
  2914. $tags['meta-generator'] = Html::element( 'meta', [
  2915. 'name' => 'generator',
  2916. 'content' => "MediaWiki $wgVersion",
  2917. ] );
  2918. if ( $config->get( 'ReferrerPolicy' ) !== false ) {
  2919. // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
  2920. // fallbacks should come before the primary value so we need to reverse the array.
  2921. foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
  2922. $tags["meta-referrer-$i"] = Html::element( 'meta', [
  2923. 'name' => 'referrer',
  2924. 'content' => $policy,
  2925. ] );
  2926. }
  2927. }
  2928. $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
  2929. if ( $p !== 'index,follow' ) {
  2930. // http://www.robotstxt.org/wc/meta-user.html
  2931. // Only show if it's different from the default robots policy
  2932. $tags['meta-robots'] = Html::element( 'meta', [
  2933. 'name' => 'robots',
  2934. 'content' => $p,
  2935. ] );
  2936. }
  2937. foreach ( $this->mMetatags as $tag ) {
  2938. if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
  2939. $a = 'http-equiv';
  2940. $tag[0] = substr( $tag[0], 5 );
  2941. } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
  2942. $a = 'property';
  2943. } else {
  2944. $a = 'name';
  2945. }
  2946. $tagName = "meta-{$tag[0]}";
  2947. if ( isset( $tags[$tagName] ) ) {
  2948. $tagName .= $tag[1];
  2949. }
  2950. $tags[$tagName] = Html::element( 'meta',
  2951. [
  2952. $a => $tag[0],
  2953. 'content' => $tag[1]
  2954. ]
  2955. );
  2956. }
  2957. foreach ( $this->mLinktags as $tag ) {
  2958. $tags[] = Html::element( 'link', $tag );
  2959. }
  2960. # Universal edit button
  2961. if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
  2962. $user = $this->getUser();
  2963. if ( $this->getTitle()->quickUserCan( 'edit', $user )
  2964. && ( $this->getTitle()->exists() ||
  2965. $this->getTitle()->quickUserCan( 'create', $user ) )
  2966. ) {
  2967. // Original UniversalEditButton
  2968. $msg = $this->msg( 'edit' )->text();
  2969. $tags['universal-edit-button'] = Html::element( 'link', [
  2970. 'rel' => 'alternate',
  2971. 'type' => 'application/x-wiki',
  2972. 'title' => $msg,
  2973. 'href' => $this->getTitle()->getEditURL(),
  2974. ] );
  2975. // Alternate edit link
  2976. $tags['alternative-edit'] = Html::element( 'link', [
  2977. 'rel' => 'edit',
  2978. 'title' => $msg,
  2979. 'href' => $this->getTitle()->getEditURL(),
  2980. ] );
  2981. }
  2982. }
  2983. # Generally the order of the favicon and apple-touch-icon links
  2984. # should not matter, but Konqueror (3.5.9 at least) incorrectly
  2985. # uses whichever one appears later in the HTML source. Make sure
  2986. # apple-touch-icon is specified first to avoid this.
  2987. if ( $config->get( 'AppleTouchIcon' ) !== false ) {
  2988. $tags['apple-touch-icon'] = Html::element( 'link', [
  2989. 'rel' => 'apple-touch-icon',
  2990. 'href' => $config->get( 'AppleTouchIcon' )
  2991. ] );
  2992. }
  2993. if ( $config->get( 'Favicon' ) !== false ) {
  2994. $tags['favicon'] = Html::element( 'link', [
  2995. 'rel' => 'shortcut icon',
  2996. 'href' => $config->get( 'Favicon' )
  2997. ] );
  2998. }
  2999. # OpenSearch description link
  3000. $tags['opensearch'] = Html::element( 'link', [
  3001. 'rel' => 'search',
  3002. 'type' => 'application/opensearchdescription+xml',
  3003. 'href' => wfScript( 'opensearch_desc' ),
  3004. 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
  3005. ] );
  3006. # Real Simple Discovery link, provides auto-discovery information
  3007. # for the MediaWiki API (and potentially additional custom API
  3008. # support such as WordPress or Twitter-compatible APIs for a
  3009. # blogging extension, etc)
  3010. $tags['rsd'] = Html::element( 'link', [
  3011. 'rel' => 'EditURI',
  3012. 'type' => 'application/rsd+xml',
  3013. // Output a protocol-relative URL here if $wgServer is protocol-relative.
  3014. // Whether RSD accepts relative or protocol-relative URLs is completely
  3015. // undocumented, though.
  3016. 'href' => wfExpandUrl( wfAppendQuery(
  3017. wfScript( 'api' ),
  3018. [ 'action' => 'rsd' ] ),
  3019. PROTO_RELATIVE
  3020. ),
  3021. ] );
  3022. # Language variants
  3023. if ( !$config->get( 'DisableLangConversion' ) ) {
  3024. $lang = $this->getTitle()->getPageLanguage();
  3025. if ( $lang->hasVariants() ) {
  3026. $variants = $lang->getVariants();
  3027. foreach ( $variants as $variant ) {
  3028. $tags["variant-$variant"] = Html::element( 'link', [
  3029. 'rel' => 'alternate',
  3030. 'hreflang' => LanguageCode::bcp47( $variant ),
  3031. 'href' => $this->getTitle()->getLocalURL(
  3032. [ 'variant' => $variant ] )
  3033. ]
  3034. );
  3035. }
  3036. # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
  3037. $tags["variant-x-default"] = Html::element( 'link', [
  3038. 'rel' => 'alternate',
  3039. 'hreflang' => 'x-default',
  3040. 'href' => $this->getTitle()->getLocalURL() ] );
  3041. }
  3042. }
  3043. # Copyright
  3044. if ( $this->copyrightUrl !== null ) {
  3045. $copyright = $this->copyrightUrl;
  3046. } else {
  3047. $copyright = '';
  3048. if ( $config->get( 'RightsPage' ) ) {
  3049. $copy = Title::newFromText( $config->get( 'RightsPage' ) );
  3050. if ( $copy ) {
  3051. $copyright = $copy->getLocalURL();
  3052. }
  3053. }
  3054. if ( !$copyright && $config->get( 'RightsUrl' ) ) {
  3055. $copyright = $config->get( 'RightsUrl' );
  3056. }
  3057. }
  3058. if ( $copyright ) {
  3059. $tags['copyright'] = Html::element( 'link', [
  3060. 'rel' => 'license',
  3061. 'href' => $copyright ]
  3062. );
  3063. }
  3064. # Feeds
  3065. if ( $config->get( 'Feed' ) ) {
  3066. $feedLinks = [];
  3067. foreach ( $this->getSyndicationLinks() as $format => $link ) {
  3068. # Use the page name for the title. In principle, this could
  3069. # lead to issues with having the same name for different feeds
  3070. # corresponding to the same page, but we can't avoid that at
  3071. # this low a level.
  3072. $feedLinks[] = $this->feedLink(
  3073. $format,
  3074. $link,
  3075. # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
  3076. $this->msg(
  3077. "page-{$format}-feed", $this->getTitle()->getPrefixedText()
  3078. )->text()
  3079. );
  3080. }
  3081. # Recent changes feed should appear on every page (except recentchanges,
  3082. # that would be redundant). Put it after the per-page feed to avoid
  3083. # changing existing behavior. It's still available, probably via a
  3084. # menu in your browser. Some sites might have a different feed they'd
  3085. # like to promote instead of the RC feed (maybe like a "Recent New Articles"
  3086. # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
  3087. # If so, use it instead.
  3088. $sitename = $config->get( 'Sitename' );
  3089. if ( $config->get( 'OverrideSiteFeed' ) ) {
  3090. foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
  3091. // Note, this->feedLink escapes the url.
  3092. $feedLinks[] = $this->feedLink(
  3093. $type,
  3094. $feedUrl,
  3095. $this->msg( "site-{$type}-feed", $sitename )->text()
  3096. );
  3097. }
  3098. } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
  3099. $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
  3100. foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
  3101. $feedLinks[] = $this->feedLink(
  3102. $format,
  3103. $rctitle->getLocalURL( [ 'feed' => $format ] ),
  3104. # For grep: 'site-rss-feed', 'site-atom-feed'
  3105. $this->msg( "site-{$format}-feed", $sitename )->text()
  3106. );
  3107. }
  3108. }
  3109. # Allow extensions to change the list pf feeds. This hook is primarily for changing,
  3110. # manipulating or removing existing feed tags. If you want to add new feeds, you should
  3111. # use OutputPage::addFeedLink() instead.
  3112. Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
  3113. $tags += $feedLinks;
  3114. }
  3115. # Canonical URL
  3116. if ( $config->get( 'EnableCanonicalServerLink' ) ) {
  3117. if ( $canonicalUrl !== false ) {
  3118. $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
  3119. } else {
  3120. if ( $this->isArticleRelated() ) {
  3121. // This affects all requests where "setArticleRelated" is true. This is
  3122. // typically all requests that show content (query title, curid, oldid, diff),
  3123. // and all wikipage actions (edit, delete, purge, info, history etc.).
  3124. // It does not apply to File pages and Special pages.
  3125. // 'history' and 'info' actions address page metadata rather than the page
  3126. // content itself, so they may not be canonicalized to the view page url.
  3127. // TODO: this ought to be better encapsulated in the Action class.
  3128. $action = Action::getActionName( $this->getContext() );
  3129. if ( in_array( $action, [ 'history', 'info' ] ) ) {
  3130. $query = "action={$action}";
  3131. } else {
  3132. $query = '';
  3133. }
  3134. $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
  3135. } else {
  3136. $reqUrl = $this->getRequest()->getRequestURL();
  3137. $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
  3138. }
  3139. }
  3140. }
  3141. if ( $canonicalUrl !== false ) {
  3142. $tags[] = Html::element( 'link', [
  3143. 'rel' => 'canonical',
  3144. 'href' => $canonicalUrl
  3145. ] );
  3146. }
  3147. // Allow extensions to add, remove and/or otherwise manipulate these links
  3148. // If you want only to *add* <head> links, please use the addHeadItem()
  3149. // (or addHeadItems() for multiple items) method instead.
  3150. // This hook is provided as a last resort for extensions to modify these
  3151. // links before the output is sent to client.
  3152. Hooks::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
  3153. return $tags;
  3154. }
  3155. /**
  3156. * Generate a "<link rel/>" for a feed.
  3157. *
  3158. * @param string $type Feed type
  3159. * @param string $url URL to the feed
  3160. * @param string $text Value of the "title" attribute
  3161. * @return string HTML fragment
  3162. */
  3163. private function feedLink( $type, $url, $text ) {
  3164. return Html::element( 'link', [
  3165. 'rel' => 'alternate',
  3166. 'type' => "application/$type+xml",
  3167. 'title' => $text,
  3168. 'href' => $url ]
  3169. );
  3170. }
  3171. /**
  3172. * Add a local or specified stylesheet, with the given media options.
  3173. * Internal use only. Use OutputPage::addModuleStyles() if possible.
  3174. *
  3175. * @param string $style URL to the file
  3176. * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
  3177. * @param string $condition For IE conditional comments, specifying an IE version
  3178. * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
  3179. */
  3180. public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
  3181. $options = [];
  3182. if ( $media ) {
  3183. $options['media'] = $media;
  3184. }
  3185. if ( $condition ) {
  3186. $options['condition'] = $condition;
  3187. }
  3188. if ( $dir ) {
  3189. $options['dir'] = $dir;
  3190. }
  3191. $this->styles[$style] = $options;
  3192. }
  3193. /**
  3194. * Adds inline CSS styles
  3195. * Internal use only. Use OutputPage::addModuleStyles() if possible.
  3196. *
  3197. * @param mixed $style_css Inline CSS
  3198. * @param string $flip Set to 'flip' to flip the CSS if needed
  3199. */
  3200. public function addInlineStyle( $style_css, $flip = 'noflip' ) {
  3201. if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
  3202. # If wanted, and the interface is right-to-left, flip the CSS
  3203. $style_css = CSSJanus::transform( $style_css, true, false );
  3204. }
  3205. $this->mInlineStyles .= Html::inlineStyle( $style_css );
  3206. }
  3207. /**
  3208. * Build exempt modules and legacy non-ResourceLoader styles.
  3209. *
  3210. * @return string|WrappedStringList HTML
  3211. */
  3212. protected function buildExemptModules() {
  3213. $chunks = [];
  3214. // Things that go after the ResourceLoaderDynamicStyles marker
  3215. $append = [];
  3216. // We want site, private and user styles to override dynamically added styles from
  3217. // general modules, but we want dynamically added styles to override statically added
  3218. // style modules. So the order has to be:
  3219. // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
  3220. // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
  3221. // - ResourceLoaderDynamicStyles marker
  3222. // - site/private/user styles
  3223. // Add legacy styles added through addStyle()/addInlineStyle() here
  3224. $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
  3225. $chunks[] = Html::element(
  3226. 'meta',
  3227. [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
  3228. );
  3229. $separateReq = [ 'site.styles', 'user.styles' ];
  3230. foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
  3231. // Combinable modules
  3232. $chunks[] = $this->makeResourceLoaderLink(
  3233. array_diff( $moduleNames, $separateReq ),
  3234. ResourceLoaderModule::TYPE_STYLES
  3235. );
  3236. foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
  3237. // These require their own dedicated request in order to support "@import"
  3238. // syntax, which is incompatible with concatenation. (T147667, T37562)
  3239. $chunks[] = $this->makeResourceLoaderLink( $name,
  3240. ResourceLoaderModule::TYPE_STYLES
  3241. );
  3242. }
  3243. }
  3244. return self::combineWrappedStrings( array_merge( $chunks, $append ) );
  3245. }
  3246. /**
  3247. * @return array
  3248. */
  3249. public function buildCssLinksArray() {
  3250. $links = [];
  3251. foreach ( $this->styles as $file => $options ) {
  3252. $link = $this->styleLink( $file, $options );
  3253. if ( $link ) {
  3254. $links[$file] = $link;
  3255. }
  3256. }
  3257. return $links;
  3258. }
  3259. /**
  3260. * Generate \<link\> tags for stylesheets
  3261. *
  3262. * @param string $style URL to the file
  3263. * @param array $options Option, can contain 'condition', 'dir', 'media' keys
  3264. * @return string HTML fragment
  3265. */
  3266. protected function styleLink( $style, array $options ) {
  3267. if ( isset( $options['dir'] ) ) {
  3268. if ( $this->getLanguage()->getDir() != $options['dir'] ) {
  3269. return '';
  3270. }
  3271. }
  3272. if ( isset( $options['media'] ) ) {
  3273. $media = self::transformCssMedia( $options['media'] );
  3274. if ( is_null( $media ) ) {
  3275. return '';
  3276. }
  3277. } else {
  3278. $media = 'all';
  3279. }
  3280. if ( substr( $style, 0, 1 ) == '/' ||
  3281. substr( $style, 0, 5 ) == 'http:' ||
  3282. substr( $style, 0, 6 ) == 'https:' ) {
  3283. $url = $style;
  3284. } else {
  3285. $config = $this->getConfig();
  3286. // Append file hash as query parameter
  3287. $url = self::transformResourcePath(
  3288. $config,
  3289. $config->get( 'StylePath' ) . '/' . $style
  3290. );
  3291. }
  3292. $link = Html::linkedStyle( $url, $media );
  3293. if ( isset( $options['condition'] ) ) {
  3294. $condition = htmlspecialchars( $options['condition'] );
  3295. $link = "<!--[if $condition]>$link<![endif]-->";
  3296. }
  3297. return $link;
  3298. }
  3299. /**
  3300. * Transform path to web-accessible static resource.
  3301. *
  3302. * This is used to add a validation hash as query string.
  3303. * This aids various behaviors:
  3304. *
  3305. * - Put long Cache-Control max-age headers on responses for improved
  3306. * cache performance.
  3307. * - Get the correct version of a file as expected by the current page.
  3308. * - Instantly get the updated version of a file after deployment.
  3309. *
  3310. * Avoid using this for urls included in HTML as otherwise clients may get different
  3311. * versions of a resource when navigating the site depending on when the page was cached.
  3312. * If changes to the url propagate, this is not a problem (e.g. if the url is in
  3313. * an external stylesheet).
  3314. *
  3315. * @since 1.27
  3316. * @param Config $config
  3317. * @param string $path Path-absolute URL to file (from document root, must start with "/")
  3318. * @return string URL
  3319. */
  3320. public static function transformResourcePath( Config $config, $path ) {
  3321. global $IP;
  3322. $localDir = $IP;
  3323. $remotePathPrefix = $config->get( 'ResourceBasePath' );
  3324. if ( $remotePathPrefix === '' ) {
  3325. // The configured base path is required to be empty string for
  3326. // wikis in the domain root
  3327. $remotePath = '/';
  3328. } else {
  3329. $remotePath = $remotePathPrefix;
  3330. }
  3331. if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
  3332. // - Path is outside wgResourceBasePath, ignore.
  3333. // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
  3334. return $path;
  3335. }
  3336. // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
  3337. // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
  3338. // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
  3339. // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
  3340. $uploadPath = $config->get( 'UploadPath' );
  3341. if ( strpos( $path, $uploadPath ) === 0 ) {
  3342. $localDir = $config->get( 'UploadDirectory' );
  3343. $remotePathPrefix = $remotePath = $uploadPath;
  3344. }
  3345. $path = RelPath::getRelativePath( $path, $remotePath );
  3346. return self::transformFilePath( $remotePathPrefix, $localDir, $path );
  3347. }
  3348. /**
  3349. * Utility method for transformResourceFilePath().
  3350. *
  3351. * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
  3352. *
  3353. * @since 1.27
  3354. * @param string $remotePathPrefix URL path prefix that points to $localPath
  3355. * @param string $localPath File directory exposed at $remotePath
  3356. * @param string $file Path to target file relative to $localPath
  3357. * @return string URL
  3358. */
  3359. public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
  3360. $hash = md5_file( "$localPath/$file" );
  3361. if ( $hash === false ) {
  3362. wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
  3363. $hash = '';
  3364. }
  3365. return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
  3366. }
  3367. /**
  3368. * Transform "media" attribute based on request parameters
  3369. *
  3370. * @param string $media Current value of the "media" attribute
  3371. * @return string Modified value of the "media" attribute, or null to skip
  3372. * this stylesheet
  3373. */
  3374. public static function transformCssMedia( $media ) {
  3375. global $wgRequest;
  3376. // https://www.w3.org/TR/css3-mediaqueries/#syntax
  3377. $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
  3378. // Switch in on-screen display for media testing
  3379. $switches = [
  3380. 'printable' => 'print',
  3381. 'handheld' => 'handheld',
  3382. ];
  3383. foreach ( $switches as $switch => $targetMedia ) {
  3384. if ( $wgRequest->getBool( $switch ) ) {
  3385. if ( $media == $targetMedia ) {
  3386. $media = '';
  3387. } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
  3388. /* This regex will not attempt to understand a comma-separated media_query_list
  3389. *
  3390. * Example supported values for $media:
  3391. * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
  3392. * Example NOT supported value for $media:
  3393. * '3d-glasses, screen, print and resolution > 90dpi'
  3394. *
  3395. * If it's a print request, we never want any kind of screen stylesheets
  3396. * If it's a handheld request (currently the only other choice with a switch),
  3397. * we don't want simple 'screen' but we might want screen queries that
  3398. * have a max-width or something, so we'll pass all others on and let the
  3399. * client do the query.
  3400. */
  3401. if ( $targetMedia == 'print' || $media == 'screen' ) {
  3402. return null;
  3403. }
  3404. }
  3405. }
  3406. }
  3407. return $media;
  3408. }
  3409. /**
  3410. * Add a wikitext-formatted message to the output.
  3411. * This is equivalent to:
  3412. *
  3413. * $wgOut->addWikiText( wfMessage( ... )->plain() )
  3414. */
  3415. public function addWikiMsg( /*...*/ ) {
  3416. $args = func_get_args();
  3417. $name = array_shift( $args );
  3418. $this->addWikiMsgArray( $name, $args );
  3419. }
  3420. /**
  3421. * Add a wikitext-formatted message to the output.
  3422. * Like addWikiMsg() except the parameters are taken as an array
  3423. * instead of a variable argument list.
  3424. *
  3425. * @param string $name
  3426. * @param array $args
  3427. */
  3428. public function addWikiMsgArray( $name, $args ) {
  3429. $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
  3430. }
  3431. /**
  3432. * This function takes a number of message/argument specifications, wraps them in
  3433. * some overall structure, and then parses the result and adds it to the output.
  3434. *
  3435. * In the $wrap, $1 is replaced with the first message, $2 with the second,
  3436. * and so on. The subsequent arguments may be either
  3437. * 1) strings, in which case they are message names, or
  3438. * 2) arrays, in which case, within each array, the first element is the message
  3439. * name, and subsequent elements are the parameters to that message.
  3440. *
  3441. * Don't use this for messages that are not in the user's interface language.
  3442. *
  3443. * For example:
  3444. *
  3445. * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
  3446. *
  3447. * Is equivalent to:
  3448. *
  3449. * $wgOut->addWikiText( "<div class='error'>\n"
  3450. * . wfMessage( 'some-error' )->plain() . "\n</div>" );
  3451. *
  3452. * The newline after the opening div is needed in some wikitext. See T21226.
  3453. *
  3454. * @param string $wrap
  3455. */
  3456. public function wrapWikiMsg( $wrap /*, ...*/ ) {
  3457. $msgSpecs = func_get_args();
  3458. array_shift( $msgSpecs );
  3459. $msgSpecs = array_values( $msgSpecs );
  3460. $s = $wrap;
  3461. foreach ( $msgSpecs as $n => $spec ) {
  3462. if ( is_array( $spec ) ) {
  3463. $args = $spec;
  3464. $name = array_shift( $args );
  3465. if ( isset( $args['options'] ) ) {
  3466. unset( $args['options'] );
  3467. wfDeprecated(
  3468. 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
  3469. '1.20'
  3470. );
  3471. }
  3472. } else {
  3473. $args = [];
  3474. $name = $spec;
  3475. }
  3476. $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
  3477. }
  3478. $this->addWikiText( $s );
  3479. }
  3480. /**
  3481. * Whether the output has a table of contents
  3482. * @return bool
  3483. * @since 1.22
  3484. */
  3485. public function isTOCEnabled() {
  3486. return $this->mEnableTOC;
  3487. }
  3488. /**
  3489. * Enables/disables section edit links, doesn't override __NOEDITSECTION__
  3490. * @param bool $flag
  3491. * @since 1.23
  3492. * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
  3493. */
  3494. public function enableSectionEditLinks( $flag = true ) {
  3495. wfDeprecated( __METHOD__, '1.31' );
  3496. }
  3497. /**
  3498. * @return bool
  3499. * @since 1.23
  3500. * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
  3501. */
  3502. public function sectionEditLinksEnabled() {
  3503. wfDeprecated( __METHOD__, '1.31' );
  3504. return true;
  3505. }
  3506. /**
  3507. * Helper function to setup the PHP implementation of OOUI to use in this request.
  3508. *
  3509. * @since 1.26
  3510. * @param String $skinName The Skin name to determine the correct OOUI theme
  3511. * @param String $dir Language direction
  3512. */
  3513. public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
  3514. $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
  3515. $theme = $themes[$skinName] ?? $themes['default'];
  3516. // For example, 'OOUI\WikimediaUITheme'.
  3517. $themeClass = "OOUI\\{$theme}Theme";
  3518. OOUI\Theme::setSingleton( new $themeClass() );
  3519. OOUI\Element::setDefaultDir( $dir );
  3520. }
  3521. /**
  3522. * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
  3523. * MediaWiki and this OutputPage instance.
  3524. *
  3525. * @since 1.25
  3526. */
  3527. public function enableOOUI() {
  3528. self::setupOOUI(
  3529. strtolower( $this->getSkin()->getSkinName() ),
  3530. $this->getLanguage()->getDir()
  3531. );
  3532. $this->addModuleStyles( [
  3533. 'oojs-ui-core.styles',
  3534. 'oojs-ui.styles.indicators',
  3535. 'oojs-ui.styles.textures',
  3536. 'mediawiki.widgets.styles',
  3537. 'oojs-ui.styles.icons-content',
  3538. 'oojs-ui.styles.icons-alerts',
  3539. 'oojs-ui.styles.icons-interactions',
  3540. ] );
  3541. }
  3542. /**
  3543. * Get (and set if not yet set) the CSP nonce.
  3544. *
  3545. * This value needs to be included in any <script> tags on the
  3546. * page.
  3547. *
  3548. * @return string|bool Nonce or false to mean don't output nonce
  3549. * @since 1.32
  3550. */
  3551. public function getCSPNonce() {
  3552. if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
  3553. return false;
  3554. }
  3555. if ( $this->CSPNonce === null ) {
  3556. // XXX It might be expensive to generate randomness
  3557. // on every request, on Windows.
  3558. $rand = random_bytes( 15 );
  3559. $this->CSPNonce = base64_encode( $rand );
  3560. }
  3561. return $this->CSPNonce;
  3562. }
  3563. }