Title.php 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787
  1. <?php
  2. /**
  3. * Representation of a title within %MediaWiki.
  4. *
  5. * See title.txt
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. * http://www.gnu.org/copyleft/gpl.html
  21. *
  22. * @file
  23. */
  24. use MediaWiki\Permissions\PermissionManager;
  25. use MediaWiki\Revision\RevisionRecord;
  26. use Wikimedia\Assert\Assert;
  27. use Wikimedia\Rdbms\Database;
  28. use Wikimedia\Rdbms\IDatabase;
  29. use MediaWiki\Linker\LinkTarget;
  30. use MediaWiki\Interwiki\InterwikiLookup;
  31. use MediaWiki\MediaWikiServices;
  32. /**
  33. * Represents a title within MediaWiki.
  34. * Optionally may contain an interwiki designation or namespace.
  35. * @note This class can fetch various kinds of data from the database;
  36. * however, it does so inefficiently.
  37. * @note Consider using a TitleValue object instead. TitleValue is more lightweight
  38. * and does not rely on global state or the database.
  39. */
  40. class Title implements LinkTarget, IDBAccessObject {
  41. /** @var MapCacheLRU|null */
  42. private static $titleCache = null;
  43. /**
  44. * Title::newFromText maintains a cache to avoid expensive re-normalization of
  45. * commonly used titles. On a batch operation this can become a memory leak
  46. * if not bounded. After hitting this many titles reset the cache.
  47. */
  48. const CACHE_MAX = 1000;
  49. /**
  50. * Used to be GAID_FOR_UPDATE define(). Used with getArticleID() and friends
  51. * to use the master DB and inject it into link cache.
  52. * @deprecated since 1.34, use Title::READ_LATEST instead.
  53. */
  54. const GAID_FOR_UPDATE = 512;
  55. /**
  56. * Flag for use with factory methods like newFromLinkTarget() that have
  57. * a $forceClone parameter. If set, the method must return a new instance.
  58. * Without this flag, some factory methods may return existing instances.
  59. *
  60. * @since 1.33
  61. */
  62. const NEW_CLONE = 'clone';
  63. /**
  64. * @name Private member variables
  65. * Please use the accessor functions instead.
  66. * @private
  67. */
  68. // @{
  69. /** @var string Text form (spaces not underscores) of the main part */
  70. public $mTextform = '';
  71. /** @var string URL-encoded form of the main part */
  72. public $mUrlform = '';
  73. /** @var string Main part with underscores */
  74. public $mDbkeyform = '';
  75. /** @var string Database key with the initial letter in the case specified by the user */
  76. protected $mUserCaseDBKey;
  77. /** @var int Namespace index, i.e. one of the NS_xxxx constants */
  78. public $mNamespace = NS_MAIN;
  79. /** @var string Interwiki prefix */
  80. public $mInterwiki = '';
  81. /** @var bool Was this Title created from a string with a local interwiki prefix? */
  82. private $mLocalInterwiki = false;
  83. /** @var string Title fragment (i.e. the bit after the #) */
  84. public $mFragment = '';
  85. /** @var int Article ID, fetched from the link cache on demand */
  86. public $mArticleID = -1;
  87. /** @var bool|int ID of most recent revision */
  88. protected $mLatestID = false;
  89. /**
  90. * @var bool|string ID of the page's content model, i.e. one of the
  91. * CONTENT_MODEL_XXX constants
  92. */
  93. private $mContentModel = false;
  94. /**
  95. * @var bool If a content model was forced via setContentModel()
  96. * this will be true to avoid having other code paths reset it
  97. */
  98. private $mForcedContentModel = false;
  99. /** @var int Estimated number of revisions; null of not loaded */
  100. private $mEstimateRevisions;
  101. /** @var array Array of groups allowed to edit this article */
  102. public $mRestrictions = [];
  103. /**
  104. * @var string|bool Comma-separated set of permission keys
  105. * indicating who can move or edit the page from the page table, (pre 1.10) rows.
  106. * Edit and move sections are separated by a colon
  107. * Example: "edit=autoconfirmed,sysop:move=sysop"
  108. */
  109. protected $mOldRestrictions = false;
  110. /** @var bool Cascade restrictions on this page to included templates and images? */
  111. public $mCascadeRestriction;
  112. /** Caching the results of getCascadeProtectionSources */
  113. public $mCascadingRestrictions;
  114. /** @var array When do the restrictions on this page expire? */
  115. protected $mRestrictionsExpiry = [];
  116. /** @var bool Are cascading restrictions in effect on this page? */
  117. protected $mHasCascadingRestrictions;
  118. /** @var array Where are the cascading restrictions coming from on this page? */
  119. public $mCascadeSources;
  120. /** @var bool Boolean for initialisation on demand */
  121. public $mRestrictionsLoaded = false;
  122. /**
  123. * Text form including namespace/interwiki, initialised on demand
  124. *
  125. * Only public to share cache with TitleFormatter
  126. *
  127. * @private
  128. * @var string|null
  129. */
  130. public $prefixedText = null;
  131. /** @var mixed Cached value for getTitleProtection (create protection) */
  132. public $mTitleProtection;
  133. /**
  134. * @var int Namespace index when there is no namespace. Don't change the
  135. * following default, NS_MAIN is hardcoded in several places. See T2696.
  136. * Zero except in {{transclusion}} tags.
  137. */
  138. public $mDefaultNamespace = NS_MAIN;
  139. /** @var int The page length, 0 for special pages */
  140. protected $mLength = -1;
  141. /** @var null Is the article at this title a redirect? */
  142. public $mRedirect = null;
  143. /** @var array Associative array of user ID -> timestamp/false */
  144. private $mNotificationTimestamp = [];
  145. /** @var bool Whether a page has any subpages */
  146. private $mHasSubpages;
  147. /** @var array|null The (string) language code of the page's language and content code. */
  148. private $mPageLanguage;
  149. /** @var string|bool|null The page language code from the database, null if not saved in
  150. * the database or false if not loaded, yet.
  151. */
  152. private $mDbPageLanguage = false;
  153. /** @var TitleValue|null A corresponding TitleValue object */
  154. private $mTitleValue = null;
  155. /** @var bool|null Would deleting this page be a big deletion? */
  156. private $mIsBigDeletion = null;
  157. // @}
  158. /**
  159. * B/C kludge: provide a TitleParser for use by Title.
  160. * Ideally, Title would have no methods that need this.
  161. * Avoid usage of this singleton by using TitleValue
  162. * and the associated services when possible.
  163. *
  164. * @return TitleFormatter
  165. */
  166. private static function getTitleFormatter() {
  167. return MediaWikiServices::getInstance()->getTitleFormatter();
  168. }
  169. /**
  170. * B/C kludge: provide an InterwikiLookup for use by Title.
  171. * Ideally, Title would have no methods that need this.
  172. * Avoid usage of this singleton by using TitleValue
  173. * and the associated services when possible.
  174. *
  175. * @return InterwikiLookup
  176. */
  177. private static function getInterwikiLookup() {
  178. return MediaWikiServices::getInstance()->getInterwikiLookup();
  179. }
  180. /**
  181. * @protected
  182. */
  183. function __construct() {
  184. }
  185. /**
  186. * Create a new Title from a prefixed DB key
  187. *
  188. * @param string $key The database key, which has underscores
  189. * instead of spaces, possibly including namespace and
  190. * interwiki prefixes
  191. * @return Title|null Title, or null on an error
  192. */
  193. public static function newFromDBkey( $key ) {
  194. $t = new self();
  195. $t->mDbkeyform = $key;
  196. try {
  197. $t->secureAndSplit();
  198. return $t;
  199. } catch ( MalformedTitleException $ex ) {
  200. return null;
  201. }
  202. }
  203. /**
  204. * Returns a Title given a TitleValue.
  205. * If the given TitleValue is already a Title instance, that instance is returned,
  206. * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
  207. * is already a Title instance, that instance is copied using the clone operator.
  208. *
  209. * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
  210. *
  211. * @param TitleValue $titleValue Assumed to be safe.
  212. * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
  213. *
  214. * @return Title
  215. */
  216. public static function newFromTitleValue( TitleValue $titleValue, $forceClone = '' ) {
  217. return self::newFromLinkTarget( $titleValue, $forceClone );
  218. }
  219. /**
  220. * Returns a Title given a LinkTarget.
  221. * If the given LinkTarget is already a Title instance, that instance is returned,
  222. * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
  223. * is already a Title instance, that instance is copied using the clone operator.
  224. *
  225. * @param LinkTarget $linkTarget Assumed to be safe.
  226. * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
  227. *
  228. * @return Title
  229. */
  230. public static function newFromLinkTarget( LinkTarget $linkTarget, $forceClone = '' ) {
  231. if ( $linkTarget instanceof Title ) {
  232. // Special case if it's already a Title object
  233. if ( $forceClone === self::NEW_CLONE ) {
  234. return clone $linkTarget;
  235. } else {
  236. return $linkTarget;
  237. }
  238. }
  239. return self::makeTitle(
  240. $linkTarget->getNamespace(),
  241. $linkTarget->getText(),
  242. $linkTarget->getFragment(),
  243. $linkTarget->getInterwiki()
  244. );
  245. }
  246. /**
  247. * Same as newFromLinkTarget, but if passed null, returns null.
  248. *
  249. * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
  250. *
  251. * @return Title|null
  252. */
  253. public static function castFromLinkTarget( $linkTarget ) {
  254. return $linkTarget ? self::newFromLinkTarget( $linkTarget ) : null;
  255. }
  256. /**
  257. * Create a new Title from text, such as what one would find in a link. De-
  258. * codes any HTML entities in the text.
  259. *
  260. * Title objects returned by this method are guaranteed to be valid, and
  261. * thus return true from the isValid() method.
  262. *
  263. * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
  264. * It may instead be a cached instance created previously, with references to it remaining
  265. * elsewhere.
  266. *
  267. * @param string|int|null $text The link text; spaces, prefixes, and an
  268. * initial ':' indicating the main namespace are accepted.
  269. * @param int $defaultNamespace The namespace to use if none is specified
  270. * by a prefix. If you want to force a specific namespace even if
  271. * $text might begin with a namespace prefix, use makeTitle() or
  272. * makeTitleSafe().
  273. * @throws InvalidArgumentException
  274. * @return Title|null Title or null on an error.
  275. */
  276. public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
  277. // DWIM: Integers can be passed in here when page titles are used as array keys.
  278. if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
  279. throw new InvalidArgumentException( '$text must be a string.' );
  280. }
  281. if ( $text === null ) {
  282. return null;
  283. }
  284. try {
  285. return self::newFromTextThrow( (string)$text, $defaultNamespace );
  286. } catch ( MalformedTitleException $ex ) {
  287. return null;
  288. }
  289. }
  290. /**
  291. * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
  292. * rather than returning null.
  293. *
  294. * The exception subclasses encode detailed information about why the title is invalid.
  295. *
  296. * Title objects returned by this method are guaranteed to be valid, and
  297. * thus return true from the isValid() method.
  298. *
  299. * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
  300. * It may instead be a cached instance created previously, with references to it remaining
  301. * elsewhere.
  302. *
  303. * @see Title::newFromText
  304. *
  305. * @since 1.25
  306. * @param string $text Title text to check
  307. * @param int $defaultNamespace
  308. * @throws MalformedTitleException If the title is invalid
  309. * @return Title
  310. */
  311. public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
  312. if ( is_object( $text ) ) {
  313. throw new MWException( '$text must be a string, given an object' );
  314. } elseif ( $text === null ) {
  315. // Legacy code relies on MalformedTitleException being thrown in this case
  316. // (happens when URL with no title in it is parsed). TODO fix
  317. throw new MalformedTitleException( 'title-invalid-empty' );
  318. }
  319. $titleCache = self::getTitleCache();
  320. // Wiki pages often contain multiple links to the same page.
  321. // Title normalization and parsing can become expensive on pages with many
  322. // links, so we can save a little time by caching them.
  323. // In theory these are value objects and won't get changed...
  324. if ( $defaultNamespace == NS_MAIN ) {
  325. $t = $titleCache->get( $text );
  326. if ( $t ) {
  327. return $t;
  328. }
  329. }
  330. // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
  331. $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
  332. $t = new Title();
  333. $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
  334. $t->mDefaultNamespace = (int)$defaultNamespace;
  335. $t->secureAndSplit();
  336. if ( $defaultNamespace == NS_MAIN ) {
  337. $titleCache->set( $text, $t );
  338. }
  339. return $t;
  340. }
  341. /**
  342. * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
  343. *
  344. * Example of wrong and broken code:
  345. * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
  346. *
  347. * Example of right code:
  348. * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
  349. *
  350. * Create a new Title from URL-encoded text. Ensures that
  351. * the given title's length does not exceed the maximum.
  352. *
  353. * @param string $url The title, as might be taken from a URL
  354. * @return Title|null The new object, or null on an error
  355. */
  356. public static function newFromURL( $url ) {
  357. $t = new Title();
  358. # For compatibility with old buggy URLs. "+" is usually not valid in titles,
  359. # but some URLs used it as a space replacement and they still come
  360. # from some external search tools.
  361. if ( strpos( self::legalChars(), '+' ) === false ) {
  362. $url = strtr( $url, '+', ' ' );
  363. }
  364. $t->mDbkeyform = strtr( $url, ' ', '_' );
  365. try {
  366. $t->secureAndSplit();
  367. return $t;
  368. } catch ( MalformedTitleException $ex ) {
  369. return null;
  370. }
  371. }
  372. /**
  373. * @return MapCacheLRU
  374. */
  375. private static function getTitleCache() {
  376. if ( self::$titleCache === null ) {
  377. self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
  378. }
  379. return self::$titleCache;
  380. }
  381. /**
  382. * Returns a list of fields that are to be selected for initializing Title
  383. * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
  384. * whether to include page_content_model.
  385. *
  386. * @return array
  387. */
  388. protected static function getSelectFields() {
  389. global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
  390. $fields = [
  391. 'page_namespace', 'page_title', 'page_id',
  392. 'page_len', 'page_is_redirect', 'page_latest',
  393. ];
  394. if ( $wgContentHandlerUseDB ) {
  395. $fields[] = 'page_content_model';
  396. }
  397. if ( $wgPageLanguageUseDB ) {
  398. $fields[] = 'page_lang';
  399. }
  400. return $fields;
  401. }
  402. /**
  403. * Create a new Title from an article ID
  404. *
  405. * @param int $id The page_id corresponding to the Title to create
  406. * @param int $flags Bitfield of class READ_* constants
  407. * @return Title|null The new object, or null on an error
  408. */
  409. public static function newFromID( $id, $flags = 0 ) {
  410. $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
  411. list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
  412. $row = wfGetDB( $index )->selectRow(
  413. 'page',
  414. self::getSelectFields(),
  415. [ 'page_id' => $id ],
  416. __METHOD__,
  417. $options
  418. );
  419. if ( $row !== false ) {
  420. $title = self::newFromRow( $row );
  421. } else {
  422. $title = null;
  423. }
  424. return $title;
  425. }
  426. /**
  427. * Make an array of titles from an array of IDs
  428. *
  429. * @param int[] $ids Array of IDs
  430. * @return Title[] Array of Titles
  431. */
  432. public static function newFromIDs( $ids ) {
  433. if ( !count( $ids ) ) {
  434. return [];
  435. }
  436. $dbr = wfGetDB( DB_REPLICA );
  437. $res = $dbr->select(
  438. 'page',
  439. self::getSelectFields(),
  440. [ 'page_id' => $ids ],
  441. __METHOD__
  442. );
  443. $titles = [];
  444. foreach ( $res as $row ) {
  445. $titles[] = self::newFromRow( $row );
  446. }
  447. return $titles;
  448. }
  449. /**
  450. * Make a Title object from a DB row
  451. *
  452. * @param stdClass $row Object database row (needs at least page_title,page_namespace)
  453. * @return Title Corresponding Title
  454. */
  455. public static function newFromRow( $row ) {
  456. $t = self::makeTitle( $row->page_namespace, $row->page_title );
  457. $t->loadFromRow( $row );
  458. return $t;
  459. }
  460. /**
  461. * Load Title object fields from a DB row.
  462. * If false is given, the title will be treated as non-existing.
  463. *
  464. * @param stdClass|bool $row Database row
  465. */
  466. public function loadFromRow( $row ) {
  467. if ( $row ) { // page found
  468. if ( isset( $row->page_id ) ) {
  469. $this->mArticleID = (int)$row->page_id;
  470. }
  471. if ( isset( $row->page_len ) ) {
  472. $this->mLength = (int)$row->page_len;
  473. }
  474. if ( isset( $row->page_is_redirect ) ) {
  475. $this->mRedirect = (bool)$row->page_is_redirect;
  476. }
  477. if ( isset( $row->page_latest ) ) {
  478. $this->mLatestID = (int)$row->page_latest;
  479. }
  480. if ( isset( $row->page_content_model ) ) {
  481. $this->lazyFillContentModel( $row->page_content_model );
  482. } else {
  483. $this->lazyFillContentModel( false ); // lazily-load getContentModel()
  484. }
  485. if ( isset( $row->page_lang ) ) {
  486. $this->mDbPageLanguage = (string)$row->page_lang;
  487. }
  488. if ( isset( $row->page_restrictions ) ) {
  489. $this->mOldRestrictions = $row->page_restrictions;
  490. }
  491. } else { // page not found
  492. $this->mArticleID = 0;
  493. $this->mLength = 0;
  494. $this->mRedirect = false;
  495. $this->mLatestID = 0;
  496. $this->lazyFillContentModel( false ); // lazily-load getContentModel()
  497. }
  498. }
  499. /**
  500. * Create a new Title from a namespace index and a DB key.
  501. *
  502. * It's assumed that $ns and $title are safe, for instance when
  503. * they came directly from the database or a special page name,
  504. * not from user input.
  505. *
  506. * No validation is applied. For convenience, spaces are normalized
  507. * to underscores, so that e.g. user_text fields can be used directly.
  508. *
  509. * @note This method may return Title objects that are "invalid"
  510. * according to the isValid() method. This is usually caused by
  511. * configuration changes: e.g. a namespace that was once defined is
  512. * no longer configured, or a character that was once allowed in
  513. * titles is now forbidden.
  514. *
  515. * @param int $ns The namespace of the article
  516. * @param string $title The unprefixed database key form
  517. * @param string $fragment The link fragment (after the "#")
  518. * @param string $interwiki The interwiki prefix
  519. * @return Title The new object
  520. */
  521. public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
  522. $t = new Title();
  523. $t->mInterwiki = $interwiki;
  524. $t->mFragment = $fragment;
  525. $t->mNamespace = $ns = (int)$ns;
  526. $t->mDbkeyform = strtr( $title, ' ', '_' );
  527. $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
  528. $t->mUrlform = wfUrlencode( $t->mDbkeyform );
  529. $t->mTextform = strtr( $title, '_', ' ' );
  530. return $t;
  531. }
  532. /**
  533. * Create a new Title from a namespace index and a DB key.
  534. * The parameters will be checked for validity, which is a bit slower
  535. * than makeTitle() but safer for user-provided data.
  536. *
  537. * Title objects returned by makeTitleSafe() are guaranteed to be valid,
  538. * that is, they return true from the isValid() method. If no valid Title
  539. * can be constructed from the input, this method returns null.
  540. *
  541. * @param int $ns The namespace of the article
  542. * @param string $title Database key form
  543. * @param string $fragment The link fragment (after the "#")
  544. * @param string $interwiki Interwiki prefix
  545. * @return Title|null The new object, or null on an error
  546. */
  547. public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
  548. // NOTE: ideally, this would just call makeTitle() and then isValid(),
  549. // but presently, that means more overhead on a potential performance hotspot.
  550. if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
  551. return null;
  552. }
  553. $t = new Title();
  554. $t->mDbkeyform = self::makeName( $ns, $title, $fragment, $interwiki, true );
  555. try {
  556. $t->secureAndSplit();
  557. return $t;
  558. } catch ( MalformedTitleException $ex ) {
  559. return null;
  560. }
  561. }
  562. /**
  563. * Create a new Title for the Main Page
  564. *
  565. * This uses the 'mainpage' interface message, which could be specified in
  566. * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
  567. * will use the user language, which would involve initialising the session
  568. * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
  569. * be sure to pass in a MessageLocalizer (such as your own RequestContext,
  570. * or ResourceloaderContext) to prevent an error.
  571. *
  572. * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
  573. * It may instead be a cached instance created previously, with references to it remaining
  574. * elsewhere.
  575. *
  576. * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
  577. * @return Title
  578. */
  579. public static function newMainPage( MessageLocalizer $localizer = null ) {
  580. if ( $localizer ) {
  581. $msg = $localizer->msg( 'mainpage' );
  582. } else {
  583. $msg = wfMessage( 'mainpage' );
  584. }
  585. $title = self::newFromText( $msg->inContentLanguage()->text() );
  586. // Every page renders at least one link to the Main Page (e.g. sidebar).
  587. // If the localised value is invalid, don't produce fatal errors that
  588. // would make the wiki inaccessible (and hard to fix the invalid message).
  589. // Gracefully fallback...
  590. if ( !$title ) {
  591. $title = self::newFromText( 'Main Page' );
  592. }
  593. return $title;
  594. }
  595. /**
  596. * Get the prefixed DB key associated with an ID
  597. *
  598. * @param int $id The page_id of the article
  599. * @return string|null An object representing the article, or null if no such article was found
  600. */
  601. public static function nameOf( $id ) {
  602. $dbr = wfGetDB( DB_REPLICA );
  603. $s = $dbr->selectRow(
  604. 'page',
  605. [ 'page_namespace', 'page_title' ],
  606. [ 'page_id' => $id ],
  607. __METHOD__
  608. );
  609. if ( $s === false ) {
  610. return null;
  611. }
  612. return self::makeName( $s->page_namespace, $s->page_title );
  613. }
  614. /**
  615. * Get a regex character class describing the legal characters in a link
  616. *
  617. * @return string The list of characters, not delimited
  618. */
  619. public static function legalChars() {
  620. global $wgLegalTitleChars;
  621. return $wgLegalTitleChars;
  622. }
  623. /**
  624. * Utility method for converting a character sequence from bytes to Unicode.
  625. *
  626. * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
  627. * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
  628. *
  629. * @param string $byteClass
  630. * @return string
  631. */
  632. public static function convertByteClassToUnicodeClass( $byteClass ) {
  633. $length = strlen( $byteClass );
  634. // Input token queue
  635. $x0 = $x1 = $x2 = '';
  636. // Decoded queue
  637. $d0 = $d1 = $d2 = '';
  638. // Decoded integer codepoints
  639. $ord0 = $ord1 = $ord2 = 0;
  640. // Re-encoded queue
  641. $r0 = $r1 = $r2 = '';
  642. // Output
  643. $out = '';
  644. // Flags
  645. $allowUnicode = false;
  646. for ( $pos = 0; $pos < $length; $pos++ ) {
  647. // Shift the queues down
  648. $x2 = $x1;
  649. $x1 = $x0;
  650. $d2 = $d1;
  651. $d1 = $d0;
  652. $ord2 = $ord1;
  653. $ord1 = $ord0;
  654. $r2 = $r1;
  655. $r1 = $r0;
  656. // Load the current input token and decoded values
  657. $inChar = $byteClass[$pos];
  658. if ( $inChar == '\\' ) {
  659. if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
  660. $x0 = $inChar . $m[0];
  661. $d0 = chr( hexdec( $m[1] ) );
  662. $pos += strlen( $m[0] );
  663. } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
  664. $x0 = $inChar . $m[0];
  665. $d0 = chr( octdec( $m[0] ) );
  666. $pos += strlen( $m[0] );
  667. } elseif ( $pos + 1 >= $length ) {
  668. $x0 = $d0 = '\\';
  669. } else {
  670. $d0 = $byteClass[$pos + 1];
  671. $x0 = $inChar . $d0;
  672. $pos += 1;
  673. }
  674. } else {
  675. $x0 = $d0 = $inChar;
  676. }
  677. $ord0 = ord( $d0 );
  678. // Load the current re-encoded value
  679. if ( $ord0 < 32 || $ord0 == 0x7f ) {
  680. $r0 = sprintf( '\x%02x', $ord0 );
  681. } elseif ( $ord0 >= 0x80 ) {
  682. // Allow unicode if a single high-bit character appears
  683. $r0 = sprintf( '\x%02x', $ord0 );
  684. $allowUnicode = true;
  685. // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
  686. } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
  687. $r0 = '\\' . $d0;
  688. } else {
  689. $r0 = $d0;
  690. }
  691. // Do the output
  692. if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
  693. // Range
  694. if ( $ord2 > $ord0 ) {
  695. // Empty range
  696. } elseif ( $ord0 >= 0x80 ) {
  697. // Unicode range
  698. $allowUnicode = true;
  699. if ( $ord2 < 0x80 ) {
  700. // Keep the non-unicode section of the range
  701. $out .= "$r2-\\x7F";
  702. }
  703. } else {
  704. // Normal range
  705. $out .= "$r2-$r0";
  706. }
  707. // Reset state to the initial value
  708. $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
  709. } elseif ( $ord2 < 0x80 ) {
  710. // ASCII character
  711. $out .= $r2;
  712. }
  713. }
  714. if ( $ord1 < 0x80 ) {
  715. $out .= $r1;
  716. }
  717. if ( $ord0 < 0x80 ) {
  718. $out .= $r0;
  719. }
  720. if ( $allowUnicode ) {
  721. $out .= '\u0080-\uFFFF';
  722. }
  723. return $out;
  724. }
  725. /**
  726. * Make a prefixed DB key from a DB key and a namespace index
  727. *
  728. * @param int $ns Numerical representation of the namespace
  729. * @param string $title The DB key form the title
  730. * @param string $fragment The link fragment (after the "#")
  731. * @param string $interwiki The interwiki prefix
  732. * @param bool $canonicalNamespace If true, use the canonical name for
  733. * $ns instead of the localized version.
  734. * @return string The prefixed form of the title
  735. */
  736. public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
  737. $canonicalNamespace = false
  738. ) {
  739. if ( $canonicalNamespace ) {
  740. $namespace = MediaWikiServices::getInstance()->getNamespaceInfo()->
  741. getCanonicalName( $ns );
  742. } else {
  743. $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
  744. }
  745. $name = $namespace == '' ? $title : "$namespace:$title";
  746. if ( strval( $interwiki ) != '' ) {
  747. $name = "$interwiki:$name";
  748. }
  749. if ( strval( $fragment ) != '' ) {
  750. $name .= '#' . $fragment;
  751. }
  752. return $name;
  753. }
  754. /**
  755. * Callback for usort() to do title sorts by (namespace, title)
  756. *
  757. * @param LinkTarget $a
  758. * @param LinkTarget $b
  759. *
  760. * @return int Result of string comparison, or namespace comparison
  761. */
  762. public static function compare( LinkTarget $a, LinkTarget $b ) {
  763. return $a->getNamespace() <=> $b->getNamespace()
  764. ?: strcmp( $a->getText(), $b->getText() );
  765. }
  766. /**
  767. * Returns true if the title is valid, false if it is invalid.
  768. *
  769. * Valid titles can be round-tripped via makeTitle() and newFromText().
  770. * Their DB key can be used in the database, though it may not have the correct
  771. * capitalization.
  772. *
  773. * Invalid titles may get returned from makeTitle(), and it may be useful to
  774. * allow them to exist, e.g. in order to process log entries about pages in
  775. * namespaces that belong to extensions that are no longer installed.
  776. *
  777. * @note This method is relatively expensive. When constructing Title
  778. * objects that need to be valid, use an instantiator method that is guaranteed
  779. * to return valid titles, such as makeTitleSafe() or newFromText().
  780. *
  781. * @return bool
  782. */
  783. public function isValid() {
  784. $services = MediaWikiServices::getInstance();
  785. if ( !$services->getNamespaceInfo()->exists( $this->mNamespace ) ) {
  786. return false;
  787. }
  788. try {
  789. $services->getTitleParser()->parseTitle( $this->mDbkeyform, $this->mNamespace );
  790. } catch ( MalformedTitleException $ex ) {
  791. return false;
  792. }
  793. try {
  794. // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
  795. new TitleValue(
  796. $this->mNamespace,
  797. $this->mDbkeyform,
  798. $this->mFragment,
  799. $this->mInterwiki
  800. );
  801. } catch ( InvalidArgumentException $ex ) {
  802. return false;
  803. }
  804. return true;
  805. }
  806. /**
  807. * Determine whether the object refers to a page within
  808. * this project (either this wiki or a wiki with a local
  809. * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
  810. *
  811. * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
  812. */
  813. public function isLocal() {
  814. if ( $this->isExternal() ) {
  815. $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
  816. if ( $iw ) {
  817. return $iw->isLocal();
  818. }
  819. }
  820. return true;
  821. }
  822. /**
  823. * Is this Title interwiki?
  824. *
  825. * @return bool
  826. */
  827. public function isExternal() {
  828. return $this->mInterwiki !== '';
  829. }
  830. /**
  831. * Get the interwiki prefix
  832. *
  833. * Use Title::isExternal to check if a interwiki is set
  834. *
  835. * @return string Interwiki prefix
  836. */
  837. public function getInterwiki() {
  838. return $this->mInterwiki;
  839. }
  840. /**
  841. * Was this a local interwiki link?
  842. *
  843. * @return bool
  844. */
  845. public function wasLocalInterwiki() {
  846. return $this->mLocalInterwiki;
  847. }
  848. /**
  849. * Determine whether the object refers to a page within
  850. * this project and is transcludable.
  851. *
  852. * @return bool True if this is transcludable
  853. */
  854. public function isTrans() {
  855. if ( !$this->isExternal() ) {
  856. return false;
  857. }
  858. return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
  859. }
  860. /**
  861. * Returns the DB name of the distant wiki which owns the object.
  862. *
  863. * @return string|false The DB name
  864. */
  865. public function getTransWikiID() {
  866. if ( !$this->isExternal() ) {
  867. return false;
  868. }
  869. return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
  870. }
  871. /**
  872. * Get a TitleValue object representing this Title.
  873. *
  874. * @note Not all valid Titles have a corresponding valid TitleValue
  875. * (e.g. TitleValues cannot represent page-local links that have a
  876. * fragment but no title text).
  877. *
  878. * @return TitleValue|null
  879. */
  880. public function getTitleValue() {
  881. if ( $this->mTitleValue === null ) {
  882. try {
  883. $this->mTitleValue = new TitleValue(
  884. $this->mNamespace,
  885. $this->mDbkeyform,
  886. $this->mFragment,
  887. $this->mInterwiki
  888. );
  889. } catch ( InvalidArgumentException $ex ) {
  890. wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
  891. $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
  892. }
  893. }
  894. return $this->mTitleValue;
  895. }
  896. /**
  897. * Get the text form (spaces not underscores) of the main part
  898. *
  899. * @return string Main part of the title
  900. */
  901. public function getText() {
  902. return $this->mTextform;
  903. }
  904. /**
  905. * Get the URL-encoded form of the main part
  906. *
  907. * @return string Main part of the title, URL-encoded
  908. */
  909. public function getPartialURL() {
  910. return $this->mUrlform;
  911. }
  912. /**
  913. * Get the main part with underscores
  914. *
  915. * @return string Main part of the title, with underscores
  916. */
  917. public function getDBkey() {
  918. return $this->mDbkeyform;
  919. }
  920. /**
  921. * Get the DB key with the initial letter case as specified by the user
  922. * @deprecated since 1.33; please use Title::getDBKey() instead
  923. *
  924. * @return string DB key
  925. */
  926. function getUserCaseDBKey() {
  927. if ( !is_null( $this->mUserCaseDBKey ) ) {
  928. return $this->mUserCaseDBKey;
  929. } else {
  930. // If created via makeTitle(), $this->mUserCaseDBKey is not set.
  931. return $this->mDbkeyform;
  932. }
  933. }
  934. /**
  935. * Get the namespace index, i.e. one of the NS_xxxx constants.
  936. *
  937. * @return int Namespace index
  938. */
  939. public function getNamespace() {
  940. return $this->mNamespace;
  941. }
  942. /**
  943. * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
  944. *
  945. * @todo Deprecate this in favor of SlotRecord::getModel()
  946. *
  947. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  948. * @return string Content model id
  949. */
  950. public function getContentModel( $flags = 0 ) {
  951. if ( $this->mForcedContentModel ) {
  952. if ( !$this->mContentModel ) {
  953. throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
  954. }
  955. // Content model is locked to the currently loaded one
  956. return $this->mContentModel;
  957. }
  958. if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
  959. $this->lazyFillContentModel( $this->loadFieldFromDB( 'page_content_model', $flags ) );
  960. } elseif (
  961. ( !$this->mContentModel || $flags & self::GAID_FOR_UPDATE ) &&
  962. $this->getArticleID( $flags )
  963. ) {
  964. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  965. $linkCache->addLinkObj( $this ); # in case we already had an article ID
  966. $this->lazyFillContentModel( $linkCache->getGoodLinkFieldObj( $this, 'model' ) );
  967. }
  968. if ( !$this->mContentModel ) {
  969. $this->lazyFillContentModel( ContentHandler::getDefaultModelFor( $this ) );
  970. }
  971. return $this->mContentModel;
  972. }
  973. /**
  974. * Convenience method for checking a title's content model name
  975. *
  976. * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
  977. * @return bool True if $this->getContentModel() == $id
  978. */
  979. public function hasContentModel( $id ) {
  980. return $this->getContentModel() == $id;
  981. }
  982. /**
  983. * Set a proposed content model for the page for permissions checking
  984. *
  985. * This does not actually change the content model of a title in the DB.
  986. * It only affects this particular Title instance. The content model is
  987. * forced to remain this value until another setContentModel() call.
  988. *
  989. * ContentHandler::canBeUsedOn() should be checked before calling this
  990. * if there is any doubt regarding the applicability of the content model
  991. *
  992. * @since 1.28
  993. * @param string $model CONTENT_MODEL_XXX constant
  994. */
  995. public function setContentModel( $model ) {
  996. if ( (string)$model === '' ) {
  997. throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
  998. }
  999. $this->mContentModel = $model;
  1000. $this->mForcedContentModel = true;
  1001. }
  1002. /**
  1003. * If the content model field is not frozen then update it with a retreived value
  1004. *
  1005. * @param string|bool $model CONTENT_MODEL_XXX constant or false
  1006. */
  1007. private function lazyFillContentModel( $model ) {
  1008. if ( !$this->mForcedContentModel ) {
  1009. $this->mContentModel = ( $model === false ) ? false : (string)$model;
  1010. }
  1011. }
  1012. /**
  1013. * Get the namespace text
  1014. *
  1015. * @return string|false Namespace text
  1016. */
  1017. public function getNsText() {
  1018. if ( $this->isExternal() ) {
  1019. // This probably shouldn't even happen, except for interwiki transclusion.
  1020. // If possible, use the canonical name for the foreign namespace.
  1021. $nsText = MediaWikiServices::getInstance()->getNamespaceInfo()->
  1022. getCanonicalName( $this->mNamespace );
  1023. if ( $nsText !== false ) {
  1024. return $nsText;
  1025. }
  1026. }
  1027. try {
  1028. $formatter = self::getTitleFormatter();
  1029. return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
  1030. } catch ( InvalidArgumentException $ex ) {
  1031. wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
  1032. return false;
  1033. }
  1034. }
  1035. /**
  1036. * Get the namespace text of the subject (rather than talk) page
  1037. *
  1038. * @return string Namespace text
  1039. */
  1040. public function getSubjectNsText() {
  1041. $services = MediaWikiServices::getInstance();
  1042. return $services->getContentLanguage()->
  1043. getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace ) );
  1044. }
  1045. /**
  1046. * Get the namespace text of the talk page
  1047. *
  1048. * @return string Namespace text
  1049. */
  1050. public function getTalkNsText() {
  1051. $services = MediaWikiServices::getInstance();
  1052. return $services->getContentLanguage()->
  1053. getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace ) );
  1054. }
  1055. /**
  1056. * Can this title have a corresponding talk page?
  1057. *
  1058. * False for relative section links (with getText() === ''),
  1059. * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
  1060. *
  1061. * @see NamespaceInfo::canHaveTalkPage
  1062. * @since 1.30
  1063. *
  1064. * @return bool True if this title either is a talk page or can have a talk page associated.
  1065. */
  1066. public function canHaveTalkPage() {
  1067. return MediaWikiServices::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
  1068. }
  1069. /**
  1070. * Is this in a namespace that allows actual pages?
  1071. *
  1072. * @return bool
  1073. */
  1074. public function canExist() {
  1075. return $this->mNamespace >= NS_MAIN;
  1076. }
  1077. /**
  1078. * Can this title be added to a user's watchlist?
  1079. *
  1080. * False for relative section links (with getText() === ''),
  1081. * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
  1082. *
  1083. * @return bool
  1084. */
  1085. public function isWatchable() {
  1086. $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
  1087. return $this->getText() !== '' && !$this->isExternal() &&
  1088. $nsInfo->isWatchable( $this->mNamespace );
  1089. }
  1090. /**
  1091. * Returns true if this is a special page.
  1092. *
  1093. * @return bool
  1094. */
  1095. public function isSpecialPage() {
  1096. return $this->mNamespace == NS_SPECIAL;
  1097. }
  1098. /**
  1099. * Returns true if this title resolves to the named special page
  1100. *
  1101. * @param string $name The special page name
  1102. * @return bool
  1103. */
  1104. public function isSpecial( $name ) {
  1105. if ( $this->isSpecialPage() ) {
  1106. list( $thisName, /* $subpage */ ) =
  1107. MediaWikiServices::getInstance()->getSpecialPageFactory()->
  1108. resolveAlias( $this->mDbkeyform );
  1109. if ( $name == $thisName ) {
  1110. return true;
  1111. }
  1112. }
  1113. return false;
  1114. }
  1115. /**
  1116. * If the Title refers to a special page alias which is not the local default, resolve
  1117. * the alias, and localise the name as necessary. Otherwise, return $this
  1118. *
  1119. * @return Title
  1120. */
  1121. public function fixSpecialName() {
  1122. if ( $this->isSpecialPage() ) {
  1123. $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
  1124. list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform );
  1125. if ( $canonicalName ) {
  1126. $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
  1127. if ( $localName != $this->mDbkeyform ) {
  1128. return self::makeTitle( NS_SPECIAL, $localName );
  1129. }
  1130. }
  1131. }
  1132. return $this;
  1133. }
  1134. /**
  1135. * Returns true if the title is inside the specified namespace.
  1136. *
  1137. * Please make use of this instead of comparing to getNamespace()
  1138. * This function is much more resistant to changes we may make
  1139. * to namespaces than code that makes direct comparisons.
  1140. * @param int $ns The namespace
  1141. * @return bool
  1142. * @since 1.19
  1143. */
  1144. public function inNamespace( $ns ) {
  1145. return MediaWikiServices::getInstance()->getNamespaceInfo()->
  1146. equals( $this->mNamespace, $ns );
  1147. }
  1148. /**
  1149. * Returns true if the title is inside one of the specified namespaces.
  1150. *
  1151. * @param int|int[] ...$namespaces The namespaces to check for
  1152. * @return bool
  1153. * @since 1.19
  1154. */
  1155. public function inNamespaces( ...$namespaces ) {
  1156. if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
  1157. $namespaces = $namespaces[0];
  1158. }
  1159. foreach ( $namespaces as $ns ) {
  1160. if ( $this->inNamespace( $ns ) ) {
  1161. return true;
  1162. }
  1163. }
  1164. return false;
  1165. }
  1166. /**
  1167. * Returns true if the title has the same subject namespace as the
  1168. * namespace specified.
  1169. * For example this method will take NS_USER and return true if namespace
  1170. * is either NS_USER or NS_USER_TALK since both of them have NS_USER
  1171. * as their subject namespace.
  1172. *
  1173. * This is MUCH simpler than individually testing for equivalence
  1174. * against both NS_USER and NS_USER_TALK, and is also forward compatible.
  1175. * @since 1.19
  1176. * @param int $ns
  1177. * @return bool
  1178. */
  1179. public function hasSubjectNamespace( $ns ) {
  1180. return MediaWikiServices::getInstance()->getNamespaceInfo()->
  1181. subjectEquals( $this->mNamespace, $ns );
  1182. }
  1183. /**
  1184. * Is this Title in a namespace which contains content?
  1185. * In other words, is this a content page, for the purposes of calculating
  1186. * statistics, etc?
  1187. *
  1188. * @return bool
  1189. */
  1190. public function isContentPage() {
  1191. return MediaWikiServices::getInstance()->getNamespaceInfo()->
  1192. isContent( $this->mNamespace );
  1193. }
  1194. /**
  1195. * Would anybody with sufficient privileges be able to move this page?
  1196. * Some pages just aren't movable.
  1197. *
  1198. * @return bool
  1199. */
  1200. public function isMovable() {
  1201. if (
  1202. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  1203. isMovable( $this->mNamespace ) || $this->isExternal()
  1204. ) {
  1205. // Interwiki title or immovable namespace. Hooks don't get to override here
  1206. return false;
  1207. }
  1208. $result = true;
  1209. Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
  1210. return $result;
  1211. }
  1212. /**
  1213. * Is this the mainpage?
  1214. * @note Title::newFromText seems to be sufficiently optimized by the title
  1215. * cache that we don't need to over-optimize by doing direct comparisons and
  1216. * accidentally creating new bugs where $title->equals( Title::newFromText() )
  1217. * ends up reporting something differently than $title->isMainPage();
  1218. *
  1219. * @since 1.18
  1220. * @return bool
  1221. */
  1222. public function isMainPage() {
  1223. return $this->equals( self::newMainPage() );
  1224. }
  1225. /**
  1226. * Is this a subpage?
  1227. *
  1228. * @return bool
  1229. */
  1230. public function isSubpage() {
  1231. return MediaWikiServices::getInstance()->getNamespaceInfo()->
  1232. hasSubpages( $this->mNamespace )
  1233. ? strpos( $this->getText(), '/' ) !== false
  1234. : false;
  1235. }
  1236. /**
  1237. * Is this a conversion table for the LanguageConverter?
  1238. *
  1239. * @return bool
  1240. */
  1241. public function isConversionTable() {
  1242. // @todo ConversionTable should become a separate content model.
  1243. return $this->mNamespace == NS_MEDIAWIKI &&
  1244. strpos( $this->getText(), 'Conversiontable/' ) === 0;
  1245. }
  1246. /**
  1247. * Does that page contain wikitext, or it is JS, CSS or whatever?
  1248. *
  1249. * @return bool
  1250. */
  1251. public function isWikitextPage() {
  1252. return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
  1253. }
  1254. /**
  1255. * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
  1256. * global UI. This is generally true for pages in the MediaWiki namespace having
  1257. * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
  1258. *
  1259. * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
  1260. * for that!
  1261. *
  1262. * Note that this method should not return true for pages that contain and show
  1263. * "inactive" CSS, JSON, or JS.
  1264. *
  1265. * @return bool
  1266. * @since 1.31
  1267. */
  1268. public function isSiteConfigPage() {
  1269. return (
  1270. $this->isSiteCssConfigPage()
  1271. || $this->isSiteJsonConfigPage()
  1272. || $this->isSiteJsConfigPage()
  1273. );
  1274. }
  1275. /**
  1276. * Is this a "config" (.css, .json, or .js) sub-page of a user page?
  1277. *
  1278. * @return bool
  1279. * @since 1.31
  1280. */
  1281. public function isUserConfigPage() {
  1282. return (
  1283. $this->isUserCssConfigPage()
  1284. || $this->isUserJsonConfigPage()
  1285. || $this->isUserJsConfigPage()
  1286. );
  1287. }
  1288. /**
  1289. * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
  1290. *
  1291. * @return string Containing skin name from .css, .json, or .js subpage title
  1292. * @since 1.31
  1293. */
  1294. public function getSkinFromConfigSubpage() {
  1295. $subpage = explode( '/', $this->mTextform );
  1296. $subpage = $subpage[count( $subpage ) - 1];
  1297. $lastdot = strrpos( $subpage, '.' );
  1298. if ( $lastdot === false ) {
  1299. return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
  1300. }
  1301. return substr( $subpage, 0, $lastdot );
  1302. }
  1303. /**
  1304. * Is this a CSS "config" sub-page of a user page?
  1305. *
  1306. * @return bool
  1307. * @since 1.31
  1308. */
  1309. public function isUserCssConfigPage() {
  1310. return (
  1311. NS_USER == $this->mNamespace
  1312. && $this->isSubpage()
  1313. && $this->hasContentModel( CONTENT_MODEL_CSS )
  1314. );
  1315. }
  1316. /**
  1317. * Is this a JSON "config" sub-page of a user page?
  1318. *
  1319. * @return bool
  1320. * @since 1.31
  1321. */
  1322. public function isUserJsonConfigPage() {
  1323. return (
  1324. NS_USER == $this->mNamespace
  1325. && $this->isSubpage()
  1326. && $this->hasContentModel( CONTENT_MODEL_JSON )
  1327. );
  1328. }
  1329. /**
  1330. * Is this a JS "config" sub-page of a user page?
  1331. *
  1332. * @return bool
  1333. * @since 1.31
  1334. */
  1335. public function isUserJsConfigPage() {
  1336. return (
  1337. NS_USER == $this->mNamespace
  1338. && $this->isSubpage()
  1339. && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
  1340. );
  1341. }
  1342. /**
  1343. * Is this a sitewide CSS "config" page?
  1344. *
  1345. * @return bool
  1346. * @since 1.32
  1347. */
  1348. public function isSiteCssConfigPage() {
  1349. return (
  1350. NS_MEDIAWIKI == $this->mNamespace
  1351. && (
  1352. $this->hasContentModel( CONTENT_MODEL_CSS )
  1353. // paranoia - a MediaWiki: namespace page with mismatching extension and content
  1354. // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
  1355. || substr( $this->mDbkeyform, -4 ) === '.css'
  1356. )
  1357. );
  1358. }
  1359. /**
  1360. * Is this a sitewide JSON "config" page?
  1361. *
  1362. * @return bool
  1363. * @since 1.32
  1364. */
  1365. public function isSiteJsonConfigPage() {
  1366. return (
  1367. NS_MEDIAWIKI == $this->mNamespace
  1368. && (
  1369. $this->hasContentModel( CONTENT_MODEL_JSON )
  1370. // paranoia - a MediaWiki: namespace page with mismatching extension and content
  1371. // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
  1372. || substr( $this->mDbkeyform, -5 ) === '.json'
  1373. )
  1374. );
  1375. }
  1376. /**
  1377. * Is this a sitewide JS "config" page?
  1378. *
  1379. * @return bool
  1380. * @since 1.31
  1381. */
  1382. public function isSiteJsConfigPage() {
  1383. return (
  1384. NS_MEDIAWIKI == $this->mNamespace
  1385. && (
  1386. $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
  1387. // paranoia - a MediaWiki: namespace page with mismatching extension and content
  1388. // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
  1389. || substr( $this->mDbkeyform, -3 ) === '.js'
  1390. )
  1391. );
  1392. }
  1393. /**
  1394. * Is this a message which can contain raw HTML?
  1395. *
  1396. * @return bool
  1397. * @since 1.32
  1398. */
  1399. public function isRawHtmlMessage() {
  1400. global $wgRawHtmlMessages;
  1401. if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
  1402. return false;
  1403. }
  1404. $message = lcfirst( $this->getRootTitle()->getDBkey() );
  1405. return in_array( $message, $wgRawHtmlMessages, true );
  1406. }
  1407. /**
  1408. * Is this a talk page of some sort?
  1409. *
  1410. * @return bool
  1411. */
  1412. public function isTalkPage() {
  1413. return MediaWikiServices::getInstance()->getNamespaceInfo()->
  1414. isTalk( $this->mNamespace );
  1415. }
  1416. /**
  1417. * Get a Title object associated with the talk page of this article
  1418. *
  1419. * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
  1420. * with NamespaceInfo::canHaveTalkPage(). Note that the new method will
  1421. * throw if asked for the talk page of a section-only link, or of an interwiki
  1422. * link.
  1423. * @return Title The object for the talk page
  1424. * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
  1425. * or because it's a relative link, or an interwiki link.
  1426. */
  1427. public function getTalkPage() {
  1428. // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
  1429. // Instead of failing on invalid titles, let's just log the issue for now.
  1430. // See the discussion on T227817.
  1431. // Is this the same title?
  1432. $talkNS = MediaWikiServices::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace );
  1433. if ( $this->mNamespace == $talkNS ) {
  1434. return $this;
  1435. }
  1436. $title = self::makeTitle( $talkNS, $this->mDbkeyform );
  1437. $this->warnIfPageCannotExist( $title, __METHOD__ );
  1438. return $title;
  1439. // TODO: replace the above with the code below:
  1440. // return self::castFromLinkTarget(
  1441. // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
  1442. }
  1443. /**
  1444. * Get a Title object associated with the talk page of this article,
  1445. * if such a talk page can exist.
  1446. *
  1447. * @since 1.30
  1448. *
  1449. * @return Title|null The object for the talk page,
  1450. * or null if no associated talk page can exist, according to canHaveTalkPage().
  1451. */
  1452. public function getTalkPageIfDefined() {
  1453. if ( !$this->canHaveTalkPage() ) {
  1454. return null;
  1455. }
  1456. return $this->getTalkPage();
  1457. }
  1458. /**
  1459. * Get a title object associated with the subject page of this
  1460. * talk page
  1461. *
  1462. * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
  1463. * @return Title The object for the subject page
  1464. */
  1465. public function getSubjectPage() {
  1466. // Is this the same title?
  1467. $subjectNS = MediaWikiServices::getInstance()->getNamespaceInfo()
  1468. ->getSubject( $this->mNamespace );
  1469. if ( $this->mNamespace == $subjectNS ) {
  1470. return $this;
  1471. }
  1472. // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
  1473. // Instead of failing on invalid titles, let's just log the issue for now.
  1474. // See the discussion on T227817.
  1475. $title = self::makeTitle( $subjectNS, $this->mDbkeyform );
  1476. $this->warnIfPageCannotExist( $title, __METHOD__ );
  1477. return $title;
  1478. // TODO: replace the above with the code below:
  1479. // return self::castFromLinkTarget(
  1480. // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
  1481. }
  1482. /**
  1483. * @param Title $title
  1484. * @param string $method
  1485. *
  1486. * @return bool whether a warning was issued
  1487. */
  1488. private function warnIfPageCannotExist( Title $title, $method ) {
  1489. if ( $this->getText() == '' ) {
  1490. wfLogWarning(
  1491. $method . ': called on empty title ' . $this->getFullText() . ', returning '
  1492. . $title->getFullText()
  1493. );
  1494. return true;
  1495. }
  1496. if ( $this->getInterwiki() !== '' ) {
  1497. wfLogWarning(
  1498. $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
  1499. . $title->getFullText()
  1500. );
  1501. return true;
  1502. }
  1503. return false;
  1504. }
  1505. /**
  1506. * Get the other title for this page, if this is a subject page
  1507. * get the talk page, if it is a subject page get the talk page
  1508. *
  1509. * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
  1510. * @since 1.25
  1511. * @throws MWException If the page doesn't have an other page
  1512. * @return Title
  1513. */
  1514. public function getOtherPage() {
  1515. // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
  1516. // until their semantics has become exactly the same.
  1517. // See the discussion on T227817.
  1518. if ( $this->isSpecialPage() ) {
  1519. throw new MWException( 'Special pages cannot have other pages' );
  1520. }
  1521. if ( $this->isTalkPage() ) {
  1522. return $this->getSubjectPage();
  1523. } else {
  1524. if ( !$this->canHaveTalkPage() ) {
  1525. throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
  1526. }
  1527. return $this->getTalkPage();
  1528. }
  1529. // TODO: replace the above with the code below:
  1530. // return self::castFromLinkTarget(
  1531. // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
  1532. }
  1533. /**
  1534. * Get the default namespace index, for when there is no namespace
  1535. *
  1536. * @return int Default namespace index
  1537. */
  1538. public function getDefaultNamespace() {
  1539. return $this->mDefaultNamespace;
  1540. }
  1541. /**
  1542. * Get the Title fragment (i.e.\ the bit after the #) in text form
  1543. *
  1544. * Use Title::hasFragment to check for a fragment
  1545. *
  1546. * @return string Title fragment
  1547. */
  1548. public function getFragment() {
  1549. return $this->mFragment;
  1550. }
  1551. /**
  1552. * Check if a Title fragment is set
  1553. *
  1554. * @return bool
  1555. * @since 1.23
  1556. */
  1557. public function hasFragment() {
  1558. return $this->mFragment !== '';
  1559. }
  1560. /**
  1561. * Get the fragment in URL form, including the "#" character if there is one
  1562. *
  1563. * @return string Fragment in URL form
  1564. */
  1565. public function getFragmentForURL() {
  1566. if ( !$this->hasFragment() ) {
  1567. return '';
  1568. } elseif ( $this->isExternal() ) {
  1569. // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
  1570. // so we treat it like a local interwiki.
  1571. $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
  1572. if ( $interwiki && !$interwiki->isLocal() ) {
  1573. return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
  1574. }
  1575. }
  1576. return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
  1577. }
  1578. /**
  1579. * Set the fragment for this title. Removes the first character from the
  1580. * specified fragment before setting, so it assumes you're passing it with
  1581. * an initial "#".
  1582. *
  1583. * Deprecated for public use, use Title::makeTitle() with fragment parameter,
  1584. * or Title::createFragmentTarget().
  1585. * Still in active use privately.
  1586. *
  1587. * @private
  1588. * @param string $fragment Text
  1589. */
  1590. public function setFragment( $fragment ) {
  1591. $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
  1592. }
  1593. /**
  1594. * Creates a new Title for a different fragment of the same page.
  1595. *
  1596. * @since 1.27
  1597. * @param string $fragment
  1598. * @return Title
  1599. */
  1600. public function createFragmentTarget( $fragment ) {
  1601. return self::makeTitle(
  1602. $this->mNamespace,
  1603. $this->getText(),
  1604. $fragment,
  1605. $this->mInterwiki
  1606. );
  1607. }
  1608. /**
  1609. * Prefix some arbitrary text with the namespace or interwiki prefix
  1610. * of this object
  1611. *
  1612. * @param string $name The text
  1613. * @return string The prefixed text
  1614. */
  1615. private function prefix( $name ) {
  1616. $p = '';
  1617. if ( $this->isExternal() ) {
  1618. $p = $this->mInterwiki . ':';
  1619. }
  1620. if ( $this->mNamespace != 0 ) {
  1621. $nsText = $this->getNsText();
  1622. if ( $nsText === false ) {
  1623. // See T165149. Awkward, but better than erroneously linking to the main namespace.
  1624. $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
  1625. getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
  1626. }
  1627. $p .= $nsText . ':';
  1628. }
  1629. return $p . $name;
  1630. }
  1631. /**
  1632. * Get the prefixed database key form
  1633. *
  1634. * @return string The prefixed title, with underscores and
  1635. * any interwiki and namespace prefixes
  1636. */
  1637. public function getPrefixedDBkey() {
  1638. $s = $this->prefix( $this->mDbkeyform );
  1639. $s = strtr( $s, ' ', '_' );
  1640. return $s;
  1641. }
  1642. /**
  1643. * Get the prefixed title with spaces.
  1644. * This is the form usually used for display
  1645. *
  1646. * @return string The prefixed title, with spaces
  1647. */
  1648. public function getPrefixedText() {
  1649. if ( $this->prefixedText === null ) {
  1650. $s = $this->prefix( $this->mTextform );
  1651. $s = strtr( $s, '_', ' ' );
  1652. $this->prefixedText = $s;
  1653. }
  1654. return $this->prefixedText;
  1655. }
  1656. /**
  1657. * Return a string representation of this title
  1658. *
  1659. * @return string Representation of this title
  1660. */
  1661. public function __toString() {
  1662. return $this->getPrefixedText();
  1663. }
  1664. /**
  1665. * Get the prefixed title with spaces, plus any fragment
  1666. * (part beginning with '#')
  1667. *
  1668. * @return string The prefixed title, with spaces and the fragment, including '#'
  1669. */
  1670. public function getFullText() {
  1671. $text = $this->getPrefixedText();
  1672. if ( $this->hasFragment() ) {
  1673. $text .= '#' . $this->mFragment;
  1674. }
  1675. return $text;
  1676. }
  1677. /**
  1678. * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
  1679. *
  1680. * @note the return value may contain trailing whitespace and is thus
  1681. * not safe for use with makeTitle or TitleValue.
  1682. *
  1683. * @par Example:
  1684. * @code
  1685. * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
  1686. * # returns: 'Foo'
  1687. * @endcode
  1688. *
  1689. * @return string Root name
  1690. * @since 1.20
  1691. */
  1692. public function getRootText() {
  1693. if (
  1694. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  1695. hasSubpages( $this->mNamespace )
  1696. || strtok( $this->getText(), '/' ) === false
  1697. ) {
  1698. return $this->getText();
  1699. }
  1700. return strtok( $this->getText(), '/' );
  1701. }
  1702. /**
  1703. * Get the root page name title, i.e. the leftmost part before any slashes
  1704. *
  1705. * @par Example:
  1706. * @code
  1707. * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
  1708. * # returns: Title{User:Foo}
  1709. * @endcode
  1710. *
  1711. * @return Title Root title
  1712. * @since 1.20
  1713. */
  1714. public function getRootTitle() {
  1715. $title = self::makeTitleSafe( $this->mNamespace, $this->getRootText() );
  1716. Assert::postcondition(
  1717. $title !== null,
  1718. 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
  1719. );
  1720. return $title;
  1721. }
  1722. /**
  1723. * Get the base page name without a namespace, i.e. the part before the subpage name
  1724. *
  1725. * @note the return value may contain trailing whitespace and is thus
  1726. * not safe for use with makeTitle or TitleValue.
  1727. *
  1728. * @par Example:
  1729. * @code
  1730. * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
  1731. * # returns: 'Foo/Bar'
  1732. * @endcode
  1733. *
  1734. * @return string Base name
  1735. */
  1736. public function getBaseText() {
  1737. $text = $this->getText();
  1738. if (
  1739. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  1740. hasSubpages( $this->mNamespace )
  1741. ) {
  1742. return $text;
  1743. }
  1744. $lastSlashPos = strrpos( $text, '/' );
  1745. // Don't discard the real title if there's no subpage involved
  1746. if ( $lastSlashPos === false ) {
  1747. return $text;
  1748. }
  1749. return substr( $text, 0, $lastSlashPos );
  1750. }
  1751. /**
  1752. * Get the base page name title, i.e. the part before the subpage name.
  1753. *
  1754. * @par Example:
  1755. * @code
  1756. * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
  1757. * # returns: Title{User:Foo/Bar}
  1758. * @endcode
  1759. *
  1760. * @return Title Base title
  1761. * @since 1.20
  1762. */
  1763. public function getBaseTitle() {
  1764. $title = self::makeTitleSafe( $this->mNamespace, $this->getBaseText() );
  1765. Assert::postcondition(
  1766. $title !== null,
  1767. 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
  1768. );
  1769. return $title;
  1770. }
  1771. /**
  1772. * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
  1773. *
  1774. * @par Example:
  1775. * @code
  1776. * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
  1777. * # returns: "Baz"
  1778. * @endcode
  1779. *
  1780. * @return string Subpage name
  1781. */
  1782. public function getSubpageText() {
  1783. if (
  1784. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  1785. hasSubpages( $this->mNamespace )
  1786. ) {
  1787. return $this->mTextform;
  1788. }
  1789. $parts = explode( '/', $this->mTextform );
  1790. return $parts[count( $parts ) - 1];
  1791. }
  1792. /**
  1793. * Get the title for a subpage of the current page
  1794. *
  1795. * @par Example:
  1796. * @code
  1797. * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
  1798. * # returns: Title{User:Foo/Bar/Baz/Asdf}
  1799. * @endcode
  1800. *
  1801. * @param string $text The subpage name to add to the title
  1802. * @return Title|null Subpage title, or null on an error
  1803. * @since 1.20
  1804. */
  1805. public function getSubpage( $text ) {
  1806. return self::makeTitleSafe(
  1807. $this->mNamespace,
  1808. $this->getText() . '/' . $text,
  1809. '',
  1810. $this->mInterwiki
  1811. );
  1812. }
  1813. /**
  1814. * Get a URL-encoded form of the subpage text
  1815. *
  1816. * @return string URL-encoded subpage name
  1817. */
  1818. public function getSubpageUrlForm() {
  1819. $text = $this->getSubpageText();
  1820. $text = wfUrlencode( strtr( $text, ' ', '_' ) );
  1821. return $text;
  1822. }
  1823. /**
  1824. * Get a URL-encoded title (not an actual URL) including interwiki
  1825. *
  1826. * @return string The URL-encoded form
  1827. */
  1828. public function getPrefixedURL() {
  1829. $s = $this->prefix( $this->mDbkeyform );
  1830. $s = wfUrlencode( strtr( $s, ' ', '_' ) );
  1831. return $s;
  1832. }
  1833. /**
  1834. * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
  1835. * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
  1836. * second argument named variant. This was deprecated in favor
  1837. * of passing an array of option with a "variant" key
  1838. * Once $query2 is removed for good, this helper can be dropped
  1839. * and the wfArrayToCgi moved to getLocalURL();
  1840. *
  1841. * @since 1.19 (r105919)
  1842. * @param array|string $query
  1843. * @param string|string[]|bool $query2
  1844. * @return string
  1845. */
  1846. private static function fixUrlQueryArgs( $query, $query2 = false ) {
  1847. if ( $query2 !== false ) {
  1848. wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
  1849. "method called with a second parameter is deprecated. Add your " .
  1850. "parameter to an array passed as the first parameter.", "1.19" );
  1851. }
  1852. if ( is_array( $query ) ) {
  1853. $query = wfArrayToCgi( $query );
  1854. }
  1855. if ( $query2 ) {
  1856. if ( is_string( $query2 ) ) {
  1857. // $query2 is a string, we will consider this to be
  1858. // a deprecated $variant argument and add it to the query
  1859. $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
  1860. } else {
  1861. $query2 = wfArrayToCgi( $query2 );
  1862. }
  1863. // If we have $query content add a & to it first
  1864. if ( $query ) {
  1865. $query .= '&';
  1866. }
  1867. // Now append the queries together
  1868. $query .= $query2;
  1869. }
  1870. return $query;
  1871. }
  1872. /**
  1873. * Get a real URL referring to this title, with interwiki link and
  1874. * fragment
  1875. *
  1876. * @see self::getLocalURL for the arguments.
  1877. * @see wfExpandUrl
  1878. * @param string|array $query
  1879. * @param string|string[]|bool $query2
  1880. * @param string|int|null $proto Protocol type to use in URL
  1881. * @return string The URL
  1882. */
  1883. public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
  1884. $query = self::fixUrlQueryArgs( $query, $query2 );
  1885. # Hand off all the decisions on urls to getLocalURL
  1886. $url = $this->getLocalURL( $query );
  1887. # Expand the url to make it a full url. Note that getLocalURL has the
  1888. # potential to output full urls for a variety of reasons, so we use
  1889. # wfExpandUrl instead of simply prepending $wgServer
  1890. $url = wfExpandUrl( $url, $proto );
  1891. # Finally, add the fragment.
  1892. $url .= $this->getFragmentForURL();
  1893. // Avoid PHP 7.1 warning from passing $this by reference
  1894. $titleRef = $this;
  1895. Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
  1896. return $url;
  1897. }
  1898. /**
  1899. * Get a url appropriate for making redirects based on an untrusted url arg
  1900. *
  1901. * This is basically the same as getFullUrl(), but in the case of external
  1902. * interwikis, we send the user to a landing page, to prevent possible
  1903. * phishing attacks and the like.
  1904. *
  1905. * @note Uses current protocol by default, since technically relative urls
  1906. * aren't allowed in redirects per HTTP spec, so this is not suitable for
  1907. * places where the url gets cached, as might pollute between
  1908. * https and non-https users.
  1909. * @see self::getLocalURL for the arguments.
  1910. * @param array|string $query
  1911. * @param string $proto Protocol type to use in URL
  1912. * @return string A url suitable to use in an HTTP location header.
  1913. */
  1914. public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
  1915. $target = $this;
  1916. if ( $this->isExternal() ) {
  1917. $target = SpecialPage::getTitleFor(
  1918. 'GoToInterwiki',
  1919. $this->getPrefixedDBkey()
  1920. );
  1921. }
  1922. return $target->getFullURL( $query, false, $proto );
  1923. }
  1924. /**
  1925. * Get a URL with no fragment or server name (relative URL) from a Title object.
  1926. * If this page is generated with action=render, however,
  1927. * $wgServer is prepended to make an absolute URL.
  1928. *
  1929. * @see self::getFullURL to always get an absolute URL.
  1930. * @see self::getLinkURL to always get a URL that's the simplest URL that will be
  1931. * valid to link, locally, to the current Title.
  1932. * @see self::newFromText to produce a Title object.
  1933. *
  1934. * @param string|array $query An optional query string,
  1935. * not used for interwiki links. Can be specified as an associative array as well,
  1936. * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
  1937. * Some query patterns will trigger various shorturl path replacements.
  1938. * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
  1939. * be an array. If a string is passed it will be interpreted as a deprecated
  1940. * variant argument and urlencoded into a variant= argument.
  1941. * This second query argument will be added to the $query
  1942. * The second parameter is deprecated since 1.19. Pass it as a key,value
  1943. * pair in the first parameter array instead.
  1944. *
  1945. * @return string String of the URL.
  1946. */
  1947. public function getLocalURL( $query = '', $query2 = false ) {
  1948. global $wgArticlePath, $wgScript, $wgServer, $wgRequest, $wgMainPageIsDomainRoot;
  1949. $query = self::fixUrlQueryArgs( $query, $query2 );
  1950. $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
  1951. if ( $interwiki ) {
  1952. $namespace = $this->getNsText();
  1953. if ( $namespace != '' ) {
  1954. # Can this actually happen? Interwikis shouldn't be parsed.
  1955. # Yes! It can in interwiki transclusion. But... it probably shouldn't.
  1956. $namespace .= ':';
  1957. }
  1958. $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
  1959. $url = wfAppendQuery( $url, $query );
  1960. } else {
  1961. $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
  1962. if ( $query == '' ) {
  1963. $url = str_replace( '$1', $dbkey, $wgArticlePath );
  1964. // Avoid PHP 7.1 warning from passing $this by reference
  1965. $titleRef = $this;
  1966. Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
  1967. } else {
  1968. global $wgVariantArticlePath, $wgActionPaths;
  1969. $url = false;
  1970. $matches = [];
  1971. $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
  1972. if ( $articlePaths
  1973. && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
  1974. ) {
  1975. $action = urldecode( $matches[2] );
  1976. if ( isset( $articlePaths[$action] ) ) {
  1977. $query = $matches[1];
  1978. if ( isset( $matches[4] ) ) {
  1979. $query .= $matches[4];
  1980. }
  1981. $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
  1982. if ( $query != '' ) {
  1983. $url = wfAppendQuery( $url, $query );
  1984. }
  1985. }
  1986. }
  1987. if ( $url === false
  1988. && $wgVariantArticlePath
  1989. && preg_match( '/^variant=([^&]*)$/', $query, $matches )
  1990. && $this->getPageLanguage()->equals(
  1991. MediaWikiServices::getInstance()->getContentLanguage() )
  1992. && $this->getPageLanguage()->hasVariants()
  1993. ) {
  1994. $variant = urldecode( $matches[1] );
  1995. if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
  1996. // Only do the variant replacement if the given variant is a valid
  1997. // variant for the page's language.
  1998. $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
  1999. $url = str_replace( '$1', $dbkey, $url );
  2000. }
  2001. }
  2002. if ( $url === false ) {
  2003. if ( $query == '-' ) {
  2004. $query = '';
  2005. }
  2006. $url = "{$wgScript}?title={$dbkey}&{$query}";
  2007. }
  2008. }
  2009. // Avoid PHP 7.1 warning from passing $this by reference
  2010. $titleRef = $this;
  2011. Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
  2012. // @todo FIXME: This causes breakage in various places when we
  2013. // actually expected a local URL and end up with dupe prefixes.
  2014. if ( $wgRequest->getVal( 'action' ) == 'render' ) {
  2015. $url = $wgServer . $url;
  2016. }
  2017. }
  2018. if ( $wgMainPageIsDomainRoot && $this->isMainPage() && $query === '' ) {
  2019. return '/';
  2020. }
  2021. // Avoid PHP 7.1 warning from passing $this by reference
  2022. $titleRef = $this;
  2023. Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
  2024. return $url;
  2025. }
  2026. /**
  2027. * Get a URL that's the simplest URL that will be valid to link, locally,
  2028. * to the current Title. It includes the fragment, but does not include
  2029. * the server unless action=render is used (or the link is external). If
  2030. * there's a fragment but the prefixed text is empty, we just return a link
  2031. * to the fragment.
  2032. *
  2033. * The result obviously should not be URL-escaped, but does need to be
  2034. * HTML-escaped if it's being output in HTML.
  2035. *
  2036. * @param string|string[] $query
  2037. * @param bool $query2
  2038. * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
  2039. * or false (default) for no expansion
  2040. * @see self::getLocalURL for the arguments.
  2041. * @return string The URL
  2042. */
  2043. public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
  2044. if ( $this->isExternal() || $proto !== false ) {
  2045. $ret = $this->getFullURL( $query, $query2, $proto );
  2046. } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
  2047. $ret = $this->getFragmentForURL();
  2048. } else {
  2049. $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
  2050. }
  2051. return $ret;
  2052. }
  2053. /**
  2054. * Get the URL form for an internal link.
  2055. * - Used in various CDN-related code, in case we have a different
  2056. * internal hostname for the server from the exposed one.
  2057. *
  2058. * This uses $wgInternalServer to qualify the path, or $wgServer
  2059. * if $wgInternalServer is not set. If the server variable used is
  2060. * protocol-relative, the URL will be expanded to http://
  2061. *
  2062. * @see self::getLocalURL for the arguments.
  2063. * @param string|array $query
  2064. * @param string|bool $query2 Deprecated
  2065. * @return string The URL
  2066. */
  2067. public function getInternalURL( $query = '', $query2 = false ) {
  2068. global $wgInternalServer, $wgServer;
  2069. $query = self::fixUrlQueryArgs( $query, $query2 );
  2070. $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
  2071. $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
  2072. // Avoid PHP 7.1 warning from passing $this by reference
  2073. $titleRef = $this;
  2074. Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
  2075. return $url;
  2076. }
  2077. /**
  2078. * Get the URL for a canonical link, for use in things like IRC and
  2079. * e-mail notifications. Uses $wgCanonicalServer and the
  2080. * GetCanonicalURL hook.
  2081. *
  2082. * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
  2083. *
  2084. * @see self::getLocalURL for the arguments.
  2085. * @param string|array $query
  2086. * @param string|bool $query2 Deprecated
  2087. * @return string The URL
  2088. * @since 1.18
  2089. */
  2090. public function getCanonicalURL( $query = '', $query2 = false ) {
  2091. $query = self::fixUrlQueryArgs( $query, $query2 );
  2092. $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
  2093. // Avoid PHP 7.1 warning from passing $this by reference
  2094. $titleRef = $this;
  2095. Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
  2096. return $url;
  2097. }
  2098. /**
  2099. * Get the edit URL for this Title
  2100. *
  2101. * @return string The URL, or a null string if this is an interwiki link
  2102. */
  2103. public function getEditURL() {
  2104. if ( $this->isExternal() ) {
  2105. return '';
  2106. }
  2107. $s = $this->getLocalURL( 'action=edit' );
  2108. return $s;
  2109. }
  2110. /**
  2111. * Can $user perform $action on this page?
  2112. * This skips potentially expensive cascading permission checks
  2113. * as well as avoids expensive error formatting
  2114. *
  2115. * Suitable for use for nonessential UI controls in common cases, but
  2116. * _not_ for functional access control.
  2117. *
  2118. * May provide false positives, but should never provide a false negative.
  2119. *
  2120. * @param string $action Action that permission needs to be checked for
  2121. * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
  2122. *
  2123. * @return bool
  2124. * @throws Exception
  2125. *
  2126. * @deprecated since 1.33,
  2127. * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
  2128. *
  2129. */
  2130. public function quickUserCan( $action, $user = null ) {
  2131. return $this->userCan( $action, $user, false );
  2132. }
  2133. /**
  2134. * Can $user perform $action on this page?
  2135. *
  2136. * @param string $action Action that permission needs to be checked for
  2137. * @param User|null $user User to check (since 1.19); $wgUser will be used if not
  2138. * provided.
  2139. * @param string $rigor Same format as Title::getUserPermissionsErrors()
  2140. *
  2141. * @return bool
  2142. * @throws Exception
  2143. *
  2144. * @deprecated since 1.33,
  2145. * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
  2146. *
  2147. */
  2148. public function userCan( $action, $user = null, $rigor = PermissionManager::RIGOR_SECURE ) {
  2149. if ( !$user instanceof User ) {
  2150. global $wgUser;
  2151. $user = $wgUser;
  2152. }
  2153. // TODO: this is for b/c, eventually will be removed
  2154. if ( $rigor === true ) {
  2155. $rigor = PermissionManager::RIGOR_SECURE; // b/c
  2156. } elseif ( $rigor === false ) {
  2157. $rigor = PermissionManager::RIGOR_QUICK; // b/c
  2158. }
  2159. return MediaWikiServices::getInstance()->getPermissionManager()
  2160. ->userCan( $action, $user, $this, $rigor );
  2161. }
  2162. /**
  2163. * Can $user perform $action on this page?
  2164. *
  2165. * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
  2166. *
  2167. * @param string $action Action that permission needs to be checked for
  2168. * @param User $user User to check
  2169. * @param string $rigor One of (quick,full,secure)
  2170. * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
  2171. * - full : does cheap and expensive checks possibly from a replica DB
  2172. * - secure : does cheap and expensive checks, using the master as needed
  2173. * @param array $ignoreErrors Array of Strings Set this to a list of message keys
  2174. * whose corresponding errors may be ignored.
  2175. *
  2176. * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
  2177. * @throws Exception
  2178. *
  2179. * @deprecated since 1.33,
  2180. * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
  2181. *
  2182. */
  2183. public function getUserPermissionsErrors(
  2184. $action, $user, $rigor = PermissionManager::RIGOR_SECURE, $ignoreErrors = []
  2185. ) {
  2186. // TODO: this is for b/c, eventually will be removed
  2187. if ( $rigor === true ) {
  2188. $rigor = PermissionManager::RIGOR_SECURE; // b/c
  2189. } elseif ( $rigor === false ) {
  2190. $rigor = PermissionManager::RIGOR_QUICK; // b/c
  2191. }
  2192. return MediaWikiServices::getInstance()->getPermissionManager()
  2193. ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
  2194. }
  2195. /**
  2196. * Get a filtered list of all restriction types supported by this wiki.
  2197. * @param bool $exists True to get all restriction types that apply to
  2198. * titles that do exist, False for all restriction types that apply to
  2199. * titles that do not exist
  2200. * @return array
  2201. */
  2202. public static function getFilteredRestrictionTypes( $exists = true ) {
  2203. global $wgRestrictionTypes;
  2204. $types = $wgRestrictionTypes;
  2205. if ( $exists ) {
  2206. # Remove the create restriction for existing titles
  2207. $types = array_diff( $types, [ 'create' ] );
  2208. } else {
  2209. # Only the create and upload restrictions apply to non-existing titles
  2210. $types = array_intersect( $types, [ 'create', 'upload' ] );
  2211. }
  2212. return $types;
  2213. }
  2214. /**
  2215. * Returns restriction types for the current Title
  2216. *
  2217. * @return array Applicable restriction types
  2218. */
  2219. public function getRestrictionTypes() {
  2220. if ( $this->isSpecialPage() ) {
  2221. return [];
  2222. }
  2223. $types = self::getFilteredRestrictionTypes( $this->exists() );
  2224. if ( $this->mNamespace != NS_FILE ) {
  2225. # Remove the upload restriction for non-file titles
  2226. $types = array_diff( $types, [ 'upload' ] );
  2227. }
  2228. Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
  2229. wfDebug( __METHOD__ . ': applicable restrictions to [[' .
  2230. $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
  2231. return $types;
  2232. }
  2233. /**
  2234. * Is this title subject to title protection?
  2235. * Title protection is the one applied against creation of such title.
  2236. *
  2237. * @return array|bool An associative array representing any existent title
  2238. * protection, or false if there's none.
  2239. */
  2240. public function getTitleProtection() {
  2241. $protection = $this->getTitleProtectionInternal();
  2242. if ( $protection ) {
  2243. if ( $protection['permission'] == 'sysop' ) {
  2244. $protection['permission'] = 'editprotected'; // B/C
  2245. }
  2246. if ( $protection['permission'] == 'autoconfirmed' ) {
  2247. $protection['permission'] = 'editsemiprotected'; // B/C
  2248. }
  2249. }
  2250. return $protection;
  2251. }
  2252. /**
  2253. * Fetch title protection settings
  2254. *
  2255. * To work correctly, $this->loadRestrictions() needs to have access to the
  2256. * actual protections in the database without munging 'sysop' =>
  2257. * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
  2258. * callers probably want $this->getTitleProtection() instead.
  2259. *
  2260. * @return array|bool
  2261. */
  2262. protected function getTitleProtectionInternal() {
  2263. // Can't protect pages in special namespaces
  2264. if ( $this->mNamespace < 0 ) {
  2265. return false;
  2266. }
  2267. // Can't protect pages that exist.
  2268. if ( $this->exists() ) {
  2269. return false;
  2270. }
  2271. if ( $this->mTitleProtection === null ) {
  2272. $dbr = wfGetDB( DB_REPLICA );
  2273. $commentStore = CommentStore::getStore();
  2274. $commentQuery = $commentStore->getJoin( 'pt_reason' );
  2275. $res = $dbr->select(
  2276. [ 'protected_titles' ] + $commentQuery['tables'],
  2277. [
  2278. 'user' => 'pt_user',
  2279. 'expiry' => 'pt_expiry',
  2280. 'permission' => 'pt_create_perm'
  2281. ] + $commentQuery['fields'],
  2282. [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
  2283. __METHOD__,
  2284. [],
  2285. $commentQuery['joins']
  2286. );
  2287. // fetchRow returns false if there are no rows.
  2288. $row = $dbr->fetchRow( $res );
  2289. if ( $row ) {
  2290. $this->mTitleProtection = [
  2291. 'user' => $row['user'],
  2292. 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
  2293. 'permission' => $row['permission'],
  2294. 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
  2295. ];
  2296. } else {
  2297. $this->mTitleProtection = false;
  2298. }
  2299. }
  2300. return $this->mTitleProtection;
  2301. }
  2302. /**
  2303. * Remove any title protection due to page existing
  2304. */
  2305. public function deleteTitleProtection() {
  2306. $dbw = wfGetDB( DB_MASTER );
  2307. $dbw->delete(
  2308. 'protected_titles',
  2309. [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
  2310. __METHOD__
  2311. );
  2312. $this->mTitleProtection = false;
  2313. }
  2314. /**
  2315. * Is this page "semi-protected" - the *only* protection levels are listed
  2316. * in $wgSemiprotectedRestrictionLevels?
  2317. *
  2318. * @param string $action Action to check (default: edit)
  2319. * @return bool
  2320. */
  2321. public function isSemiProtected( $action = 'edit' ) {
  2322. global $wgSemiprotectedRestrictionLevels;
  2323. $restrictions = $this->getRestrictions( $action );
  2324. $semi = $wgSemiprotectedRestrictionLevels;
  2325. if ( !$restrictions || !$semi ) {
  2326. // Not protected, or all protection is full protection
  2327. return false;
  2328. }
  2329. // Remap autoconfirmed to editsemiprotected for BC
  2330. foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
  2331. $semi[$key] = 'editsemiprotected';
  2332. }
  2333. foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
  2334. $restrictions[$key] = 'editsemiprotected';
  2335. }
  2336. return !array_diff( $restrictions, $semi );
  2337. }
  2338. /**
  2339. * Does the title correspond to a protected article?
  2340. *
  2341. * @param string $action The action the page is protected from,
  2342. * by default checks all actions.
  2343. * @return bool
  2344. */
  2345. public function isProtected( $action = '' ) {
  2346. global $wgRestrictionLevels;
  2347. $restrictionTypes = $this->getRestrictionTypes();
  2348. # Special pages have inherent protection
  2349. if ( $this->isSpecialPage() ) {
  2350. return true;
  2351. }
  2352. # Check regular protection levels
  2353. foreach ( $restrictionTypes as $type ) {
  2354. if ( $action == $type || $action == '' ) {
  2355. $r = $this->getRestrictions( $type );
  2356. foreach ( $wgRestrictionLevels as $level ) {
  2357. if ( in_array( $level, $r ) && $level != '' ) {
  2358. return true;
  2359. }
  2360. }
  2361. }
  2362. }
  2363. return false;
  2364. }
  2365. /**
  2366. * Determines if $user is unable to edit this page because it has been protected
  2367. * by $wgNamespaceProtection.
  2368. *
  2369. * @deprecated since 1.34 Don't use this function in new code.
  2370. * @param User $user User object to check permissions
  2371. * @return bool
  2372. */
  2373. public function isNamespaceProtected( User $user ) {
  2374. global $wgNamespaceProtection;
  2375. if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
  2376. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  2377. foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
  2378. if ( !$permissionManager->userHasRight( $user, $right ) ) {
  2379. return true;
  2380. }
  2381. }
  2382. }
  2383. return false;
  2384. }
  2385. /**
  2386. * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
  2387. *
  2388. * @return bool If the page is subject to cascading restrictions.
  2389. */
  2390. public function isCascadeProtected() {
  2391. list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
  2392. return ( $sources > 0 );
  2393. }
  2394. /**
  2395. * Determines whether cascading protection sources have already been loaded from
  2396. * the database.
  2397. *
  2398. * @param bool $getPages True to check if the pages are loaded, or false to check
  2399. * if the status is loaded.
  2400. * @return bool Whether or not the specified information has been loaded
  2401. * @since 1.23
  2402. */
  2403. public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
  2404. return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
  2405. }
  2406. /**
  2407. * Cascading protection: Get the source of any cascading restrictions on this page.
  2408. *
  2409. * @param bool $getPages Whether or not to retrieve the actual pages
  2410. * that the restrictions have come from and the actual restrictions
  2411. * themselves.
  2412. * @return array Two elements: First is an array of Title objects of the
  2413. * pages from which cascading restrictions have come, false for
  2414. * none, or true if such restrictions exist but $getPages was not
  2415. * set. Second is an array like that returned by
  2416. * Title::getAllRestrictions(), or an empty array if $getPages is
  2417. * false.
  2418. */
  2419. public function getCascadeProtectionSources( $getPages = true ) {
  2420. $pagerestrictions = [];
  2421. if ( $this->mCascadeSources !== null && $getPages ) {
  2422. return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
  2423. } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
  2424. return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
  2425. }
  2426. $dbr = wfGetDB( DB_REPLICA );
  2427. if ( $this->mNamespace == NS_FILE ) {
  2428. $tables = [ 'imagelinks', 'page_restrictions' ];
  2429. $where_clauses = [
  2430. 'il_to' => $this->mDbkeyform,
  2431. 'il_from=pr_page',
  2432. 'pr_cascade' => 1
  2433. ];
  2434. } else {
  2435. $tables = [ 'templatelinks', 'page_restrictions' ];
  2436. $where_clauses = [
  2437. 'tl_namespace' => $this->mNamespace,
  2438. 'tl_title' => $this->mDbkeyform,
  2439. 'tl_from=pr_page',
  2440. 'pr_cascade' => 1
  2441. ];
  2442. }
  2443. if ( $getPages ) {
  2444. $cols = [ 'pr_page', 'page_namespace', 'page_title',
  2445. 'pr_expiry', 'pr_type', 'pr_level' ];
  2446. $where_clauses[] = 'page_id=pr_page';
  2447. $tables[] = 'page';
  2448. } else {
  2449. $cols = [ 'pr_expiry' ];
  2450. }
  2451. $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
  2452. $sources = $getPages ? [] : false;
  2453. $now = wfTimestampNow();
  2454. foreach ( $res as $row ) {
  2455. $expiry = $dbr->decodeExpiry( $row->pr_expiry );
  2456. if ( $expiry > $now ) {
  2457. if ( $getPages ) {
  2458. $page_id = $row->pr_page;
  2459. $page_ns = $row->page_namespace;
  2460. $page_title = $row->page_title;
  2461. $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
  2462. # Add groups needed for each restriction type if its not already there
  2463. # Make sure this restriction type still exists
  2464. if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
  2465. $pagerestrictions[$row->pr_type] = [];
  2466. }
  2467. if (
  2468. isset( $pagerestrictions[$row->pr_type] )
  2469. && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
  2470. ) {
  2471. $pagerestrictions[$row->pr_type][] = $row->pr_level;
  2472. }
  2473. } else {
  2474. $sources = true;
  2475. }
  2476. }
  2477. }
  2478. if ( $getPages ) {
  2479. $this->mCascadeSources = $sources;
  2480. $this->mCascadingRestrictions = $pagerestrictions;
  2481. } else {
  2482. $this->mHasCascadingRestrictions = $sources;
  2483. }
  2484. return [ $sources, $pagerestrictions ];
  2485. }
  2486. /**
  2487. * Accessor for mRestrictionsLoaded
  2488. *
  2489. * @return bool Whether or not the page's restrictions have already been
  2490. * loaded from the database
  2491. * @since 1.23
  2492. */
  2493. public function areRestrictionsLoaded() {
  2494. return $this->mRestrictionsLoaded;
  2495. }
  2496. /**
  2497. * Accessor/initialisation for mRestrictions
  2498. *
  2499. * @param string $action Action that permission needs to be checked for
  2500. * @return array Restriction levels needed to take the action. All levels are
  2501. * required. Note that restriction levels are normally user rights, but 'sysop'
  2502. * and 'autoconfirmed' are also allowed for backwards compatibility. These should
  2503. * be mapped to 'editprotected' and 'editsemiprotected' respectively.
  2504. */
  2505. public function getRestrictions( $action ) {
  2506. if ( !$this->mRestrictionsLoaded ) {
  2507. $this->loadRestrictions();
  2508. }
  2509. return $this->mRestrictions[$action] ?? [];
  2510. }
  2511. /**
  2512. * Accessor/initialisation for mRestrictions
  2513. *
  2514. * @return array Keys are actions, values are arrays as returned by
  2515. * Title::getRestrictions()
  2516. * @since 1.23
  2517. */
  2518. public function getAllRestrictions() {
  2519. if ( !$this->mRestrictionsLoaded ) {
  2520. $this->loadRestrictions();
  2521. }
  2522. return $this->mRestrictions;
  2523. }
  2524. /**
  2525. * Get the expiry time for the restriction against a given action
  2526. *
  2527. * @param string $action
  2528. * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
  2529. * or not protected at all, or false if the action is not recognised.
  2530. */
  2531. public function getRestrictionExpiry( $action ) {
  2532. if ( !$this->mRestrictionsLoaded ) {
  2533. $this->loadRestrictions();
  2534. }
  2535. return $this->mRestrictionsExpiry[$action] ?? false;
  2536. }
  2537. /**
  2538. * Returns cascading restrictions for the current article
  2539. *
  2540. * @return bool
  2541. */
  2542. function areRestrictionsCascading() {
  2543. if ( !$this->mRestrictionsLoaded ) {
  2544. $this->loadRestrictions();
  2545. }
  2546. return $this->mCascadeRestriction;
  2547. }
  2548. /**
  2549. * Compiles list of active page restrictions from both page table (pre 1.10)
  2550. * and page_restrictions table for this existing page.
  2551. * Public for usage by LiquidThreads.
  2552. *
  2553. * @param array $rows Array of db result objects
  2554. * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
  2555. * indicating who can move or edit the page from the page table, (pre 1.10) rows.
  2556. * Edit and move sections are separated by a colon
  2557. * Example: "edit=autoconfirmed,sysop:move=sysop"
  2558. */
  2559. public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
  2560. // This function will only read rows from a table that we migrated away
  2561. // from before adding READ_LATEST support to loadRestrictions, so we
  2562. // don't need to support reading from DB_MASTER here.
  2563. $dbr = wfGetDB( DB_REPLICA );
  2564. $restrictionTypes = $this->getRestrictionTypes();
  2565. foreach ( $restrictionTypes as $type ) {
  2566. $this->mRestrictions[$type] = [];
  2567. $this->mRestrictionsExpiry[$type] = 'infinity';
  2568. }
  2569. $this->mCascadeRestriction = false;
  2570. # Backwards-compatibility: also load the restrictions from the page record (old format).
  2571. if ( $oldFashionedRestrictions !== null ) {
  2572. $this->mOldRestrictions = $oldFashionedRestrictions;
  2573. }
  2574. if ( $this->mOldRestrictions === false ) {
  2575. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2576. $linkCache->addLinkObj( $this ); # in case we already had an article ID
  2577. $this->mOldRestrictions = $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
  2578. }
  2579. if ( $this->mOldRestrictions != '' ) {
  2580. foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
  2581. $temp = explode( '=', trim( $restrict ) );
  2582. if ( count( $temp ) == 1 ) {
  2583. // old old format should be treated as edit/move restriction
  2584. $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
  2585. $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
  2586. } else {
  2587. $restriction = trim( $temp[1] );
  2588. if ( $restriction != '' ) { // some old entries are empty
  2589. $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
  2590. }
  2591. }
  2592. }
  2593. }
  2594. if ( count( $rows ) ) {
  2595. # Current system - load second to make them override.
  2596. $now = wfTimestampNow();
  2597. # Cycle through all the restrictions.
  2598. foreach ( $rows as $row ) {
  2599. // Don't take care of restrictions types that aren't allowed
  2600. if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
  2601. continue;
  2602. }
  2603. $expiry = $dbr->decodeExpiry( $row->pr_expiry );
  2604. // Only apply the restrictions if they haven't expired!
  2605. if ( !$expiry || $expiry > $now ) {
  2606. $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
  2607. $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
  2608. $this->mCascadeRestriction |= $row->pr_cascade;
  2609. }
  2610. }
  2611. }
  2612. $this->mRestrictionsLoaded = true;
  2613. }
  2614. /**
  2615. * Load restrictions from the page_restrictions table
  2616. *
  2617. * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
  2618. * indicating who can move or edit the page from the page table, (pre 1.10) rows.
  2619. * Edit and move sections are separated by a colon
  2620. * Example: "edit=autoconfirmed,sysop:move=sysop"
  2621. * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
  2622. * from the master DB.
  2623. */
  2624. public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
  2625. $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
  2626. if ( $this->mRestrictionsLoaded && !$readLatest ) {
  2627. return;
  2628. }
  2629. $id = $this->getArticleID( $flags );
  2630. if ( $id ) {
  2631. $fname = __METHOD__;
  2632. $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
  2633. return iterator_to_array(
  2634. $dbr->select(
  2635. 'page_restrictions',
  2636. [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
  2637. [ 'pr_page' => $id ],
  2638. $fname
  2639. )
  2640. );
  2641. };
  2642. if ( $readLatest ) {
  2643. $dbr = wfGetDB( DB_MASTER );
  2644. $rows = $loadRestrictionsFromDb( $dbr );
  2645. } else {
  2646. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  2647. $rows = $cache->getWithSetCallback(
  2648. // Page protections always leave a new null revision
  2649. $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
  2650. $cache::TTL_DAY,
  2651. function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
  2652. $dbr = wfGetDB( DB_REPLICA );
  2653. $setOpts += Database::getCacheSetOptions( $dbr );
  2654. $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
  2655. if ( $lb->hasOrMadeRecentMasterChanges() ) {
  2656. // @TODO: cleanup Title cache and caller assumption mess in general
  2657. $ttl = WANObjectCache::TTL_UNCACHEABLE;
  2658. }
  2659. return $loadRestrictionsFromDb( $dbr );
  2660. }
  2661. );
  2662. }
  2663. $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
  2664. } else {
  2665. $title_protection = $this->getTitleProtectionInternal();
  2666. if ( $title_protection ) {
  2667. $now = wfTimestampNow();
  2668. $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
  2669. if ( !$expiry || $expiry > $now ) {
  2670. // Apply the restrictions
  2671. $this->mRestrictionsExpiry['create'] = $expiry;
  2672. $this->mRestrictions['create'] =
  2673. explode( ',', trim( $title_protection['permission'] ) );
  2674. } else { // Get rid of the old restrictions
  2675. $this->mTitleProtection = false;
  2676. }
  2677. } else {
  2678. $this->mRestrictionsExpiry['create'] = 'infinity';
  2679. }
  2680. $this->mRestrictionsLoaded = true;
  2681. }
  2682. }
  2683. /**
  2684. * Flush the protection cache in this object and force reload from the database.
  2685. * This is used when updating protection from WikiPage::doUpdateRestrictions().
  2686. */
  2687. public function flushRestrictions() {
  2688. $this->mRestrictionsLoaded = false;
  2689. $this->mTitleProtection = null;
  2690. }
  2691. /**
  2692. * Purge expired restrictions from the page_restrictions table
  2693. *
  2694. * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
  2695. */
  2696. static function purgeExpiredRestrictions() {
  2697. if ( wfReadOnly() ) {
  2698. return;
  2699. }
  2700. DeferredUpdates::addUpdate( new AtomicSectionUpdate(
  2701. wfGetDB( DB_MASTER ),
  2702. __METHOD__,
  2703. function ( IDatabase $dbw, $fname ) {
  2704. $config = MediaWikiServices::getInstance()->getMainConfig();
  2705. $ids = $dbw->selectFieldValues(
  2706. 'page_restrictions',
  2707. 'pr_id',
  2708. [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
  2709. $fname,
  2710. [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
  2711. );
  2712. if ( $ids ) {
  2713. $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
  2714. }
  2715. }
  2716. ) );
  2717. DeferredUpdates::addUpdate( new AtomicSectionUpdate(
  2718. wfGetDB( DB_MASTER ),
  2719. __METHOD__,
  2720. function ( IDatabase $dbw, $fname ) {
  2721. $dbw->delete(
  2722. 'protected_titles',
  2723. [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
  2724. $fname
  2725. );
  2726. }
  2727. ) );
  2728. }
  2729. /**
  2730. * Does this have subpages? (Warning, usually requires an extra DB query.)
  2731. *
  2732. * @return bool
  2733. */
  2734. public function hasSubpages() {
  2735. if (
  2736. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  2737. hasSubpages( $this->mNamespace )
  2738. ) {
  2739. # Duh
  2740. return false;
  2741. }
  2742. # We dynamically add a member variable for the purpose of this method
  2743. # alone to cache the result. There's no point in having it hanging
  2744. # around uninitialized in every Title object; therefore we only add it
  2745. # if needed and don't declare it statically.
  2746. if ( $this->mHasSubpages === null ) {
  2747. $this->mHasSubpages = false;
  2748. $subpages = $this->getSubpages( 1 );
  2749. if ( $subpages instanceof TitleArray ) {
  2750. $this->mHasSubpages = (bool)$subpages->current();
  2751. }
  2752. }
  2753. return $this->mHasSubpages;
  2754. }
  2755. /**
  2756. * Get all subpages of this page.
  2757. *
  2758. * @param int $limit Maximum number of subpages to fetch; -1 for no limit
  2759. * @return TitleArray|array TitleArray, or empty array if this page's namespace
  2760. * doesn't allow subpages
  2761. */
  2762. public function getSubpages( $limit = -1 ) {
  2763. if (
  2764. !MediaWikiServices::getInstance()->getNamespaceInfo()->
  2765. hasSubpages( $this->mNamespace )
  2766. ) {
  2767. return [];
  2768. }
  2769. $dbr = wfGetDB( DB_REPLICA );
  2770. $conds = [ 'page_namespace' => $this->mNamespace ];
  2771. $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
  2772. $options = [];
  2773. if ( $limit > -1 ) {
  2774. $options['LIMIT'] = $limit;
  2775. }
  2776. return TitleArray::newFromResult(
  2777. $dbr->select( 'page',
  2778. [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
  2779. $conds,
  2780. __METHOD__,
  2781. $options
  2782. )
  2783. );
  2784. }
  2785. /**
  2786. * Is there a version of this page in the deletion archive?
  2787. *
  2788. * @return int The number of archived revisions
  2789. */
  2790. public function isDeleted() {
  2791. if ( $this->mNamespace < 0 ) {
  2792. $n = 0;
  2793. } else {
  2794. $dbr = wfGetDB( DB_REPLICA );
  2795. $n = $dbr->selectField( 'archive', 'COUNT(*)',
  2796. [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
  2797. __METHOD__
  2798. );
  2799. if ( $this->mNamespace == NS_FILE ) {
  2800. $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
  2801. [ 'fa_name' => $this->mDbkeyform ],
  2802. __METHOD__
  2803. );
  2804. }
  2805. }
  2806. return (int)$n;
  2807. }
  2808. /**
  2809. * Is there a version of this page in the deletion archive?
  2810. *
  2811. * @return bool
  2812. */
  2813. public function isDeletedQuick() {
  2814. if ( $this->mNamespace < 0 ) {
  2815. return false;
  2816. }
  2817. $dbr = wfGetDB( DB_REPLICA );
  2818. $deleted = (bool)$dbr->selectField( 'archive', '1',
  2819. [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
  2820. __METHOD__
  2821. );
  2822. if ( !$deleted && $this->mNamespace == NS_FILE ) {
  2823. $deleted = (bool)$dbr->selectField( 'filearchive', '1',
  2824. [ 'fa_name' => $this->mDbkeyform ],
  2825. __METHOD__
  2826. );
  2827. }
  2828. return $deleted;
  2829. }
  2830. /**
  2831. * Get the article ID for this Title from the link cache,
  2832. * adding it if necessary
  2833. *
  2834. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  2835. * @return int The ID
  2836. */
  2837. public function getArticleID( $flags = 0 ) {
  2838. if ( $this->mNamespace < 0 ) {
  2839. $this->mArticleID = 0;
  2840. return $this->mArticleID;
  2841. }
  2842. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2843. if ( $flags & self::GAID_FOR_UPDATE ) {
  2844. $oldUpdate = $linkCache->forUpdate( true );
  2845. $linkCache->clearLink( $this );
  2846. $this->mArticleID = $linkCache->addLinkObj( $this );
  2847. $linkCache->forUpdate( $oldUpdate );
  2848. } elseif ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
  2849. $this->mArticleID = (int)$this->loadFieldFromDB( 'page_id', $flags );
  2850. } elseif ( $this->mArticleID == -1 ) {
  2851. $this->mArticleID = $linkCache->addLinkObj( $this );
  2852. }
  2853. return $this->mArticleID;
  2854. }
  2855. /**
  2856. * Is this an article that is a redirect page?
  2857. * Uses link cache, adding it if necessary
  2858. *
  2859. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  2860. * @return bool
  2861. */
  2862. public function isRedirect( $flags = 0 ) {
  2863. if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
  2864. $this->mRedirect = (bool)$this->loadFieldFromDB( 'page_is_redirect', $flags );
  2865. } else {
  2866. if ( $this->mRedirect !== null ) {
  2867. return $this->mRedirect;
  2868. } elseif ( !$this->getArticleID( $flags ) ) {
  2869. $this->mRedirect = false;
  2870. return $this->mRedirect;
  2871. }
  2872. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2873. $linkCache->addLinkObj( $this ); // in case we already had an article ID
  2874. // Note that LinkCache returns null if it thinks the page does not exist;
  2875. // always trust the state of LinkCache over that of this Title instance.
  2876. $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
  2877. }
  2878. return $this->mRedirect;
  2879. }
  2880. /**
  2881. * What is the length of this page?
  2882. * Uses link cache, adding it if necessary
  2883. *
  2884. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  2885. * @return int
  2886. */
  2887. public function getLength( $flags = 0 ) {
  2888. if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
  2889. $this->mLength = (int)$this->loadFieldFromDB( 'page_len', $flags );
  2890. } else {
  2891. if ( $this->mLength != -1 ) {
  2892. return $this->mLength;
  2893. } elseif ( !$this->getArticleID( $flags ) ) {
  2894. $this->mLength = 0;
  2895. return $this->mLength;
  2896. }
  2897. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2898. $linkCache->addLinkObj( $this ); // in case we already had an article ID
  2899. // Note that LinkCache returns null if it thinks the page does not exist;
  2900. // always trust the state of LinkCache over that of this Title instance.
  2901. $this->mLength = (int)$linkCache->getGoodLinkFieldObj( $this, 'length' );
  2902. }
  2903. return $this->mLength;
  2904. }
  2905. /**
  2906. * What is the page_latest field for this page?
  2907. *
  2908. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  2909. * @return int Int or 0 if the page doesn't exist
  2910. */
  2911. public function getLatestRevID( $flags = 0 ) {
  2912. if ( DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST ) ) {
  2913. $this->mLatestID = (int)$this->loadFieldFromDB( 'page_latest', $flags );
  2914. } else {
  2915. if ( $this->mLatestID !== false ) {
  2916. return (int)$this->mLatestID;
  2917. } elseif ( !$this->getArticleID( $flags ) ) {
  2918. $this->mLatestID = 0;
  2919. return $this->mLatestID;
  2920. }
  2921. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2922. $linkCache->addLinkObj( $this ); // in case we already had an article ID
  2923. // Note that LinkCache returns null if it thinks the page does not exist;
  2924. // always trust the state of LinkCache over that of this Title instance.
  2925. $this->mLatestID = (int)$linkCache->getGoodLinkFieldObj( $this, 'revision' );
  2926. }
  2927. return $this->mLatestID;
  2928. }
  2929. /**
  2930. * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
  2931. *
  2932. * This can be called on page insertion to allow loading of the new page_id without
  2933. * having to create a new Title instance. Likewise with deletion.
  2934. *
  2935. * @note This overrides Title::setContentModel()
  2936. *
  2937. * @param int|bool $id Page ID, 0 for non-existant, or false for "unknown" (lazy-load)
  2938. */
  2939. public function resetArticleID( $id ) {
  2940. if ( $id === false ) {
  2941. $this->mArticleID = -1;
  2942. } else {
  2943. $this->mArticleID = (int)$id;
  2944. }
  2945. $this->mRestrictionsLoaded = false;
  2946. $this->mRestrictions = [];
  2947. $this->mOldRestrictions = false;
  2948. $this->mRedirect = null;
  2949. $this->mLength = -1;
  2950. $this->mLatestID = false;
  2951. $this->mContentModel = false;
  2952. $this->mForcedContentModel = false;
  2953. $this->mEstimateRevisions = null;
  2954. $this->mPageLanguage = null;
  2955. $this->mDbPageLanguage = false;
  2956. $this->mIsBigDeletion = null;
  2957. MediaWikiServices::getInstance()->getLinkCache()->clearLink( $this );
  2958. }
  2959. public static function clearCaches() {
  2960. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  2961. $linkCache->clear();
  2962. $titleCache = self::getTitleCache();
  2963. $titleCache->clear();
  2964. }
  2965. /**
  2966. * Capitalize a text string for a title if it belongs to a namespace that capitalizes
  2967. *
  2968. * @param string $text Containing title to capitalize
  2969. * @param int $ns Namespace index, defaults to NS_MAIN
  2970. * @return string Containing capitalized title
  2971. */
  2972. public static function capitalize( $text, $ns = NS_MAIN ) {
  2973. $services = MediaWikiServices::getInstance();
  2974. if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
  2975. return $services->getContentLanguage()->ucfirst( $text );
  2976. } else {
  2977. return $text;
  2978. }
  2979. }
  2980. /**
  2981. * Secure and split - main initialisation function for this object
  2982. *
  2983. * Assumes that mDbkeyform has been set, and is urldecoded
  2984. * and uses underscores, but not otherwise munged. This function
  2985. * removes illegal characters, splits off the interwiki and
  2986. * namespace prefixes, sets the other forms, and canonicalizes
  2987. * everything.
  2988. *
  2989. * @throws MalformedTitleException On invalid titles
  2990. * @return bool True on success
  2991. */
  2992. private function secureAndSplit() {
  2993. // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
  2994. // the parsing code with Title, while avoiding massive refactoring.
  2995. // @todo: get rid of secureAndSplit, refactor parsing code.
  2996. // @note: getTitleParser() returns a TitleParser implementation which does not have a
  2997. // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
  2998. /** @var MediaWikiTitleCodec $titleCodec */
  2999. $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
  3000. '@phan-var MediaWikiTitleCodec $titleCodec';
  3001. // MalformedTitleException can be thrown here
  3002. $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
  3003. # Fill fields
  3004. $this->setFragment( '#' . $parts['fragment'] );
  3005. $this->mInterwiki = $parts['interwiki'];
  3006. $this->mLocalInterwiki = $parts['local_interwiki'];
  3007. $this->mNamespace = $parts['namespace'];
  3008. $this->mUserCaseDBKey = $parts['user_case_dbkey'];
  3009. $this->mDbkeyform = $parts['dbkey'];
  3010. $this->mUrlform = wfUrlencode( $this->mDbkeyform );
  3011. $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
  3012. # We already know that some pages won't be in the database!
  3013. if ( $this->isExternal() || $this->isSpecialPage() ) {
  3014. $this->mArticleID = 0;
  3015. }
  3016. return true;
  3017. }
  3018. /**
  3019. * Get an array of Title objects linking to this Title
  3020. * Also stores the IDs in the link cache.
  3021. *
  3022. * WARNING: do not use this function on arbitrary user-supplied titles!
  3023. * On heavily-used templates it will max out the memory.
  3024. *
  3025. * @param array $options May be FOR UPDATE
  3026. * @param string $table Table name
  3027. * @param string $prefix Fields prefix
  3028. * @return Title[] Array of Title objects linking here
  3029. */
  3030. public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
  3031. if ( count( $options ) > 0 ) {
  3032. $db = wfGetDB( DB_MASTER );
  3033. } else {
  3034. $db = wfGetDB( DB_REPLICA );
  3035. }
  3036. $res = $db->select(
  3037. [ 'page', $table ],
  3038. self::getSelectFields(),
  3039. [
  3040. "{$prefix}_from=page_id",
  3041. "{$prefix}_namespace" => $this->mNamespace,
  3042. "{$prefix}_title" => $this->mDbkeyform ],
  3043. __METHOD__,
  3044. $options
  3045. );
  3046. $retVal = [];
  3047. if ( $res->numRows() ) {
  3048. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  3049. foreach ( $res as $row ) {
  3050. $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
  3051. if ( $titleObj ) {
  3052. $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
  3053. $retVal[] = $titleObj;
  3054. }
  3055. }
  3056. }
  3057. return $retVal;
  3058. }
  3059. /**
  3060. * Get an array of Title objects using this Title as a template
  3061. * Also stores the IDs in the link cache.
  3062. *
  3063. * WARNING: do not use this function on arbitrary user-supplied titles!
  3064. * On heavily-used templates it will max out the memory.
  3065. *
  3066. * @param array $options Query option to Database::select()
  3067. * @return Title[] Array of Title the Title objects linking here
  3068. */
  3069. public function getTemplateLinksTo( $options = [] ) {
  3070. return $this->getLinksTo( $options, 'templatelinks', 'tl' );
  3071. }
  3072. /**
  3073. * Get an array of Title objects linked from this Title
  3074. * Also stores the IDs in the link cache.
  3075. *
  3076. * WARNING: do not use this function on arbitrary user-supplied titles!
  3077. * On heavily-used templates it will max out the memory.
  3078. *
  3079. * @param array $options Query option to Database::select()
  3080. * @param string $table Table name
  3081. * @param string $prefix Fields prefix
  3082. * @return array Array of Title objects linking here
  3083. */
  3084. public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
  3085. $id = $this->getArticleID();
  3086. # If the page doesn't exist; there can't be any link from this page
  3087. if ( !$id ) {
  3088. return [];
  3089. }
  3090. $db = wfGetDB( DB_REPLICA );
  3091. $blNamespace = "{$prefix}_namespace";
  3092. $blTitle = "{$prefix}_title";
  3093. $pageQuery = WikiPage::getQueryInfo();
  3094. $res = $db->select(
  3095. [ $table, 'nestpage' => $pageQuery['tables'] ],
  3096. array_merge(
  3097. [ $blNamespace, $blTitle ],
  3098. $pageQuery['fields']
  3099. ),
  3100. [ "{$prefix}_from" => $id ],
  3101. __METHOD__,
  3102. $options,
  3103. [ 'nestpage' => [
  3104. 'LEFT JOIN',
  3105. [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
  3106. ] ] + $pageQuery['joins']
  3107. );
  3108. $retVal = [];
  3109. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  3110. foreach ( $res as $row ) {
  3111. if ( $row->page_id ) {
  3112. $titleObj = self::newFromRow( $row );
  3113. } else {
  3114. $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
  3115. $linkCache->addBadLinkObj( $titleObj );
  3116. }
  3117. $retVal[] = $titleObj;
  3118. }
  3119. return $retVal;
  3120. }
  3121. /**
  3122. * Get an array of Title objects used on this Title as a template
  3123. * Also stores the IDs in the link cache.
  3124. *
  3125. * WARNING: do not use this function on arbitrary user-supplied titles!
  3126. * On heavily-used templates it will max out the memory.
  3127. *
  3128. * @param array $options May be FOR UPDATE
  3129. * @return Title[] Array of Title the Title objects used here
  3130. */
  3131. public function getTemplateLinksFrom( $options = [] ) {
  3132. return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
  3133. }
  3134. /**
  3135. * Get an array of Title objects referring to non-existent articles linked
  3136. * from this page.
  3137. *
  3138. * @todo check if needed (used only in SpecialBrokenRedirects.php, and
  3139. * should use redirect table in this case).
  3140. * @return Title[] Array of Title the Title objects
  3141. */
  3142. public function getBrokenLinksFrom() {
  3143. if ( $this->getArticleID() == 0 ) {
  3144. # All links from article ID 0 are false positives
  3145. return [];
  3146. }
  3147. $dbr = wfGetDB( DB_REPLICA );
  3148. $res = $dbr->select(
  3149. [ 'page', 'pagelinks' ],
  3150. [ 'pl_namespace', 'pl_title' ],
  3151. [
  3152. 'pl_from' => $this->getArticleID(),
  3153. 'page_namespace IS NULL'
  3154. ],
  3155. __METHOD__, [],
  3156. [
  3157. 'page' => [
  3158. 'LEFT JOIN',
  3159. [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
  3160. ]
  3161. ]
  3162. );
  3163. $retVal = [];
  3164. foreach ( $res as $row ) {
  3165. $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
  3166. }
  3167. return $retVal;
  3168. }
  3169. /**
  3170. * Get a list of URLs to purge from the CDN cache when this
  3171. * page changes
  3172. *
  3173. * @return string[] Array of String the URLs
  3174. */
  3175. public function getCdnUrls() {
  3176. $urls = [
  3177. $this->getInternalURL(),
  3178. $this->getInternalURL( 'action=history' )
  3179. ];
  3180. $pageLang = $this->getPageLanguage();
  3181. if ( $pageLang->hasVariants() ) {
  3182. $variants = $pageLang->getVariants();
  3183. foreach ( $variants as $vCode ) {
  3184. $urls[] = $this->getInternalURL( $vCode );
  3185. }
  3186. }
  3187. // If we are looking at a css/js user subpage, purge the action=raw.
  3188. if ( $this->isUserJsConfigPage() ) {
  3189. $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
  3190. } elseif ( $this->isUserJsonConfigPage() ) {
  3191. $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
  3192. } elseif ( $this->isUserCssConfigPage() ) {
  3193. $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
  3194. }
  3195. Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
  3196. return $urls;
  3197. }
  3198. /**
  3199. * Purge all applicable CDN URLs
  3200. */
  3201. public function purgeSquid() {
  3202. DeferredUpdates::addUpdate(
  3203. new CdnCacheUpdate( $this->getCdnUrls() ),
  3204. DeferredUpdates::PRESEND
  3205. );
  3206. }
  3207. /**
  3208. * Check whether a given move operation would be valid.
  3209. * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
  3210. *
  3211. * @deprecated since 1.25, use MovePage's methods instead
  3212. * @param Title &$nt The new title
  3213. * @param bool $auth Whether to check user permissions (uses $wgUser)
  3214. * @param string $reason Is the log summary of the move, used for spam checking
  3215. * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
  3216. */
  3217. public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
  3218. wfDeprecated( __METHOD__, '1.25' );
  3219. global $wgUser;
  3220. if ( !( $nt instanceof Title ) ) {
  3221. // Normally we'd add this to $errors, but we'll get
  3222. // lots of syntax errors if $nt is not an object
  3223. return [ [ 'badtitletext' ] ];
  3224. }
  3225. $mp = MediaWikiServices::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
  3226. $errors = $mp->isValidMove()->getErrorsArray();
  3227. if ( $auth ) {
  3228. $errors = wfMergeErrorArrays(
  3229. $errors,
  3230. $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
  3231. );
  3232. }
  3233. return $errors ?: true;
  3234. }
  3235. /**
  3236. * Move a title to a new location
  3237. *
  3238. * @deprecated since 1.25, use the MovePage class instead
  3239. * @param Title &$nt The new title
  3240. * @param bool $auth Indicates whether $wgUser's permissions
  3241. * should be checked
  3242. * @param string $reason The reason for the move
  3243. * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
  3244. * Ignored if the user doesn't have the suppressredirect right.
  3245. * @param array $changeTags Applied to the entry in the move log and redirect page revision
  3246. * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
  3247. */
  3248. public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
  3249. array $changeTags = []
  3250. ) {
  3251. wfDeprecated( __METHOD__, '1.25' );
  3252. global $wgUser;
  3253. $mp = MediaWikiServices::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
  3254. $method = $auth ? 'moveIfAllowed' : 'move';
  3255. /** @var Status $status */
  3256. $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
  3257. if ( $status->isOK() ) {
  3258. return true;
  3259. } else {
  3260. return $status->getErrorsArray();
  3261. }
  3262. }
  3263. /**
  3264. * Move this page's subpages to be subpages of $nt
  3265. *
  3266. * @deprecated since 1.34, use MovePage instead
  3267. * @param Title $nt Move target
  3268. * @param bool $auth Whether $wgUser's permissions should be checked
  3269. * @param string $reason The reason for the move
  3270. * @param bool $createRedirect Whether to create redirects from the old subpages to
  3271. * the new ones Ignored if the user doesn't have the 'suppressredirect' right
  3272. * @param array $changeTags Applied to the entry in the move log and redirect page revision
  3273. * @return array Array with old page titles as keys, and strings (new page titles) or
  3274. * getUserPermissionsErrors()-like arrays (errors) as values, or a
  3275. * getUserPermissionsErrors()-like error array with numeric indices if
  3276. * no pages were moved
  3277. */
  3278. public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
  3279. array $changeTags = []
  3280. ) {
  3281. wfDeprecated( __METHOD__, '1.34' );
  3282. global $wgUser;
  3283. $mp = new MovePage( $this, $nt );
  3284. $method = $auth ? 'moveSubpagesIfAllowed' : 'moveSubpages';
  3285. /** @var Status $result */
  3286. $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
  3287. if ( !$result->isOK() ) {
  3288. return $result->getErrorsArray();
  3289. }
  3290. $retval = [];
  3291. foreach ( $result->getValue() as $key => $status ) {
  3292. /** @var Status $status */
  3293. if ( $status->isOK() ) {
  3294. $retval[$key] = $status->getValue();
  3295. } else {
  3296. $retval[$key] = $status->getErrorsArray();
  3297. }
  3298. }
  3299. return $retval;
  3300. }
  3301. /**
  3302. * Locks the page row and check if this page is single revision redirect
  3303. *
  3304. * This updates the cached fields of this instance via Title::loadFromRow()
  3305. *
  3306. * @return bool
  3307. */
  3308. public function isSingleRevRedirect() {
  3309. global $wgContentHandlerUseDB;
  3310. $dbw = wfGetDB( DB_MASTER );
  3311. # Is it a redirect?
  3312. $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
  3313. if ( $wgContentHandlerUseDB ) {
  3314. $fields[] = 'page_content_model';
  3315. }
  3316. $row = $dbw->selectRow( 'page',
  3317. $fields,
  3318. $this->pageCond(),
  3319. __METHOD__,
  3320. [ 'FOR UPDATE' ]
  3321. );
  3322. # Cache some fields we may want
  3323. $this->mArticleID = $row ? intval( $row->page_id ) : 0;
  3324. $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
  3325. $this->mLatestID = $row ? intval( $row->page_latest ) : false;
  3326. $this->mContentModel = $row && isset( $row->page_content_model )
  3327. ? strval( $row->page_content_model )
  3328. : false;
  3329. if ( !$this->mRedirect ) {
  3330. return false;
  3331. }
  3332. # Does the article have a history?
  3333. $row = $dbw->selectField( [ 'page', 'revision' ],
  3334. 'rev_id',
  3335. [ 'page_namespace' => $this->mNamespace,
  3336. 'page_title' => $this->mDbkeyform,
  3337. 'page_id=rev_page',
  3338. 'page_latest != rev_id'
  3339. ],
  3340. __METHOD__,
  3341. [ 'FOR UPDATE' ]
  3342. );
  3343. # Return true if there was no history
  3344. return ( $row === false );
  3345. }
  3346. /**
  3347. * Checks if $this can be moved to a given Title
  3348. * - Selects for update, so don't call it unless you mean business
  3349. *
  3350. * @deprecated since 1.25, use MovePage's methods instead
  3351. * @param Title $nt The new title to check
  3352. * @return bool
  3353. */
  3354. public function isValidMoveTarget( $nt ) {
  3355. wfDeprecated( __METHOD__, '1.25' );
  3356. # Is it an existing file?
  3357. if ( $nt->getNamespace() == NS_FILE ) {
  3358. $file = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
  3359. ->newFile( $nt );
  3360. $file->load( File::READ_LATEST );
  3361. if ( $file->exists() ) {
  3362. wfDebug( __METHOD__ . ": file exists\n" );
  3363. return false;
  3364. }
  3365. }
  3366. # Is it a redirect with no history?
  3367. if ( !$nt->isSingleRevRedirect() ) {
  3368. wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
  3369. return false;
  3370. }
  3371. # Get the article text
  3372. $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
  3373. if ( !is_object( $rev ) ) {
  3374. return false;
  3375. }
  3376. $content = $rev->getContent();
  3377. # Does the redirect point to the source?
  3378. # Or is it a broken self-redirect, usually caused by namespace collisions?
  3379. $redirTitle = $content ? $content->getRedirectTarget() : null;
  3380. if ( $redirTitle ) {
  3381. if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
  3382. $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
  3383. wfDebug( __METHOD__ . ": redirect points to other page\n" );
  3384. return false;
  3385. } else {
  3386. return true;
  3387. }
  3388. } else {
  3389. # Fail safe (not a redirect after all. strange.)
  3390. wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
  3391. " is a redirect, but it doesn't contain a valid redirect.\n" );
  3392. return false;
  3393. }
  3394. }
  3395. /**
  3396. * Get categories to which this Title belongs and return an array of
  3397. * categories' names.
  3398. *
  3399. * @return array Array of parents in the form:
  3400. * $parent => $currentarticle
  3401. */
  3402. public function getParentCategories() {
  3403. $data = [];
  3404. $titleKey = $this->getArticleID();
  3405. if ( $titleKey === 0 ) {
  3406. return $data;
  3407. }
  3408. $dbr = wfGetDB( DB_REPLICA );
  3409. $res = $dbr->select(
  3410. 'categorylinks',
  3411. 'cl_to',
  3412. [ 'cl_from' => $titleKey ],
  3413. __METHOD__
  3414. );
  3415. if ( $res->numRows() > 0 ) {
  3416. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  3417. foreach ( $res as $row ) {
  3418. // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
  3419. $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
  3420. $this->getFullText();
  3421. }
  3422. }
  3423. return $data;
  3424. }
  3425. /**
  3426. * Get a tree of parent categories
  3427. *
  3428. * @param array $children Array with the children in the keys, to check for circular refs
  3429. * @return array Tree of parent categories
  3430. */
  3431. public function getParentCategoryTree( $children = [] ) {
  3432. $stack = [];
  3433. $parents = $this->getParentCategories();
  3434. if ( $parents ) {
  3435. foreach ( $parents as $parent => $current ) {
  3436. if ( array_key_exists( $parent, $children ) ) {
  3437. # Circular reference
  3438. $stack[$parent] = [];
  3439. } else {
  3440. $nt = self::newFromText( $parent );
  3441. if ( $nt ) {
  3442. $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
  3443. }
  3444. }
  3445. }
  3446. }
  3447. return $stack;
  3448. }
  3449. /**
  3450. * Get an associative array for selecting this title from
  3451. * the "page" table
  3452. *
  3453. * @return array Array suitable for the $where parameter of DB::select()
  3454. */
  3455. public function pageCond() {
  3456. if ( $this->mArticleID > 0 ) {
  3457. // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
  3458. return [ 'page_id' => $this->mArticleID ];
  3459. } else {
  3460. return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
  3461. }
  3462. }
  3463. /**
  3464. * Get next/previous revision ID relative to another revision ID
  3465. * @param int $revId Revision ID. Get the revision that was before this one.
  3466. * @param int $flags Bitfield of class READ_* constants
  3467. * @param string $dir 'next' or 'prev'
  3468. * @return int|bool New revision ID, or false if none exists
  3469. */
  3470. private function getRelativeRevisionID( $revId, $flags, $dir ) {
  3471. $rl = MediaWikiServices::getInstance()->getRevisionLookup();
  3472. $rev = $rl->getRevisionById( $revId, $flags );
  3473. if ( !$rev ) {
  3474. return false;
  3475. }
  3476. $oldRev = ( $dir === 'next' )
  3477. ? $rl->getNextRevision( $rev, $flags )
  3478. : $rl->getPreviousRevision( $rev, $flags );
  3479. return $oldRev ? $oldRev->getId() : false;
  3480. }
  3481. /**
  3482. * Get the revision ID of the previous revision
  3483. *
  3484. * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
  3485. * @param int $revId Revision ID. Get the revision that was before this one.
  3486. * @param int $flags Bitfield of class READ_* constants
  3487. * @return int|bool Old revision ID, or false if none exists
  3488. */
  3489. public function getPreviousRevisionID( $revId, $flags = 0 ) {
  3490. return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
  3491. }
  3492. /**
  3493. * Get the revision ID of the next revision
  3494. *
  3495. * @deprecated since 1.34, use RevisionLookup::getNextRevision
  3496. * @param int $revId Revision ID. Get the revision that was after this one.
  3497. * @param int $flags Bitfield of class READ_* constants
  3498. * @return int|bool Next revision ID, or false if none exists
  3499. */
  3500. public function getNextRevisionID( $revId, $flags = 0 ) {
  3501. return $this->getRelativeRevisionID( $revId, $flags, 'next' );
  3502. }
  3503. /**
  3504. * Get the first revision of the page
  3505. *
  3506. * @param int $flags Bitfield of class READ_* constants
  3507. * @return Revision|null If page doesn't exist
  3508. */
  3509. public function getFirstRevision( $flags = 0 ) {
  3510. $pageId = $this->getArticleID( $flags );
  3511. if ( $pageId ) {
  3512. $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
  3513. list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
  3514. $revQuery = Revision::getQueryInfo();
  3515. $row = wfGetDB( $index )->selectRow(
  3516. $revQuery['tables'], $revQuery['fields'],
  3517. [ 'rev_page' => $pageId ],
  3518. __METHOD__,
  3519. array_merge(
  3520. [
  3521. 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
  3522. 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
  3523. ],
  3524. $options
  3525. ),
  3526. $revQuery['joins']
  3527. );
  3528. if ( $row ) {
  3529. return new Revision( $row, 0, $this );
  3530. }
  3531. }
  3532. return null;
  3533. }
  3534. /**
  3535. * Get the oldest revision timestamp of this page
  3536. *
  3537. * @param int $flags Bitfield of class READ_* constants
  3538. * @return string|null MW timestamp
  3539. */
  3540. public function getEarliestRevTime( $flags = 0 ) {
  3541. $rev = $this->getFirstRevision( $flags );
  3542. return $rev ? $rev->getTimestamp() : null;
  3543. }
  3544. /**
  3545. * Check if this is a new page
  3546. *
  3547. * @return bool
  3548. */
  3549. public function isNewPage() {
  3550. $dbr = wfGetDB( DB_REPLICA );
  3551. return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
  3552. }
  3553. /**
  3554. * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
  3555. *
  3556. * @return bool
  3557. */
  3558. public function isBigDeletion() {
  3559. global $wgDeleteRevisionsLimit;
  3560. if ( !$wgDeleteRevisionsLimit ) {
  3561. return false;
  3562. }
  3563. if ( $this->mIsBigDeletion === null ) {
  3564. $dbr = wfGetDB( DB_REPLICA );
  3565. $revCount = $dbr->selectRowCount(
  3566. 'revision',
  3567. '1',
  3568. [ 'rev_page' => $this->getArticleID() ],
  3569. __METHOD__,
  3570. [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
  3571. );
  3572. $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
  3573. }
  3574. return $this->mIsBigDeletion;
  3575. }
  3576. /**
  3577. * Get the approximate revision count of this page.
  3578. *
  3579. * @return int
  3580. */
  3581. public function estimateRevisionCount() {
  3582. if ( !$this->exists() ) {
  3583. return 0;
  3584. }
  3585. if ( $this->mEstimateRevisions === null ) {
  3586. $dbr = wfGetDB( DB_REPLICA );
  3587. $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
  3588. [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
  3589. }
  3590. return $this->mEstimateRevisions;
  3591. }
  3592. /**
  3593. * Get the number of revisions between the given revision.
  3594. * Used for diffs and other things that really need it.
  3595. *
  3596. * @param int|Revision $old Old revision or rev ID (first before range)
  3597. * @param int|Revision $new New revision or rev ID (first after range)
  3598. * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
  3599. * @return int Number of revisions between these revisions.
  3600. */
  3601. public function countRevisionsBetween( $old, $new, $max = null ) {
  3602. if ( !( $old instanceof Revision ) ) {
  3603. $old = Revision::newFromTitle( $this, (int)$old );
  3604. }
  3605. if ( !( $new instanceof Revision ) ) {
  3606. $new = Revision::newFromTitle( $this, (int)$new );
  3607. }
  3608. if ( !$old || !$new ) {
  3609. return 0; // nothing to compare
  3610. }
  3611. $dbr = wfGetDB( DB_REPLICA );
  3612. $conds = [
  3613. 'rev_page' => $this->getArticleID(),
  3614. 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
  3615. 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
  3616. ];
  3617. if ( $max !== null ) {
  3618. return $dbr->selectRowCount( 'revision', '1',
  3619. $conds,
  3620. __METHOD__,
  3621. [ 'LIMIT' => $max + 1 ] // extra to detect truncation
  3622. );
  3623. } else {
  3624. return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
  3625. }
  3626. }
  3627. /**
  3628. * Get the authors between the given revisions or revision IDs.
  3629. * Used for diffs and other things that really need it.
  3630. *
  3631. * @since 1.23
  3632. *
  3633. * @param int|Revision $old Old revision or rev ID (first before range by default)
  3634. * @param int|Revision $new New revision or rev ID (first after range by default)
  3635. * @param int $limit Maximum number of authors
  3636. * @param string|array $options (Optional): Single option, or an array of options:
  3637. * 'include_old' Include $old in the range; $new is excluded.
  3638. * 'include_new' Include $new in the range; $old is excluded.
  3639. * 'include_both' Include both $old and $new in the range.
  3640. * Unknown option values are ignored.
  3641. * @return array|null Names of revision authors in the range; null if not both revisions exist
  3642. */
  3643. public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
  3644. if ( !( $old instanceof Revision ) ) {
  3645. $old = Revision::newFromTitle( $this, (int)$old );
  3646. }
  3647. if ( !( $new instanceof Revision ) ) {
  3648. $new = Revision::newFromTitle( $this, (int)$new );
  3649. }
  3650. // XXX: what if Revision objects are passed in, but they don't refer to this title?
  3651. // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
  3652. // in the sanity check below?
  3653. if ( !$old || !$new ) {
  3654. return null; // nothing to compare
  3655. }
  3656. $authors = [];
  3657. $old_cmp = '>';
  3658. $new_cmp = '<';
  3659. $options = (array)$options;
  3660. if ( in_array( 'include_old', $options ) ) {
  3661. $old_cmp = '>=';
  3662. }
  3663. if ( in_array( 'include_new', $options ) ) {
  3664. $new_cmp = '<=';
  3665. }
  3666. if ( in_array( 'include_both', $options ) ) {
  3667. $old_cmp = '>=';
  3668. $new_cmp = '<=';
  3669. }
  3670. // No DB query needed if $old and $new are the same or successive revisions:
  3671. if ( $old->getId() === $new->getId() ) {
  3672. return ( $old_cmp === '>' && $new_cmp === '<' ) ?
  3673. [] :
  3674. [ $old->getUserText( RevisionRecord::RAW ) ];
  3675. } elseif ( $old->getId() === $new->getParentId() ) {
  3676. if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
  3677. $authors[] = $oldUserText = $old->getUserText( RevisionRecord::RAW );
  3678. $newUserText = $new->getUserText( RevisionRecord::RAW );
  3679. if ( $oldUserText != $newUserText ) {
  3680. $authors[] = $newUserText;
  3681. }
  3682. } elseif ( $old_cmp === '>=' ) {
  3683. $authors[] = $old->getUserText( RevisionRecord::RAW );
  3684. } elseif ( $new_cmp === '<=' ) {
  3685. $authors[] = $new->getUserText( RevisionRecord::RAW );
  3686. }
  3687. return $authors;
  3688. }
  3689. $dbr = wfGetDB( DB_REPLICA );
  3690. $revQuery = Revision::getQueryInfo();
  3691. $authors = $dbr->selectFieldValues(
  3692. $revQuery['tables'],
  3693. $revQuery['fields']['rev_user_text'],
  3694. [
  3695. 'rev_page' => $this->getArticleID(),
  3696. "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
  3697. "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
  3698. ], __METHOD__,
  3699. [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
  3700. $revQuery['joins']
  3701. );
  3702. return $authors;
  3703. }
  3704. /**
  3705. * Get the number of authors between the given revisions or revision IDs.
  3706. * Used for diffs and other things that really need it.
  3707. *
  3708. * @param int|Revision $old Old revision or rev ID (first before range by default)
  3709. * @param int|Revision $new New revision or rev ID (first after range by default)
  3710. * @param int $limit Maximum number of authors
  3711. * @param string|array $options (Optional): Single option, or an array of options:
  3712. * 'include_old' Include $old in the range; $new is excluded.
  3713. * 'include_new' Include $new in the range; $old is excluded.
  3714. * 'include_both' Include both $old and $new in the range.
  3715. * Unknown option values are ignored.
  3716. * @return int Number of revision authors in the range; zero if not both revisions exist
  3717. */
  3718. public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
  3719. $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
  3720. return $authors ? count( $authors ) : 0;
  3721. }
  3722. /**
  3723. * Compare with another title.
  3724. *
  3725. * @param LinkTarget $title
  3726. * @return bool
  3727. */
  3728. public function equals( LinkTarget $title ) {
  3729. // Note: === is necessary for proper matching of number-like titles.
  3730. return $this->mInterwiki === $title->getInterwiki()
  3731. && $this->mNamespace == $title->getNamespace()
  3732. && $this->mDbkeyform === $title->getDBkey();
  3733. }
  3734. /**
  3735. * Check if this title is a subpage of another title
  3736. *
  3737. * @param Title $title
  3738. * @return bool
  3739. */
  3740. public function isSubpageOf( Title $title ) {
  3741. return $this->mInterwiki === $title->mInterwiki
  3742. && $this->mNamespace == $title->mNamespace
  3743. && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
  3744. }
  3745. /**
  3746. * Check if page exists. For historical reasons, this function simply
  3747. * checks for the existence of the title in the page table, and will
  3748. * thus return false for interwiki links, special pages and the like.
  3749. * If you want to know if a title can be meaningfully viewed, you should
  3750. * probably call the isKnown() method instead.
  3751. *
  3752. * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
  3753. * @return bool
  3754. */
  3755. public function exists( $flags = 0 ) {
  3756. $exists = $this->getArticleID( $flags ) != 0;
  3757. Hooks::run( 'TitleExists', [ $this, &$exists ] );
  3758. return $exists;
  3759. }
  3760. /**
  3761. * Should links to this title be shown as potentially viewable (i.e. as
  3762. * "bluelinks"), even if there's no record by this title in the page
  3763. * table?
  3764. *
  3765. * This function is semi-deprecated for public use, as well as somewhat
  3766. * misleadingly named. You probably just want to call isKnown(), which
  3767. * calls this function internally.
  3768. *
  3769. * (ISSUE: Most of these checks are cheap, but the file existence check
  3770. * can potentially be quite expensive. Including it here fixes a lot of
  3771. * existing code, but we might want to add an optional parameter to skip
  3772. * it and any other expensive checks.)
  3773. *
  3774. * @return bool
  3775. */
  3776. public function isAlwaysKnown() {
  3777. $isKnown = null;
  3778. /**
  3779. * Allows overriding default behavior for determining if a page exists.
  3780. * If $isKnown is kept as null, regular checks happen. If it's
  3781. * a boolean, this value is returned by the isKnown method.
  3782. *
  3783. * @since 1.20
  3784. *
  3785. * @param Title $title
  3786. * @param bool|null $isKnown
  3787. */
  3788. Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
  3789. if ( !is_null( $isKnown ) ) {
  3790. return $isKnown;
  3791. }
  3792. if ( $this->isExternal() ) {
  3793. return true; // any interwiki link might be viewable, for all we know
  3794. }
  3795. $services = MediaWikiServices::getInstance();
  3796. switch ( $this->mNamespace ) {
  3797. case NS_MEDIA:
  3798. case NS_FILE:
  3799. // file exists, possibly in a foreign repo
  3800. return (bool)$services->getRepoGroup()->findFile( $this );
  3801. case NS_SPECIAL:
  3802. // valid special page
  3803. return $services->getSpecialPageFactory()->exists( $this->mDbkeyform );
  3804. case NS_MAIN:
  3805. // selflink, possibly with fragment
  3806. return $this->mDbkeyform == '';
  3807. case NS_MEDIAWIKI:
  3808. // known system message
  3809. return $this->hasSourceText() !== false;
  3810. default:
  3811. return false;
  3812. }
  3813. }
  3814. /**
  3815. * Does this title refer to a page that can (or might) be meaningfully
  3816. * viewed? In particular, this function may be used to determine if
  3817. * links to the title should be rendered as "bluelinks" (as opposed to
  3818. * "redlinks" to non-existent pages).
  3819. * Adding something else to this function will cause inconsistency
  3820. * since LinkHolderArray calls isAlwaysKnown() and does its own
  3821. * page existence check.
  3822. *
  3823. * @return bool
  3824. */
  3825. public function isKnown() {
  3826. return $this->isAlwaysKnown() || $this->exists();
  3827. }
  3828. /**
  3829. * Does this page have source text?
  3830. *
  3831. * @return bool
  3832. */
  3833. public function hasSourceText() {
  3834. if ( $this->exists() ) {
  3835. return true;
  3836. }
  3837. if ( $this->mNamespace == NS_MEDIAWIKI ) {
  3838. // If the page doesn't exist but is a known system message, default
  3839. // message content will be displayed, same for language subpages-
  3840. // Use always content language to avoid loading hundreds of languages
  3841. // to get the link color.
  3842. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  3843. list( $name, ) = MessageCache::singleton()->figureMessage(
  3844. $contLang->lcfirst( $this->getText() )
  3845. );
  3846. $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
  3847. return $message->exists();
  3848. }
  3849. return false;
  3850. }
  3851. /**
  3852. * Get the default (plain) message contents for an page that overrides an
  3853. * interface message key.
  3854. *
  3855. * Primary use cases:
  3856. *
  3857. * - Article:
  3858. * - Show default when viewing the page. The Article::getSubstituteContent
  3859. * method displays the default message content, instead of the
  3860. * 'noarticletext' placeholder message normally used.
  3861. *
  3862. * - EditPage:
  3863. * - Title of edit page. When creating an interface message override,
  3864. * the editor is told they are "Editing the page", instead of
  3865. * "Creating the page". (EditPage::setHeaders)
  3866. * - Edit notice. The 'translateinterface' edit notice is shown when creating
  3867. * or editing a an interface message override. (EditPage::showIntro)
  3868. * - Opening the editor. The contents of the localisation message are used
  3869. * as contents of the editor when creating a new page in the MediaWiki
  3870. * namespace. This simplifies the process for editors when "changing"
  3871. * an interface message by creating an override. (EditPage::getContentObject)
  3872. * - Showing a diff. The left-hand side of a diff when an editor is
  3873. * previewing their changes before saving the creation of a page in the
  3874. * MediaWiki namespace. (EditPage::showDiff)
  3875. * - Disallowing a save. When attempting to create a a MediaWiki-namespace
  3876. * page with the proposed content matching the interface message default,
  3877. * the save is rejected, the same way we disallow blank pages from being
  3878. * created. (EditPage::internalAttemptSave)
  3879. *
  3880. * - ApiEditPage:
  3881. * - Default content, when using the 'prepend' or 'append' feature.
  3882. *
  3883. * - SkinTemplate:
  3884. * - Label the create action as "Edit", if the page can be an override.
  3885. *
  3886. * @return string|bool
  3887. */
  3888. public function getDefaultMessageText() {
  3889. if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
  3890. return false;
  3891. }
  3892. list( $name, $lang ) = MessageCache::singleton()->figureMessage(
  3893. MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
  3894. );
  3895. $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
  3896. if ( $message->exists() ) {
  3897. return $message->plain();
  3898. } else {
  3899. return false;
  3900. }
  3901. }
  3902. /**
  3903. * Updates page_touched for this page; called from LinksUpdate.php
  3904. *
  3905. * @param string|null $purgeTime [optional] TS_MW timestamp
  3906. * @return bool True if the update succeeded
  3907. */
  3908. public function invalidateCache( $purgeTime = null ) {
  3909. if ( wfReadOnly() ) {
  3910. return false;
  3911. } elseif ( $this->mArticleID === 0 ) {
  3912. return true; // avoid gap locking if we know it's not there
  3913. }
  3914. $dbw = wfGetDB( DB_MASTER );
  3915. $dbw->onTransactionPreCommitOrIdle(
  3916. function () use ( $dbw ) {
  3917. ResourceLoaderWikiModule::invalidateModuleCache(
  3918. $this, null, null, $dbw->getDomainID() );
  3919. },
  3920. __METHOD__
  3921. );
  3922. $conds = $this->pageCond();
  3923. DeferredUpdates::addUpdate(
  3924. new AutoCommitUpdate(
  3925. $dbw,
  3926. __METHOD__,
  3927. function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
  3928. $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
  3929. $dbw->update(
  3930. 'page',
  3931. [ 'page_touched' => $dbTimestamp ],
  3932. $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
  3933. $fname
  3934. );
  3935. MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
  3936. }
  3937. ),
  3938. DeferredUpdates::PRESEND
  3939. );
  3940. return true;
  3941. }
  3942. /**
  3943. * Update page_touched timestamps and send CDN purge messages for
  3944. * pages linking to this title. May be sent to the job queue depending
  3945. * on the number of links. Typically called on create and delete.
  3946. */
  3947. public function touchLinks() {
  3948. $jobs = [];
  3949. $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
  3950. $this,
  3951. 'pagelinks',
  3952. [ 'causeAction' => 'page-touch' ]
  3953. );
  3954. if ( $this->mNamespace == NS_CATEGORY ) {
  3955. $jobs[] = HTMLCacheUpdateJob::newForBacklinks(
  3956. $this,
  3957. 'categorylinks',
  3958. [ 'causeAction' => 'category-touch' ]
  3959. );
  3960. }
  3961. JobQueueGroup::singleton()->lazyPush( $jobs );
  3962. }
  3963. /**
  3964. * Get the last touched timestamp
  3965. *
  3966. * @param IDatabase|null $db
  3967. * @return string|false Last-touched timestamp
  3968. */
  3969. public function getTouched( $db = null ) {
  3970. if ( $db === null ) {
  3971. $db = wfGetDB( DB_REPLICA );
  3972. }
  3973. $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
  3974. return $touched;
  3975. }
  3976. /**
  3977. * Get the timestamp when this page was updated since the user last saw it.
  3978. *
  3979. * @param User|null $user
  3980. * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
  3981. */
  3982. public function getNotificationTimestamp( $user = null ) {
  3983. global $wgUser;
  3984. // Assume current user if none given
  3985. if ( !$user ) {
  3986. $user = $wgUser;
  3987. }
  3988. // Check cache first
  3989. $uid = $user->getId();
  3990. if ( !$uid ) {
  3991. return false;
  3992. }
  3993. // avoid isset here, as it'll return false for null entries
  3994. if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
  3995. return $this->mNotificationTimestamp[$uid];
  3996. }
  3997. // Don't cache too much!
  3998. if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
  3999. $this->mNotificationTimestamp = [];
  4000. }
  4001. $store = MediaWikiServices::getInstance()->getWatchedItemStore();
  4002. $watchedItem = $store->getWatchedItem( $user, $this );
  4003. if ( $watchedItem ) {
  4004. $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
  4005. } else {
  4006. $this->mNotificationTimestamp[$uid] = false;
  4007. }
  4008. return $this->mNotificationTimestamp[$uid];
  4009. }
  4010. /**
  4011. * Generate strings used for xml 'id' names in monobook tabs
  4012. *
  4013. * @param string $prepend Defaults to 'nstab-'
  4014. * @return string XML 'id' name
  4015. */
  4016. public function getNamespaceKey( $prepend = 'nstab-' ) {
  4017. // Gets the subject namespace of this title
  4018. $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
  4019. $subjectNS = $nsInfo->getSubject( $this->mNamespace );
  4020. // Prefer canonical namespace name for HTML IDs
  4021. $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
  4022. if ( $namespaceKey === false ) {
  4023. // Fallback to localised text
  4024. $namespaceKey = $this->getSubjectNsText();
  4025. }
  4026. // Makes namespace key lowercase
  4027. $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
  4028. // Uses main
  4029. if ( $namespaceKey == '' ) {
  4030. $namespaceKey = 'main';
  4031. }
  4032. // Changes file to image for backwards compatibility
  4033. if ( $namespaceKey == 'file' ) {
  4034. $namespaceKey = 'image';
  4035. }
  4036. return $prepend . $namespaceKey;
  4037. }
  4038. /**
  4039. * Get all extant redirects to this Title
  4040. *
  4041. * @param int|null $ns Single namespace to consider; null to consider all namespaces
  4042. * @return Title[] Array of Title redirects to this title
  4043. */
  4044. public function getRedirectsHere( $ns = null ) {
  4045. $redirs = [];
  4046. $dbr = wfGetDB( DB_REPLICA );
  4047. $where = [
  4048. 'rd_namespace' => $this->mNamespace,
  4049. 'rd_title' => $this->mDbkeyform,
  4050. 'rd_from = page_id'
  4051. ];
  4052. if ( $this->isExternal() ) {
  4053. $where['rd_interwiki'] = $this->mInterwiki;
  4054. } else {
  4055. $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
  4056. }
  4057. if ( !is_null( $ns ) ) {
  4058. $where['page_namespace'] = $ns;
  4059. }
  4060. $res = $dbr->select(
  4061. [ 'redirect', 'page' ],
  4062. [ 'page_namespace', 'page_title' ],
  4063. $where,
  4064. __METHOD__
  4065. );
  4066. foreach ( $res as $row ) {
  4067. $redirs[] = self::newFromRow( $row );
  4068. }
  4069. return $redirs;
  4070. }
  4071. /**
  4072. * Check if this Title is a valid redirect target
  4073. *
  4074. * @return bool
  4075. */
  4076. public function isValidRedirectTarget() {
  4077. global $wgInvalidRedirectTargets;
  4078. if ( $this->isSpecialPage() ) {
  4079. // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
  4080. if ( $this->isSpecial( 'Userlogout' ) ) {
  4081. return false;
  4082. }
  4083. foreach ( $wgInvalidRedirectTargets as $target ) {
  4084. if ( $this->isSpecial( $target ) ) {
  4085. return false;
  4086. }
  4087. }
  4088. }
  4089. return true;
  4090. }
  4091. /**
  4092. * Get a backlink cache object
  4093. *
  4094. * @return BacklinkCache
  4095. */
  4096. public function getBacklinkCache() {
  4097. return BacklinkCache::get( $this );
  4098. }
  4099. /**
  4100. * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
  4101. *
  4102. * @return bool
  4103. */
  4104. public function canUseNoindex() {
  4105. global $wgExemptFromUserRobotsControl;
  4106. $bannedNamespaces = $wgExemptFromUserRobotsControl ??
  4107. MediaWikiServices::getInstance()->getNamespaceInfo()->getContentNamespaces();
  4108. return !in_array( $this->mNamespace, $bannedNamespaces );
  4109. }
  4110. /**
  4111. * Returns the raw sort key to be used for categories, with the specified
  4112. * prefix. This will be fed to Collation::getSortKey() to get a
  4113. * binary sortkey that can be used for actual sorting.
  4114. *
  4115. * @param string $prefix The prefix to be used, specified using
  4116. * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
  4117. * prefix.
  4118. * @return string
  4119. */
  4120. public function getCategorySortkey( $prefix = '' ) {
  4121. $unprefixed = $this->getText();
  4122. // Anything that uses this hook should only depend
  4123. // on the Title object passed in, and should probably
  4124. // tell the users to run updateCollations.php --force
  4125. // in order to re-sort existing category relations.
  4126. Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
  4127. if ( $prefix !== '' ) {
  4128. # Separate with a line feed, so the unprefixed part is only used as
  4129. # a tiebreaker when two pages have the exact same prefix.
  4130. # In UCA, tab is the only character that can sort above LF
  4131. # so we strip both of them from the original prefix.
  4132. $prefix = strtr( $prefix, "\n\t", ' ' );
  4133. return "$prefix\n$unprefixed";
  4134. }
  4135. return $unprefixed;
  4136. }
  4137. /**
  4138. * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
  4139. * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
  4140. * the db, it will return NULL.
  4141. *
  4142. * @return string|null|bool
  4143. */
  4144. private function getDbPageLanguageCode() {
  4145. global $wgPageLanguageUseDB;
  4146. // check, if the page language could be saved in the database, and if so and
  4147. // the value is not requested already, lookup the page language using LinkCache
  4148. if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
  4149. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  4150. $linkCache->addLinkObj( $this );
  4151. $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
  4152. }
  4153. return $this->mDbPageLanguage;
  4154. }
  4155. /**
  4156. * Get the language in which the content of this page is written in
  4157. * wikitext. Defaults to content language, but in certain cases it can be
  4158. * e.g. $wgLang (such as special pages, which are in the user language).
  4159. *
  4160. * @since 1.18
  4161. * @return Language
  4162. */
  4163. public function getPageLanguage() {
  4164. global $wgLang, $wgLanguageCode;
  4165. if ( $this->isSpecialPage() ) {
  4166. // special pages are in the user language
  4167. return $wgLang;
  4168. }
  4169. // Checking if DB language is set
  4170. $dbPageLanguage = $this->getDbPageLanguageCode();
  4171. if ( $dbPageLanguage ) {
  4172. return wfGetLangObj( $dbPageLanguage );
  4173. }
  4174. if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
  4175. // Note that this may depend on user settings, so the cache should
  4176. // be only per-request.
  4177. // NOTE: ContentHandler::getPageLanguage() may need to load the
  4178. // content to determine the page language!
  4179. // Checking $wgLanguageCode hasn't changed for the benefit of unit
  4180. // tests.
  4181. $contentHandler = ContentHandler::getForTitle( $this );
  4182. $langObj = $contentHandler->getPageLanguage( $this );
  4183. $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
  4184. } else {
  4185. $langObj = Language::factory( $this->mPageLanguage[0] );
  4186. }
  4187. return $langObj;
  4188. }
  4189. /**
  4190. * Get the language in which the content of this page is written when
  4191. * viewed by user. Defaults to content language, but in certain cases it can be
  4192. * e.g. $wgLang (such as special pages, which are in the user language).
  4193. *
  4194. * @since 1.20
  4195. * @return Language
  4196. */
  4197. public function getPageViewLanguage() {
  4198. global $wgLang;
  4199. if ( $this->isSpecialPage() ) {
  4200. // If the user chooses a variant, the content is actually
  4201. // in a language whose code is the variant code.
  4202. $variant = $wgLang->getPreferredVariant();
  4203. if ( $wgLang->getCode() !== $variant ) {
  4204. return Language::factory( $variant );
  4205. }
  4206. return $wgLang;
  4207. }
  4208. // Checking if DB language is set
  4209. $dbPageLanguage = $this->getDbPageLanguageCode();
  4210. if ( $dbPageLanguage ) {
  4211. $pageLang = wfGetLangObj( $dbPageLanguage );
  4212. $variant = $pageLang->getPreferredVariant();
  4213. if ( $pageLang->getCode() !== $variant ) {
  4214. $pageLang = Language::factory( $variant );
  4215. }
  4216. return $pageLang;
  4217. }
  4218. // @note Can't be cached persistently, depends on user settings.
  4219. // @note ContentHandler::getPageViewLanguage() may need to load the
  4220. // content to determine the page language!
  4221. $contentHandler = ContentHandler::getForTitle( $this );
  4222. $pageLang = $contentHandler->getPageViewLanguage( $this );
  4223. return $pageLang;
  4224. }
  4225. /**
  4226. * Get a list of rendered edit notices for this page.
  4227. *
  4228. * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
  4229. * they will already be wrapped in paragraphs.
  4230. *
  4231. * @since 1.21
  4232. * @param int $oldid Revision ID that's being edited
  4233. * @return array
  4234. */
  4235. public function getEditNotices( $oldid = 0 ) {
  4236. $notices = [];
  4237. // Optional notice for the entire namespace
  4238. $editnotice_ns = 'editnotice-' . $this->mNamespace;
  4239. $msg = wfMessage( $editnotice_ns );
  4240. if ( $msg->exists() ) {
  4241. $html = $msg->parseAsBlock();
  4242. // Edit notices may have complex logic, but output nothing (T91715)
  4243. if ( trim( $html ) !== '' ) {
  4244. $notices[$editnotice_ns] = Html::rawElement(
  4245. 'div',
  4246. [ 'class' => [
  4247. 'mw-editnotice',
  4248. 'mw-editnotice-namespace',
  4249. Sanitizer::escapeClass( "mw-$editnotice_ns" )
  4250. ] ],
  4251. $html
  4252. );
  4253. }
  4254. }
  4255. if (
  4256. MediaWikiServices::getInstance()->getNamespaceInfo()->
  4257. hasSubpages( $this->mNamespace )
  4258. ) {
  4259. // Optional notice for page itself and any parent page
  4260. $editnotice_base = $editnotice_ns;
  4261. foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
  4262. $editnotice_base .= '-' . $part;
  4263. $msg = wfMessage( $editnotice_base );
  4264. if ( $msg->exists() ) {
  4265. $html = $msg->parseAsBlock();
  4266. if ( trim( $html ) !== '' ) {
  4267. $notices[$editnotice_base] = Html::rawElement(
  4268. 'div',
  4269. [ 'class' => [
  4270. 'mw-editnotice',
  4271. 'mw-editnotice-base',
  4272. Sanitizer::escapeClass( "mw-$editnotice_base" )
  4273. ] ],
  4274. $html
  4275. );
  4276. }
  4277. }
  4278. }
  4279. } else {
  4280. // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
  4281. $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
  4282. $msg = wfMessage( $editnoticeText );
  4283. if ( $msg->exists() ) {
  4284. $html = $msg->parseAsBlock();
  4285. if ( trim( $html ) !== '' ) {
  4286. $notices[$editnoticeText] = Html::rawElement(
  4287. 'div',
  4288. [ 'class' => [
  4289. 'mw-editnotice',
  4290. 'mw-editnotice-page',
  4291. Sanitizer::escapeClass( "mw-$editnoticeText" )
  4292. ] ],
  4293. $html
  4294. );
  4295. }
  4296. }
  4297. }
  4298. Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
  4299. return $notices;
  4300. }
  4301. /**
  4302. * @param int $flags Bitfield of class READ_* constants
  4303. * @return string|bool
  4304. */
  4305. private function loadFieldFromDB( $field, $flags ) {
  4306. if ( !in_array( $field, self::getSelectFields(), true ) ) {
  4307. return false; // field does not exist
  4308. }
  4309. $flags |= ( $flags & self::GAID_FOR_UPDATE ) ? self::READ_LATEST : 0; // b/c
  4310. list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
  4311. return wfGetDB( $index )->selectField(
  4312. 'page',
  4313. $field,
  4314. $this->pageCond(),
  4315. __METHOD__,
  4316. $options
  4317. );
  4318. }
  4319. /**
  4320. * @return array
  4321. */
  4322. public function __sleep() {
  4323. return [
  4324. 'mNamespace',
  4325. 'mDbkeyform',
  4326. 'mFragment',
  4327. 'mInterwiki',
  4328. 'mLocalInterwiki',
  4329. 'mUserCaseDBKey',
  4330. 'mDefaultNamespace',
  4331. ];
  4332. }
  4333. public function __wakeup() {
  4334. $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
  4335. $this->mUrlform = wfUrlencode( $this->mDbkeyform );
  4336. $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
  4337. }
  4338. }