Article.php 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675
  1. <?php
  2. /**
  3. * File for articles
  4. * @file
  5. */
  6. /**
  7. * Class representing a MediaWiki article and history.
  8. *
  9. * See design.txt for an overview.
  10. * Note: edit user interface and cache support functions have been
  11. * moved to separate EditPage and HTMLFileCache classes.
  12. *
  13. */
  14. class Article {
  15. /**@{{
  16. * @private
  17. */
  18. var $mComment = ''; //!<
  19. var $mContent; //!<
  20. var $mContentLoaded = false; //!<
  21. var $mCounter = -1; //!< Not loaded
  22. var $mCurID = -1; //!< Not loaded
  23. var $mDataLoaded = false; //!<
  24. var $mForUpdate = false; //!<
  25. var $mGoodAdjustment = 0; //!<
  26. var $mIsRedirect = false; //!<
  27. var $mLatest = false; //!<
  28. var $mMinorEdit; //!<
  29. var $mOldId; //!<
  30. var $mPreparedEdit = false; //!< Title object if set
  31. var $mRedirectedFrom = null; //!< Title object if set
  32. var $mRedirectTarget = null; //!< Title object if set
  33. var $mRedirectUrl = false; //!<
  34. var $mRevIdFetched = 0; //!<
  35. var $mRevision; //!<
  36. var $mTimestamp = ''; //!<
  37. var $mTitle; //!<
  38. var $mTotalAdjustment = 0; //!<
  39. var $mTouched = '19700101000000'; //!<
  40. var $mUser = -1; //!< Not loaded
  41. var $mUserText = ''; //!<
  42. /**@}}*/
  43. /**
  44. * Constructor and clear the article
  45. * @param $title Reference to a Title object.
  46. * @param $oldId Integer revision ID, null to fetch from request, zero for current
  47. */
  48. public function __construct( Title $title, $oldId = null ) {
  49. $this->mTitle =& $title;
  50. $this->mOldId = $oldId;
  51. }
  52. /**
  53. * Constructor from an article article
  54. * @param $id The article ID to load
  55. */
  56. public static function newFromID( $id ) {
  57. $t = Title::newFromID( $id );
  58. return $t == null ? null : new Article( $t );
  59. }
  60. /**
  61. * Tell the page view functions that this view was redirected
  62. * from another page on the wiki.
  63. * @param $from Title object.
  64. */
  65. public function setRedirectedFrom( $from ) {
  66. $this->mRedirectedFrom = $from;
  67. }
  68. /**
  69. * If this page is a redirect, get its target
  70. *
  71. * The target will be fetched from the redirect table if possible.
  72. * If this page doesn't have an entry there, call insertRedirect()
  73. * @return mixed Title object, or null if this page is not a redirect
  74. */
  75. public function getRedirectTarget() {
  76. if( !$this->mTitle || !$this->mTitle->isRedirect() )
  77. return null;
  78. if( !is_null($this->mRedirectTarget) )
  79. return $this->mRedirectTarget;
  80. # Query the redirect table
  81. $dbr = wfGetDB( DB_SLAVE );
  82. $row = $dbr->selectRow( 'redirect',
  83. array('rd_namespace', 'rd_title'),
  84. array('rd_from' => $this->getID() ),
  85. __METHOD__
  86. );
  87. if( $row ) {
  88. return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
  89. }
  90. # This page doesn't have an entry in the redirect table
  91. return $this->mRedirectTarget = $this->insertRedirect();
  92. }
  93. /**
  94. * Insert an entry for this page into the redirect table.
  95. *
  96. * Don't call this function directly unless you know what you're doing.
  97. * @return Title object
  98. */
  99. public function insertRedirect() {
  100. $retval = Title::newFromRedirect( $this->getContent() );
  101. if( !$retval ) {
  102. return null;
  103. }
  104. $dbw = wfGetDB( DB_MASTER );
  105. $dbw->replace( 'redirect', array('rd_from'),
  106. array(
  107. 'rd_from' => $this->getID(),
  108. 'rd_namespace' => $retval->getNamespace(),
  109. 'rd_title' => $retval->getDBKey()
  110. ),
  111. __METHOD__
  112. );
  113. return $retval;
  114. }
  115. /**
  116. * Get the Title object this page redirects to
  117. *
  118. * @return mixed false, Title of in-wiki target, or string with URL
  119. */
  120. public function followRedirect() {
  121. $text = $this->getContent();
  122. return $this->followRedirectText( $text );
  123. }
  124. /**
  125. * Get the Title object this text redirects to
  126. *
  127. * @return mixed false, Title of in-wiki target, or string with URL
  128. */
  129. public function followRedirectText( $text ) {
  130. $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
  131. # process if title object is valid and not special:userlogout
  132. if( $rt ) {
  133. if( $rt->getInterwiki() != '' ) {
  134. if( $rt->isLocal() ) {
  135. // Offsite wikis need an HTTP redirect.
  136. //
  137. // This can be hard to reverse and may produce loops,
  138. // so they may be disabled in the site configuration.
  139. $source = $this->mTitle->getFullURL( 'redirect=no' );
  140. return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
  141. }
  142. } else {
  143. if( $rt->getNamespace() == NS_SPECIAL ) {
  144. // Gotta handle redirects to special pages differently:
  145. // Fill the HTTP response "Location" header and ignore
  146. // the rest of the page we're on.
  147. //
  148. // This can be hard to reverse, so they may be disabled.
  149. if( $rt->isSpecial( 'Userlogout' ) ) {
  150. // rolleyes
  151. } else {
  152. return $rt->getFullURL();
  153. }
  154. }
  155. return $rt;
  156. }
  157. }
  158. // No or invalid redirect
  159. return false;
  160. }
  161. /**
  162. * get the title object of the article
  163. */
  164. public function getTitle() {
  165. return $this->mTitle;
  166. }
  167. /**
  168. * Clear the object
  169. * @private
  170. */
  171. public function clear() {
  172. $this->mDataLoaded = false;
  173. $this->mContentLoaded = false;
  174. $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
  175. $this->mRedirectedFrom = null; # Title object if set
  176. $this->mRedirectTarget = null; # Title object if set
  177. $this->mUserText =
  178. $this->mTimestamp = $this->mComment = '';
  179. $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
  180. $this->mTouched = '19700101000000';
  181. $this->mForUpdate = false;
  182. $this->mIsRedirect = false;
  183. $this->mRevIdFetched = 0;
  184. $this->mRedirectUrl = false;
  185. $this->mLatest = false;
  186. $this->mPreparedEdit = false;
  187. }
  188. /**
  189. * Note that getContent/loadContent do not follow redirects anymore.
  190. * If you need to fetch redirectable content easily, try
  191. * the shortcut in Article::followContent()
  192. *
  193. * @return Return the text of this revision
  194. */
  195. public function getContent() {
  196. global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
  197. wfProfileIn( __METHOD__ );
  198. if( $this->getID() === 0 ) {
  199. # If this is a MediaWiki:x message, then load the messages
  200. # and return the message value for x.
  201. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
  202. # If this is a system message, get the default text.
  203. list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
  204. $wgMessageCache->loadAllMessages( $lang );
  205. $text = wfMsgGetKey( $message, false, $lang, false );
  206. if( wfEmptyMsg( $message, $text ) )
  207. $text = '';
  208. } else {
  209. $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
  210. }
  211. wfProfileOut( __METHOD__ );
  212. return $text;
  213. } else {
  214. $this->loadContent();
  215. wfProfileOut( __METHOD__ );
  216. return $this->mContent;
  217. }
  218. }
  219. /**
  220. * Get the text of the current revision. No side-effects...
  221. *
  222. * @return Return the text of the current revision
  223. */
  224. public function getRawText() {
  225. // Check process cache for current revision
  226. if( $this->mContentLoaded && $this->mOldId == 0 ) {
  227. return $this->mContent;
  228. }
  229. $rev = Revision::newFromTitle( $this->mTitle );
  230. $text = $rev ? $rev->getRawText() : false;
  231. return $text;
  232. }
  233. /**
  234. * This function returns the text of a section, specified by a number ($section).
  235. * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
  236. * the first section before any such heading (section 0).
  237. *
  238. * If a section contains subsections, these are also returned.
  239. *
  240. * @param $text String: text to look in
  241. * @param $section Integer: section number
  242. * @return string text of the requested section
  243. * @deprecated
  244. */
  245. public function getSection( $text, $section ) {
  246. global $wgParser;
  247. return $wgParser->getSection( $text, $section );
  248. }
  249. /**
  250. * Get the text that needs to be saved in order to undo all revisions
  251. * between $undo and $undoafter. Revisions must belong to the same page,
  252. * must exist and must not be deleted
  253. * @param $undo Revision
  254. * @param $undoafter Revision Must be an earlier revision than $undo
  255. * @return mixed string on success, false on failure
  256. */
  257. public function getUndoText( Revision $undo, Revision $undoafter = null ) {
  258. $undo_text = $undo->getText();
  259. $undoafter_text = $undoafter->getText();
  260. $cur_text = $this->getContent();
  261. if ( $cur_text == $undo_text ) {
  262. # No use doing a merge if it's just a straight revert.
  263. return $undoafter_text;
  264. }
  265. $undone_text = '';
  266. if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
  267. return false;
  268. return $undone_text;
  269. }
  270. /**
  271. * @return int The oldid of the article that is to be shown, 0 for the
  272. * current revision
  273. */
  274. public function getOldID() {
  275. if( is_null( $this->mOldId ) ) {
  276. $this->mOldId = $this->getOldIDFromRequest();
  277. }
  278. return $this->mOldId;
  279. }
  280. /**
  281. * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
  282. *
  283. * @return int The old id for the request
  284. */
  285. public function getOldIDFromRequest() {
  286. global $wgRequest;
  287. $this->mRedirectUrl = false;
  288. $oldid = $wgRequest->getVal( 'oldid' );
  289. if( isset( $oldid ) ) {
  290. $oldid = intval( $oldid );
  291. if( $wgRequest->getVal( 'direction' ) == 'next' ) {
  292. $nextid = $this->mTitle->getNextRevisionID( $oldid );
  293. if( $nextid ) {
  294. $oldid = $nextid;
  295. } else {
  296. $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
  297. }
  298. } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
  299. $previd = $this->mTitle->getPreviousRevisionID( $oldid );
  300. if( $previd ) {
  301. $oldid = $previd;
  302. }
  303. }
  304. }
  305. if( !$oldid ) {
  306. $oldid = 0;
  307. }
  308. return $oldid;
  309. }
  310. /**
  311. * Load the revision (including text) into this object
  312. */
  313. function loadContent() {
  314. if( $this->mContentLoaded ) return;
  315. wfProfileIn( __METHOD__ );
  316. # Query variables :P
  317. $oldid = $this->getOldID();
  318. # Pre-fill content with error message so that if something
  319. # fails we'll have something telling us what we intended.
  320. $this->mOldId = $oldid;
  321. $this->fetchContent( $oldid );
  322. wfProfileOut( __METHOD__ );
  323. }
  324. /**
  325. * Fetch a page record with the given conditions
  326. * @param $dbr Database object
  327. * @param $conditions Array
  328. */
  329. protected function pageData( $dbr, $conditions ) {
  330. $fields = array(
  331. 'page_id',
  332. 'page_namespace',
  333. 'page_title',
  334. 'page_restrictions',
  335. 'page_counter',
  336. 'page_is_redirect',
  337. 'page_is_new',
  338. 'page_random',
  339. 'page_touched',
  340. 'page_latest',
  341. 'page_len',
  342. );
  343. wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
  344. $row = $dbr->selectRow(
  345. 'page',
  346. $fields,
  347. $conditions,
  348. __METHOD__
  349. );
  350. wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
  351. return $row ;
  352. }
  353. /**
  354. * @param $dbr Database object
  355. * @param $title Title object
  356. */
  357. public function pageDataFromTitle( $dbr, $title ) {
  358. return $this->pageData( $dbr, array(
  359. 'page_namespace' => $title->getNamespace(),
  360. 'page_title' => $title->getDBkey() ) );
  361. }
  362. /**
  363. * @param $dbr Database
  364. * @param $id Integer
  365. */
  366. protected function pageDataFromId( $dbr, $id ) {
  367. return $this->pageData( $dbr, array( 'page_id' => $id ) );
  368. }
  369. /**
  370. * Set the general counter, title etc data loaded from
  371. * some source.
  372. *
  373. * @param $data Database row object or "fromdb"
  374. */
  375. public function loadPageData( $data = 'fromdb' ) {
  376. if( $data === 'fromdb' ) {
  377. $dbr = wfGetDB( DB_MASTER );
  378. $data = $this->pageDataFromId( $dbr, $this->getId() );
  379. }
  380. $lc = LinkCache::singleton();
  381. if( $data ) {
  382. $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
  383. $this->mTitle->mArticleID = $data->page_id;
  384. # Old-fashioned restrictions
  385. $this->mTitle->loadRestrictions( $data->page_restrictions );
  386. $this->mCounter = $data->page_counter;
  387. $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
  388. $this->mIsRedirect = $data->page_is_redirect;
  389. $this->mLatest = $data->page_latest;
  390. } else {
  391. if( is_object( $this->mTitle ) ) {
  392. $lc->addBadLinkObj( $this->mTitle );
  393. }
  394. $this->mTitle->mArticleID = 0;
  395. }
  396. $this->mDataLoaded = true;
  397. }
  398. /**
  399. * Get text of an article from database
  400. * Does *NOT* follow redirects.
  401. * @param $oldid Int: 0 for whatever the latest revision is
  402. * @return string
  403. */
  404. function fetchContent( $oldid = 0 ) {
  405. if( $this->mContentLoaded ) {
  406. return $this->mContent;
  407. }
  408. $dbr = wfGetDB( DB_MASTER );
  409. # Pre-fill content with error message so that if something
  410. # fails we'll have something telling us what we intended.
  411. $t = $this->mTitle->getPrefixedText();
  412. $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
  413. $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
  414. if( $oldid ) {
  415. $revision = Revision::newFromId( $oldid );
  416. if( is_null( $revision ) ) {
  417. wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
  418. return false;
  419. }
  420. $data = $this->pageDataFromId( $dbr, $revision->getPage() );
  421. if( !$data ) {
  422. wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
  423. return false;
  424. }
  425. $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
  426. $this->loadPageData( $data );
  427. } else {
  428. if( !$this->mDataLoaded ) {
  429. $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
  430. if( !$data ) {
  431. wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
  432. return false;
  433. }
  434. $this->loadPageData( $data );
  435. }
  436. $revision = Revision::newFromId( $this->mLatest );
  437. if( is_null( $revision ) ) {
  438. wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
  439. return false;
  440. }
  441. }
  442. // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
  443. // We should instead work with the Revision object when we need it...
  444. $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
  445. $this->mUser = $revision->getUser();
  446. $this->mUserText = $revision->getUserText();
  447. $this->mComment = $revision->getComment();
  448. $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
  449. $this->mRevIdFetched = $revision->getId();
  450. $this->mContentLoaded = true;
  451. $this->mRevision =& $revision;
  452. wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
  453. return $this->mContent;
  454. }
  455. /**
  456. * Read/write accessor to select FOR UPDATE
  457. *
  458. * @param $x Mixed: FIXME
  459. */
  460. public function forUpdate( $x = NULL ) {
  461. return wfSetVar( $this->mForUpdate, $x );
  462. }
  463. /**
  464. * Get the database which should be used for reads
  465. *
  466. * @return Database
  467. * @deprecated - just call wfGetDB( DB_MASTER ) instead
  468. */
  469. function getDB() {
  470. wfDeprecated( __METHOD__ );
  471. return wfGetDB( DB_MASTER );
  472. }
  473. /**
  474. * Get options for all SELECT statements
  475. *
  476. * @param $options Array: an optional options array which'll be appended to
  477. * the default
  478. * @return Array: options
  479. */
  480. protected function getSelectOptions( $options = '' ) {
  481. if( $this->mForUpdate ) {
  482. if( is_array( $options ) ) {
  483. $options[] = 'FOR UPDATE';
  484. } else {
  485. $options = 'FOR UPDATE';
  486. }
  487. }
  488. return $options;
  489. }
  490. /**
  491. * @return int Page ID
  492. */
  493. public function getID() {
  494. if( $this->mTitle ) {
  495. return $this->mTitle->getArticleID();
  496. } else {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * @return bool Whether or not the page exists in the database
  502. */
  503. public function exists() {
  504. return $this->getId() > 0;
  505. }
  506. /**
  507. * Check if this page is something we're going to be showing
  508. * some sort of sensible content for. If we return false, page
  509. * views (plain action=view) will return an HTTP 404 response,
  510. * so spiders and robots can know they're following a bad link.
  511. *
  512. * @return bool
  513. */
  514. public function hasViewableContent() {
  515. return $this->exists() || $this->mTitle->isAlwaysKnown();
  516. }
  517. /**
  518. * @return int The view count for the page
  519. */
  520. public function getCount() {
  521. if( -1 == $this->mCounter ) {
  522. $id = $this->getID();
  523. if( $id == 0 ) {
  524. $this->mCounter = 0;
  525. } else {
  526. $dbr = wfGetDB( DB_SLAVE );
  527. $this->mCounter = $dbr->selectField( 'page',
  528. 'page_counter',
  529. array( 'page_id' => $id ),
  530. __METHOD__,
  531. $this->getSelectOptions()
  532. );
  533. }
  534. }
  535. return $this->mCounter;
  536. }
  537. /**
  538. * Determine whether a page would be suitable for being counted as an
  539. * article in the site_stats table based on the title & its content
  540. *
  541. * @param $text String: text to analyze
  542. * @return bool
  543. */
  544. public function isCountable( $text ) {
  545. global $wgUseCommaCount;
  546. $token = $wgUseCommaCount ? ',' : '[[';
  547. return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
  548. }
  549. /**
  550. * Tests if the article text represents a redirect
  551. *
  552. * @param $text String: FIXME
  553. * @return bool
  554. */
  555. public function isRedirect( $text = false ) {
  556. if( $text === false ) {
  557. if( $this->mDataLoaded ) {
  558. return $this->mIsRedirect;
  559. }
  560. // Apparently loadPageData was never called
  561. $this->loadContent();
  562. $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
  563. } else {
  564. $titleObj = Title::newFromRedirect( $text );
  565. }
  566. return $titleObj !== NULL;
  567. }
  568. /**
  569. * Returns true if the currently-referenced revision is the current edit
  570. * to this page (and it exists).
  571. * @return bool
  572. */
  573. public function isCurrent() {
  574. # If no oldid, this is the current version.
  575. if( $this->getOldID() == 0 ) {
  576. return true;
  577. }
  578. return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
  579. }
  580. /**
  581. * Loads everything except the text
  582. * This isn't necessary for all uses, so it's only done if needed.
  583. */
  584. protected function loadLastEdit() {
  585. if( -1 != $this->mUser )
  586. return;
  587. # New or non-existent articles have no user information
  588. $id = $this->getID();
  589. if( 0 == $id ) return;
  590. $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
  591. if( !is_null( $this->mLastRevision ) ) {
  592. $this->mUser = $this->mLastRevision->getUser();
  593. $this->mUserText = $this->mLastRevision->getUserText();
  594. $this->mTimestamp = $this->mLastRevision->getTimestamp();
  595. $this->mComment = $this->mLastRevision->getComment();
  596. $this->mMinorEdit = $this->mLastRevision->isMinor();
  597. $this->mRevIdFetched = $this->mLastRevision->getId();
  598. }
  599. }
  600. public function getTimestamp() {
  601. // Check if the field has been filled by ParserCache::get()
  602. if( !$this->mTimestamp ) {
  603. $this->loadLastEdit();
  604. }
  605. return wfTimestamp(TS_MW, $this->mTimestamp);
  606. }
  607. public function getUser() {
  608. $this->loadLastEdit();
  609. return $this->mUser;
  610. }
  611. public function getUserText() {
  612. $this->loadLastEdit();
  613. return $this->mUserText;
  614. }
  615. public function getComment() {
  616. $this->loadLastEdit();
  617. return $this->mComment;
  618. }
  619. public function getMinorEdit() {
  620. $this->loadLastEdit();
  621. return $this->mMinorEdit;
  622. }
  623. /* Use this to fetch the rev ID used on page views */
  624. public function getRevIdFetched() {
  625. $this->loadLastEdit();
  626. return $this->mRevIdFetched;
  627. }
  628. /**
  629. * @param $limit Integer: default 0.
  630. * @param $offset Integer: default 0.
  631. */
  632. public function getContributors($limit = 0, $offset = 0) {
  633. # XXX: this is expensive; cache this info somewhere.
  634. $contribs = array();
  635. $dbr = wfGetDB( DB_SLAVE );
  636. $revTable = $dbr->tableName( 'revision' );
  637. $userTable = $dbr->tableName( 'user' );
  638. $user = $this->getUser();
  639. $pageId = $this->getId();
  640. $hideBit = Revision::DELETED_USER; // username hidden?
  641. $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
  642. FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
  643. WHERE rev_page = $pageId
  644. AND rev_user != $user
  645. AND rev_deleted & $hideBit = 0
  646. GROUP BY rev_user, rev_user_text, user_real_name
  647. ORDER BY timestamp DESC";
  648. if($limit > 0) { $sql .= ' LIMIT '.$limit; }
  649. if($offset > 0) { $sql .= ' OFFSET '.$offset; }
  650. $sql .= ' '. $this->getSelectOptions();
  651. $res = $dbr->query($sql, __METHOD__ );
  652. return new UserArrayFromResult( $res );
  653. }
  654. /**
  655. * This is the default action of the script: just view the page of
  656. * the given title.
  657. */
  658. public function view() {
  659. global $wgUser, $wgOut, $wgRequest, $wgContLang;
  660. global $wgEnableParserCache, $wgStylePath, $wgParser;
  661. global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
  662. global $wgDefaultRobotPolicy;
  663. # Let the parser know if this is the printable version
  664. if( $wgOut->isPrintable() ) {
  665. $wgOut->parserOptions()->setIsPrintable( true );
  666. }
  667. wfProfileIn( __METHOD__ );
  668. # Get variables from query string
  669. $oldid = $this->getOldID();
  670. # Try client and file cache
  671. if( $oldid === 0 && $this->checkTouched() ) {
  672. global $wgUseETag;
  673. if( $wgUseETag ) {
  674. $parserCache = ParserCache::singleton();
  675. $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) );
  676. }
  677. # Is is client cached?
  678. if( $wgOut->checkLastModified( $this->getTouched() ) ) {
  679. wfProfileOut( __METHOD__ );
  680. return;
  681. # Try file cache
  682. } else if( $this->tryFileCache() ) {
  683. # tell wgOut that output is taken care of
  684. $wgOut->disable();
  685. $this->viewUpdates();
  686. wfProfileOut( __METHOD__ );
  687. return;
  688. }
  689. }
  690. $ns = $this->mTitle->getNamespace(); # shortcut
  691. $sk = $wgUser->getSkin();
  692. # getOldID may want us to redirect somewhere else
  693. if( $this->mRedirectUrl ) {
  694. $wgOut->redirect( $this->mRedirectUrl );
  695. wfProfileOut( __METHOD__ );
  696. return;
  697. }
  698. $diff = $wgRequest->getVal( 'diff' );
  699. $rcid = $wgRequest->getVal( 'rcid' );
  700. $rdfrom = $wgRequest->getVal( 'rdfrom' );
  701. $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
  702. $purge = $wgRequest->getVal( 'action' ) == 'purge';
  703. $return404 = false;
  704. $wgOut->setArticleFlag( true );
  705. # Discourage indexing of printable versions, but encourage following
  706. if( $wgOut->isPrintable() ) {
  707. $policy = 'noindex,follow';
  708. } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
  709. $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
  710. } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
  711. # Honour customised robot policies for this namespace
  712. $policy = $wgNamespaceRobotPolicies[$ns];
  713. } else {
  714. $policy = $wgDefaultRobotPolicy;
  715. }
  716. $wgOut->setRobotPolicy( $policy );
  717. # Allow admins to see deleted content if explicitly requested
  718. $delId = $diff ? $diff : $oldid;
  719. $unhide = $wgRequest->getInt('unhide') == 1
  720. && $wgUser->matchEditToken( $wgRequest->getVal('token'), $delId );
  721. # If we got diff and oldid in the query, we want to see a
  722. # diff page instead of the article.
  723. if( !is_null( $diff ) ) {
  724. $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
  725. $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
  726. $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
  727. // DifferenceEngine directly fetched the revision:
  728. $this->mRevIdFetched = $de->mNewid;
  729. $de->showDiffPage( $diffOnly );
  730. // Needed to get the page's current revision
  731. $this->loadPageData();
  732. if( $diff == 0 || $diff == $this->mLatest ) {
  733. # Run view updates for current revision only
  734. $this->viewUpdates();
  735. }
  736. wfProfileOut( __METHOD__ );
  737. return;
  738. }
  739. if( $ns == NS_USER || $ns == NS_USER_TALK ) {
  740. # User/User_talk subpages are not modified. (bug 11443)
  741. if( !$this->mTitle->isSubpage() ) {
  742. $block = new Block();
  743. if( $block->load( $this->mTitle->getBaseText() ) ) {
  744. $wgOut->setRobotpolicy( 'noindex,nofollow' );
  745. }
  746. }
  747. }
  748. # Should the parser cache be used?
  749. $pcache = $this->useParserCache( $oldid );
  750. wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
  751. if( $wgUser->getOption( 'stubthreshold' ) ) {
  752. wfIncrStats( 'pcache_miss_stub' );
  753. }
  754. $wasRedirected = false;
  755. if( isset( $this->mRedirectedFrom ) ) {
  756. // This is an internally redirected page view.
  757. // We'll need a backlink to the source page for navigation.
  758. if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
  759. $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
  760. $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
  761. $wgOut->setSubtitle( $s );
  762. // Set the fragment if one was specified in the redirect
  763. if( strval( $this->mTitle->getFragment() ) != '' ) {
  764. $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
  765. $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
  766. }
  767. // Add a <link rel="canonical"> tag
  768. $wgOut->addLink( array( 'rel' => 'canonical',
  769. 'href' => $this->mTitle->getLocalURL() )
  770. );
  771. $wasRedirected = true;
  772. }
  773. } elseif( !empty( $rdfrom ) ) {
  774. // This is an externally redirected view, from some other wiki.
  775. // If it was reported from a trusted site, supply a backlink.
  776. global $wgRedirectSources;
  777. if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
  778. $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
  779. $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
  780. $wgOut->setSubtitle( $s );
  781. $wasRedirected = true;
  782. }
  783. }
  784. $outputDone = false;
  785. wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
  786. if( $pcache && $wgOut->tryParserCache( $this ) ) {
  787. // Ensure that UI elements requiring revision ID have
  788. // the correct version information.
  789. $wgOut->setRevisionId( $this->mLatest );
  790. $outputDone = true;
  791. }
  792. # Fetch content and check for errors
  793. if( !$outputDone ) {
  794. # If the article does not exist and was deleted, show the log
  795. if( $this->getID() == 0 ) {
  796. $this->showDeletionLog();
  797. }
  798. $text = $this->getContent();
  799. // For now, check also for ID until getContent actually returns
  800. // false for pages that do not exists
  801. if( $text === false || $this->getID() === 0 ) {
  802. # Failed to load, replace text with error message
  803. $t = $this->mTitle->getPrefixedText();
  804. if( $oldid ) {
  805. $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
  806. $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
  807. // Always use page content for pages in the MediaWiki namespace
  808. // since it contains the default message
  809. } elseif ( $this->mTitle->getNamespace() != NS_MEDIAWIKI ) {
  810. $text = wfMsgExt( 'noarticletext', 'parsemag' );
  811. }
  812. }
  813. # Non-existent pages
  814. if( $this->getID() === 0 ) {
  815. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  816. $text = "<div class='noarticletext'>\n$text\n</div>";
  817. if( !$this->hasViewableContent() ) {
  818. // If there's no backing content, send a 404 Not Found
  819. // for better machine handling of broken links.
  820. $return404 = true;
  821. }
  822. }
  823. if( $return404 ) {
  824. $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
  825. }
  826. # Another whitelist check in case oldid is altering the title
  827. if( !$this->mTitle->userCanRead() ) {
  828. $wgOut->loginToUse();
  829. $wgOut->output();
  830. $wgOut->disable();
  831. wfProfileOut( __METHOD__ );
  832. return;
  833. }
  834. # For ?curid=x urls, disallow indexing
  835. if( $wgRequest->getInt('curid') )
  836. $wgOut->setRobotPolicy( 'noindex,follow' );
  837. # We're looking at an old revision
  838. if( !empty( $oldid ) ) {
  839. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  840. if( is_null( $this->mRevision ) ) {
  841. // FIXME: This would be a nice place to load the 'no such page' text.
  842. } else {
  843. $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
  844. # Allow admins to see deleted content if explicitly requested
  845. if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
  846. if( !$unhide || !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
  847. $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
  848. $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
  849. wfProfileOut( __METHOD__ );
  850. return;
  851. } else {
  852. $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
  853. // and we are allowed to see...
  854. }
  855. }
  856. // Is this the current revision and otherwise cacheable? Try the parser cache...
  857. if( $oldid === $this->getLatest() && $this->useParserCache( false )
  858. && $wgOut->tryParserCache( $this ) )
  859. {
  860. $outputDone = true;
  861. }
  862. }
  863. }
  864. // Ensure that UI elements requiring revision ID have
  865. // the correct version information.
  866. $wgOut->setRevisionId( $this->getRevIdFetched() );
  867. if( $outputDone ) {
  868. // do nothing...
  869. // Pages containing custom CSS or JavaScript get special treatment
  870. } else if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
  871. $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
  872. // Give hooks a chance to customise the output
  873. if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
  874. // Wrap the whole lot in a <pre> and don't parse
  875. $m = array();
  876. preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
  877. $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
  878. $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
  879. $wgOut->addHTML( "\n</pre>\n" );
  880. }
  881. } else if( $rt = Title::newFromRedirectArray( $text ) ) { # get an array of redirect targets
  882. # Don't append the subtitle if this was an old revision
  883. $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
  884. $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
  885. $wgOut->addParserOutputNoText( $parseout );
  886. } else if( $pcache ) {
  887. # Display content and save to parser cache
  888. $this->outputWikiText( $text );
  889. } else {
  890. # Display content, don't attempt to save to parser cache
  891. # Don't show section-edit links on old revisions... this way lies madness.
  892. if( !$this->isCurrent() ) {
  893. $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
  894. }
  895. # Display content and don't save to parser cache
  896. # With timing hack -- TS 2006-07-26
  897. $time = -wfTime();
  898. $this->outputWikiText( $text, false );
  899. $time += wfTime();
  900. # Timing hack
  901. if( $time > 3 ) {
  902. wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
  903. $this->mTitle->getPrefixedDBkey()));
  904. }
  905. if( !$this->isCurrent() ) {
  906. $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
  907. }
  908. }
  909. }
  910. /* title may have been set from the cache */
  911. $t = $wgOut->getPageTitle();
  912. if( empty( $t ) ) {
  913. $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
  914. # For the main page, overwrite the <title> element with the con-
  915. # tents of 'pagetitle-view-mainpage' instead of the default (if
  916. # that's not empty).
  917. if( $this->mTitle->equals( Title::newMainPage() ) &&
  918. wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' ) {
  919. $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
  920. }
  921. }
  922. # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
  923. if( $ns == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
  924. $wgOut->addWikiMsg('anontalkpagetext');
  925. }
  926. # If we have been passed an &rcid= parameter, we want to give the user a
  927. # chance to mark this new article as patrolled.
  928. if( !empty($rcid) && $this->mTitle->exists() && $this->mTitle->quickUserCan('patrol') ) {
  929. $wgOut->addHTML(
  930. "<div class='patrollink'>" .
  931. wfMsgHtml( 'markaspatrolledlink',
  932. $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
  933. "action=markpatrolled&rcid=$rcid" )
  934. ) .
  935. '</div>'
  936. );
  937. }
  938. # Trackbacks
  939. if( $wgUseTrackbacks ) {
  940. $this->addTrackbacks();
  941. }
  942. $this->viewUpdates();
  943. wfProfileOut( __METHOD__ );
  944. }
  945. protected function showDeletionLog() {
  946. global $wgUser, $wgOut;
  947. $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
  948. $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
  949. if( $pager->getNumRows() > 0 ) {
  950. $pager->mLimit = 10;
  951. $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
  952. $wgOut->addWikiMsg( 'deleted-notice' );
  953. $wgOut->addHTML(
  954. $loglist->beginLogEventsList() .
  955. $pager->getBody() .
  956. $loglist->endLogEventsList()
  957. );
  958. if( $pager->getNumRows() > 10 ) {
  959. $wgOut->addHTML( $wgUser->getSkin()->link(
  960. SpecialPage::getTitleFor( 'Log' ),
  961. wfMsgHtml( 'deletelog-fulllog' ),
  962. array(),
  963. array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() )
  964. ) );
  965. }
  966. $wgOut->addHTML( '</div>' );
  967. }
  968. }
  969. /*
  970. * Should the parser cache be used?
  971. */
  972. protected function useParserCache( $oldid ) {
  973. global $wgUser, $wgEnableParserCache;
  974. return $wgEnableParserCache
  975. && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
  976. && $this->exists()
  977. && empty( $oldid )
  978. && !$this->mTitle->isCssOrJsPage()
  979. && !$this->mTitle->isCssJsSubpage();
  980. }
  981. /**
  982. * View redirect
  983. * @param $target Title object or Array of destination(s) to redirect
  984. * @param $appendSubtitle Boolean [optional]
  985. * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
  986. */
  987. public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
  988. global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
  989. # Display redirect
  990. if( !is_array( $target ) ) {
  991. $target = array( $target );
  992. }
  993. $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
  994. $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
  995. $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
  996. $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
  997. if( $appendSubtitle ) {
  998. $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
  999. }
  1000. $sk = $wgUser->getSkin();
  1001. // the loop prepends the arrow image before the link, so the first case needs to be outside
  1002. $title = array_shift( $target );
  1003. if( $forceKnown ) {
  1004. $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
  1005. } else {
  1006. $link = $sk->makeLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
  1007. }
  1008. // automatically append redirect=no to each link, since most of them are redirect pages themselves
  1009. foreach( $target as $rt ) {
  1010. if( $forceKnown ) {
  1011. $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
  1012. . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
  1013. } else {
  1014. $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
  1015. . $sk->makeLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
  1016. }
  1017. }
  1018. return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
  1019. '<span class="redirectText">'.$link.'</span>';
  1020. }
  1021. public function addTrackbacks() {
  1022. global $wgOut, $wgUser;
  1023. $dbr = wfGetDB( DB_SLAVE );
  1024. $tbs = $dbr->select( 'trackbacks',
  1025. array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
  1026. array('tb_page' => $this->getID() )
  1027. );
  1028. if( !$dbr->numRows($tbs) ) return;
  1029. $tbtext = "";
  1030. while( $o = $dbr->fetchObject($tbs) ) {
  1031. $rmvtxt = "";
  1032. if( $wgUser->isAllowed( 'trackback' ) ) {
  1033. $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
  1034. $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
  1035. $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
  1036. }
  1037. $tbtext .= "\n";
  1038. $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
  1039. $o->tb_title,
  1040. $o->tb_url,
  1041. $o->tb_ex,
  1042. $o->tb_name,
  1043. $rmvtxt);
  1044. }
  1045. $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
  1046. $this->mTitle->invalidateCache();
  1047. }
  1048. public function deletetrackback() {
  1049. global $wgUser, $wgRequest, $wgOut, $wgTitle;
  1050. if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
  1051. $wgOut->addWikiMsg( 'sessionfailure' );
  1052. return;
  1053. }
  1054. $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
  1055. if( count($permission_errors) ) {
  1056. $wgOut->showPermissionsErrorPage( $permission_errors );
  1057. return;
  1058. }
  1059. $db = wfGetDB( DB_MASTER );
  1060. $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
  1061. $wgOut->addWikiMsg( 'trackbackdeleteok' );
  1062. $this->mTitle->invalidateCache();
  1063. }
  1064. public function render() {
  1065. global $wgOut;
  1066. $wgOut->setArticleBodyOnly(true);
  1067. $this->view();
  1068. }
  1069. /**
  1070. * Handle action=purge
  1071. */
  1072. public function purge() {
  1073. global $wgUser, $wgRequest, $wgOut;
  1074. if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
  1075. if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
  1076. $this->doPurge();
  1077. $this->view();
  1078. }
  1079. } else {
  1080. $action = htmlspecialchars( $wgRequest->getRequestURL() );
  1081. $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
  1082. $form = "<form method=\"post\" action=\"$action\">\n" .
  1083. "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
  1084. "</form>\n";
  1085. $top = wfMsgExt( 'confirm-purge-top', array('parse') );
  1086. $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
  1087. $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
  1088. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  1089. $wgOut->addHTML( $top . $form . $bottom );
  1090. }
  1091. }
  1092. /**
  1093. * Perform the actions of a page purging
  1094. */
  1095. public function doPurge() {
  1096. global $wgUseSquid;
  1097. // Invalidate the cache
  1098. $this->mTitle->invalidateCache();
  1099. if( $wgUseSquid ) {
  1100. // Commit the transaction before the purge is sent
  1101. $dbw = wfGetDB( DB_MASTER );
  1102. $dbw->immediateCommit();
  1103. // Send purge
  1104. $update = SquidUpdate::newSimplePurge( $this->mTitle );
  1105. $update->doUpdate();
  1106. }
  1107. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
  1108. global $wgMessageCache;
  1109. if( $this->getID() == 0 ) {
  1110. $text = false;
  1111. } else {
  1112. $text = $this->getRawText();
  1113. }
  1114. $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
  1115. }
  1116. }
  1117. /**
  1118. * Insert a new empty page record for this article.
  1119. * This *must* be followed up by creating a revision
  1120. * and running $this->updateToLatest( $rev_id );
  1121. * or else the record will be left in a funky state.
  1122. * Best if all done inside a transaction.
  1123. *
  1124. * @param $dbw Database
  1125. * @return int The newly created page_id key, or false if the title already existed
  1126. * @private
  1127. */
  1128. public function insertOn( $dbw ) {
  1129. wfProfileIn( __METHOD__ );
  1130. $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
  1131. $dbw->insert( 'page', array(
  1132. 'page_id' => $page_id,
  1133. 'page_namespace' => $this->mTitle->getNamespace(),
  1134. 'page_title' => $this->mTitle->getDBkey(),
  1135. 'page_counter' => 0,
  1136. 'page_restrictions' => '',
  1137. 'page_is_redirect' => 0, # Will set this shortly...
  1138. 'page_is_new' => 1,
  1139. 'page_random' => wfRandom(),
  1140. 'page_touched' => $dbw->timestamp(),
  1141. 'page_latest' => 0, # Fill this in shortly...
  1142. 'page_len' => 0, # Fill this in shortly...
  1143. ), __METHOD__, 'IGNORE' );
  1144. $affected = $dbw->affectedRows();
  1145. if( $affected ) {
  1146. $newid = $dbw->insertId();
  1147. $this->mTitle->resetArticleId( $newid );
  1148. }
  1149. wfProfileOut( __METHOD__ );
  1150. return $affected ? $newid : false;
  1151. }
  1152. /**
  1153. * Update the page record to point to a newly saved revision.
  1154. *
  1155. * @param $dbw Database object
  1156. * @param $revision Revision: For ID number, and text used to set
  1157. length and redirect status fields
  1158. * @param $lastRevision Integer: if given, will not overwrite the page field
  1159. * when different from the currently set value.
  1160. * Giving 0 indicates the new page flag should be set
  1161. * on.
  1162. * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
  1163. * removing rows in redirect table.
  1164. * @return bool true on success, false on failure
  1165. * @private
  1166. */
  1167. public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
  1168. wfProfileIn( __METHOD__ );
  1169. $text = $revision->getText();
  1170. $rt = Title::newFromRedirect( $text );
  1171. $conditions = array( 'page_id' => $this->getId() );
  1172. if( !is_null( $lastRevision ) ) {
  1173. # An extra check against threads stepping on each other
  1174. $conditions['page_latest'] = $lastRevision;
  1175. }
  1176. $dbw->update( 'page',
  1177. array( /* SET */
  1178. 'page_latest' => $revision->getId(),
  1179. 'page_touched' => $dbw->timestamp(),
  1180. 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
  1181. 'page_is_redirect' => $rt !== NULL ? 1 : 0,
  1182. 'page_len' => strlen( $text ),
  1183. ),
  1184. $conditions,
  1185. __METHOD__ );
  1186. $result = $dbw->affectedRows() != 0;
  1187. if( $result ) {
  1188. $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
  1189. }
  1190. wfProfileOut( __METHOD__ );
  1191. return $result;
  1192. }
  1193. /**
  1194. * Add row to the redirect table if this is a redirect, remove otherwise.
  1195. *
  1196. * @param $dbw Database
  1197. * @param $redirectTitle a title object pointing to the redirect target,
  1198. * or NULL if this is not a redirect
  1199. * @param $lastRevIsRedirect If given, will optimize adding and
  1200. * removing rows in redirect table.
  1201. * @return bool true on success, false on failure
  1202. * @private
  1203. */
  1204. public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
  1205. // Always update redirects (target link might have changed)
  1206. // Update/Insert if we don't know if the last revision was a redirect or not
  1207. // Delete if changing from redirect to non-redirect
  1208. $isRedirect = !is_null($redirectTitle);
  1209. if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
  1210. wfProfileIn( __METHOD__ );
  1211. if( $isRedirect ) {
  1212. // This title is a redirect, Add/Update row in the redirect table
  1213. $set = array( /* SET */
  1214. 'rd_namespace' => $redirectTitle->getNamespace(),
  1215. 'rd_title' => $redirectTitle->getDBkey(),
  1216. 'rd_from' => $this->getId(),
  1217. );
  1218. $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
  1219. } else {
  1220. // This is not a redirect, remove row from redirect table
  1221. $where = array( 'rd_from' => $this->getId() );
  1222. $dbw->delete( 'redirect', $where, __METHOD__);
  1223. }
  1224. if( $this->getTitle()->getNamespace() == NS_FILE ) {
  1225. RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
  1226. }
  1227. wfProfileOut( __METHOD__ );
  1228. return ( $dbw->affectedRows() != 0 );
  1229. }
  1230. return true;
  1231. }
  1232. /**
  1233. * If the given revision is newer than the currently set page_latest,
  1234. * update the page record. Otherwise, do nothing.
  1235. *
  1236. * @param $dbw Database object
  1237. * @param $revision Revision object
  1238. */
  1239. public function updateIfNewerOn( &$dbw, $revision ) {
  1240. wfProfileIn( __METHOD__ );
  1241. $row = $dbw->selectRow(
  1242. array( 'revision', 'page' ),
  1243. array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
  1244. array(
  1245. 'page_id' => $this->getId(),
  1246. 'page_latest=rev_id' ),
  1247. __METHOD__ );
  1248. if( $row ) {
  1249. if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
  1250. wfProfileOut( __METHOD__ );
  1251. return false;
  1252. }
  1253. $prev = $row->rev_id;
  1254. $lastRevIsRedirect = (bool)$row->page_is_redirect;
  1255. } else {
  1256. # No or missing previous revision; mark the page as new
  1257. $prev = 0;
  1258. $lastRevIsRedirect = null;
  1259. }
  1260. $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
  1261. wfProfileOut( __METHOD__ );
  1262. return $ret;
  1263. }
  1264. /**
  1265. * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
  1266. * @return string Complete article text, or null if error
  1267. */
  1268. public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
  1269. wfProfileIn( __METHOD__ );
  1270. if( strval( $section ) == '' ) {
  1271. // Whole-page edit; let the whole text through
  1272. } else {
  1273. if( is_null($edittime) ) {
  1274. $rev = Revision::newFromTitle( $this->mTitle );
  1275. } else {
  1276. $dbw = wfGetDB( DB_MASTER );
  1277. $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
  1278. }
  1279. if( !$rev ) {
  1280. wfDebug( "Article::replaceSection asked for bogus section (page: " .
  1281. $this->getId() . "; section: $section; edittime: $edittime)\n" );
  1282. return null;
  1283. }
  1284. $oldtext = $rev->getText();
  1285. if( $section == 'new' ) {
  1286. # Inserting a new section
  1287. $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
  1288. $text = strlen( trim( $oldtext ) ) > 0
  1289. ? "{$oldtext}\n\n{$subject}{$text}"
  1290. : "{$subject}{$text}";
  1291. } else {
  1292. # Replacing an existing section; roll out the big guns
  1293. global $wgParser;
  1294. $text = $wgParser->replaceSection( $oldtext, $section, $text );
  1295. }
  1296. }
  1297. wfProfileOut( __METHOD__ );
  1298. return $text;
  1299. }
  1300. /**
  1301. * @deprecated use Article::doEdit()
  1302. */
  1303. function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
  1304. wfDeprecated( __METHOD__ );
  1305. $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
  1306. ( $isminor ? EDIT_MINOR : 0 ) |
  1307. ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
  1308. ( $bot ? EDIT_FORCE_BOT : 0 );
  1309. # If this is a comment, add the summary as headline
  1310. if( $comment && $summary != "" ) {
  1311. $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
  1312. }
  1313. $this->doEdit( $text, $summary, $flags );
  1314. $dbw = wfGetDB( DB_MASTER );
  1315. if($watchthis) {
  1316. if(!$this->mTitle->userIsWatching()) {
  1317. $dbw->begin();
  1318. $this->doWatch();
  1319. $dbw->commit();
  1320. }
  1321. } else {
  1322. if( $this->mTitle->userIsWatching() ) {
  1323. $dbw->begin();
  1324. $this->doUnwatch();
  1325. $dbw->commit();
  1326. }
  1327. }
  1328. $this->doRedirect( $this->isRedirect( $text ) );
  1329. }
  1330. /**
  1331. * @deprecated use Article::doEdit()
  1332. */
  1333. function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
  1334. wfDeprecated( __METHOD__ );
  1335. $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
  1336. ( $minor ? EDIT_MINOR : 0 ) |
  1337. ( $forceBot ? EDIT_FORCE_BOT : 0 );
  1338. $status = $this->doEdit( $text, $summary, $flags );
  1339. if( !$status->isOK() ) {
  1340. return false;
  1341. }
  1342. $dbw = wfGetDB( DB_MASTER );
  1343. if( $watchthis ) {
  1344. if(!$this->mTitle->userIsWatching()) {
  1345. $dbw->begin();
  1346. $this->doWatch();
  1347. $dbw->commit();
  1348. }
  1349. } else {
  1350. if( $this->mTitle->userIsWatching() ) {
  1351. $dbw->begin();
  1352. $this->doUnwatch();
  1353. $dbw->commit();
  1354. }
  1355. }
  1356. $extraQuery = ''; // Give extensions a chance to modify URL query on update
  1357. wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
  1358. $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
  1359. return true;
  1360. }
  1361. /**
  1362. * Article::doEdit()
  1363. *
  1364. * Change an existing article or create a new article. Updates RC and all necessary caches,
  1365. * optionally via the deferred update array.
  1366. *
  1367. * $wgUser must be set before calling this function.
  1368. *
  1369. * @param $text String: new text
  1370. * @param $summary String: edit summary
  1371. * @param $flags Integer bitfield:
  1372. * EDIT_NEW
  1373. * Article is known or assumed to be non-existent, create a new one
  1374. * EDIT_UPDATE
  1375. * Article is known or assumed to be pre-existing, update it
  1376. * EDIT_MINOR
  1377. * Mark this edit minor, if the user is allowed to do so
  1378. * EDIT_SUPPRESS_RC
  1379. * Do not log the change in recentchanges
  1380. * EDIT_FORCE_BOT
  1381. * Mark the edit a "bot" edit regardless of user rights
  1382. * EDIT_DEFER_UPDATES
  1383. * Defer some of the updates until the end of index.php
  1384. * EDIT_AUTOSUMMARY
  1385. * Fill in blank summaries with generated text where possible
  1386. *
  1387. * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
  1388. * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
  1389. * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
  1390. * edit-already-exists error will be returned. These two conditions are also possible with
  1391. * auto-detection due to MediaWiki's performance-optimised locking strategy.
  1392. *
  1393. * @param $baseRevId the revision ID this edit was based off, if any
  1394. * @param $user Optional user object, $wgUser will be used if not passed
  1395. *
  1396. * @return Status object. Possible errors:
  1397. * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
  1398. * edit-gone-missing: In update mode, but the article didn't exist
  1399. * edit-conflict: In update mode, the article changed unexpectedly
  1400. * edit-no-change: Warning that the text was the same as before
  1401. * edit-already-exists: In creation mode, but the article already exists
  1402. *
  1403. * Extensions may define additional errors.
  1404. *
  1405. * $return->value will contain an associative array with members as follows:
  1406. * new: Boolean indicating if the function attempted to create a new article
  1407. * revision: The revision object for the inserted revision, or null
  1408. *
  1409. * Compatibility note: this function previously returned a boolean value indicating success/failure
  1410. */
  1411. public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
  1412. global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
  1413. # Low-level sanity check
  1414. if( $this->mTitle->getText() == '' ) {
  1415. throw new MWException( 'Something is trying to edit an article with an empty title' );
  1416. }
  1417. wfProfileIn( __METHOD__ );
  1418. $user = is_null($user) ? $wgUser : $user;
  1419. $status = Status::newGood( array() );
  1420. # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
  1421. $this->loadPageData();
  1422. if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
  1423. $aid = $this->mTitle->getArticleID();
  1424. if( $aid ) {
  1425. $flags |= EDIT_UPDATE;
  1426. } else {
  1427. $flags |= EDIT_NEW;
  1428. }
  1429. }
  1430. if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
  1431. $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
  1432. {
  1433. wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
  1434. wfProfileOut( __METHOD__ );
  1435. if( $status->isOK() ) {
  1436. $status->fatal( 'edit-hook-aborted');
  1437. }
  1438. return $status;
  1439. }
  1440. # Silently ignore EDIT_MINOR if not allowed
  1441. $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
  1442. $bot = $flags & EDIT_FORCE_BOT;
  1443. $oldtext = $this->getRawText(); // current revision
  1444. $oldsize = strlen( $oldtext );
  1445. # Provide autosummaries if one is not provided and autosummaries are enabled.
  1446. if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
  1447. $summary = $this->getAutosummary( $oldtext, $text, $flags );
  1448. }
  1449. $editInfo = $this->prepareTextForEdit( $text );
  1450. $text = $editInfo->pst;
  1451. $newsize = strlen( $text );
  1452. $dbw = wfGetDB( DB_MASTER );
  1453. $now = wfTimestampNow();
  1454. if( $flags & EDIT_UPDATE ) {
  1455. # Update article, but only if changed.
  1456. $status->value['new'] = false;
  1457. # Make sure the revision is either completely inserted or not inserted at all
  1458. if( !$wgDBtransactions ) {
  1459. $userAbort = ignore_user_abort( true );
  1460. }
  1461. $revisionId = 0;
  1462. $changed = ( strcmp( $text, $oldtext ) != 0 );
  1463. if( $changed ) {
  1464. $this->mGoodAdjustment = (int)$this->isCountable( $text )
  1465. - (int)$this->isCountable( $oldtext );
  1466. $this->mTotalAdjustment = 0;
  1467. if( !$this->mLatest ) {
  1468. # Article gone missing
  1469. wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
  1470. $status->fatal( 'edit-gone-missing' );
  1471. wfProfileOut( __METHOD__ );
  1472. return $status;
  1473. }
  1474. $revision = new Revision( array(
  1475. 'page' => $this->getId(),
  1476. 'comment' => $summary,
  1477. 'minor_edit' => $isminor,
  1478. 'text' => $text,
  1479. 'parent_id' => $this->mLatest,
  1480. 'user' => $user->getId(),
  1481. 'user_text' => $user->getName(),
  1482. ) );
  1483. $dbw->begin();
  1484. $revisionId = $revision->insertOn( $dbw );
  1485. # Update page
  1486. #
  1487. # Note that we use $this->mLatest instead of fetching a value from the master DB
  1488. # during the course of this function. This makes sure that EditPage can detect
  1489. # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
  1490. # before this function is called. A previous function used a separate query, this
  1491. # creates a window where concurrent edits can cause an ignored edit conflict.
  1492. $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
  1493. if( !$ok ) {
  1494. /* Belated edit conflict! Run away!! */
  1495. $status->fatal( 'edit-conflict' );
  1496. # Delete the invalid revision if the DB is not transactional
  1497. if( !$wgDBtransactions ) {
  1498. $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
  1499. }
  1500. $revisionId = 0;
  1501. $dbw->rollback();
  1502. } else {
  1503. global $wgUseRCPatrol;
  1504. wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
  1505. # Update recentchanges
  1506. if( !( $flags & EDIT_SUPPRESS_RC ) ) {
  1507. # Mark as patrolled if the user can do so
  1508. $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
  1509. # Add RC row to the DB
  1510. $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
  1511. $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
  1512. $revisionId, $patrolled
  1513. );
  1514. # Log auto-patrolled edits
  1515. if( $patrolled ) {
  1516. PatrolLog::record( $rc, true );
  1517. }
  1518. }
  1519. $user->incEditCount();
  1520. $dbw->commit();
  1521. }
  1522. } else {
  1523. $status->warning( 'edit-no-change' );
  1524. $revision = null;
  1525. // Keep the same revision ID, but do some updates on it
  1526. $revisionId = $this->getRevIdFetched();
  1527. // Update page_touched, this is usually implicit in the page update
  1528. // Other cache updates are done in onArticleEdit()
  1529. $this->mTitle->invalidateCache();
  1530. }
  1531. if( !$wgDBtransactions ) {
  1532. ignore_user_abort( $userAbort );
  1533. }
  1534. // Now that ignore_user_abort is restored, we can respond to fatal errors
  1535. if( !$status->isOK() ) {
  1536. wfProfileOut( __METHOD__ );
  1537. return $status;
  1538. }
  1539. # Invalidate cache of this article and all pages using this article
  1540. # as a template. Partly deferred.
  1541. Article::onArticleEdit( $this->mTitle );
  1542. # Update links tables, site stats, etc.
  1543. $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
  1544. } else {
  1545. # Create new article
  1546. $status->value['new'] = true;
  1547. # Set statistics members
  1548. # We work out if it's countable after PST to avoid counter drift
  1549. # when articles are created with {{subst:}}
  1550. $this->mGoodAdjustment = (int)$this->isCountable( $text );
  1551. $this->mTotalAdjustment = 1;
  1552. $dbw->begin();
  1553. # Add the page record; stake our claim on this title!
  1554. # This will return false if the article already exists
  1555. $newid = $this->insertOn( $dbw );
  1556. if( $newid === false ) {
  1557. $dbw->rollback();
  1558. $status->fatal( 'edit-already-exists' );
  1559. wfProfileOut( __METHOD__ );
  1560. return $status;
  1561. }
  1562. # Save the revision text...
  1563. $revision = new Revision( array(
  1564. 'page' => $newid,
  1565. 'comment' => $summary,
  1566. 'minor_edit' => $isminor,
  1567. 'text' => $text,
  1568. 'user' => $user->getId(),
  1569. 'user_text' => $user->getName(),
  1570. ) );
  1571. $revisionId = $revision->insertOn( $dbw );
  1572. $this->mTitle->resetArticleID( $newid );
  1573. # Update the page record with revision data
  1574. $this->updateRevisionOn( $dbw, $revision, 0 );
  1575. wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
  1576. # Update recentchanges
  1577. if( !( $flags & EDIT_SUPPRESS_RC ) ) {
  1578. global $wgUseRCPatrol, $wgUseNPPatrol;
  1579. # Mark as patrolled if the user can do so
  1580. $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
  1581. # Add RC row to the DB
  1582. $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
  1583. '', strlen($text), $revisionId, $patrolled );
  1584. # Log auto-patrolled edits
  1585. if( $patrolled ) {
  1586. PatrolLog::record( $rc, true );
  1587. }
  1588. }
  1589. $user->incEditCount();
  1590. $dbw->commit();
  1591. # Update links, etc.
  1592. $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
  1593. # Clear caches
  1594. Article::onArticleCreate( $this->mTitle );
  1595. wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
  1596. $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
  1597. }
  1598. # Do updates right now unless deferral was requested
  1599. if( !( $flags & EDIT_DEFER_UPDATES ) ) {
  1600. wfDoUpdates();
  1601. }
  1602. // Return the new revision (or null) to the caller
  1603. $status->value['revision'] = $revision;
  1604. wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
  1605. $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
  1606. wfProfileOut( __METHOD__ );
  1607. return $status;
  1608. }
  1609. /**
  1610. * @deprecated wrapper for doRedirect
  1611. */
  1612. public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
  1613. wfDeprecated( __METHOD__ );
  1614. $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
  1615. }
  1616. /**
  1617. * Output a redirect back to the article.
  1618. * This is typically used after an edit.
  1619. *
  1620. * @param $noRedir Boolean: add redirect=no
  1621. * @param $sectionAnchor String: section to redirect to, including "#"
  1622. * @param $extraQuery String: extra query params
  1623. */
  1624. public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
  1625. global $wgOut;
  1626. if( $noRedir ) {
  1627. $query = 'redirect=no';
  1628. if( $extraQuery )
  1629. $query .= "&$query";
  1630. } else {
  1631. $query = $extraQuery;
  1632. }
  1633. $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
  1634. }
  1635. /**
  1636. * Mark this particular edit/page as patrolled
  1637. */
  1638. public function markpatrolled() {
  1639. global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
  1640. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  1641. # If we haven't been given an rc_id value, we can't do anything
  1642. $rcid = (int) $wgRequest->getVal('rcid');
  1643. $rc = RecentChange::newFromId($rcid);
  1644. if( is_null($rc) ) {
  1645. $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
  1646. return;
  1647. }
  1648. #It would be nice to see where the user had actually come from, but for now just guess
  1649. $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
  1650. $return = SpecialPage::getTitleFor( $returnto );
  1651. $dbw = wfGetDB( DB_MASTER );
  1652. $errors = $rc->doMarkPatrolled();
  1653. if( in_array(array('rcpatroldisabled'), $errors) ) {
  1654. $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
  1655. return;
  1656. }
  1657. if( in_array(array('hookaborted'), $errors) ) {
  1658. // The hook itself has handled any output
  1659. return;
  1660. }
  1661. if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
  1662. $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
  1663. $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
  1664. $wgOut->returnToMain( false, $return );
  1665. return;
  1666. }
  1667. if( !empty($errors) ) {
  1668. $wgOut->showPermissionsErrorPage( $errors );
  1669. return;
  1670. }
  1671. # Inform the user
  1672. $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
  1673. $wgOut->addWikiMsg( 'markedaspatrolledtext' );
  1674. $wgOut->returnToMain( false, $return );
  1675. }
  1676. /**
  1677. * User-interface handler for the "watch" action
  1678. */
  1679. public function watch() {
  1680. global $wgUser, $wgOut;
  1681. if( $wgUser->isAnon() ) {
  1682. $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
  1683. return;
  1684. }
  1685. if( wfReadOnly() ) {
  1686. $wgOut->readOnlyPage();
  1687. return;
  1688. }
  1689. if( $this->doWatch() ) {
  1690. $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
  1691. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  1692. $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
  1693. }
  1694. $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
  1695. }
  1696. /**
  1697. * Add this page to $wgUser's watchlist
  1698. * @return bool true on successful watch operation
  1699. */
  1700. public function doWatch() {
  1701. global $wgUser;
  1702. if( $wgUser->isAnon() ) {
  1703. return false;
  1704. }
  1705. if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
  1706. $wgUser->addWatch( $this->mTitle );
  1707. return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
  1708. }
  1709. return false;
  1710. }
  1711. /**
  1712. * User interface handler for the "unwatch" action.
  1713. */
  1714. public function unwatch() {
  1715. global $wgUser, $wgOut;
  1716. if( $wgUser->isAnon() ) {
  1717. $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
  1718. return;
  1719. }
  1720. if( wfReadOnly() ) {
  1721. $wgOut->readOnlyPage();
  1722. return;
  1723. }
  1724. if( $this->doUnwatch() ) {
  1725. $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
  1726. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  1727. $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
  1728. }
  1729. $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
  1730. }
  1731. /**
  1732. * Stop watching a page
  1733. * @return bool true on successful unwatch
  1734. */
  1735. public function doUnwatch() {
  1736. global $wgUser;
  1737. if( $wgUser->isAnon() ) {
  1738. return false;
  1739. }
  1740. if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
  1741. $wgUser->removeWatch( $this->mTitle );
  1742. return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
  1743. }
  1744. return false;
  1745. }
  1746. /**
  1747. * action=protect handler
  1748. */
  1749. public function protect() {
  1750. $form = new ProtectionForm( $this );
  1751. $form->execute();
  1752. }
  1753. /**
  1754. * action=unprotect handler (alias)
  1755. */
  1756. public function unprotect() {
  1757. $this->protect();
  1758. }
  1759. /**
  1760. * Update the article's restriction field, and leave a log entry.
  1761. *
  1762. * @param $limit Array: set of restriction keys
  1763. * @param $reason String
  1764. * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
  1765. * @param $expiry Array: per restriction type expiration
  1766. * @return bool true on success
  1767. */
  1768. public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
  1769. global $wgUser, $wgRestrictionTypes, $wgContLang;
  1770. $id = $this->mTitle->getArticleID();
  1771. if ( $id <= 0 ) {
  1772. wfDebug( "updateRestrictions failed: $id <= 0\n" );
  1773. return false;
  1774. }
  1775. if ( wfReadOnly() ) {
  1776. wfDebug( "updateRestrictions failed: read-only\n" );
  1777. return false;
  1778. }
  1779. if ( !$this->mTitle->userCan( 'protect' ) ) {
  1780. wfDebug( "updateRestrictions failed: insufficient permissions\n" );
  1781. return false;
  1782. }
  1783. if( !$cascade ) {
  1784. $cascade = false;
  1785. }
  1786. // Take this opportunity to purge out expired restrictions
  1787. Title::purgeExpiredRestrictions();
  1788. # FIXME: Same limitations as described in ProtectionForm.php (line 37);
  1789. # we expect a single selection, but the schema allows otherwise.
  1790. $current = array();
  1791. $updated = Article::flattenRestrictions( $limit );
  1792. $changed = false;
  1793. foreach( $wgRestrictionTypes as $action ) {
  1794. if( isset( $expiry[$action] ) ) {
  1795. # Get current restrictions on $action
  1796. $aLimits = $this->mTitle->getRestrictions( $action );
  1797. $current[$action] = implode( '', $aLimits );
  1798. # Are any actual restrictions being dealt with here?
  1799. $aRChanged = count($aLimits) || !empty($limit[$action]);
  1800. # If something changed, we need to log it. Checking $aRChanged
  1801. # assures that "unprotecting" a page that is not protected does
  1802. # not log just because the expiry was "changed".
  1803. if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
  1804. $changed = true;
  1805. }
  1806. }
  1807. }
  1808. $current = Article::flattenRestrictions( $current );
  1809. $changed = ($changed || $current != $updated );
  1810. $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
  1811. $protect = ( $updated != '' );
  1812. # If nothing's changed, do nothing
  1813. if( $changed ) {
  1814. if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
  1815. $dbw = wfGetDB( DB_MASTER );
  1816. # Prepare a null revision to be added to the history
  1817. $modified = $current != '' && $protect;
  1818. if( $protect ) {
  1819. $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
  1820. } else {
  1821. $comment_type = 'unprotectedarticle';
  1822. }
  1823. $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
  1824. # Only restrictions with the 'protect' right can cascade...
  1825. # Otherwise, people who cannot normally protect can "protect" pages via transclusion
  1826. $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
  1827. # The schema allows multiple restrictions
  1828. if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
  1829. $cascade = false;
  1830. $cascade_description = '';
  1831. if( $cascade ) {
  1832. $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
  1833. }
  1834. if( $reason )
  1835. $comment .= ": $reason";
  1836. $editComment = $comment;
  1837. $encodedExpiry = array();
  1838. $protect_description = '';
  1839. foreach( $limit as $action => $restrictions ) {
  1840. if ( !isset($expiry[$action]) )
  1841. $expiry[$action] = 'infinite';
  1842. $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
  1843. if( $restrictions != '' ) {
  1844. $protect_description .= "[$action=$restrictions] (";
  1845. if( $encodedExpiry[$action] != 'infinity' ) {
  1846. $protect_description .= wfMsgForContent( 'protect-expiring',
  1847. $wgContLang->timeanddate( $expiry[$action], false, false ) ,
  1848. $wgContLang->date( $expiry[$action], false, false ) ,
  1849. $wgContLang->time( $expiry[$action], false, false ) );
  1850. } else {
  1851. $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
  1852. }
  1853. $protect_description .= ') ';
  1854. }
  1855. }
  1856. $protect_description = trim($protect_description);
  1857. if( $protect_description && $protect )
  1858. $editComment .= " ($protect_description)";
  1859. if( $cascade )
  1860. $editComment .= "$cascade_description";
  1861. # Update restrictions table
  1862. foreach( $limit as $action => $restrictions ) {
  1863. if($restrictions != '' ) {
  1864. $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
  1865. array( 'pr_page' => $id,
  1866. 'pr_type' => $action,
  1867. 'pr_level' => $restrictions,
  1868. 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
  1869. 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
  1870. } else {
  1871. $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
  1872. 'pr_type' => $action ), __METHOD__ );
  1873. }
  1874. }
  1875. # Insert a null revision
  1876. $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
  1877. $nullRevId = $nullRevision->insertOn( $dbw );
  1878. $latest = $this->getLatest();
  1879. # Update page record
  1880. $dbw->update( 'page',
  1881. array( /* SET */
  1882. 'page_touched' => $dbw->timestamp(),
  1883. 'page_restrictions' => '',
  1884. 'page_latest' => $nullRevId
  1885. ), array( /* WHERE */
  1886. 'page_id' => $id
  1887. ), 'Article::protect'
  1888. );
  1889. wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
  1890. wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
  1891. # Update the protection log
  1892. $log = new LogPage( 'protect' );
  1893. if( $protect ) {
  1894. $params = array($protect_description,$cascade ? 'cascade' : '');
  1895. $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
  1896. } else {
  1897. $log->addEntry( 'unprotect', $this->mTitle, $reason );
  1898. }
  1899. } # End hook
  1900. } # End "changed" check
  1901. return true;
  1902. }
  1903. /**
  1904. * Take an array of page restrictions and flatten it to a string
  1905. * suitable for insertion into the page_restrictions field.
  1906. * @param $limit Array
  1907. * @return String
  1908. */
  1909. protected static function flattenRestrictions( $limit ) {
  1910. if( !is_array( $limit ) ) {
  1911. throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
  1912. }
  1913. $bits = array();
  1914. ksort( $limit );
  1915. foreach( $limit as $action => $restrictions ) {
  1916. if( $restrictions != '' ) {
  1917. $bits[] = "$action=$restrictions";
  1918. }
  1919. }
  1920. return implode( ':', $bits );
  1921. }
  1922. /**
  1923. * Auto-generates a deletion reason
  1924. * @param &$hasHistory Boolean: whether the page has a history
  1925. */
  1926. public function generateReason( &$hasHistory ) {
  1927. global $wgContLang;
  1928. $dbw = wfGetDB( DB_MASTER );
  1929. // Get the last revision
  1930. $rev = Revision::newFromTitle( $this->mTitle );
  1931. if( is_null( $rev ) )
  1932. return false;
  1933. // Get the article's contents
  1934. $contents = $rev->getText();
  1935. $blank = false;
  1936. // If the page is blank, use the text from the previous revision,
  1937. // which can only be blank if there's a move/import/protect dummy revision involved
  1938. if( $contents == '' ) {
  1939. $prev = $rev->getPrevious();
  1940. if( $prev ) {
  1941. $contents = $prev->getText();
  1942. $blank = true;
  1943. }
  1944. }
  1945. // Find out if there was only one contributor
  1946. // Only scan the last 20 revisions
  1947. $limit = 20;
  1948. $res = $dbw->select( 'revision', 'rev_user_text',
  1949. array( 'rev_page' => $this->getID() ), __METHOD__,
  1950. array( 'LIMIT' => $limit )
  1951. );
  1952. if( $res === false )
  1953. // This page has no revisions, which is very weird
  1954. return false;
  1955. if( $res->numRows() > 1 )
  1956. $hasHistory = true;
  1957. else
  1958. $hasHistory = false;
  1959. $row = $dbw->fetchObject( $res );
  1960. $onlyAuthor = $row->rev_user_text;
  1961. // Try to find a second contributor
  1962. foreach( $res as $row ) {
  1963. if( $row->rev_user_text != $onlyAuthor ) {
  1964. $onlyAuthor = false;
  1965. break;
  1966. }
  1967. }
  1968. $dbw->freeResult( $res );
  1969. // Generate the summary with a '$1' placeholder
  1970. if( $blank ) {
  1971. // The current revision is blank and the one before is also
  1972. // blank. It's just not our lucky day
  1973. $reason = wfMsgForContent( 'exbeforeblank', '$1' );
  1974. } else {
  1975. if( $onlyAuthor )
  1976. $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
  1977. else
  1978. $reason = wfMsgForContent( 'excontent', '$1' );
  1979. }
  1980. if( $reason == '-' ) {
  1981. // Allow these UI messages to be blanked out cleanly
  1982. return '';
  1983. }
  1984. // Replace newlines with spaces to prevent uglyness
  1985. $contents = preg_replace( "/[\n\r]/", ' ', $contents );
  1986. // Calculate the maximum amount of chars to get
  1987. // Max content length = max comment length - length of the comment (excl. $1) - '...'
  1988. $maxLength = 255 - (strlen( $reason ) - 2) - 3;
  1989. $contents = $wgContLang->truncate( $contents, $maxLength );
  1990. // Remove possible unfinished links
  1991. $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
  1992. // Now replace the '$1' placeholder
  1993. $reason = str_replace( '$1', $contents, $reason );
  1994. return $reason;
  1995. }
  1996. /*
  1997. * UI entry point for page deletion
  1998. */
  1999. public function delete() {
  2000. global $wgUser, $wgOut, $wgRequest;
  2001. $confirm = $wgRequest->wasPosted() &&
  2002. $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
  2003. $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
  2004. $this->DeleteReason = $wgRequest->getText( 'wpReason' );
  2005. $reason = $this->DeleteReasonList;
  2006. if( $reason != 'other' && $this->DeleteReason != '' ) {
  2007. // Entry from drop down menu + additional comment
  2008. $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
  2009. } elseif( $reason == 'other' ) {
  2010. $reason = $this->DeleteReason;
  2011. }
  2012. # Flag to hide all contents of the archived revisions
  2013. $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
  2014. # This code desperately needs to be totally rewritten
  2015. # Read-only check...
  2016. if( wfReadOnly() ) {
  2017. $wgOut->readOnlyPage();
  2018. return;
  2019. }
  2020. # Check permissions
  2021. $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
  2022. if( count( $permission_errors ) > 0 ) {
  2023. $wgOut->showPermissionsErrorPage( $permission_errors );
  2024. return;
  2025. }
  2026. $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
  2027. # Better double-check that it hasn't been deleted yet!
  2028. $dbw = wfGetDB( DB_MASTER );
  2029. $conds = $this->mTitle->pageCond();
  2030. $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
  2031. if( $latest === false ) {
  2032. $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
  2033. $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
  2034. LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
  2035. return;
  2036. }
  2037. # Hack for big sites
  2038. $bigHistory = $this->isBigDeletion();
  2039. if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
  2040. global $wgLang, $wgDeleteRevisionsLimit;
  2041. $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
  2042. array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
  2043. return;
  2044. }
  2045. if( $confirm ) {
  2046. $this->doDelete( $reason, $suppress );
  2047. if( $wgRequest->getCheck( 'wpWatch' ) ) {
  2048. $this->doWatch();
  2049. } elseif( $this->mTitle->userIsWatching() ) {
  2050. $this->doUnwatch();
  2051. }
  2052. return;
  2053. }
  2054. // Generate deletion reason
  2055. $hasHistory = false;
  2056. if( !$reason ) $reason = $this->generateReason($hasHistory);
  2057. // If the page has a history, insert a warning
  2058. if( $hasHistory && !$confirm ) {
  2059. $skin = $wgUser->getSkin();
  2060. $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
  2061. if( $bigHistory ) {
  2062. global $wgLang, $wgDeleteRevisionsLimit;
  2063. $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
  2064. array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
  2065. }
  2066. }
  2067. return $this->confirmDelete( $reason );
  2068. }
  2069. /**
  2070. * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
  2071. */
  2072. public function isBigDeletion() {
  2073. global $wgDeleteRevisionsLimit;
  2074. if( $wgDeleteRevisionsLimit ) {
  2075. $revCount = $this->estimateRevisionCount();
  2076. return $revCount > $wgDeleteRevisionsLimit;
  2077. }
  2078. return false;
  2079. }
  2080. /**
  2081. * @return int approximate revision count
  2082. */
  2083. public function estimateRevisionCount() {
  2084. $dbr = wfGetDB( DB_SLAVE );
  2085. // For an exact count...
  2086. //return $dbr->selectField( 'revision', 'COUNT(*)',
  2087. // array( 'rev_page' => $this->getId() ), __METHOD__ );
  2088. return $dbr->estimateRowCount( 'revision', '*',
  2089. array( 'rev_page' => $this->getId() ), __METHOD__ );
  2090. }
  2091. /**
  2092. * Get the last N authors
  2093. * @param $num Integer: number of revisions to get
  2094. * @param $revLatest String: the latest rev_id, selected from the master (optional)
  2095. * @return array Array of authors, duplicates not removed
  2096. */
  2097. public function getLastNAuthors( $num, $revLatest = 0 ) {
  2098. wfProfileIn( __METHOD__ );
  2099. // First try the slave
  2100. // If that doesn't have the latest revision, try the master
  2101. $continue = 2;
  2102. $db = wfGetDB( DB_SLAVE );
  2103. do {
  2104. $res = $db->select( array( 'page', 'revision' ),
  2105. array( 'rev_id', 'rev_user_text' ),
  2106. array(
  2107. 'page_namespace' => $this->mTitle->getNamespace(),
  2108. 'page_title' => $this->mTitle->getDBkey(),
  2109. 'rev_page = page_id'
  2110. ), __METHOD__, $this->getSelectOptions( array(
  2111. 'ORDER BY' => 'rev_timestamp DESC',
  2112. 'LIMIT' => $num
  2113. ) )
  2114. );
  2115. if( !$res ) {
  2116. wfProfileOut( __METHOD__ );
  2117. return array();
  2118. }
  2119. $row = $db->fetchObject( $res );
  2120. if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
  2121. $db = wfGetDB( DB_MASTER );
  2122. $continue--;
  2123. } else {
  2124. $continue = 0;
  2125. }
  2126. } while ( $continue );
  2127. $authors = array( $row->rev_user_text );
  2128. while ( $row = $db->fetchObject( $res ) ) {
  2129. $authors[] = $row->rev_user_text;
  2130. }
  2131. wfProfileOut( __METHOD__ );
  2132. return $authors;
  2133. }
  2134. /**
  2135. * Output deletion confirmation dialog
  2136. * @param $reason String: prefilled reason
  2137. */
  2138. public function confirmDelete( $reason ) {
  2139. global $wgOut, $wgUser;
  2140. wfDebug( "Article::confirmDelete\n" );
  2141. $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
  2142. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  2143. $wgOut->addWikiMsg( 'confirmdeletetext' );
  2144. if( $wgUser->isAllowed( 'suppressrevision' ) ) {
  2145. $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
  2146. <td></td>
  2147. <td class='mw-input'>" .
  2148. Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
  2149. 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
  2150. "</td>
  2151. </tr>";
  2152. } else {
  2153. $suppress = '';
  2154. }
  2155. $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
  2156. $form = Xml::openElement( 'form', array( 'method' => 'post',
  2157. 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
  2158. Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
  2159. Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
  2160. Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
  2161. "<tr id=\"wpDeleteReasonListRow\">
  2162. <td class='mw-label'>" .
  2163. Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
  2164. "</td>
  2165. <td class='mw-input'>" .
  2166. Xml::listDropDown( 'wpDeleteReasonList',
  2167. wfMsgForContent( 'deletereason-dropdown' ),
  2168. wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
  2169. "</td>
  2170. </tr>
  2171. <tr id=\"wpDeleteReasonRow\">
  2172. <td class='mw-label'>" .
  2173. Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
  2174. "</td>
  2175. <td class='mw-input'>" .
  2176. Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
  2177. 'tabindex' => '2', 'id' => 'wpReason' ) ) .
  2178. "</td>
  2179. </tr>
  2180. <tr>
  2181. <td></td>
  2182. <td class='mw-input'>" .
  2183. Xml::checkLabel( wfMsg( 'watchthis' ),
  2184. 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
  2185. "</td>
  2186. </tr>
  2187. $suppress
  2188. <tr>
  2189. <td></td>
  2190. <td class='mw-submit'>" .
  2191. Xml::submitButton( wfMsg( 'deletepage' ),
  2192. array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
  2193. "</td>
  2194. </tr>" .
  2195. Xml::closeElement( 'table' ) .
  2196. Xml::closeElement( 'fieldset' ) .
  2197. Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
  2198. Xml::closeElement( 'form' );
  2199. if( $wgUser->isAllowed( 'editinterface' ) ) {
  2200. $skin = $wgUser->getSkin();
  2201. $link = $skin->makeLink ( 'MediaWiki:Deletereason-dropdown', wfMsgHtml( 'delete-edit-reasonlist' ) );
  2202. $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
  2203. }
  2204. $wgOut->addHTML( $form );
  2205. LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
  2206. }
  2207. /**
  2208. * Perform a deletion and output success or failure messages
  2209. */
  2210. public function doDelete( $reason, $suppress = false ) {
  2211. global $wgOut, $wgUser;
  2212. $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
  2213. $error = '';
  2214. if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
  2215. if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
  2216. $deleted = $this->mTitle->getPrefixedText();
  2217. $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
  2218. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  2219. $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
  2220. $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
  2221. $wgOut->returnToMain( false );
  2222. wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
  2223. } else {
  2224. if( $error == '' ) {
  2225. $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
  2226. $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
  2227. LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
  2228. } else {
  2229. $wgOut->showFatalError( $error );
  2230. }
  2231. }
  2232. }
  2233. }
  2234. /**
  2235. * Back-end article deletion
  2236. * Deletes the article with database consistency, writes logs, purges caches
  2237. * Returns success
  2238. */
  2239. public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
  2240. global $wgUseSquid, $wgDeferredUpdateList;
  2241. global $wgUseTrackbacks;
  2242. wfDebug( __METHOD__."\n" );
  2243. $dbw = wfGetDB( DB_MASTER );
  2244. $ns = $this->mTitle->getNamespace();
  2245. $t = $this->mTitle->getDBkey();
  2246. $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
  2247. if( $t == '' || $id == 0 ) {
  2248. return false;
  2249. }
  2250. $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
  2251. array_push( $wgDeferredUpdateList, $u );
  2252. // Bitfields to further suppress the content
  2253. if( $suppress ) {
  2254. $bitfield = 0;
  2255. // This should be 15...
  2256. $bitfield |= Revision::DELETED_TEXT;
  2257. $bitfield |= Revision::DELETED_COMMENT;
  2258. $bitfield |= Revision::DELETED_USER;
  2259. $bitfield |= Revision::DELETED_RESTRICTED;
  2260. } else {
  2261. $bitfield = 'rev_deleted';
  2262. }
  2263. $dbw->begin();
  2264. // For now, shunt the revision data into the archive table.
  2265. // Text is *not* removed from the text table; bulk storage
  2266. // is left intact to avoid breaking block-compression or
  2267. // immutable storage schemes.
  2268. //
  2269. // For backwards compatibility, note that some older archive
  2270. // table entries will have ar_text and ar_flags fields still.
  2271. //
  2272. // In the future, we may keep revisions and mark them with
  2273. // the rev_deleted field, which is reserved for this purpose.
  2274. $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
  2275. array(
  2276. 'ar_namespace' => 'page_namespace',
  2277. 'ar_title' => 'page_title',
  2278. 'ar_comment' => 'rev_comment',
  2279. 'ar_user' => 'rev_user',
  2280. 'ar_user_text' => 'rev_user_text',
  2281. 'ar_timestamp' => 'rev_timestamp',
  2282. 'ar_minor_edit' => 'rev_minor_edit',
  2283. 'ar_rev_id' => 'rev_id',
  2284. 'ar_text_id' => 'rev_text_id',
  2285. 'ar_text' => '\'\'', // Be explicit to appease
  2286. 'ar_flags' => '\'\'', // MySQL's "strict mode"...
  2287. 'ar_len' => 'rev_len',
  2288. 'ar_page_id' => 'page_id',
  2289. 'ar_deleted' => $bitfield
  2290. ), array(
  2291. 'page_id' => $id,
  2292. 'page_id = rev_page'
  2293. ), __METHOD__
  2294. );
  2295. # Delete restrictions for it
  2296. $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
  2297. # Now that it's safely backed up, delete it
  2298. $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
  2299. $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
  2300. if( !$ok ) {
  2301. $dbw->rollback();
  2302. return false;
  2303. }
  2304. # Fix category table counts
  2305. $cats = array();
  2306. $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
  2307. foreach( $res as $row ) {
  2308. $cats []= $row->cl_to;
  2309. }
  2310. $this->updateCategoryCounts( array(), $cats );
  2311. # If using cascading deletes, we can skip some explicit deletes
  2312. if( !$dbw->cascadingDeletes() ) {
  2313. $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
  2314. if($wgUseTrackbacks)
  2315. $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
  2316. # Delete outgoing links
  2317. $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
  2318. $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
  2319. $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
  2320. $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
  2321. $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
  2322. $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
  2323. $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
  2324. }
  2325. # If using cleanup triggers, we can skip some manual deletes
  2326. if( !$dbw->cleanupTriggers() ) {
  2327. # Clean up recentchanges entries...
  2328. $dbw->delete( 'recentchanges',
  2329. array( 'rc_type != '.RC_LOG,
  2330. 'rc_namespace' => $this->mTitle->getNamespace(),
  2331. 'rc_title' => $this->mTitle->getDBKey() ),
  2332. __METHOD__ );
  2333. $dbw->delete( 'recentchanges',
  2334. array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
  2335. __METHOD__ );
  2336. }
  2337. # Clear caches
  2338. Article::onArticleDelete( $this->mTitle );
  2339. # Clear the cached article id so the interface doesn't act like we exist
  2340. $this->mTitle->resetArticleID( 0 );
  2341. # Log the deletion, if the page was suppressed, log it at Oversight instead
  2342. $logtype = $suppress ? 'suppress' : 'delete';
  2343. $log = new LogPage( $logtype );
  2344. # Make sure logging got through
  2345. $log->addEntry( 'delete', $this->mTitle, $reason, array() );
  2346. $dbw->commit();
  2347. return true;
  2348. }
  2349. /**
  2350. * Roll back the most recent consecutive set of edits to a page
  2351. * from the same user; fails if there are no eligible edits to
  2352. * roll back to, e.g. user is the sole contributor. This function
  2353. * performs permissions checks on $wgUser, then calls commitRollback()
  2354. * to do the dirty work
  2355. *
  2356. * @param $fromP String: Name of the user whose edits to rollback.
  2357. * @param $summary String: Custom summary. Set to default summary if empty.
  2358. * @param $token String: Rollback token.
  2359. * @param $bot Boolean: If true, mark all reverted edits as bot.
  2360. *
  2361. * @param $resultDetails Array: contains result-specific array of additional values
  2362. * 'alreadyrolled' : 'current' (rev)
  2363. * success : 'summary' (str), 'current' (rev), 'target' (rev)
  2364. *
  2365. * @return array of errors, each error formatted as
  2366. * array(messagekey, param1, param2, ...).
  2367. * On success, the array is empty. This array can also be passed to
  2368. * OutputPage::showPermissionsErrorPage().
  2369. */
  2370. public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
  2371. global $wgUser;
  2372. $resultDetails = null;
  2373. # Check permissions
  2374. $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
  2375. $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
  2376. $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
  2377. if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
  2378. $errors[] = array( 'sessionfailure' );
  2379. if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
  2380. $errors[] = array( 'actionthrottledtext' );
  2381. }
  2382. # If there were errors, bail out now
  2383. if( !empty( $errors ) )
  2384. return $errors;
  2385. return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
  2386. }
  2387. /**
  2388. * Backend implementation of doRollback(), please refer there for parameter
  2389. * and return value documentation
  2390. *
  2391. * NOTE: This function does NOT check ANY permissions, it just commits the
  2392. * rollback to the DB Therefore, you should only call this function direct-
  2393. * ly if you want to use custom permissions checks. If you don't, use
  2394. * doRollback() instead.
  2395. */
  2396. public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
  2397. global $wgUseRCPatrol, $wgUser, $wgLang;
  2398. $dbw = wfGetDB( DB_MASTER );
  2399. if( wfReadOnly() ) {
  2400. return array( array( 'readonlytext' ) );
  2401. }
  2402. # Get the last editor
  2403. $current = Revision::newFromTitle( $this->mTitle );
  2404. if( is_null( $current ) ) {
  2405. # Something wrong... no page?
  2406. return array(array('notanarticle'));
  2407. }
  2408. $from = str_replace( '_', ' ', $fromP );
  2409. if( $from != $current->getUserText() ) {
  2410. $resultDetails = array( 'current' => $current );
  2411. return array(array('alreadyrolled',
  2412. htmlspecialchars($this->mTitle->getPrefixedText()),
  2413. htmlspecialchars($fromP),
  2414. htmlspecialchars($current->getUserText())
  2415. ));
  2416. }
  2417. # Get the last edit not by this guy
  2418. $user = intval( $current->getUser() );
  2419. $user_text = $dbw->addQuotes( $current->getUserText() );
  2420. $s = $dbw->selectRow( 'revision',
  2421. array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
  2422. array( 'rev_page' => $current->getPage(),
  2423. "rev_user != {$user} OR rev_user_text != {$user_text}"
  2424. ), __METHOD__,
  2425. array( 'USE INDEX' => 'page_timestamp',
  2426. 'ORDER BY' => 'rev_timestamp DESC' )
  2427. );
  2428. if( $s === false ) {
  2429. # No one else ever edited this page
  2430. return array(array('cantrollback'));
  2431. } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
  2432. # Only admins can see this text
  2433. return array(array('notvisiblerev'));
  2434. }
  2435. $set = array();
  2436. if( $bot && $wgUser->isAllowed('markbotedits') ) {
  2437. # Mark all reverted edits as bot
  2438. $set['rc_bot'] = 1;
  2439. }
  2440. if( $wgUseRCPatrol ) {
  2441. # Mark all reverted edits as patrolled
  2442. $set['rc_patrolled'] = 1;
  2443. }
  2444. if( $set ) {
  2445. $dbw->update( 'recentchanges', $set,
  2446. array( /* WHERE */
  2447. 'rc_cur_id' => $current->getPage(),
  2448. 'rc_user_text' => $current->getUserText(),
  2449. "rc_timestamp > '{$s->rev_timestamp}'",
  2450. ), __METHOD__
  2451. );
  2452. }
  2453. # Generate the edit summary if necessary
  2454. $target = Revision::newFromId( $s->rev_id );
  2455. if( empty( $summary ) ){
  2456. $summary = wfMsgForContent( 'revertpage' );
  2457. }
  2458. # Allow the custom summary to use the same args as the default message
  2459. $args = array(
  2460. $target->getUserText(), $from, $s->rev_id,
  2461. $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
  2462. $current->getId(), $wgLang->timeanddate($current->getTimestamp())
  2463. );
  2464. $summary = wfMsgReplaceArgs( $summary, $args );
  2465. # Save
  2466. $flags = EDIT_UPDATE;
  2467. if( $wgUser->isAllowed('minoredit') )
  2468. $flags |= EDIT_MINOR;
  2469. if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
  2470. $flags |= EDIT_FORCE_BOT;
  2471. # Actually store the edit
  2472. $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
  2473. if( !empty( $status->value['revision'] ) ) {
  2474. $revId = $status->value['revision']->getId();
  2475. } else {
  2476. $revId = false;
  2477. }
  2478. wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
  2479. $resultDetails = array(
  2480. 'summary' => $summary,
  2481. 'current' => $current,
  2482. 'target' => $target,
  2483. 'newid' => $revId
  2484. );
  2485. return array();
  2486. }
  2487. /**
  2488. * User interface for rollback operations
  2489. */
  2490. public function rollback() {
  2491. global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
  2492. $details = null;
  2493. $result = $this->doRollback(
  2494. $wgRequest->getVal( 'from' ),
  2495. $wgRequest->getText( 'summary' ),
  2496. $wgRequest->getVal( 'token' ),
  2497. $wgRequest->getBool( 'bot' ),
  2498. $details
  2499. );
  2500. if( in_array( array( 'actionthrottledtext' ), $result ) ) {
  2501. $wgOut->rateLimited();
  2502. return;
  2503. }
  2504. if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
  2505. $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
  2506. $errArray = $result[0];
  2507. $errMsg = array_shift( $errArray );
  2508. $wgOut->addWikiMsgArray( $errMsg, $errArray );
  2509. if( isset( $details['current'] ) ){
  2510. $current = $details['current'];
  2511. if( $current->getComment() != '' ) {
  2512. $wgOut->addWikiMsgArray( 'editcomment', array(
  2513. $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
  2514. }
  2515. }
  2516. return;
  2517. }
  2518. # Display permissions errors before read-only message -- there's no
  2519. # point in misleading the user into thinking the inability to rollback
  2520. # is only temporary.
  2521. if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
  2522. # array_diff is completely broken for arrays of arrays, sigh. Re-
  2523. # move any 'readonlytext' error manually.
  2524. $out = array();
  2525. foreach( $result as $error ) {
  2526. if( $error != array( 'readonlytext' ) ) {
  2527. $out []= $error;
  2528. }
  2529. }
  2530. $wgOut->showPermissionsErrorPage( $out );
  2531. return;
  2532. }
  2533. if( $result == array( array( 'readonlytext' ) ) ) {
  2534. $wgOut->readOnlyPage();
  2535. return;
  2536. }
  2537. $current = $details['current'];
  2538. $target = $details['target'];
  2539. $newId = $details['newid'];
  2540. $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
  2541. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  2542. $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
  2543. . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
  2544. $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
  2545. . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
  2546. $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
  2547. $wgOut->returnToMain( false, $this->mTitle );
  2548. if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
  2549. $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
  2550. $de->showDiff( '', '' );
  2551. }
  2552. }
  2553. /**
  2554. * Do standard deferred updates after page view
  2555. */
  2556. public function viewUpdates() {
  2557. global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
  2558. # Don't update page view counters on views from bot users (bug 14044)
  2559. if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
  2560. Article::incViewCount( $this->getID() );
  2561. $u = new SiteStatsUpdate( 1, 0, 0 );
  2562. array_push( $wgDeferredUpdateList, $u );
  2563. }
  2564. # Update newtalk / watchlist notification status
  2565. $wgUser->clearNotification( $this->mTitle );
  2566. }
  2567. /**
  2568. * Prepare text which is about to be saved.
  2569. * Returns a stdclass with source, pst and output members
  2570. */
  2571. public function prepareTextForEdit( $text, $revid=null ) {
  2572. if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
  2573. // Already prepared
  2574. return $this->mPreparedEdit;
  2575. }
  2576. global $wgParser;
  2577. $edit = (object)array();
  2578. $edit->revid = $revid;
  2579. $edit->newText = $text;
  2580. $edit->pst = $this->preSaveTransform( $text );
  2581. $options = new ParserOptions;
  2582. $options->setTidy( true );
  2583. $options->enableLimitReport();
  2584. $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
  2585. $edit->oldText = $this->getContent();
  2586. $this->mPreparedEdit = $edit;
  2587. return $edit;
  2588. }
  2589. /**
  2590. * Do standard deferred updates after page edit.
  2591. * Update links tables, site stats, search index and message cache.
  2592. * Purges pages that include this page if the text was changed here.
  2593. * Every 100th edit, prune the recent changes table.
  2594. *
  2595. * @private
  2596. * @param $text New text of the article
  2597. * @param $summary Edit summary
  2598. * @param $minoredit Minor edit
  2599. * @param $timestamp_of_pagechange Timestamp associated with the page change
  2600. * @param $newid rev_id value of the new revision
  2601. * @param $changed Whether or not the content actually changed
  2602. */
  2603. public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
  2604. global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
  2605. wfProfileIn( __METHOD__ );
  2606. # Parse the text
  2607. # Be careful not to double-PST: $text is usually already PST-ed once
  2608. if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
  2609. wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
  2610. $editInfo = $this->prepareTextForEdit( $text, $newid );
  2611. } else {
  2612. wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
  2613. $editInfo = $this->mPreparedEdit;
  2614. }
  2615. # Save it to the parser cache
  2616. if( $wgEnableParserCache ) {
  2617. $popts = new ParserOptions;
  2618. $popts->setTidy( true );
  2619. $popts->enableLimitReport();
  2620. $parserCache = ParserCache::singleton();
  2621. $parserCache->save( $editInfo->output, $this, $popts );
  2622. }
  2623. # Update the links tables
  2624. $u = new LinksUpdate( $this->mTitle, $editInfo->output );
  2625. $u->doUpdate();
  2626. wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
  2627. if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
  2628. if( 0 == mt_rand( 0, 99 ) ) {
  2629. // Flush old entries from the `recentchanges` table; we do this on
  2630. // random requests so as to avoid an increase in writes for no good reason
  2631. global $wgRCMaxAge;
  2632. $dbw = wfGetDB( DB_MASTER );
  2633. $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
  2634. $recentchanges = $dbw->tableName( 'recentchanges' );
  2635. $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
  2636. $dbw->query( $sql );
  2637. }
  2638. }
  2639. $id = $this->getID();
  2640. $title = $this->mTitle->getPrefixedDBkey();
  2641. $shortTitle = $this->mTitle->getDBkey();
  2642. if( 0 == $id ) {
  2643. wfProfileOut( __METHOD__ );
  2644. return;
  2645. }
  2646. $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
  2647. array_push( $wgDeferredUpdateList, $u );
  2648. $u = new SearchUpdate( $id, $title, $text );
  2649. array_push( $wgDeferredUpdateList, $u );
  2650. # If this is another user's talk page, update newtalk
  2651. # Don't do this if $changed = false otherwise some idiot can null-edit a
  2652. # load of user talk pages and piss people off, nor if it's a minor edit
  2653. # by a properly-flagged bot.
  2654. if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
  2655. && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
  2656. if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
  2657. $other = User::newFromName( $shortTitle, false );
  2658. if( !$other ) {
  2659. wfDebug( __METHOD__.": invalid username\n" );
  2660. } elseif( User::isIP( $shortTitle ) ) {
  2661. // An anonymous user
  2662. $other->setNewtalk( true );
  2663. } elseif( $other->isLoggedIn() ) {
  2664. $other->setNewtalk( true );
  2665. } else {
  2666. wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
  2667. }
  2668. }
  2669. }
  2670. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
  2671. $wgMessageCache->replace( $shortTitle, $text );
  2672. }
  2673. wfProfileOut( __METHOD__ );
  2674. }
  2675. /**
  2676. * Perform article updates on a special page creation.
  2677. *
  2678. * @param $rev Revision object
  2679. *
  2680. * @todo This is a shitty interface function. Kill it and replace the
  2681. * other shitty functions like editUpdates and such so it's not needed
  2682. * anymore.
  2683. */
  2684. public function createUpdates( $rev ) {
  2685. $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
  2686. $this->mTotalAdjustment = 1;
  2687. $this->editUpdates( $rev->getText(), $rev->getComment(),
  2688. $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
  2689. }
  2690. /**
  2691. * Generate the navigation links when browsing through an article revisions
  2692. * It shows the information as:
  2693. * Revision as of \<date\>; view current revision
  2694. * \<- Previous version | Next Version -\>
  2695. *
  2696. * @param $oldid String: revision ID of this article revision
  2697. */
  2698. public function setOldSubtitle( $oldid = 0 ) {
  2699. global $wgLang, $wgOut, $wgUser, $wgRequest;
  2700. if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
  2701. return;
  2702. }
  2703. $revision = Revision::newFromId( $oldid );
  2704. $current = ( $oldid == $this->mLatest );
  2705. $td = $wgLang->timeanddate( $this->mTimestamp, true );
  2706. $sk = $wgUser->getSkin();
  2707. $lnk = $current
  2708. ? wfMsgHtml( 'currentrevisionlink' )
  2709. : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'currentrevisionlink' ) );
  2710. $curdiff = $current
  2711. ? wfMsgHtml( 'diff' )
  2712. : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
  2713. $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
  2714. $prevlink = $prev
  2715. ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
  2716. : wfMsgHtml( 'previousrevision' );
  2717. $prevdiff = $prev
  2718. ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
  2719. : wfMsgHtml( 'diff' );
  2720. $nextlink = $current
  2721. ? wfMsgHtml( 'nextrevision' )
  2722. : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
  2723. $nextdiff = $current
  2724. ? wfMsgHtml( 'diff' )
  2725. : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
  2726. $cdel='';
  2727. if( $wgUser->isAllowed( 'deleterevision' ) ) {
  2728. $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
  2729. if( $revision->isCurrent() ) {
  2730. // We don't handle top deleted edits too well
  2731. $cdel = wfMsgHtml( 'rev-delundel' );
  2732. } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
  2733. // If revision was hidden from sysops
  2734. $cdel = wfMsgHtml( 'rev-delundel' );
  2735. } else {
  2736. $cdel = $sk->makeKnownLinkObj( $revdel,
  2737. wfMsgHtml('rev-delundel'),
  2738. 'target=' . urlencode( $this->mTitle->getPrefixedDbkey() ) .
  2739. '&oldid=' . urlencode( $oldid ) );
  2740. // Bolden oversighted content
  2741. if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
  2742. $cdel = "<strong>$cdel</strong>";
  2743. }
  2744. $cdel = "(<small>$cdel</small>) ";
  2745. }
  2746. $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
  2747. # Show user links if allowed to see them. If hidden, then show them only if requested...
  2748. $userlinks = $sk->revUserTools( $revision, !$unhide );
  2749. $m = wfMsg( 'revision-info-current' );
  2750. $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
  2751. ? 'revision-info-current'
  2752. : 'revision-info';
  2753. $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ),
  2754. $td, $userlinks, $revision->getID() ) . "</div>\n" .
  2755. "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
  2756. $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
  2757. $wgOut->setSubtitle( $r );
  2758. }
  2759. /**
  2760. * This function is called right before saving the wikitext,
  2761. * so we can do things like signatures and links-in-context.
  2762. *
  2763. * @param $text String
  2764. */
  2765. public function preSaveTransform( $text ) {
  2766. global $wgParser, $wgUser;
  2767. return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
  2768. }
  2769. /* Caching functions */
  2770. /**
  2771. * checkLastModified returns true if it has taken care of all
  2772. * output to the client that is necessary for this request.
  2773. * (that is, it has sent a cached version of the page)
  2774. */
  2775. protected function tryFileCache() {
  2776. static $called = false;
  2777. if( $called ) {
  2778. wfDebug( "Article::tryFileCache(): called twice!?\n" );
  2779. return false;
  2780. }
  2781. $called = true;
  2782. if( $this->isFileCacheable() ) {
  2783. $cache = new HTMLFileCache( $this->mTitle );
  2784. if( $cache->isFileCacheGood( $this->mTouched ) ) {
  2785. wfDebug( "Article::tryFileCache(): about to load file\n" );
  2786. $cache->loadFromFileCache();
  2787. return true;
  2788. } else {
  2789. wfDebug( "Article::tryFileCache(): starting buffer\n" );
  2790. ob_start( array(&$cache, 'saveToFileCache' ) );
  2791. }
  2792. } else {
  2793. wfDebug( "Article::tryFileCache(): not cacheable\n" );
  2794. }
  2795. return false;
  2796. }
  2797. /**
  2798. * Check if the page can be cached
  2799. * @return bool
  2800. */
  2801. public function isFileCacheable() {
  2802. $cacheable = false;
  2803. if( HTMLFileCache::useFileCache() ) {
  2804. $cacheable = $this->getID() && !$this->mRedirectedFrom;
  2805. // Extension may have reason to disable file caching on some pages.
  2806. if( $cacheable ) {
  2807. $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
  2808. }
  2809. }
  2810. return $cacheable;
  2811. }
  2812. /**
  2813. * Loads page_touched and returns a value indicating if it should be used
  2814. *
  2815. */
  2816. public function checkTouched() {
  2817. if( !$this->mDataLoaded ) {
  2818. $this->loadPageData();
  2819. }
  2820. return !$this->mIsRedirect;
  2821. }
  2822. /**
  2823. * Get the page_touched field
  2824. */
  2825. public function getTouched() {
  2826. # Ensure that page data has been loaded
  2827. if( !$this->mDataLoaded ) {
  2828. $this->loadPageData();
  2829. }
  2830. return $this->mTouched;
  2831. }
  2832. /**
  2833. * Get the page_latest field
  2834. */
  2835. public function getLatest() {
  2836. if( !$this->mDataLoaded ) {
  2837. $this->loadPageData();
  2838. }
  2839. return (int)$this->mLatest;
  2840. }
  2841. /**
  2842. * Edit an article without doing all that other stuff
  2843. * The article must already exist; link tables etc
  2844. * are not updated, caches are not flushed.
  2845. *
  2846. * @param $text String: text submitted
  2847. * @param $comment String: comment submitted
  2848. * @param $minor Boolean: whereas it's a minor modification
  2849. */
  2850. public function quickEdit( $text, $comment = '', $minor = 0 ) {
  2851. wfProfileIn( __METHOD__ );
  2852. $dbw = wfGetDB( DB_MASTER );
  2853. $revision = new Revision( array(
  2854. 'page' => $this->getId(),
  2855. 'text' => $text,
  2856. 'comment' => $comment,
  2857. 'minor_edit' => $minor ? 1 : 0,
  2858. ) );
  2859. $revision->insertOn( $dbw );
  2860. $this->updateRevisionOn( $dbw, $revision );
  2861. wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
  2862. wfProfileOut( __METHOD__ );
  2863. }
  2864. /**
  2865. * Used to increment the view counter
  2866. *
  2867. * @param $id Integer: article id
  2868. */
  2869. public static function incViewCount( $id ) {
  2870. $id = intval( $id );
  2871. global $wgHitcounterUpdateFreq, $wgDBtype;
  2872. $dbw = wfGetDB( DB_MASTER );
  2873. $pageTable = $dbw->tableName( 'page' );
  2874. $hitcounterTable = $dbw->tableName( 'hitcounter' );
  2875. $acchitsTable = $dbw->tableName( 'acchits' );
  2876. if( $wgHitcounterUpdateFreq <= 1 ) {
  2877. $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
  2878. return;
  2879. }
  2880. # Not important enough to warrant an error page in case of failure
  2881. $oldignore = $dbw->ignoreErrors( true );
  2882. $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
  2883. $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
  2884. if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
  2885. # Most of the time (or on SQL errors), skip row count check
  2886. $dbw->ignoreErrors( $oldignore );
  2887. return;
  2888. }
  2889. $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
  2890. $row = $dbw->fetchObject( $res );
  2891. $rown = intval( $row->n );
  2892. if( $rown >= $wgHitcounterUpdateFreq ){
  2893. wfProfileIn( 'Article::incViewCount-collect' );
  2894. $old_user_abort = ignore_user_abort( true );
  2895. if($wgDBtype == 'mysql')
  2896. $dbw->query("LOCK TABLES $hitcounterTable WRITE");
  2897. $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
  2898. $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
  2899. "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
  2900. 'GROUP BY hc_id');
  2901. $dbw->query("DELETE FROM $hitcounterTable");
  2902. if($wgDBtype == 'mysql') {
  2903. $dbw->query('UNLOCK TABLES');
  2904. $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
  2905. 'WHERE page_id = hc_id');
  2906. }
  2907. else {
  2908. $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
  2909. "FROM $acchitsTable WHERE page_id = hc_id");
  2910. }
  2911. $dbw->query("DROP TABLE $acchitsTable");
  2912. ignore_user_abort( $old_user_abort );
  2913. wfProfileOut( 'Article::incViewCount-collect' );
  2914. }
  2915. $dbw->ignoreErrors( $oldignore );
  2916. }
  2917. /**#@+
  2918. * The onArticle*() functions are supposed to be a kind of hooks
  2919. * which should be called whenever any of the specified actions
  2920. * are done.
  2921. *
  2922. * This is a good place to put code to clear caches, for instance.
  2923. *
  2924. * This is called on page move and undelete, as well as edit
  2925. *
  2926. * @param $title a title object
  2927. */
  2928. public static function onArticleCreate( $title ) {
  2929. # Update existence markers on article/talk tabs...
  2930. if( $title->isTalkPage() ) {
  2931. $other = $title->getSubjectPage();
  2932. } else {
  2933. $other = $title->getTalkPage();
  2934. }
  2935. $other->invalidateCache();
  2936. $other->purgeSquid();
  2937. $title->touchLinks();
  2938. $title->purgeSquid();
  2939. $title->deleteTitleProtection();
  2940. }
  2941. public static function onArticleDelete( $title ) {
  2942. global $wgMessageCache;
  2943. # Update existence markers on article/talk tabs...
  2944. if( $title->isTalkPage() ) {
  2945. $other = $title->getSubjectPage();
  2946. } else {
  2947. $other = $title->getTalkPage();
  2948. }
  2949. $other->invalidateCache();
  2950. $other->purgeSquid();
  2951. $title->touchLinks();
  2952. $title->purgeSquid();
  2953. # File cache
  2954. HTMLFileCache::clearFileCache( $title );
  2955. # Messages
  2956. if( $title->getNamespace() == NS_MEDIAWIKI ) {
  2957. $wgMessageCache->replace( $title->getDBkey(), false );
  2958. }
  2959. # Images
  2960. if( $title->getNamespace() == NS_FILE ) {
  2961. $update = new HTMLCacheUpdate( $title, 'imagelinks' );
  2962. $update->doUpdate();
  2963. }
  2964. # User talk pages
  2965. if( $title->getNamespace() == NS_USER_TALK ) {
  2966. $user = User::newFromName( $title->getText(), false );
  2967. $user->setNewtalk( false );
  2968. }
  2969. # Image redirects
  2970. RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
  2971. }
  2972. /**
  2973. * Purge caches on page update etc
  2974. */
  2975. public static function onArticleEdit( $title, $flags = '' ) {
  2976. global $wgDeferredUpdateList;
  2977. // Invalidate caches of articles which include this page
  2978. $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
  2979. // Invalidate the caches of all pages which redirect here
  2980. $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
  2981. # Purge squid for this page only
  2982. $title->purgeSquid();
  2983. # Clear file cache for this page only
  2984. HTMLFileCache::clearFileCache( $title );
  2985. }
  2986. /**#@-*/
  2987. /**
  2988. * Overriden by ImagePage class, only present here to avoid a fatal error
  2989. * Called for ?action=revert
  2990. */
  2991. public function revert() {
  2992. global $wgOut;
  2993. $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
  2994. }
  2995. /**
  2996. * Info about this page
  2997. * Called for ?action=info when $wgAllowPageInfo is on.
  2998. */
  2999. public function info() {
  3000. global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
  3001. if( !$wgAllowPageInfo ) {
  3002. $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
  3003. return;
  3004. }
  3005. $page = $this->mTitle->getSubjectPage();
  3006. $wgOut->setPagetitle( $page->getPrefixedText() );
  3007. $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
  3008. $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
  3009. if( !$this->mTitle->exists() ) {
  3010. $wgOut->addHTML( '<div class="noarticletext">' );
  3011. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
  3012. // This doesn't quite make sense; the user is asking for
  3013. // information about the _page_, not the message... -- RC
  3014. $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
  3015. } else {
  3016. $msg = $wgUser->isLoggedIn()
  3017. ? 'noarticletext'
  3018. : 'noarticletextanon';
  3019. $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
  3020. }
  3021. $wgOut->addHTML( '</div>' );
  3022. } else {
  3023. $dbr = wfGetDB( DB_SLAVE );
  3024. $wl_clause = array(
  3025. 'wl_title' => $page->getDBkey(),
  3026. 'wl_namespace' => $page->getNamespace() );
  3027. $numwatchers = $dbr->selectField(
  3028. 'watchlist',
  3029. 'COUNT(*)',
  3030. $wl_clause,
  3031. __METHOD__,
  3032. $this->getSelectOptions() );
  3033. $pageInfo = $this->pageCountInfo( $page );
  3034. $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
  3035. $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
  3036. $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
  3037. if( $talkInfo ) {
  3038. $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
  3039. }
  3040. $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
  3041. if( $talkInfo ) {
  3042. $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
  3043. }
  3044. $wgOut->addHTML( '</ul>' );
  3045. }
  3046. }
  3047. /**
  3048. * Return the total number of edits and number of unique editors
  3049. * on a given page. If page does not exist, returns false.
  3050. *
  3051. * @param $title Title object
  3052. * @return array
  3053. */
  3054. protected function pageCountInfo( $title ) {
  3055. $id = $title->getArticleId();
  3056. if( $id == 0 ) {
  3057. return false;
  3058. }
  3059. $dbr = wfGetDB( DB_SLAVE );
  3060. $rev_clause = array( 'rev_page' => $id );
  3061. $edits = $dbr->selectField(
  3062. 'revision',
  3063. 'COUNT(rev_page)',
  3064. $rev_clause,
  3065. __METHOD__,
  3066. $this->getSelectOptions()
  3067. );
  3068. $authors = $dbr->selectField(
  3069. 'revision',
  3070. 'COUNT(DISTINCT rev_user_text)',
  3071. $rev_clause,
  3072. __METHOD__,
  3073. $this->getSelectOptions()
  3074. );
  3075. return array( 'edits' => $edits, 'authors' => $authors );
  3076. }
  3077. /**
  3078. * Return a list of templates used by this article.
  3079. * Uses the templatelinks table
  3080. *
  3081. * @return Array of Title objects
  3082. */
  3083. public function getUsedTemplates() {
  3084. $result = array();
  3085. $id = $this->mTitle->getArticleID();
  3086. if( $id == 0 ) {
  3087. return array();
  3088. }
  3089. $dbr = wfGetDB( DB_SLAVE );
  3090. $res = $dbr->select( array( 'templatelinks' ),
  3091. array( 'tl_namespace', 'tl_title' ),
  3092. array( 'tl_from' => $id ),
  3093. __METHOD__ );
  3094. if( $res !== false ) {
  3095. foreach( $res as $row ) {
  3096. $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
  3097. }
  3098. }
  3099. $dbr->freeResult( $res );
  3100. return $result;
  3101. }
  3102. /**
  3103. * Returns a list of hidden categories this page is a member of.
  3104. * Uses the page_props and categorylinks tables.
  3105. *
  3106. * @return Array of Title objects
  3107. */
  3108. public function getHiddenCategories() {
  3109. $result = array();
  3110. $id = $this->mTitle->getArticleID();
  3111. if( $id == 0 ) {
  3112. return array();
  3113. }
  3114. $dbr = wfGetDB( DB_SLAVE );
  3115. $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
  3116. array( 'cl_to' ),
  3117. array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
  3118. 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
  3119. __METHOD__ );
  3120. if( $res !== false ) {
  3121. foreach( $res as $row ) {
  3122. $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
  3123. }
  3124. }
  3125. $dbr->freeResult( $res );
  3126. return $result;
  3127. }
  3128. /**
  3129. * Return an applicable autosummary if one exists for the given edit.
  3130. * @param $oldtext String: the previous text of the page.
  3131. * @param $newtext String: The submitted text of the page.
  3132. * @param $flags Bitmask: a bitmask of flags submitted for the edit.
  3133. * @return string An appropriate autosummary, or an empty string.
  3134. */
  3135. public static function getAutosummary( $oldtext, $newtext, $flags ) {
  3136. # Decide what kind of autosummary is needed.
  3137. # Redirect autosummaries
  3138. $ot = Title::newFromRedirect( $oldtext );
  3139. $rt = Title::newFromRedirect( $newtext );
  3140. if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
  3141. return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
  3142. }
  3143. # New page autosummaries
  3144. if( $flags & EDIT_NEW && strlen( $newtext ) ) {
  3145. # If they're making a new article, give its text, truncated, in the summary.
  3146. global $wgContLang;
  3147. $truncatedtext = $wgContLang->truncate(
  3148. str_replace("\n", ' ', $newtext),
  3149. max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
  3150. return wfMsgForContent( 'autosumm-new', $truncatedtext );
  3151. }
  3152. # Blanking autosummaries
  3153. if( $oldtext != '' && $newtext == '' ) {
  3154. return wfMsgForContent( 'autosumm-blank' );
  3155. } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
  3156. # Removing more than 90% of the article
  3157. global $wgContLang;
  3158. $truncatedtext = $wgContLang->truncate(
  3159. $newtext,
  3160. max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
  3161. return wfMsgForContent( 'autosumm-replace', $truncatedtext );
  3162. }
  3163. # If we reach this point, there's no applicable autosummary for our case, so our
  3164. # autosummary is empty.
  3165. return '';
  3166. }
  3167. /**
  3168. * Add the primary page-view wikitext to the output buffer
  3169. * Saves the text into the parser cache if possible.
  3170. * Updates templatelinks if it is out of date.
  3171. *
  3172. * @param $text String
  3173. * @param $cache Boolean
  3174. */
  3175. public function outputWikiText( $text, $cache = true ) {
  3176. global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
  3177. $popts = $wgOut->parserOptions();
  3178. $popts->setTidy(true);
  3179. $popts->enableLimitReport();
  3180. $parserOutput = $wgParser->parse( $text, $this->mTitle,
  3181. $popts, true, true, $this->getRevIdFetched() );
  3182. $popts->setTidy(false);
  3183. $popts->enableLimitReport( false );
  3184. if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
  3185. $parserCache = ParserCache::singleton();
  3186. $parserCache->save( $parserOutput, $this, $popts );
  3187. }
  3188. // Make sure file cache is not used on uncacheable content.
  3189. // Output that has magic words in it can still use the parser cache
  3190. // (if enabled), though it will generally expire sooner.
  3191. if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
  3192. $wgUseFileCache = false;
  3193. }
  3194. if( $this->isCurrent() && !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
  3195. // templatelinks table may have become out of sync,
  3196. // especially if using variable-based transclusions.
  3197. // For paranoia, check if things have changed and if
  3198. // so apply updates to the database. This will ensure
  3199. // that cascaded protections apply as soon as the changes
  3200. // are visible.
  3201. # Get templates from templatelinks
  3202. $id = $this->mTitle->getArticleID();
  3203. $tlTemplates = array();
  3204. $dbr = wfGetDB( DB_SLAVE );
  3205. $res = $dbr->select( array( 'templatelinks' ),
  3206. array( 'tl_namespace', 'tl_title' ),
  3207. array( 'tl_from' => $id ),
  3208. __METHOD__ );
  3209. global $wgContLang;
  3210. foreach( $res as $row ) {
  3211. $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
  3212. }
  3213. # Get templates from parser output.
  3214. $poTemplates = array();
  3215. foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
  3216. foreach ( $templates as $dbk => $id ) {
  3217. $key = $row->tl_namespace . ':'. $row->tl_title;
  3218. $poTemplates["$ns:$dbk"] = true;
  3219. }
  3220. }
  3221. # Get the diff
  3222. # Note that we simulate array_diff_key in PHP <5.0.x
  3223. $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
  3224. if( count( $templates_diff ) > 0 ) {
  3225. # Whee, link updates time.
  3226. $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
  3227. $u->doUpdate();
  3228. }
  3229. }
  3230. $wgOut->addParserOutput( $parserOutput );
  3231. }
  3232. /**
  3233. * Update all the appropriate counts in the category table, given that
  3234. * we've added the categories $added and deleted the categories $deleted.
  3235. *
  3236. * @param $added array The names of categories that were added
  3237. * @param $deleted array The names of categories that were deleted
  3238. * @return null
  3239. */
  3240. public function updateCategoryCounts( $added, $deleted ) {
  3241. $ns = $this->mTitle->getNamespace();
  3242. $dbw = wfGetDB( DB_MASTER );
  3243. # First make sure the rows exist. If one of the "deleted" ones didn't
  3244. # exist, we might legitimately not create it, but it's simpler to just
  3245. # create it and then give it a negative value, since the value is bogus
  3246. # anyway.
  3247. #
  3248. # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
  3249. $insertCats = array_merge( $added, $deleted );
  3250. if( !$insertCats ) {
  3251. # Okay, nothing to do
  3252. return;
  3253. }
  3254. $insertRows = array();
  3255. foreach( $insertCats as $cat ) {
  3256. $insertRows[] = array( 'cat_title' => $cat );
  3257. }
  3258. $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
  3259. $addFields = array( 'cat_pages = cat_pages + 1' );
  3260. $removeFields = array( 'cat_pages = cat_pages - 1' );
  3261. if( $ns == NS_CATEGORY ) {
  3262. $addFields[] = 'cat_subcats = cat_subcats + 1';
  3263. $removeFields[] = 'cat_subcats = cat_subcats - 1';
  3264. } elseif( $ns == NS_FILE ) {
  3265. $addFields[] = 'cat_files = cat_files + 1';
  3266. $removeFields[] = 'cat_files = cat_files - 1';
  3267. }
  3268. if( $added ) {
  3269. $dbw->update(
  3270. 'category',
  3271. $addFields,
  3272. array( 'cat_title' => $added ),
  3273. __METHOD__
  3274. );
  3275. }
  3276. if( $deleted ) {
  3277. $dbw->update(
  3278. 'category',
  3279. $removeFields,
  3280. array( 'cat_title' => $deleted ),
  3281. __METHOD__
  3282. );
  3283. }
  3284. }
  3285. }