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