Merge "Use HTML::hidden to create input fields"
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * User interface for page editing.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
31 * interfaces.
32 *
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
38 *
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
41 */
42 class EditPage {
43 /**
44 * Status: Article successfully updated
45 */
46 const AS_SUCCESS_UPDATE = 200;
47
48 /**
49 * Status: Article successfully created
50 */
51 const AS_SUCCESS_NEW_ARTICLE = 201;
52
53 /**
54 * Status: Article update aborted by a hook function
55 */
56 const AS_HOOK_ERROR = 210;
57
58 /**
59 * Status: A hook function returned an error
60 */
61 const AS_HOOK_ERROR_EXPECTED = 212;
62
63 /**
64 * Status: User is blocked from editing this page
65 */
66 const AS_BLOCKED_PAGE_FOR_USER = 215;
67
68 /**
69 * Status: Content too big (> $wgMaxArticleSize)
70 */
71 const AS_CONTENT_TOO_BIG = 216;
72
73 /**
74 * Status: this anonymous user is not allowed to edit this page
75 */
76 const AS_READ_ONLY_PAGE_ANON = 218;
77
78 /**
79 * Status: this logged in user is not allowed to edit this page
80 */
81 const AS_READ_ONLY_PAGE_LOGGED = 219;
82
83 /**
84 * Status: wiki is in readonly mode (wfReadOnly() == true)
85 */
86 const AS_READ_ONLY_PAGE = 220;
87
88 /**
89 * Status: rate limiter for action 'edit' was tripped
90 */
91 const AS_RATE_LIMITED = 221;
92
93 /**
94 * Status: article was deleted while editing and param wpRecreate == false or form
95 * was not posted
96 */
97 const AS_ARTICLE_WAS_DELETED = 222;
98
99 /**
100 * Status: user tried to create this page, but is not allowed to do that
101 * ( Title->userCan('create') == false )
102 */
103 const AS_NO_CREATE_PERMISSION = 223;
104
105 /**
106 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
107 */
108 const AS_BLANK_ARTICLE = 224;
109
110 /**
111 * Status: (non-resolvable) edit conflict
112 */
113 const AS_CONFLICT_DETECTED = 225;
114
115 /**
116 * Status: no edit summary given and the user has forceeditsummary set and the user is not
117 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
118 */
119 const AS_SUMMARY_NEEDED = 226;
120
121 /**
122 * Status: user tried to create a new section without content
123 */
124 const AS_TEXTBOX_EMPTY = 228;
125
126 /**
127 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
128 */
129 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
130
131 /**
132 * Status: WikiPage::doEdit() was unsuccessful
133 */
134 const AS_END = 231;
135
136 /**
137 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
138 */
139 const AS_SPAM_ERROR = 232;
140
141 /**
142 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
143 */
144 const AS_IMAGE_REDIRECT_ANON = 233;
145
146 /**
147 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
148 */
149 const AS_IMAGE_REDIRECT_LOGGED = 234;
150
151 /**
152 * Status: user tried to modify the content model, but is not allowed to do that
153 * ( User::isAllowed('editcontentmodel') == false )
154 */
155 const AS_NO_CHANGE_CONTENT_MODEL = 235;
156
157 /**
158 * Status: user tried to create self-redirect (redirect to the same article) and
159 * wpIgnoreSelfRedirect == false
160 */
161 const AS_SELF_REDIRECT = 236;
162
163 /**
164 * Status: an error relating to change tagging. Look at the message key for
165 * more details
166 */
167 const AS_CHANGE_TAG_ERROR = 237;
168
169 /**
170 * Status: can't parse content
171 */
172 const AS_PARSE_ERROR = 240;
173
174 /**
175 * Status: when changing the content model is disallowed due to
176 * $wgContentHandlerUseDB being false
177 */
178 const AS_CANNOT_USE_CUSTOM_MODEL = 241;
179
180 /**
181 * HTML id and name for the beginning of the edit form.
182 */
183 const EDITFORM_ID = 'editform';
184
185 /**
186 * Prefix of key for cookie used to pass post-edit state.
187 * The revision id edited is added after this
188 */
189 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
190
191 /**
192 * Duration of PostEdit cookie, in seconds.
193 * The cookie will be removed instantly if the JavaScript runs.
194 *
195 * Otherwise, though, we don't want the cookies to accumulate.
196 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
197 * limit of only 20 cookies per domain. This still applies at least to some
198 * versions of IE without full updates:
199 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
200 *
201 * A value of 20 minutes should be enough to take into account slow loads and minor
202 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
203 */
204 const POST_EDIT_COOKIE_DURATION = 1200;
205
206 /** @var Article */
207 public $mArticle;
208 /** @var WikiPage */
209 private $page;
210
211 /** @var Title */
212 public $mTitle;
213
214 /** @var null|Title */
215 private $mContextTitle = null;
216
217 /** @var string */
218 public $action = 'submit';
219
220 /** @var bool */
221 public $isConflict = false;
222
223 /** @var bool */
224 public $isCssJsSubpage = false;
225
226 /** @var bool */
227 public $isCssSubpage = false;
228
229 /** @var bool */
230 public $isJsSubpage = false;
231
232 /** @var bool */
233 public $isWrongCaseCssJsPage = false;
234
235 /** @var bool New page or new section */
236 public $isNew = false;
237
238 /** @var bool */
239 public $deletedSinceEdit;
240
241 /** @var string */
242 public $formtype;
243
244 /** @var bool */
245 public $firsttime;
246
247 /** @var bool|stdClass */
248 public $lastDelete;
249
250 /** @var bool */
251 public $mTokenOk = false;
252
253 /** @var bool */
254 public $mTokenOkExceptSuffix = false;
255
256 /** @var bool */
257 public $mTriedSave = false;
258
259 /** @var bool */
260 public $incompleteForm = false;
261
262 /** @var bool */
263 public $tooBig = false;
264
265 /** @var bool */
266 public $missingComment = false;
267
268 /** @var bool */
269 public $missingSummary = false;
270
271 /** @var bool */
272 public $allowBlankSummary = false;
273
274 /** @var bool */
275 protected $blankArticle = false;
276
277 /** @var bool */
278 protected $allowBlankArticle = false;
279
280 /** @var bool */
281 protected $selfRedirect = false;
282
283 /** @var bool */
284 protected $allowSelfRedirect = false;
285
286 /** @var string */
287 public $autoSumm = '';
288
289 /** @var string */
290 public $hookError = '';
291
292 /** @var ParserOutput */
293 public $mParserOutput;
294
295 /** @var bool Has a summary been preset using GET parameter &summary= ? */
296 public $hasPresetSummary = false;
297
298 /** @var Revision|bool */
299 public $mBaseRevision = false;
300
301 /** @var bool */
302 public $mShowSummaryField = true;
303
304 # Form values
305
306 /** @var bool */
307 public $save = false;
308
309 /** @var bool */
310 public $preview = false;
311
312 /** @var bool */
313 public $diff = false;
314
315 /** @var bool */
316 public $minoredit = false;
317
318 /** @var bool */
319 public $watchthis = false;
320
321 /** @var bool */
322 public $recreate = false;
323
324 /** @var string */
325 public $textbox1 = '';
326
327 /** @var string */
328 public $textbox2 = '';
329
330 /** @var string */
331 public $summary = '';
332
333 /** @var bool */
334 public $nosummary = false;
335
336 /** @var string */
337 public $edittime = '';
338
339 /** @var integer */
340 private $editRevId = null;
341
342 /** @var string */
343 public $section = '';
344
345 /** @var string */
346 public $sectiontitle = '';
347
348 /** @var string */
349 public $starttime = '';
350
351 /** @var int */
352 public $oldid = 0;
353
354 /** @var int */
355 public $parentRevId = 0;
356
357 /** @var string */
358 public $editintro = '';
359
360 /** @var null */
361 public $scrolltop = null;
362
363 /** @var bool */
364 public $bot = true;
365
366 /** @var string */
367 public $contentModel;
368
369 /** @var null|string */
370 public $contentFormat = null;
371
372 /** @var null|array */
373 private $changeTags = null;
374
375 # Placeholders for text injection by hooks (must be HTML)
376 # extensions should take care to _append_ to the present value
377
378 /** @var string Before even the preview */
379 public $editFormPageTop = '';
380 public $editFormTextTop = '';
381 public $editFormTextBeforeContent = '';
382 public $editFormTextAfterWarn = '';
383 public $editFormTextAfterTools = '';
384 public $editFormTextBottom = '';
385 public $editFormTextAfterContent = '';
386 public $previewTextAfterContent = '';
387 public $mPreloadContent = null;
388
389 /* $didSave should be set to true whenever an article was successfully altered. */
390 public $didSave = false;
391 public $undidRev = 0;
392
393 public $suppressIntro = false;
394
395 /** @var bool */
396 protected $edit;
397
398 /** @var bool|int */
399 protected $contentLength = false;
400
401 /**
402 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
403 */
404 private $enableApiEditOverride = false;
405
406 /**
407 * @var IContextSource
408 */
409 protected $context;
410
411 /**
412 * @var bool Whether an old revision is edited
413 */
414 private $isOldRev = false;
415
416 /**
417 * @var bool Whether OOUI should be enabled here
418 */
419 private $oouiEnabled = false;
420
421 /**
422 * @param Article $article
423 */
424 public function __construct( Article $article ) {
425 $this->mArticle = $article;
426 $this->page = $article->getPage(); // model object
427 $this->mTitle = $article->getTitle();
428 $this->context = $article->getContext();
429
430 $this->contentModel = $this->mTitle->getContentModel();
431
432 $handler = ContentHandler::getForModelID( $this->contentModel );
433 $this->contentFormat = $handler->getDefaultFormat();
434
435 $this->oouiEnabled = $this->context->getConfig()->get( 'OOUIEditPage' );
436 }
437
438 /**
439 * @return Article
440 */
441 public function getArticle() {
442 return $this->mArticle;
443 }
444
445 /**
446 * @since 1.28
447 * @return IContextSource
448 */
449 public function getContext() {
450 return $this->context;
451 }
452
453 /**
454 * @since 1.19
455 * @return Title
456 */
457 public function getTitle() {
458 return $this->mTitle;
459 }
460
461 /**
462 * Set the context Title object
463 *
464 * @param Title|null $title Title object or null
465 */
466 public function setContextTitle( $title ) {
467 $this->mContextTitle = $title;
468 }
469
470 /**
471 * Get the context title object.
472 * If not set, $wgTitle will be returned. This behavior might change in
473 * the future to return $this->mTitle instead.
474 *
475 * @return Title
476 */
477 public function getContextTitle() {
478 if ( is_null( $this->mContextTitle ) ) {
479 global $wgTitle;
480 return $wgTitle;
481 } else {
482 return $this->mContextTitle;
483 }
484 }
485
486 /**
487 * Check if the edit page is using OOUI controls
488 * @return bool
489 */
490 public function isOouiEnabled() {
491 return $this->oouiEnabled;
492 }
493
494 /**
495 * Returns if the given content model is editable.
496 *
497 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
498 * @return bool
499 * @throws MWException If $modelId has no known handler
500 */
501 public function isSupportedContentModel( $modelId ) {
502 return $this->enableApiEditOverride === true ||
503 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
504 }
505
506 /**
507 * Allow editing of content that supports API direct editing, but not general
508 * direct editing. Set to false by default.
509 *
510 * @param bool $enableOverride
511 */
512 public function setApiEditOverride( $enableOverride ) {
513 $this->enableApiEditOverride = $enableOverride;
514 }
515
516 /**
517 * @deprecated since 1.29, call edit directly
518 */
519 public function submit() {
520 $this->edit();
521 }
522
523 /**
524 * This is the function that gets called for "action=edit". It
525 * sets up various member variables, then passes execution to
526 * another function, usually showEditForm()
527 *
528 * The edit form is self-submitting, so that when things like
529 * preview and edit conflicts occur, we get the same form back
530 * with the extra stuff added. Only when the final submission
531 * is made and all is well do we actually save and redirect to
532 * the newly-edited page.
533 */
534 public function edit() {
535 global $wgOut, $wgRequest, $wgUser;
536 // Allow extensions to modify/prevent this form or submission
537 if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
538 return;
539 }
540
541 wfDebug( __METHOD__ . ": enter\n" );
542
543 // If they used redlink=1 and the page exists, redirect to the main article
544 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
545 $wgOut->redirect( $this->mTitle->getFullURL() );
546 return;
547 }
548
549 $this->importFormData( $wgRequest );
550 $this->firsttime = false;
551
552 if ( wfReadOnly() && $this->save ) {
553 // Force preview
554 $this->save = false;
555 $this->preview = true;
556 }
557
558 if ( $this->save ) {
559 $this->formtype = 'save';
560 } elseif ( $this->preview ) {
561 $this->formtype = 'preview';
562 } elseif ( $this->diff ) {
563 $this->formtype = 'diff';
564 } else { # First time through
565 $this->firsttime = true;
566 if ( $this->previewOnOpen() ) {
567 $this->formtype = 'preview';
568 } else {
569 $this->formtype = 'initial';
570 }
571 }
572
573 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
574 if ( $permErrors ) {
575 wfDebug( __METHOD__ . ": User can't edit\n" );
576 // Auto-block user's IP if the account was "hard" blocked
577 if ( !wfReadOnly() ) {
578 $user = $wgUser;
579 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
580 $user->spreadAnyEditBlock();
581 } );
582 }
583 $this->displayPermissionsError( $permErrors );
584
585 return;
586 }
587
588 $revision = $this->mArticle->getRevisionFetched();
589 // Disallow editing revisions with content models different from the current one
590 // Undo edits being an exception in order to allow reverting content model changes.
591 if ( $revision
592 && $revision->getContentModel() !== $this->contentModel
593 ) {
594 $prevRev = null;
595 if ( $this->undidRev ) {
596 $undidRevObj = Revision::newFromId( $this->undidRev );
597 $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
598 }
599 if ( !$this->undidRev
600 || !$prevRev
601 || $prevRev->getContentModel() !== $this->contentModel
602 ) {
603 $this->displayViewSourcePage(
604 $this->getContentObject(),
605 $this->context->msg(
606 'contentmodelediterror',
607 $revision->getContentModel(),
608 $this->contentModel
609 )->plain()
610 );
611 return;
612 }
613 }
614
615 $this->isConflict = false;
616 // css / js subpages of user pages get a special treatment
617 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
618 $this->isCssSubpage = $this->mTitle->isCssSubpage();
619 $this->isJsSubpage = $this->mTitle->isJsSubpage();
620 // @todo FIXME: Silly assignment.
621 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
622
623 # Show applicable editing introductions
624 if ( $this->formtype == 'initial' || $this->firsttime ) {
625 $this->showIntro();
626 }
627
628 # Attempt submission here. This will check for edit conflicts,
629 # and redundantly check for locked database, blocked IPs, etc.
630 # that edit() already checked just in case someone tries to sneak
631 # in the back door with a hand-edited submission URL.
632
633 if ( 'save' == $this->formtype ) {
634 $resultDetails = null;
635 $status = $this->attemptSave( $resultDetails );
636 if ( !$this->handleStatus( $status, $resultDetails ) ) {
637 return;
638 }
639 }
640
641 # First time through: get contents, set time for conflict
642 # checking, etc.
643 if ( 'initial' == $this->formtype || $this->firsttime ) {
644 if ( $this->initialiseForm() === false ) {
645 $this->noSuchSectionPage();
646 return;
647 }
648
649 if ( !$this->mTitle->getArticleID() ) {
650 Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
651 } else {
652 Hooks::run( 'EditFormInitialText', [ $this ] );
653 }
654
655 }
656
657 $this->showEditForm();
658 }
659
660 /**
661 * @param string $rigor Same format as Title::getUserPermissionErrors()
662 * @return array
663 */
664 protected function getEditPermissionErrors( $rigor = 'secure' ) {
665 global $wgUser;
666
667 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
668 # Can this title be created?
669 if ( !$this->mTitle->exists() ) {
670 $permErrors = array_merge(
671 $permErrors,
672 wfArrayDiff2(
673 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
674 $permErrors
675 )
676 );
677 }
678 # Ignore some permissions errors when a user is just previewing/viewing diffs
679 $remove = [];
680 foreach ( $permErrors as $error ) {
681 if ( ( $this->preview || $this->diff )
682 && (
683 $error[0] == 'blockedtext' ||
684 $error[0] == 'autoblockedtext' ||
685 $error[0] == 'systemblockedtext'
686 )
687 ) {
688 $remove[] = $error;
689 }
690 }
691 $permErrors = wfArrayDiff2( $permErrors, $remove );
692
693 return $permErrors;
694 }
695
696 /**
697 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
698 * but with the following differences:
699 * - If redlink=1, the user will be redirected to the page
700 * - If there is content to display or the error occurs while either saving,
701 * previewing or showing the difference, it will be a
702 * "View source for ..." page displaying the source code after the error message.
703 *
704 * @since 1.19
705 * @param array $permErrors Array of permissions errors, as returned by
706 * Title::getUserPermissionsErrors().
707 * @throws PermissionsError
708 */
709 protected function displayPermissionsError( array $permErrors ) {
710 global $wgRequest, $wgOut;
711
712 if ( $wgRequest->getBool( 'redlink' ) ) {
713 // The edit page was reached via a red link.
714 // Redirect to the article page and let them click the edit tab if
715 // they really want a permission error.
716 $wgOut->redirect( $this->mTitle->getFullURL() );
717 return;
718 }
719
720 $content = $this->getContentObject();
721
722 # Use the normal message if there's nothing to display
723 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
724 $action = $this->mTitle->exists() ? 'edit' :
725 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
726 throw new PermissionsError( $action, $permErrors );
727 }
728
729 $this->displayViewSourcePage(
730 $content,
731 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
732 );
733 }
734
735 /**
736 * Display a read-only View Source page
737 * @param Content $content content object
738 * @param string $errorMessage additional wikitext error message to display
739 */
740 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
741 global $wgOut;
742
743 Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
744
745 $wgOut->setRobotPolicy( 'noindex,nofollow' );
746 $wgOut->setPageTitle( $this->context->msg(
747 'viewsource-title',
748 $this->getContextTitle()->getPrefixedText()
749 ) );
750 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
751 $wgOut->addHTML( $this->editFormPageTop );
752 $wgOut->addHTML( $this->editFormTextTop );
753
754 if ( $errorMessage !== '' ) {
755 $wgOut->addWikiText( $errorMessage );
756 $wgOut->addHTML( "<hr />\n" );
757 }
758
759 # If the user made changes, preserve them when showing the markup
760 # (This happens when a user is blocked during edit, for instance)
761 if ( !$this->firsttime ) {
762 $text = $this->textbox1;
763 $wgOut->addWikiMsg( 'viewyourtext' );
764 } else {
765 try {
766 $text = $this->toEditText( $content );
767 } catch ( MWException $e ) {
768 # Serialize using the default format if the content model is not supported
769 # (e.g. for an old revision with a different model)
770 $text = $content->serialize();
771 }
772 $wgOut->addWikiMsg( 'viewsourcetext' );
773 }
774
775 $wgOut->addHTML( $this->editFormTextBeforeContent );
776 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
777 $wgOut->addHTML( $this->editFormTextAfterContent );
778
779 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
780
781 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
782
783 $wgOut->addHTML( $this->editFormTextBottom );
784 if ( $this->mTitle->exists() ) {
785 $wgOut->returnToMain( null, $this->mTitle );
786 }
787 }
788
789 /**
790 * Should we show a preview when the edit form is first shown?
791 *
792 * @return bool
793 */
794 protected function previewOnOpen() {
795 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
796 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
797 // Explicit override from request
798 return true;
799 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
800 // Explicit override from request
801 return false;
802 } elseif ( $this->section == 'new' ) {
803 // Nothing *to* preview for new sections
804 return false;
805 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
806 && $wgUser->getOption( 'previewonfirst' )
807 ) {
808 // Standard preference behavior
809 return true;
810 } elseif ( !$this->mTitle->exists()
811 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
812 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
813 ) {
814 // Categories are special
815 return true;
816 } else {
817 return false;
818 }
819 }
820
821 /**
822 * Checks whether the user entered a skin name in uppercase,
823 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
824 *
825 * @return bool
826 */
827 protected function isWrongCaseCssJsPage() {
828 if ( $this->mTitle->isCssJsSubpage() ) {
829 $name = $this->mTitle->getSkinFromCssJsSubpage();
830 $skins = array_merge(
831 array_keys( Skin::getSkinNames() ),
832 [ 'common' ]
833 );
834 return !in_array( $name, $skins )
835 && in_array( strtolower( $name ), $skins );
836 } else {
837 return false;
838 }
839 }
840
841 /**
842 * Returns whether section editing is supported for the current page.
843 * Subclasses may override this to replace the default behavior, which is
844 * to check ContentHandler::supportsSections.
845 *
846 * @return bool True if this edit page supports sections, false otherwise.
847 */
848 protected function isSectionEditSupported() {
849 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
850 return $contentHandler->supportsSections();
851 }
852
853 /**
854 * This function collects the form data and uses it to populate various member variables.
855 * @param WebRequest $request
856 * @throws ErrorPageError
857 */
858 public function importFormData( &$request ) {
859 global $wgContLang, $wgUser;
860
861 # Allow users to change the mode for testing
862 $this->oouiEnabled = $request->getFuzzyBool( 'ooui', $this->oouiEnabled );
863
864 # Section edit can come from either the form or a link
865 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
866
867 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
868 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
869 }
870
871 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
872
873 if ( $request->wasPosted() ) {
874 # These fields need to be checked for encoding.
875 # Also remove trailing whitespace, but don't remove _initial_
876 # whitespace from the text boxes. This may be significant formatting.
877 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
878 if ( !$request->getCheck( 'wpTextbox2' ) ) {
879 // Skip this if wpTextbox2 has input, it indicates that we came
880 // from a conflict page with raw page text, not a custom form
881 // modified by subclasses
882 $textbox1 = $this->importContentFormData( $request );
883 if ( $textbox1 !== null ) {
884 $this->textbox1 = $textbox1;
885 }
886 }
887
888 # Truncate for whole multibyte characters
889 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
890
891 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
892 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
893 # section titles.
894 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
895
896 # Treat sectiontitle the same way as summary.
897 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
898 # currently doing double duty as both edit summary and section title. Right now this
899 # is just to allow API edits to work around this limitation, but this should be
900 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
901 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
902 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
903
904 $this->edittime = $request->getVal( 'wpEdittime' );
905 $this->editRevId = $request->getIntOrNull( 'editRevId' );
906 $this->starttime = $request->getVal( 'wpStarttime' );
907
908 $undidRev = $request->getInt( 'wpUndidRevision' );
909 if ( $undidRev ) {
910 $this->undidRev = $undidRev;
911 }
912
913 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
914
915 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
916 // wpTextbox1 field is missing, possibly due to being "too big"
917 // according to some filter rules such as Suhosin's setting for
918 // suhosin.request.max_value_length (d'oh)
919 $this->incompleteForm = true;
920 } else {
921 // If we receive the last parameter of the request, we can fairly
922 // claim the POST request has not been truncated.
923
924 // TODO: softened the check for cutover. Once we determine
925 // that it is safe, we should complete the transition by
926 // removing the "edittime" clause.
927 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
928 && is_null( $this->edittime ) );
929 }
930 if ( $this->incompleteForm ) {
931 # If the form is incomplete, force to preview.
932 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
933 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
934 $this->preview = true;
935 } else {
936 $this->preview = $request->getCheck( 'wpPreview' );
937 $this->diff = $request->getCheck( 'wpDiff' );
938
939 // Remember whether a save was requested, so we can indicate
940 // if we forced preview due to session failure.
941 $this->mTriedSave = !$this->preview;
942
943 if ( $this->tokenOk( $request ) ) {
944 # Some browsers will not report any submit button
945 # if the user hits enter in the comment box.
946 # The unmarked state will be assumed to be a save,
947 # if the form seems otherwise complete.
948 wfDebug( __METHOD__ . ": Passed token check.\n" );
949 } elseif ( $this->diff ) {
950 # Failed token check, but only requested "Show Changes".
951 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
952 } else {
953 # Page might be a hack attempt posted from
954 # an external site. Preview instead of saving.
955 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
956 $this->preview = true;
957 }
958 }
959 $this->save = !$this->preview && !$this->diff;
960 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
961 $this->edittime = null;
962 }
963
964 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
965 $this->starttime = null;
966 }
967
968 $this->recreate = $request->getCheck( 'wpRecreate' );
969
970 $this->minoredit = $request->getCheck( 'wpMinoredit' );
971 $this->watchthis = $request->getCheck( 'wpWatchthis' );
972
973 # Don't force edit summaries when a user is editing their own user or talk page
974 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
975 && $this->mTitle->getText() == $wgUser->getName()
976 ) {
977 $this->allowBlankSummary = true;
978 } else {
979 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
980 || !$wgUser->getOption( 'forceeditsummary' );
981 }
982
983 $this->autoSumm = $request->getText( 'wpAutoSummary' );
984
985 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
986 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
987
988 $changeTags = $request->getVal( 'wpChangeTags' );
989 if ( is_null( $changeTags ) || $changeTags === '' ) {
990 $this->changeTags = [];
991 } else {
992 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
993 $changeTags ) ) );
994 }
995 } else {
996 # Not a posted form? Start with nothing.
997 wfDebug( __METHOD__ . ": Not a posted form.\n" );
998 $this->textbox1 = '';
999 $this->summary = '';
1000 $this->sectiontitle = '';
1001 $this->edittime = '';
1002 $this->editRevId = null;
1003 $this->starttime = wfTimestampNow();
1004 $this->edit = false;
1005 $this->preview = false;
1006 $this->save = false;
1007 $this->diff = false;
1008 $this->minoredit = false;
1009 // Watch may be overridden by request parameters
1010 $this->watchthis = $request->getBool( 'watchthis', false );
1011 $this->recreate = false;
1012
1013 // When creating a new section, we can preload a section title by passing it as the
1014 // preloadtitle parameter in the URL (T15100)
1015 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
1016 $this->sectiontitle = $request->getVal( 'preloadtitle' );
1017 // Once wpSummary isn't being use for setting section titles, we should delete this.
1018 $this->summary = $request->getVal( 'preloadtitle' );
1019 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
1020 $this->summary = $request->getText( 'summary' );
1021 if ( $this->summary !== '' ) {
1022 $this->hasPresetSummary = true;
1023 }
1024 }
1025
1026 if ( $request->getVal( 'minor' ) ) {
1027 $this->minoredit = true;
1028 }
1029 }
1030
1031 $this->oldid = $request->getInt( 'oldid' );
1032 $this->parentRevId = $request->getInt( 'parentRevId' );
1033
1034 $this->bot = $request->getBool( 'bot', true );
1035 $this->nosummary = $request->getBool( 'nosummary' );
1036
1037 // May be overridden by revision.
1038 $this->contentModel = $request->getText( 'model', $this->contentModel );
1039 // May be overridden by revision.
1040 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1041
1042 try {
1043 $handler = ContentHandler::getForModelID( $this->contentModel );
1044 } catch ( MWUnknownContentModelException $e ) {
1045 throw new ErrorPageError(
1046 'editpage-invalidcontentmodel-title',
1047 'editpage-invalidcontentmodel-text',
1048 [ wfEscapeWikiText( $this->contentModel ) ]
1049 );
1050 }
1051
1052 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1053 throw new ErrorPageError(
1054 'editpage-notsupportedcontentformat-title',
1055 'editpage-notsupportedcontentformat-text',
1056 [
1057 wfEscapeWikiText( $this->contentFormat ),
1058 wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1059 ]
1060 );
1061 }
1062
1063 /**
1064 * @todo Check if the desired model is allowed in this namespace, and if
1065 * a transition from the page's current model to the new model is
1066 * allowed.
1067 */
1068
1069 $this->editintro = $request->getText( 'editintro',
1070 // Custom edit intro for new sections
1071 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1072
1073 // Allow extensions to modify form data
1074 Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1075 }
1076
1077 /**
1078 * Subpage overridable method for extracting the page content data from the
1079 * posted form to be placed in $this->textbox1, if using customized input
1080 * this method should be overridden and return the page text that will be used
1081 * for saving, preview parsing and so on...
1082 *
1083 * @param WebRequest $request
1084 * @return string|null
1085 */
1086 protected function importContentFormData( &$request ) {
1087 return; // Don't do anything, EditPage already extracted wpTextbox1
1088 }
1089
1090 /**
1091 * Initialise form fields in the object
1092 * Called on the first invocation, e.g. when a user clicks an edit link
1093 * @return bool If the requested section is valid
1094 */
1095 public function initialiseForm() {
1096 global $wgUser;
1097 $this->edittime = $this->page->getTimestamp();
1098 $this->editRevId = $this->page->getLatest();
1099
1100 $content = $this->getContentObject( false ); # TODO: track content object?!
1101 if ( $content === false ) {
1102 return false;
1103 }
1104 $this->textbox1 = $this->toEditText( $content );
1105
1106 // activate checkboxes if user wants them to be always active
1107 # Sort out the "watch" checkbox
1108 if ( $wgUser->getOption( 'watchdefault' ) ) {
1109 # Watch all edits
1110 $this->watchthis = true;
1111 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1112 # Watch creations
1113 $this->watchthis = true;
1114 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1115 # Already watched
1116 $this->watchthis = true;
1117 }
1118 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1119 $this->minoredit = true;
1120 }
1121 if ( $this->textbox1 === false ) {
1122 return false;
1123 }
1124 return true;
1125 }
1126
1127 /**
1128 * @param Content|null $def_content The default value to return
1129 *
1130 * @return Content|null Content on success, $def_content for invalid sections
1131 *
1132 * @since 1.21
1133 */
1134 protected function getContentObject( $def_content = null ) {
1135 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1136
1137 $content = false;
1138
1139 // For message page not locally set, use the i18n message.
1140 // For other non-existent articles, use preload text if any.
1141 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1142 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1143 # If this is a system message, get the default text.
1144 $msg = $this->mTitle->getDefaultMessageText();
1145
1146 $content = $this->toEditContent( $msg );
1147 }
1148 if ( $content === false ) {
1149 # If requested, preload some text.
1150 $preload = $wgRequest->getVal( 'preload',
1151 // Custom preload text for new sections
1152 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1153 $params = $wgRequest->getArray( 'preloadparams', [] );
1154
1155 $content = $this->getPreloadedContent( $preload, $params );
1156 }
1157 // For existing pages, get text based on "undo" or section parameters.
1158 } else {
1159 if ( $this->section != '' ) {
1160 // Get section edit text (returns $def_text for invalid sections)
1161 $orig = $this->getOriginalContent( $wgUser );
1162 $content = $orig ? $orig->getSection( $this->section ) : null;
1163
1164 if ( !$content ) {
1165 $content = $def_content;
1166 }
1167 } else {
1168 $undoafter = $wgRequest->getInt( 'undoafter' );
1169 $undo = $wgRequest->getInt( 'undo' );
1170
1171 if ( $undo > 0 && $undoafter > 0 ) {
1172 $undorev = Revision::newFromId( $undo );
1173 $oldrev = Revision::newFromId( $undoafter );
1174
1175 # Sanity check, make sure it's the right page,
1176 # the revisions exist and they were not deleted.
1177 # Otherwise, $content will be left as-is.
1178 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1179 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1180 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1181 ) {
1182 $content = $this->page->getUndoContent( $undorev, $oldrev );
1183
1184 if ( $content === false ) {
1185 # Warn the user that something went wrong
1186 $undoMsg = 'failure';
1187 } else {
1188 $oldContent = $this->page->getContent( Revision::RAW );
1189 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1190 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1191 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1192 // The undo may change content
1193 // model if its reverting the top
1194 // edit. This can result in
1195 // mismatched content model/format.
1196 $this->contentModel = $newContent->getModel();
1197 $this->contentFormat = $oldrev->getContentFormat();
1198 }
1199
1200 if ( $newContent->equals( $oldContent ) ) {
1201 # Tell the user that the undo results in no change,
1202 # i.e. the revisions were already undone.
1203 $undoMsg = 'nochange';
1204 $content = false;
1205 } else {
1206 # Inform the user of our success and set an automatic edit summary
1207 $undoMsg = 'success';
1208
1209 # If we just undid one rev, use an autosummary
1210 $firstrev = $oldrev->getNext();
1211 if ( $firstrev && $firstrev->getId() == $undo ) {
1212 $userText = $undorev->getUserText();
1213 if ( $userText === '' ) {
1214 $undoSummary = $this->context->msg(
1215 'undo-summary-username-hidden',
1216 $undo
1217 )->inContentLanguage()->text();
1218 } else {
1219 $undoSummary = $this->context->msg(
1220 'undo-summary',
1221 $undo,
1222 $userText
1223 )->inContentLanguage()->text();
1224 }
1225 if ( $this->summary === '' ) {
1226 $this->summary = $undoSummary;
1227 } else {
1228 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1229 ->inContentLanguage()->text() . $this->summary;
1230 }
1231 $this->undidRev = $undo;
1232 }
1233 $this->formtype = 'diff';
1234 }
1235 }
1236 } else {
1237 // Failed basic sanity checks.
1238 // Older revisions may have been removed since the link
1239 // was created, or we may simply have got bogus input.
1240 $undoMsg = 'norev';
1241 }
1242
1243 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1244 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1245 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1246 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1247 }
1248
1249 if ( $content === false ) {
1250 $content = $this->getOriginalContent( $wgUser );
1251 }
1252 }
1253 }
1254
1255 return $content;
1256 }
1257
1258 /**
1259 * Get the content of the wanted revision, without section extraction.
1260 *
1261 * The result of this function can be used to compare user's input with
1262 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1263 * to the original text of the edit.
1264 *
1265 * This differs from Article::getContent() that when a missing revision is
1266 * encountered the result will be null and not the
1267 * 'missing-revision' message.
1268 *
1269 * @since 1.19
1270 * @param User $user The user to get the revision for
1271 * @return Content|null
1272 */
1273 private function getOriginalContent( User $user ) {
1274 if ( $this->section == 'new' ) {
1275 return $this->getCurrentContent();
1276 }
1277 $revision = $this->mArticle->getRevisionFetched();
1278 if ( $revision === null ) {
1279 $handler = ContentHandler::getForModelID( $this->contentModel );
1280 return $handler->makeEmptyContent();
1281 }
1282 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1283 return $content;
1284 }
1285
1286 /**
1287 * Get the edit's parent revision ID
1288 *
1289 * The "parent" revision is the ancestor that should be recorded in this
1290 * page's revision history. It is either the revision ID of the in-memory
1291 * article content, or in the case of a 3-way merge in order to rebase
1292 * across a recoverable edit conflict, the ID of the newer revision to
1293 * which we have rebased this page.
1294 *
1295 * @since 1.27
1296 * @return int Revision ID
1297 */
1298 public function getParentRevId() {
1299 if ( $this->parentRevId ) {
1300 return $this->parentRevId;
1301 } else {
1302 return $this->mArticle->getRevIdFetched();
1303 }
1304 }
1305
1306 /**
1307 * Get the current content of the page. This is basically similar to
1308 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1309 * content object is returned instead of null.
1310 *
1311 * @since 1.21
1312 * @return Content
1313 */
1314 protected function getCurrentContent() {
1315 $rev = $this->page->getRevision();
1316 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1317
1318 if ( $content === false || $content === null ) {
1319 $handler = ContentHandler::getForModelID( $this->contentModel );
1320 return $handler->makeEmptyContent();
1321 } elseif ( !$this->undidRev ) {
1322 // Content models should always be the same since we error
1323 // out if they are different before this point (in ->edit()).
1324 // The exception being, during an undo, the current revision might
1325 // differ from the prior revision.
1326 $logger = LoggerFactory::getInstance( 'editpage' );
1327 if ( $this->contentModel !== $rev->getContentModel() ) {
1328 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1329 'prev' => $this->contentModel,
1330 'new' => $rev->getContentModel(),
1331 'title' => $this->getTitle()->getPrefixedDBkey(),
1332 'method' => __METHOD__
1333 ] );
1334 $this->contentModel = $rev->getContentModel();
1335 }
1336
1337 // Given that the content models should match, the current selected
1338 // format should be supported.
1339 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1340 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1341
1342 'prev' => $this->contentFormat,
1343 'new' => $rev->getContentFormat(),
1344 'title' => $this->getTitle()->getPrefixedDBkey(),
1345 'method' => __METHOD__
1346 ] );
1347 $this->contentFormat = $rev->getContentFormat();
1348 }
1349 }
1350 return $content;
1351 }
1352
1353 /**
1354 * Use this method before edit() to preload some content into the edit box
1355 *
1356 * @param Content $content
1357 *
1358 * @since 1.21
1359 */
1360 public function setPreloadedContent( Content $content ) {
1361 $this->mPreloadContent = $content;
1362 }
1363
1364 /**
1365 * Get the contents to be preloaded into the box, either set by
1366 * an earlier setPreloadText() or by loading the given page.
1367 *
1368 * @param string $preload Representing the title to preload from.
1369 * @param array $params Parameters to use (interface-message style) in the preloaded text
1370 *
1371 * @return Content
1372 *
1373 * @since 1.21
1374 */
1375 protected function getPreloadedContent( $preload, $params = [] ) {
1376 global $wgUser;
1377
1378 if ( !empty( $this->mPreloadContent ) ) {
1379 return $this->mPreloadContent;
1380 }
1381
1382 $handler = ContentHandler::getForModelID( $this->contentModel );
1383
1384 if ( $preload === '' ) {
1385 return $handler->makeEmptyContent();
1386 }
1387
1388 $title = Title::newFromText( $preload );
1389 # Check for existence to avoid getting MediaWiki:Noarticletext
1390 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1391 // TODO: somehow show a warning to the user!
1392 return $handler->makeEmptyContent();
1393 }
1394
1395 $page = WikiPage::factory( $title );
1396 if ( $page->isRedirect() ) {
1397 $title = $page->getRedirectTarget();
1398 # Same as before
1399 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1400 // TODO: somehow show a warning to the user!
1401 return $handler->makeEmptyContent();
1402 }
1403 $page = WikiPage::factory( $title );
1404 }
1405
1406 $parserOptions = ParserOptions::newFromUser( $wgUser );
1407 $content = $page->getContent( Revision::RAW );
1408
1409 if ( !$content ) {
1410 // TODO: somehow show a warning to the user!
1411 return $handler->makeEmptyContent();
1412 }
1413
1414 if ( $content->getModel() !== $handler->getModelID() ) {
1415 $converted = $content->convert( $handler->getModelID() );
1416
1417 if ( !$converted ) {
1418 // TODO: somehow show a warning to the user!
1419 wfDebug( "Attempt to preload incompatible content: " .
1420 "can't convert " . $content->getModel() .
1421 " to " . $handler->getModelID() );
1422
1423 return $handler->makeEmptyContent();
1424 }
1425
1426 $content = $converted;
1427 }
1428
1429 return $content->preloadTransform( $title, $parserOptions, $params );
1430 }
1431
1432 /**
1433 * Make sure the form isn't faking a user's credentials.
1434 *
1435 * @param WebRequest $request
1436 * @return bool
1437 * @private
1438 */
1439 public function tokenOk( &$request ) {
1440 global $wgUser;
1441 $token = $request->getVal( 'wpEditToken' );
1442 $this->mTokenOk = $wgUser->matchEditToken( $token );
1443 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1444 return $this->mTokenOk;
1445 }
1446
1447 /**
1448 * Sets post-edit cookie indicating the user just saved a particular revision.
1449 *
1450 * This uses a temporary cookie for each revision ID so separate saves will never
1451 * interfere with each other.
1452 *
1453 * Article::view deletes the cookie on server-side after the redirect and
1454 * converts the value to the global JavaScript variable wgPostEdit.
1455 *
1456 * If the variable were set on the server, it would be cached, which is unwanted
1457 * since the post-edit state should only apply to the load right after the save.
1458 *
1459 * @param int $statusValue The status value (to check for new article status)
1460 */
1461 protected function setPostEditCookie( $statusValue ) {
1462 $revisionId = $this->page->getLatest();
1463 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1464
1465 $val = 'saved';
1466 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1467 $val = 'created';
1468 } elseif ( $this->oldid ) {
1469 $val = 'restored';
1470 }
1471
1472 $response = RequestContext::getMain()->getRequest()->response();
1473 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1474 }
1475
1476 /**
1477 * Attempt submission
1478 * @param array|bool $resultDetails See docs for $result in internalAttemptSave
1479 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1480 * @return Status The resulting status object.
1481 */
1482 public function attemptSave( &$resultDetails = false ) {
1483 global $wgUser;
1484
1485 # Allow bots to exempt some edits from bot flagging
1486 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1487 $status = $this->internalAttemptSave( $resultDetails, $bot );
1488
1489 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1490
1491 return $status;
1492 }
1493
1494 /**
1495 * Log when a page was successfully saved after the edit conflict view
1496 */
1497 private function incrementResolvedConflicts() {
1498 global $wgRequest;
1499
1500 if ( $wgRequest->getText( 'mode' ) !== 'conflict' ) {
1501 return;
1502 }
1503
1504 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1505 $stats->increment( 'edit.failures.conflict.resolved' );
1506 }
1507
1508 /**
1509 * Handle status, such as after attempt save
1510 *
1511 * @param Status $status
1512 * @param array|bool $resultDetails
1513 *
1514 * @throws ErrorPageError
1515 * @return bool False, if output is done, true if rest of the form should be displayed
1516 */
1517 private function handleStatus( Status $status, $resultDetails ) {
1518 global $wgUser, $wgOut;
1519
1520 /**
1521 * @todo FIXME: once the interface for internalAttemptSave() is made
1522 * nicer, this should use the message in $status
1523 */
1524 if ( $status->value == self::AS_SUCCESS_UPDATE
1525 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1526 ) {
1527 $this->incrementResolvedConflicts();
1528
1529 $this->didSave = true;
1530 if ( !$resultDetails['nullEdit'] ) {
1531 $this->setPostEditCookie( $status->value );
1532 }
1533 }
1534
1535 // "wpExtraQueryRedirect" is a hidden input to modify
1536 // after save URL and is not used by actual edit form
1537 $request = RequestContext::getMain()->getRequest();
1538 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1539
1540 switch ( $status->value ) {
1541 case self::AS_HOOK_ERROR_EXPECTED:
1542 case self::AS_CONTENT_TOO_BIG:
1543 case self::AS_ARTICLE_WAS_DELETED:
1544 case self::AS_CONFLICT_DETECTED:
1545 case self::AS_SUMMARY_NEEDED:
1546 case self::AS_TEXTBOX_EMPTY:
1547 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1548 case self::AS_END:
1549 case self::AS_BLANK_ARTICLE:
1550 case self::AS_SELF_REDIRECT:
1551 return true;
1552
1553 case self::AS_HOOK_ERROR:
1554 return false;
1555
1556 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1557 case self::AS_PARSE_ERROR:
1558 $wgOut->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1559 return true;
1560
1561 case self::AS_SUCCESS_NEW_ARTICLE:
1562 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1563 if ( $extraQueryRedirect ) {
1564 if ( $query === '' ) {
1565 $query = $extraQueryRedirect;
1566 } else {
1567 $query = $query . '&' . $extraQueryRedirect;
1568 }
1569 }
1570 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1571 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1572 return false;
1573
1574 case self::AS_SUCCESS_UPDATE:
1575 $extraQuery = '';
1576 $sectionanchor = $resultDetails['sectionanchor'];
1577
1578 // Give extensions a chance to modify URL query on update
1579 Hooks::run(
1580 'ArticleUpdateBeforeRedirect',
1581 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1582 );
1583
1584 if ( $resultDetails['redirect'] ) {
1585 if ( $extraQuery == '' ) {
1586 $extraQuery = 'redirect=no';
1587 } else {
1588 $extraQuery = 'redirect=no&' . $extraQuery;
1589 }
1590 }
1591 if ( $extraQueryRedirect ) {
1592 if ( $extraQuery === '' ) {
1593 $extraQuery = $extraQueryRedirect;
1594 } else {
1595 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1596 }
1597 }
1598
1599 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1600 return false;
1601
1602 case self::AS_SPAM_ERROR:
1603 $this->spamPageWithContent( $resultDetails['spam'] );
1604 return false;
1605
1606 case self::AS_BLOCKED_PAGE_FOR_USER:
1607 throw new UserBlockedError( $wgUser->getBlock() );
1608
1609 case self::AS_IMAGE_REDIRECT_ANON:
1610 case self::AS_IMAGE_REDIRECT_LOGGED:
1611 throw new PermissionsError( 'upload' );
1612
1613 case self::AS_READ_ONLY_PAGE_ANON:
1614 case self::AS_READ_ONLY_PAGE_LOGGED:
1615 throw new PermissionsError( 'edit' );
1616
1617 case self::AS_READ_ONLY_PAGE:
1618 throw new ReadOnlyError;
1619
1620 case self::AS_RATE_LIMITED:
1621 throw new ThrottledError();
1622
1623 case self::AS_NO_CREATE_PERMISSION:
1624 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1625 throw new PermissionsError( $permission );
1626
1627 case self::AS_NO_CHANGE_CONTENT_MODEL:
1628 throw new PermissionsError( 'editcontentmodel' );
1629
1630 default:
1631 // We don't recognize $status->value. The only way that can happen
1632 // is if an extension hook aborted from inside ArticleSave.
1633 // Render the status object into $this->hookError
1634 // FIXME this sucks, we should just use the Status object throughout
1635 $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
1636 '</div>';
1637 return true;
1638 }
1639 }
1640
1641 /**
1642 * Run hooks that can filter edits just before they get saved.
1643 *
1644 * @param Content $content The Content to filter.
1645 * @param Status $status For reporting the outcome to the caller
1646 * @param User $user The user performing the edit
1647 *
1648 * @return bool
1649 */
1650 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1651 // Run old style post-section-merge edit filter
1652 if ( $this->hookError != '' ) {
1653 # ...or the hook could be expecting us to produce an error
1654 $status->fatal( 'hookaborted' );
1655 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1656 return false;
1657 }
1658
1659 // Run new style post-section-merge edit filter
1660 if ( !Hooks::run( 'EditFilterMergedContent',
1661 [ $this->mArticle->getContext(), $content, $status, $this->summary,
1662 $user, $this->minoredit ] )
1663 ) {
1664 # Error messages etc. could be handled within the hook...
1665 if ( $status->isGood() ) {
1666 $status->fatal( 'hookaborted' );
1667 // Not setting $this->hookError here is a hack to allow the hook
1668 // to cause a return to the edit page without $this->hookError
1669 // being set. This is used by ConfirmEdit to display a captcha
1670 // without any error message cruft.
1671 } else {
1672 $this->hookError = $status->getWikiText();
1673 }
1674 // Use the existing $status->value if the hook set it
1675 if ( !$status->value ) {
1676 $status->value = self::AS_HOOK_ERROR;
1677 }
1678 return false;
1679 } elseif ( !$status->isOK() ) {
1680 # ...or the hook could be expecting us to produce an error
1681 // FIXME this sucks, we should just use the Status object throughout
1682 $this->hookError = $status->getWikiText();
1683 $status->fatal( 'hookaborted' );
1684 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1685 return false;
1686 }
1687
1688 return true;
1689 }
1690
1691 /**
1692 * Return the summary to be used for a new section.
1693 *
1694 * @param string $sectionanchor Set to the section anchor text
1695 * @return string
1696 */
1697 private function newSectionSummary( &$sectionanchor = null ) {
1698 global $wgParser;
1699
1700 if ( $this->sectiontitle !== '' ) {
1701 $sectionanchor = $this->guessSectionName( $this->sectiontitle );
1702 // If no edit summary was specified, create one automatically from the section
1703 // title and have it link to the new section. Otherwise, respect the summary as
1704 // passed.
1705 if ( $this->summary === '' ) {
1706 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1707 return $this->context->msg( 'newsectionsummary' )
1708 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1709 }
1710 } elseif ( $this->summary !== '' ) {
1711 $sectionanchor = $this->guessSectionName( $this->summary );
1712 # This is a new section, so create a link to the new section
1713 # in the revision summary.
1714 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1715 return $this->context->msg( 'newsectionsummary' )
1716 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1717 }
1718 return $this->summary;
1719 }
1720
1721 /**
1722 * Attempt submission (no UI)
1723 *
1724 * @param array $result Array to add statuses to, currently with the
1725 * possible keys:
1726 * - spam (string): Spam string from content if any spam is detected by
1727 * matchSpamRegex.
1728 * - sectionanchor (string): Section anchor for a section save.
1729 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1730 * false otherwise.
1731 * - redirect (bool): Set if doEditContent is OK. True if resulting
1732 * revision is a redirect.
1733 * @param bool $bot True if edit is being made under the bot right.
1734 *
1735 * @return Status Status object, possibly with a message, but always with
1736 * one of the AS_* constants in $status->value,
1737 *
1738 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1739 * various error display idiosyncrasies. There are also lots of cases
1740 * where error metadata is set in the object and retrieved later instead
1741 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1742 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1743 * time.
1744 */
1745 public function internalAttemptSave( &$result, $bot = false ) {
1746 global $wgUser, $wgRequest, $wgMaxArticleSize;
1747 global $wgContentHandlerUseDB;
1748
1749 $status = Status::newGood();
1750
1751 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1752 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1753 $status->fatal( 'hookaborted' );
1754 $status->value = self::AS_HOOK_ERROR;
1755 return $status;
1756 }
1757
1758 $spam = $wgRequest->getText( 'wpAntispam' );
1759 if ( $spam !== '' ) {
1760 wfDebugLog(
1761 'SimpleAntiSpam',
1762 $wgUser->getName() .
1763 ' editing "' .
1764 $this->mTitle->getPrefixedText() .
1765 '" submitted bogus field "' .
1766 $spam .
1767 '"'
1768 );
1769 $status->fatal( 'spamprotectionmatch', false );
1770 $status->value = self::AS_SPAM_ERROR;
1771 return $status;
1772 }
1773
1774 try {
1775 # Construct Content object
1776 $textbox_content = $this->toEditContent( $this->textbox1 );
1777 } catch ( MWContentSerializationException $ex ) {
1778 $status->fatal(
1779 'content-failed-to-parse',
1780 $this->contentModel,
1781 $this->contentFormat,
1782 $ex->getMessage()
1783 );
1784 $status->value = self::AS_PARSE_ERROR;
1785 return $status;
1786 }
1787
1788 # Check image redirect
1789 if ( $this->mTitle->getNamespace() == NS_FILE &&
1790 $textbox_content->isRedirect() &&
1791 !$wgUser->isAllowed( 'upload' )
1792 ) {
1793 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1794 $status->setResult( false, $code );
1795
1796 return $status;
1797 }
1798
1799 # Check for spam
1800 $match = self::matchSummarySpamRegex( $this->summary );
1801 if ( $match === false && $this->section == 'new' ) {
1802 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1803 # regular summaries, it is added to the actual wikitext.
1804 if ( $this->sectiontitle !== '' ) {
1805 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1806 $match = self::matchSpamRegex( $this->sectiontitle );
1807 } else {
1808 # This branch is taken when the "Add Topic" user interface is used, or the API
1809 # is used with the 'summary' parameter.
1810 $match = self::matchSpamRegex( $this->summary );
1811 }
1812 }
1813 if ( $match === false ) {
1814 $match = self::matchSpamRegex( $this->textbox1 );
1815 }
1816 if ( $match !== false ) {
1817 $result['spam'] = $match;
1818 $ip = $wgRequest->getIP();
1819 $pdbk = $this->mTitle->getPrefixedDBkey();
1820 $match = str_replace( "\n", '', $match );
1821 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1822 $status->fatal( 'spamprotectionmatch', $match );
1823 $status->value = self::AS_SPAM_ERROR;
1824 return $status;
1825 }
1826 if ( !Hooks::run(
1827 'EditFilter',
1828 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1829 ) {
1830 # Error messages etc. could be handled within the hook...
1831 $status->fatal( 'hookaborted' );
1832 $status->value = self::AS_HOOK_ERROR;
1833 return $status;
1834 } elseif ( $this->hookError != '' ) {
1835 # ...or the hook could be expecting us to produce an error
1836 $status->fatal( 'hookaborted' );
1837 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1838 return $status;
1839 }
1840
1841 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1842 // Auto-block user's IP if the account was "hard" blocked
1843 if ( !wfReadOnly() ) {
1844 $wgUser->spreadAnyEditBlock();
1845 }
1846 # Check block state against master, thus 'false'.
1847 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1848 return $status;
1849 }
1850
1851 $this->contentLength = strlen( $this->textbox1 );
1852 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
1853 // Error will be displayed by showEditForm()
1854 $this->tooBig = true;
1855 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1856 return $status;
1857 }
1858
1859 if ( !$wgUser->isAllowed( 'edit' ) ) {
1860 if ( $wgUser->isAnon() ) {
1861 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1862 return $status;
1863 } else {
1864 $status->fatal( 'readonlytext' );
1865 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1866 return $status;
1867 }
1868 }
1869
1870 $changingContentModel = false;
1871 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1872 if ( !$wgContentHandlerUseDB ) {
1873 $status->fatal( 'editpage-cannot-use-custom-model' );
1874 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1875 return $status;
1876 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1877 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1878 return $status;
1879 }
1880 // Make sure the user can edit the page under the new content model too
1881 $titleWithNewContentModel = clone $this->mTitle;
1882 $titleWithNewContentModel->setContentModel( $this->contentModel );
1883 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1884 || !$titleWithNewContentModel->userCan( 'edit', $wgUser )
1885 ) {
1886 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1887 return $status;
1888 }
1889
1890 $changingContentModel = true;
1891 $oldContentModel = $this->mTitle->getContentModel();
1892 }
1893
1894 if ( $this->changeTags ) {
1895 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1896 $this->changeTags, $wgUser );
1897 if ( !$changeTagsStatus->isOK() ) {
1898 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1899 return $changeTagsStatus;
1900 }
1901 }
1902
1903 if ( wfReadOnly() ) {
1904 $status->fatal( 'readonlytext' );
1905 $status->value = self::AS_READ_ONLY_PAGE;
1906 return $status;
1907 }
1908 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 )
1909 || ( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1910 ) {
1911 $status->fatal( 'actionthrottledtext' );
1912 $status->value = self::AS_RATE_LIMITED;
1913 return $status;
1914 }
1915
1916 # If the article has been deleted while editing, don't save it without
1917 # confirmation
1918 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1919 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1920 return $status;
1921 }
1922
1923 # Load the page data from the master. If anything changes in the meantime,
1924 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1925 $this->page->loadPageData( 'fromdbmaster' );
1926 $new = !$this->page->exists();
1927
1928 if ( $new ) {
1929 // Late check for create permission, just in case *PARANOIA*
1930 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1931 $status->fatal( 'nocreatetext' );
1932 $status->value = self::AS_NO_CREATE_PERMISSION;
1933 wfDebug( __METHOD__ . ": no create permission\n" );
1934 return $status;
1935 }
1936
1937 // Don't save a new page if it's blank or if it's a MediaWiki:
1938 // message with content equivalent to default (allow empty pages
1939 // in this case to disable messages, see T52124)
1940 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1941 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1942 $defaultText = $defaultMessageText;
1943 } else {
1944 $defaultText = '';
1945 }
1946
1947 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1948 $this->blankArticle = true;
1949 $status->fatal( 'blankarticle' );
1950 $status->setResult( false, self::AS_BLANK_ARTICLE );
1951 return $status;
1952 }
1953
1954 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1955 return $status;
1956 }
1957
1958 $content = $textbox_content;
1959
1960 $result['sectionanchor'] = '';
1961 if ( $this->section == 'new' ) {
1962 if ( $this->sectiontitle !== '' ) {
1963 // Insert the section title above the content.
1964 $content = $content->addSectionHeader( $this->sectiontitle );
1965 } elseif ( $this->summary !== '' ) {
1966 // Insert the section title above the content.
1967 $content = $content->addSectionHeader( $this->summary );
1968 }
1969 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1970 }
1971
1972 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1973
1974 } else { # not $new
1975
1976 # Article exists. Check for edit conflict.
1977
1978 $this->page->clear(); # Force reload of dates, etc.
1979 $timestamp = $this->page->getTimestamp();
1980 $latest = $this->page->getLatest();
1981
1982 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1983
1984 // Check editRevId if set, which handles same-second timestamp collisions
1985 if ( $timestamp != $this->edittime
1986 || ( $this->editRevId !== null && $this->editRevId != $latest )
1987 ) {
1988 $this->isConflict = true;
1989 if ( $this->section == 'new' ) {
1990 if ( $this->page->getUserText() == $wgUser->getName() &&
1991 $this->page->getComment() == $this->newSectionSummary()
1992 ) {
1993 // Probably a duplicate submission of a new comment.
1994 // This can happen when CDN resends a request after
1995 // a timeout but the first one actually went through.
1996 wfDebug( __METHOD__
1997 . ": duplicate new section submission; trigger edit conflict!\n" );
1998 } else {
1999 // New comment; suppress conflict.
2000 $this->isConflict = false;
2001 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
2002 }
2003 } elseif ( $this->section == ''
2004 && Revision::userWasLastToEdit(
2005 DB_MASTER, $this->mTitle->getArticleID(),
2006 $wgUser->getId(), $this->edittime
2007 )
2008 ) {
2009 # Suppress edit conflict with self, except for section edits where merging is required.
2010 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2011 $this->isConflict = false;
2012 }
2013 }
2014
2015 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2016 if ( $this->sectiontitle !== '' ) {
2017 $sectionTitle = $this->sectiontitle;
2018 } else {
2019 $sectionTitle = $this->summary;
2020 }
2021
2022 $content = null;
2023
2024 if ( $this->isConflict ) {
2025 wfDebug( __METHOD__
2026 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2027 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2028 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2029 // ...or disable section editing for non-current revisions (not exposed anyway).
2030 if ( $this->editRevId !== null ) {
2031 $content = $this->page->replaceSectionAtRev(
2032 $this->section,
2033 $textbox_content,
2034 $sectionTitle,
2035 $this->editRevId
2036 );
2037 } else {
2038 $content = $this->page->replaceSectionContent(
2039 $this->section,
2040 $textbox_content,
2041 $sectionTitle,
2042 $this->edittime
2043 );
2044 }
2045 } else {
2046 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2047 $content = $this->page->replaceSectionContent(
2048 $this->section,
2049 $textbox_content,
2050 $sectionTitle
2051 );
2052 }
2053
2054 if ( is_null( $content ) ) {
2055 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2056 $this->isConflict = true;
2057 $content = $textbox_content; // do not try to merge here!
2058 } elseif ( $this->isConflict ) {
2059 # Attempt merge
2060 if ( $this->mergeChangesIntoContent( $content ) ) {
2061 // Successful merge! Maybe we should tell the user the good news?
2062 $this->isConflict = false;
2063 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2064 } else {
2065 $this->section = '';
2066 $this->textbox1 = ContentHandler::getContentText( $content );
2067 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2068 }
2069 }
2070
2071 if ( $this->isConflict ) {
2072 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2073 return $status;
2074 }
2075
2076 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2077 return $status;
2078 }
2079
2080 if ( $this->section == 'new' ) {
2081 // Handle the user preference to force summaries here
2082 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2083 $this->missingSummary = true;
2084 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2085 $status->value = self::AS_SUMMARY_NEEDED;
2086 return $status;
2087 }
2088
2089 // Do not allow the user to post an empty comment
2090 if ( $this->textbox1 == '' ) {
2091 $this->missingComment = true;
2092 $status->fatal( 'missingcommenttext' );
2093 $status->value = self::AS_TEXTBOX_EMPTY;
2094 return $status;
2095 }
2096 } elseif ( !$this->allowBlankSummary
2097 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2098 && !$content->isRedirect()
2099 && md5( $this->summary ) == $this->autoSumm
2100 ) {
2101 $this->missingSummary = true;
2102 $status->fatal( 'missingsummary' );
2103 $status->value = self::AS_SUMMARY_NEEDED;
2104 return $status;
2105 }
2106
2107 # All's well
2108 $sectionanchor = '';
2109 if ( $this->section == 'new' ) {
2110 $this->summary = $this->newSectionSummary( $sectionanchor );
2111 } elseif ( $this->section != '' ) {
2112 # Try to get a section anchor from the section source, redirect
2113 # to edited section if header found.
2114 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2115 # for duplicate heading checking and maybe parsing.
2116 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2117 # We can't deal with anchors, includes, html etc in the header for now,
2118 # headline would need to be parsed to improve this.
2119 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2120 $sectionanchor = $this->guessSectionName( $matches[2] );
2121 }
2122 }
2123 $result['sectionanchor'] = $sectionanchor;
2124
2125 // Save errors may fall down to the edit form, but we've now
2126 // merged the section into full text. Clear the section field
2127 // so that later submission of conflict forms won't try to
2128 // replace that into a duplicated mess.
2129 $this->textbox1 = $this->toEditText( $content );
2130 $this->section = '';
2131
2132 $status->value = self::AS_SUCCESS_UPDATE;
2133 }
2134
2135 if ( !$this->allowSelfRedirect
2136 && $content->isRedirect()
2137 && $content->getRedirectTarget()->equals( $this->getTitle() )
2138 ) {
2139 // If the page already redirects to itself, don't warn.
2140 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2141 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2142 $this->selfRedirect = true;
2143 $status->fatal( 'selfredirect' );
2144 $status->value = self::AS_SELF_REDIRECT;
2145 return $status;
2146 }
2147 }
2148
2149 // Check for length errors again now that the section is merged in
2150 $this->contentLength = strlen( $this->toEditText( $content ) );
2151 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
2152 $this->tooBig = true;
2153 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2154 return $status;
2155 }
2156
2157 $flags = EDIT_AUTOSUMMARY |
2158 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2159 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2160 ( $bot ? EDIT_FORCE_BOT : 0 );
2161
2162 $doEditStatus = $this->page->doEditContent(
2163 $content,
2164 $this->summary,
2165 $flags,
2166 false,
2167 $wgUser,
2168 $content->getDefaultFormat(),
2169 $this->changeTags,
2170 $this->undidRev
2171 );
2172
2173 if ( !$doEditStatus->isOK() ) {
2174 // Failure from doEdit()
2175 // Show the edit conflict page for certain recognized errors from doEdit(),
2176 // but don't show it for errors from extension hooks
2177 $errors = $doEditStatus->getErrorsArray();
2178 if ( in_array( $errors[0][0],
2179 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2180 ) {
2181 $this->isConflict = true;
2182 // Destroys data doEdit() put in $status->value but who cares
2183 $doEditStatus->value = self::AS_END;
2184 }
2185 return $doEditStatus;
2186 }
2187
2188 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2189 if ( $result['nullEdit'] ) {
2190 // We don't know if it was a null edit until now, so increment here
2191 $wgUser->pingLimiter( 'linkpurge' );
2192 }
2193 $result['redirect'] = $content->isRedirect();
2194
2195 $this->updateWatchlist();
2196
2197 // If the content model changed, add a log entry
2198 if ( $changingContentModel ) {
2199 $this->addContentModelChangeLogEntry(
2200 $wgUser,
2201 $new ? false : $oldContentModel,
2202 $this->contentModel,
2203 $this->summary
2204 );
2205 }
2206
2207 return $status;
2208 }
2209
2210 /**
2211 * @param User $user
2212 * @param string|false $oldModel false if the page is being newly created
2213 * @param string $newModel
2214 * @param string $reason
2215 */
2216 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2217 $new = $oldModel === false;
2218 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2219 $log->setPerformer( $user );
2220 $log->setTarget( $this->mTitle );
2221 $log->setComment( $reason );
2222 $log->setParameters( [
2223 '4::oldmodel' => $oldModel,
2224 '5::newmodel' => $newModel
2225 ] );
2226 $logid = $log->insert();
2227 $log->publish( $logid );
2228 }
2229
2230 /**
2231 * Register the change of watch status
2232 */
2233 protected function updateWatchlist() {
2234 global $wgUser;
2235
2236 if ( !$wgUser->isLoggedIn() ) {
2237 return;
2238 }
2239
2240 $user = $wgUser;
2241 $title = $this->mTitle;
2242 $watch = $this->watchthis;
2243 // Do this in its own transaction to reduce contention...
2244 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2245 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2246 return; // nothing to change
2247 }
2248 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2249 } );
2250 }
2251
2252 /**
2253 * Attempts to do 3-way merge of edit content with a base revision
2254 * and current content, in case of edit conflict, in whichever way appropriate
2255 * for the content type.
2256 *
2257 * @since 1.21
2258 *
2259 * @param Content $editContent
2260 *
2261 * @return bool
2262 */
2263 private function mergeChangesIntoContent( &$editContent ) {
2264 $db = wfGetDB( DB_MASTER );
2265
2266 // This is the revision the editor started from
2267 $baseRevision = $this->getBaseRevision();
2268 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2269
2270 if ( is_null( $baseContent ) ) {
2271 return false;
2272 }
2273
2274 // The current state, we want to merge updates into it
2275 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2276 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2277
2278 if ( is_null( $currentContent ) ) {
2279 return false;
2280 }
2281
2282 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2283
2284 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2285
2286 if ( $result ) {
2287 $editContent = $result;
2288 // Update parentRevId to what we just merged.
2289 $this->parentRevId = $currentRevision->getId();
2290 return true;
2291 }
2292
2293 return false;
2294 }
2295
2296 /**
2297 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2298 * one might think of X as the "base revision", which is NOT what this returns.
2299 * @return Revision Current version when the edit was started
2300 */
2301 public function getBaseRevision() {
2302 if ( !$this->mBaseRevision ) {
2303 $db = wfGetDB( DB_MASTER );
2304 $this->mBaseRevision = $this->editRevId
2305 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2306 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2307 }
2308 return $this->mBaseRevision;
2309 }
2310
2311 /**
2312 * Check given input text against $wgSpamRegex, and return the text of the first match.
2313 *
2314 * @param string $text
2315 *
2316 * @return string|bool Matching string or false
2317 */
2318 public static function matchSpamRegex( $text ) {
2319 global $wgSpamRegex;
2320 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2321 $regexes = (array)$wgSpamRegex;
2322 return self::matchSpamRegexInternal( $text, $regexes );
2323 }
2324
2325 /**
2326 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2327 *
2328 * @param string $text
2329 *
2330 * @return string|bool Matching string or false
2331 */
2332 public static function matchSummarySpamRegex( $text ) {
2333 global $wgSummarySpamRegex;
2334 $regexes = (array)$wgSummarySpamRegex;
2335 return self::matchSpamRegexInternal( $text, $regexes );
2336 }
2337
2338 /**
2339 * @param string $text
2340 * @param array $regexes
2341 * @return bool|string
2342 */
2343 protected static function matchSpamRegexInternal( $text, $regexes ) {
2344 foreach ( $regexes as $regex ) {
2345 $matches = [];
2346 if ( preg_match( $regex, $text, $matches ) ) {
2347 return $matches[0];
2348 }
2349 }
2350 return false;
2351 }
2352
2353 public function setHeaders() {
2354 global $wgOut, $wgUser, $wgAjaxEditStash;
2355
2356 $wgOut->addModules( 'mediawiki.action.edit' );
2357 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2358
2359 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2360 // The addition of default buttons is handled by getEditToolbar() which
2361 // has its own dependency on this module. The call here ensures the module
2362 // is loaded in time (it has position "top") for other modules to register
2363 // buttons (e.g. extensions, gadgets, user scripts).
2364 $wgOut->addModules( 'mediawiki.toolbar' );
2365 }
2366
2367 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2368 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2369 }
2370
2371 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2372 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2373 }
2374
2375 # Enabled article-related sidebar, toplinks, etc.
2376 $wgOut->setArticleRelated( true );
2377
2378 $contextTitle = $this->getContextTitle();
2379 if ( $this->isConflict ) {
2380 $msg = 'editconflict';
2381 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2382 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2383 } else {
2384 $msg = $contextTitle->exists()
2385 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2386 && $contextTitle->getDefaultMessageText() !== false
2387 )
2388 ? 'editing'
2389 : 'creating';
2390 }
2391
2392 # Use the title defined by DISPLAYTITLE magic word when present
2393 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2394 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2395 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2396 if ( $displayTitle === false ) {
2397 $displayTitle = $contextTitle->getPrefixedText();
2398 }
2399 $wgOut->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2400 # Transmit the name of the message to JavaScript for live preview
2401 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2402 $wgOut->addJsConfigVars( [
2403 'wgEditMessage' => $msg,
2404 'wgAjaxEditStash' => $wgAjaxEditStash,
2405 ] );
2406 }
2407
2408 /**
2409 * Show all applicable editing introductions
2410 */
2411 protected function showIntro() {
2412 global $wgOut, $wgUser;
2413 if ( $this->suppressIntro ) {
2414 return;
2415 }
2416
2417 $namespace = $this->mTitle->getNamespace();
2418
2419 if ( $namespace == NS_MEDIAWIKI ) {
2420 # Show a warning if editing an interface message
2421 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2422 # If this is a default message (but not css or js),
2423 # show a hint that it is translatable on translatewiki.net
2424 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2425 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2426 ) {
2427 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2428 if ( $defaultMessageText !== false ) {
2429 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2430 'translateinterface' );
2431 }
2432 }
2433 } elseif ( $namespace == NS_FILE ) {
2434 # Show a hint to shared repo
2435 $file = wfFindFile( $this->mTitle );
2436 if ( $file && !$file->isLocal() ) {
2437 $descUrl = $file->getDescriptionUrl();
2438 # there must be a description url to show a hint to shared repo
2439 if ( $descUrl ) {
2440 if ( !$this->mTitle->exists() ) {
2441 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2442 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2443 ] );
2444 } else {
2445 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2446 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2447 ] );
2448 }
2449 }
2450 }
2451 }
2452
2453 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2454 # Show log extract when the user is currently blocked
2455 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2456 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2457 $user = User::newFromName( $username, false /* allow IP users */ );
2458 $ip = User::isIP( $username );
2459 $block = Block::newFromTarget( $user, $user );
2460 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2461 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2462 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2463 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2464 # Show log extract if the user is currently blocked
2465 LogEventsList::showLogExtract(
2466 $wgOut,
2467 'block',
2468 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2469 '',
2470 [
2471 'lim' => 1,
2472 'showIfEmpty' => false,
2473 'msgKey' => [
2474 'blocked-notice-logextract',
2475 $user->getName() # Support GENDER in notice
2476 ]
2477 ]
2478 );
2479 }
2480 }
2481 # Try to add a custom edit intro, or use the standard one if this is not possible.
2482 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2483 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2484 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2485 ) );
2486 if ( $wgUser->isLoggedIn() ) {
2487 $wgOut->wrapWikiMsg(
2488 // Suppress the external link icon, consider the help url an internal one
2489 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2490 [
2491 'newarticletext',
2492 $helpLink
2493 ]
2494 );
2495 } else {
2496 $wgOut->wrapWikiMsg(
2497 // Suppress the external link icon, consider the help url an internal one
2498 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2499 [
2500 'newarticletextanon',
2501 $helpLink
2502 ]
2503 );
2504 }
2505 }
2506 # Give a notice if the user is editing a deleted/moved page...
2507 if ( !$this->mTitle->exists() ) {
2508 $dbr = wfGetDB( DB_REPLICA );
2509
2510 LogEventsList::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle,
2511 '',
2512 [
2513 'lim' => 10,
2514 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2515 'showIfEmpty' => false,
2516 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2517 ]
2518 );
2519 }
2520 }
2521
2522 /**
2523 * Attempt to show a custom editing introduction, if supplied
2524 *
2525 * @return bool
2526 */
2527 protected function showCustomIntro() {
2528 if ( $this->editintro ) {
2529 $title = Title::newFromText( $this->editintro );
2530 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2531 global $wgOut;
2532 // Added using template syntax, to take <noinclude>'s into account.
2533 $wgOut->addWikiTextTitleTidy(
2534 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2535 $this->mTitle
2536 );
2537 return true;
2538 }
2539 }
2540 return false;
2541 }
2542
2543 /**
2544 * Gets an editable textual representation of $content.
2545 * The textual representation can be turned by into a Content object by the
2546 * toEditContent() method.
2547 *
2548 * If $content is null or false or a string, $content is returned unchanged.
2549 *
2550 * If the given Content object is not of a type that can be edited using
2551 * the text base EditPage, an exception will be raised. Set
2552 * $this->allowNonTextContent to true to allow editing of non-textual
2553 * content.
2554 *
2555 * @param Content|null|bool|string $content
2556 * @return string The editable text form of the content.
2557 *
2558 * @throws MWException If $content is not an instance of TextContent and
2559 * $this->allowNonTextContent is not true.
2560 */
2561 protected function toEditText( $content ) {
2562 if ( $content === null || $content === false || is_string( $content ) ) {
2563 return $content;
2564 }
2565
2566 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2567 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2568 }
2569
2570 return $content->serialize( $this->contentFormat );
2571 }
2572
2573 /**
2574 * Turns the given text into a Content object by unserializing it.
2575 *
2576 * If the resulting Content object is not of a type that can be edited using
2577 * the text base EditPage, an exception will be raised. Set
2578 * $this->allowNonTextContent to true to allow editing of non-textual
2579 * content.
2580 *
2581 * @param string|null|bool $text Text to unserialize
2582 * @return Content|bool|null The content object created from $text. If $text was false
2583 * or null, false resp. null will be returned instead.
2584 *
2585 * @throws MWException If unserializing the text results in a Content
2586 * object that is not an instance of TextContent and
2587 * $this->allowNonTextContent is not true.
2588 */
2589 protected function toEditContent( $text ) {
2590 if ( $text === false || $text === null ) {
2591 return $text;
2592 }
2593
2594 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2595 $this->contentModel, $this->contentFormat );
2596
2597 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2598 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2599 }
2600
2601 return $content;
2602 }
2603
2604 /**
2605 * Send the edit form and related headers to $wgOut
2606 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2607 * during form output near the top, for captchas and the like.
2608 *
2609 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2610 * use the EditPage::showEditForm:fields hook instead.
2611 */
2612 public function showEditForm( $formCallback = null ) {
2613 global $wgOut, $wgUser;
2614
2615 # need to parse the preview early so that we know which templates are used,
2616 # otherwise users with "show preview after edit box" will get a blank list
2617 # we parse this near the beginning so that setHeaders can do the title
2618 # setting work instead of leaving it in getPreviewText
2619 $previewOutput = '';
2620 if ( $this->formtype == 'preview' ) {
2621 $previewOutput = $this->getPreviewText();
2622 }
2623
2624 // Avoid PHP 7.1 warning of passing $this by reference
2625 $editPage = $this;
2626 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$wgOut ] );
2627
2628 $this->setHeaders();
2629
2630 $this->addTalkPageText();
2631 $this->addEditNotices();
2632
2633 if ( !$this->isConflict &&
2634 $this->section != '' &&
2635 !$this->isSectionEditSupported() ) {
2636 // We use $this->section to much before this and getVal('wgSection') directly in other places
2637 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2638 // Someone is welcome to try refactoring though
2639 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2640 return;
2641 }
2642
2643 $this->showHeader();
2644
2645 $wgOut->addHTML( $this->editFormPageTop );
2646
2647 if ( $wgUser->getOption( 'previewontop' ) ) {
2648 $this->displayPreviewArea( $previewOutput, true );
2649 }
2650
2651 $wgOut->addHTML( $this->editFormTextTop );
2652
2653 $showToolbar = true;
2654 if ( $this->wasDeletedSinceLastEdit() ) {
2655 if ( $this->formtype == 'save' ) {
2656 // Hide the toolbar and edit area, user can click preview to get it back
2657 // Add an confirmation checkbox and explanation.
2658 $showToolbar = false;
2659 } else {
2660 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2661 'deletedwhileediting' );
2662 }
2663 }
2664
2665 // @todo add EditForm plugin interface and use it here!
2666 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2667 $wgOut->addHTML( Html::openElement(
2668 'form',
2669 [
2670 'class' => $this->oouiEnabled ? 'mw-editform-ooui' : 'mw-editform-legacy',
2671 'id' => self::EDITFORM_ID,
2672 'name' => self::EDITFORM_ID,
2673 'method' => 'post',
2674 'action' => $this->getActionURL( $this->getContextTitle() ),
2675 'enctype' => 'multipart/form-data'
2676 ]
2677 ) );
2678
2679 if ( is_callable( $formCallback ) ) {
2680 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2681 call_user_func_array( $formCallback, [ &$wgOut ] );
2682 }
2683
2684 // Add an empty field to trip up spambots
2685 $wgOut->addHTML(
2686 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2687 . Html::rawElement(
2688 'label',
2689 [ 'for' => 'wpAntispam' ],
2690 $this->context->msg( 'simpleantispam-label' )->parse()
2691 )
2692 . Xml::element(
2693 'input',
2694 [
2695 'type' => 'text',
2696 'name' => 'wpAntispam',
2697 'id' => 'wpAntispam',
2698 'value' => ''
2699 ]
2700 )
2701 . Xml::closeElement( 'div' )
2702 );
2703
2704 // Avoid PHP 7.1 warning of passing $this by reference
2705 $editPage = $this;
2706 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$wgOut ] );
2707
2708 // Put these up at the top to ensure they aren't lost on early form submission
2709 $this->showFormBeforeText();
2710
2711 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2712 $username = $this->lastDelete->user_name;
2713 $comment = $this->lastDelete->log_comment;
2714
2715 // It is better to not parse the comment at all than to have templates expanded in the middle
2716 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2717 $key = $comment === ''
2718 ? 'confirmrecreate-noreason'
2719 : 'confirmrecreate';
2720 $wgOut->addHTML(
2721 '<div class="mw-confirm-recreate">' .
2722 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2723 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2724 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2725 ) .
2726 '</div>'
2727 );
2728 }
2729
2730 # When the summary is hidden, also hide them on preview/show changes
2731 if ( $this->nosummary ) {
2732 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2733 }
2734
2735 # If a blank edit summary was previously provided, and the appropriate
2736 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2737 # user being bounced back more than once in the event that a summary
2738 # is not required.
2739 # ####
2740 # For a bit more sophisticated detection of blank summaries, hash the
2741 # automatic one and pass that in the hidden field wpAutoSummary.
2742 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2743 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2744 }
2745
2746 if ( $this->undidRev ) {
2747 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2748 }
2749
2750 if ( $this->selfRedirect ) {
2751 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2752 }
2753
2754 if ( $this->hasPresetSummary ) {
2755 // If a summary has been preset using &summary= we don't want to prompt for
2756 // a different summary. Only prompt for a summary if the summary is blanked.
2757 // (T19416)
2758 $this->autoSumm = md5( '' );
2759 }
2760
2761 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2762 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2763
2764 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2765 $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2766
2767 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2768 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2769
2770 // Preserve &ooui=1 / &ooui=0 from URL parameters after submitting the page for preview
2771 $wgOut->addHTML( Html::hidden( 'ooui', $this->oouiEnabled ? '1' : '0' ) );
2772
2773 // following functions will need OOUI, enable it only once; here.
2774 if ( $this->oouiEnabled ) {
2775 $wgOut->enableOOUI();
2776 }
2777
2778 if ( $this->section == 'new' ) {
2779 $this->showSummaryInput( true, $this->summary );
2780 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2781 }
2782
2783 $wgOut->addHTML( $this->editFormTextBeforeContent );
2784
2785 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2786 $wgOut->addHTML( self::getEditToolbar( $this->mTitle ) );
2787 }
2788
2789 if ( $this->blankArticle ) {
2790 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2791 }
2792
2793 if ( $this->isConflict ) {
2794 // In an edit conflict bypass the overridable content form method
2795 // and fallback to the raw wpTextbox1 since editconflicts can't be
2796 // resolved between page source edits and custom ui edits using the
2797 // custom edit ui.
2798 $this->textbox2 = $this->textbox1;
2799
2800 $content = $this->getCurrentContent();
2801 $this->textbox1 = $this->toEditText( $content );
2802
2803 $this->showTextbox1();
2804 } else {
2805 $this->showContentForm();
2806 }
2807
2808 $wgOut->addHTML( $this->editFormTextAfterContent );
2809
2810 $this->showStandardInputs();
2811
2812 $this->showFormAfterText();
2813
2814 $this->showTosSummary();
2815
2816 $this->showEditTools();
2817
2818 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2819
2820 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2821
2822 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2823 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2824
2825 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2826 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2827
2828 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2829
2830 if ( $this->isConflict ) {
2831 try {
2832 $this->showConflict();
2833 } catch ( MWContentSerializationException $ex ) {
2834 // this can't really happen, but be nice if it does.
2835 $msg = $this->context->msg(
2836 'content-failed-to-parse',
2837 $this->contentModel,
2838 $this->contentFormat,
2839 $ex->getMessage()
2840 );
2841 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2842 }
2843 }
2844
2845 // Set a hidden field so JS knows what edit form mode we are in
2846 if ( $this->isConflict ) {
2847 $mode = 'conflict';
2848 } elseif ( $this->preview ) {
2849 $mode = 'preview';
2850 } elseif ( $this->diff ) {
2851 $mode = 'diff';
2852 } else {
2853 $mode = 'text';
2854 }
2855 $wgOut->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2856
2857 // Marker for detecting truncated form data. This must be the last
2858 // parameter sent in order to be of use, so do not move me.
2859 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2860 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2861
2862 if ( !$wgUser->getOption( 'previewontop' ) ) {
2863 $this->displayPreviewArea( $previewOutput, false );
2864 }
2865 }
2866
2867 /**
2868 * Wrapper around TemplatesOnThisPageFormatter to make
2869 * a "templates on this page" list.
2870 *
2871 * @param Title[] $templates
2872 * @return string HTML
2873 */
2874 public function makeTemplatesOnThisPageList( array $templates ) {
2875 $templateListFormatter = new TemplatesOnThisPageFormatter(
2876 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
2877 );
2878
2879 // preview if preview, else section if section, else false
2880 $type = false;
2881 if ( $this->preview ) {
2882 $type = 'preview';
2883 } elseif ( $this->section != '' ) {
2884 $type = 'section';
2885 }
2886
2887 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2888 $templateListFormatter->format( $templates, $type )
2889 );
2890 }
2891
2892 /**
2893 * Extract the section title from current section text, if any.
2894 *
2895 * @param string $text
2896 * @return string|bool String or false
2897 */
2898 public static function extractSectionTitle( $text ) {
2899 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2900 if ( !empty( $matches[2] ) ) {
2901 global $wgParser;
2902 return $wgParser->stripSectionName( trim( $matches[2] ) );
2903 } else {
2904 return false;
2905 }
2906 }
2907
2908 protected function showHeader() {
2909 global $wgOut, $wgUser;
2910 global $wgAllowUserCss, $wgAllowUserJs;
2911
2912 if ( $this->isConflict ) {
2913 $this->addExplainConflictHeader( $wgOut );
2914 $this->editRevId = $this->page->getLatest();
2915 } else {
2916 if ( $this->section != '' && $this->section != 'new' ) {
2917 if ( !$this->summary && !$this->preview && !$this->diff ) {
2918 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2919 if ( $sectionTitle !== false ) {
2920 $this->summary = "/* $sectionTitle */ ";
2921 }
2922 }
2923 }
2924
2925 $buttonLabel = $this->context->msg( $this->getSaveButtonLabel() )->text();
2926
2927 if ( $this->missingComment ) {
2928 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2929 }
2930
2931 if ( $this->missingSummary && $this->section != 'new' ) {
2932 $wgOut->wrapWikiMsg(
2933 "<div id='mw-missingsummary'>\n$1\n</div>",
2934 [ 'missingsummary', $buttonLabel ]
2935 );
2936 }
2937
2938 if ( $this->missingSummary && $this->section == 'new' ) {
2939 $wgOut->wrapWikiMsg(
2940 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2941 [ 'missingcommentheader', $buttonLabel ]
2942 );
2943 }
2944
2945 if ( $this->blankArticle ) {
2946 $wgOut->wrapWikiMsg(
2947 "<div id='mw-blankarticle'>\n$1\n</div>",
2948 [ 'blankarticle', $buttonLabel ]
2949 );
2950 }
2951
2952 if ( $this->selfRedirect ) {
2953 $wgOut->wrapWikiMsg(
2954 "<div id='mw-selfredirect'>\n$1\n</div>",