PageRenderTime 35ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/EditPage.php

https://bitbucket.org/ghostfreeman/freeside-wiki
PHP | 3281 lines | 2055 code | 395 blank | 831 comment | 470 complexity | d4e1586f44beac127ba969d76901c161 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Page edition user interface.
  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. /**
  23. * The edit page/HTML interface (split from Article)
  24. * The actual database and text munging is still in Article,
  25. * but it should get easier to call those from alternate
  26. * interfaces.
  27. *
  28. * EditPage cares about two distinct titles:
  29. * $this->mContextTitle is the page that forms submit to, links point to,
  30. * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
  31. * page in the database that is actually being edited. These are
  32. * usually the same, but they are now allowed to be different.
  33. *
  34. * Surgeon General's Warning: prolonged exposure to this class is known to cause
  35. * headaches, which may be fatal.
  36. */
  37. class EditPage {
  38. /**
  39. * Status: Article successfully updated
  40. */
  41. const AS_SUCCESS_UPDATE = 200;
  42. /**
  43. * Status: Article successfully created
  44. */
  45. const AS_SUCCESS_NEW_ARTICLE = 201;
  46. /**
  47. * Status: Article update aborted by a hook function
  48. */
  49. const AS_HOOK_ERROR = 210;
  50. /**
  51. * Status: A hook function returned an error
  52. */
  53. const AS_HOOK_ERROR_EXPECTED = 212;
  54. /**
  55. * Status: User is blocked from editting this page
  56. */
  57. const AS_BLOCKED_PAGE_FOR_USER = 215;
  58. /**
  59. * Status: Content too big (> $wgMaxArticleSize)
  60. */
  61. const AS_CONTENT_TOO_BIG = 216;
  62. /**
  63. * Status: User cannot edit? (not used)
  64. */
  65. const AS_USER_CANNOT_EDIT = 217;
  66. /**
  67. * Status: this anonymous user is not allowed to edit this page
  68. */
  69. const AS_READ_ONLY_PAGE_ANON = 218;
  70. /**
  71. * Status: this logged in user is not allowed to edit this page
  72. */
  73. const AS_READ_ONLY_PAGE_LOGGED = 219;
  74. /**
  75. * Status: wiki is in readonly mode (wfReadOnly() == true)
  76. */
  77. const AS_READ_ONLY_PAGE = 220;
  78. /**
  79. * Status: rate limiter for action 'edit' was tripped
  80. */
  81. const AS_RATE_LIMITED = 221;
  82. /**
  83. * Status: article was deleted while editting and param wpRecreate == false or form
  84. * was not posted
  85. */
  86. const AS_ARTICLE_WAS_DELETED = 222;
  87. /**
  88. * Status: user tried to create this page, but is not allowed to do that
  89. * ( Title->usercan('create') == false )
  90. */
  91. const AS_NO_CREATE_PERMISSION = 223;
  92. /**
  93. * Status: user tried to create a blank page
  94. */
  95. const AS_BLANK_ARTICLE = 224;
  96. /**
  97. * Status: (non-resolvable) edit conflict
  98. */
  99. const AS_CONFLICT_DETECTED = 225;
  100. /**
  101. * Status: no edit summary given and the user has forceeditsummary set and the user is not
  102. * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
  103. */
  104. const AS_SUMMARY_NEEDED = 226;
  105. /**
  106. * Status: user tried to create a new section without content
  107. */
  108. const AS_TEXTBOX_EMPTY = 228;
  109. /**
  110. * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
  111. */
  112. const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
  113. /**
  114. * not used
  115. */
  116. const AS_OK = 230;
  117. /**
  118. * Status: WikiPage::doEdit() was unsuccessfull
  119. */
  120. const AS_END = 231;
  121. /**
  122. * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
  123. */
  124. const AS_SPAM_ERROR = 232;
  125. /**
  126. * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
  127. */
  128. const AS_IMAGE_REDIRECT_ANON = 233;
  129. /**
  130. * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
  131. */
  132. const AS_IMAGE_REDIRECT_LOGGED = 234;
  133. /**
  134. * HTML id and name for the beginning of the edit form.
  135. */
  136. const EDITFORM_ID = 'editform';
  137. /**
  138. * @var Article
  139. */
  140. var $mArticle;
  141. /**
  142. * @var Title
  143. */
  144. var $mTitle;
  145. private $mContextTitle = null;
  146. var $action = 'submit';
  147. var $isConflict = false;
  148. var $isCssJsSubpage = false;
  149. var $isCssSubpage = false;
  150. var $isJsSubpage = false;
  151. var $isWrongCaseCssJsPage = false;
  152. var $isNew = false; // new page or new section
  153. var $deletedSinceEdit;
  154. var $formtype;
  155. var $firsttime;
  156. var $lastDelete;
  157. var $mTokenOk = false;
  158. var $mTokenOkExceptSuffix = false;
  159. var $mTriedSave = false;
  160. var $incompleteForm = false;
  161. var $tooBig = false;
  162. var $kblength = false;
  163. var $missingComment = false;
  164. var $missingSummary = false;
  165. var $allowBlankSummary = false;
  166. var $autoSumm = '';
  167. var $hookError = '';
  168. #var $mPreviewTemplates;
  169. /**
  170. * @var ParserOutput
  171. */
  172. var $mParserOutput;
  173. /**
  174. * Has a summary been preset using GET parameter &summary= ?
  175. * @var Bool
  176. */
  177. var $hasPresetSummary = false;
  178. var $mBaseRevision = false;
  179. var $mShowSummaryField = true;
  180. # Form values
  181. var $save = false, $preview = false, $diff = false;
  182. var $minoredit = false, $watchthis = false, $recreate = false;
  183. var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
  184. var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
  185. var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
  186. # Placeholders for text injection by hooks (must be HTML)
  187. # extensions should take care to _append_ to the present value
  188. public $editFormPageTop = ''; // Before even the preview
  189. public $editFormTextTop = '';
  190. public $editFormTextBeforeContent = '';
  191. public $editFormTextAfterWarn = '';
  192. public $editFormTextAfterTools = '';
  193. public $editFormTextBottom = '';
  194. public $editFormTextAfterContent = '';
  195. public $previewTextAfterContent = '';
  196. public $mPreloadText = '';
  197. /* $didSave should be set to true whenever an article was succesfully altered. */
  198. public $didSave = false;
  199. public $undidRev = 0;
  200. public $suppressIntro = false;
  201. /**
  202. * @param $article Article
  203. */
  204. public function __construct( Article $article ) {
  205. $this->mArticle = $article;
  206. $this->mTitle = $article->getTitle();
  207. }
  208. /**
  209. * @return Article
  210. */
  211. public function getArticle() {
  212. return $this->mArticle;
  213. }
  214. /**
  215. * @since 1.19
  216. * @return Title
  217. */
  218. public function getTitle() {
  219. return $this->mTitle;
  220. }
  221. /**
  222. * Set the context Title object
  223. *
  224. * @param $title Title object or null
  225. */
  226. public function setContextTitle( $title ) {
  227. $this->mContextTitle = $title;
  228. }
  229. /**
  230. * Get the context title object.
  231. * If not set, $wgTitle will be returned. This behavior might changed in
  232. * the future to return $this->mTitle instead.
  233. *
  234. * @return Title object
  235. */
  236. public function getContextTitle() {
  237. if ( is_null( $this->mContextTitle ) ) {
  238. global $wgTitle;
  239. return $wgTitle;
  240. } else {
  241. return $this->mContextTitle;
  242. }
  243. }
  244. function submit() {
  245. $this->edit();
  246. }
  247. /**
  248. * This is the function that gets called for "action=edit". It
  249. * sets up various member variables, then passes execution to
  250. * another function, usually showEditForm()
  251. *
  252. * The edit form is self-submitting, so that when things like
  253. * preview and edit conflicts occur, we get the same form back
  254. * with the extra stuff added. Only when the final submission
  255. * is made and all is well do we actually save and redirect to
  256. * the newly-edited page.
  257. */
  258. function edit() {
  259. global $wgOut, $wgRequest, $wgUser;
  260. // Allow extensions to modify/prevent this form or submission
  261. if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
  262. return;
  263. }
  264. wfProfileIn( __METHOD__ );
  265. wfDebug( __METHOD__ . ": enter\n" );
  266. // If they used redlink=1 and the page exists, redirect to the main article
  267. if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
  268. $wgOut->redirect( $this->mTitle->getFullURL() );
  269. wfProfileOut( __METHOD__ );
  270. return;
  271. }
  272. $this->importFormData( $wgRequest );
  273. $this->firsttime = false;
  274. if ( $this->live ) {
  275. $this->livePreview();
  276. wfProfileOut( __METHOD__ );
  277. return;
  278. }
  279. if ( wfReadOnly() && $this->save ) {
  280. // Force preview
  281. $this->save = false;
  282. $this->preview = true;
  283. }
  284. if ( $this->save ) {
  285. $this->formtype = 'save';
  286. } elseif ( $this->preview ) {
  287. $this->formtype = 'preview';
  288. } elseif ( $this->diff ) {
  289. $this->formtype = 'diff';
  290. } else { # First time through
  291. $this->firsttime = true;
  292. if ( $this->previewOnOpen() ) {
  293. $this->formtype = 'preview';
  294. } else {
  295. $this->formtype = 'initial';
  296. }
  297. }
  298. $permErrors = $this->getEditPermissionErrors();
  299. if ( $permErrors ) {
  300. wfDebug( __METHOD__ . ": User can't edit\n" );
  301. // Auto-block user's IP if the account was "hard" blocked
  302. $wgUser->spreadAnyEditBlock();
  303. $this->displayPermissionsError( $permErrors );
  304. wfProfileOut( __METHOD__ );
  305. return;
  306. }
  307. wfProfileIn( __METHOD__ . "-business-end" );
  308. $this->isConflict = false;
  309. // css / js subpages of user pages get a special treatment
  310. $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
  311. $this->isCssSubpage = $this->mTitle->isCssSubpage();
  312. $this->isJsSubpage = $this->mTitle->isJsSubpage();
  313. $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
  314. $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
  315. # Show applicable editing introductions
  316. if ( $this->formtype == 'initial' || $this->firsttime ) {
  317. $this->showIntro();
  318. }
  319. # Attempt submission here. This will check for edit conflicts,
  320. # and redundantly check for locked database, blocked IPs, etc.
  321. # that edit() already checked just in case someone tries to sneak
  322. # in the back door with a hand-edited submission URL.
  323. if ( 'save' == $this->formtype ) {
  324. if ( !$this->attemptSave() ) {
  325. wfProfileOut( __METHOD__ . "-business-end" );
  326. wfProfileOut( __METHOD__ );
  327. return;
  328. }
  329. }
  330. # First time through: get contents, set time for conflict
  331. # checking, etc.
  332. if ( 'initial' == $this->formtype || $this->firsttime ) {
  333. if ( $this->initialiseForm() === false ) {
  334. $this->noSuchSectionPage();
  335. wfProfileOut( __METHOD__ . "-business-end" );
  336. wfProfileOut( __METHOD__ );
  337. return;
  338. }
  339. if ( !$this->mTitle->getArticleID() )
  340. wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
  341. else
  342. wfRunHooks( 'EditFormInitialText', array( $this ) );
  343. }
  344. $this->showEditForm();
  345. wfProfileOut( __METHOD__ . "-business-end" );
  346. wfProfileOut( __METHOD__ );
  347. }
  348. /**
  349. * @return array
  350. */
  351. protected function getEditPermissionErrors() {
  352. global $wgUser;
  353. $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
  354. # Can this title be created?
  355. if ( !$this->mTitle->exists() ) {
  356. $permErrors = array_merge( $permErrors,
  357. wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
  358. }
  359. # Ignore some permissions errors when a user is just previewing/viewing diffs
  360. $remove = array();
  361. foreach ( $permErrors as $error ) {
  362. if ( ( $this->preview || $this->diff ) &&
  363. ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
  364. {
  365. $remove[] = $error;
  366. }
  367. }
  368. $permErrors = wfArrayDiff2( $permErrors, $remove );
  369. return $permErrors;
  370. }
  371. /**
  372. * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
  373. * but with the following differences:
  374. * - If redlink=1, the user will be redirected to the page
  375. * - If there is content to display or the error occurs while either saving,
  376. * previewing or showing the difference, it will be a
  377. * "View source for ..." page displaying the source code after the error message.
  378. *
  379. * @since 1.19
  380. * @param $permErrors Array of permissions errors, as returned by
  381. * Title::getUserPermissionsErrors().
  382. */
  383. protected function displayPermissionsError( array $permErrors ) {
  384. global $wgRequest, $wgOut;
  385. if ( $wgRequest->getBool( 'redlink' ) ) {
  386. // The edit page was reached via a red link.
  387. // Redirect to the article page and let them click the edit tab if
  388. // they really want a permission error.
  389. $wgOut->redirect( $this->mTitle->getFullUrl() );
  390. return;
  391. }
  392. $content = $this->getContent();
  393. # Use the normal message if there's nothing to display
  394. if ( $this->firsttime && $content === '' ) {
  395. $action = $this->mTitle->exists() ? 'edit' :
  396. ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
  397. throw new PermissionsError( $action, $permErrors );
  398. }
  399. $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
  400. $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
  401. $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
  402. $wgOut->addHTML( "<hr />\n" );
  403. # If the user made changes, preserve them when showing the markup
  404. # (This happens when a user is blocked during edit, for instance)
  405. if ( !$this->firsttime ) {
  406. $content = $this->textbox1;
  407. $wgOut->addWikiMsg( 'viewyourtext' );
  408. } else {
  409. $wgOut->addWikiMsg( 'viewsourcetext' );
  410. }
  411. $this->showTextbox( $content, 'wpTextbox1', array( 'readonly' ) );
  412. $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
  413. Linker::formatTemplates( $this->getTemplates() ) ) );
  414. if ( $this->mTitle->exists() ) {
  415. $wgOut->returnToMain( null, $this->mTitle );
  416. }
  417. }
  418. /**
  419. * Show a read-only error
  420. * Parameters are the same as OutputPage:readOnlyPage()
  421. * Redirect to the article page if redlink=1
  422. * @deprecated in 1.19; use displayPermissionsError() instead
  423. */
  424. function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
  425. wfDeprecated( __METHOD__, '1.19' );
  426. global $wgRequest, $wgOut;
  427. if ( $wgRequest->getBool( 'redlink' ) ) {
  428. // The edit page was reached via a red link.
  429. // Redirect to the article page and let them click the edit tab if
  430. // they really want a permission error.
  431. $wgOut->redirect( $this->mTitle->getFullUrl() );
  432. } else {
  433. $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
  434. }
  435. }
  436. /**
  437. * Should we show a preview when the edit form is first shown?
  438. *
  439. * @return bool
  440. */
  441. protected function previewOnOpen() {
  442. global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
  443. if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
  444. // Explicit override from request
  445. return true;
  446. } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
  447. // Explicit override from request
  448. return false;
  449. } elseif ( $this->section == 'new' ) {
  450. // Nothing *to* preview for new sections
  451. return false;
  452. } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
  453. // Standard preference behaviour
  454. return true;
  455. } elseif ( !$this->mTitle->exists() &&
  456. isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] ) &&
  457. $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
  458. {
  459. // Categories are special
  460. return true;
  461. } else {
  462. return false;
  463. }
  464. }
  465. /**
  466. * Checks whether the user entered a skin name in uppercase,
  467. * e.g. "User:Example/Monobook.css" instead of "monobook.css"
  468. *
  469. * @return bool
  470. */
  471. protected function isWrongCaseCssJsPage() {
  472. if ( $this->mTitle->isCssJsSubpage() ) {
  473. $name = $this->mTitle->getSkinFromCssJsSubpage();
  474. $skins = array_merge(
  475. array_keys( Skin::getSkinNames() ),
  476. array( 'common' )
  477. );
  478. return !in_array( $name, $skins )
  479. && in_array( strtolower( $name ), $skins );
  480. } else {
  481. return false;
  482. }
  483. }
  484. /**
  485. * Does this EditPage class support section editing?
  486. * This is used by EditPage subclasses to indicate their ui cannot handle section edits
  487. *
  488. * @return bool
  489. */
  490. protected function isSectionEditSupported() {
  491. return true;
  492. }
  493. /**
  494. * This function collects the form data and uses it to populate various member variables.
  495. * @param $request WebRequest
  496. */
  497. function importFormData( &$request ) {
  498. global $wgLang, $wgUser;
  499. wfProfileIn( __METHOD__ );
  500. # Section edit can come from either the form or a link
  501. $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
  502. if ( $request->wasPosted() ) {
  503. # These fields need to be checked for encoding.
  504. # Also remove trailing whitespace, but don't remove _initial_
  505. # whitespace from the text boxes. This may be significant formatting.
  506. $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
  507. if ( !$request->getCheck( 'wpTextbox2' ) ) {
  508. // Skip this if wpTextbox2 has input, it indicates that we came
  509. // from a conflict page with raw page text, not a custom form
  510. // modified by subclasses
  511. wfProfileIn( get_class( $this ) . "::importContentFormData" );
  512. $textbox1 = $this->importContentFormData( $request );
  513. if ( isset( $textbox1 ) )
  514. $this->textbox1 = $textbox1;
  515. wfProfileOut( get_class( $this ) . "::importContentFormData" );
  516. }
  517. # Truncate for whole multibyte characters
  518. $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 255 );
  519. # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
  520. # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
  521. # section titles.
  522. $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
  523. # Treat sectiontitle the same way as summary.
  524. # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
  525. # currently doing double duty as both edit summary and section title. Right now this
  526. # is just to allow API edits to work around this limitation, but this should be
  527. # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
  528. $this->sectiontitle = $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
  529. $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
  530. $this->edittime = $request->getVal( 'wpEdittime' );
  531. $this->starttime = $request->getVal( 'wpStarttime' );
  532. $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
  533. if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
  534. // wpTextbox1 field is missing, possibly due to being "too big"
  535. // according to some filter rules such as Suhosin's setting for
  536. // suhosin.request.max_value_length (d'oh)
  537. $this->incompleteForm = true;
  538. } else {
  539. // edittime should be one of our last fields; if it's missing,
  540. // the submission probably broke somewhere in the middle.
  541. $this->incompleteForm = is_null( $this->edittime );
  542. }
  543. if ( $this->incompleteForm ) {
  544. # If the form is incomplete, force to preview.
  545. wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
  546. wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
  547. $this->preview = true;
  548. } else {
  549. /* Fallback for live preview */
  550. $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
  551. $this->diff = $request->getCheck( 'wpDiff' );
  552. // Remember whether a save was requested, so we can indicate
  553. // if we forced preview due to session failure.
  554. $this->mTriedSave = !$this->preview;
  555. if ( $this->tokenOk( $request ) ) {
  556. # Some browsers will not report any submit button
  557. # if the user hits enter in the comment box.
  558. # The unmarked state will be assumed to be a save,
  559. # if the form seems otherwise complete.
  560. wfDebug( __METHOD__ . ": Passed token check.\n" );
  561. } elseif ( $this->diff ) {
  562. # Failed token check, but only requested "Show Changes".
  563. wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
  564. } else {
  565. # Page might be a hack attempt posted from
  566. # an external site. Preview instead of saving.
  567. wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
  568. $this->preview = true;
  569. }
  570. }
  571. $this->save = !$this->preview && !$this->diff;
  572. if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
  573. $this->edittime = null;
  574. }
  575. if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
  576. $this->starttime = null;
  577. }
  578. $this->recreate = $request->getCheck( 'wpRecreate' );
  579. $this->minoredit = $request->getCheck( 'wpMinoredit' );
  580. $this->watchthis = $request->getCheck( 'wpWatchthis' );
  581. # Don't force edit summaries when a user is editing their own user or talk page
  582. if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) &&
  583. $this->mTitle->getText() == $wgUser->getName() )
  584. {
  585. $this->allowBlankSummary = true;
  586. } else {
  587. $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
  588. }
  589. $this->autoSumm = $request->getText( 'wpAutoSummary' );
  590. } else {
  591. # Not a posted form? Start with nothing.
  592. wfDebug( __METHOD__ . ": Not a posted form.\n" );
  593. $this->textbox1 = '';
  594. $this->summary = '';
  595. $this->sectiontitle = '';
  596. $this->edittime = '';
  597. $this->starttime = wfTimestampNow();
  598. $this->edit = false;
  599. $this->preview = false;
  600. $this->save = false;
  601. $this->diff = false;
  602. $this->minoredit = false;
  603. $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
  604. $this->recreate = false;
  605. // When creating a new section, we can preload a section title by passing it as the
  606. // preloadtitle parameter in the URL (Bug 13100)
  607. if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
  608. $this->sectiontitle = $request->getVal( 'preloadtitle' );
  609. // Once wpSummary isn't being use for setting section titles, we should delete this.
  610. $this->summary = $request->getVal( 'preloadtitle' );
  611. }
  612. elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
  613. $this->summary = $request->getText( 'summary' );
  614. if ( $this->summary !== '' ) {
  615. $this->hasPresetSummary = true;
  616. }
  617. }
  618. if ( $request->getVal( 'minor' ) ) {
  619. $this->minoredit = true;
  620. }
  621. }
  622. $this->bot = $request->getBool( 'bot', true );
  623. $this->nosummary = $request->getBool( 'nosummary' );
  624. $this->oldid = $request->getInt( 'oldid' );
  625. $this->live = $request->getCheck( 'live' );
  626. $this->editintro = $request->getText( 'editintro',
  627. // Custom edit intro for new sections
  628. $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
  629. // Allow extensions to modify form data
  630. wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
  631. wfProfileOut( __METHOD__ );
  632. }
  633. /**
  634. * Subpage overridable method for extracting the page content data from the
  635. * posted form to be placed in $this->textbox1, if using customized input
  636. * this method should be overrided and return the page text that will be used
  637. * for saving, preview parsing and so on...
  638. *
  639. * @param $request WebRequest
  640. */
  641. protected function importContentFormData( &$request ) {
  642. return; // Don't do anything, EditPage already extracted wpTextbox1
  643. }
  644. /**
  645. * Initialise form fields in the object
  646. * Called on the first invocation, e.g. when a user clicks an edit link
  647. * @return bool -- if the requested section is valid
  648. */
  649. function initialiseForm() {
  650. global $wgUser;
  651. $this->edittime = $this->mArticle->getTimestamp();
  652. $this->textbox1 = $this->getContent( false );
  653. // activate checkboxes if user wants them to be always active
  654. # Sort out the "watch" checkbox
  655. if ( $wgUser->getOption( 'watchdefault' ) ) {
  656. # Watch all edits
  657. $this->watchthis = true;
  658. } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
  659. # Watch creations
  660. $this->watchthis = true;
  661. } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
  662. # Already watched
  663. $this->watchthis = true;
  664. }
  665. if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
  666. $this->minoredit = true;
  667. }
  668. if ( $this->textbox1 === false ) {
  669. return false;
  670. }
  671. wfProxyCheck();
  672. return true;
  673. }
  674. /**
  675. * Fetch initial editing page content.
  676. *
  677. * @param $def_text string
  678. * @return mixed string on success, $def_text for invalid sections
  679. * @private
  680. */
  681. function getContent( $def_text = '' ) {
  682. global $wgOut, $wgRequest, $wgParser;
  683. wfProfileIn( __METHOD__ );
  684. $text = false;
  685. // For message page not locally set, use the i18n message.
  686. // For other non-existent articles, use preload text if any.
  687. if ( !$this->mTitle->exists() || $this->section == 'new' ) {
  688. if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
  689. # If this is a system message, get the default text.
  690. $text = $this->mTitle->getDefaultMessageText();
  691. }
  692. if ( $text === false ) {
  693. # If requested, preload some text.
  694. $preload = $wgRequest->getVal( 'preload',
  695. // Custom preload text for new sections
  696. $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
  697. $text = $this->getPreloadedText( $preload );
  698. }
  699. // For existing pages, get text based on "undo" or section parameters.
  700. } else {
  701. if ( $this->section != '' ) {
  702. // Get section edit text (returns $def_text for invalid sections)
  703. $text = $wgParser->getSection( $this->getOriginalContent(), $this->section, $def_text );
  704. } else {
  705. $undoafter = $wgRequest->getInt( 'undoafter' );
  706. $undo = $wgRequest->getInt( 'undo' );
  707. if ( $undo > 0 && $undoafter > 0 ) {
  708. if ( $undo < $undoafter ) {
  709. # If they got undoafter and undo round the wrong way, switch them
  710. list( $undo, $undoafter ) = array( $undoafter, $undo );
  711. }
  712. $undorev = Revision::newFromId( $undo );
  713. $oldrev = Revision::newFromId( $undoafter );
  714. # Sanity check, make sure it's the right page,
  715. # the revisions exist and they were not deleted.
  716. # Otherwise, $text will be left as-is.
  717. if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
  718. $undorev->getPage() == $oldrev->getPage() &&
  719. $undorev->getPage() == $this->mTitle->getArticleID() &&
  720. !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
  721. !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
  722. $text = $this->mArticle->getUndoText( $undorev, $oldrev );
  723. if ( $text === false ) {
  724. # Warn the user that something went wrong
  725. $undoMsg = 'failure';
  726. } else {
  727. # Inform the user of our success and set an automatic edit summary
  728. $undoMsg = 'success';
  729. # If we just undid one rev, use an autosummary
  730. $firstrev = $oldrev->getNext();
  731. if ( $firstrev && $firstrev->getId() == $undo ) {
  732. $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
  733. if ( $this->summary === '' ) {
  734. $this->summary = $undoSummary;
  735. } else {
  736. $this->summary = $undoSummary . wfMessage( 'colon-separator' )
  737. ->inContentLanguage()->text() . $this->summary;
  738. }
  739. $this->undidRev = $undo;
  740. }
  741. $this->formtype = 'diff';
  742. }
  743. } else {
  744. // Failed basic sanity checks.
  745. // Older revisions may have been removed since the link
  746. // was created, or we may simply have got bogus input.
  747. $undoMsg = 'norev';
  748. }
  749. $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
  750. $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
  751. wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
  752. }
  753. if ( $text === false ) {
  754. $text = $this->getOriginalContent();
  755. }
  756. }
  757. }
  758. wfProfileOut( __METHOD__ );
  759. return $text;
  760. }
  761. /**
  762. * Get the content of the wanted revision, without section extraction.
  763. *
  764. * The result of this function can be used to compare user's input with
  765. * section replaced in its context (using WikiPage::replaceSection())
  766. * to the original text of the edit.
  767. *
  768. * This difers from Article::getContent() that when a missing revision is
  769. * encountered the result will be an empty string and not the
  770. * 'missing-revision' message.
  771. *
  772. * @since 1.19
  773. * @return string
  774. */
  775. private function getOriginalContent() {
  776. if ( $this->section == 'new' ) {
  777. return $this->getCurrentText();
  778. }
  779. $revision = $this->mArticle->getRevisionFetched();
  780. if ( $revision === null ) {
  781. return '';
  782. }
  783. return $this->mArticle->getContent();
  784. }
  785. /**
  786. * Get the actual text of the page. This is basically similar to
  787. * WikiPage::getRawText() except that when the page doesn't exist an empty
  788. * string is returned instead of false.
  789. *
  790. * @since 1.19
  791. * @return string
  792. */
  793. private function getCurrentText() {
  794. $text = $this->mArticle->getRawText();
  795. if ( $text === false ) {
  796. return '';
  797. } else {
  798. return $text;
  799. }
  800. }
  801. /**
  802. * Use this method before edit() to preload some text into the edit box
  803. *
  804. * @param $text string
  805. */
  806. public function setPreloadedText( $text ) {
  807. $this->mPreloadText = $text;
  808. }
  809. /**
  810. * Get the contents to be preloaded into the box, either set by
  811. * an earlier setPreloadText() or by loading the given page.
  812. *
  813. * @param $preload String: representing the title to preload from.
  814. * @return String
  815. */
  816. protected function getPreloadedText( $preload ) {
  817. global $wgUser, $wgParser;
  818. if ( !empty( $this->mPreloadText ) ) {
  819. return $this->mPreloadText;
  820. }
  821. if ( $preload === '' ) {
  822. return '';
  823. }
  824. $title = Title::newFromText( $preload );
  825. # Check for existence to avoid getting MediaWiki:Noarticletext
  826. if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
  827. return '';
  828. }
  829. $page = WikiPage::factory( $title );
  830. if ( $page->isRedirect() ) {
  831. $title = $page->getRedirectTarget();
  832. # Same as before
  833. if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
  834. return '';
  835. }
  836. $page = WikiPage::factory( $title );
  837. }
  838. $parserOptions = ParserOptions::newFromUser( $wgUser );
  839. return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
  840. }
  841. /**
  842. * Make sure the form isn't faking a user's credentials.
  843. *
  844. * @param $request WebRequest
  845. * @return bool
  846. * @private
  847. */
  848. function tokenOk( &$request ) {
  849. global $wgUser;
  850. $token = $request->getVal( 'wpEditToken' );
  851. $this->mTokenOk = $wgUser->matchEditToken( $token );
  852. $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
  853. return $this->mTokenOk;
  854. }
  855. /**
  856. * Attempt submission
  857. * @return bool false if output is done, true if the rest of the form should be displayed
  858. */
  859. function attemptSave() {
  860. global $wgUser, $wgOut;
  861. $resultDetails = false;
  862. # Allow bots to exempt some edits from bot flagging
  863. $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
  864. $status = $this->internalAttemptSave( $resultDetails, $bot );
  865. // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
  866. if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
  867. $this->didSave = true;
  868. }
  869. switch ( $status->value ) {
  870. case self::AS_HOOK_ERROR_EXPECTED:
  871. case self::AS_CONTENT_TOO_BIG:
  872. case self::AS_ARTICLE_WAS_DELETED:
  873. case self::AS_CONFLICT_DETECTED:
  874. case self::AS_SUMMARY_NEEDED:
  875. case self::AS_TEXTBOX_EMPTY:
  876. case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
  877. case self::AS_END:
  878. return true;
  879. case self::AS_HOOK_ERROR:
  880. return false;
  881. case self::AS_SUCCESS_NEW_ARTICLE:
  882. $query = $resultDetails['redirect'] ? 'redirect=no' : '';
  883. $anchor = isset ( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
  884. $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
  885. return false;
  886. case self::AS_SUCCESS_UPDATE:
  887. $extraQuery = '';
  888. $sectionanchor = $resultDetails['sectionanchor'];
  889. // Give extensions a chance to modify URL query on update
  890. wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
  891. if ( $resultDetails['redirect'] ) {
  892. if ( $extraQuery == '' ) {
  893. $extraQuery = 'redirect=no';
  894. } else {
  895. $extraQuery = 'redirect=no&' . $extraQuery;
  896. }
  897. }
  898. $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
  899. return false;
  900. case self::AS_BLANK_ARTICLE:
  901. $wgOut->redirect( $this->getContextTitle()->getFullURL() );
  902. return false;
  903. case self::AS_SPAM_ERROR:
  904. $this->spamPageWithContent( $resultDetails['spam'] );
  905. return false;
  906. case self::AS_BLOCKED_PAGE_FOR_USER:
  907. throw new UserBlockedError( $wgUser->getBlock() );
  908. case self::AS_IMAGE_REDIRECT_ANON:
  909. case self::AS_IMAGE_REDIRECT_LOGGED:
  910. throw new PermissionsError( 'upload' );
  911. case self::AS_READ_ONLY_PAGE_ANON:
  912. case self::AS_READ_ONLY_PAGE_LOGGED:
  913. throw new PermissionsError( 'edit' );
  914. case self::AS_READ_ONLY_PAGE:
  915. throw new ReadOnlyError;
  916. case self::AS_RATE_LIMITED:
  917. throw new ThrottledError();
  918. case self::AS_NO_CREATE_PERMISSION:
  919. $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
  920. throw new PermissionsError( $permission );
  921. default:
  922. // We don't recognize $status->value. The only way that can happen
  923. // is if an extension hook aborted from inside ArticleSave.
  924. // Render the status object into $this->hookError
  925. // FIXME this sucks, we should just use the Status object throughout
  926. $this->hookError = '<div class="error">' . $status->getWikitext() .
  927. '</div>';
  928. return true;
  929. }
  930. }
  931. /**
  932. * Attempt submission (no UI)
  933. *
  934. * @param $result
  935. * @param $bot bool
  936. *
  937. * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
  938. *
  939. * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
  940. * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
  941. * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
  942. */
  943. function internalAttemptSave( &$result, $bot = false ) {
  944. global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
  945. $status = Status::newGood();
  946. wfProfileIn( __METHOD__ );
  947. wfProfileIn( __METHOD__ . '-checks' );
  948. if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
  949. wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
  950. $status->fatal( 'hookaborted' );
  951. $status->value = self::AS_HOOK_ERROR;
  952. wfProfileOut( __METHOD__ . '-checks' );
  953. wfProfileOut( __METHOD__ );
  954. return $status;
  955. }
  956. # Check image redirect
  957. if ( $this->mTitle->getNamespace() == NS_FILE &&
  958. Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
  959. !$wgUser->isAllowed( 'upload' ) ) {
  960. $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
  961. $status->setResult( false, $code );
  962. wfProfileOut( __METHOD__ . '-checks' );
  963. wfProfileOut( __METHOD__ );
  964. return $status;
  965. }
  966. # Check for spam
  967. $match = self::matchSummarySpamRegex( $this->summary );
  968. if ( $match === false ) {
  969. $match = self::matchSpamRegex( $this->textbox1 );
  970. }
  971. if ( $match !== false ) {
  972. $result['spam'] = $match;
  973. $ip = $wgRequest->getIP();
  974. $pdbk = $this->mTitle->getPrefixedDBkey();
  975. $match = str_replace( "\n", '', $match );
  976. wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
  977. $status->fatal( 'spamprotectionmatch', $match );
  978. $status->value = self::AS_SPAM_ERROR;
  979. wfProfileOut( __METHOD__ . '-checks' );
  980. wfProfileOut( __METHOD__ );
  981. return $status;
  982. }
  983. if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
  984. # Error messages etc. could be handled within the hook...
  985. $status->fatal( 'hookaborted' );
  986. $status->value = self::AS_HOOK_ERROR;
  987. wfProfileOut( __METHOD__ . '-checks' );
  988. wfProfileOut( __METHOD__ );
  989. return $status;
  990. } elseif ( $this->hookError != '' ) {
  991. # ...or the hook could be expecting us to produce an error
  992. $status->fatal( 'hookaborted' );
  993. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  994. wfProfileOut( __METHOD__ . '-checks' );
  995. wfProfileOut( __METHOD__ );
  996. return $status;
  997. }
  998. if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
  999. // Auto-block user's IP if the account was "hard" blocked
  1000. $wgUser->spreadAnyEditBlock();
  1001. # Check block state against master, thus 'false'.
  1002. $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
  1003. wfProfileOut( __METHOD__ . '-checks' );
  1004. wfProfileOut( __METHOD__ );
  1005. return $status;
  1006. }
  1007. $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
  1008. if ( $this->kblength > $wgMaxArticleSize ) {
  1009. // Error will be displayed by showEditForm()
  1010. $this->tooBig = true;
  1011. $status->setResult( false, self::AS_CONTENT_TOO_BIG );
  1012. wfProfileOut( __METHOD__ . '-checks' );
  1013. wfProfileOut( __METHOD__ );
  1014. return $status;
  1015. }
  1016. if ( !$wgUser->isAllowed( 'edit' ) ) {
  1017. if ( $wgUser->isAnon() ) {
  1018. $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
  1019. wfProfileOut( __METHOD__ . '-checks' );
  1020. wfProfileOut( __METHOD__ );
  1021. return $status;
  1022. } else {
  1023. $status->fatal( 'readonlytext' );
  1024. $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
  1025. wfProfileOut( __METHOD__ . '-checks' );
  1026. wfProfileOut( __METHOD__ );
  1027. return $status;
  1028. }
  1029. }
  1030. if ( wfReadOnly() ) {
  1031. $status->fatal( 'readonlytext' );
  1032. $status->value = self::AS_READ_ONLY_PAGE;
  1033. wfProfileOut( __METHOD__ . '-checks' );
  1034. wfProfileOut( __METHOD__ );
  1035. return $status;
  1036. }
  1037. if ( $wgUser->pingLimiter() ) {
  1038. $status->fatal( 'actionthrottledtext' );
  1039. $status->value = self::AS_RATE_LIMITED;
  1040. wfProfileOut( __METHOD__ . '-checks' );
  1041. wfProfileOut( __METHOD__ );
  1042. return $status;
  1043. }
  1044. # If the article has been deleted while editing, don't save it without
  1045. # confirmation
  1046. if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
  1047. $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
  1048. wfProfileOut( __METHOD__ . '-checks' );
  1049. wfProfileOut( __METHOD__ );
  1050. return $status;
  1051. }
  1052. wfProfileOut( __METHOD__ . '-checks' );
  1053. # Load the page data from the master. If anything changes in the meantime,
  1054. # we detect it by using page_latest like a token in a 1 try compare-and-swap.
  1055. $this->mArticle->loadPageData( 'fromdbmaster' );
  1056. $new = !$this->mArticle->exists();
  1057. if ( $new ) {
  1058. // Late check for create permission, just in case *PARANOIA*
  1059. if ( !$this->mTitle->userCan( 'create' ) ) {
  1060. $status->fatal( 'nocreatetext' );
  1061. $status->value = self::AS_NO_CREATE_PERMISSION;
  1062. wfDebug( __METHOD__ . ": no create permission\n" );
  1063. wfProfileOut( __METHOD__ );
  1064. return $status;
  1065. }
  1066. # Don't save a new article if it's blank.
  1067. if ( $this->textbox1 == '' ) {
  1068. $status->setResult( false, self::AS_BLANK_ARTICLE );
  1069. wfProfileOut( __METHOD__ );
  1070. return $status;
  1071. }
  1072. // Run post-section-merge edit filter
  1073. if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
  1074. # Error messages etc. could be handled within the hook...
  1075. $status->fatal( 'hookaborted' );
  1076. $status->value = self::AS_HOOK_ERROR;
  1077. wfProfileOut( __METHOD__ );
  1078. return $status;
  1079. } elseif ( $this->hookError != '' ) {
  1080. # ...or the hook could be expecting us to produce an error
  1081. $status->fatal( 'hookaborted' );
  1082. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  1083. wfProfileOut( __METHOD__ );
  1084. return $status;
  1085. }
  1086. $text = $this->textbox1;
  1087. $result['sectionanchor'] = '';
  1088. if ( $this->section == 'new' ) {
  1089. if ( $this->sectiontitle !== '' ) {
  1090. // Insert the section title above the content.
  1091. $text = wfMessage( 'newsectionheaderdefaultlevel', $this->sectiontitle )
  1092. ->inContentLanguage()->text() . "\n\n" . $text;
  1093. // Jump to the new section
  1094. $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
  1095. // If no edit summary was specified, create one automatically from the section
  1096. // title and have it link to the new section. Otherwise, respect the summary as
  1097. // passed.
  1098. if ( $this->summary === '' ) {
  1099. $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
  1100. $this->summary = wfMessage( 'newsectionsummary' )
  1101. ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
  1102. }
  1103. } elseif ( $this->summary !== '' ) {
  1104. // Insert the section title above the content.
  1105. $text = wfMessage( 'newsectionheaderdefaultlevel', $this->summary )
  1106. ->inContentLanguage()->text() . "\n\n" . $text;
  1107. // Jump to the new section
  1108. $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
  1109. // Create a link to the new section from the edit summary.
  1110. $cleanSummary = $wgParser->stripSectionName( $this->summary );
  1111. $this->summary = wfMessage( 'newsectionsummary' )
  1112. ->rawParams( $cleanSummary )->inContentLanguage()->text();
  1113. }
  1114. }
  1115. $status->value = self::AS_SUCCESS_NEW_ARTICLE;
  1116. } else {
  1117. # Article exists. Check for edit conflict.
  1118. $timestamp = $this->mArticle->getTimestamp();
  1119. wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
  1120. if ( $timestamp != $this->edittime ) {
  1121. $this->isConflict = true;
  1122. if ( $this->section == 'new' ) {
  1123. if ( $this->mArticle->getUserText() == $wgUser->getName() &&
  1124. $this->mArticle->getComment() == $this->summary ) {
  1125. // Probably a duplicate submission of a new comment.
  1126. // This can happen when squid resends a request after
  1127. // a timeout but the first one actually went through.
  1128. wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
  1129. } else {
  1130. // New comment; suppress conflict.
  1131. $this->isConflict = false;
  1132. wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
  1133. }
  1134. } elseif ( $this->section == '' && Revision::userWasLastToEdit( DB_MASTER, $this->mTitle->getArticleID(), $wgUser->getId(), $this->edittime ) ) {
  1135. # Suppress edit conflict with self, except for section edits where merging is required.
  1136. wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
  1137. $this->isConflict = false;
  1138. }
  1139. }
  1140. // If sectiontitle is set, use it, otherwise use the summary as the section title (for
  1141. // backwards compatibility with old forms/bots).
  1142. if ( $this->sectiontitle !== '' ) {
  1143. $sectionTitle = $this->sectiontitle;
  1144. } else {
  1145. $sectionTitle = $this->summary;
  1146. }
  1147. if ( $this->isConflict ) {
  1148. wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
  1149. $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
  1150. } else {
  1151. wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
  1152. $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle );
  1153. }
  1154. if ( is_null( $text ) ) {
  1155. wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
  1156. $this->isConflict = true;
  1157. $text = $this->textbox1; // do not try to merge here!
  1158. } elseif ( $this->isConflict ) {
  1159. # Attempt merge
  1160. if ( $this->mergeChangesInto( $text ) ) {
  1161. // Successful merge! Maybe we should tell the user the good news?
  1162. $this->isConflict = false;
  1163. wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
  1164. } else {
  1165. $this->section = '';
  1166. $this->textbox1 = $text;
  1167. wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
  1168. }
  1169. }
  1170. if ( $this->isConflict ) {
  1171. $status->setResult( false, self::AS_CONFLICT_DETECTED );
  1172. wfProfileOut( __METHOD__ );
  1173. return $status;
  1174. }
  1175. // Run post-section-merge edit filter
  1176. if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
  1177. # Error messages etc. could be handled within the hook...
  1178. $status->fatal( 'hookaborted' );
  1179. $status->value = self::AS_HOOK_ERROR;
  1180. wfProfileOut( __METHOD__ );
  1181. return $status;
  1182. } elseif ( $this->hookError != '' ) {
  1183. # ...or the hook could be expecting us to produce an error
  1184. $status->fatal( 'hookaborted' );
  1185. $status->value = self::AS_HOOK_ERROR_EXPECTED;
  1186. wfProfileOut( __METHOD__ );
  1187. return $status;
  1188. }
  1189. # Handle the user preference to force summaries here, but not for null edits
  1190. if ( $this->section != 'new' && !$this->allowBlankSummary
  1191. && $this->getOriginalContent() != $text
  1192. && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
  1193. {
  1194. if ( md5( $this->summary ) == $this->autoSumm ) {
  1195. $this->missingSummary = true;
  1196. $status->fatal( 'missingsummary' );
  1197. $status->value = self::AS_SUMMARY_NEEDED;
  1198. wfProfileOut( __METHOD__ );
  1199. return $status;
  1200. }
  1201. }
  1202. # And a similar thing for new sections
  1203. if ( $this->section == 'new' && !$this->allowBlankSummary ) {
  1204. if ( trim( $this->summary ) == '' ) {
  1205. $this->missingSummary = true;
  1206. $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
  1207. $status->value = self::AS_SUMMARY_NEEDED;
  1208. wfProfileOut( __METHOD__ );
  1209. return $status;
  1210. }
  1211. }
  1212. # All's well
  1213. wfProfileIn( __METHOD__ . '-sectionanchor' );
  1214. $sectionanchor = '';
  1215. if ( $this->section == 'new' ) {
  1216. if ( $this->textbox1 == '' ) {
  1217. $this->missingComment = true;
  1218. $status->fatal( 'missingcommenttext' );
  1219. $status->value = self::AS_TEXTBOX_EMPTY;
  1220. wfProfileOut( __METHOD__ . '-sectionanchor' );
  1221. wfProfileOut( __METHOD__ );
  1222. return $status;
  1223. }
  1224. if ( $this->sectiontitle !== '' ) {
  1225. $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
  1226. // If no edit summary was specified, create one automatically from the section
  1227. // title and have it link to the new section. Otherwise, respect the summary as
  1228. // passed.
  1229. if ( $this->summary === '' ) {
  1230. $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
  1231. $this->summary = wfMessage( 'newsectionsummary' )
  1232. ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
  1233. }
  1234. } elseif ( $this->summary !== '' ) {
  1235. $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
  1236. # This is a new section, so create a link to the new section
  1237. # in the revision summary.
  1238. $cleanSummary = $wgParser->stripSectionName( $this->summary );
  1239. $this->summary = wfMessage( 'newsectionsummary' )
  1240. ->rawParams( $cleanSummary )->inContentLanguage()->text();
  1241. }
  1242. } elseif ( $this->section != '' ) {
  1243. # Try to get a section anchor from the section source, redirect to edited section if header found
  1244. # XXX: might be better to integrate this into Article::replaceSection
  1245. # for duplicate heading checking and maybe parsing
  1246. $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
  1247. # we can't deal with anchors, includes, html etc in the header for now,
  1248. # headline would need to be parsed to improve this
  1249. if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
  1250. $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
  1251. }
  1252. }
  1253. $result['sectionanchor'] = $sectionanchor;
  1254. wfProfileOut( __METHOD__ . '-sectionanchor' );
  1255. // Save errors may fall down to the edit form, but we've now
  1256. // merged the section into full text. Clear the section field
  1257. // so that later submission of conflict forms won't try to
  1258. // replace that into a duplicated mess.
  1259. $this->textbox1 = $text;
  1260. $this->section = '';
  1261. $status->value = self::AS_SUCCESS_UPDATE;
  1262. }
  1263. // Check for length errors again now that the section is merged in
  1264. $this->kblength = (int)( strlen( $text ) / 1024 );
  1265. if ( $this->kblength > $wgMaxArticleSize ) {
  1266. $this->tooBig = true;
  1267. $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
  1268. wfProfileOut( __METHOD__ );
  1269. return $status;
  1270. }
  1271. $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
  1272. ( $new ? EDIT_NEW : EDIT_UPDATE ) |
  1273. ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
  1274. ( $bot ? EDIT_FORCE_BOT : 0 );
  1275. $doEditStatus = $this->mArticle->doEdit( $text, $this->summary, $flags );
  1276. if ( $doEditStatus->isOK() ) {
  1277. $result['redirect'] = Title::newFromRedirect( $text ) !== null;
  1278. $this->commitWatch();
  1279. wfProfileOut( __METHOD__ );
  1280. return $status;
  1281. } else {
  1282. // Failure from doEdit()
  1283. // Show the edit conflict page for certain recognized errors from doEdit(),
  1284. // but don't show it for errors from extension hooks
  1285. $errors = $doEditStatus->getErrorsArray();
  1286. if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
  1287. 'edit-already-exists' ) ) )
  1288. {
  1289. $this->isConflict = true;
  1290. // Destroys data doEdit() put in $status->value but who cares
  1291. $doEditStatus->value = self::AS_END;
  1292. }
  1293. wfProfileOut( __METHOD__ );
  1294. return $doEditStatus;
  1295. }
  1296. }
  1297. /**
  1298. * Commit the change of watch status
  1299. */
  1300. protected function commitWatch() {
  1301. global $wgUser;
  1302. if ( $wgUser->isLoggedIn() && $this->watchthis != $wgUser->isWatched( $this->mTitle ) ) {
  1303. $dbw = wfGetDB( DB_MASTER );
  1304. $dbw->begin( __METHOD__ );
  1305. if ( $this->watchthis ) {
  1306. WatchAction::doWatch( $this->mTitle, $wgUser );
  1307. } else {
  1308. WatchAction::doUnwatch( $this->mTitle, $wgUser );
  1309. }
  1310. $dbw->commit( __METHOD__ );
  1311. }
  1312. }
  1313. /**
  1314. * @private
  1315. * @todo document
  1316. *
  1317. * @param $editText string
  1318. *
  1319. * @return bool
  1320. */
  1321. function mergeChangesInto( &$editText ) {
  1322. wfProfileIn( __METHOD__ );
  1323. $db = wfGetDB( DB_MASTER );
  1324. // This is the revision the editor started from
  1325. $baseRevision = $this->getBaseRevision();
  1326. if ( is_null( $baseRevision ) ) {
  1327. wfProfileOut( __METHOD__ );
  1328. return false;
  1329. }
  1330. $baseText = $baseRevision->getText();
  1331. // The current state, we want to merge updates into it
  1332. $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
  1333. if ( is_null( $currentRevision ) ) {
  1334. wfProfileOut( __METHOD__ );
  1335. return false;
  1336. }
  1337. $currentText = $currentRevision->getText();
  1338. $result = '';
  1339. if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
  1340. $editText = $result;
  1341. wfProfileOut( __METHOD__ );
  1342. return true;
  1343. } else {
  1344. wfProfileOut( __METHOD__ );
  1345. return false;
  1346. }
  1347. }
  1348. /**
  1349. * @return Revision
  1350. */
  1351. function getBaseRevision() {
  1352. if ( !$this->mBaseRevision ) {
  1353. $db = wfGetDB( DB_MASTER );
  1354. $baseRevision = Revision::loadFromTimestamp(
  1355. $db, $this->mTitle, $this->edittime );
  1356. return $this->mBaseRevision = $baseRevision;
  1357. } else {
  1358. return $this->mBaseRevision;
  1359. }
  1360. }
  1361. /**
  1362. * Check given input text against $wgSpamRegex, and return the text of the first match.
  1363. *
  1364. * @param $text string
  1365. *
  1366. * @return string|bool matching string or false
  1367. */
  1368. public static function matchSpamRegex( $text ) {
  1369. global $wgSpamRegex;
  1370. // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
  1371. $regexes = (array)$wgSpamRegex;
  1372. return self::matchSpamRegexInternal( $text, $regexes );
  1373. }
  1374. /**
  1375. * Check given input text against $wgSpamRegex, and return the text of the first match.
  1376. *
  1377. * @param $text string
  1378. *
  1379. * @return string|bool matching string or false
  1380. */
  1381. public static function matchSummarySpamRegex( $text ) {
  1382. global $wgSummarySpamRegex;
  1383. $regexes = (array)$wgSummarySpamRegex;
  1384. return self::matchSpamRegexInternal( $text, $regexes );
  1385. }
  1386. /**
  1387. * @param $text string
  1388. * @param $regexes array
  1389. * @return bool|string
  1390. */
  1391. protected static function matchSpamRegexInternal( $text, $regexes ) {
  1392. foreach ( $regexes as $regex ) {
  1393. $matches = array();
  1394. if ( preg_match( $regex, $text, $matches ) ) {
  1395. return $matches[0];
  1396. }
  1397. }
  1398. return false;
  1399. }
  1400. function setHeaders() {
  1401. global $wgOut, $wgUser;
  1402. $wgOut->addModules( 'mediawiki.action.edit' );
  1403. if ( $wgUser->getOption( 'uselivepreview', false ) ) {
  1404. $wgOut->addModules( 'mediawiki.action.edit.preview' );
  1405. }
  1406. // Bug #19334: textarea jumps when editing articles in IE8
  1407. $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
  1408. $wgOut->setRobotPolicy( 'noindex,nofollow' );
  1409. # Enabled article-related sidebar, toplinks, etc.
  1410. $wgOut->setArticleRelated( true );
  1411. $contextTitle = $this->getContextTitle();
  1412. if ( $this->isConflict ) {
  1413. $msg = 'editconflict';
  1414. } elseif ( $contextTitle->exists() && $this->section != '' ) {
  1415. $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
  1416. } else {
  1417. $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
  1418. 'editing' : 'creating';
  1419. }
  1420. # Use the title defined by DISPLAYTITLE magic word when present
  1421. $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
  1422. if ( $displayTitle === false ) {
  1423. $displayTitle = $contextTitle->getPrefixedText();
  1424. }
  1425. $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
  1426. }
  1427. /**
  1428. * Show all applicable editing introductions
  1429. */
  1430. protected function showIntro() {
  1431. global $wgOut, $wgUser;
  1432. if ( $this->suppressIntro ) {
  1433. return;
  1434. }
  1435. $namespace = $this->mTitle->getNamespace();
  1436. if ( $namespace == NS_MEDIAWIKI ) {
  1437. # Show a warning if editing an interface message
  1438. $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
  1439. } else if( $namespace == NS_FILE ) {
  1440. # Show a hint to shared repo
  1441. $file = wfFindFile( $this->mTitle );
  1442. if( $file && !$file->isLocal() ) {
  1443. $descUrl = $file->getDescriptionUrl();
  1444. # there must be a description url to show a hint to shared repo
  1445. if( $descUrl ) {
  1446. if( !$this->mTitle->exists() ) {
  1447. $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
  1448. 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
  1449. ) );
  1450. } else {
  1451. $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
  1452. 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
  1453. ) );
  1454. }
  1455. }
  1456. }
  1457. }
  1458. # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
  1459. # Show log extract when the user is currently blocked
  1460. if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
  1461. $parts = explode( '/', $this->mTitle->getText(), 2 );
  1462. $username = $parts[0];
  1463. $user = User::newFromName( $username, false /* allow IP users*/ );
  1464. $ip = User::isIP( $username );
  1465. if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
  1466. $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
  1467. array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
  1468. } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
  1469. LogEventsList::showLogExtract(
  1470. $wgOut,
  1471. 'block',
  1472. $user->getUserPage(),
  1473. '',
  1474. array(
  1475. 'lim' => 1,
  1476. 'showIfEmpty' => false,
  1477. 'msgKey' => array(
  1478. 'blocked-notice-logextract',
  1479. $user->getName() # Support GENDER in notice
  1480. )
  1481. )
  1482. );
  1483. }
  1484. }
  1485. # Try to add a custom edit intro, or use the standard one if this is not possible.
  1486. if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
  1487. if ( $wgUser->isLoggedIn() ) {
  1488. $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
  1489. } else {
  1490. $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
  1491. }
  1492. }
  1493. # Give a notice if the user is editing a deleted/moved page...
  1494. if ( !$this->mTitle->exists() ) {
  1495. LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
  1496. '', array( 'lim' => 10,
  1497. 'conds' => array( "log_action != 'revision'" ),
  1498. 'showIfEmpty' => false,
  1499. 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
  1500. );
  1501. }
  1502. }
  1503. /**
  1504. * Attempt to show a custom editing introduction, if supplied
  1505. *
  1506. * @return bool
  1507. */
  1508. protected function showCustomIntro() {
  1509. if ( $this->editintro ) {
  1510. $title = Title::newFromText( $this->editintro );
  1511. if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
  1512. global $wgOut;
  1513. // Added using template syntax, to take <noinclude>'s into account.
  1514. $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
  1515. return true;
  1516. } else {
  1517. return false;
  1518. }
  1519. } else {
  1520. return false;
  1521. }
  1522. }
  1523. /**
  1524. * Send the edit form and related headers to $wgOut
  1525. * @param $formCallback Callback that takes an OutputPage parameter; will be called
  1526. * during form output near the top, for captchas and the like.
  1527. */
  1528. function showEditForm( $formCallback = null ) {
  1529. global $wgOut, $wgUser;
  1530. wfProfileIn( __METHOD__ );
  1531. # need to parse the preview early so that we know which templates are used,
  1532. # otherwise users with "show preview after edit box" will get a blank list
  1533. # we parse this near the beginning so that setHeaders can do the title
  1534. # setting work instead of leaving it in getPreviewText
  1535. $previewOutput = '';
  1536. if ( $this->formtype == 'preview' ) {
  1537. $previewOutput = $this->getPreviewText();
  1538. }
  1539. wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
  1540. $this->setHeaders();
  1541. if ( $this->showHeader() === false ) {
  1542. wfProfileOut( __METHOD__ );
  1543. return;
  1544. }
  1545. $wgOut->addHTML( $this->editFormPageTop );
  1546. if ( $wgUser->getOption( 'previewontop' ) ) {
  1547. $this->displayPreviewArea( $previewOutput, true );
  1548. }
  1549. $wgOut->addHTML( $this->editFormTextTop );
  1550. $showToolbar = true;
  1551. if ( $this->wasDeletedSinceLastEdit() ) {
  1552. if ( $this->formtype == 'save' ) {
  1553. // Hide the toolbar and edit area, user can click preview to get it back
  1554. // Add an confirmation checkbox and explanation.
  1555. $showToolbar = false;
  1556. } else {
  1557. $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
  1558. 'deletedwhileediting' );
  1559. }
  1560. }
  1561. $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
  1562. 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
  1563. 'enctype' => 'multipart/form-data' ) ) );
  1564. if ( is_callable( $formCallback ) ) {
  1565. call_user_func_array( $formCallback, array( &$wgOut ) );
  1566. }
  1567. wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
  1568. // Put these up at the top to ensure they aren't lost on early form submission
  1569. $this->showFormBeforeText();
  1570. if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
  1571. $username = $this->lastDelete->user_name;
  1572. $comment = $this->lastDelete->log_comment;
  1573. // It is better to not parse the comment at all than to have templates expanded in the middle
  1574. // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
  1575. $key = $comment === ''
  1576. ? 'confirmrecreate-noreason'
  1577. : 'confirmrecreate';
  1578. $wgOut->addHTML(
  1579. '<div class="mw-confirm-recreate">' .
  1580. wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
  1581. Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
  1582. array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
  1583. ) .
  1584. '</div>'
  1585. );
  1586. }
  1587. # When the summary is hidden, also hide them on preview/show changes
  1588. if( $this->nosummary ) {
  1589. $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
  1590. }
  1591. # If a blank edit summary was previously provided, and the appropriate
  1592. # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
  1593. # user being bounced back more than once in the event that a summary
  1594. # is not required.
  1595. #####
  1596. # For a bit more sophisticated detection of blank summaries, hash the
  1597. # automatic one and pass that in the hidden field wpAutoSummary.
  1598. if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
  1599. $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
  1600. }
  1601. if ( $this->undidRev ) {
  1602. $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
  1603. }
  1604. if ( $this->hasPresetSummary ) {
  1605. // If a summary has been preset using &summary= we dont want to prompt for
  1606. // a different summary. Only prompt for a summary if the summary is blanked.
  1607. // (Bug 17416)
  1608. $this->autoSumm = md5( '' );
  1609. }
  1610. $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
  1611. $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
  1612. $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
  1613. if ( $this->section == 'new' ) {
  1614. $this->showSummaryInput( true, $this->summary );
  1615. $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
  1616. }
  1617. $wgOut->addHTML( $this->editFormTextBeforeContent );
  1618. if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
  1619. $wgOut->addHTML( EditPage::getEditToolbar() );
  1620. }
  1621. if ( $this->isConflict ) {
  1622. // In an edit conflict bypass the overrideable content form method
  1623. // and fallback to the raw wpTextbox1 since editconflicts can't be
  1624. // resolved between page source edits and custom ui edits using the
  1625. // custom edit ui.
  1626. $this->textbox2 = $this->textbox1;
  1627. $this->textbox1 = $this->getCurrentText();
  1628. $this->showTextbox1();
  1629. } else {
  1630. $this->showContentForm();
  1631. }
  1632. $wgOut->addHTML( $this->editFormTextAfterContent );
  1633. $this->showStandardInputs();
  1634. $this->showFormAfterText();
  1635. $this->showTosSummary();
  1636. $this->showEditTools();
  1637. $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
  1638. $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
  1639. Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
  1640. $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
  1641. Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
  1642. if ( $this->isConflict ) {
  1643. $this->showConflict();
  1644. }
  1645. $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
  1646. if ( !$wgUser->getOption( 'previewontop' ) ) {
  1647. $this->displayPreviewArea( $previewOutput, false );
  1648. }
  1649. wfProfileOut( __METHOD__ );
  1650. }
  1651. /**
  1652. * Extract the section title from current section text, if any.
  1653. *
  1654. * @param string $text
  1655. * @return Mixed|string or false
  1656. */
  1657. public static function extractSectionTitle( $text ) {
  1658. preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
  1659. if ( !empty( $matches[2] ) ) {
  1660. global $wgParser;
  1661. return $wgParser->stripSectionName( trim( $matches[2] ) );
  1662. } else {
  1663. return false;
  1664. }
  1665. }
  1666. protected function showHeader() {
  1667. global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
  1668. if ( $this->mTitle->isTalkPage() ) {
  1669. $wgOut->addWikiMsg( 'talkpagetext' );
  1670. }
  1671. # Optional notices on a per-namespace and per-page basis
  1672. $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
  1673. $editnotice_ns_message = wfMessage( $editnotice_ns );
  1674. if ( $editnotice_ns_message->exists() ) {
  1675. $wgOut->addWikiText( $editnotice_ns_message->plain() );
  1676. }
  1677. if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
  1678. $parts = explode( '/', $this->mTitle->getDBkey() );
  1679. $editnotice_base = $editnotice_ns;
  1680. while ( count( $parts ) > 0 ) {
  1681. $editnotice_base .= '-' . array_shift( $parts );
  1682. $editnotice_base_msg = wfMessage( $editnotice_base );
  1683. if ( $editnotice_base_msg->exists() ) {
  1684. $wgOut->addWikiText( $editnotice_base_msg->plain() );
  1685. }
  1686. }
  1687. } else {
  1688. # Even if there are no subpages in namespace, we still don't want / in MW ns.
  1689. $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
  1690. $editnoticeMsg = wfMessage( $editnoticeText );
  1691. if ( $editnoticeMsg->exists() ) {
  1692. $wgOut->addWikiText( $editnoticeMsg->plain() );
  1693. }
  1694. }
  1695. if ( $this->isConflict ) {
  1696. $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
  1697. $this->edittime = $this->mArticle->getTimestamp();
  1698. } else {
  1699. if ( $this->section != '' && !$this->isSectionEditSupported() ) {
  1700. // We use $this->section to much before this and getVal('wgSection') directly in other places
  1701. // at this point we can't reset $this->section to '' to fallback to non-section editing.
  1702. // Someone is welcome to try refactoring though
  1703. $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
  1704. return false;
  1705. }
  1706. if ( $this->section != '' && $this->section != 'new' ) {
  1707. if ( !$this->summary && !$this->preview && !$this->diff ) {
  1708. $sectionTitle = self::extractSectionTitle( $this->textbox1 );
  1709. if ( $sectionTitle !== false ) {
  1710. $this->summary = "/* $sectionTitle */ ";
  1711. }
  1712. }
  1713. }
  1714. if ( $this->missingComment ) {
  1715. $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
  1716. }
  1717. if ( $this->missingSummary && $this->section != 'new' ) {
  1718. $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
  1719. }
  1720. if ( $this->missingSummary && $this->section == 'new' ) {
  1721. $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
  1722. }
  1723. if ( $this->hookError !== '' ) {
  1724. $wgOut->addWikiText( $this->hookError );
  1725. }
  1726. if ( !$this->checkUnicodeCompliantBrowser() ) {
  1727. $wgOut->addWikiMsg( 'nonunicodebrowser' );
  1728. }
  1729. if ( $this->section != 'new' ) {
  1730. $revision = $this->mArticle->getRevisionFetched();
  1731. if ( $revision ) {
  1732. // Let sysop know that this will make private content public if saved
  1733. if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
  1734. $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
  1735. } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
  1736. $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
  1737. }
  1738. if ( !$revision->isCurrent() ) {
  1739. $this->mArticle->setOldSubtitle( $revision->getId() );
  1740. $wgOut->addWikiMsg( 'editingold' );
  1741. }
  1742. } elseif ( $this->mTitle->exists() ) {
  1743. // Something went wrong
  1744. $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
  1745. array( 'missing-revision', $this->oldid ) );
  1746. }
  1747. }
  1748. }
  1749. if ( wfReadOnly() ) {
  1750. $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
  1751. } elseif ( $wgUser->isAnon() ) {
  1752. if ( $this->formtype != 'preview' ) {
  1753. $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
  1754. } else {
  1755. $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
  1756. }
  1757. } else {
  1758. if ( $this->isCssJsSubpage ) {
  1759. # Check the skin exists
  1760. if ( $this->isWrongCaseCssJsPage ) {
  1761. $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
  1762. }
  1763. if ( $this->formtype !== 'preview' ) {
  1764. if ( $this->isCssSubpage )
  1765. $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
  1766. if ( $this->isJsSubpage )
  1767. $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
  1768. }
  1769. }
  1770. }
  1771. if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
  1772. # Is the title semi-protected?
  1773. if ( $this->mTitle->isSemiProtected() ) {
  1774. $noticeMsg = 'semiprotectedpagewarning';
  1775. } else {
  1776. # Then it must be protected based on static groups (regular)
  1777. $noticeMsg = 'protectedpagewarning';
  1778. }
  1779. LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
  1780. array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
  1781. }
  1782. if ( $this->mTitle->isCascadeProtected() ) {
  1783. # Is this page under cascading protection from some source pages?
  1784. list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
  1785. $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
  1786. $cascadeSourcesCount = count( $cascadeSources );
  1787. if ( $cascadeSourcesCount > 0 ) {
  1788. # Explain, and list the titles responsible
  1789. foreach ( $cascadeSources as $page ) {
  1790. $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
  1791. }
  1792. }
  1793. $notice .= '</div>';
  1794. $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
  1795. }
  1796. if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
  1797. LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
  1798. array( 'lim' => 1,
  1799. 'showIfEmpty' => false,
  1800. 'msgKey' => array( 'titleprotectedwarning' ),
  1801. 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
  1802. }
  1803. if ( $this->kblength === false ) {
  1804. $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
  1805. }
  1806. if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
  1807. $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
  1808. array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
  1809. } else {
  1810. if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
  1811. $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
  1812. array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
  1813. );
  1814. }
  1815. }
  1816. # Add header copyright warning
  1817. $this->showHeaderCopyrightWarning();
  1818. }
  1819. /**
  1820. * Standard summary input and label (wgSummary), abstracted so EditPage
  1821. * subclasses may reorganize the form.
  1822. * Note that you do not need to worry about the label's for=, it will be
  1823. * inferred by the id given to the input. You can remove them both by
  1824. * passing array( 'id' => false ) to $userInputAttrs.
  1825. *
  1826. * @param $summary string The value of the summary input
  1827. * @param $labelText string The html to place inside the label
  1828. * @param $inputAttrs array of attrs to use on the input
  1829. * @param $spanLabelAttrs array of attrs to use on the span inside the label
  1830. *
  1831. * @return array An array in the format array( $label, $input )
  1832. */
  1833. function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
  1834. // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
  1835. $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
  1836. 'id' => 'wpSummary',
  1837. 'maxlength' => '200',
  1838. 'tabindex' => '1',
  1839. 'size' => 60,
  1840. 'spellcheck' => 'true',
  1841. ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
  1842. $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
  1843. 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
  1844. 'id' => "wpSummaryLabel"
  1845. );
  1846. $label = null;
  1847. if ( $labelText ) {
  1848. $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
  1849. $label = Xml::tags( 'span', $spanLabelAttrs, $label );
  1850. }
  1851. $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
  1852. return array( $label, $input );
  1853. }
  1854. /**
  1855. * @param $isSubjectPreview Boolean: true if this is the section subject/title
  1856. * up top, or false if this is the comment summary
  1857. * down below the textarea
  1858. * @param $summary String: The text of the summary to display
  1859. * @return String
  1860. */
  1861. protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
  1862. global $wgOut, $wgContLang;
  1863. # Add a class if 'missingsummary' is triggered to allow styling of the summary line
  1864. $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
  1865. if ( $isSubjectPreview ) {
  1866. if ( $this->nosummary ) {
  1867. return;
  1868. }
  1869. } else {
  1870. if ( !$this->mShowSummaryField ) {
  1871. return;
  1872. }
  1873. }
  1874. $summary = $wgContLang->recodeForEdit( $summary );
  1875. $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
  1876. list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
  1877. $wgOut->addHTML( "{$label} {$input}" );
  1878. }
  1879. /**
  1880. * @param $isSubjectPreview Boolean: true if this is the section subject/title
  1881. * up top, or false if this is the comment summary
  1882. * down below the textarea
  1883. * @param $summary String: the text of the summary to display
  1884. * @return String
  1885. */
  1886. protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
  1887. if ( !$summary || ( !$this->preview && !$this->diff ) )
  1888. return "";
  1889. global $wgParser;
  1890. if ( $isSubjectPreview )
  1891. $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
  1892. ->inContentLanguage()->text();
  1893. $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
  1894. $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
  1895. return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
  1896. }
  1897. protected function showFormBeforeText() {
  1898. global $wgOut;
  1899. $section = htmlspecialchars( $this->section );
  1900. $wgOut->addHTML( <<<HTML
  1901. <input type='hidden' value="{$section}" name="wpSection" />
  1902. <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
  1903. <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
  1904. <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
  1905. HTML
  1906. );
  1907. if ( !$this->checkUnicodeCompliantBrowser() )
  1908. $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
  1909. }
  1910. protected function showFormAfterText() {
  1911. global $wgOut, $wgUser;
  1912. /**
  1913. * To make it harder for someone to slip a user a page
  1914. * which submits an edit form to the wiki without their
  1915. * knowledge, a random token is associated with the login
  1916. * session. If it's not passed back with the submission,
  1917. * we won't save the page, or render user JavaScript and
  1918. * CSS previews.
  1919. *
  1920. * For anon editors, who may not have a session, we just
  1921. * include the constant suffix to prevent editing from
  1922. * broken text-mangling proxies.
  1923. */
  1924. $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
  1925. }
  1926. /**
  1927. * Subpage overridable method for printing the form for page content editing
  1928. * By default this simply outputs wpTextbox1
  1929. * Subclasses can override this to provide a custom UI for editing;
  1930. * be it a form, or simply wpTextbox1 with a modified content that will be
  1931. * reverse modified when extracted from the post data.
  1932. * Note that this is basically the inverse for importContentFormData
  1933. */
  1934. protected function showContentForm() {
  1935. $this->showTextbox1();
  1936. }
  1937. /**
  1938. * Method to output wpTextbox1
  1939. * The $textoverride method can be used by subclasses overriding showContentForm
  1940. * to pass back to this method.
  1941. *
  1942. * @param $customAttribs array of html attributes to use in the textarea
  1943. * @param $textoverride String: optional text to override $this->textarea1 with
  1944. */
  1945. protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
  1946. if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
  1947. $attribs = array( 'style' => 'display:none;' );
  1948. } else {
  1949. $classes = array(); // Textarea CSS
  1950. if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
  1951. # Is the title semi-protected?
  1952. if ( $this->mTitle->isSemiProtected() ) {
  1953. $classes[] = 'mw-textarea-sprotected';
  1954. } else {
  1955. # Then it must be protected based on static groups (regular)
  1956. $classes[] = 'mw-textarea-protected';
  1957. }
  1958. # Is the title cascade-protected?
  1959. if ( $this->mTitle->isCascadeProtected() ) {
  1960. $classes[] = 'mw-textarea-cprotected';
  1961. }
  1962. }
  1963. $attribs = array( 'tabindex' => 1 );
  1964. if ( is_array( $customAttribs ) ) {
  1965. $attribs += $customAttribs;
  1966. }
  1967. if ( count( $classes ) ) {
  1968. if ( isset( $attribs['class'] ) ) {
  1969. $classes[] = $attribs['class'];
  1970. }
  1971. $attribs['class'] = implode( ' ', $classes );
  1972. }
  1973. }
  1974. $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
  1975. }
  1976. protected function showTextbox2() {
  1977. $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
  1978. }
  1979. protected function showTextbox( $content, $name, $customAttribs = array() ) {
  1980. global $wgOut, $wgUser;
  1981. $wikitext = $this->safeUnicodeOutput( $content );
  1982. if ( strval( $wikitext ) !== '' ) {
  1983. // Ensure there's a newline at the end, otherwise adding lines
  1984. // is awkward.
  1985. // But don't add a newline if the ext is empty, or Firefox in XHTML
  1986. // mode will show an extra newline. A bit annoying.
  1987. $wikitext .= "\n";
  1988. }
  1989. $attribs = $customAttribs + array(
  1990. 'accesskey' => ',',
  1991. 'id' => $name,
  1992. 'cols' => $wgUser->getIntOption( 'cols' ),
  1993. 'rows' => $wgUser->getIntOption( 'rows' ),
  1994. 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
  1995. );
  1996. $pageLang = $this->mTitle->getPageLanguage();
  1997. $attribs['lang'] = $pageLang->getCode();
  1998. $attribs['dir'] = $pageLang->getDir();
  1999. $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
  2000. }
  2001. protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
  2002. global $wgOut;
  2003. $classes = array();
  2004. if ( $isOnTop )
  2005. $classes[] = 'ontop';
  2006. $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
  2007. if ( $this->formtype != 'preview' )
  2008. $attribs['style'] = 'display: none;';
  2009. $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
  2010. if ( $this->formtype == 'preview' ) {
  2011. $this->showPreview( $previewOutput );
  2012. }
  2013. $wgOut->addHTML( '</div>' );
  2014. if ( $this->formtype == 'diff' ) {
  2015. $this->showDiff();
  2016. }
  2017. }
  2018. /**
  2019. * Append preview output to $wgOut.
  2020. * Includes category rendering if this is a category page.
  2021. *
  2022. * @param $text String: the HTML to be output for the preview.
  2023. */
  2024. protected function showPreview( $text ) {
  2025. global $wgOut;
  2026. if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
  2027. $this->mArticle->openShowCategory();
  2028. }
  2029. # This hook seems slightly odd here, but makes things more
  2030. # consistent for extensions.
  2031. wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
  2032. $wgOut->addHTML( $text );
  2033. if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
  2034. $this->mArticle->closeShowCategory();
  2035. }
  2036. }
  2037. /**
  2038. * Get a diff between the current contents of the edit box and the
  2039. * version of the page we're editing from.
  2040. *
  2041. * If this is a section edit, we'll replace the section as for final
  2042. * save and then make a comparison.
  2043. */
  2044. function showDiff() {
  2045. global $wgUser, $wgContLang, $wgParser, $wgOut;
  2046. $oldtitlemsg = 'currentrev';
  2047. # if message does not exist, show diff against the preloaded default
  2048. if( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
  2049. $oldtext = $this->mTitle->getDefaultMessageText();
  2050. if( $oldtext !== false ) {
  2051. $oldtitlemsg = 'defaultmessagetext';
  2052. }
  2053. } else {
  2054. $oldtext = $this->mArticle->getRawText();
  2055. }
  2056. $newtext = $this->mArticle->replaceSection(
  2057. $this->section, $this->textbox1, $this->summary, $this->edittime );
  2058. wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
  2059. $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
  2060. $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
  2061. if ( $oldtext !== false || $newtext != '' ) {
  2062. $oldtitle = wfMessage( $oldtitlemsg )->parse();
  2063. $newtitle = wfMessage( 'yourtext' )->parse();
  2064. $de = new DifferenceEngine( $this->mArticle->getContext() );
  2065. $de->setText( $oldtext, $newtext );
  2066. $difftext = $de->getDiff( $oldtitle, $newtitle );
  2067. $de->showDiffStyle();
  2068. } else {
  2069. $difftext = '';
  2070. }
  2071. $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
  2072. }
  2073. /**
  2074. * Show the header copyright warning.
  2075. */
  2076. protected function showHeaderCopyrightWarning() {
  2077. $msg = 'editpage-head-copy-warn';
  2078. if ( !wfMessage( $msg )->isDisabled() ) {
  2079. global $wgOut;
  2080. $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
  2081. 'editpage-head-copy-warn' );
  2082. }
  2083. }
  2084. /**
  2085. * Give a chance for site and per-namespace customizations of
  2086. * terms of service summary link that might exist separately
  2087. * from the copyright notice.
  2088. *
  2089. * This will display between the save button and the edit tools,
  2090. * so should remain short!
  2091. */
  2092. protected function showTosSummary() {
  2093. $msg = 'editpage-tos-summary';
  2094. wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
  2095. if ( !wfMessage( $msg )->isDisabled() ) {
  2096. global $wgOut;
  2097. $wgOut->addHTML( '<div class="mw-tos-summary">' );
  2098. $wgOut->addWikiMsg( $msg );
  2099. $wgOut->addHTML( '</div>' );
  2100. }
  2101. }
  2102. protected function showEditTools() {
  2103. global $wgOut;
  2104. $wgOut->addHTML( '<div class="mw-editTools">' .
  2105. wfMessage( 'edittools' )->inContentLanguage()->parse() .
  2106. '</div>' );
  2107. }
  2108. /**
  2109. * Get the copyright warning
  2110. *
  2111. * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
  2112. */
  2113. protected function getCopywarn() {
  2114. return self::getCopyrightWarning( $this->mTitle );
  2115. }
  2116. public static function getCopyrightWarning( $title ) {
  2117. global $wgRightsText;
  2118. if ( $wgRightsText ) {
  2119. $copywarnMsg = array( 'copyrightwarning',
  2120. '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
  2121. $wgRightsText );
  2122. } else {
  2123. $copywarnMsg = array( 'copyrightwarning2',
  2124. '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
  2125. }
  2126. // Allow for site and per-namespace customization of contribution/copyright notice.
  2127. wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
  2128. return "<div id=\"editpage-copywarn\">\n" .
  2129. call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
  2130. }
  2131. protected function showStandardInputs( &$tabindex = 2 ) {
  2132. global $wgOut;
  2133. $wgOut->addHTML( "<div class='editOptions'>\n" );
  2134. if ( $this->section != 'new' ) {
  2135. $this->showSummaryInput( false, $this->summary );
  2136. $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
  2137. }
  2138. $checkboxes = $this->getCheckboxes( $tabindex,
  2139. array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
  2140. $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
  2141. // Show copyright warning.
  2142. $wgOut->addWikiText( $this->getCopywarn() );
  2143. $wgOut->addHTML( $this->editFormTextAfterWarn );
  2144. $wgOut->addHTML( "<div class='editButtons'>\n" );
  2145. $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
  2146. $cancel = $this->getCancelLink();
  2147. if ( $cancel !== '' ) {
  2148. $cancel .= wfMessage( 'pipe-separator' )->text();
  2149. }
  2150. $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
  2151. $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
  2152. wfMessage( 'edithelp' )->escaped() . '</a> ' .
  2153. wfMessage( 'newwindow' )->parse();
  2154. $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
  2155. $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
  2156. $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
  2157. }
  2158. /**
  2159. * Show an edit conflict. textbox1 is already shown in showEditForm().
  2160. * If you want to use another entry point to this function, be careful.
  2161. */
  2162. protected function showConflict() {
  2163. global $wgOut;
  2164. if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
  2165. $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
  2166. $de = new DifferenceEngine( $this->mArticle->getContext() );
  2167. $de->setText( $this->textbox2, $this->textbox1 );
  2168. $de->showDiff(
  2169. wfMessage( 'yourtext' )->parse(),
  2170. wfMessage( 'storedversion' )->text()
  2171. );
  2172. $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
  2173. $this->showTextbox2();
  2174. }
  2175. }
  2176. /**
  2177. * @return string
  2178. */
  2179. public function getCancelLink() {
  2180. $cancelParams = array();
  2181. if ( !$this->isConflict && $this->oldid > 0 ) {
  2182. $cancelParams['oldid'] = $this->oldid;
  2183. }
  2184. return Linker::linkKnown(
  2185. $this->getContextTitle(),
  2186. wfMessage( 'cancel' )->parse(),
  2187. array( 'id' => 'mw-editform-cancel' ),
  2188. $cancelParams
  2189. );
  2190. }
  2191. /**
  2192. * Returns the URL to use in the form's action attribute.
  2193. * This is used by EditPage subclasses when simply customizing the action
  2194. * variable in the constructor is not enough. This can be used when the
  2195. * EditPage lives inside of a Special page rather than a custom page action.
  2196. *
  2197. * @param $title Title object for which is being edited (where we go to for &action= links)
  2198. * @return string
  2199. */
  2200. protected function getActionURL( Title $title ) {
  2201. return $title->getLocalURL( array( 'action' => $this->action ) );
  2202. }
  2203. /**
  2204. * Check if a page was deleted while the user was editing it, before submit.
  2205. * Note that we rely on the logging table, which hasn't been always there,
  2206. * but that doesn't matter, because this only applies to brand new
  2207. * deletes.
  2208. */
  2209. protected function wasDeletedSinceLastEdit() {
  2210. if ( $this->deletedSinceEdit !== null ) {
  2211. return $this->deletedSinceEdit;
  2212. }
  2213. $this->deletedSinceEdit = false;
  2214. if ( $this->mTitle->isDeletedQuick() ) {
  2215. $this->lastDelete = $this->getLastDelete();
  2216. if ( $this->lastDelete ) {
  2217. $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
  2218. if ( $deleteTime > $this->starttime ) {
  2219. $this->deletedSinceEdit = true;
  2220. }
  2221. }
  2222. }
  2223. return $this->deletedSinceEdit;
  2224. }
  2225. protected function getLastDelete() {
  2226. $dbr = wfGetDB( DB_SLAVE );
  2227. $data = $dbr->selectRow(
  2228. array( 'logging', 'user' ),
  2229. array( 'log_type',
  2230. 'log_action',
  2231. 'log_timestamp',
  2232. 'log_user',
  2233. 'log_namespace',
  2234. 'log_title',
  2235. 'log_comment',
  2236. 'log_params',
  2237. 'log_deleted',
  2238. 'user_name' ),
  2239. array( 'log_namespace' => $this->mTitle->getNamespace(),
  2240. 'log_title' => $this->mTitle->getDBkey(),
  2241. 'log_type' => 'delete',
  2242. 'log_action' => 'delete',
  2243. 'user_id=log_user' ),
  2244. __METHOD__,
  2245. array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
  2246. );
  2247. // Quick paranoid permission checks...
  2248. if ( is_object( $data ) ) {
  2249. if ( $data->log_deleted & LogPage::DELETED_USER )
  2250. $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
  2251. if ( $data->log_deleted & LogPage::DELETED_COMMENT )
  2252. $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
  2253. }
  2254. return $data;
  2255. }
  2256. /**
  2257. * Get the rendered text for previewing.
  2258. * @return string
  2259. */
  2260. function getPreviewText() {
  2261. global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
  2262. wfProfileIn( __METHOD__ );
  2263. if ( $wgRawHtml && !$this->mTokenOk ) {
  2264. // Could be an offsite preview attempt. This is very unsafe if
  2265. // HTML is enabled, as it could be an attack.
  2266. $parsedNote = '';
  2267. if ( $this->textbox1 !== '' ) {
  2268. // Do not put big scary notice, if previewing the empty
  2269. // string, which happens when you initially edit
  2270. // a category page, due to automatic preview-on-open.
  2271. $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
  2272. wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
  2273. }
  2274. wfProfileOut( __METHOD__ );
  2275. return $parsedNote;
  2276. }
  2277. if ( $this->mTriedSave && !$this->mTokenOk ) {
  2278. if ( $this->mTokenOkExceptSuffix ) {
  2279. $note = wfMessage( 'token_suffix_mismatch' )->plain();
  2280. } else {
  2281. $note = wfMessage( 'session_fail_preview' )->plain();
  2282. }
  2283. } elseif ( $this->incompleteForm ) {
  2284. $note = wfMessage( 'edit_form_incomplete' )->plain();
  2285. } else {
  2286. $note = wfMessage( 'previewnote' )->plain() .
  2287. ' [[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
  2288. }
  2289. $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
  2290. $parserOptions->setEditSection( false );
  2291. $parserOptions->setIsPreview( true );
  2292. $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
  2293. # don't parse non-wikitext pages, show message about preview
  2294. if ( $this->mTitle->isCssJsSubpage() || !$this->mTitle->isWikitextPage() ) {
  2295. if ( $this->mTitle->isCssJsSubpage() ) {
  2296. $level = 'user';
  2297. } elseif ( $this->mTitle->isCssOrJsPage() ) {
  2298. $level = 'site';
  2299. } else {
  2300. $level = false;
  2301. }
  2302. # Used messages to make sure grep find them:
  2303. # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
  2304. $class = 'mw-code';
  2305. if ( $level ) {
  2306. if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
  2307. $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMessage( "{$level}csspreview" )->text() . "\n</div>";
  2308. $class .= " mw-css";
  2309. } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
  2310. $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMessage( "{$level}jspreview" )->text() . "\n</div>";
  2311. $class .= " mw-js";
  2312. } else {
  2313. throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
  2314. }
  2315. $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
  2316. $previewHTML = $parserOutput->getText();
  2317. } else {
  2318. $previewHTML = '';
  2319. }
  2320. $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
  2321. } else {
  2322. $toparse = $this->textbox1;
  2323. # If we're adding a comment, we need to show the
  2324. # summary as the headline
  2325. if ( $this->section == "new" && $this->summary != "" ) {
  2326. $toparse = wfMessage( 'newsectionheaderdefaultlevel', $this->summary )->inContentLanguage()->text() . "\n\n" . $toparse;
  2327. }
  2328. wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
  2329. $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
  2330. $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
  2331. $rt = Title::newFromRedirectArray( $this->textbox1 );
  2332. if ( $rt ) {
  2333. $previewHTML = $this->mArticle->viewRedirect( $rt, false );
  2334. } else {
  2335. $previewHTML = $parserOutput->getText();
  2336. }
  2337. $this->mParserOutput = $parserOutput;
  2338. $wgOut->addParserOutputNoText( $parserOutput );
  2339. if ( count( $parserOutput->getWarnings() ) ) {
  2340. $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
  2341. }
  2342. }
  2343. if ( $this->isConflict ) {
  2344. $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
  2345. } else {
  2346. $conflict = '<hr />';
  2347. }
  2348. $previewhead = "<div class='previewnote'>\n" .
  2349. '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
  2350. $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
  2351. $pageLang = $this->mTitle->getPageLanguage();
  2352. $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
  2353. 'class' => 'mw-content-' . $pageLang->getDir() );
  2354. $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
  2355. wfProfileOut( __METHOD__ );
  2356. return $previewhead . $previewHTML . $this->previewTextAfterContent;
  2357. }
  2358. /**
  2359. * @return Array
  2360. */
  2361. function getTemplates() {
  2362. if ( $this->preview || $this->section != '' ) {
  2363. $templates = array();
  2364. if ( !isset( $this->mParserOutput ) ) {
  2365. return $templates;
  2366. }
  2367. foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
  2368. foreach ( array_keys( $template ) as $dbk ) {
  2369. $templates[] = Title::makeTitle( $ns, $dbk );
  2370. }
  2371. }
  2372. return $templates;
  2373. } else {
  2374. return $this->mTitle->getTemplateLinksFrom();
  2375. }
  2376. }
  2377. /**
  2378. * Shows a bulletin board style toolbar for common editing functions.
  2379. * It can be disabled in the user preferences.
  2380. * The necessary JavaScript code can be found in skins/common/edit.js.
  2381. *
  2382. * @return string
  2383. */
  2384. static function getEditToolbar() {
  2385. global $wgStylePath, $wgContLang, $wgLang, $wgOut;
  2386. global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
  2387. $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
  2388. /**
  2389. * $toolarray is an array of arrays each of which includes the
  2390. * filename of the button image (without path), the opening
  2391. * tag, the closing tag, optionally a sample text that is
  2392. * inserted between the two when no selection is highlighted
  2393. * and. The tip text is shown when the user moves the mouse
  2394. * over the button.
  2395. *
  2396. * Also here: accesskeys (key), which are not used yet until
  2397. * someone can figure out a way to make them work in
  2398. * IE. However, we should make sure these keys are not defined
  2399. * on the edit page.
  2400. */
  2401. $toolarray = array(
  2402. array(
  2403. 'image' => $wgLang->getImageFile( 'button-bold' ),
  2404. 'id' => 'mw-editbutton-bold',
  2405. 'open' => '\'\'\'',
  2406. 'close' => '\'\'\'',
  2407. 'sample' => wfMessage( 'bold_sample' )->text(),
  2408. 'tip' => wfMessage( 'bold_tip' )->text(),
  2409. 'key' => 'B'
  2410. ),
  2411. array(
  2412. 'image' => $wgLang->getImageFile( 'button-italic' ),
  2413. 'id' => 'mw-editbutton-italic',
  2414. 'open' => '\'\'',
  2415. 'close' => '\'\'',
  2416. 'sample' => wfMessage( 'italic_sample' )->text(),
  2417. 'tip' => wfMessage( 'italic_tip' )->text(),
  2418. 'key' => 'I'
  2419. ),
  2420. array(
  2421. 'image' => $wgLang->getImageFile( 'button-link' ),
  2422. 'id' => 'mw-editbutton-link',
  2423. 'open' => '[[',
  2424. 'close' => ']]',
  2425. 'sample' => wfMessage( 'link_sample' )->text(),
  2426. 'tip' => wfMessage( 'link_tip' )->text(),
  2427. 'key' => 'L'
  2428. ),
  2429. array(
  2430. 'image' => $wgLang->getImageFile( 'button-extlink' ),
  2431. 'id' => 'mw-editbutton-extlink',
  2432. 'open' => '[',
  2433. 'close' => ']',
  2434. 'sample' => wfMessage( 'extlink_sample' )->text(),
  2435. 'tip' => wfMessage( 'extlink_tip' )->text(),
  2436. 'key' => 'X'
  2437. ),
  2438. array(
  2439. 'image' => $wgLang->getImageFile( 'button-headline' ),
  2440. 'id' => 'mw-editbutton-headline',
  2441. 'open' => "\n== ",
  2442. 'close' => " ==\n",
  2443. 'sample' => wfMessage( 'headline_sample' )->text(),
  2444. 'tip' => wfMessage( 'headline_tip' )->text(),
  2445. 'key' => 'H'
  2446. ),
  2447. $imagesAvailable ? array(
  2448. 'image' => $wgLang->getImageFile( 'button-image' ),
  2449. 'id' => 'mw-editbutton-image',
  2450. 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
  2451. 'close' => ']]',
  2452. 'sample' => wfMessage( 'image_sample' )->text(),
  2453. 'tip' => wfMessage( 'image_tip' )->text(),
  2454. 'key' => 'D',
  2455. ) : false,
  2456. $imagesAvailable ? array(
  2457. 'image' => $wgLang->getImageFile( 'button-media' ),
  2458. 'id' => 'mw-editbutton-media',
  2459. 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
  2460. 'close' => ']]',
  2461. 'sample' => wfMessage( 'media_sample' )->text(),
  2462. 'tip' => wfMessage( 'media_tip' )->text(),
  2463. 'key' => 'M'
  2464. ) : false,
  2465. $wgUseTeX ? array(
  2466. 'image' => $wgLang->getImageFile( 'button-math' ),
  2467. 'id' => 'mw-editbutton-math',
  2468. 'open' => "<math>",
  2469. 'close' => "</math>",
  2470. 'sample' => wfMessage( 'math_sample' )->text(),
  2471. 'tip' => wfMessage( 'math_tip' )->text(),
  2472. 'key' => 'C'
  2473. ) : false,
  2474. array(
  2475. 'image' => $wgLang->getImageFile( 'button-nowiki' ),
  2476. 'id' => 'mw-editbutton-nowiki',
  2477. 'open' => "<nowiki>",
  2478. 'close' => "</nowiki>",
  2479. 'sample' => wfMessage( 'nowiki_sample' )->text(),
  2480. 'tip' => wfMessage( 'nowiki_tip' )->text(),
  2481. 'key' => 'N'
  2482. ),
  2483. array(
  2484. 'image' => $wgLang->getImageFile( 'button-sig' ),
  2485. 'id' => 'mw-editbutton-signature',
  2486. 'open' => '--~~~~',
  2487. 'close' => '',
  2488. 'sample' => '',
  2489. 'tip' => wfMessage( 'sig_tip' )->text(),
  2490. 'key' => 'Y'
  2491. ),
  2492. array(
  2493. 'image' => $wgLang->getImageFile( 'button-hr' ),
  2494. 'id' => 'mw-editbutton-hr',
  2495. 'open' => "\n----\n",
  2496. 'close' => '',
  2497. 'sample' => '',
  2498. 'tip' => wfMessage( 'hr_tip' )->text(),
  2499. 'key' => 'R'
  2500. )
  2501. );
  2502. $script = 'mw.loader.using("mediawiki.action.edit", function() {';
  2503. foreach ( $toolarray as $tool ) {
  2504. if ( !$tool ) {
  2505. continue;
  2506. }
  2507. $params = array(
  2508. $image = $wgStylePath . '/common/images/' . $tool['image'],
  2509. // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
  2510. // Older browsers show a "speedtip" type message only for ALT.
  2511. // Ideally these should be different, realistically they
  2512. // probably don't need to be.
  2513. $tip = $tool['tip'],
  2514. $open = $tool['open'],
  2515. $close = $tool['close'],
  2516. $sample = $tool['sample'],
  2517. $cssId = $tool['id'],
  2518. );
  2519. $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
  2520. }
  2521. // This used to be called on DOMReady from mediawiki.action.edit, which
  2522. // ended up causing race conditions with the setup code above.
  2523. $script .= "\n" .
  2524. "// Create button bar\n" .
  2525. "$(function() { mw.toolbar.init(); } );\n";
  2526. $script .= '});';
  2527. $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
  2528. $toolbar = '<div id="toolbar"></div>';
  2529. wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
  2530. return $toolbar;
  2531. }
  2532. /**
  2533. * Returns an array of html code of the following checkboxes:
  2534. * minor and watch
  2535. *
  2536. * @param $tabindex int Current tabindex
  2537. * @param $checked Array of checkbox => bool, where bool indicates the checked
  2538. * status of the checkbox
  2539. *
  2540. * @return array
  2541. */
  2542. public function getCheckboxes( &$tabindex, $checked ) {
  2543. global $wgUser;
  2544. $checkboxes = array();
  2545. // don't show the minor edit checkbox if it's a new page or section
  2546. if ( !$this->isNew ) {
  2547. $checkboxes['minor'] = '';
  2548. $minorLabel = wfMessage( 'minoredit' )->parse();
  2549. if ( $wgUser->isAllowed( 'minoredit' ) ) {
  2550. $attribs = array(
  2551. 'tabindex' => ++$tabindex,
  2552. 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
  2553. 'id' => 'wpMinoredit',
  2554. );
  2555. $checkboxes['minor'] =
  2556. Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
  2557. "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
  2558. Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
  2559. ">{$minorLabel}</label>";
  2560. }
  2561. }
  2562. $watchLabel = wfMessage( 'watchthis' )->parse();
  2563. $checkboxes['watch'] = '';
  2564. if ( $wgUser->isLoggedIn() ) {
  2565. $attribs = array(
  2566. 'tabindex' => ++$tabindex,
  2567. 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
  2568. 'id' => 'wpWatchthis',
  2569. );
  2570. $checkboxes['watch'] =
  2571. Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
  2572. "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
  2573. Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
  2574. ">{$watchLabel}</label>";
  2575. }
  2576. wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
  2577. return $checkboxes;
  2578. }
  2579. /**
  2580. * Returns an array of html code of the following buttons:
  2581. * save, diff, preview and live
  2582. *
  2583. * @param $tabindex int Current tabindex
  2584. *
  2585. * @return array
  2586. */
  2587. public function getEditButtons( &$tabindex ) {
  2588. $buttons = array();
  2589. $temp = array(
  2590. 'id' => 'wpSave',
  2591. 'name' => 'wpSave',
  2592. 'type' => 'submit',
  2593. 'tabindex' => ++$tabindex,
  2594. 'value' => wfMessage( 'savearticle' )->text(),
  2595. 'accesskey' => wfMessage( 'accesskey-save' )->text(),
  2596. 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
  2597. );
  2598. $buttons['save'] = Xml::element( 'input', $temp, '' );
  2599. ++$tabindex; // use the same for preview and live preview
  2600. $temp = array(
  2601. 'id' => 'wpPreview',
  2602. 'name' => 'wpPreview',
  2603. 'type' => 'submit',
  2604. 'tabindex' => $tabindex,
  2605. 'value' => wfMessage( 'showpreview' )->text(),
  2606. 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
  2607. 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
  2608. );
  2609. $buttons['preview'] = Xml::element( 'input', $temp, '' );
  2610. $buttons['live'] = '';
  2611. $temp = array(
  2612. 'id' => 'wpDiff',
  2613. 'name' => 'wpDiff',
  2614. 'type' => 'submit',
  2615. 'tabindex' => ++$tabindex,
  2616. 'value' => wfMessage( 'showdiff' )->text(),
  2617. 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
  2618. 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
  2619. );
  2620. $buttons['diff'] = Xml::element( 'input', $temp, '' );
  2621. wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
  2622. return $buttons;
  2623. }
  2624. /**
  2625. * Output preview text only. This can be sucked into the edit page
  2626. * via JavaScript, and saves the server time rendering the skin as
  2627. * well as theoretically being more robust on the client (doesn't
  2628. * disturb the edit box's undo history, won't eat your text on
  2629. * failure, etc).
  2630. *
  2631. * @todo This doesn't include category or interlanguage links.
  2632. * Would need to enhance it a bit, "<s>maybe wrap them in XML
  2633. * or something...</s>" that might also require more skin
  2634. * initialization, so check whether that's a problem.
  2635. */
  2636. function livePreview() {
  2637. global $wgOut;
  2638. $wgOut->disable();
  2639. header( 'Content-type: text/xml; charset=utf-8' );
  2640. header( 'Cache-control: no-cache' );
  2641. $previewText = $this->getPreviewText();
  2642. #$categories = $skin->getCategoryLinks();
  2643. $s =
  2644. '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
  2645. Xml::tags( 'livepreview', null,
  2646. Xml::element( 'preview', null, $previewText )
  2647. #. Xml::element( 'category', null, $categories )
  2648. );
  2649. echo $s;
  2650. }
  2651. /**
  2652. * Call the stock "user is blocked" page
  2653. *
  2654. * @deprecated in 1.19; throw an exception directly instead
  2655. */
  2656. function blockedPage() {
  2657. wfDeprecated( __METHOD__, '1.19' );
  2658. global $wgUser;
  2659. throw new UserBlockedError( $wgUser->getBlock() );
  2660. }
  2661. /**
  2662. * Produce the stock "please login to edit pages" page
  2663. *
  2664. * @deprecated in 1.19; throw an exception directly instead
  2665. */
  2666. function userNotLoggedInPage() {
  2667. wfDeprecated( __METHOD__, '1.19' );
  2668. throw new PermissionsError( 'edit' );
  2669. }
  2670. /**
  2671. * Show an error page saying to the user that he has insufficient permissions
  2672. * to create a new page
  2673. *
  2674. * @deprecated in 1.19; throw an exception directly instead
  2675. */
  2676. function noCreatePermission() {
  2677. wfDeprecated( __METHOD__, '1.19' );
  2678. $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
  2679. throw new PermissionsError( $permission );
  2680. }
  2681. /**
  2682. * Creates a basic error page which informs the user that
  2683. * they have attempted to edit a nonexistent section.
  2684. */
  2685. function noSuchSectionPage() {
  2686. global $wgOut;
  2687. $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
  2688. $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
  2689. wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
  2690. $wgOut->addHTML( $res );
  2691. $wgOut->returnToMain( false, $this->mTitle );
  2692. }
  2693. /**
  2694. * Produce the stock "your edit contains spam" page
  2695. *
  2696. * @param $match string Text which triggered one or more filters
  2697. * @deprecated since 1.17 Use method spamPageWithContent() instead
  2698. */
  2699. static function spamPage( $match = false ) {
  2700. wfDeprecated( __METHOD__, '1.17' );
  2701. global $wgOut, $wgTitle;
  2702. $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
  2703. $wgOut->addHTML( '<div id="spamprotected">' );
  2704. $wgOut->addWikiMsg( 'spamprotectiontext' );
  2705. if ( $match ) {
  2706. $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
  2707. }
  2708. $wgOut->addHTML( '</div>' );
  2709. $wgOut->returnToMain( false, $wgTitle );
  2710. }
  2711. /**
  2712. * Show "your edit contains spam" page with your diff and text
  2713. *
  2714. * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
  2715. */
  2716. public function spamPageWithContent( $match = false ) {
  2717. global $wgOut, $wgLang;
  2718. $this->textbox2 = $this->textbox1;
  2719. if( is_array( $match ) ){
  2720. $match = $wgLang->listToText( $match );
  2721. }
  2722. $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
  2723. $wgOut->addHTML( '<div id="spamprotected">' );
  2724. $wgOut->addWikiMsg( 'spamprotectiontext' );
  2725. if ( $match ) {
  2726. $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
  2727. }
  2728. $wgOut->addHTML( '</div>' );
  2729. $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
  2730. $this->showDiff();
  2731. $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
  2732. $this->showTextbox2();
  2733. $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
  2734. }
  2735. /**
  2736. * Format an anchor fragment as it would appear for a given section name
  2737. * @param $text String
  2738. * @return String
  2739. * @private
  2740. */
  2741. function sectionAnchor( $text ) {
  2742. global $wgParser;
  2743. return $wgParser->guessSectionNameFromWikiText( $text );
  2744. }
  2745. /**
  2746. * Check if the browser is on a blacklist of user-agents known to
  2747. * mangle UTF-8 data on form submission. Returns true if Unicode
  2748. * should make it through, false if it's known to be a problem.
  2749. * @return bool
  2750. * @private
  2751. */
  2752. function checkUnicodeCompliantBrowser() {
  2753. global $wgBrowserBlackList, $wgRequest;
  2754. $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
  2755. if ( $currentbrowser === false ) {
  2756. // No User-Agent header sent? Trust it by default...
  2757. return true;
  2758. }
  2759. foreach ( $wgBrowserBlackList as $browser ) {
  2760. if ( preg_match( $browser, $currentbrowser ) ) {
  2761. return false;
  2762. }
  2763. }
  2764. return true;
  2765. }
  2766. /**
  2767. * Filter an input field through a Unicode de-armoring process if it
  2768. * came from an old browser with known broken Unicode editing issues.
  2769. *
  2770. * @param $request WebRequest
  2771. * @param $field String
  2772. * @return String
  2773. * @private
  2774. */
  2775. function safeUnicodeInput( $request, $field ) {
  2776. $text = rtrim( $request->getText( $field ) );
  2777. return $request->getBool( 'safemode' )
  2778. ? $this->unmakesafe( $text )
  2779. : $text;
  2780. }
  2781. /**
  2782. * @param $request WebRequest
  2783. * @param $text string
  2784. * @return string
  2785. */
  2786. function safeUnicodeText( $request, $text ) {
  2787. $text = rtrim( $text );
  2788. return $request->getBool( 'safemode' )
  2789. ? $this->unmakesafe( $text )
  2790. : $text;
  2791. }
  2792. /**
  2793. * Filter an output field through a Unicode armoring process if it is
  2794. * going to an old browser with known broken Unicode editing issues.
  2795. *
  2796. * @param $text String
  2797. * @return String
  2798. * @private
  2799. */
  2800. function safeUnicodeOutput( $text ) {
  2801. global $wgContLang;
  2802. $codedText = $wgContLang->recodeForEdit( $text );
  2803. return $this->checkUnicodeCompliantBrowser()
  2804. ? $codedText
  2805. : $this->makesafe( $codedText );
  2806. }
  2807. /**
  2808. * A number of web browsers are known to corrupt non-ASCII characters
  2809. * in a UTF-8 text editing environment. To protect against this,
  2810. * detected browsers will be served an armored version of the text,
  2811. * with non-ASCII chars converted to numeric HTML character references.
  2812. *
  2813. * Preexisting such character references will have a 0 added to them
  2814. * to ensure that round-trips do not alter the original data.
  2815. *
  2816. * @param $invalue String
  2817. * @return String
  2818. * @private
  2819. */
  2820. function makesafe( $invalue ) {
  2821. // Armor existing references for reversability.
  2822. $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
  2823. $bytesleft = 0;
  2824. $result = "";
  2825. $working = 0;
  2826. for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
  2827. $bytevalue = ord( $invalue[$i] );
  2828. if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
  2829. $result .= chr( $bytevalue );
  2830. $bytesleft = 0;
  2831. } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
  2832. $working = $working << 6;
  2833. $working += ( $bytevalue & 0x3F );
  2834. $bytesleft--;
  2835. if ( $bytesleft <= 0 ) {
  2836. $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
  2837. }
  2838. } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
  2839. $working = $bytevalue & 0x1F;
  2840. $bytesleft = 1;
  2841. } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
  2842. $working = $bytevalue & 0x0F;
  2843. $bytesleft = 2;
  2844. } else { // 1111 0xxx
  2845. $working = $bytevalue & 0x07;
  2846. $bytesleft = 3;
  2847. }
  2848. }
  2849. return $result;
  2850. }
  2851. /**
  2852. * Reverse the previously applied transliteration of non-ASCII characters
  2853. * back to UTF-8. Used to protect data from corruption by broken web browsers
  2854. * as listed in $wgBrowserBlackList.
  2855. *
  2856. * @param $invalue String
  2857. * @return String
  2858. * @private
  2859. */
  2860. function unmakesafe( $invalue ) {
  2861. $result = "";
  2862. for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
  2863. if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
  2864. $i += 3;
  2865. $hexstring = "";
  2866. do {
  2867. $hexstring .= $invalue[$i];
  2868. $i++;
  2869. } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
  2870. // Do some sanity checks. These aren't needed for reversability,
  2871. // but should help keep the breakage down if the editor
  2872. // breaks one of the entities whilst editing.
  2873. if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
  2874. $codepoint = hexdec( $hexstring );
  2875. $result .= codepointToUtf8( $codepoint );
  2876. } else {
  2877. $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
  2878. }
  2879. } else {
  2880. $result .= substr( $invalue, $i, 1 );
  2881. }
  2882. }
  2883. // reverse the transform that we made for reversability reasons.
  2884. return strtr( $result, array( "&#x0" => "&#x" ) );
  2885. }
  2886. }