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