EditPage.php 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622
  1. <?php
  2. /**
  3. * User interface for page editing.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\EditPage\TextboxBuilder;
  23. use MediaWiki\EditPage\TextConflictHelper;
  24. use MediaWiki\Logger\LoggerFactory;
  25. use MediaWiki\MediaWikiServices;
  26. use Wikimedia\ScopedCallback;
  27. /**
  28. * The edit page/HTML interface (split from Article)
  29. * The actual database and text munging is still in Article,
  30. * but it should get easier to call those from alternate
  31. * interfaces.
  32. *
  33. * EditPage cares about two distinct titles:
  34. * $this->mContextTitle is the page that forms submit to, links point to,
  35. * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
  36. * page in the database that is actually being edited. These are
  37. * usually the same, but they are now allowed to be different.
  38. *
  39. * Surgeon General's Warning: prolonged exposure to this class is known to cause
  40. * headaches, which may be fatal.
  41. */
  42. class EditPage {
  43. /**
  44. * Used for Unicode support checks
  45. */
  46. const UNICODE_CHECK = 'ℳ𝒲♥𝓊𝓃𝒾𝒸ℴ𝒹ℯ';
  47. /**
  48. * Status: Article successfully updated
  49. */
  50. const AS_SUCCESS_UPDATE = 200;
  51. /**
  52. * Status: Article successfully created
  53. */
  54. const AS_SUCCESS_NEW_ARTICLE = 201;
  55. /**
  56. * Status: Article update aborted by a hook function
  57. */
  58. const AS_HOOK_ERROR = 210;
  59. /**
  60. * Status: A hook function returned an error
  61. */
  62. const AS_HOOK_ERROR_EXPECTED = 212;
  63. /**
  64. * Status: User is blocked from editing this page
  65. */
  66. const AS_BLOCKED_PAGE_FOR_USER = 215;
  67. /**
  68. * Status: Content too big (> $wgMaxArticleSize)
  69. */
  70. const AS_CONTENT_TOO_BIG = 216;
  71. /**
  72. * Status: this anonymous user is not allowed to edit this page
  73. */
  74. const AS_READ_ONLY_PAGE_ANON = 218;
  75. /**
  76. * Status: this logged in user is not allowed to edit this page
  77. */
  78. const AS_READ_ONLY_PAGE_LOGGED = 219;
  79. /**
  80. * Status: wiki is in readonly mode (wfReadOnly() == true)
  81. */
  82. const AS_READ_ONLY_PAGE = 220;
  83. /**
  84. * Status: rate limiter for action 'edit' was tripped
  85. */
  86. const AS_RATE_LIMITED = 221;
  87. /**
  88. * Status: article was deleted while editing and param wpRecreate == false or form
  89. * was not posted
  90. */
  91. const AS_ARTICLE_WAS_DELETED = 222;
  92. /**
  93. * Status: user tried to create this page, but is not allowed to do that
  94. * ( Title->userCan('create') == false )
  95. */
  96. const AS_NO_CREATE_PERMISSION = 223;
  97. /**
  98. * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
  99. */
  100. const AS_BLANK_ARTICLE = 224;
  101. /**
  102. * Status: (non-resolvable) edit conflict
  103. */
  104. const AS_CONFLICT_DETECTED = 225;
  105. /**
  106. * Status: no edit summary given and the user has forceeditsummary set and the user is not
  107. * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
  108. */
  109. const AS_SUMMARY_NEEDED = 226;
  110. /**
  111. * Status: user tried to create a new section without content
  112. */
  113. const AS_TEXTBOX_EMPTY = 228;
  114. /**
  115. * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
  116. */
  117. const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
  118. /**
  119. * Status: WikiPage::doEdit() was unsuccessful
  120. */
  121. const AS_END = 231;
  122. /**
  123. * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
  124. */
  125. const AS_SPAM_ERROR = 232;
  126. /**
  127. * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
  128. */
  129. const AS_IMAGE_REDIRECT_ANON = 233;
  130. /**
  131. * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
  132. */
  133. const AS_IMAGE_REDIRECT_LOGGED = 234;
  134. /**
  135. * Status: user tried to modify the content model, but is not allowed to do that
  136. * ( User::isAllowed('editcontentmodel') == false )
  137. */
  138. const AS_NO_CHANGE_CONTENT_MODEL = 235;
  139. /**
  140. * Status: user tried to create self-redirect (redirect to the same article) and
  141. * wpIgnoreSelfRedirect == false
  142. */
  143. const AS_SELF_REDIRECT = 236;
  144. /**
  145. * Status: an error relating to change tagging. Look at the message key for
  146. * more details
  147. */
  148. const AS_CHANGE_TAG_ERROR = 237;
  149. /**
  150. * Status: can't parse content
  151. */
  152. const AS_PARSE_ERROR = 240;
  153. /**
  154. * Status: when changing the content model is disallowed due to
  155. * $wgContentHandlerUseDB being false
  156. */
  157. const AS_CANNOT_USE_CUSTOM_MODEL = 241;
  158. /**
  159. * Status: edit rejected because browser doesn't support Unicode.
  160. */
  161. const AS_UNICODE_NOT_SUPPORTED = 242;
  162. /**
  163. * HTML id and name for the beginning of the edit form.
  164. */
  165. const EDITFORM_ID = 'editform';
  166. /**
  167. * Prefix of key for cookie used to pass post-edit state.
  168. * The revision id edited is added after this
  169. */
  170. const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
  171. /**
  172. * Duration of PostEdit cookie, in seconds.
  173. * The cookie will be removed instantly if the JavaScript runs.
  174. *
  175. * Otherwise, though, we don't want the cookies to accumulate.
  176. * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
  177. * limit of only 20 cookies per domain. This still applies at least to some
  178. * versions of IE without full updates:
  179. * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
  180. *
  181. * A value of 20 minutes should be enough to take into account slow loads and minor
  182. * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
  183. */
  184. const POST_EDIT_COOKIE_DURATION = 1200;
  185. /**
  186. * @deprecated for public usage since 1.30 use EditPage::getArticle()
  187. * @var Article
  188. */
  189. public $mArticle;
  190. /** @var WikiPage */
  191. private $page;
  192. /**
  193. * @deprecated for public usage since 1.30 use EditPage::getTitle()
  194. * @var Title
  195. */
  196. public $mTitle;
  197. /** @var null|Title */
  198. private $mContextTitle = null;
  199. /** @var string */
  200. public $action = 'submit';
  201. /** @var bool */
  202. public $isConflict = false;
  203. /** @var bool New page or new section */
  204. public $isNew = false;
  205. /** @var bool */
  206. public $deletedSinceEdit;
  207. /** @var string */
  208. public $formtype;
  209. /** @var bool */
  210. public $firsttime;
  211. /** @var bool|stdClass */
  212. public $lastDelete;
  213. /** @var bool */
  214. public $mTokenOk = false;
  215. /** @var bool */
  216. public $mTokenOkExceptSuffix = false;
  217. /** @var bool */
  218. public $mTriedSave = false;
  219. /** @var bool */
  220. public $incompleteForm = false;
  221. /** @var bool */
  222. public $tooBig = false;
  223. /** @var bool */
  224. public $missingComment = false;
  225. /** @var bool */
  226. public $missingSummary = false;
  227. /** @var bool */
  228. public $allowBlankSummary = false;
  229. /** @var bool */
  230. protected $blankArticle = false;
  231. /** @var bool */
  232. protected $allowBlankArticle = false;
  233. /** @var bool */
  234. protected $selfRedirect = false;
  235. /** @var bool */
  236. protected $allowSelfRedirect = false;
  237. /** @var string */
  238. public $autoSumm = '';
  239. /** @var string */
  240. public $hookError = '';
  241. /** @var ParserOutput */
  242. public $mParserOutput;
  243. /** @var bool Has a summary been preset using GET parameter &summary= ? */
  244. public $hasPresetSummary = false;
  245. /** @var Revision|bool|null */
  246. public $mBaseRevision = false;
  247. /** @var bool */
  248. public $mShowSummaryField = true;
  249. # Form values
  250. /** @var bool */
  251. public $save = false;
  252. /** @var bool */
  253. public $preview = false;
  254. /** @var bool */
  255. public $diff = false;
  256. /** @var bool */
  257. public $minoredit = false;
  258. /** @var bool */
  259. public $watchthis = false;
  260. /** @var bool */
  261. public $recreate = false;
  262. /** @var string */
  263. public $textbox1 = '';
  264. /** @var string */
  265. public $textbox2 = '';
  266. /** @var string */
  267. public $summary = '';
  268. /** @var bool */
  269. public $nosummary = false;
  270. /** @var string */
  271. public $edittime = '';
  272. /** @var int */
  273. private $editRevId = null;
  274. /** @var string */
  275. public $section = '';
  276. /** @var string */
  277. public $sectiontitle = '';
  278. /** @var string */
  279. public $starttime = '';
  280. /** @var int */
  281. public $oldid = 0;
  282. /** @var int */
  283. public $parentRevId = 0;
  284. /** @var string */
  285. public $editintro = '';
  286. /** @var null */
  287. public $scrolltop = null;
  288. /** @var bool */
  289. public $bot = true;
  290. /** @var string */
  291. public $contentModel;
  292. /** @var null|string */
  293. public $contentFormat = null;
  294. /** @var null|array */
  295. private $changeTags = null;
  296. # Placeholders for text injection by hooks (must be HTML)
  297. # extensions should take care to _append_ to the present value
  298. /** @var string Before even the preview */
  299. public $editFormPageTop = '';
  300. public $editFormTextTop = '';
  301. public $editFormTextBeforeContent = '';
  302. public $editFormTextAfterWarn = '';
  303. public $editFormTextAfterTools = '';
  304. public $editFormTextBottom = '';
  305. public $editFormTextAfterContent = '';
  306. public $previewTextAfterContent = '';
  307. public $mPreloadContent = null;
  308. /* $didSave should be set to true whenever an article was successfully altered. */
  309. public $didSave = false;
  310. public $undidRev = 0;
  311. public $suppressIntro = false;
  312. /** @var bool */
  313. protected $edit;
  314. /** @var bool|int */
  315. protected $contentLength = false;
  316. /**
  317. * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
  318. */
  319. private $enableApiEditOverride = false;
  320. /**
  321. * @var IContextSource
  322. */
  323. protected $context;
  324. /**
  325. * @var bool Whether an old revision is edited
  326. */
  327. private $isOldRev = false;
  328. /**
  329. * @var string|null What the user submitted in the 'wpUnicodeCheck' field
  330. */
  331. private $unicodeCheck;
  332. /**
  333. * Factory function to create an edit conflict helper
  334. *
  335. * @var callable
  336. */
  337. private $editConflictHelperFactory;
  338. /**
  339. * @var TextConflictHelper|null
  340. */
  341. private $editConflictHelper;
  342. /**
  343. * @param Article $article
  344. */
  345. public function __construct( Article $article ) {
  346. $this->mArticle = $article;
  347. $this->page = $article->getPage(); // model object
  348. $this->mTitle = $article->getTitle();
  349. $this->context = $article->getContext();
  350. $this->contentModel = $this->mTitle->getContentModel();
  351. $handler = ContentHandler::getForModelID( $this->contentModel );
  352. $this->contentFormat = $handler->getDefaultFormat();
  353. $this->editConflictHelperFactory = [ $this, 'newTextConflictHelper' ];
  354. }
  355. /**
  356. * @return Article
  357. */
  358. public function getArticle() {
  359. return $this->mArticle;
  360. }
  361. /**
  362. * @since 1.28
  363. * @return IContextSource
  364. */
  365. public function getContext() {
  366. return $this->context;
  367. }
  368. /**
  369. * @since 1.19
  370. * @return Title
  371. */
  372. public function getTitle() {
  373. return $this->mTitle;
  374. }
  375. /**
  376. * Set the context Title object
  377. *
  378. * @param Title|null $title Title object or null
  379. */
  380. public function setContextTitle( $title ) {
  381. $this->mContextTitle = $title;
  382. }
  383. /**
  384. * Get the context title object.
  385. * If not set, $wgTitle will be returned. This behavior might change in
  386. * the future to return $this->mTitle instead.
  387. *
  388. * @return Title
  389. */
  390. public function getContextTitle() {
  391. if ( is_null( $this->mContextTitle ) ) {
  392. wfDebugLog(
  393. 'GlobalTitleFail',
  394. __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.'
  395. );
  396. global $wgTitle;
  397. return $wgTitle;
  398. } else {
  399. return $this->mContextTitle;
  400. }
  401. }
  402. /**
  403. * Check if the edit page is using OOUI controls
  404. * @return bool Always true
  405. * @deprecated since 1.30
  406. */
  407. public function isOouiEnabled() {
  408. wfDeprecated( __METHOD__, '1.30' );
  409. return true;
  410. }
  411. /**
  412. * Returns if the given content model is editable.
  413. *
  414. * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
  415. * @return bool
  416. * @throws MWException If $modelId has no known handler
  417. */
  418. public function isSupportedContentModel( $modelId ) {
  419. return $this->enableApiEditOverride === true ||
  420. ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
  421. }
  422. /**
  423. * Allow editing of content that supports API direct editing, but not general
  424. * direct editing. Set to false by default.
  425. *
  426. * @param bool $enableOverride
  427. */
  428. public function setApiEditOverride( $enableOverride ) {
  429. $this->enableApiEditOverride = $enableOverride;
  430. }
  431. /**
  432. * @deprecated since 1.29, call edit directly
  433. */
  434. public function submit() {
  435. wfDeprecated( __METHOD__, '1.29' );
  436. $this->edit();
  437. }
  438. /**
  439. * This is the function that gets called for "action=edit". It
  440. * sets up various member variables, then passes execution to
  441. * another function, usually showEditForm()
  442. *
  443. * The edit form is self-submitting, so that when things like
  444. * preview and edit conflicts occur, we get the same form back
  445. * with the extra stuff added. Only when the final submission
  446. * is made and all is well do we actually save and redirect to
  447. * the newly-edited page.
  448. */
  449. public function edit() {
  450. // Allow extensions to modify/prevent this form or submission
  451. if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
  452. return;
  453. }
  454. wfDebug( __METHOD__ . ": enter\n" );
  455. $request = $this->context->getRequest();
  456. // If they used redlink=1 and the page exists, redirect to the main article
  457. if ( $request->getBool( 'redlink' ) && $this->mTitle->exists() ) {
  458. $this->context->getOutput()->redirect( $this->mTitle->getFullURL() );
  459. return;
  460. }
  461. $this->importFormData( $request );
  462. $this->firsttime = false;
  463. if ( wfReadOnly() && $this->save ) {
  464. // Force preview
  465. $this->save = false;
  466. $this->preview = true;
  467. }
  468. if ( $this->save ) {
  469. $this->formtype = 'save';
  470. } elseif ( $this->preview ) {
  471. $this->formtype = 'preview';
  472. } elseif ( $this->diff ) {
  473. $this->formtype = 'diff';
  474. } else { # First time through
  475. $this->firsttime = true;
  476. if ( $this->previewOnOpen() ) {
  477. $this->formtype = 'preview';
  478. } else {
  479. $this->formtype = 'initial';
  480. }
  481. }
  482. $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
  483. if ( $permErrors ) {
  484. wfDebug( __METHOD__ . ": User can't edit\n" );
  485. // Auto-block user's IP if the account was "hard" blocked
  486. if ( !wfReadOnly() ) {
  487. DeferredUpdates::addCallableUpdate( function () {
  488. $this->context->getUser()->spreadAnyEditBlock();
  489. } );
  490. }
  491. $this->displayPermissionsError( $permErrors );
  492. return;
  493. }
  494. $revision = $this->mArticle->getRevisionFetched();
  495. // Disallow editing revisions with content models different from the current one
  496. // Undo edits being an exception in order to allow reverting content model changes.
  497. if ( $revision
  498. && $revision->getContentModel() !== $this->contentModel
  499. ) {
  500. $prevRev = null;
  501. if ( $this->undidRev ) {
  502. $undidRevObj = Revision::newFromId( $this->undidRev );
  503. $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
  504. }
  505. if ( !$this->undidRev
  506. || !$prevRev
  507. || $prevRev->getContentModel() !== $this->contentModel
  508. ) {
  509. $this->displayViewSourcePage(
  510. $this->getContentObject(),
  511. $this->context->msg(
  512. 'contentmodelediterror',
  513. $revision->getContentModel(),
  514. $this->contentModel
  515. )->plain()
  516. );
  517. return;
  518. }
  519. }
  520. $this->isConflict = false;
  521. # Show applicable editing introductions
  522. if ( $this->formtype == 'initial' || $this->firsttime ) {
  523. $this->showIntro();
  524. }
  525. # Attempt submission here. This will check for edit conflicts,
  526. # and redundantly check for locked database, blocked IPs, etc.
  527. # that edit() already checked just in case someone tries to sneak
  528. # in the back door with a hand-edited submission URL.
  529. if ( 'save' == $this->formtype ) {
  530. $resultDetails = null;
  531. $status = $this->attemptSave( $resultDetails );
  532. if ( !$this->handleStatus( $status, $resultDetails ) ) {
  533. return;
  534. }
  535. }
  536. # First time through: get contents, set time for conflict
  537. # checking, etc.
  538. if ( 'initial' == $this->formtype || $this->firsttime ) {
  539. if ( $this->initialiseForm() === false ) {
  540. $this->noSuchSectionPage();
  541. return;
  542. }
  543. if ( !$this->mTitle->getArticleID() ) {
  544. Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
  545. } else {
  546. Hooks::run( 'EditFormInitialText', [ $this ] );
  547. }
  548. }
  549. $this->showEditForm();
  550. }
  551. /**
  552. * @param string $rigor Same format as Title::getUserPermissionErrors()
  553. * @return array
  554. */
  555. protected function getEditPermissionErrors( $rigor = 'secure' ) {
  556. $user = $this->context->getUser();
  557. $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user, $rigor );
  558. # Can this title be created?
  559. if ( !$this->mTitle->exists() ) {
  560. $permErrors = array_merge(
  561. $permErrors,
  562. wfArrayDiff2(
  563. $this->mTitle->getUserPermissionsErrors( 'create', $user, $rigor ),
  564. $permErrors
  565. )
  566. );
  567. }
  568. # Ignore some permissions errors when a user is just previewing/viewing diffs
  569. $remove = [];
  570. foreach ( $permErrors as $error ) {
  571. if ( ( $this->preview || $this->diff )
  572. && (
  573. $error[0] == 'blockedtext' ||
  574. $error[0] == 'autoblockedtext' ||
  575. $error[0] == 'systemblockedtext'
  576. )
  577. ) {
  578. $remove[] = $error;
  579. }
  580. }
  581. $permErrors = wfArrayDiff2( $permErrors, $remove );
  582. return $permErrors;
  583. }
  584. /**
  585. * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
  586. * but with the following differences:
  587. * - If redlink=1, the user will be redirected to the page
  588. * - If there is content to display or the error occurs while either saving,
  589. * previewing or showing the difference, it will be a
  590. * "View source for ..." page displaying the source code after the error message.
  591. *
  592. * @since 1.19
  593. * @param array $permErrors Array of permissions errors, as returned by
  594. * Title::getUserPermissionsErrors().
  595. * @throws PermissionsError
  596. */
  597. protected function displayPermissionsError( array $permErrors ) {
  598. $out = $this->context->getOutput();
  599. if ( $this->context->getRequest()->getBool( 'redlink' ) ) {
  600. // The edit page was reached via a red link.
  601. // Redirect to the article page and let them click the edit tab if
  602. // they really want a permission error.
  603. $out->redirect( $this->mTitle->getFullURL() );
  604. return;
  605. }
  606. $content = $this->getContentObject();
  607. # Use the normal message if there's nothing to display
  608. if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
  609. $action = $this->mTitle->exists() ? 'edit' :
  610. ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
  611. throw new PermissionsError( $action, $permErrors );
  612. }
  613. $this->displayViewSourcePage(
  614. $content,
  615. $out->formatPermissionsErrorMessage( $permErrors, 'edit' )
  616. );
  617. }
  618. /**
  619. * Display a read-only View Source page
  620. * @param Content $content
  621. * @param string $errorMessage additional wikitext error message to display
  622. */
  623. protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
  624. $out = $this->context->getOutput();
  625. Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$out ] );
  626. $out->setRobotPolicy( 'noindex,nofollow' );
  627. $out->setPageTitle( $this->context->msg(
  628. 'viewsource-title',
  629. $this->getContextTitle()->getPrefixedText()
  630. ) );
  631. $out->addBacklinkSubtitle( $this->getContextTitle() );
  632. $out->addHTML( $this->editFormPageTop );
  633. $out->addHTML( $this->editFormTextTop );
  634. if ( $errorMessage !== '' ) {
  635. $out->addWikiText( $errorMessage );
  636. $out->addHTML( "<hr />\n" );
  637. }
  638. # If the user made changes, preserve them when showing the markup
  639. # (This happens when a user is blocked during edit, for instance)
  640. if ( !$this->firsttime ) {
  641. $text = $this->textbox1;
  642. $out->addWikiMsg( 'viewyourtext' );
  643. } else {
  644. try {
  645. $text = $this->toEditText( $content );
  646. } catch ( MWException $e ) {
  647. # Serialize using the default format if the content model is not supported
  648. # (e.g. for an old revision with a different model)
  649. $text = $content->serialize();
  650. }
  651. $out->addWikiMsg( 'viewsourcetext' );
  652. }
  653. $out->addHTML( $this->editFormTextBeforeContent );
  654. $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
  655. $out->addHTML( $this->editFormTextAfterContent );
  656. $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
  657. $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
  658. $out->addHTML( $this->editFormTextBottom );
  659. if ( $this->mTitle->exists() ) {
  660. $out->returnToMain( null, $this->mTitle );
  661. }
  662. }
  663. /**
  664. * Should we show a preview when the edit form is first shown?
  665. *
  666. * @return bool
  667. */
  668. protected function previewOnOpen() {
  669. $config = $this->context->getConfig();
  670. $previewOnOpenNamespaces = $config->get( 'PreviewOnOpenNamespaces' );
  671. $request = $this->context->getRequest();
  672. if ( $config->get( 'RawHtml' ) ) {
  673. // If raw HTML is enabled, disable preview on open
  674. // since it has to be posted with a token for
  675. // security reasons
  676. return false;
  677. }
  678. if ( $request->getVal( 'preview' ) == 'yes' ) {
  679. // Explicit override from request
  680. return true;
  681. } elseif ( $request->getVal( 'preview' ) == 'no' ) {
  682. // Explicit override from request
  683. return false;
  684. } elseif ( $this->section == 'new' ) {
  685. // Nothing *to* preview for new sections
  686. return false;
  687. } elseif ( ( $request->getVal( 'preload' ) !== null || $this->mTitle->exists() )
  688. && $this->context->getUser()->getOption( 'previewonfirst' )
  689. ) {
  690. // Standard preference behavior
  691. return true;
  692. } elseif ( !$this->mTitle->exists()
  693. && isset( $previewOnOpenNamespaces[$this->mTitle->getNamespace()] )
  694. && $previewOnOpenNamespaces[$this->mTitle->getNamespace()]
  695. ) {
  696. // Categories are special
  697. return true;
  698. } else {
  699. return false;
  700. }
  701. }
  702. /**
  703. * Checks whether the user entered a skin name in uppercase,
  704. * e.g. "User:Example/Monobook.css" instead of "monobook.css"
  705. *
  706. * @return bool
  707. */
  708. protected function isWrongCaseUserConfigPage() {
  709. if ( $this->mTitle->isUserConfigPage() ) {
  710. $name = $this->mTitle->getSkinFromConfigSubpage();
  711. $skins = array_merge(
  712. array_keys( Skin::getSkinNames() ),
  713. [ 'common' ]
  714. );
  715. return !in_array( $name, $skins )
  716. && in_array( strtolower( $name ), $skins );
  717. } else {
  718. return false;
  719. }
  720. }
  721. /**
  722. * Returns whether section editing is supported for the current page.
  723. * Subclasses may override this to replace the default behavior, which is
  724. * to check ContentHandler::supportsSections.
  725. *
  726. * @return bool True if this edit page supports sections, false otherwise.
  727. */
  728. protected function isSectionEditSupported() {
  729. $contentHandler = ContentHandler::getForTitle( $this->mTitle );
  730. return $contentHandler->supportsSections();
  731. }
  732. /**
  733. * This function collects the form data and uses it to populate various member variables.
  734. * @param WebRequest &$request
  735. * @throws ErrorPageError
  736. */
  737. public function importFormData( &$request ) {
  738. # Section edit can come from either the form or a link
  739. $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
  740. if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
  741. throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
  742. }
  743. $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
  744. if ( $request->wasPosted() ) {
  745. # These fields need to be checked for encoding.
  746. # Also remove trailing whitespace, but don't remove _initial_
  747. # whitespace from the text boxes. This may be significant formatting.
  748. $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
  749. if ( !$request->getCheck( 'wpTextbox2' ) ) {
  750. // Skip this if wpTextbox2 has input, it indicates that we came
  751. // from a conflict page with raw page text, not a custom form
  752. // modified by subclasses
  753. $textbox1 = $this->importContentFormData( $request );
  754. if ( $textbox1 !== null ) {
  755. $this->textbox1 = $textbox1;
  756. }
  757. }
  758. $this->unicodeCheck = $request->getText( 'wpUnicodeCheck' );
  759. $this->summary = $request->getText( 'wpSummary' );
  760. # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
  761. # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
  762. # section titles.
  763. $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
  764. # Treat sectiontitle the same way as summary.
  765. # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
  766. # currently doing double duty as both edit summary and section title. Right now this
  767. # is just to allow API edits to work around this limitation, but this should be
  768. # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
  769. $this->sectiontitle = $request->getText( 'wpSectionTitle' );
  770. $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
  771. $this->edittime = $request->getVal( 'wpEdittime' );
  772. $this->editRevId = $request->getIntOrNull( 'editRevId' );
  773. $this->starttime = $request->getVal( 'wpStarttime' );
  774. $undidRev = $request->getInt( 'wpUndidRevision' );
  775. if ( $undidRev ) {
  776. $this->undidRev = $undidRev;
  777. }
  778. $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
  779. if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
  780. // wpTextbox1 field is missing, possibly due to being "too big"
  781. // according to some filter rules such as Suhosin's setting for
  782. // suhosin.request.max_value_length (d'oh)
  783. $this->incompleteForm = true;
  784. } else {
  785. // If we receive the last parameter of the request, we can fairly
  786. // claim the POST request has not been truncated.
  787. // TODO: softened the check for cutover. Once we determine
  788. // that it is safe, we should complete the transition by
  789. // removing the "edittime" clause.
  790. $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
  791. && is_null( $this->edittime ) );
  792. }
  793. if ( $this->incompleteForm ) {
  794. # If the form is incomplete, force to preview.
  795. wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
  796. wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
  797. $this->preview = true;
  798. } else {
  799. $this->preview = $request->getCheck( 'wpPreview' );
  800. $this->diff = $request->getCheck( 'wpDiff' );
  801. // Remember whether a save was requested, so we can indicate
  802. // if we forced preview due to session failure.
  803. $this->mTriedSave = !$this->preview;
  804. if ( $this->tokenOk( $request ) ) {
  805. # Some browsers will not report any submit button
  806. # if the user hits enter in the comment box.
  807. # The unmarked state will be assumed to be a save,
  808. # if the form seems otherwise complete.
  809. wfDebug( __METHOD__ . ": Passed token check.\n" );
  810. } elseif ( $this->diff ) {
  811. # Failed token check, but only requested "Show Changes".
  812. wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
  813. } else {
  814. # Page might be a hack attempt posted from
  815. # an external site. Preview instead of saving.
  816. wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
  817. $this->preview = true;
  818. }
  819. }
  820. $this->save = !$this->preview && !$this->diff;
  821. if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
  822. $this->edittime = null;
  823. }
  824. if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
  825. $this->starttime = null;
  826. }
  827. $this->recreate = $request->getCheck( 'wpRecreate' );
  828. $this->minoredit = $request->getCheck( 'wpMinoredit' );
  829. $this->watchthis = $request->getCheck( 'wpWatchthis' );
  830. $user = $this->context->getUser();
  831. # Don't force edit summaries when a user is editing their own user or talk page
  832. if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
  833. && $this->mTitle->getText() == $user->getName()
  834. ) {
  835. $this->allowBlankSummary = true;
  836. } else {
  837. $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
  838. || !$user->getOption( 'forceeditsummary' );
  839. }
  840. $this->autoSumm = $request->getText( 'wpAutoSummary' );
  841. $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
  842. $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
  843. $changeTags = $request->getVal( 'wpChangeTags' );
  844. if ( is_null( $changeTags ) || $changeTags === '' ) {
  845. $this->changeTags = [];
  846. } else {
  847. $this->changeTags = array_filter( array_map( 'trim', explode( ',',
  848. $changeTags ) ) );
  849. }
  850. } else {
  851. # Not a posted form? Start with nothing.
  852. wfDebug( __METHOD__ . ": Not a posted form.\n" );
  853. $this->textbox1 = '';
  854. $this->summary = '';
  855. $this->sectiontitle = '';
  856. $this->edittime = '';
  857. $this->editRevId = null;
  858. $this->starttime = wfTimestampNow();
  859. $this->edit = false;
  860. $this->preview = false;
  861. $this->save = false;
  862. $this->diff = false;
  863. $this->minoredit = false;
  864. // Watch may be overridden by request parameters
  865. $this->watchthis = $request->getBool( 'watchthis', false );
  866. $this->recreate = false;
  867. // When creating a new section, we can preload a section title by passing it as the
  868. // preloadtitle parameter in the URL (T15100)
  869. if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
  870. $this->sectiontitle = $request->getVal( 'preloadtitle' );
  871. // Once wpSummary isn't being use for setting section titles, we should delete this.
  872. $this->summary = $request->getVal( 'preloadtitle' );
  873. } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
  874. $this->summary = $request->getText( 'summary' );
  875. if ( $this->summary !== '' ) {
  876. $this->hasPresetSummary = true;
  877. }
  878. }
  879. if ( $request->getVal( 'minor' ) ) {
  880. $this->minoredit = true;
  881. }
  882. }
  883. $this->oldid = $request->getInt( 'oldid' );
  884. $this->parentRevId = $request->getInt( 'parentRevId' );
  885. $this->bot = $request->getBool( 'bot', true );
  886. $this->nosummary = $request->getBool( 'nosummary' );
  887. // May be overridden by revision.
  888. $this->contentModel = $request->getText( 'model', $this->contentModel );
  889. // May be overridden by revision.
  890. $this->contentFormat = $request->getText( 'format', $this->contentFormat );
  891. try {
  892. $handler = ContentHandler::getForModelID( $this->contentModel );
  893. } catch ( MWUnknownContentModelException $e ) {
  894. throw new ErrorPageError(
  895. 'editpage-invalidcontentmodel-title',
  896. 'editpage-invalidcontentmodel-text',
  897. [ wfEscapeWikiText( $this->contentModel ) ]
  898. );
  899. }
  900. if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
  901. throw new ErrorPageError(
  902. 'editpage-notsupportedcontentformat-title',
  903. 'editpage-notsupportedcontentformat-text',
  904. [
  905. wfEscapeWikiText( $this->contentFormat ),
  906. wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
  907. ]
  908. );
  909. }
  910. /**
  911. * @todo Check if the desired model is allowed in this namespace, and if
  912. * a transition from the page's current model to the new model is
  913. * allowed.
  914. */
  915. $this->editintro = $request->getText( 'editintro',
  916. // Custom edit intro for new sections
  917. $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
  918. // Allow extensions to modify form data
  919. Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
  920. }
  921. /**
  922. * Subpage overridable method for extracting the page content data from the
  923. * posted form to be placed in $this->textbox1, if using customized input
  924. * this method should be overridden and return the page text that will be used
  925. * for saving, preview parsing and so on...
  926. *
  927. * @param WebRequest &$request
  928. * @return string|null
  929. */
  930. protected function importContentFormData( &$request ) {
  931. return; // Don't do anything, EditPage already extracted wpTextbox1
  932. }
  933. /**
  934. * Initialise form fields in the object
  935. * Called on the first invocation, e.g. when a user clicks an edit link
  936. * @return bool If the requested section is valid
  937. */
  938. public function initialiseForm() {
  939. $this->edittime = $this->page->getTimestamp();
  940. $this->editRevId = $this->page->getLatest();
  941. $content = $this->getContentObject( false ); # TODO: track content object?!
  942. if ( $content === false ) {
  943. return false;
  944. }
  945. $this->textbox1 = $this->toEditText( $content );
  946. $user = $this->context->getUser();
  947. // activate checkboxes if user wants them to be always active
  948. # Sort out the "watch" checkbox
  949. if ( $user->getOption( 'watchdefault' ) ) {
  950. # Watch all edits
  951. $this->watchthis = true;
  952. } elseif ( $user->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
  953. # Watch creations
  954. $this->watchthis = true;
  955. } elseif ( $user->isWatched( $this->mTitle ) ) {
  956. # Already watched
  957. $this->watchthis = true;
  958. }
  959. if ( $user->getOption( 'minordefault' ) && !$this->isNew ) {
  960. $this->minoredit = true;
  961. }
  962. if ( $this->textbox1 === false ) {
  963. return false;
  964. }
  965. return true;
  966. }
  967. /**
  968. * @param Content|null $def_content The default value to return
  969. *
  970. * @return Content|null Content on success, $def_content for invalid sections
  971. *
  972. * @since 1.21
  973. */
  974. protected function getContentObject( $def_content = null ) {
  975. global $wgContLang;
  976. $content = false;
  977. $user = $this->context->getUser();
  978. $request = $this->context->getRequest();
  979. // For message page not locally set, use the i18n message.
  980. // For other non-existent articles, use preload text if any.
  981. if ( !$this->mTitle->exists() || $this->section == 'new' ) {
  982. if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
  983. # If this is a system message, get the default text.
  984. $msg = $this->mTitle->getDefaultMessageText();
  985. $content = $this->toEditContent( $msg );
  986. }
  987. if ( $content === false ) {
  988. # If requested, preload some text.
  989. $preload = $request->getVal( 'preload',
  990. // Custom preload text for new sections
  991. $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
  992. $params = $request->getArray( 'preloadparams', [] );
  993. $content = $this->getPreloadedContent( $preload, $params );
  994. }
  995. // For existing pages, get text based on "undo" or section parameters.
  996. } else {
  997. if ( $this->section != '' ) {
  998. // Get section edit text (returns $def_text for invalid sections)
  999. $orig = $this->getOriginalContent( $user );
  1000. $content = $orig ? $orig->getSection( $this->section ) : null;
  1001. if ( !$content ) {
  1002. $content = $def_content;
  1003. }
  1004. } else {
  1005. $undoafter = $request->getInt( 'undoafter' );
  1006. $undo = $request->getInt( 'undo' );
  1007. if ( $undo > 0 && $undoafter > 0 ) {
  1008. $undorev = Revision::newFromId( $undo );
  1009. $oldrev = Revision::newFromId( $undoafter );
  1010. # Sanity check, make sure it's the right page,
  1011. # the revisions exist and they were not deleted.
  1012. # Otherwise, $content will be left as-is.
  1013. if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
  1014. !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
  1015. !$oldrev->isDeleted( Revision::DELETED_TEXT )
  1016. ) {
  1017. $content = $this->page->getUndoContent( $undorev, $oldrev );
  1018. if ( $content === false ) {
  1019. # Warn the user that something went wrong
  1020. $undoMsg = 'failure';
  1021. } else {
  1022. $oldContent = $this->page->getContent( Revision::RAW );
  1023. $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
  1024. $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
  1025. if ( $newContent->getModel() !== $oldContent->getModel() ) {
  1026. // The undo may change content
  1027. // model if its reverting the top
  1028. // edit. This can result in
  1029. // mismatched content model/format.
  1030. $this->contentModel = $newContent->getModel();
  1031. $this->contentFormat = $oldrev->getContentFormat();
  1032. }
  1033. if ( $newContent->equals( $oldContent ) ) {
  1034. # Tell the user that the undo results in no change,
  1035. # i.e. the revisions were already undone.
  1036. $undoMsg = 'nochange';
  1037. $content = false;
  1038. } else {
  1039. # Inform the user of our success and set an automatic edit summary
  1040. $undoMsg = 'success';
  1041. # If we just undid one rev, use an autosummary
  1042. $firstrev = $oldrev->getNext();
  1043. if ( $firstrev && $firstrev->getId() == $undo ) {
  1044. $userText = $undorev->getUserText();
  1045. if ( $userText === '' ) {
  1046. $undoSummary = $this->context->msg(
  1047. 'undo-summary-username-hidden',
  1048. $undo
  1049. )->inContentLanguage()->text();
  1050. } else {
  1051. $undoSummary = $this->context->msg(
  1052. 'undo-summary',
  1053. $undo,
  1054. $userText
  1055. )->inContentLanguage()->text();
  1056. }
  1057. if ( $this->summary === '' ) {
  1058. $this->summary = $undoSummary;
  1059. } else {
  1060. $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
  1061. ->inContentLanguage()->text() . $this->summary;
  1062. }
  1063. $this->undidRev = $undo;
  1064. }
  1065. $this->formtype = 'diff';
  1066. }
  1067. }
  1068. } else {
  1069. // Failed basic sanity checks.
  1070. // Older revisions may have been removed since the link
  1071. // was created, or we may simply have got bogus input.
  1072. $undoMsg = 'norev';
  1073. }
  1074. $out = $this->context->getOutput();
  1075. // Messages: undo-success, undo-failure, undo-norev, undo-nochange
  1076. $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
  1077. $this->editFormPageTop .= $out->parse( "<div class=\"{$class}\">" .
  1078. $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
  1079. }
  1080. if ( $content === false ) {
  1081. $content = $this->getOriginalContent( $user );
  1082. }
  1083. }
  1084. }
  1085. return $content;
  1086. }
  1087. /**
  1088. * Get the content of the wanted revision, without section extraction.
  1089. *
  1090. * The result of this function can be used to compare user's input with
  1091. * section replaced in its context (using WikiPage::replaceSectionAtRev())
  1092. * to the original text of the edit.
  1093. *
  1094. * This differs from Article::getContent() that when a missing revision is
  1095. * encountered the result will be null and not the
  1096. * 'missing-revision' message.
  1097. *
  1098. * @since 1.19
  1099. * @param User $user The user to get the revision for
  1100. * @return Content|null
  1101. */
  1102. private function getOriginalContent( User $user ) {
  1103. if ( $this->section == 'new' ) {
  1104. return $this->getCurrentContent();
  1105. }
  1106. $revision = $this->mArticle->getRevisionFetched();
  1107. if ( $revision === null ) {
  1108. $handler = ContentHandler::getForModelID( $this->contentModel );
  1109. return $handler->makeEmptyContent();
  1110. }
  1111. $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
  1112. return $content;
  1113. }
  1114. /**
  1115. * Get the edit's parent revision ID
  1116. *
  1117. * The "parent" revision is the ancestor that should be recorded in this
  1118. * page's revision history. It is either the revision ID of the in-memory
  1119. * article content, or in the case of a 3-way merge in order to rebase
  1120. * across a recoverable edit conflict, the ID of the newer revision to
  1121. * which we have rebased this page.
  1122. *
  1123. * @since 1.27
  1124. * @return int Revision ID
  1125. */
  1126. public function getParentRevId() {
  1127. if ( $this->parentRevId ) {
  1128. return $this->parentRevId;
  1129. } else {
  1130. return $this->mArticle->getRevIdFetched();
  1131. }
  1132. }
  1133. /**
  1134. * Get the current content of the page. This is basically similar to
  1135. * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
  1136. * content object is returned instead of null.
  1137. *
  1138. * @since 1.21
  1139. * @return Content
  1140. */
  1141. protected function getCurrentContent() {
  1142. $rev = $this->page->getRevision();
  1143. $content = $rev ? $rev->getContent( Revision::RAW ) : null;
  1144. if ( $content === false || $content === null ) {
  1145. $handler = ContentHandler::getForModelID( $this->contentModel );
  1146. return $handler->makeEmptyContent();
  1147. } elseif ( !$this->undidRev ) {
  1148. // Content models should always be the same since we error
  1149. // out if they are different before this point (in ->edit()).
  1150. // The exception being, during an undo, the current revision might
  1151. // differ from the prior revision.
  1152. $logger = LoggerFactory::getInstance( 'editpage' );
  1153. if ( $this->contentModel !== $rev->getContentModel() ) {
  1154. $logger->warning( "Overriding content model from current edit {prev} to {new}", [
  1155. 'prev' => $this->contentModel,
  1156. 'new' => $rev->getContentModel(),
  1157. 'title' => $this->getTitle()->getPrefixedDBkey(),
  1158. 'method' => __METHOD__
  1159. ] );
  1160. $this->contentModel = $rev->getContentModel();
  1161. }
  1162. // Given that the content models should match, the current selected
  1163. // format should be supported.
  1164. if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
  1165. $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
  1166. 'prev' => $this->contentFormat,
  1167. 'new' => $rev->getContentFormat(),
  1168. 'title' => $this->getTitle()->getPrefixedDBkey(),
  1169. 'method' => __METHOD__
  1170. ] );
  1171. $this->contentFormat = $rev->getContentFormat();
  1172. }
  1173. }
  1174. return $content;
  1175. }
  1176. /**
  1177. * Use this method before edit() to preload some content into the edit box
  1178. *
  1179. * @param Content $content
  1180. *
  1181. * @since 1.21
  1182. */
  1183. public function setPreloadedContent( Content $content ) {
  1184. $this->mPreloadContent = $content;
  1185. }
  1186. /**
  1187. * Get the contents to be preloaded into the box, either set by
  1188. * an earlier setPreloadText() or by loading the given page.
  1189. *
  1190. * @param string $preload Representing the title to preload from.
  1191. * @param array $params Parameters to use (interface-message style) in the preloaded text
  1192. *
  1193. * @return Content
  1194. *
  1195. * @since 1.21
  1196. */
  1197. protected function getPreloadedContent( $preload, $params = [] ) {
  1198. if ( !empty( $this->mPreloadContent ) ) {
  1199. return $this->mPreloadContent;
  1200. }
  1201. $handler = ContentHandler::getForModelID( $this->contentModel );
  1202. if ( $preload === '' ) {
  1203. return $handler->makeEmptyContent();
  1204. }
  1205. $user = $this->context->getUser();
  1206. $title = Title::newFromText( $preload );
  1207. # Check for existence to avoid getting MediaWiki:Noarticletext
  1208. if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
  1209. // TODO: somehow show a warning to the user!
  1210. return $handler->makeEmptyContent();
  1211. }
  1212. $page = WikiPage::factory( $title );
  1213. if ( $page->isRedirect() ) {
  1214. $title = $page->getRedirectTarget();
  1215. # Same as before
  1216. if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
  1217. // TODO: somehow show a warning to the user!
  1218. return $handler->makeEmptyContent();
  1219. }
  1220. $page = WikiPage::factory( $title );
  1221. }
  1222. $parserOptions = ParserOptions::newFromUser( $user );
  1223. $content = $page->getContent( Revision::RAW );
  1224. if ( !$content ) {
  1225. // TODO: somehow show a warning to the user!
  1226. return $handler->makeEmptyContent();
  1227. }
  1228. if ( $content->getModel() !== $handler->getModelID() ) {
  1229. $converted = $content->convert( $handler->getModelID() );
  1230. if ( !$converted ) {
  1231. // TODO: somehow show a warning to the user!
  1232. wfDebug( "Attempt to preload incompatible content: " .
  1233. "can't convert " . $content->getModel() .
  1234. " to " . $handler->getModelID() );
  1235. return $handler->makeEmptyContent();
  1236. }
  1237. $content = $converted;
  1238. }
  1239. return $content->preloadTransform( $title, $parserOptions, $params );
  1240. }
  1241. /**
  1242. * Make sure the form isn't faking a user's credentials.
  1243. *
  1244. * @param WebRequest &$request
  1245. * @return bool
  1246. * @private
  1247. */
  1248. public function tokenOk( &$request ) {
  1249. $token = $request->getVal( 'wpEditToken' );
  1250. $user = $this->context->getUser();
  1251. $this->mTokenOk = $user->matchEditToken( $token );
  1252. $this->mTokenOkExceptSuffix = $user->matchEditTokenNoSuffix( $token );
  1253. return $this->mTokenOk;
  1254. }
  1255. /**
  1256. * Sets post-edit cookie indicating the user just saved a particular revision.
  1257. *
  1258. * This uses a temporary cookie for each revision ID so separate saves will never
  1259. * interfere with each other.
  1260. *
  1261. * Article::view deletes the cookie on server-side after the redirect and
  1262. * converts the value to the global JavaScript variable wgPostEdit.
  1263. *
  1264. * If the variable were set on the server, it would be cached, which is unwanted
  1265. * since the post-edit state should only apply to the load right after the save.
  1266. *
  1267. * @param int $statusValue The status value (to check for new article status)
  1268. */
  1269. protected function setPostEditCookie( $statusValue ) {
  1270. $revisionId = $this->page->getLatest();
  1271. $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
  1272. $val = 'saved';
  1273. if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
  1274. $val = 'created';
  1275. } elseif ( $this->oldid ) {
  1276. $val = 'restored';
  1277. }
  1278. $response = $this->context->getRequest()->response();
  1279. $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
  1280. }
  1281. /**
  1282. * Attempt submission
  1283. * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
  1284. * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
  1285. * @return Status The resulting status object.
  1286. */
  1287. public function attemptSave( &$resultDetails = false ) {
  1288. # Allow bots to exempt some edits from bot flagging
  1289. $bot = $this->context->getUser()->isAllowed( 'bot' ) && $this->bot;
  1290. $status = $this->internalAttemptSave( $resultDetails, $bot );
  1291. Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
  1292. return $status;
  1293. }
  1294. /**
  1295. * Log when a page was successfully saved after the edit conflict view
  1296. */
  1297. private function incrementResolvedConflicts() {
  1298. if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
  1299. return;
  1300. }
  1301. $this->getEditConflictHelper()->incrementResolvedStats();
  1302. }
  1303. /**
  1304. * Handle status, such as after attempt save
  1305. *
  1306. * @param Status $status
  1307. * @param array|bool $resultDetails
  1308. *
  1309. * @throws ErrorPageError
  1310. * @return bool False, if output is done, true if rest of the form should be displayed
  1311. */
  1312. private function handleStatus( Status $status, $resultDetails ) {
  1313. /**
  1314. * @todo FIXME: once the interface for internalAttemptSave() is made
  1315. * nicer, this should use the message in $status
  1316. */
  1317. if ( $status->value == self::AS_SUCCESS_UPDATE
  1318. || $status->value == self::AS_SUCCESS_NEW_ARTICLE
  1319. ) {
  1320. $this->incrementResolvedConflicts();
  1321. $this->didSave = true;
  1322. if ( !$resultDetails['nullEdit'] ) {
  1323. $this->setPostEditCookie( $status->value );
  1324. }
  1325. }
  1326. $out = $this->context->getOutput();
  1327. // "wpExtraQueryRedirect" is a hidden input to modify
  1328. // after save URL and is not used by actual edit form
  1329. $request = $this->context->getRequest();
  1330. $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
  1331. switch ( $status->value ) {
  1332. case self::AS_HOOK_ERROR_EXPECTED:
  1333. case self::AS_CONTENT_TOO_BIG:
  1334. case self::AS_ARTICLE_WAS_DELETED:
  1335. case self::AS_CONFLICT_DETECTED:
  1336. case self::AS_SUMMARY_NEEDED:
  1337. case self::AS_TEXTBOX_EMPTY:
  1338. case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
  1339. case self::AS_END:
  1340. case self::AS_BLANK_ARTICLE:
  1341. case self::AS_SELF_REDIRECT:
  1342. return true;
  1343. case self::AS_HOOK_ERROR:
  1344. return false;
  1345. case self::AS_CANNOT_USE_CUSTOM_MODEL:
  1346. case self::AS_PARSE_ERROR:
  1347. case self::AS_UNICODE_NOT_SUPPORTED:
  1348. $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
  1349. return true;
  1350. case self::AS_SUCCESS_NEW_ARTICLE:
  1351. $query = $resultDetails['redirect'] ? 'redirect=no' : '';
  1352. if ( $extraQueryRedirect ) {
  1353. if ( $query === '' ) {
  1354. $query = $extraQueryRedirect;
  1355. } else {
  1356. $query = $query . '&' . $extraQueryRedirect;
  1357. }
  1358. }
  1359. $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
  1360. $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
  1361. return false;
  1362. case self::AS_SUCCESS_UPDATE:
  1363. $extraQuery = '';
  1364. $sectionanchor = $resultDetails['sectionanchor'];
  1365. // Give extensions a chance to modify URL query on update
  1366. Hooks::run(
  1367. 'ArticleUpdateBeforeRedirect',
  1368. [ $this->mArticle, &$sectionanchor, &$extraQuery ]
  1369. );
  1370. if ( $resultDetails['redirect'] ) {
  1371. if ( $extraQuery == '' ) {
  1372. $extraQuery = 'redirect=no';
  1373. } else {
  1374. $extraQuery = 'redirect=no&' . $extraQuery;
  1375. }
  1376. }
  1377. if ( $extraQueryRedirect ) {
  1378. if ( $extraQuery === '' ) {
  1379. $extraQuery = $extraQueryRedirect;
  1380. } else {
  1381. $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
  1382. }
  1383. }
  1384. $out->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
  1385. return false;
  1386. case self::AS_SPAM_ERROR:
  1387. $this->spamPageWithContent( $resultDetails['spam'] );
  1388. return false;
  1389. case self::AS_BLOCKED_PAGE_FOR_USER:
  1390. throw new UserBlockedError( $this->context->getUser()->getBlock() );
  1391. case self::AS_IMAGE_REDIRECT_ANON:
  1392. case self::AS_IMAGE_REDIRECT_LOGGED:
  1393. throw new PermissionsError( 'upload' );
  1394. case self::AS_READ_ONLY_PAGE_ANON:
  1395. case self::AS_READ_ONLY_PAGE_LOGGED:
  1396. throw new PermissionsError( 'edit' );
  1397. case self::AS_READ_ONLY_PAGE:
  1398. throw new ReadOnlyError;
  1399. case self::AS_RATE_LIMITED:
  1400. throw new ThrottledError();
  1401. case self::AS_NO_CREATE_PERMISSION:
  1402. $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
  1403. throw new PermissionsError( $permission );
  1404. case self::AS_NO_CHANGE_CONTENT_MODEL:
  1405. throw new PermissionsError( 'editcontentmodel' );
  1406. default:
  1407. // We don't recognize $status->value. The only way that can happen
  1408. // is if an extension hook aborted from inside ArticleSave.
  1409. // Render the status object into $this->hookError
  1410. // FIXME this sucks, we should just use the Status object throughout
  1411. $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
  1412. '</div>';
  1413. return true;
  1414. }
  1415. }
  1416. /**
  1417. * Run hooks that can filter edits just before they get saved.
  1418. *
  1419. * @param Content $content The Content to filter.
  1420. * @param Status $status For reporting the outcome to the caller
  1421. * @param User $user The user performing the edit
  1422. *
  1423. * @return bool
  1424. */
  1425. protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
  1426. // Run old style post-section-merge edit filter
  1427. if ( $this->hookError != '' ) {
  1428. # ...or the hook could be expecting us to produce an error
  1429. $status->fatal( 'hookaborted' );
  1430. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  1431. return false;
  1432. }
  1433. // Run new style post-section-merge edit filter
  1434. if ( !Hooks::run( 'EditFilterMergedContent',
  1435. [ $this->context, $content, $status, $this->summary,
  1436. $user, $this->minoredit ] )
  1437. ) {
  1438. # Error messages etc. could be handled within the hook...
  1439. if ( $status->isGood() ) {
  1440. $status->fatal( 'hookaborted' );
  1441. // Not setting $this->hookError here is a hack to allow the hook
  1442. // to cause a return to the edit page without $this->hookError
  1443. // being set. This is used by ConfirmEdit to display a captcha
  1444. // without any error message cruft.
  1445. } else {
  1446. $this->hookError = $this->formatStatusErrors( $status );
  1447. }
  1448. // Use the existing $status->value if the hook set it
  1449. if ( !$status->value ) {
  1450. $status->value = self::AS_HOOK_ERROR;
  1451. }
  1452. return false;
  1453. } elseif ( !$status->isOK() ) {
  1454. # ...or the hook could be expecting us to produce an error
  1455. // FIXME this sucks, we should just use the Status object throughout
  1456. $this->hookError = $this->formatStatusErrors( $status );
  1457. $status->fatal( 'hookaborted' );
  1458. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  1459. return false;
  1460. }
  1461. return true;
  1462. }
  1463. /**
  1464. * Wrap status errors in an errorbox for increased visibility
  1465. *
  1466. * @param Status $status
  1467. * @return string Wikitext
  1468. */
  1469. private function formatStatusErrors( Status $status ) {
  1470. $errmsg = $status->getWikiText(
  1471. 'edit-error-short',
  1472. 'edit-error-long',
  1473. $this->context->getLanguage()
  1474. );
  1475. return <<<ERROR
  1476. <div class="errorbox">
  1477. {$errmsg}
  1478. </div>
  1479. <br clear="all" />
  1480. ERROR;
  1481. }
  1482. /**
  1483. * Return the summary to be used for a new section.
  1484. *
  1485. * @param string $sectionanchor Set to the section anchor text
  1486. * @return string
  1487. */
  1488. private function newSectionSummary( &$sectionanchor = null ) {
  1489. global $wgParser;
  1490. if ( $this->sectiontitle !== '' ) {
  1491. $sectionanchor = $this->guessSectionName( $this->sectiontitle );
  1492. // If no edit summary was specified, create one automatically from the section
  1493. // title and have it link to the new section. Otherwise, respect the summary as
  1494. // passed.
  1495. if ( $this->summary === '' ) {
  1496. $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
  1497. return $this->context->msg( 'newsectionsummary' )
  1498. ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
  1499. }
  1500. } elseif ( $this->summary !== '' ) {
  1501. $sectionanchor = $this->guessSectionName( $this->summary );
  1502. # This is a new section, so create a link to the new section
  1503. # in the revision summary.
  1504. $cleanSummary = $wgParser->stripSectionName( $this->summary );
  1505. return $this->context->msg( 'newsectionsummary' )
  1506. ->rawParams( $cleanSummary )->inContentLanguage()->text();
  1507. }
  1508. return $this->summary;
  1509. }
  1510. /**
  1511. * Attempt submission (no UI)
  1512. *
  1513. * @param array &$result Array to add statuses to, currently with the
  1514. * possible keys:
  1515. * - spam (string): Spam string from content if any spam is detected by
  1516. * matchSpamRegex.
  1517. * - sectionanchor (string): Section anchor for a section save.
  1518. * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
  1519. * false otherwise.
  1520. * - redirect (bool): Set if doEditContent is OK. True if resulting
  1521. * revision is a redirect.
  1522. * @param bool $bot True if edit is being made under the bot right.
  1523. *
  1524. * @return Status Status object, possibly with a message, but always with
  1525. * one of the AS_* constants in $status->value,
  1526. *
  1527. * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
  1528. * various error display idiosyncrasies. There are also lots of cases
  1529. * where error metadata is set in the object and retrieved later instead
  1530. * of being returned, e.g. AS_CONTENT_TOO_BIG and
  1531. * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
  1532. * time.
  1533. */
  1534. public function internalAttemptSave( &$result, $bot = false ) {
  1535. $status = Status::newGood();
  1536. $user = $this->context->getUser();
  1537. if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
  1538. wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
  1539. $status->fatal( 'hookaborted' );
  1540. $status->value = self::AS_HOOK_ERROR;
  1541. return $status;
  1542. }
  1543. if ( $this->unicodeCheck !== self::UNICODE_CHECK ) {
  1544. $status->fatal( 'unicode-support-fail' );
  1545. $status->value = self::AS_UNICODE_NOT_SUPPORTED;
  1546. return $status;
  1547. }
  1548. $request = $this->context->getRequest();
  1549. $spam = $request->getText( 'wpAntispam' );
  1550. if ( $spam !== '' ) {
  1551. wfDebugLog(
  1552. 'SimpleAntiSpam',
  1553. $user->getName() .
  1554. ' editing "' .
  1555. $this->mTitle->getPrefixedText() .
  1556. '" submitted bogus field "' .
  1557. $spam .
  1558. '"'
  1559. );
  1560. $status->fatal( 'spamprotectionmatch', false );
  1561. $status->value = self::AS_SPAM_ERROR;
  1562. return $status;
  1563. }
  1564. try {
  1565. # Construct Content object
  1566. $textbox_content = $this->toEditContent( $this->textbox1 );
  1567. } catch ( MWContentSerializationException $ex ) {
  1568. $status->fatal(
  1569. 'content-failed-to-parse',
  1570. $this->contentModel,
  1571. $this->contentFormat,
  1572. $ex->getMessage()
  1573. );
  1574. $status->value = self::AS_PARSE_ERROR;
  1575. return $status;
  1576. }
  1577. # Check image redirect
  1578. if ( $this->mTitle->getNamespace() == NS_FILE &&
  1579. $textbox_content->isRedirect() &&
  1580. !$user->isAllowed( 'upload' )
  1581. ) {
  1582. $code = $user->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
  1583. $status->setResult( false, $code );
  1584. return $status;
  1585. }
  1586. # Check for spam
  1587. $match = self::matchSummarySpamRegex( $this->summary );
  1588. if ( $match === false && $this->section == 'new' ) {
  1589. # $wgSpamRegex is enforced on this new heading/summary because, unlike
  1590. # regular summaries, it is added to the actual wikitext.
  1591. if ( $this->sectiontitle !== '' ) {
  1592. # This branch is taken when the API is used with the 'sectiontitle' parameter.
  1593. $match = self::matchSpamRegex( $this->sectiontitle );
  1594. } else {
  1595. # This branch is taken when the "Add Topic" user interface is used, or the API
  1596. # is used with the 'summary' parameter.
  1597. $match = self::matchSpamRegex( $this->summary );
  1598. }
  1599. }
  1600. if ( $match === false ) {
  1601. $match = self::matchSpamRegex( $this->textbox1 );
  1602. }
  1603. if ( $match !== false ) {
  1604. $result['spam'] = $match;
  1605. $ip = $request->getIP();
  1606. $pdbk = $this->mTitle->getPrefixedDBkey();
  1607. $match = str_replace( "\n", '', $match );
  1608. wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
  1609. $status->fatal( 'spamprotectionmatch', $match );
  1610. $status->value = self::AS_SPAM_ERROR;
  1611. return $status;
  1612. }
  1613. if ( !Hooks::run(
  1614. 'EditFilter',
  1615. [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
  1616. ) {
  1617. # Error messages etc. could be handled within the hook...
  1618. $status->fatal( 'hookaborted' );
  1619. $status->value = self::AS_HOOK_ERROR;
  1620. return $status;
  1621. } elseif ( $this->hookError != '' ) {
  1622. # ...or the hook could be expecting us to produce an error
  1623. $status->fatal( 'hookaborted' );
  1624. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  1625. return $status;
  1626. }
  1627. if ( $user->isBlockedFrom( $this->mTitle, false ) ) {
  1628. // Auto-block user's IP if the account was "hard" blocked
  1629. if ( !wfReadOnly() ) {
  1630. $user->spreadAnyEditBlock();
  1631. }
  1632. # Check block state against master, thus 'false'.
  1633. $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
  1634. return $status;
  1635. }
  1636. $this->contentLength = strlen( $this->textbox1 );
  1637. $config = $this->context->getConfig();
  1638. $maxArticleSize = $config->get( 'MaxArticleSize' );
  1639. if ( $this->contentLength > $maxArticleSize * 1024 ) {
  1640. // Error will be displayed by showEditForm()
  1641. $this->tooBig = true;
  1642. $status->setResult( false, self::AS_CONTENT_TOO_BIG );
  1643. return $status;
  1644. }
  1645. if ( !$user->isAllowed( 'edit' ) ) {
  1646. if ( $user->isAnon() ) {
  1647. $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
  1648. return $status;
  1649. } else {
  1650. $status->fatal( 'readonlytext' );
  1651. $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
  1652. return $status;
  1653. }
  1654. }
  1655. $changingContentModel = false;
  1656. if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
  1657. if ( !$config->get( 'ContentHandlerUseDB' ) ) {
  1658. $status->fatal( 'editpage-cannot-use-custom-model' );
  1659. $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
  1660. return $status;
  1661. } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
  1662. $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
  1663. return $status;
  1664. }
  1665. // Make sure the user can edit the page under the new content model too
  1666. $titleWithNewContentModel = clone $this->mTitle;
  1667. $titleWithNewContentModel->setContentModel( $this->contentModel );
  1668. if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
  1669. || !$titleWithNewContentModel->userCan( 'edit', $user )
  1670. ) {
  1671. $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
  1672. return $status;
  1673. }
  1674. $changingContentModel = true;
  1675. $oldContentModel = $this->mTitle->getContentModel();
  1676. }
  1677. if ( $this->changeTags ) {
  1678. $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
  1679. $this->changeTags, $user );
  1680. if ( !$changeTagsStatus->isOK() ) {
  1681. $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
  1682. return $changeTagsStatus;
  1683. }
  1684. }
  1685. if ( wfReadOnly() ) {
  1686. $status->fatal( 'readonlytext' );
  1687. $status->value = self::AS_READ_ONLY_PAGE;
  1688. return $status;
  1689. }
  1690. if ( $user->pingLimiter() || $user->pingLimiter( 'linkpurge', 0 )
  1691. || ( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
  1692. ) {
  1693. $status->fatal( 'actionthrottledtext' );
  1694. $status->value = self::AS_RATE_LIMITED;
  1695. return $status;
  1696. }
  1697. # If the article has been deleted while editing, don't save it without
  1698. # confirmation
  1699. if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
  1700. $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
  1701. return $status;
  1702. }
  1703. # Load the page data from the master. If anything changes in the meantime,
  1704. # we detect it by using page_latest like a token in a 1 try compare-and-swap.
  1705. $this->page->loadPageData( 'fromdbmaster' );
  1706. $new = !$this->page->exists();
  1707. if ( $new ) {
  1708. // Late check for create permission, just in case *PARANOIA*
  1709. if ( !$this->mTitle->userCan( 'create', $user ) ) {
  1710. $status->fatal( 'nocreatetext' );
  1711. $status->value = self::AS_NO_CREATE_PERMISSION;
  1712. wfDebug( __METHOD__ . ": no create permission\n" );
  1713. return $status;
  1714. }
  1715. // Don't save a new page if it's blank or if it's a MediaWiki:
  1716. // message with content equivalent to default (allow empty pages
  1717. // in this case to disable messages, see T52124)
  1718. $defaultMessageText = $this->mTitle->getDefaultMessageText();
  1719. if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
  1720. $defaultText = $defaultMessageText;
  1721. } else {
  1722. $defaultText = '';
  1723. }
  1724. if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
  1725. $this->blankArticle = true;
  1726. $status->fatal( 'blankarticle' );
  1727. $status->setResult( false, self::AS_BLANK_ARTICLE );
  1728. return $status;
  1729. }
  1730. if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
  1731. return $status;
  1732. }
  1733. $content = $textbox_content;
  1734. $result['sectionanchor'] = '';
  1735. if ( $this->section == 'new' ) {
  1736. if ( $this->sectiontitle !== '' ) {
  1737. // Insert the section title above the content.
  1738. $content = $content->addSectionHeader( $this->sectiontitle );
  1739. } elseif ( $this->summary !== '' ) {
  1740. // Insert the section title above the content.
  1741. $content = $content->addSectionHeader( $this->summary );
  1742. }
  1743. $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
  1744. }
  1745. $status->value = self::AS_SUCCESS_NEW_ARTICLE;
  1746. } else { # not $new
  1747. # Article exists. Check for edit conflict.
  1748. $this->page->clear(); # Force reload of dates, etc.
  1749. $timestamp = $this->page->getTimestamp();
  1750. $latest = $this->page->getLatest();
  1751. wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
  1752. // Check editRevId if set, which handles same-second timestamp collisions
  1753. if ( $timestamp != $this->edittime
  1754. || ( $this->editRevId !== null && $this->editRevId != $latest )
  1755. ) {
  1756. $this->isConflict = true;
  1757. if ( $this->section == 'new' ) {
  1758. if ( $this->page->getUserText() == $user->getName() &&
  1759. $this->page->getComment() == $this->newSectionSummary()
  1760. ) {
  1761. // Probably a duplicate submission of a new comment.
  1762. // This can happen when CDN resends a request after
  1763. // a timeout but the first one actually went through.
  1764. wfDebug( __METHOD__
  1765. . ": duplicate new section submission; trigger edit conflict!\n" );
  1766. } else {
  1767. // New comment; suppress conflict.
  1768. $this->isConflict = false;
  1769. wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
  1770. }
  1771. } elseif ( $this->section == ''
  1772. && Revision::userWasLastToEdit(
  1773. DB_MASTER, $this->mTitle->getArticleID(),
  1774. $user->getId(), $this->edittime
  1775. )
  1776. ) {
  1777. # Suppress edit conflict with self, except for section edits where merging is required.
  1778. wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
  1779. $this->isConflict = false;
  1780. }
  1781. }
  1782. // If sectiontitle is set, use it, otherwise use the summary as the section title.
  1783. if ( $this->sectiontitle !== '' ) {
  1784. $sectionTitle = $this->sectiontitle;
  1785. } else {
  1786. $sectionTitle = $this->summary;
  1787. }
  1788. $content = null;
  1789. if ( $this->isConflict ) {
  1790. wfDebug( __METHOD__
  1791. . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
  1792. . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
  1793. // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
  1794. // ...or disable section editing for non-current revisions (not exposed anyway).
  1795. if ( $this->editRevId !== null ) {
  1796. $content = $this->page->replaceSectionAtRev(
  1797. $this->section,
  1798. $textbox_content,
  1799. $sectionTitle,
  1800. $this->editRevId
  1801. );
  1802. } else {
  1803. $content = $this->page->replaceSectionContent(
  1804. $this->section,
  1805. $textbox_content,
  1806. $sectionTitle,
  1807. $this->edittime
  1808. );
  1809. }
  1810. } else {
  1811. wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
  1812. $content = $this->page->replaceSectionContent(
  1813. $this->section,
  1814. $textbox_content,
  1815. $sectionTitle
  1816. );
  1817. }
  1818. if ( is_null( $content ) ) {
  1819. wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
  1820. $this->isConflict = true;
  1821. $content = $textbox_content; // do not try to merge here!
  1822. } elseif ( $this->isConflict ) {
  1823. # Attempt merge
  1824. if ( $this->mergeChangesIntoContent( $content ) ) {
  1825. // Successful merge! Maybe we should tell the user the good news?
  1826. $this->isConflict = false;
  1827. wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
  1828. } else {
  1829. $this->section = '';
  1830. $this->textbox1 = ContentHandler::getContentText( $content );
  1831. wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
  1832. }
  1833. }
  1834. if ( $this->isConflict ) {
  1835. $status->setResult( false, self::AS_CONFLICT_DETECTED );
  1836. return $status;
  1837. }
  1838. if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
  1839. return $status;
  1840. }
  1841. if ( $this->section == 'new' ) {
  1842. // Handle the user preference to force summaries here
  1843. if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
  1844. $this->missingSummary = true;
  1845. $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
  1846. $status->value = self::AS_SUMMARY_NEEDED;
  1847. return $status;
  1848. }
  1849. // Do not allow the user to post an empty comment
  1850. if ( $this->textbox1 == '' ) {
  1851. $this->missingComment = true;
  1852. $status->fatal( 'missingcommenttext' );
  1853. $status->value = self::AS_TEXTBOX_EMPTY;
  1854. return $status;
  1855. }
  1856. } elseif ( !$this->allowBlankSummary
  1857. && !$content->equals( $this->getOriginalContent( $user ) )
  1858. && !$content->isRedirect()
  1859. && md5( $this->summary ) == $this->autoSumm
  1860. ) {
  1861. $this->missingSummary = true;
  1862. $status->fatal( 'missingsummary' );
  1863. $status->value = self::AS_SUMMARY_NEEDED;
  1864. return $status;
  1865. }
  1866. # All's well
  1867. $sectionanchor = '';
  1868. if ( $this->section == 'new' ) {
  1869. $this->summary = $this->newSectionSummary( $sectionanchor );
  1870. } elseif ( $this->section != '' ) {
  1871. # Try to get a section anchor from the section source, redirect
  1872. # to edited section if header found.
  1873. # XXX: Might be better to integrate this into Article::replaceSectionAtRev
  1874. # for duplicate heading checking and maybe parsing.
  1875. $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
  1876. # We can't deal with anchors, includes, html etc in the header for now,
  1877. # headline would need to be parsed to improve this.
  1878. if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
  1879. $sectionanchor = $this->guessSectionName( $matches[2] );
  1880. }
  1881. }
  1882. $result['sectionanchor'] = $sectionanchor;
  1883. // Save errors may fall down to the edit form, but we've now
  1884. // merged the section into full text. Clear the section field
  1885. // so that later submission of conflict forms won't try to
  1886. // replace that into a duplicated mess.
  1887. $this->textbox1 = $this->toEditText( $content );
  1888. $this->section = '';
  1889. $status->value = self::AS_SUCCESS_UPDATE;
  1890. }
  1891. if ( !$this->allowSelfRedirect
  1892. && $content->isRedirect()
  1893. && $content->getRedirectTarget()->equals( $this->getTitle() )
  1894. ) {
  1895. // If the page already redirects to itself, don't warn.
  1896. $currentTarget = $this->getCurrentContent()->getRedirectTarget();
  1897. if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
  1898. $this->selfRedirect = true;
  1899. $status->fatal( 'selfredirect' );
  1900. $status->value = self::AS_SELF_REDIRECT;
  1901. return $status;
  1902. }
  1903. }
  1904. // Check for length errors again now that the section is merged in
  1905. $this->contentLength = strlen( $this->toEditText( $content ) );
  1906. if ( $this->contentLength > $maxArticleSize * 1024 ) {
  1907. $this->tooBig = true;
  1908. $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
  1909. return $status;
  1910. }
  1911. $flags = EDIT_AUTOSUMMARY |
  1912. ( $new ? EDIT_NEW : EDIT_UPDATE ) |
  1913. ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
  1914. ( $bot ? EDIT_FORCE_BOT : 0 );
  1915. $doEditStatus = $this->page->doEditContent(
  1916. $content,
  1917. $this->summary,
  1918. $flags,
  1919. false,
  1920. $user,
  1921. $content->getDefaultFormat(),
  1922. $this->changeTags,
  1923. $this->undidRev
  1924. );
  1925. if ( !$doEditStatus->isOK() ) {
  1926. // Failure from doEdit()
  1927. // Show the edit conflict page for certain recognized errors from doEdit(),
  1928. // but don't show it for errors from extension hooks
  1929. $errors = $doEditStatus->getErrorsArray();
  1930. if ( in_array( $errors[0][0],
  1931. [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
  1932. ) {
  1933. $this->isConflict = true;
  1934. // Destroys data doEdit() put in $status->value but who cares
  1935. $doEditStatus->value = self::AS_END;
  1936. }
  1937. return $doEditStatus;
  1938. }
  1939. $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
  1940. if ( $result['nullEdit'] ) {
  1941. // We don't know if it was a null edit until now, so increment here
  1942. $user->pingLimiter( 'linkpurge' );
  1943. }
  1944. $result['redirect'] = $content->isRedirect();
  1945. $this->updateWatchlist();
  1946. // If the content model changed, add a log entry
  1947. if ( $changingContentModel ) {
  1948. $this->addContentModelChangeLogEntry(
  1949. $user,
  1950. $new ? false : $oldContentModel,
  1951. $this->contentModel,
  1952. $this->summary
  1953. );
  1954. }
  1955. return $status;
  1956. }
  1957. /**
  1958. * @param User $user
  1959. * @param string|false $oldModel false if the page is being newly created
  1960. * @param string $newModel
  1961. * @param string $reason
  1962. */
  1963. protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
  1964. $new = $oldModel === false;
  1965. $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
  1966. $log->setPerformer( $user );
  1967. $log->setTarget( $this->mTitle );
  1968. $log->setComment( $reason );
  1969. $log->setParameters( [
  1970. '4::oldmodel' => $oldModel,
  1971. '5::newmodel' => $newModel
  1972. ] );
  1973. $logid = $log->insert();
  1974. $log->publish( $logid );
  1975. }
  1976. /**
  1977. * Register the change of watch status
  1978. */
  1979. protected function updateWatchlist() {
  1980. $user = $this->context->getUser();
  1981. if ( !$user->isLoggedIn() ) {
  1982. return;
  1983. }
  1984. $title = $this->mTitle;
  1985. $watch = $this->watchthis;
  1986. // Do this in its own transaction to reduce contention...
  1987. DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
  1988. if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
  1989. return; // nothing to change
  1990. }
  1991. WatchAction::doWatchOrUnwatch( $watch, $title, $user );
  1992. } );
  1993. }
  1994. /**
  1995. * Attempts to do 3-way merge of edit content with a base revision
  1996. * and current content, in case of edit conflict, in whichever way appropriate
  1997. * for the content type.
  1998. *
  1999. * @since 1.21
  2000. *
  2001. * @param Content $editContent
  2002. *
  2003. * @return bool
  2004. */
  2005. private function mergeChangesIntoContent( &$editContent ) {
  2006. $db = wfGetDB( DB_MASTER );
  2007. // This is the revision the editor started from
  2008. $baseRevision = $this->getBaseRevision();
  2009. $baseContent = $baseRevision ? $baseRevision->getContent() : null;
  2010. if ( is_null( $baseContent ) ) {
  2011. return false;
  2012. }
  2013. // The current state, we want to merge updates into it
  2014. $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
  2015. $currentContent = $currentRevision ? $currentRevision->getContent() : null;
  2016. if ( is_null( $currentContent ) ) {
  2017. return false;
  2018. }
  2019. $handler = ContentHandler::getForModelID( $baseContent->getModel() );
  2020. $result = $handler->merge3( $baseContent, $editContent, $currentContent );
  2021. if ( $result ) {
  2022. $editContent = $result;
  2023. // Update parentRevId to what we just merged.
  2024. $this->parentRevId = $currentRevision->getId();
  2025. return true;
  2026. }
  2027. return false;
  2028. }
  2029. /**
  2030. * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
  2031. * one might think of X as the "base revision", which is NOT what this returns.
  2032. * @return Revision|null Current version when the edit was started
  2033. */
  2034. public function getBaseRevision() {
  2035. if ( !$this->mBaseRevision ) {
  2036. $db = wfGetDB( DB_MASTER );
  2037. $this->mBaseRevision = $this->editRevId
  2038. ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
  2039. : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
  2040. }
  2041. return $this->mBaseRevision;
  2042. }
  2043. /**
  2044. * Check given input text against $wgSpamRegex, and return the text of the first match.
  2045. *
  2046. * @param string $text
  2047. *
  2048. * @return string|bool Matching string or false
  2049. */
  2050. public static function matchSpamRegex( $text ) {
  2051. global $wgSpamRegex;
  2052. // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
  2053. $regexes = (array)$wgSpamRegex;
  2054. return self::matchSpamRegexInternal( $text, $regexes );
  2055. }
  2056. /**
  2057. * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
  2058. *
  2059. * @param string $text
  2060. *
  2061. * @return string|bool Matching string or false
  2062. */
  2063. public static function matchSummarySpamRegex( $text ) {
  2064. global $wgSummarySpamRegex;
  2065. $regexes = (array)$wgSummarySpamRegex;
  2066. return self::matchSpamRegexInternal( $text, $regexes );
  2067. }
  2068. /**
  2069. * @param string $text
  2070. * @param array $regexes
  2071. * @return bool|string
  2072. */
  2073. protected static function matchSpamRegexInternal( $text, $regexes ) {
  2074. foreach ( $regexes as $regex ) {
  2075. $matches = [];
  2076. if ( preg_match( $regex, $text, $matches ) ) {
  2077. return $matches[0];
  2078. }
  2079. }
  2080. return false;
  2081. }
  2082. public function setHeaders() {
  2083. $out = $this->context->getOutput();
  2084. $out->addModules( 'mediawiki.action.edit' );
  2085. $out->addModuleStyles( 'mediawiki.action.edit.styles' );
  2086. $out->addModuleStyles( 'mediawiki.editfont.styles' );
  2087. $user = $this->context->getUser();
  2088. if ( $user->getOption( 'showtoolbar' ) ) {
  2089. // The addition of default buttons is handled by getEditToolbar() which
  2090. // has its own dependency on this module. The call here ensures the module
  2091. // is loaded in time (it has position "top") for other modules to register
  2092. // buttons (e.g. extensions, gadgets, user scripts).
  2093. $out->addModules( 'mediawiki.toolbar' );
  2094. }
  2095. if ( $user->getOption( 'uselivepreview' ) ) {
  2096. $out->addModules( 'mediawiki.action.edit.preview' );
  2097. }
  2098. if ( $user->getOption( 'useeditwarning' ) ) {
  2099. $out->addModules( 'mediawiki.action.edit.editWarning' );
  2100. }
  2101. # Enabled article-related sidebar, toplinks, etc.
  2102. $out->setArticleRelated( true );
  2103. $contextTitle = $this->getContextTitle();
  2104. if ( $this->isConflict ) {
  2105. $msg = 'editconflict';
  2106. } elseif ( $contextTitle->exists() && $this->section != '' ) {
  2107. $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
  2108. } else {
  2109. $msg = $contextTitle->exists()
  2110. || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
  2111. && $contextTitle->getDefaultMessageText() !== false
  2112. )
  2113. ? 'editing'
  2114. : 'creating';
  2115. }
  2116. # Use the title defined by DISPLAYTITLE magic word when present
  2117. # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
  2118. # setPageTitle() treats the input as wikitext, which should be safe in either case.
  2119. $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
  2120. if ( $displayTitle === false ) {
  2121. $displayTitle = $contextTitle->getPrefixedText();
  2122. }
  2123. $out->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
  2124. $config = $this->context->getConfig();
  2125. # Transmit the name of the message to JavaScript for live preview
  2126. # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
  2127. $out->addJsConfigVars( [
  2128. 'wgEditMessage' => $msg,
  2129. 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
  2130. ] );
  2131. // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
  2132. // editors, etc.
  2133. $out->addJsConfigVars(
  2134. 'wgEditSubmitButtonLabelPublish',
  2135. $config->get( 'EditSubmitButtonLabelPublish' )
  2136. );
  2137. }
  2138. /**
  2139. * Show all applicable editing introductions
  2140. */
  2141. protected function showIntro() {
  2142. if ( $this->suppressIntro ) {
  2143. return;
  2144. }
  2145. $out = $this->context->getOutput();
  2146. $namespace = $this->mTitle->getNamespace();
  2147. if ( $namespace == NS_MEDIAWIKI ) {
  2148. # Show a warning if editing an interface message
  2149. $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
  2150. # If this is a default message (but not css, json, or js),
  2151. # show a hint that it is translatable on translatewiki.net
  2152. if (
  2153. !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
  2154. && !$this->mTitle->hasContentModel( CONTENT_MODEL_JSON )
  2155. && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
  2156. ) {
  2157. $defaultMessageText = $this->mTitle->getDefaultMessageText();
  2158. if ( $defaultMessageText !== false ) {
  2159. $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
  2160. 'translateinterface' );
  2161. }
  2162. }
  2163. } elseif ( $namespace == NS_FILE ) {
  2164. # Show a hint to shared repo
  2165. $file = wfFindFile( $this->mTitle );
  2166. if ( $file && !$file->isLocal() ) {
  2167. $descUrl = $file->getDescriptionUrl();
  2168. # there must be a description url to show a hint to shared repo
  2169. if ( $descUrl ) {
  2170. if ( !$this->mTitle->exists() ) {
  2171. $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
  2172. 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
  2173. ] );
  2174. } else {
  2175. $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
  2176. 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
  2177. ] );
  2178. }
  2179. }
  2180. }
  2181. }
  2182. # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
  2183. # Show log extract when the user is currently blocked
  2184. if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
  2185. $username = explode( '/', $this->mTitle->getText(), 2 )[0];
  2186. $user = User::newFromName( $username, false /* allow IP users */ );
  2187. $ip = User::isIP( $username );
  2188. $block = Block::newFromTarget( $user, $user );
  2189. if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
  2190. $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
  2191. [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
  2192. } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
  2193. # Show log extract if the user is currently blocked
  2194. LogEventsList::showLogExtract(
  2195. $out,
  2196. 'block',
  2197. MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
  2198. '',
  2199. [
  2200. 'lim' => 1,
  2201. 'showIfEmpty' => false,
  2202. 'msgKey' => [
  2203. 'blocked-notice-logextract',
  2204. $user->getName() # Support GENDER in notice
  2205. ]
  2206. ]
  2207. );
  2208. }
  2209. }
  2210. # Try to add a custom edit intro, or use the standard one if this is not possible.
  2211. if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
  2212. $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
  2213. $this->context->msg( 'helppage' )->inContentLanguage()->text()
  2214. ) );
  2215. if ( $this->context->getUser()->isLoggedIn() ) {
  2216. $out->wrapWikiMsg(
  2217. // Suppress the external link icon, consider the help url an internal one
  2218. "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
  2219. [
  2220. 'newarticletext',
  2221. $helpLink
  2222. ]
  2223. );
  2224. } else {
  2225. $out->wrapWikiMsg(
  2226. // Suppress the external link icon, consider the help url an internal one
  2227. "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
  2228. [
  2229. 'newarticletextanon',
  2230. $helpLink
  2231. ]
  2232. );
  2233. }
  2234. }
  2235. # Give a notice if the user is editing a deleted/moved page...
  2236. if ( !$this->mTitle->exists() ) {
  2237. $dbr = wfGetDB( DB_REPLICA );
  2238. LogEventsList::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle,
  2239. '',
  2240. [
  2241. 'lim' => 10,
  2242. 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
  2243. 'showIfEmpty' => false,
  2244. 'msgKey' => [ 'recreate-moveddeleted-warn' ]
  2245. ]
  2246. );
  2247. }
  2248. }
  2249. /**
  2250. * Attempt to show a custom editing introduction, if supplied
  2251. *
  2252. * @return bool
  2253. */
  2254. protected function showCustomIntro() {
  2255. if ( $this->editintro ) {
  2256. $title = Title::newFromText( $this->editintro );
  2257. if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
  2258. // Added using template syntax, to take <noinclude>'s into account.
  2259. $this->context->getOutput()->addWikiTextTitleTidy(
  2260. '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
  2261. $this->mTitle
  2262. );
  2263. return true;
  2264. }
  2265. }
  2266. return false;
  2267. }
  2268. /**
  2269. * Gets an editable textual representation of $content.
  2270. * The textual representation can be turned by into a Content object by the
  2271. * toEditContent() method.
  2272. *
  2273. * If $content is null or false or a string, $content is returned unchanged.
  2274. *
  2275. * If the given Content object is not of a type that can be edited using
  2276. * the text base EditPage, an exception will be raised. Set
  2277. * $this->allowNonTextContent to true to allow editing of non-textual
  2278. * content.
  2279. *
  2280. * @param Content|null|bool|string $content
  2281. * @return string The editable text form of the content.
  2282. *
  2283. * @throws MWException If $content is not an instance of TextContent and
  2284. * $this->allowNonTextContent is not true.
  2285. */
  2286. protected function toEditText( $content ) {
  2287. if ( $content === null || $content === false || is_string( $content ) ) {
  2288. return $content;
  2289. }
  2290. if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
  2291. throw new MWException( 'This content model is not supported: ' . $content->getModel() );
  2292. }
  2293. return $content->serialize( $this->contentFormat );
  2294. }
  2295. /**
  2296. * Turns the given text into a Content object by unserializing it.
  2297. *
  2298. * If the resulting Content object is not of a type that can be edited using
  2299. * the text base EditPage, an exception will be raised. Set
  2300. * $this->allowNonTextContent to true to allow editing of non-textual
  2301. * content.
  2302. *
  2303. * @param string|null|bool $text Text to unserialize
  2304. * @return Content|bool|null The content object created from $text. If $text was false
  2305. * or null, false resp. null will be returned instead.
  2306. *
  2307. * @throws MWException If unserializing the text results in a Content
  2308. * object that is not an instance of TextContent and
  2309. * $this->allowNonTextContent is not true.
  2310. */
  2311. protected function toEditContent( $text ) {
  2312. if ( $text === false || $text === null ) {
  2313. return $text;
  2314. }
  2315. $content = ContentHandler::makeContent( $text, $this->getTitle(),
  2316. $this->contentModel, $this->contentFormat );
  2317. if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
  2318. throw new MWException( 'This content model is not supported: ' . $content->getModel() );
  2319. }
  2320. return $content;
  2321. }
  2322. /**
  2323. * Send the edit form and related headers to OutputPage
  2324. * @param callable|null $formCallback That takes an OutputPage parameter; will be called
  2325. * during form output near the top, for captchas and the like.
  2326. *
  2327. * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
  2328. * use the EditPage::showEditForm:fields hook instead.
  2329. */
  2330. public function showEditForm( $formCallback = null ) {
  2331. # need to parse the preview early so that we know which templates are used,
  2332. # otherwise users with "show preview after edit box" will get a blank list
  2333. # we parse this near the beginning so that setHeaders can do the title
  2334. # setting work instead of leaving it in getPreviewText
  2335. $previewOutput = '';
  2336. if ( $this->formtype == 'preview' ) {
  2337. $previewOutput = $this->getPreviewText();
  2338. }
  2339. $out = $this->context->getOutput();
  2340. // Avoid PHP 7.1 warning of passing $this by reference
  2341. $editPage = $this;
  2342. Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
  2343. $this->setHeaders();
  2344. $this->addTalkPageText();
  2345. $this->addEditNotices();
  2346. if ( !$this->isConflict &&
  2347. $this->section != '' &&
  2348. !$this->isSectionEditSupported() ) {
  2349. // We use $this->section to much before this and getVal('wgSection') directly in other places
  2350. // at this point we can't reset $this->section to '' to fallback to non-section editing.
  2351. // Someone is welcome to try refactoring though
  2352. $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
  2353. return;
  2354. }
  2355. $this->showHeader();
  2356. $out->addHTML( $this->editFormPageTop );
  2357. $user = $this->context->getUser();
  2358. if ( $user->getOption( 'previewontop' ) ) {
  2359. $this->displayPreviewArea( $previewOutput, true );
  2360. }
  2361. $out->addHTML( $this->editFormTextTop );
  2362. $showToolbar = true;
  2363. if ( $this->wasDeletedSinceLastEdit() ) {
  2364. if ( $this->formtype == 'save' ) {
  2365. // Hide the toolbar and edit area, user can click preview to get it back
  2366. // Add an confirmation checkbox and explanation.
  2367. $showToolbar = false;
  2368. } else {
  2369. $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
  2370. 'deletedwhileediting' );
  2371. }
  2372. }
  2373. // @todo add EditForm plugin interface and use it here!
  2374. // search for textarea1 and textarea2, and allow EditForm to override all uses.
  2375. $out->addHTML( Html::openElement(
  2376. 'form',
  2377. [
  2378. 'class' => 'mw-editform',
  2379. 'id' => self::EDITFORM_ID,
  2380. 'name' => self::EDITFORM_ID,
  2381. 'method' => 'post',
  2382. 'action' => $this->getActionURL( $this->getContextTitle() ),
  2383. 'enctype' => 'multipart/form-data'
  2384. ]
  2385. ) );
  2386. if ( is_callable( $formCallback ) ) {
  2387. wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
  2388. call_user_func_array( $formCallback, [ &$out ] );
  2389. }
  2390. // Add a check for Unicode support
  2391. $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
  2392. // Add an empty field to trip up spambots
  2393. $out->addHTML(
  2394. Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
  2395. . Html::rawElement(
  2396. 'label',
  2397. [ 'for' => 'wpAntispam' ],
  2398. $this->context->msg( 'simpleantispam-label' )->parse()
  2399. )
  2400. . Xml::element(
  2401. 'input',
  2402. [
  2403. 'type' => 'text',
  2404. 'name' => 'wpAntispam',
  2405. 'id' => 'wpAntispam',
  2406. 'value' => ''
  2407. ]
  2408. )
  2409. . Xml::closeElement( 'div' )
  2410. );
  2411. // Avoid PHP 7.1 warning of passing $this by reference
  2412. $editPage = $this;
  2413. Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
  2414. // Put these up at the top to ensure they aren't lost on early form submission
  2415. $this->showFormBeforeText();
  2416. if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
  2417. $username = $this->lastDelete->user_name;
  2418. $comment = CommentStore::getStore()
  2419. ->getComment( 'log_comment', $this->lastDelete )->text;
  2420. // It is better to not parse the comment at all than to have templates expanded in the middle
  2421. // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
  2422. $key = $comment === ''
  2423. ? 'confirmrecreate-noreason'
  2424. : 'confirmrecreate';
  2425. $out->addHTML(
  2426. '<div class="mw-confirm-recreate">' .
  2427. $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
  2428. Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
  2429. [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
  2430. ) .
  2431. '</div>'
  2432. );
  2433. }
  2434. # When the summary is hidden, also hide them on preview/show changes
  2435. if ( $this->nosummary ) {
  2436. $out->addHTML( Html::hidden( 'nosummary', true ) );
  2437. }
  2438. # If a blank edit summary was previously provided, and the appropriate
  2439. # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
  2440. # user being bounced back more than once in the event that a summary
  2441. # is not required.
  2442. # ####
  2443. # For a bit more sophisticated detection of blank summaries, hash the
  2444. # automatic one and pass that in the hidden field wpAutoSummary.
  2445. if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
  2446. $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
  2447. }
  2448. if ( $this->undidRev ) {
  2449. $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
  2450. }
  2451. if ( $this->selfRedirect ) {
  2452. $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
  2453. }
  2454. if ( $this->hasPresetSummary ) {
  2455. // If a summary has been preset using &summary= we don't want to prompt for
  2456. // a different summary. Only prompt for a summary if the summary is blanked.
  2457. // (T19416)
  2458. $this->autoSumm = md5( '' );
  2459. }
  2460. $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
  2461. $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
  2462. $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
  2463. $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
  2464. $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
  2465. $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
  2466. $out->enableOOUI();
  2467. if ( $this->section == 'new' ) {
  2468. $this->showSummaryInput( true, $this->summary );
  2469. $out->addHTML( $this->getSummaryPreview( true, $this->summary ) );
  2470. }
  2471. $out->addHTML( $this->editFormTextBeforeContent );
  2472. if ( $this->isConflict ) {
  2473. // In an edit conflict, we turn textbox2 into the user's text,
  2474. // and textbox1 into the stored version
  2475. $this->textbox2 = $this->textbox1;
  2476. $content = $this->getCurrentContent();
  2477. $this->textbox1 = $this->toEditText( $content );
  2478. $editConflictHelper = $this->getEditConflictHelper();
  2479. $editConflictHelper->setTextboxes( $this->textbox2, $this->textbox1 );
  2480. $editConflictHelper->setContentModel( $this->contentModel );
  2481. $editConflictHelper->setContentFormat( $this->contentFormat );
  2482. $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
  2483. }
  2484. if ( !$this->mTitle->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
  2485. $out->addHTML( self::getEditToolbar( $this->mTitle ) );
  2486. }
  2487. if ( $this->blankArticle ) {
  2488. $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
  2489. }
  2490. if ( $this->isConflict ) {
  2491. // In an edit conflict bypass the overridable content form method
  2492. // and fallback to the raw wpTextbox1 since editconflicts can't be
  2493. // resolved between page source edits and custom ui edits using the
  2494. // custom edit ui.
  2495. $conflictTextBoxAttribs = [];
  2496. if ( $this->wasDeletedSinceLastEdit() ) {
  2497. $conflictTextBoxAttribs['style'] = 'display:none;';
  2498. } elseif ( $this->isOldRev ) {
  2499. $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
  2500. }
  2501. $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
  2502. $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
  2503. } else {
  2504. $this->showContentForm();
  2505. }
  2506. $out->addHTML( $this->editFormTextAfterContent );
  2507. $this->showStandardInputs();
  2508. $this->showFormAfterText();
  2509. $this->showTosSummary();
  2510. $this->showEditTools();
  2511. $out->addHTML( $this->editFormTextAfterTools . "\n" );
  2512. $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
  2513. $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
  2514. Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
  2515. $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
  2516. self::getPreviewLimitReport( $this->mParserOutput ) ) );
  2517. $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
  2518. if ( $this->isConflict ) {
  2519. try {
  2520. $this->showConflict();
  2521. } catch ( MWContentSerializationException $ex ) {
  2522. // this can't really happen, but be nice if it does.
  2523. $msg = $this->context->msg(
  2524. 'content-failed-to-parse',
  2525. $this->contentModel,
  2526. $this->contentFormat,
  2527. $ex->getMessage()
  2528. );
  2529. $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
  2530. }
  2531. }
  2532. // Set a hidden field so JS knows what edit form mode we are in
  2533. if ( $this->isConflict ) {
  2534. $mode = 'conflict';
  2535. } elseif ( $this->preview ) {
  2536. $mode = 'preview';
  2537. } elseif ( $this->diff ) {
  2538. $mode = 'diff';
  2539. } else {
  2540. $mode = 'text';
  2541. }
  2542. $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
  2543. // Marker for detecting truncated form data. This must be the last
  2544. // parameter sent in order to be of use, so do not move me.
  2545. $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
  2546. $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
  2547. if ( !$user->getOption( 'previewontop' ) ) {
  2548. $this->displayPreviewArea( $previewOutput, false );
  2549. }
  2550. }
  2551. /**
  2552. * Wrapper around TemplatesOnThisPageFormatter to make
  2553. * a "templates on this page" list.
  2554. *
  2555. * @param Title[] $templates
  2556. * @return string HTML
  2557. */
  2558. public function makeTemplatesOnThisPageList( array $templates ) {
  2559. $templateListFormatter = new TemplatesOnThisPageFormatter(
  2560. $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
  2561. );
  2562. // preview if preview, else section if section, else false
  2563. $type = false;
  2564. if ( $this->preview ) {
  2565. $type = 'preview';
  2566. } elseif ( $this->section != '' ) {
  2567. $type = 'section';
  2568. }
  2569. return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
  2570. $templateListFormatter->format( $templates, $type )
  2571. );
  2572. }
  2573. /**
  2574. * Extract the section title from current section text, if any.
  2575. *
  2576. * @param string $text
  2577. * @return string|bool String or false
  2578. */
  2579. public static function extractSectionTitle( $text ) {
  2580. preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
  2581. if ( !empty( $matches[2] ) ) {
  2582. global $wgParser;
  2583. return $wgParser->stripSectionName( trim( $matches[2] ) );
  2584. } else {
  2585. return false;
  2586. }
  2587. }
  2588. protected function showHeader() {
  2589. $out = $this->context->getOutput();
  2590. $user = $this->context->getUser();
  2591. if ( $this->isConflict ) {
  2592. $this->addExplainConflictHeader( $out );
  2593. $this->editRevId = $this->page->getLatest();
  2594. } else {
  2595. if ( $this->section != '' && $this->section != 'new' ) {
  2596. if ( !$this->summary && !$this->preview && !$this->diff ) {
  2597. $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
  2598. if ( $sectionTitle !== false ) {
  2599. $this->summary = "/* $sectionTitle */ ";
  2600. }
  2601. }
  2602. }
  2603. $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
  2604. if ( $this->missingComment ) {
  2605. $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
  2606. }
  2607. if ( $this->missingSummary && $this->section != 'new' ) {
  2608. $out->wrapWikiMsg(
  2609. "<div id='mw-missingsummary'>\n$1\n</div>",
  2610. [ 'missingsummary', $buttonLabel ]
  2611. );
  2612. }
  2613. if ( $this->missingSummary && $this->section == 'new' ) {
  2614. $out->wrapWikiMsg(
  2615. "<div id='mw-missingcommentheader'>\n$1\n</div>",
  2616. [ 'missingcommentheader', $buttonLabel ]
  2617. );
  2618. }
  2619. if ( $this->blankArticle ) {
  2620. $out->wrapWikiMsg(
  2621. "<div id='mw-blankarticle'>\n$1\n</div>",
  2622. [ 'blankarticle', $buttonLabel ]
  2623. );
  2624. }
  2625. if ( $this->selfRedirect ) {
  2626. $out->wrapWikiMsg(
  2627. "<div id='mw-selfredirect'>\n$1\n</div>",
  2628. [ 'selfredirect', $buttonLabel ]
  2629. );
  2630. }
  2631. if ( $this->hookError !== '' ) {
  2632. $out->addWikiText( $this->hookError );
  2633. }
  2634. if ( $this->section != 'new' ) {
  2635. $revision = $this->mArticle->getRevisionFetched();
  2636. if ( $revision ) {
  2637. // Let sysop know that this will make private content public if saved
  2638. if ( !$revision->userCan( Revision::DELETED_TEXT, $user ) ) {
  2639. $out->wrapWikiMsg(
  2640. "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
  2641. 'rev-deleted-text-permission'
  2642. );
  2643. } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
  2644. $out->wrapWikiMsg(
  2645. "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
  2646. 'rev-deleted-text-view'
  2647. );
  2648. }
  2649. if ( !$revision->isCurrent() ) {
  2650. $this->mArticle->setOldSubtitle( $revision->getId() );
  2651. $out->addWikiMsg( 'editingold' );
  2652. $this->isOldRev = true;
  2653. }
  2654. } elseif ( $this->mTitle->exists() ) {
  2655. // Something went wrong
  2656. $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
  2657. [ 'missing-revision', $this->oldid ] );
  2658. }
  2659. }
  2660. }
  2661. if ( wfReadOnly() ) {
  2662. $out->wrapWikiMsg(
  2663. "<div id=\"mw-read-only-warning\">\n$1\n</div>",
  2664. [ 'readonlywarning', wfReadOnlyReason() ]
  2665. );
  2666. } elseif ( $user->isAnon() ) {
  2667. if ( $this->formtype != 'preview' ) {
  2668. $out->wrapWikiMsg(
  2669. "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
  2670. [ 'anoneditwarning',
  2671. // Log-in link
  2672. SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
  2673. 'returnto' => $this->getTitle()->getPrefixedDBkey()
  2674. ] ),
  2675. // Sign-up link
  2676. SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
  2677. 'returnto' => $this->getTitle()->getPrefixedDBkey()
  2678. ] )
  2679. ]
  2680. );
  2681. } else {
  2682. $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
  2683. 'anonpreviewwarning'
  2684. );
  2685. }
  2686. } else {
  2687. if ( $this->mTitle->isUserConfigPage() ) {
  2688. # Check the skin exists
  2689. if ( $this->isWrongCaseUserConfigPage() ) {
  2690. $out->wrapWikiMsg(
  2691. "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
  2692. [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
  2693. );
  2694. }
  2695. if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
  2696. $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
  2697. $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
  2698. $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
  2699. $warning = $isUserCssConfig
  2700. ? 'usercssispublic'
  2701. : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
  2702. $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
  2703. if ( $this->formtype !== 'preview' ) {
  2704. $config = $this->context->getConfig();
  2705. if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
  2706. $out->wrapWikiMsg(
  2707. "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
  2708. [ 'usercssyoucanpreview' ]
  2709. );
  2710. } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
  2711. $out->wrapWikiMsg(
  2712. "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
  2713. [ 'userjsonyoucanpreview' ]
  2714. );
  2715. } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
  2716. $out->wrapWikiMsg(
  2717. "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
  2718. [ 'userjsyoucanpreview' ]
  2719. );
  2720. }
  2721. }
  2722. }
  2723. }
  2724. }
  2725. $this->addPageProtectionWarningHeaders();
  2726. $this->addLongPageWarningHeader();
  2727. # Add header copyright warning
  2728. $this->showHeaderCopyrightWarning();
  2729. }
  2730. /**
  2731. * Helper function for summary input functions, which returns the neccessary
  2732. * attributes for the input.
  2733. *
  2734. * @param array|null $inputAttrs Array of attrs to use on the input
  2735. * @return array
  2736. */
  2737. private function getSummaryInputAttributes( array $inputAttrs = null ) {
  2738. $conf = $this->context->getConfig();
  2739. $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
  2740. // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
  2741. // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
  2742. // Unicode codepoints (or 255 UTF-8 bytes for old schema).
  2743. return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
  2744. 'id' => 'wpSummary',
  2745. 'name' => 'wpSummary',
  2746. 'maxlength' => $oldCommentSchema ? 200 : CommentStore::COMMENT_CHARACTER_LIMIT,
  2747. 'tabindex' => 1,
  2748. 'size' => 60,
  2749. 'spellcheck' => 'true',
  2750. ];
  2751. }
  2752. /**
  2753. * Builds a standard summary input with a label.
  2754. *
  2755. * @param string $summary The value of the summary input
  2756. * @param string $labelText The html to place inside the label
  2757. * @param array $inputAttrs Array of attrs to use on the input
  2758. *
  2759. * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
  2760. */
  2761. function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
  2762. $inputAttrs = OOUI\Element::configFromHtmlAttributes(
  2763. $this->getSummaryInputAttributes( $inputAttrs )
  2764. );
  2765. $inputAttrs += [
  2766. 'title' => Linker::titleAttrib( 'summary' ),
  2767. 'accessKey' => Linker::accesskey( 'summary' ),
  2768. ];
  2769. // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
  2770. $inputAttrs['inputId'] = $inputAttrs['id'];
  2771. $inputAttrs['id'] = 'wpSummaryWidget';
  2772. return new OOUI\FieldLayout(
  2773. new OOUI\TextInputWidget( [
  2774. 'value' => $summary,
  2775. 'infusable' => true,
  2776. ] + $inputAttrs ),
  2777. [
  2778. 'label' => new OOUI\HtmlSnippet( $labelText ),
  2779. 'align' => 'top',
  2780. 'id' => 'wpSummaryLabel',
  2781. 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
  2782. ]
  2783. );
  2784. }
  2785. /**
  2786. * @param bool $isSubjectPreview True if this is the section subject/title
  2787. * up top, or false if this is the comment summary
  2788. * down below the textarea
  2789. * @param string $summary The text of the summary to display
  2790. */
  2791. protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
  2792. # Add a class if 'missingsummary' is triggered to allow styling of the summary line
  2793. $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
  2794. if ( $isSubjectPreview ) {
  2795. if ( $this->nosummary ) {
  2796. return;
  2797. }
  2798. } else {
  2799. if ( !$this->mShowSummaryField ) {
  2800. return;
  2801. }
  2802. }
  2803. $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
  2804. $this->context->getOutput()->addHTML( $this->getSummaryInputWidget(
  2805. $summary,
  2806. $labelText,
  2807. [ 'class' => $summaryClass ]
  2808. ) );
  2809. }
  2810. /**
  2811. * @param bool $isSubjectPreview True if this is the section subject/title
  2812. * up top, or false if this is the comment summary
  2813. * down below the textarea
  2814. * @param string $summary The text of the summary to display
  2815. * @return string
  2816. */
  2817. protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
  2818. // avoid spaces in preview, gets always trimmed on save
  2819. $summary = trim( $summary );
  2820. if ( !$summary || ( !$this->preview && !$this->diff ) ) {
  2821. return "";
  2822. }
  2823. global $wgParser;
  2824. if ( $isSubjectPreview ) {
  2825. $summary = $this->context->msg( 'newsectionsummary' )
  2826. ->rawParams( $wgParser->stripSectionName( $summary ) )
  2827. ->inContentLanguage()->text();
  2828. }
  2829. $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
  2830. $summary = $this->context->msg( $message )->parse()
  2831. . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
  2832. return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
  2833. }
  2834. protected function showFormBeforeText() {
  2835. $out = $this->context->getOutput();
  2836. $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
  2837. $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
  2838. $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
  2839. $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
  2840. $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
  2841. }
  2842. protected function showFormAfterText() {
  2843. /**
  2844. * To make it harder for someone to slip a user a page
  2845. * which submits an edit form to the wiki without their
  2846. * knowledge, a random token is associated with the login
  2847. * session. If it's not passed back with the submission,
  2848. * we won't save the page, or render user JavaScript and
  2849. * CSS previews.
  2850. *
  2851. * For anon editors, who may not have a session, we just
  2852. * include the constant suffix to prevent editing from
  2853. * broken text-mangling proxies.
  2854. */
  2855. $this->context->getOutput()->addHTML(
  2856. "\n" .
  2857. Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
  2858. "\n"
  2859. );
  2860. }
  2861. /**
  2862. * Subpage overridable method for printing the form for page content editing
  2863. * By default this simply outputs wpTextbox1
  2864. * Subclasses can override this to provide a custom UI for editing;
  2865. * be it a form, or simply wpTextbox1 with a modified content that will be
  2866. * reverse modified when extracted from the post data.
  2867. * Note that this is basically the inverse for importContentFormData
  2868. */
  2869. protected function showContentForm() {
  2870. $this->showTextbox1();
  2871. }
  2872. /**
  2873. * Method to output wpTextbox1
  2874. * The $textoverride method can be used by subclasses overriding showContentForm
  2875. * to pass back to this method.
  2876. *
  2877. * @param array $customAttribs Array of html attributes to use in the textarea
  2878. * @param string $textoverride Optional text to override $this->textarea1 with
  2879. */
  2880. protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
  2881. if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
  2882. $attribs = [ 'style' => 'display:none;' ];
  2883. } else {
  2884. $builder = new TextboxBuilder();
  2885. $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
  2886. # Is an old revision being edited?
  2887. if ( $this->isOldRev ) {
  2888. $classes[] = 'mw-textarea-oldrev';
  2889. }
  2890. $attribs = [ 'tabindex' => 1 ];
  2891. if ( is_array( $customAttribs ) ) {
  2892. $attribs += $customAttribs;
  2893. }
  2894. $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
  2895. }
  2896. $this->showTextbox(
  2897. $textoverride !== null ? $textoverride : $this->textbox1,
  2898. 'wpTextbox1',
  2899. $attribs
  2900. );
  2901. }
  2902. protected function showTextbox2() {
  2903. $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
  2904. }
  2905. protected function showTextbox( $text, $name, $customAttribs = [] ) {
  2906. $builder = new TextboxBuilder();
  2907. $attribs = $builder->buildTextboxAttribs(
  2908. $name,
  2909. $customAttribs,
  2910. $this->context->getUser(),
  2911. $this->mTitle
  2912. );
  2913. $this->context->getOutput()->addHTML(
  2914. Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
  2915. );
  2916. }
  2917. protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
  2918. $classes = [];
  2919. if ( $isOnTop ) {
  2920. $classes[] = 'ontop';
  2921. }
  2922. $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
  2923. if ( $this->formtype != 'preview' ) {
  2924. $attribs['style'] = 'display: none;';
  2925. }
  2926. $out = $this->context->getOutput();
  2927. $out->addHTML( Xml::openElement( 'div', $attribs ) );
  2928. if ( $this->formtype == 'preview' ) {
  2929. $this->showPreview( $previewOutput );
  2930. } else {
  2931. // Empty content container for LivePreview
  2932. $pageViewLang = $this->mTitle->getPageViewLanguage();
  2933. $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
  2934. 'class' => 'mw-content-' . $pageViewLang->getDir() ];
  2935. $out->addHTML( Html::rawElement( 'div', $attribs ) );
  2936. }
  2937. $out->addHTML( '</div>' );
  2938. if ( $this->formtype == 'diff' ) {
  2939. try {
  2940. $this->showDiff();
  2941. } catch ( MWContentSerializationException $ex ) {
  2942. $msg = $this->context->msg(
  2943. 'content-failed-to-parse',
  2944. $this->contentModel,
  2945. $this->contentFormat,
  2946. $ex->getMessage()
  2947. );
  2948. $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
  2949. }
  2950. }
  2951. }
  2952. /**
  2953. * Append preview output to OutputPage.
  2954. * Includes category rendering if this is a category page.
  2955. *
  2956. * @param string $text The HTML to be output for the preview.
  2957. */
  2958. protected function showPreview( $text ) {
  2959. if ( $this->mArticle instanceof CategoryPage ) {
  2960. $this->mArticle->openShowCategory();
  2961. }
  2962. # This hook seems slightly odd here, but makes things more
  2963. # consistent for extensions.
  2964. $out = $this->context->getOutput();
  2965. Hooks::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
  2966. $out->addHTML( $text );
  2967. if ( $this->mArticle instanceof CategoryPage ) {
  2968. $this->mArticle->closeShowCategory();
  2969. }
  2970. }
  2971. /**
  2972. * Get a diff between the current contents of the edit box and the
  2973. * version of the page we're editing from.
  2974. *
  2975. * If this is a section edit, we'll replace the section as for final
  2976. * save and then make a comparison.
  2977. */
  2978. public function showDiff() {
  2979. global $wgContLang;
  2980. $oldtitlemsg = 'currentrev';
  2981. # if message does not exist, show diff against the preloaded default
  2982. if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
  2983. $oldtext = $this->mTitle->getDefaultMessageText();
  2984. if ( $oldtext !== false ) {
  2985. $oldtitlemsg = 'defaultmessagetext';
  2986. $oldContent = $this->toEditContent( $oldtext );
  2987. } else {
  2988. $oldContent = null;
  2989. }
  2990. } else {
  2991. $oldContent = $this->getCurrentContent();
  2992. }
  2993. $textboxContent = $this->toEditContent( $this->textbox1 );
  2994. if ( $this->editRevId !== null ) {
  2995. $newContent = $this->page->replaceSectionAtRev(
  2996. $this->section, $textboxContent, $this->summary, $this->editRevId
  2997. );
  2998. } else {
  2999. $newContent = $this->page->replaceSectionContent(
  3000. $this->section, $textboxContent, $this->summary, $this->edittime
  3001. );
  3002. }
  3003. if ( $newContent ) {
  3004. Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
  3005. $user = $this->context->getUser();
  3006. $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
  3007. $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts );
  3008. }
  3009. if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
  3010. $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
  3011. $newtitle = $this->context->msg( 'yourtext' )->parse();
  3012. if ( !$oldContent ) {
  3013. $oldContent = $newContent->getContentHandler()->makeEmptyContent();
  3014. }
  3015. if ( !$newContent ) {
  3016. $newContent = $oldContent->getContentHandler()->makeEmptyContent();
  3017. }
  3018. $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
  3019. $de->setContent( $oldContent, $newContent );
  3020. $difftext = $de->getDiff( $oldtitle, $newtitle );
  3021. $de->showDiffStyle();
  3022. } else {
  3023. $difftext = '';
  3024. }
  3025. $this->context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
  3026. }
  3027. /**
  3028. * Show the header copyright warning.
  3029. */
  3030. protected function showHeaderCopyrightWarning() {
  3031. $msg = 'editpage-head-copy-warn';
  3032. if ( !$this->context->msg( $msg )->isDisabled() ) {
  3033. $this->context->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
  3034. 'editpage-head-copy-warn' );
  3035. }
  3036. }
  3037. /**
  3038. * Give a chance for site and per-namespace customizations of
  3039. * terms of service summary link that might exist separately
  3040. * from the copyright notice.
  3041. *
  3042. * This will display between the save button and the edit tools,
  3043. * so should remain short!
  3044. */
  3045. protected function showTosSummary() {
  3046. $msg = 'editpage-tos-summary';
  3047. Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
  3048. if ( !$this->context->msg( $msg )->isDisabled() ) {
  3049. $out = $this->context->getOutput();
  3050. $out->addHTML( '<div class="mw-tos-summary">' );
  3051. $out->addWikiMsg( $msg );
  3052. $out->addHTML( '</div>' );
  3053. }
  3054. }
  3055. /**
  3056. * Inserts optional text shown below edit and upload forms. Can be used to offer special
  3057. * characters not present on most keyboards for copying/pasting.
  3058. */
  3059. protected function showEditTools() {
  3060. $this->context->getOutput()->addHTML( '<div class="mw-editTools">' .
  3061. $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
  3062. '</div>' );
  3063. }
  3064. /**
  3065. * Get the copyright warning
  3066. *
  3067. * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
  3068. * @return string
  3069. */
  3070. protected function getCopywarn() {
  3071. return self::getCopyrightWarning( $this->mTitle );
  3072. }
  3073. /**
  3074. * Get the copyright warning, by default returns wikitext
  3075. *
  3076. * @param Title $title
  3077. * @param string $format Output format, valid values are any function of a Message object
  3078. * @param Language|string|null $langcode Language code or Language object.
  3079. * @return string
  3080. */
  3081. public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
  3082. global $wgRightsText;
  3083. if ( $wgRightsText ) {
  3084. $copywarnMsg = [ 'copyrightwarning',
  3085. '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
  3086. $wgRightsText ];
  3087. } else {
  3088. $copywarnMsg = [ 'copyrightwarning2',
  3089. '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
  3090. }
  3091. // Allow for site and per-namespace customization of contribution/copyright notice.
  3092. Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
  3093. $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
  3094. if ( $langcode ) {
  3095. $msg->inLanguage( $langcode );
  3096. }
  3097. return "<div id=\"editpage-copywarn\">\n" .
  3098. $msg->$format() . "\n</div>";
  3099. }
  3100. /**
  3101. * Get the Limit report for page previews
  3102. *
  3103. * @since 1.22
  3104. * @param ParserOutput $output ParserOutput object from the parse
  3105. * @return string HTML
  3106. */
  3107. public static function getPreviewLimitReport( $output ) {
  3108. global $wgLang;
  3109. if ( !$output || !$output->getLimitReportData() ) {
  3110. return '';
  3111. }
  3112. $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
  3113. wfMessage( 'limitreport-title' )->parseAsBlock()
  3114. );
  3115. // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
  3116. $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
  3117. $limitReport .= Html::openElement( 'table', [
  3118. 'class' => 'preview-limit-report wikitable'
  3119. ] ) .
  3120. Html::openElement( 'tbody' );
  3121. foreach ( $output->getLimitReportData() as $key => $value ) {
  3122. if ( Hooks::run( 'ParserLimitReportFormat',
  3123. [ $key, &$value, &$limitReport, true, true ]
  3124. ) ) {
  3125. $keyMsg = wfMessage( $key );
  3126. $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
  3127. if ( !$valueMsg->exists() ) {
  3128. $valueMsg = new RawMessage( '$1' );
  3129. }
  3130. if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
  3131. $limitReport .= Html::openElement( 'tr' ) .
  3132. Html::rawElement( 'th', null, $keyMsg->parse() ) .
  3133. Html::rawElement( 'td', null,
  3134. $wgLang->formatNum( $valueMsg->params( $value )->parse() )
  3135. ) .
  3136. Html::closeElement( 'tr' );
  3137. }
  3138. }
  3139. }
  3140. $limitReport .= Html::closeElement( 'tbody' ) .
  3141. Html::closeElement( 'table' ) .
  3142. Html::closeElement( 'div' );
  3143. return $limitReport;
  3144. }
  3145. protected function showStandardInputs( &$tabindex = 2 ) {
  3146. $out = $this->context->getOutput();
  3147. $out->addHTML( "<div class='editOptions'>\n" );
  3148. if ( $this->section != 'new' ) {
  3149. $this->showSummaryInput( false, $this->summary );
  3150. $out->addHTML( $this->getSummaryPreview( false, $this->summary ) );
  3151. }
  3152. $checkboxes = $this->getCheckboxesWidget(
  3153. $tabindex,
  3154. [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
  3155. );
  3156. $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
  3157. $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
  3158. // Show copyright warning.
  3159. $out->addWikiText( $this->getCopywarn() );
  3160. $out->addHTML( $this->editFormTextAfterWarn );
  3161. $out->addHTML( "<div class='editButtons'>\n" );
  3162. $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
  3163. $cancel = $this->getCancelLink();
  3164. $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
  3165. $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
  3166. $edithelp =
  3167. Html::linkButton(
  3168. $this->context->msg( 'edithelp' )->text(),
  3169. [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
  3170. [ 'mw-ui-quiet' ]
  3171. ) .
  3172. $this->context->msg( 'word-separator' )->escaped() .
  3173. $this->context->msg( 'newwindow' )->parse();
  3174. $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
  3175. $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
  3176. $out->addHTML( "</div><!-- editButtons -->\n" );
  3177. Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
  3178. $out->addHTML( "</div><!-- editOptions -->\n" );
  3179. }
  3180. /**
  3181. * Show an edit conflict. textbox1 is already shown in showEditForm().
  3182. * If you want to use another entry point to this function, be careful.
  3183. */
  3184. protected function showConflict() {
  3185. $out = $this->context->getOutput();
  3186. // Avoid PHP 7.1 warning of passing $this by reference
  3187. $editPage = $this;
  3188. if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
  3189. $this->incrementConflictStats();
  3190. $this->getEditConflictHelper()->showEditFormTextAfterFooters();
  3191. }
  3192. }
  3193. protected function incrementConflictStats() {
  3194. $this->getEditConflictHelper()->incrementConflictStats();
  3195. }
  3196. /**
  3197. * @return string
  3198. */
  3199. public function getCancelLink() {
  3200. $cancelParams = [];
  3201. if ( !$this->isConflict && $this->oldid > 0 ) {
  3202. $cancelParams['oldid'] = $this->oldid;
  3203. } elseif ( $this->getContextTitle()->isRedirect() ) {
  3204. $cancelParams['redirect'] = 'no';
  3205. }
  3206. return new OOUI\ButtonWidget( [
  3207. 'id' => 'mw-editform-cancel',
  3208. 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
  3209. 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
  3210. 'framed' => false,
  3211. 'infusable' => true,
  3212. 'flags' => 'destructive',
  3213. ] );
  3214. }
  3215. /**
  3216. * Returns the URL to use in the form's action attribute.
  3217. * This is used by EditPage subclasses when simply customizing the action
  3218. * variable in the constructor is not enough. This can be used when the
  3219. * EditPage lives inside of a Special page rather than a custom page action.
  3220. *
  3221. * @param Title $title Title object for which is being edited (where we go to for &action= links)
  3222. * @return string
  3223. */
  3224. protected function getActionURL( Title $title ) {
  3225. return $title->getLocalURL( [ 'action' => $this->action ] );
  3226. }
  3227. /**
  3228. * Check if a page was deleted while the user was editing it, before submit.
  3229. * Note that we rely on the logging table, which hasn't been always there,
  3230. * but that doesn't matter, because this only applies to brand new
  3231. * deletes.
  3232. * @return bool
  3233. */
  3234. protected function wasDeletedSinceLastEdit() {
  3235. if ( $this->deletedSinceEdit !== null ) {
  3236. return $this->deletedSinceEdit;
  3237. }
  3238. $this->deletedSinceEdit = false;
  3239. if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
  3240. $this->lastDelete = $this->getLastDelete();
  3241. if ( $this->lastDelete ) {
  3242. $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
  3243. if ( $deleteTime > $this->starttime ) {
  3244. $this->deletedSinceEdit = true;
  3245. }
  3246. }
  3247. }
  3248. return $this->deletedSinceEdit;
  3249. }
  3250. /**
  3251. * @return bool|stdClass
  3252. */
  3253. protected function getLastDelete() {
  3254. $dbr = wfGetDB( DB_REPLICA );
  3255. $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
  3256. $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
  3257. $data = $dbr->selectRow(
  3258. array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
  3259. [
  3260. 'log_type',
  3261. 'log_action',
  3262. 'log_timestamp',
  3263. 'log_namespace',
  3264. 'log_title',
  3265. 'log_params',
  3266. 'log_deleted',
  3267. 'user_name'
  3268. ] + $commentQuery['fields'] + $actorQuery['fields'],
  3269. [
  3270. 'log_namespace' => $this->mTitle->getNamespace(),
  3271. 'log_title' => $this->mTitle->getDBkey(),
  3272. 'log_type' => 'delete',
  3273. 'log_action' => 'delete',
  3274. ],
  3275. __METHOD__,
  3276. [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
  3277. [
  3278. 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
  3279. ] + $commentQuery['joins'] + $actorQuery['joins']
  3280. );
  3281. // Quick paranoid permission checks...
  3282. if ( is_object( $data ) ) {
  3283. if ( $data->log_deleted & LogPage::DELETED_USER ) {
  3284. $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
  3285. }
  3286. if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
  3287. $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
  3288. $data->log_comment_data = null;
  3289. }
  3290. }
  3291. return $data;
  3292. }
  3293. /**
  3294. * Get the rendered text for previewing.
  3295. * @throws MWException
  3296. * @return string
  3297. */
  3298. public function getPreviewText() {
  3299. $out = $this->context->getOutput();
  3300. $config = $this->context->getConfig();
  3301. if ( $config->get( 'RawHtml' ) && !$this->mTokenOk ) {
  3302. // Could be an offsite preview attempt. This is very unsafe if
  3303. // HTML is enabled, as it could be an attack.
  3304. $parsedNote = '';
  3305. if ( $this->textbox1 !== '' ) {
  3306. // Do not put big scary notice, if previewing the empty
  3307. // string, which happens when you initially edit
  3308. // a category page, due to automatic preview-on-open.
  3309. $parsedNote = $out->parse( "<div class='previewnote'>" .
  3310. $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
  3311. true, /* interface */true );
  3312. }
  3313. $this->incrementEditFailureStats( 'session_loss' );
  3314. return $parsedNote;
  3315. }
  3316. $note = '';
  3317. try {
  3318. $content = $this->toEditContent( $this->textbox1 );
  3319. $previewHTML = '';
  3320. if ( !Hooks::run(
  3321. 'AlternateEditPreview',
  3322. [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
  3323. ) {
  3324. return $previewHTML;
  3325. }
  3326. # provide a anchor link to the editform
  3327. $continueEditing = '<span class="mw-continue-editing">' .
  3328. '[[#' . self::EDITFORM_ID . '|' .
  3329. $this->context->getLanguage()->getArrow() . ' ' .
  3330. $this->context->msg( 'continue-editing' )->text() . ']]</span>';
  3331. if ( $this->mTriedSave && !$this->mTokenOk ) {
  3332. if ( $this->mTokenOkExceptSuffix ) {
  3333. $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
  3334. $this->incrementEditFailureStats( 'bad_token' );
  3335. } else {
  3336. $note = $this->context->msg( 'session_fail_preview' )->plain();
  3337. $this->incrementEditFailureStats( 'session_loss' );
  3338. }
  3339. } elseif ( $this->incompleteForm ) {
  3340. $note = $this->context->msg( 'edit_form_incomplete' )->plain();
  3341. if ( $this->mTriedSave ) {
  3342. $this->incrementEditFailureStats( 'incomplete_form' );
  3343. }
  3344. } else {
  3345. $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
  3346. }
  3347. # don't parse non-wikitext pages, show message about preview
  3348. if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
  3349. if ( $this->mTitle->isUserConfigPage() ) {
  3350. $level = 'user';
  3351. } elseif ( $this->mTitle->isSiteConfigPage() ) {
  3352. $level = 'site';
  3353. } else {
  3354. $level = false;
  3355. }
  3356. if ( $content->getModel() == CONTENT_MODEL_CSS ) {
  3357. $format = 'css';
  3358. if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
  3359. $format = false;
  3360. }
  3361. } elseif ( $content->getModel() == CONTENT_MODEL_JSON ) {
  3362. $format = 'json';
  3363. if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
  3364. $format = false;
  3365. }
  3366. } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
  3367. $format = 'js';
  3368. if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
  3369. $format = false;
  3370. }
  3371. } else {
  3372. $format = false;
  3373. }
  3374. # Used messages to make sure grep find them:
  3375. # Messages: usercsspreview, userjsonpreview, userjspreview,
  3376. # sitecsspreview, sitejsonpreview, sitejspreview
  3377. if ( $level && $format ) {
  3378. $note = "<div id='mw-{$level}{$format}preview'>" .
  3379. $this->context->msg( "{$level}{$format}preview" )->text() .
  3380. ' ' . $continueEditing . "</div>";
  3381. }
  3382. }
  3383. # If we're adding a comment, we need to show the
  3384. # summary as the headline
  3385. if ( $this->section === "new" && $this->summary !== "" ) {
  3386. $content = $content->addSectionHeader( $this->summary );
  3387. }
  3388. $hook_args = [ $this, &$content ];
  3389. Hooks::run( 'EditPageGetPreviewContent', $hook_args );
  3390. $parserResult = $this->doPreviewParse( $content );
  3391. $parserOutput = $parserResult['parserOutput'];
  3392. $previewHTML = $parserResult['html'];
  3393. $this->mParserOutput = $parserOutput;
  3394. $out->addParserOutputMetadata( $parserOutput );
  3395. if ( count( $parserOutput->getWarnings() ) ) {
  3396. $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
  3397. }
  3398. } catch ( MWContentSerializationException $ex ) {
  3399. $m = $this->context->msg(
  3400. 'content-failed-to-parse',
  3401. $this->contentModel,
  3402. $this->contentFormat,
  3403. $ex->getMessage()
  3404. );
  3405. $note .= "\n\n" . $m->parse();
  3406. $previewHTML = '';
  3407. }
  3408. if ( $this->isConflict ) {
  3409. $conflict = '<h2 id="mw-previewconflict">'
  3410. . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
  3411. } else {
  3412. $conflict = '<hr />';
  3413. }
  3414. $previewhead = "<div class='previewnote'>\n" .
  3415. '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
  3416. $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
  3417. $pageViewLang = $this->mTitle->getPageViewLanguage();
  3418. $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
  3419. 'class' => 'mw-content-' . $pageViewLang->getDir() ];
  3420. $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
  3421. return $previewhead . $previewHTML . $this->previewTextAfterContent;
  3422. }
  3423. private function incrementEditFailureStats( $failureType ) {
  3424. $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
  3425. $stats->increment( 'edit.failures.' . $failureType );
  3426. }
  3427. /**
  3428. * Get parser options for a preview
  3429. * @return ParserOptions
  3430. */
  3431. protected function getPreviewParserOptions() {
  3432. $parserOptions = $this->page->makeParserOptions( $this->context );
  3433. $parserOptions->setIsPreview( true );
  3434. $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
  3435. $parserOptions->enableLimitReport();
  3436. return $parserOptions;
  3437. }
  3438. /**
  3439. * Parse the page for a preview. Subclasses may override this class, in order
  3440. * to parse with different options, or to otherwise modify the preview HTML.
  3441. *
  3442. * @param Content $content The page content
  3443. * @return array with keys:
  3444. * - parserOutput: The ParserOutput object
  3445. * - html: The HTML to be displayed
  3446. */
  3447. protected function doPreviewParse( Content $content ) {
  3448. $user = $this->context->getUser();
  3449. $parserOptions = $this->getPreviewParserOptions();
  3450. $pstContent = $content->preSaveTransform( $this->mTitle, $user, $parserOptions );
  3451. $scopedCallback = $parserOptions->setupFakeRevision(
  3452. $this->mTitle, $pstContent, $user );
  3453. $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
  3454. ScopedCallback::consume( $scopedCallback );
  3455. return [
  3456. 'parserOutput' => $parserOutput,
  3457. 'html' => $parserOutput->getText( [
  3458. 'enableSectionEditLinks' => false
  3459. ] )
  3460. ];
  3461. }
  3462. /**
  3463. * @return array
  3464. */
  3465. public function getTemplates() {
  3466. if ( $this->preview || $this->section != '' ) {
  3467. $templates = [];
  3468. if ( !isset( $this->mParserOutput ) ) {
  3469. return $templates;
  3470. }
  3471. foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
  3472. foreach ( array_keys( $template ) as $dbk ) {
  3473. $templates[] = Title::makeTitle( $ns, $dbk );
  3474. }
  3475. }
  3476. return $templates;
  3477. } else {
  3478. return $this->mTitle->getTemplateLinksFrom();
  3479. }
  3480. }
  3481. /**
  3482. * Shows a bulletin board style toolbar for common editing functions.
  3483. * It can be disabled in the user preferences.
  3484. *
  3485. * @param Title $title Title object for the page being edited (optional)
  3486. * @return string
  3487. */
  3488. public static function getEditToolbar( $title = null ) {
  3489. global $wgContLang, $wgOut;
  3490. global $wgEnableUploads, $wgForeignFileRepos;
  3491. $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
  3492. $showSignature = true;
  3493. if ( $title ) {
  3494. $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
  3495. }
  3496. /**
  3497. * $toolarray is an array of arrays each of which includes the
  3498. * opening tag, the closing tag, optionally a sample text that is
  3499. * inserted between the two when no selection is highlighted
  3500. * and. The tip text is shown when the user moves the mouse
  3501. * over the button.
  3502. *
  3503. * Images are defined in ResourceLoaderEditToolbarModule.
  3504. */
  3505. $toolarray = [
  3506. [
  3507. 'id' => 'mw-editbutton-bold',
  3508. 'open' => '\'\'\'',
  3509. 'close' => '\'\'\'',
  3510. 'sample' => wfMessage( 'bold_sample' )->text(),
  3511. 'tip' => wfMessage( 'bold_tip' )->text(),
  3512. ],
  3513. [
  3514. 'id' => 'mw-editbutton-italic',
  3515. 'open' => '\'\'',
  3516. 'close' => '\'\'',
  3517. 'sample' => wfMessage( 'italic_sample' )->text(),
  3518. 'tip' => wfMessage( 'italic_tip' )->text(),
  3519. ],
  3520. [
  3521. 'id' => 'mw-editbutton-link',
  3522. 'open' => '[[',
  3523. 'close' => ']]',
  3524. 'sample' => wfMessage( 'link_sample' )->text(),
  3525. 'tip' => wfMessage( 'link_tip' )->text(),
  3526. ],
  3527. [
  3528. 'id' => 'mw-editbutton-extlink',
  3529. 'open' => '[',
  3530. 'close' => ']',
  3531. 'sample' => wfMessage( 'extlink_sample' )->text(),
  3532. 'tip' => wfMessage( 'extlink_tip' )->text(),
  3533. ],
  3534. [
  3535. 'id' => 'mw-editbutton-headline',
  3536. 'open' => "\n== ",
  3537. 'close' => " ==\n",
  3538. 'sample' => wfMessage( 'headline_sample' )->text(),
  3539. 'tip' => wfMessage( 'headline_tip' )->text(),
  3540. ],
  3541. $imagesAvailable ? [
  3542. 'id' => 'mw-editbutton-image',
  3543. 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
  3544. 'close' => ']]',
  3545. 'sample' => wfMessage( 'image_sample' )->text(),
  3546. 'tip' => wfMessage( 'image_tip' )->text(),
  3547. ] : false,
  3548. $imagesAvailable ? [
  3549. 'id' => 'mw-editbutton-media',
  3550. 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
  3551. 'close' => ']]',
  3552. 'sample' => wfMessage( 'media_sample' )->text(),
  3553. 'tip' => wfMessage( 'media_tip' )->text(),
  3554. ] : false,
  3555. [
  3556. 'id' => 'mw-editbutton-nowiki',
  3557. 'open' => "<nowiki>",
  3558. 'close' => "</nowiki>",
  3559. 'sample' => wfMessage( 'nowiki_sample' )->text(),
  3560. 'tip' => wfMessage( 'nowiki_tip' )->text(),
  3561. ],
  3562. $showSignature ? [
  3563. 'id' => 'mw-editbutton-signature',
  3564. 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
  3565. 'close' => '',
  3566. 'sample' => '',
  3567. 'tip' => wfMessage( 'sig_tip' )->text(),
  3568. ] : false,
  3569. [
  3570. 'id' => 'mw-editbutton-hr',
  3571. 'open' => "\n----\n",
  3572. 'close' => '',
  3573. 'sample' => '',
  3574. 'tip' => wfMessage( 'hr_tip' )->text(),
  3575. ]
  3576. ];
  3577. $script = 'mw.loader.using("mediawiki.toolbar", function () {';
  3578. foreach ( $toolarray as $tool ) {
  3579. if ( !$tool ) {
  3580. continue;
  3581. }
  3582. $params = [
  3583. // Images are defined in ResourceLoaderEditToolbarModule
  3584. false,
  3585. // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
  3586. // Older browsers show a "speedtip" type message only for ALT.
  3587. // Ideally these should be different, realistically they
  3588. // probably don't need to be.
  3589. $tool['tip'],
  3590. $tool['open'],
  3591. $tool['close'],
  3592. $tool['sample'],
  3593. $tool['id'],
  3594. ];
  3595. $script .= Xml::encodeJsCall(
  3596. 'mw.toolbar.addButton',
  3597. $params,
  3598. ResourceLoader::inDebugMode()
  3599. );
  3600. }
  3601. $script .= '});';
  3602. $toolbar = '<div id="toolbar"></div>';
  3603. if ( Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
  3604. // Only add the old toolbar cruft to the page payload if the toolbar has not
  3605. // been over-written by a hook caller
  3606. $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
  3607. };
  3608. return $toolbar;
  3609. }
  3610. /**
  3611. * Return an array of checkbox definitions.
  3612. *
  3613. * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
  3614. *
  3615. * Array values are associative arrays with the following keys:
  3616. * - 'label-message' (required): message for label text
  3617. * - 'id' (required): 'id' attribute for the `<input>`
  3618. * - 'default' (required): default checkedness (true or false)
  3619. * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
  3620. * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
  3621. * from messages like 'tooltip-foo', 'accesskey-foo'
  3622. * - 'label-id' (optional): 'id' attribute for the `<label>`
  3623. * - 'legacy-name' (optional): short name for backwards-compatibility
  3624. * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
  3625. * where bool indicates the checked status of the checkbox
  3626. * @return array
  3627. */
  3628. public function getCheckboxesDefinition( $checked ) {
  3629. $checkboxes = [];
  3630. $user = $this->context->getUser();
  3631. // don't show the minor edit checkbox if it's a new page or section
  3632. if ( !$this->isNew && $user->isAllowed( 'minoredit' ) ) {
  3633. $checkboxes['wpMinoredit'] = [
  3634. 'id' => 'wpMinoredit',
  3635. 'label-message' => 'minoredit',
  3636. // Uses messages: tooltip-minoredit, accesskey-minoredit
  3637. 'tooltip' => 'minoredit',
  3638. 'label-id' => 'mw-editpage-minoredit',
  3639. 'legacy-name' => 'minor',
  3640. 'default' => $checked['minor'],
  3641. ];
  3642. }
  3643. if ( $user->isLoggedIn() ) {
  3644. $checkboxes['wpWatchthis'] = [
  3645. 'id' => 'wpWatchthis',
  3646. 'label-message' => 'watchthis',
  3647. // Uses messages: tooltip-watch, accesskey-watch
  3648. 'tooltip' => 'watch',
  3649. 'label-id' => 'mw-editpage-watch',
  3650. 'legacy-name' => 'watch',
  3651. 'default' => $checked['watch'],
  3652. ];
  3653. }
  3654. $editPage = $this;
  3655. Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
  3656. return $checkboxes;
  3657. }
  3658. /**
  3659. * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
  3660. * any other added by extensions.
  3661. *
  3662. * @param int &$tabindex Current tabindex
  3663. * @param array $checked Array of checkbox => bool, where bool indicates the checked
  3664. * status of the checkbox
  3665. *
  3666. * @return array Associative array of string keys to OOUI\FieldLayout instances
  3667. */
  3668. public function getCheckboxesWidget( &$tabindex, $checked ) {
  3669. $checkboxes = [];
  3670. $checkboxesDef = $this->getCheckboxesDefinition( $checked );
  3671. foreach ( $checkboxesDef as $name => $options ) {
  3672. $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name;
  3673. $title = null;
  3674. $accesskey = null;
  3675. if ( isset( $options['tooltip'] ) ) {
  3676. $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
  3677. $title = Linker::titleAttrib( $options['tooltip'] );
  3678. }
  3679. if ( isset( $options['title-message'] ) ) {
  3680. $title = $this->context->msg( $options['title-message'] )->text();
  3681. }
  3682. $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
  3683. new OOUI\CheckboxInputWidget( [
  3684. 'tabIndex' => ++$tabindex,
  3685. 'accessKey' => $accesskey,
  3686. 'id' => $options['id'] . 'Widget',
  3687. 'inputId' => $options['id'],
  3688. 'name' => $name,
  3689. 'selected' => $options['default'],
  3690. 'infusable' => true,
  3691. ] ),
  3692. [
  3693. 'align' => 'inline',
  3694. 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
  3695. 'title' => $title,
  3696. 'id' => isset( $options['label-id'] ) ? $options['label-id'] : null,
  3697. ]
  3698. );
  3699. }
  3700. // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
  3701. // people have used it for the weirdest things completely unrelated to checkboxes...
  3702. // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
  3703. $legacyCheckboxes = [];
  3704. if ( !$this->isNew ) {
  3705. $legacyCheckboxes['minor'] = '';
  3706. }
  3707. $legacyCheckboxes['watch'] = '';
  3708. // Copy new-style checkboxes into an old-style structure
  3709. foreach ( $checkboxes as $name => $oouiLayout ) {
  3710. $legacyCheckboxes[$name] = (string)$oouiLayout;
  3711. }
  3712. // Avoid PHP 7.1 warning of passing $this by reference
  3713. $ep = $this;
  3714. Hooks::run( 'EditPageBeforeEditChecks', [ &$ep, &$legacyCheckboxes, &$tabindex ], '1.29' );
  3715. // Copy back any additional old-style checkboxes into the new-style structure
  3716. foreach ( $legacyCheckboxes as $name => $html ) {
  3717. if ( $html && !isset( $checkboxes[$name] ) ) {
  3718. $checkboxes[$name] = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $html ) ] );
  3719. }
  3720. }
  3721. return $checkboxes;
  3722. }
  3723. /**
  3724. * Get the message key of the label for the button to save the page
  3725. *
  3726. * @since 1.30
  3727. * @return string
  3728. */
  3729. protected function getSubmitButtonLabel() {
  3730. $labelAsPublish =
  3731. $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
  3732. // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
  3733. $newPage = !$this->mTitle->exists();
  3734. if ( $labelAsPublish ) {
  3735. $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
  3736. } else {
  3737. $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
  3738. }
  3739. return $buttonLabelKey;
  3740. }
  3741. /**
  3742. * Returns an array of html code of the following buttons:
  3743. * save, diff and preview
  3744. *
  3745. * @param int &$tabindex Current tabindex
  3746. *
  3747. * @return array
  3748. */
  3749. public function getEditButtons( &$tabindex ) {
  3750. $buttons = [];
  3751. $labelAsPublish =
  3752. $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
  3753. $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
  3754. $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
  3755. $buttons['save'] = new OOUI\ButtonInputWidget( [
  3756. 'name' => 'wpSave',
  3757. 'tabIndex' => ++$tabindex,
  3758. 'id' => 'wpSaveWidget',
  3759. 'inputId' => 'wpSave',
  3760. // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
  3761. 'useInputTag' => true,
  3762. 'flags' => [ 'progressive', 'primary' ],
  3763. 'label' => $buttonLabel,
  3764. 'infusable' => true,
  3765. 'type' => 'submit',
  3766. // Messages used: tooltip-save, tooltip-publish
  3767. 'title' => Linker::titleAttrib( $buttonTooltip ),
  3768. // Messages used: accesskey-save, accesskey-publish
  3769. 'accessKey' => Linker::accesskey( $buttonTooltip ),
  3770. ] );
  3771. $buttons['preview'] = new OOUI\ButtonInputWidget( [
  3772. 'name' => 'wpPreview',
  3773. 'tabIndex' => ++$tabindex,
  3774. 'id' => 'wpPreviewWidget',
  3775. 'inputId' => 'wpPreview',
  3776. // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
  3777. 'useInputTag' => true,
  3778. 'label' => $this->context->msg( 'showpreview' )->text(),
  3779. 'infusable' => true,
  3780. 'type' => 'submit',
  3781. // Message used: tooltip-preview
  3782. 'title' => Linker::titleAttrib( 'preview' ),
  3783. // Message used: accesskey-preview
  3784. 'accessKey' => Linker::accesskey( 'preview' ),
  3785. ] );
  3786. $buttons['diff'] = new OOUI\ButtonInputWidget( [
  3787. 'name' => 'wpDiff',
  3788. 'tabIndex' => ++$tabindex,
  3789. 'id' => 'wpDiffWidget',
  3790. 'inputId' => 'wpDiff',
  3791. // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
  3792. 'useInputTag' => true,
  3793. 'label' => $this->context->msg( 'showdiff' )->text(),
  3794. 'infusable' => true,
  3795. 'type' => 'submit',
  3796. // Message used: tooltip-diff
  3797. 'title' => Linker::titleAttrib( 'diff' ),
  3798. // Message used: accesskey-diff
  3799. 'accessKey' => Linker::accesskey( 'diff' ),
  3800. ] );
  3801. // Avoid PHP 7.1 warning of passing $this by reference
  3802. $editPage = $this;
  3803. Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
  3804. return $buttons;
  3805. }
  3806. /**
  3807. * Creates a basic error page which informs the user that
  3808. * they have attempted to edit a nonexistent section.
  3809. */
  3810. public function noSuchSectionPage() {
  3811. $out = $this->context->getOutput();
  3812. $out->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
  3813. $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
  3814. // Avoid PHP 7.1 warning of passing $this by reference
  3815. $editPage = $this;
  3816. Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
  3817. $out->addHTML( $res );
  3818. $out->returnToMain( false, $this->mTitle );
  3819. }
  3820. /**
  3821. * Show "your edit contains spam" page with your diff and text
  3822. *
  3823. * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
  3824. */
  3825. public function spamPageWithContent( $match = false ) {
  3826. $this->textbox2 = $this->textbox1;
  3827. if ( is_array( $match ) ) {
  3828. $match = $this->context->getLanguage()->listToText( $match );
  3829. }
  3830. $out = $this->context->getOutput();
  3831. $out->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
  3832. $out->addHTML( '<div id="spamprotected">' );
  3833. $out->addWikiMsg( 'spamprotectiontext' );
  3834. if ( $match ) {
  3835. $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
  3836. }
  3837. $out->addHTML( '</div>' );
  3838. $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
  3839. $this->showDiff();
  3840. $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
  3841. $this->showTextbox2();
  3842. $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
  3843. }
  3844. /**
  3845. * Filter an input field through a Unicode de-armoring process if it
  3846. * came from an old browser with known broken Unicode editing issues.
  3847. *
  3848. * @deprecated since 1.30, does nothing
  3849. *
  3850. * @param WebRequest $request
  3851. * @param string $field
  3852. * @return string
  3853. */
  3854. protected function safeUnicodeInput( $request, $field ) {
  3855. return rtrim( $request->getText( $field ) );
  3856. }
  3857. /**
  3858. * Filter an output field through a Unicode armoring process if it is
  3859. * going to an old browser with known broken Unicode editing issues.
  3860. *
  3861. * @deprecated since 1.30, does nothing
  3862. *
  3863. * @param string $text
  3864. * @return string
  3865. */
  3866. protected function safeUnicodeOutput( $text ) {
  3867. return $text;
  3868. }
  3869. /**
  3870. * @since 1.29
  3871. */
  3872. protected function addEditNotices() {
  3873. $out = $this->context->getOutput();
  3874. $editNotices = $this->mTitle->getEditNotices( $this->oldid );
  3875. if ( count( $editNotices ) ) {
  3876. $out->addHTML( implode( "\n", $editNotices ) );
  3877. } else {
  3878. $msg = $this->context->msg( 'editnotice-notext' );
  3879. if ( !$msg->isDisabled() ) {
  3880. $out->addHTML(
  3881. '<div class="mw-editnotice-notext">'
  3882. . $msg->parseAsBlock()
  3883. . '</div>'
  3884. );
  3885. }
  3886. }
  3887. }
  3888. /**
  3889. * @since 1.29
  3890. */
  3891. protected function addTalkPageText() {
  3892. if ( $this->mTitle->isTalkPage() ) {
  3893. $this->context->getOutput()->addWikiMsg( 'talkpagetext' );
  3894. }
  3895. }
  3896. /**
  3897. * @since 1.29
  3898. */
  3899. protected function addLongPageWarningHeader() {
  3900. if ( $this->contentLength === false ) {
  3901. $this->contentLength = strlen( $this->textbox1 );
  3902. }
  3903. $out = $this->context->getOutput();
  3904. $lang = $this->context->getLanguage();
  3905. $maxArticleSize = $this->context->getConfig()->get( 'MaxArticleSize' );
  3906. if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
  3907. $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
  3908. [
  3909. 'longpageerror',
  3910. $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
  3911. $lang->formatNum( $maxArticleSize )
  3912. ]
  3913. );
  3914. } else {
  3915. if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
  3916. $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
  3917. [
  3918. 'longpage-hint',
  3919. $lang->formatSize( strlen( $this->textbox1 ) ),
  3920. strlen( $this->textbox1 )
  3921. ]
  3922. );
  3923. }
  3924. }
  3925. }
  3926. /**
  3927. * @since 1.29
  3928. */
  3929. protected function addPageProtectionWarningHeaders() {
  3930. $out = $this->context->getOutput();
  3931. if ( $this->mTitle->isProtected( 'edit' ) &&
  3932. MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
  3933. ) {
  3934. # Is the title semi-protected?
  3935. if ( $this->mTitle->isSemiProtected() ) {
  3936. $noticeMsg = 'semiprotectedpagewarning';
  3937. } else {
  3938. # Then it must be protected based on static groups (regular)
  3939. $noticeMsg = 'protectedpagewarning';
  3940. }
  3941. LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
  3942. [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
  3943. }
  3944. if ( $this->mTitle->isCascadeProtected() ) {
  3945. # Is this page under cascading protection from some source pages?
  3946. /** @var Title[] $cascadeSources */
  3947. list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
  3948. $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
  3949. $cascadeSourcesCount = count( $cascadeSources );
  3950. if ( $cascadeSourcesCount > 0 ) {
  3951. # Explain, and list the titles responsible
  3952. foreach ( $cascadeSources as $page ) {
  3953. $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
  3954. }
  3955. }
  3956. $notice .= '</div>';
  3957. $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
  3958. }
  3959. if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
  3960. LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
  3961. [ 'lim' => 1,
  3962. 'showIfEmpty' => false,
  3963. 'msgKey' => [ 'titleprotectedwarning' ],
  3964. 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
  3965. }
  3966. }
  3967. /**
  3968. * @param OutputPage $out
  3969. * @since 1.29
  3970. */
  3971. protected function addExplainConflictHeader( OutputPage $out ) {
  3972. $out->addHTML(
  3973. $this->getEditConflictHelper()->getExplainHeader()
  3974. );
  3975. }
  3976. /**
  3977. * @param string $name
  3978. * @param mixed[] $customAttribs
  3979. * @param User $user
  3980. * @return mixed[]
  3981. * @since 1.29
  3982. */
  3983. protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
  3984. return ( new TextboxBuilder() )->buildTextboxAttribs(
  3985. $name, $customAttribs, $user, $this->mTitle
  3986. );
  3987. }
  3988. /**
  3989. * @param string $wikitext
  3990. * @return string
  3991. * @since 1.29
  3992. */
  3993. protected function addNewLineAtEnd( $wikitext ) {
  3994. return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
  3995. }
  3996. /**
  3997. * Turns section name wikitext into anchors for use in HTTP redirects. Various
  3998. * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
  3999. * resulting in mojibake in address bar. Redirect them to legacy section IDs,
  4000. * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
  4001. * spread the new style links more efficiently.
  4002. *
  4003. * @param string $text
  4004. * @return string
  4005. */
  4006. private function guessSectionName( $text ) {
  4007. global $wgParser;
  4008. // Detect Microsoft browsers
  4009. $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
  4010. if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
  4011. // ...and redirect them to legacy encoding, if available
  4012. return $wgParser->guessLegacySectionNameFromWikiText( $text );
  4013. }
  4014. // Meanwhile, real browsers get real anchors
  4015. return $wgParser->guessSectionNameFromWikiText( $text );
  4016. }
  4017. /**
  4018. * Set a factory function to create an EditConflictHelper
  4019. *
  4020. * @param callable $factory Factory function
  4021. * @since 1.31
  4022. */
  4023. public function setEditConflictHelperFactory( callable $factory ) {
  4024. $this->editConflictHelperFactory = $factory;
  4025. $this->editConflictHelper = null;
  4026. }
  4027. /**
  4028. * @return TextConflictHelper
  4029. */
  4030. private function getEditConflictHelper() {
  4031. if ( !$this->editConflictHelper ) {
  4032. $this->editConflictHelper = call_user_func(
  4033. $this->editConflictHelperFactory,
  4034. $this->getSubmitButtonLabel()
  4035. );
  4036. }
  4037. return $this->editConflictHelper;
  4038. }
  4039. /**
  4040. * @param string $submitButtonLabel
  4041. * @return TextConflictHelper
  4042. */
  4043. private function newTextConflictHelper( $submitButtonLabel ) {
  4044. return new TextConflictHelper(
  4045. $this->getTitle(),
  4046. $this->getContext()->getOutput(),
  4047. MediaWikiServices::getInstance()->getStatsdDataFactory(),
  4048. $submitButtonLabel
  4049. );
  4050. }
  4051. }