EditPage: Don't set 'hookaborted' error if the hook set a better error
[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 $content = false;
1183
1184 $user = $this->context->getUser();
1185 $request = $this->context->getRequest();
1186 // For message page not locally set, use the i18n message.
1187 // For other non-existent articles, use preload text if any.
1188 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1189 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1190 # If this is a system message, get the default text.
1191 $msg = $this->mTitle->getDefaultMessageText();
1192
1193 $content = $this->toEditContent( $msg );
1194 }
1195 if ( $content === false ) {
1196 # If requested, preload some text.
1197 $preload = $request->getVal( 'preload',
1198 // Custom preload text for new sections
1199 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1200 $params = $request->getArray( 'preloadparams', [] );
1201
1202 $content = $this->getPreloadedContent( $preload, $params );
1203 }
1204 // For existing pages, get text based on "undo" or section parameters.
1205 } elseif ( $this->section != '' ) {
1206 // Get section edit text (returns $def_text for invalid sections)
1207 $orig = $this->getOriginalContent( $user );
1208 $content = $orig ? $orig->getSection( $this->section ) : null;
1209
1210 if ( !$content ) {
1211 $content = $def_content;
1212 }
1213 } else {
1214 $undoafter = $request->getInt( 'undoafter' );
1215 $undo = $request->getInt( 'undo' );
1216
1217 if ( $undo > 0 && $undoafter > 0 ) {
1218 $undorev = Revision::newFromId( $undo );
1219 $oldrev = Revision::newFromId( $undoafter );
1220 $undoMsg = null;
1221
1222 # Sanity check, make sure it's the right page,
1223 # the revisions exist and they were not deleted.
1224 # Otherwise, $content will be left as-is.
1225 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1226 !$undorev->isDeleted( RevisionRecord::DELETED_TEXT ) &&
1227 !$oldrev->isDeleted( RevisionRecord::DELETED_TEXT )
1228 ) {
1229 if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1230 || !$this->isSupportedContentModel( $oldrev->getContentModel() )
1231 ) {
1232 // Hack for undo while EditPage can't handle multi-slot editing
1233 $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [
1234 'action' => 'mcrundo',
1235 'undo' => $undo,
1236 'undoafter' => $undoafter,
1237 ] ) );
1238 return false;
1239 } else {
1240 $content = $this->page->getUndoContent( $undorev, $oldrev );
1241
1242 if ( $content === false ) {
1243 # Warn the user that something went wrong
1244 $undoMsg = 'failure';
1245 }
1246 }
1247
1248 if ( $undoMsg === null ) {
1249 $oldContent = $this->page->getContent( RevisionRecord::RAW );
1250 $popts = ParserOptions::newFromUserAndLang(
1251 $user, MediaWikiServices::getInstance()->getContentLanguage() );
1252 $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1253 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1254 // The undo may change content
1255 // model if its reverting the top
1256 // edit. This can result in
1257 // mismatched content model/format.
1258 $this->contentModel = $newContent->getModel();
1259 $this->contentFormat = $oldrev->getContentFormat();
1260 }
1261
1262 if ( $newContent->equals( $oldContent ) ) {
1263 # Tell the user that the undo results in no change,
1264 # i.e. the revisions were already undone.
1265 $undoMsg = 'nochange';
1266 $content = false;
1267 } else {
1268 # Inform the user of our success and set an automatic edit summary
1269 $undoMsg = 'success';
1270
1271 # If we just undid one rev, use an autosummary
1272 $firstrev = $oldrev->getNext();
1273 if ( $firstrev && $firstrev->getId() == $undo ) {
1274 $userText = $undorev->getUserText();
1275 if ( $userText === '' ) {
1276 $undoSummary = $this->context->msg(
1277 'undo-summary-username-hidden',
1278 $undo
1279 )->inContentLanguage()->text();
1280 } else {
1281 $undoSummary = $this->context->msg(
1282 'undo-summary',
1283 $undo,
1284 $userText
1285 )->inContentLanguage()->text();
1286 }
1287 if ( $this->summary === '' ) {
1288 $this->summary = $undoSummary;
1289 } else {
1290 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1291 ->inContentLanguage()->text() . $this->summary;
1292 }
1293 $this->undidRev = $undo;
1294 }
1295 $this->formtype = 'diff';
1296 }
1297 }
1298 } else {
1299 // Failed basic sanity checks.
1300 // Older revisions may have been removed since the link
1301 // was created, or we may simply have got bogus input.
1302 $undoMsg = 'norev';
1303 }
1304
1305 $out = $this->context->getOutput();
1306 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1307 // undo-nochange.
1308 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1309 $this->editFormPageTop .= Html::rawElement(
1310 'div', [ 'class' => $class ],
1311 $out->parseAsInterface(
1312 $this->context->msg( 'undo-' . $undoMsg )->plain()
1313 )
1314 );
1315 }
1316
1317 if ( $content === false ) {
1318 // Hack for restoring old revisions while EditPage
1319 // can't handle multi-slot editing.
1320
1321 $curRevision = $this->page->getRevision();
1322 $oldRevision = $this->mArticle->getRevisionFetched();
1323
1324 if ( $curRevision
1325 && $oldRevision
1326 && $curRevision->getId() !== $oldRevision->getId()
1327 && ( WikiPage::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
1328 || !$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
1329 ) {
1330 $this->context->getOutput()->redirect(
1331 $this->mTitle->getFullURL(
1332 [
1333 'action' => 'mcrrestore',
1334 'restore' => $oldRevision->getId(),
1335 ]
1336 )
1337 );
1338
1339 return false;
1340 }
1341 }
1342
1343 if ( $content === false ) {
1344 $content = $this->getOriginalContent( $user );
1345 }
1346 }
1347
1348 return $content;
1349 }
1350
1351 /**
1352 * Get the content of the wanted revision, without section extraction.
1353 *
1354 * The result of this function can be used to compare user's input with
1355 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1356 * to the original text of the edit.
1357 *
1358 * This differs from Article::getContent() that when a missing revision is
1359 * encountered the result will be null and not the
1360 * 'missing-revision' message.
1361 *
1362 * @since 1.19
1363 * @param User $user The user to get the revision for
1364 * @return Content|null
1365 */
1366 private function getOriginalContent( User $user ) {
1367 if ( $this->section == 'new' ) {
1368 return $this->getCurrentContent();
1369 }
1370 $revision = $this->mArticle->getRevisionFetched();
1371 if ( $revision === null ) {
1372 $handler = ContentHandler::getForModelID( $this->contentModel );
1373 return $handler->makeEmptyContent();
1374 }
1375 $content = $revision->getContent( RevisionRecord::FOR_THIS_USER, $user );
1376 return $content;
1377 }
1378
1379 /**
1380 * Get the edit's parent revision ID
1381 *
1382 * The "parent" revision is the ancestor that should be recorded in this
1383 * page's revision history. It is either the revision ID of the in-memory
1384 * article content, or in the case of a 3-way merge in order to rebase
1385 * across a recoverable edit conflict, the ID of the newer revision to
1386 * which we have rebased this page.
1387 *
1388 * @since 1.27
1389 * @return int Revision ID
1390 */
1391 public function getParentRevId() {
1392 if ( $this->parentRevId ) {
1393 return $this->parentRevId;
1394 } else {
1395 return $this->mArticle->getRevIdFetched();
1396 }
1397 }
1398
1399 /**
1400 * Get the current content of the page. This is basically similar to
1401 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1402 * content object is returned instead of null.
1403 *
1404 * @since 1.21
1405 * @return Content
1406 */
1407 protected function getCurrentContent() {
1408 $rev = $this->page->getRevision();
1409 $content = $rev ? $rev->getContent( RevisionRecord::RAW ) : null;
1410
1411 if ( $content === false || $content === null ) {
1412 $handler = ContentHandler::getForModelID( $this->contentModel );
1413 return $handler->makeEmptyContent();
1414 } elseif ( !$this->undidRev ) {
1415 // Content models should always be the same since we error
1416 // out if they are different before this point (in ->edit()).
1417 // The exception being, during an undo, the current revision might
1418 // differ from the prior revision.
1419 $logger = LoggerFactory::getInstance( 'editpage' );
1420 if ( $this->contentModel !== $rev->getContentModel() ) {
1421 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1422 'prev' => $this->contentModel,
1423 'new' => $rev->getContentModel(),
1424 'title' => $this->getTitle()->getPrefixedDBkey(),
1425 'method' => __METHOD__
1426 ] );
1427 $this->contentModel = $rev->getContentModel();
1428 }
1429
1430 // Given that the content models should match, the current selected
1431 // format should be supported.
1432 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1433 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1434
1435 'prev' => $this->contentFormat,
1436 'new' => $rev->getContentFormat(),
1437 'title' => $this->getTitle()->getPrefixedDBkey(),
1438 'method' => __METHOD__
1439 ] );
1440 $this->contentFormat = $rev->getContentFormat();
1441 }
1442 }
1443 return $content;
1444 }
1445
1446 /**
1447 * Use this method before edit() to preload some content into the edit box
1448 *
1449 * @param Content $content
1450 *
1451 * @since 1.21
1452 */
1453 public function setPreloadedContent( Content $content ) {
1454 $this->mPreloadContent = $content;
1455 }
1456
1457 /**
1458 * Get the contents to be preloaded into the box, either set by
1459 * an earlier setPreloadText() or by loading the given page.
1460 *
1461 * @param string $preload Representing the title to preload from.
1462 * @param array $params Parameters to use (interface-message style) in the preloaded text
1463 *
1464 * @return Content
1465 *
1466 * @since 1.21
1467 */
1468 protected function getPreloadedContent( $preload, $params = [] ) {
1469 if ( !empty( $this->mPreloadContent ) ) {
1470 return $this->mPreloadContent;
1471 }
1472
1473 $handler = ContentHandler::getForModelID( $this->contentModel );
1474
1475 if ( $preload === '' ) {
1476 return $handler->makeEmptyContent();
1477 }
1478
1479 $user = $this->context->getUser();
1480 $title = Title::newFromText( $preload );
1481
1482 # Check for existence to avoid getting MediaWiki:Noarticletext
1483 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1484 // TODO: somehow show a warning to the user!
1485 return $handler->makeEmptyContent();
1486 }
1487
1488 $page = WikiPage::factory( $title );
1489 if ( $page->isRedirect() ) {
1490 $title = $page->getRedirectTarget();
1491 # Same as before
1492 if ( !$this->isPageExistingAndViewable( $title, $user ) ) {
1493 // TODO: somehow show a warning to the user!
1494 return $handler->makeEmptyContent();
1495 }
1496 $page = WikiPage::factory( $title );
1497 }
1498
1499 $parserOptions = ParserOptions::newFromUser( $user );
1500 $content = $page->getContent( RevisionRecord::RAW );
1501
1502 if ( !$content ) {
1503 // TODO: somehow show a warning to the user!
1504 return $handler->makeEmptyContent();
1505 }
1506
1507 if ( $content->getModel() !== $handler->getModelID() ) {
1508 $converted = $content->convert( $handler->getModelID() );
1509
1510 if ( !$converted ) {
1511 // TODO: somehow show a warning to the user!
1512 wfDebug( "Attempt to preload incompatible content: " .
1513 "can't convert " . $content->getModel() .
1514 " to " . $handler->getModelID() );
1515
1516 return $handler->makeEmptyContent();
1517 }
1518
1519 $content = $converted;
1520 }
1521
1522 return $content->preloadTransform( $title, $parserOptions, $params );
1523 }
1524
1525 /**
1526 * Verify if a given title exists and the given user is allowed to view it
1527 *
1528 * @see EditPage::getPreloadedContent()
1529 * @param Title|null $title
1530 * @param User $user
1531 * @return bool
1532 * @throws Exception
1533 */
1534 private function isPageExistingAndViewable( $title, User $user ) {
1535 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1536
1537 return $title && $title->exists() && $permissionManager->userCan( 'read', $user, $title );
1538 }
1539
1540 /**
1541 * Make sure the form isn't faking a user's credentials.
1542 *
1543 * @param WebRequest &$request
1544 * @return bool
1545 * @private
1546 */
1547 public function tokenOk( &$request ) {
1548 $token = $request->getVal( 'wpEditToken' );
1549 $user = $this->context->getUser();
1550 $this->mTokenOk = $user->matchEditToken( $token );
1551 $this->mTokenOkExceptSuffix = $user->matchEditTokenNoSuffix( $token );
1552 return $this->mTokenOk;
1553 }
1554
1555 /**
1556 * Sets post-edit cookie indicating the user just saved a particular revision.
1557 *
1558 * This uses a temporary cookie for each revision ID so separate saves will never
1559 * interfere with each other.
1560 *
1561 * Article::view deletes the cookie on server-side after the redirect and
1562 * converts the value to the global JavaScript variable wgPostEdit.
1563 *
1564 * If the variable were set on the server, it would be cached, which is unwanted
1565 * since the post-edit state should only apply to the load right after the save.
1566 *
1567 * @param int $statusValue The status value (to check for new article status)
1568 */
1569 protected function setPostEditCookie( $statusValue ) {
1570 $revisionId = $this->page->getLatest();
1571 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1572
1573 $val = 'saved';
1574 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1575 $val = 'created';
1576 } elseif ( $this->oldid ) {
1577 $val = 'restored';
1578 }
1579
1580 $response = $this->context->getRequest()->response();
1581 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1582 }
1583
1584 /**
1585 * Attempt submission
1586 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1587 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1588 * @return Status The resulting status object.
1589 */
1590 public function attemptSave( &$resultDetails = false ) {
1591 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1592 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1593 // This is needed since PageUpdater no longer checks these rights!
1594
1595 // Allow bots to exempt some edits from bot flagging
1596 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1597 $bot = $permissionManager->userHasRight( $this->context->getUser(), 'bot' ) && $this->bot;
1598 $status = $this->internalAttemptSave( $resultDetails, $bot );
1599
1600 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1601
1602 return $status;
1603 }
1604
1605 /**
1606 * Log when a page was successfully saved after the edit conflict view
1607 */
1608 private function incrementResolvedConflicts() {
1609 if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1610 return;
1611 }
1612
1613 $this->getEditConflictHelper()->incrementResolvedStats();
1614 }
1615
1616 /**
1617 * Handle status, such as after attempt save
1618 *
1619 * @param Status $status
1620 * @param array|bool $resultDetails
1621 *
1622 * @throws ErrorPageError
1623 * @return bool False, if output is done, true if rest of the form should be displayed
1624 */
1625 private function handleStatus( Status $status, $resultDetails ) {
1626 /**
1627 * @todo FIXME: once the interface for internalAttemptSave() is made
1628 * nicer, this should use the message in $status
1629 */
1630 if ( $status->value == self::AS_SUCCESS_UPDATE
1631 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1632 ) {
1633 $this->incrementResolvedConflicts();
1634
1635 $this->didSave = true;
1636 if ( !$resultDetails['nullEdit'] ) {
1637 $this->setPostEditCookie( $status->value );
1638 }
1639 }
1640
1641 $out = $this->context->getOutput();
1642
1643 // "wpExtraQueryRedirect" is a hidden input to modify
1644 // after save URL and is not used by actual edit form
1645 $request = $this->context->getRequest();
1646 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1647
1648 switch ( $status->value ) {
1649 case self::AS_HOOK_ERROR_EXPECTED:
1650 case self::AS_CONTENT_TOO_BIG:
1651 case self::AS_ARTICLE_WAS_DELETED:
1652 case self::AS_CONFLICT_DETECTED:
1653 case self::AS_SUMMARY_NEEDED:
1654 case self::AS_TEXTBOX_EMPTY:
1655 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1656 case self::AS_END:
1657 case self::AS_BLANK_ARTICLE:
1658 case self::AS_SELF_REDIRECT:
1659 return true;
1660
1661 case self::AS_HOOK_ERROR:
1662 return false;
1663
1664 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1665 case self::AS_PARSE_ERROR:
1666 case self::AS_UNICODE_NOT_SUPPORTED:
1667 $out->wrapWikiTextAsInterface( 'error', $status->getWikiText() );
1668 return true;
1669
1670 case self::AS_SUCCESS_NEW_ARTICLE:
1671 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1672 if ( $extraQueryRedirect ) {
1673 if ( $query !== '' ) {
1674 $query .= '&';
1675 }
1676 $query .= $extraQueryRedirect;
1677 }
1678 $anchor = $resultDetails['sectionanchor'] ?? '';
1679 $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1680 return false;
1681
1682 case self::AS_SUCCESS_UPDATE:
1683 $extraQuery = '';
1684 $sectionanchor = $resultDetails['sectionanchor'];
1685
1686 // Give extensions a chance to modify URL query on update
1687 Hooks::run(
1688 'ArticleUpdateBeforeRedirect',
1689 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1690 );
1691
1692 if ( $resultDetails['redirect'] ) {
1693 if ( $extraQuery !== '' ) {
1694 $extraQuery = '&' . $extraQuery;
1695 }
1696 $extraQuery = 'redirect=no' . $extraQuery;
1697 }
1698 if ( $extraQueryRedirect ) {
1699 if ( $extraQuery !== '' ) {
1700 $extraQuery .= '&';
1701 }
1702 $extraQuery .= $extraQueryRedirect;
1703 }
1704
1705 $out->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1706 return false;
1707
1708 case self::AS_SPAM_ERROR:
1709 $this->spamPageWithContent( $resultDetails['spam'] );
1710 return false;
1711
1712 case self::AS_BLOCKED_PAGE_FOR_USER:
1713 throw new UserBlockedError( $this->context->getUser()->getBlock() );
1714
1715 case self::AS_IMAGE_REDIRECT_ANON:
1716 case self::AS_IMAGE_REDIRECT_LOGGED:
1717 throw new PermissionsError( 'upload' );
1718
1719 case self::AS_READ_ONLY_PAGE_ANON:
1720 case self::AS_READ_ONLY_PAGE_LOGGED:
1721 throw new PermissionsError( 'edit' );
1722
1723 case self::AS_READ_ONLY_PAGE:
1724 throw new ReadOnlyError;
1725
1726 case self::AS_RATE_LIMITED:
1727 throw new ThrottledError();
1728
1729 case self::AS_NO_CREATE_PERMISSION:
1730 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1731 throw new PermissionsError( $permission );
1732
1733 case self::AS_NO_CHANGE_CONTENT_MODEL:
1734 throw new PermissionsError( 'editcontentmodel' );
1735
1736 default:
1737 // We don't recognize $status->value. The only way that can happen
1738 // is if an extension hook aborted from inside ArticleSave.
1739 // Render the status object into $this->hookError
1740 // FIXME this sucks, we should just use the Status object throughout
1741 $this->hookError = '<div class="error">' . "\n" . $status->getWikiText() .
1742 '</div>';
1743 return true;
1744 }
1745 }
1746
1747 /**
1748 * Run hooks that can filter edits just before they get saved.
1749 *
1750 * @param Content $content The Content to filter.
1751 * @param Status $status For reporting the outcome to the caller
1752 * @param User $user The user performing the edit
1753 *
1754 * @return bool
1755 */
1756 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1757 // Run old style post-section-merge edit filter
1758 if ( $this->hookError != '' ) {
1759 # ...or the hook could be expecting us to produce an error
1760 $status->fatal( 'hookaborted' );
1761 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1762 return false;
1763 }
1764
1765 // Run new style post-section-merge edit filter
1766 if ( !Hooks::run( 'EditFilterMergedContent',
1767 [ $this->context, $content, $status, $this->summary,
1768 $user, $this->minoredit ] )
1769 ) {
1770 # Error messages etc. could be handled within the hook...
1771 if ( $status->isGood() ) {
1772 $status->fatal( 'hookaborted' );
1773 // Not setting $this->hookError here is a hack to allow the hook
1774 // to cause a return to the edit page without $this->hookError
1775 // being set. This is used by ConfirmEdit to display a captcha
1776 // without any error message cruft.
1777 } else {
1778 $this->hookError = $this->formatStatusErrors( $status );
1779 }
1780 // Use the existing $status->value if the hook set it
1781 if ( !$status->value ) {
1782 $status->value = self::AS_HOOK_ERROR;
1783 }
1784 return false;
1785 } elseif ( !$status->isOK() ) {
1786 # ...or the hook could be expecting us to produce an error
1787 // FIXME this sucks, we should just use the Status object throughout
1788 if ( !$status->getErrors() ) {
1789 // Provide a fallback error message if none was set
1790 $status->fatal( 'hookaborted' );
1791 }
1792 $this->hookError = $this->formatStatusErrors( $status );
1793 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1794 return false;
1795 }
1796
1797 return true;
1798 }
1799
1800 /**
1801 * Wrap status errors in an errorbox for increased visibility
1802 *
1803 * @param Status $status
1804 * @return string Wikitext
1805 */
1806 private function formatStatusErrors( Status $status ) {
1807 $errmsg = $status->getWikiText(
1808 'edit-error-short',
1809 'edit-error-long',
1810 $this->context->getLanguage()
1811 );
1812 return <<<ERROR
1813 <div class="errorbox">
1814 {$errmsg}
1815 </div>
1816 <br clear="all" />
1817 ERROR;
1818 }
1819
1820 /**
1821 * Return the summary to be used for a new section.
1822 *
1823 * @param string $sectionanchor Set to the section anchor text
1824 * @return string
1825 */
1826 private function newSectionSummary( &$sectionanchor = null ) {
1827 if ( $this->sectiontitle !== '' ) {
1828 $sectionanchor = $this->guessSectionName( $this->sectiontitle );
1829 // If no edit summary was specified, create one automatically from the section
1830 // title and have it link to the new section. Otherwise, respect the summary as
1831 // passed.
1832 if ( $this->summary === '' ) {
1833 $cleanSectionTitle = MediaWikiServices::getInstance()->getParser()
1834 ->stripSectionName( $this->sectiontitle );
1835 return $this->context->msg( 'newsectionsummary' )
1836 ->plaintextParams( $cleanSectionTitle )->inContentLanguage()->text();
1837 }
1838 } elseif ( $this->summary !== '' ) {
1839 $sectionanchor = $this->guessSectionName( $this->summary );
1840 # This is a new section, so create a link to the new section
1841 # in the revision summary.
1842 $cleanSummary = MediaWikiServices::getInstance()->getParser()
1843 ->stripSectionName( $this->summary );
1844 return $this->context->msg( 'newsectionsummary' )
1845 ->plaintextParams( $cleanSummary )->inContentLanguage()->text();
1846 }
1847 return $this->summary;
1848 }
1849
1850 /**
1851 * Attempt submission (no UI)
1852 *
1853 * @param array &$result Array to add statuses to, currently with the
1854 * possible keys:
1855 * - spam (string): Spam string from content if any spam is detected by
1856 * matchSpamRegex.
1857 * - sectionanchor (string): Section anchor for a section save.
1858 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1859 * false otherwise.
1860 * - redirect (bool): Set if doEditContent is OK. True if resulting
1861 * revision is a redirect.
1862 * @param bool $bot True if edit is being made under the bot right.
1863 *
1864 * @return Status Status object, possibly with a message, but always with
1865 * one of the AS_* constants in $status->value,
1866 *
1867 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1868 * various error display idiosyncrasies. There are also lots of cases
1869 * where error metadata is set in the object and retrieved later instead
1870 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1871 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1872 * time.
1873 */
1874 public function internalAttemptSave( &$result, $bot = false ) {
1875 $status = Status::newGood();
1876 $user = $this->context->getUser();
1877 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1878
1879 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1880 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1881 $status->fatal( 'hookaborted' );
1882 $status->value = self::AS_HOOK_ERROR;
1883 return $status;
1884 }
1885
1886 if ( $this->unicodeCheck !== self::UNICODE_CHECK ) {
1887 $status->fatal( 'unicode-support-fail' );
1888 $status->value = self::AS_UNICODE_NOT_SUPPORTED;
1889 return $status;
1890 }
1891
1892 $request = $this->context->getRequest();
1893 $spam = $request->getText( 'wpAntispam' );
1894 if ( $spam !== '' ) {
1895 wfDebugLog(
1896 'SimpleAntiSpam',
1897 $user->getName() .
1898 ' editing "' .
1899 $this->mTitle->getPrefixedText() .
1900 '" submitted bogus field "' .
1901 $spam .
1902 '"'
1903 );
1904 $status->fatal( 'spamprotectionmatch', false );
1905 $status->value = self::AS_SPAM_ERROR;
1906 return $status;
1907 }
1908
1909 try {
1910 # Construct Content object
1911 $textbox_content = $this->toEditContent( $this->textbox1 );
1912 } catch ( MWContentSerializationException $ex ) {
1913 $status->fatal(
1914 'content-failed-to-parse',
1915 $this->contentModel,
1916 $this->contentFormat,
1917 $ex->getMessage()
1918 );
1919 $status->value = self::AS_PARSE_ERROR;
1920 return $status;
1921 }
1922
1923 # Check image redirect
1924 if ( $this->mTitle->getNamespace() == NS_FILE &&
1925 $textbox_content->isRedirect() &&
1926 !$permissionManager->userHasRight( $user, 'upload' )
1927 ) {
1928 $code = $user->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1929 $status->setResult( false, $code );
1930
1931 return $status;
1932 }
1933
1934 # Check for spam
1935 $match = self::matchSummarySpamRegex( $this->summary );
1936 if ( $match === false && $this->section == 'new' ) {
1937 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1938 # regular summaries, it is added to the actual wikitext.
1939 if ( $this->sectiontitle !== '' ) {
1940 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1941 $match = self::matchSpamRegex( $this->sectiontitle );
1942 } else {
1943 # This branch is taken when the "Add Topic" user interface is used, or the API
1944 # is used with the 'summary' parameter.
1945 $match = self::matchSpamRegex( $this->summary );
1946 }
1947 }
1948 if ( $match === false ) {
1949 $match = self::matchSpamRegex( $this->textbox1 );
1950 }
1951 if ( $match !== false ) {
1952 $result['spam'] = $match;
1953 $ip = $request->getIP();
1954 $pdbk = $this->mTitle->getPrefixedDBkey();
1955 $match = str_replace( "\n", '', $match );
1956 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1957 $status->fatal( 'spamprotectionmatch', $match );
1958 $status->value = self::AS_SPAM_ERROR;
1959 return $status;
1960 }
1961 if ( !Hooks::run(
1962 'EditFilter',
1963 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1964 ) {
1965 # Error messages etc. could be handled within the hook...
1966 $status->fatal( 'hookaborted' );
1967 $status->value = self::AS_HOOK_ERROR;
1968 return $status;
1969 } elseif ( $this->hookError != '' ) {
1970 # ...or the hook could be expecting us to produce an error
1971 $status->fatal( 'hookaborted' );
1972 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1973 return $status;
1974 }
1975
1976 if ( $permissionManager->isBlockedFrom( $user, $this->mTitle ) ) {
1977 // Auto-block user's IP if the account was "hard" blocked
1978 if ( !wfReadOnly() ) {
1979 $user->spreadAnyEditBlock();
1980 }
1981 # Check block state against master, thus 'false'.
1982 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1983 return $status;
1984 }
1985
1986 $this->contentLength = strlen( $this->textbox1 );
1987 $config = $this->context->getConfig();
1988 $maxArticleSize = $config->get( 'MaxArticleSize' );
1989 if ( $this->contentLength > $maxArticleSize * 1024 ) {
1990 // Error will be displayed by showEditForm()
1991 $this->tooBig = true;
1992 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1993 return $status;
1994 }
1995
1996 if ( !$permissionManager->userHasRight( $user, 'edit' ) ) {
1997 if ( $user->isAnon() ) {
1998 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1999 return $status;
2000 } else {
2001 $status->fatal( 'readonlytext' );
2002 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
2003 return $status;
2004 }
2005 }
2006
2007 $changingContentModel = false;
2008 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
2009 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
2010 $status->fatal( 'editpage-cannot-use-custom-model' );
2011 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
2012 return $status;
2013 } elseif ( !$permissionManager->userHasRight( $user, 'editcontentmodel' ) ) {
2014 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
2015 return $status;
2016 }
2017 // Make sure the user can edit the page under the new content model too
2018 $titleWithNewContentModel = clone $this->mTitle;
2019 $titleWithNewContentModel->setContentModel( $this->contentModel );
2020
2021 $canEditModel = $permissionManager->userCan(
2022 'editcontentmodel',
2023 $user,
2024 $titleWithNewContentModel
2025 );
2026
2027 if (
2028 !$canEditModel
2029 || !$permissionManager->userCan( 'edit', $user, $titleWithNewContentModel )
2030 ) {
2031 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
2032
2033 return $status;
2034 }
2035
2036 $changingContentModel = true;
2037 $oldContentModel = $this->mTitle->getContentModel();
2038 }
2039
2040 if ( $this->changeTags ) {
2041 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
2042 $this->changeTags, $user );
2043 if ( !$changeTagsStatus->isOK() ) {
2044 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
2045 return $changeTagsStatus;
2046 }
2047 }
2048
2049 if ( wfReadOnly() ) {
2050 $status->fatal( 'readonlytext' );
2051 $status->value = self::AS_READ_ONLY_PAGE;
2052 return $status;
2053 }
2054 if ( $user->pingLimiter() || $user->pingLimiter( 'linkpurge', 0 )
2055 || ( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
2056 ) {
2057 $status->fatal( 'actionthrottledtext' );
2058 $status->value = self::AS_RATE_LIMITED;
2059 return $status;
2060 }
2061
2062 # If the article has been deleted while editing, don't save it without
2063 # confirmation
2064 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
2065 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
2066 return $status;
2067 }
2068
2069 # Load the page data from the master. If anything changes in the meantime,
2070 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
2071 $this->page->loadPageData( 'fromdbmaster' );
2072 $new = !$this->page->exists();
2073
2074 if ( $new ) {
2075 // Late check for create permission, just in case *PARANOIA*
2076 if ( !$permissionManager->userCan( 'create', $user, $this->mTitle ) ) {
2077 $status->fatal( 'nocreatetext' );
2078 $status->value = self::AS_NO_CREATE_PERMISSION;
2079 wfDebug( __METHOD__ . ": no create permission\n" );
2080 return $status;
2081 }
2082
2083 // Don't save a new page if it's blank or if it's a MediaWiki:
2084 // message with content equivalent to default (allow empty pages
2085 // in this case to disable messages, see T52124)
2086 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2087 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
2088 $defaultText = $defaultMessageText;
2089 } else {
2090 $defaultText = '';
2091 }
2092
2093 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
2094 $this->blankArticle = true;
2095 $status->fatal( 'blankarticle' );
2096 $status->setResult( false, self::AS_BLANK_ARTICLE );
2097 return $status;
2098 }
2099
2100 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2101 return $status;
2102 }
2103
2104 $content = $textbox_content;
2105
2106 $result['sectionanchor'] = '';
2107 if ( $this->section == 'new' ) {
2108 if ( $this->sectiontitle !== '' ) {
2109 // Insert the section title above the content.
2110 $content = $content->addSectionHeader( $this->sectiontitle );
2111 } elseif ( $this->summary !== '' ) {
2112 // Insert the section title above the content.
2113 $content = $content->addSectionHeader( $this->summary );
2114 }
2115 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
2116 }
2117
2118 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
2119
2120 } else { # not $new
2121
2122 # Article exists. Check for edit conflict.
2123
2124 $this->page->clear(); # Force reload of dates, etc.
2125 $timestamp = $this->page->getTimestamp();
2126 $latest = $this->page->getLatest();
2127
2128 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2129
2130 // An edit conflict is detected if the current revision is different from the
2131 // revision that was current when editing was initiated on the client.
2132 // This is checked based on the timestamp and revision ID.
2133 // TODO: the timestamp based check can probably go away now.
2134 if ( $timestamp != $this->edittime
2135 || ( $this->editRevId !== null && $this->editRevId != $latest )
2136 ) {
2137 $this->isConflict = true;
2138 if ( $this->section == 'new' ) {
2139 if ( $this->page->getUserText() == $user->getName() &&
2140 $this->page->getComment() == $this->newSectionSummary()
2141 ) {
2142 // Probably a duplicate submission of a new comment.
2143 // This can happen when CDN resends a request after
2144 // a timeout but the first one actually went through.
2145 wfDebug( __METHOD__
2146 . ": duplicate new section submission; trigger edit conflict!\n" );
2147 } else {
2148 // New comment; suppress conflict.
2149 $this->isConflict = false;
2150 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
2151 }
2152 } elseif ( $this->section == ''
2153 && Revision::userWasLastToEdit(
2154 DB_MASTER, $this->mTitle->getArticleID(),
2155 $user->getId(), $this->edittime
2156 )
2157 ) {
2158 # Suppress edit conflict with self, except for section edits where merging is required.
2159 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2160 $this->isConflict = false;
2161 }
2162 }
2163
2164 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2165 if ( $this->sectiontitle !== '' ) {
2166 $sectionTitle = $this->sectiontitle;
2167 } else {
2168 $sectionTitle = $this->summary;
2169 }
2170
2171 $content = null;
2172
2173 if ( $this->isConflict ) {
2174 wfDebug( __METHOD__
2175 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2176 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2177 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2178 // ...or disable section editing for non-current revisions (not exposed anyway).
2179 if ( $this->editRevId !== null ) {
2180 $content = $this->page->replaceSectionAtRev(
2181 $this->section,
2182 $textbox_content,
2183 $sectionTitle,
2184 $this->editRevId
2185 );
2186 } else {
2187 $content = $this->page->replaceSectionContent(
2188 $this->section,
2189 $textbox_content,
2190 $sectionTitle,
2191 $this->edittime
2192 );
2193 }
2194 } else {
2195 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2196 $content = $this->page->replaceSectionContent(
2197 $this->section,
2198 $textbox_content,
2199 $sectionTitle
2200 );
2201 }
2202
2203 if ( is_null( $content ) ) {
2204 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2205 $this->isConflict = true;
2206 $content = $textbox_content; // do not try to merge here!
2207 } elseif ( $this->isConflict ) {
2208 # Attempt merge
2209 if ( $this->mergeChangesIntoContent( $content ) ) {
2210 // Successful merge! Maybe we should tell the user the good news?
2211 $this->isConflict = false;
2212 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2213 } else {
2214 $this->section = '';
2215 $this->textbox1 = ContentHandler::getContentText( $content );
2216 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2217 }
2218 }
2219
2220 if ( $this->isConflict ) {
2221 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2222 return $status;
2223 }
2224
2225 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2226 return $status;
2227 }
2228
2229 if ( $this->section == 'new' ) {
2230 // Handle the user preference to force summaries here
2231 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2232 $this->missingSummary = true;
2233 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2234 $status->value = self::AS_SUMMARY_NEEDED;
2235 return $status;
2236 }
2237
2238 // Do not allow the user to post an empty comment
2239 if ( $this->textbox1 == '' ) {
2240 $this->missingComment = true;
2241 $status->fatal( 'missingcommenttext' );
2242 $status->value = self::AS_TEXTBOX_EMPTY;
2243 return $status;
2244 }
2245 } elseif ( !$this->allowBlankSummary
2246 && !$content->equals( $this->getOriginalContent( $user ) )
2247 && !$content->isRedirect()
2248 && md5( $this->summary ) == $this->autoSumm
2249 ) {
2250 $this->missingSummary = true;
2251 $status->fatal( 'missingsummary' );
2252 $status->value = self::AS_SUMMARY_NEEDED;
2253 return $status;
2254 }
2255
2256 # All's well
2257 $sectionanchor = '';
2258 if ( $this->section == 'new' ) {
2259 $this->summary = $this->newSectionSummary( $sectionanchor );
2260 } elseif ( $this->section != '' ) {
2261 # Try to get a section anchor from the section source, redirect
2262 # to edited section if header found.
2263 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2264 # for duplicate heading checking and maybe parsing.
2265 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2266 # We can't deal with anchors, includes, html etc in the header for now,
2267 # headline would need to be parsed to improve this.
2268 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2269 $sectionanchor = $this->guessSectionName( $matches[2] );
2270 }
2271 }
2272 $result['sectionanchor'] = $sectionanchor;
2273
2274 // Save errors may fall down to the edit form, but we've now
2275 // merged the section into full text. Clear the section field
2276 // so that later submission of conflict forms won't try to
2277 // replace that into a duplicated mess.
2278 $this->textbox1 = $this->toEditText( $content );
2279 $this->section = '';
2280
2281 $status->value = self::AS_SUCCESS_UPDATE;
2282 }
2283
2284 if ( !$this->allowSelfRedirect
2285 && $content->isRedirect()
2286 && $content->getRedirectTarget()->equals( $this->getTitle() )
2287 ) {
2288 // If the page already redirects to itself, don't warn.
2289 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2290 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2291 $this->selfRedirect = true;
2292 $status->fatal( 'selfredirect' );
2293 $status->value = self::AS_SELF_REDIRECT;
2294 return $status;
2295 }
2296 }
2297
2298 // Check for length errors again now that the section is merged in
2299 $this->contentLength = strlen( $this->toEditText( $content ) );
2300 if ( $this->contentLength > $maxArticleSize * 1024 ) {
2301 $this->tooBig = true;
2302 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2303 return $status;
2304 }
2305
2306 $flags = EDIT_AUTOSUMMARY |
2307 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2308 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2309 ( $bot ? EDIT_FORCE_BOT : 0 );
2310
2311 $doEditStatus = $this->page->doEditContent(
2312 $content,
2313 $this->summary,
2314 $flags,
2315 false,
2316 $user,
2317 $content->getDefaultFormat(),
2318 $this->changeTags,
2319 $this->undidRev
2320 );
2321
2322 if ( !$doEditStatus->isOK() ) {
2323 // Failure from doEdit()
2324 // Show the edit conflict page for certain recognized errors from doEdit(),
2325 // but don't show it for errors from extension hooks
2326 $errors = $doEditStatus->getErrorsArray();
2327 if ( in_array( $errors[0][0],
2328 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2329 ) {
2330 $this->isConflict = true;
2331 // Destroys data doEdit() put in $status->value but who cares
2332 $doEditStatus->value = self::AS_END;
2333 }
2334 return $doEditStatus;
2335 }
2336
2337 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2338 if ( $result['nullEdit'] ) {
2339 // We don't know if it was a null edit until now, so increment here
2340 $user->pingLimiter( 'linkpurge' );
2341 }
2342 $result['redirect'] = $content->isRedirect();
2343
2344 $this->updateWatchlist();
2345
2346 // If the content model changed, add a log entry
2347 if ( $changingContentModel ) {
2348 $this->addContentModelChangeLogEntry(
2349 $user,
2350 $new ? false : $oldContentModel,
2351 $this->contentModel,
2352 $this->summary
2353 );
2354 }
2355
2356 return $status;
2357 }
2358
2359 /**
2360 * @param User $user
2361 * @param string|false $oldModel false if the page is being newly created
2362 * @param string $newModel
2363 * @param string $reason
2364 */
2365 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2366 $new = $oldModel === false;
2367 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2368 $log->setPerformer( $user );
2369 $log->setTarget( $this->mTitle );
2370 $log->setComment( $reason );
2371 $log->setParameters( [
2372 '4::oldmodel' => $oldModel,
2373 '5::newmodel' => $newModel
2374 ] );
2375 $logid = $log->insert();
2376 $log->publish( $logid );
2377 }
2378
2379 /**
2380 * Register the change of watch status
2381 */
2382 protected function updateWatchlist() {
2383 $user = $this->context->getUser();
2384 if ( !$user->isLoggedIn() ) {
2385 return;
2386 }
2387
2388 $title = $this->mTitle;
2389 $watch = $this->watchthis;
2390 // Do this in its own transaction to reduce contention...
2391 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2392 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2393 return; // nothing to change
2394 }
2395 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2396 } );
2397 }
2398
2399 /**
2400 * Attempts to do 3-way merge of edit content with a base revision
2401 * and current content, in case of edit conflict, in whichever way appropriate
2402 * for the content type.
2403 *
2404 * @since 1.21
2405 *
2406 * @param Content $editContent
2407 *
2408 * @return bool
2409 */
2410 private function mergeChangesIntoContent( &$editContent ) {
2411 $db = wfGetDB( DB_MASTER );
2412
2413 // This is the revision that was current at the time editing was initiated on the client,
2414 // even if the edit was based on an old revision.
2415 $baseRevision = $this->getBaseRevision();
2416 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2417
2418 if ( is_null( $baseContent ) ) {
2419 return false;
2420 }
2421
2422 // The current state, we want to merge updates into it
2423 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2424 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2425
2426 if ( is_null( $currentContent ) ) {
2427 return false;
2428 }
2429
2430 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2431
2432 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2433
2434 if ( $result ) {
2435 $editContent = $result;
2436 // Update parentRevId to what we just merged.
2437 $this->parentRevId = $currentRevision->getId();
2438 return true;
2439 }
2440
2441 return false;
2442 }
2443
2444 /**
2445 * Returns the revision that was current at the time editing was initiated on the client,
2446 * even if the edit was based on an old revision.
2447 *
2448 * @warning this method is very poorly named. If the user opened the form with ?oldid=X,
2449 * one might think of X as the "base revision", which is NOT what this returns,
2450 * see oldid for that. One might further assume that this corresponds to the $baseRevId
2451 * parameter of WikiPage::doEditContent, which is not the case either.
2452 * getExpectedParentRevision() would perhaps be a better name.
2453 *
2454 * @return Revision|null Current version when editing was initiated on the client
2455 */
2456 public function getBaseRevision() {
2457 if ( !$this->mBaseRevision ) {
2458 $db = wfGetDB( DB_MASTER );
2459 $this->mBaseRevision = $this->editRevId
2460 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2461 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2462 }
2463 return $this->mBaseRevision;
2464 }
2465
2466 /**
2467 * Check given input text against $wgSpamRegex, and return the text of the first match.
2468 *
2469 * @param string $text
2470 *
2471 * @return string|bool Matching string or false
2472 */
2473 public static function matchSpamRegex( $text ) {
2474 global $wgSpamRegex;
2475 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2476 $regexes = (array)$wgSpamRegex;
2477 return self::matchSpamRegexInternal( $text, $regexes );
2478 }
2479
2480 /**
2481 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2482 *
2483 * @param string $text
2484 *
2485 * @return string|bool Matching string or false
2486 */
2487 public static function matchSummarySpamRegex( $text ) {
2488 global $wgSummarySpamRegex;
2489 $regexes = (array)$wgSummarySpamRegex;
2490 return self::matchSpamRegexInternal( $text, $regexes );
2491 }
2492
2493 /**
2494 * @param string $text
2495 * @param array $regexes
2496 * @return bool|string
2497 */
2498 protected static function matchSpamRegexInternal( $text, $regexes ) {
2499 foreach ( $regexes as $regex ) {
2500 $matches = [];
2501 if ( preg_match( $regex, $text, $matches ) ) {
2502 return $matches[0];
2503 }
2504 }
2505 return false;
2506 }
2507
2508 public function setHeaders() {
2509 $out = $this->context->getOutput();
2510
2511 $out->addModules( 'mediawiki.action.edit' );
2512 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2513 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2514
2515 $user = $this->context->getUser();
2516
2517 if ( $user->getOption( 'uselivepreview' ) ) {
2518 $out->addModules( 'mediawiki.action.edit.preview' );
2519 }
2520
2521 if ( $user->getOption( 'useeditwarning' ) ) {
2522 $out->addModules( 'mediawiki.action.edit.editWarning' );
2523 }
2524
2525 # Enabled article-related sidebar, toplinks, etc.
2526 $out->setArticleRelated( true );
2527
2528 $contextTitle = $this->getContextTitle();
2529 if ( $this->isConflict ) {
2530 $msg = 'editconflict';
2531 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2532 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2533 } else {
2534 $msg = $contextTitle->exists()
2535 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2536 && $contextTitle->getDefaultMessageText() !== false
2537 )
2538 ? 'editing'
2539 : 'creating';
2540 }
2541
2542 # Use the title defined by DISPLAYTITLE magic word when present
2543 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2544 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2545 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2546 if ( $displayTitle === false ) {
2547 $displayTitle = $contextTitle->getPrefixedText();
2548 } else {
2549 $out->setDisplayTitle( $displayTitle );
2550 }
2551 $out->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2552
2553 $config = $this->context->getConfig();
2554
2555 # Transmit the name of the message to JavaScript for live preview
2556 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2557 $out->addJsConfigVars( [
2558 'wgEditMessage' => $msg,
2559 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2560 ] );
2561
2562 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2563 // editors, etc.
2564 $out->addJsConfigVars(
2565 'wgEditSubmitButtonLabelPublish',
2566 $config->get( 'EditSubmitButtonLabelPublish' )
2567 );
2568 }
2569
2570 /**
2571 * Show all applicable editing introductions
2572 */
2573 protected function showIntro() {
2574 if ( $this->suppressIntro ) {
2575 return;
2576 }
2577
2578 $out = $this->context->getOutput();
2579 $namespace = $this->mTitle->getNamespace();
2580
2581 if ( $namespace == NS_MEDIAWIKI ) {
2582 # Show a warning if editing an interface message
2583 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2584 # If this is a default message (but not css, json, or js),
2585 # show a hint that it is translatable on translatewiki.net
2586 if (
2587 !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2588 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JSON )
2589 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2590 ) {
2591 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2592 if ( $defaultMessageText !== false ) {
2593 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2594 'translateinterface' );
2595 }
2596 }
2597 } elseif ( $namespace == NS_FILE ) {
2598 # Show a hint to shared repo
2599 $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile( $this->mTitle );
2600 if ( $file && !$file->isLocal() ) {
2601 $descUrl = $file->getDescriptionUrl();
2602 # there must be a description url to show a hint to shared repo
2603 if ( $descUrl ) {
2604 if ( !$this->mTitle->exists() ) {
2605 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2606 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2607 ] );
2608 } else {
2609 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2610 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2611 ] );
2612 }
2613 }
2614 }
2615 }
2616
2617 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2618 # Show log extract when the user is currently blocked
2619 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2620 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2621 $user = User::newFromName( $username, false /* allow IP users */ );
2622 $ip = User::isIP( $username );
2623 $block = DatabaseBlock::newFromTarget( $user, $user );
2624 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2625 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2626 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2627 } elseif (
2628 !is_null( $block ) &&
2629 $block->getType() != DatabaseBlock::TYPE_AUTO &&
2630 ( $block->isSitewide() || $user->isBlockedFrom( $this->mTitle ) )
2631 ) {
2632 // Show log extract if the user is sitewide blocked or is partially
2633 // blocked and not allowed to edit their user page or user talk page
2634 LogEventsList::showLogExtract(
2635 $out,
2636 'block',
2637 MediaWikiServices::getInstance()->getNamespaceInfo()->
2638 getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2639 '',
2640 [
2641 'lim' => 1,
2642 'showIfEmpty' => false,
2643 'msgKey' => [
2644 'blocked-notice-logextract',
2645 $user->getName() # Support GENDER in notice
2646 ]
2647 ]
2648 );
2649 }
2650 }
2651 # Try to add a custom edit intro, or use the standard one if this is not possible.
2652 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2653 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2654 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2655 ) );
2656 if ( $this->context->getUser()->isLoggedIn() ) {
2657 $out->wrapWikiMsg(
2658 // Suppress the external link icon, consider the help url an internal one
2659 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2660 [
2661 'newarticletext',
2662 $helpLink
2663 ]
2664 );
2665 } else {
2666 $out->wrapWikiMsg(
2667 // Suppress the external link icon, consider the help url an internal one
2668 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2669 [
2670 'newarticletextanon',
2671 $helpLink
2672 ]
2673 );
2674 }
2675 }
2676 # Give a notice if the user is editing a deleted/moved page...
2677 if ( !$this->mTitle->exists() ) {
2678 $dbr = wfGetDB( DB_REPLICA );
2679
2680 LogEventsList::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle,
2681 '',
2682 [
2683 'lim' => 10,
2684 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2685 'showIfEmpty' => false,
2686 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2687 ]
2688 );
2689 }
2690 }
2691
2692 /**
2693 * Attempt to show a custom editing introduction, if supplied
2694 *
2695 * @return bool
2696 */
2697 protected function showCustomIntro() {
2698 if ( $this->editintro ) {
2699 $title = Title::newFromText( $this->editintro );
2700 if ( $this->isPageExistingAndViewable( $title, $this->context->getUser() ) ) {
2701 // Added using template syntax, to take <noinclude>'s into account.
2702 $this->context->getOutput()->addWikiTextAsContent(
2703 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2704 /*linestart*/true,
2705 $this->mTitle
2706 );
2707 return true;
2708 }
2709 }
2710 return false;
2711 }
2712
2713 /**
2714 * Gets an editable textual representation of $content.
2715 * The textual representation can be turned by into a Content object by the
2716 * toEditContent() method.
2717 *
2718 * If $content is null or false or a string, $content is returned unchanged.
2719 *
2720 * If the given Content object is not of a type that can be edited using
2721 * the text base EditPage, an exception will be raised. Set
2722 * $this->allowNonTextContent to true to allow editing of non-textual
2723 * content.
2724 *
2725 * @param Content|null|bool|string $content
2726 * @return string The editable text form of the content.
2727 *
2728 * @throws MWException If $content is not an instance of TextContent and
2729 * $this->allowNonTextContent is not true.
2730 */
2731 protected function toEditText( $content ) {
2732 if ( $content === null || $content === false || is_string( $content ) ) {
2733 return $content;
2734 }
2735
2736 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2737 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2738 }
2739
2740 return $content->serialize( $this->contentFormat );
2741 }
2742
2743 /**
2744 * Turns the given text into a Content object by unserializing it.
2745 *
2746 * If the resulting Content object is not of a type that can be edited using
2747 * the text base EditPage, an exception will be raised. Set
2748 * $this->allowNonTextContent to true to allow editing of non-textual
2749 * content.
2750 *
2751 * @param string|null|bool $text Text to unserialize
2752 * @return Content|bool|null The content object created from $text. If $text was false
2753 * or null, then false or null will be returned instead.
2754 *
2755 * @throws MWException If unserializing the text results in a Content
2756 * object that is not an instance of TextContent and
2757 * $this->allowNonTextContent is not true.
2758 */
2759 protected function toEditContent( $text ) {
2760 if ( $text === false || $text === null ) {
2761 return $text;
2762 }
2763
2764 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2765 $this->contentModel, $this->contentFormat );
2766
2767 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2768 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2769 }
2770
2771 return $content;
2772 }
2773
2774 /**
2775 * Send the edit form and related headers to OutputPage
2776 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2777 * during form output near the top, for captchas and the like.
2778 *
2779 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2780 * use the EditPage::showEditForm:fields hook instead.
2781 */
2782 public function showEditForm( $formCallback = null ) {
2783 # need to parse the preview early so that we know which templates are used,
2784 # otherwise users with "show preview after edit box" will get a blank list
2785 # we parse this near the beginning so that setHeaders can do the title
2786 # setting work instead of leaving it in getPreviewText
2787 $previewOutput = '';
2788 if ( $this->formtype == 'preview' ) {
2789 $previewOutput = $this->getPreviewText();
2790 }
2791
2792 $out = $this->context->getOutput();
2793
2794 // Avoid PHP 7.1 warning of passing $this by reference
2795 $editPage = $this;
2796 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2797
2798 $this->setHeaders();
2799
2800 $this->addTalkPageText();
2801 $this->addEditNotices();
2802
2803 if ( !$this->isConflict &&
2804 $this->section != '' &&
2805 !$this->isSectionEditSupported() ) {
2806 // We use $this->section to much before this and getVal('wgSection') directly in other places
2807 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2808 // Someone is welcome to try refactoring though
2809 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2810 return;
2811 }
2812
2813 $this->showHeader();
2814
2815 $out->addHTML( $this->editFormPageTop );
2816
2817 $user = $this->context->getUser();
2818 if ( $user->getOption( 'previewontop' ) ) {
2819 $this->displayPreviewArea( $previewOutput, true );
2820 }
2821
2822 $out->addHTML( $this->editFormTextTop );
2823
2824 if ( $this->wasDeletedSinceLastEdit() && $this->formtype !== 'save' ) {
2825 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2826 'deletedwhileediting' );
2827 }
2828
2829 // @todo add EditForm plugin interface and use it here!
2830 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2831 $out->addHTML( Html::openElement(
2832 'form',
2833 [
2834 'class' => 'mw-editform',
2835 'id' => self::EDITFORM_ID,
2836 'name' => self::EDITFORM_ID,
2837 'method' => 'post',
2838 'action' => $this->getActionURL( $this->getContextTitle() ),
2839 'enctype' => 'multipart/form-data'
2840 ]
2841 ) );
2842
2843 if ( is_callable( $formCallback ) ) {
2844 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2845 call_user_func_array( $formCallback, [ &$out ] );
2846 }
2847
2848 // Add a check for Unicode support
2849 $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
2850
2851 // Add an empty field to trip up spambots
2852 $out->addHTML(
2853 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2854 . Html::rawElement(
2855 'label',
2856 [ 'for' => 'wpAntispam' ],
2857 $this->context->msg( 'simpleantispam-label' )->parse()
2858 )
2859 . Xml::element(
2860 'input',
2861 [
2862 'type' => 'text',
2863 'name' => 'wpAntispam',
2864 'id' => 'wpAntispam',
2865 'value' => ''
2866 ]
2867 )
2868 . Xml::closeElement( 'div' )
2869 );
2870
2871 // Avoid PHP 7.1 warning of passing $this by reference
2872 $editPage = $this;
2873 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2874
2875 // Put these up at the top to ensure they aren't lost on early form submission
2876 $this->showFormBeforeText();
2877
2878 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2879 $username = $this->lastDelete->user_name;
2880 $comment = CommentStore::getStore()
2881 ->getComment( 'log_comment', $this->lastDelete )->text;
2882
2883 // It is better to not parse the comment at all than to have templates expanded in the middle
2884 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2885 $key = $comment === ''
2886 ? 'confirmrecreate-noreason'
2887 : 'confirmrecreate';
2888 $out->addHTML(
2889 '<div class="mw-confirm-recreate">' .
2890 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2891 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2892 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2893 ) .
2894 '</div>'
2895 );
2896 }
2897
2898 # When the summary is hidden, also hide them on preview/show changes
2899 if ( $this->nosummary ) {
2900 $out->addHTML( Html::hidden( 'nosummary', true ) );
2901 }
2902
2903 # If a blank edit summary was previously provided, and the appropriate
2904 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2905 # user being bounced back more than once in the event that a summary
2906 # is not required.
2907 # ####
2908 # For a bit more sophisticated detection of blank summaries, hash the
2909 # automatic one and pass that in the hidden field wpAutoSummary.
2910 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2911 $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2912 }
2913
2914 if ( $this->undidRev ) {
2915 $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2916 }
2917
2918 if ( $this->selfRedirect ) {
2919 $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2920 }
2921
2922 if ( $this->hasPresetSummary ) {
2923 // If a summary has been preset using &summary= we don't want to prompt for
2924 // a different summary. Only prompt for a summary if the summary is blanked.
2925 // (T19416)
2926 $this->autoSumm = md5( '' );
2927 }
2928
2929 $autosumm = $this->autoSumm !== '' ? $this->autoSumm : md5( $this->summary );
2930 $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2931
2932 $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2933 $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2934
2935 $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2936 $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
2937
2938 $out->enableOOUI();
2939
2940 if ( $this->section == 'new' ) {
2941 $this->showSummaryInput( true, $this->summary );
2942 $out->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2943 }
2944
2945 $out->addHTML( $this->editFormTextBeforeContent );
2946 if ( $this->isConflict ) {
2947 // In an edit conflict, we turn textbox2 into the user's text,
2948 // and textbox1 into the stored version
2949 $this->textbox2 = $this->textbox1;
2950
2951 $content = $this->getCurrentContent();
2952 $this->textbox1 = $this->toEditText( $content );
2953
2954 $editConflictHelper = $this->getEditConflictHelper();
2955 $editConflictHelper->setTextboxes( $this->textbox2, $this->textbox1 );
2956 $editConflictHelper->setContentModel( $this->contentModel );
2957 $editConflictHelper->setContentFormat( $this->contentFormat );
2958 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2959 }
2960
2961 if ( !$this->mTitle->isUserConfigPage() ) {
2962 $out->addHTML( self::getEditToolbar() );
2963 }
2964
2965 if ( $this->blankArticle ) {
2966 $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2967 }
2968
2969 if ( $this->isConflict ) {
2970 // In an edit conflict bypass the overridable content form method
2971 // and fallback to the raw wpTextbox1 since editconflicts can't be
2972 // resolved between page source edits and custom ui edits using the
2973 // custom edit ui.
2974 $conflictTextBoxAttribs = [];
2975 if ( $this->wasDeletedSinceLastEdit() ) {
2976 $conflictTextBoxAttribs['style'] = 'display:none;';
2977 } elseif ( $this->isOldRev ) {
2978 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2979 }
2980
2981 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2982 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2983 } else {
2984 $this->showContentForm();
2985 }
2986
2987 $out->addHTML( $this->editFormTextAfterContent );
2988
2989 $this->showStandardInputs();
2990
2991 $this->showFormAfterText();
2992
2993 $this->showTosSummary();
2994
2995 $this->showEditTools();
2996
2997 $out->addHTML( $this->editFormTextAfterTools . "\n" );
2998
2999 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
3000
3001 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
3002 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
3003
3004 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
3005 self::getPreviewLimitReport( $this->mParserOutput ) ) );
3006
3007 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3008
3009 if ( $this->isConflict ) {
3010 try {
3011 $this->showConflict();
3012 } catch ( MWContentSerializationException $ex ) {
3013 // this can't really happen, but be nice if it does.
3014 $msg = $this->context->msg(
3015 'content-failed-to-parse',
3016 $this->contentModel,
3017 $this->contentFormat,
3018 $ex->getMessage()
3019 );
3020 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3021 }
3022 }
3023
3024 // Set a hidden field so JS knows what edit form mode we are in
3025 if ( $this->isConflict ) {
3026 $mode = 'conflict';
3027 } elseif ( $this->preview ) {
3028 $mode = 'preview';
3029 } elseif ( $this->diff ) {
3030 $mode = 'diff';
3031 } else {
3032 $mode = 'text';
3033 }
3034 $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3035
3036 // Marker for detecting truncated form data. This must be the last
3037 // parameter sent in order to be of use, so do not move me.
3038 $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
3039 $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
3040
3041 if ( !$user->getOption( 'previewontop' ) ) {
3042 $this->displayPreviewArea( $previewOutput, false );
3043 }
3044 }
3045
3046 /**
3047 * Wrapper around TemplatesOnThisPageFormatter to make
3048 * a "templates on this page" list.
3049 *
3050 * @param Title[] $templates
3051 * @return string HTML
3052 */
3053 public function makeTemplatesOnThisPageList( array $templates ) {
3054 $templateListFormatter = new TemplatesOnThisPageFormatter(
3055 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
3056 );
3057
3058 // preview if preview, else section if section, else false
3059 $type = false;
3060 if ( $this->preview ) {
3061 $type = 'preview';
3062 } elseif ( $this->section != '' ) {
3063 $type = 'section';
3064 }
3065
3066 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3067 $templateListFormatter->format( $templates, $type )
3068 );
3069 }
3070
3071 /**
3072 * Extract the section title from current section text, if any.
3073 *
3074 * @param string $text
3075 * @return string|bool String or false
3076 */
3077 public static function extractSectionTitle( $text ) {
3078 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
3079 if ( !empty( $matches[2] ) ) {
3080 return MediaWikiServices::getInstance()->getParser()
3081 ->stripSectionName( trim( $matches[2] ) );
3082 } else {
3083 return false;
3084 }
3085 }
3086
3087 protected function showHeader() {
3088 $out = $this->context->getOutput();
3089 $user = $this->context->getUser();
3090 if ( $this->isConflict ) {
3091 $this->addExplainConflictHeader( $out );
3092 $this->editRevId = $this->page->getLatest();
3093 } else {
3094 if ( $this->section != '' && $this->section != 'new' && !$this->summary &&
3095 !$this->preview && !$this->diff
3096 ) {
3097 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
3098 if ( $sectionTitle !== false ) {
3099 $this->summary = "/* $sectionTitle */ ";
3100 }
3101 }
3102
3103 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
3104
3105 if ( $this->missingComment ) {
3106 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3107 }
3108
3109 if ( $this->missingSummary && $this->section != 'new' ) {
3110 $out->wrapWikiMsg(
3111 "<div id='mw-missingsummary'>\n$1\n</div>",
3112 [ 'missingsummary', $buttonLabel ]
3113 );
3114 }
3115
3116 if ( $this->missingSummary && $this->section == 'new' ) {
3117 $out->wrapWikiMsg(
3118 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3119 [ 'missingcommentheader', $buttonLabel ]
3120 );
3121 }
3122
3123 if ( $this->blankArticle ) {
3124 $out->wrapWikiMsg(
3125 "<div id='mw-blankarticle'>\n$1\n</div>",
3126 [ 'blankarticle', $buttonLabel ]
3127 );
3128 }
3129
3130 if ( $this->selfRedirect ) {
3131 $out->wrapWikiMsg(
3132 "<div id='mw-selfredirect'>\n$1\n</div>",
3133 [ 'selfredirect', $buttonLabel ]
3134 );
3135 }
3136
3137 if ( $this->hookError !== '' ) {
3138 $out->addWikiTextAsInterface( $this->hookError );
3139 }
3140
3141 if ( $this->section != 'new' ) {
3142 $revision = $this->mArticle->getRevisionFetched();
3143 if ( $revision ) {
3144 // Let sysop know that this will make private content public if saved
3145
3146 if ( !$revision->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
3147 $out->wrapWikiMsg(
3148 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3149 'rev-deleted-text-permission'
3150 );
3151 } elseif ( $revision->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
3152 $out->wrapWikiMsg(
3153 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3154 'rev-deleted-text-view'
3155 );
3156 }
3157
3158 if ( !$revision->isCurrent() ) {
3159 $this->mArticle->setOldSubtitle( $revision->getId() );
3160 $out->wrapWikiMsg(
3161 Html::warningBox( "\n$1\n" ),
3162 'editingold'
3163 );
3164 $this->isOldRev = true;
3165 }
3166 } elseif ( $this->mTitle->exists() ) {
3167 // Something went wrong
3168
3169 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3170 [ 'missing-revision', $this->oldid ] );
3171 }
3172 }
3173 }
3174
3175 if ( wfReadOnly() ) {
3176 $out->wrapWikiMsg(
3177 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3178 [ 'readonlywarning', wfReadOnlyReason() ]
3179 );
3180 } elseif ( $user->isAnon() ) {
3181 if ( $this->formtype != 'preview' ) {
3182 $returntoquery = array_diff_key(
3183 $this->context->getRequest()->getValues(),
3184 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
3185 );
3186 $out->wrapWikiMsg(
3187 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3188 [ 'anoneditwarning',
3189 // Log-in link
3190 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
3191 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3192 'returntoquery' => wfArrayToCgi( $returntoquery ),
3193 ] ),
3194 // Sign-up link
3195 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
3196 'returnto' => $this->getTitle()->getPrefixedDBkey(),
3197 'returntoquery' => wfArrayToCgi( $returntoquery ),
3198 ] )
3199 ]
3200 );
3201 } else {
3202 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3203 'anonpreviewwarning'
3204 );
3205 }
3206 } elseif ( $this->mTitle->isUserConfigPage() ) {
3207 # Check the skin exists
3208 if ( $this->isWrongCaseUserConfigPage() ) {
3209 $out->wrapWikiMsg(
3210 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3211 [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
3212 );
3213 }
3214 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3215 $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
3216 $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
3217 $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
3218
3219 $warning = $isUserCssConfig
3220 ? 'usercssispublic'
3221 : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
3222
3223 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3224
3225 if ( $this->formtype !== 'preview' ) {
3226 $config = $this->context->getConfig();
3227 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3228 $out->wrapWikiMsg(
3229 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3230 [ 'usercssyoucanpreview' ]
3231 );
3232 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3233 $out->wrapWikiMsg(
3234 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3235 [ 'userjsonyoucanpreview' ]
3236 );
3237 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3238 $out->wrapWikiMsg(
3239 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3240 [ 'userjsyoucanpreview' ]
3241 );
3242 }
3243 }
3244 }
3245 }
3246
3247 $this->addPageProtectionWarningHeaders();
3248
3249 $this->addLongPageWarningHeader();
3250
3251 # Add header copyright warning
3252 $this->showHeaderCopyrightWarning();
3253 }
3254
3255 /**
3256 * Helper function for summary input functions, which returns the necessary
3257 * attributes for the input.
3258 *
3259 * @param array|null $inputAttrs Array of attrs to use on the input
3260 * @return array
3261 */
3262 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3263 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3264 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3265 // Unicode codepoints.
3266 return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3267 'id' => 'wpSummary',
3268 'name' => 'wpSummary',
3269 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
3270 'tabindex' => 1,
3271 'size' => 60,
3272 'spellcheck' => 'true',
3273 ];
3274 }
3275
3276 /**
3277 * Builds a standard summary input with a label.
3278 *
3279 * @param string $summary The value of the summary input
3280 * @param string|null $labelText The html to place inside the label
3281 * @param array|null $inputAttrs Array of attrs to use on the input
3282 *
3283 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3284 */
3285 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3286 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3287 $this->getSummaryInputAttributes( $inputAttrs )
3288 );
3289 $inputAttrs += [
3290 'title' => Linker::titleAttrib( 'summary' ),
3291 'accessKey' => Linker::accesskey( 'summary' ),
3292 ];
3293
3294 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3295 $inputAttrs['inputId'] = $inputAttrs['id'];
3296 $inputAttrs['id'] = 'wpSummaryWidget';
3297
3298 return new OOUI\FieldLayout(
3299 new OOUI\TextInputWidget( [
3300 'value' => $summary,
3301 'infusable' => true,
3302 ] + $inputAttrs ),
3303 [
3304 'label' => new OOUI\HtmlSnippet( $labelText ),
3305 'align' => 'top',
3306 'id' => 'wpSummaryLabel',
3307 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3308 ]
3309 );
3310 }
3311
3312 /**
3313 * @param bool $isSubjectPreview True if this is the section subject/title
3314 * up top, or false if this is the comment summary
3315 * down below the textarea
3316 * @param string $summary The text of the summary to display
3317 */
3318 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3319 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3320 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3321 if ( $isSubjectPreview ) {
3322 if ( $this->nosummary ) {
3323 return;
3324 }
3325 } elseif ( !$this->mShowSummaryField ) {
3326 return;
3327 }
3328
3329 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3330 $this->context->getOutput()->addHTML( $this->getSummaryInputWidget(
3331 $summary,
3332 $labelText,
3333 [ 'class' => $summaryClass ]
3334 ) );
3335 }
3336
3337 /**
3338 * @param bool $isSubjectPreview True if this is the section subject/title
3339 * up top, or false if this is the comment summary
3340 * down below the textarea
3341 * @param string $summary The text of the summary to display
3342 * @return string
3343 */
3344 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3345 // avoid spaces in preview, gets always trimmed on save
3346 $summary = trim( $summary );
3347 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3348 return "";
3349 }
3350
3351 if ( $isSubjectPreview ) {
3352 $summary = $this->context->msg( 'newsectionsummary' )
3353 ->rawParams( MediaWikiServices::getInstance()->getParser()
3354 ->stripSectionName( $summary ) )
3355 ->inContentLanguage()->text();
3356 }
3357
3358 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3359
3360 $summary = $this->context->msg( $message )->parse()
3361 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3362 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3363 }
3364
3365 protected function showFormBeforeText() {
3366 $out = $this->context->getOutput();
3367 $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
3368 $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
3369 $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
3370 $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
3371 $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
3372 }
3373
3374 protected function showFormAfterText() {
3375 /**
3376 * To make it harder for someone to slip a user a page
3377 * which submits an edit form to the wiki without their
3378 * knowledge, a random token is associated with the login
3379 * session. If it's not passed back with the submission,
3380 * we won't save the page, or render user JavaScript and
3381 * CSS previews.
3382 *
3383 * For anon editors, who may not have a session, we just
3384 * include the constant suffix to prevent editing from
3385 * broken text-mangling proxies.
3386 */
3387 $this->context->getOutput()->addHTML(
3388 "\n" .
3389 Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
3390 "\n"
3391 );
3392 }
3393
3394 /**
3395 * Subpage overridable method for printing the form for page content editing
3396 * By default this simply outputs wpTextbox1
3397 * Subclasses can override this to provide a custom UI for editing;
3398 * be it a form, or simply wpTextbox1 with a modified content that will be
3399 * reverse modified when extracted from the post data.
3400 * Note that this is basically the inverse for importContentFormData
3401 */
3402 protected function showContentForm() {
3403 $this->showTextbox1();
3404 }
3405
3406 /**
3407 * Method to output wpTextbox1
3408 * The $textoverride method can be used by subclasses overriding showContentForm
3409 * to pass back to this method.
3410 *
3411 * @param array|null $customAttribs Array of html attributes to use in the textarea
3412 * @param string|null $textoverride Optional text to override $this->textarea1 with
3413 */
3414 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3415 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3416 $attribs = [ 'style' => 'display:none;' ];
3417 } else {
3418 $builder = new TextboxBuilder();
3419 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3420
3421 # Is an old revision being edited?
3422 if ( $this->isOldRev ) {
3423 $classes[] = 'mw-textarea-oldrev';
3424 }
3425
3426 $attribs = [ 'tabindex' => 1 ];
3427
3428 if ( is_array( $customAttribs ) ) {
3429 $attribs += $customAttribs;
3430 }
3431
3432 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3433 }
3434
3435 $this->showTextbox(
3436 $textoverride ?? $this->textbox1,
3437 'wpTextbox1',
3438 $attribs
3439 );
3440 }
3441
3442 protected function showTextbox2() {
3443 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3444 }
3445
3446 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3447 $builder = new TextboxBuilder();
3448 $attribs = $builder->buildTextboxAttribs(
3449 $name,
3450 $customAttribs,
3451 $this->context->getUser(),
3452 $this->mTitle
3453 );
3454
3455 $this->context->getOutput()->addHTML(
3456 Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3457 );
3458 }
3459
3460 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3461 $classes = [];
3462 if ( $isOnTop ) {
3463 $classes[] = 'ontop';
3464 }
3465
3466 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3467
3468 if ( $this->formtype != 'preview' ) {
3469 $attribs['style'] = 'display: none;';
3470 }
3471
3472 $out = $this->context->getOutput();
3473 $out->addHTML( Xml::openElement( 'div', $attribs ) );
3474
3475 if ( $this->formtype == 'preview' ) {
3476 $this->showPreview( $previewOutput );
3477 } else {
3478 // Empty content container for LivePreview
3479 $pageViewLang = $this->mTitle->getPageViewLanguage();
3480 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3481 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3482 $out->addHTML( Html::rawElement( 'div', $attribs ) );
3483 }
3484
3485 $out->addHTML( '</div>' );
3486
3487 if ( $this->formtype == 'diff' ) {
3488 try {
3489 $this->showDiff();
3490 } catch ( MWContentSerializationException $ex ) {
3491 $msg = $this->context->msg(
3492 'content-failed-to-parse',
3493 $this->contentModel,
3494 $this->contentFormat,
3495 $ex->getMessage()
3496 );
3497 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3498 }
3499 }
3500 }
3501
3502 /**
3503 * Append preview output to OutputPage.
3504 * Includes category rendering if this is a category page.
3505 *
3506 * @param string $text The HTML to be output for the preview.
3507 */
3508 protected function showPreview( $text ) {
3509 if ( $this->mArticle instanceof CategoryPage ) {
3510 $this->mArticle->openShowCategory();
3511 }
3512 # This hook seems slightly odd here, but makes things more
3513 # consistent for extensions.
3514 $out = $this->context->getOutput();
3515 Hooks::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3516 $out->addHTML( $text );
3517 if ( $this->mArticle instanceof CategoryPage ) {
3518 $this->mArticle->closeShowCategory();
3519 }
3520 }
3521
3522 /**
3523 * Get a diff between the current contents of the edit box and the
3524 * version of the page we're editing from.
3525 *
3526 * If this is a section edit, we'll replace the section as for final
3527 * save and then make a comparison.
3528 */
3529 public function showDiff() {
3530 $oldtitlemsg = 'currentrev';
3531 # if message does not exist, show diff against the preloaded default
3532 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3533 $oldtext = $this->mTitle->getDefaultMessageText();
3534 if ( $oldtext !== false ) {
3535 $oldtitlemsg = 'defaultmessagetext';
3536 $oldContent = $this->toEditContent( $oldtext );
3537 } else {
3538 $oldContent = null;
3539 }
3540 } else {
3541 $oldContent = $this->getCurrentContent();
3542 }
3543
3544 $textboxContent = $this->toEditContent( $this->textbox1 );
3545 if ( $this->editRevId !== null ) {
3546 $newContent = $this->page->replaceSectionAtRev(
3547 $this->section, $textboxContent, $this->summary, $this->editRevId
3548 );
3549 } else {
3550 $newContent = $this->page->replaceSectionContent(
3551 $this->section, $textboxContent, $this->summary, $this->edittime
3552 );
3553 }
3554
3555 if ( $newContent ) {
3556 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3557
3558 $user = $this->context->getUser();
3559 $popts = ParserOptions::newFromUserAndLang( $user,
3560 MediaWikiServices::getInstance()->getContentLanguage() );
3561 $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts );
3562 }
3563
3564 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3565 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3566 $newtitle = $this->context->msg( 'yourtext' )->parse();
3567
3568 if ( !$oldContent ) {
3569 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3570 }
3571
3572 if ( !$newContent ) {
3573 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3574 }
3575
3576 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
3577 $de->setContent( $oldContent, $newContent );
3578
3579 $difftext = $de->getDiff( $oldtitle, $newtitle );
3580 $de->showDiffStyle();
3581 } else {
3582 $difftext = '';
3583 }
3584
3585 $this->context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3586 }
3587
3588 /**
3589 * Show the header copyright warning.
3590 */
3591 protected function showHeaderCopyrightWarning() {
3592 $msg = 'editpage-head-copy-warn';
3593 if ( !$this->context->msg( $msg )->isDisabled() ) {
3594 $this->context->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3595 'editpage-head-copy-warn' );
3596 }
3597 }
3598
3599 /**
3600 * Give a chance for site and per-namespace customizations of
3601 * terms of service summary link that might exist separately
3602 * from the copyright notice.
3603 *
3604 * This will display between the save button and the edit tools,
3605 * so should remain short!
3606 */
3607 protected function showTosSummary() {
3608 $msg = 'editpage-tos-summary';
3609 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3610 if ( !$this->context->msg( $msg )->isDisabled() ) {
3611 $out = $this->context->getOutput();
3612 $out->addHTML( '<div class="mw-tos-summary">' );
3613 $out->addWikiMsg( $msg );
3614 $out->addHTML( '</div>' );
3615 }
3616 }
3617
3618 /**
3619 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3620 * characters not present on most keyboards for copying/pasting.
3621 */
3622 protected function showEditTools() {
3623 $this->context->getOutput()->addHTML( '<div class="mw-editTools">' .
3624 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3625 '</div>' );
3626 }
3627
3628 /**
3629 * Get the copyright warning
3630 *
3631 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3632 * @return string
3633 */
3634 protected function getCopywarn() {
3635 return self::getCopyrightWarning( $this->mTitle );
3636 }
3637
3638 /**
3639 * Get the copyright warning, by default returns wikitext
3640 *
3641 * @param Title $title
3642 * @param string $format Output format, valid values are any function of a Message object
3643 * @param Language|string|null $langcode Language code or Language object.
3644 * @return string
3645 */
3646 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3647 global $wgRightsText;
3648 if ( $wgRightsText ) {
3649 $copywarnMsg = [ 'copyrightwarning',
3650 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3651 $wgRightsText ];
3652 } else {
3653 $copywarnMsg = [ 'copyrightwarning2',
3654 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3655 }
3656 // Allow for site and per-namespace customization of contribution/copyright notice.
3657 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3658
3659 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3660 if ( $langcode ) {
3661 $msg->inLanguage( $langcode );
3662 }
3663 return "<div id=\"editpage-copywarn\">\n" .
3664 $msg->$format() . "\n</div>";
3665 }
3666
3667 /**
3668 * Get the Limit report for page previews
3669 *
3670 * @since 1.22
3671 * @param ParserOutput|null $output ParserOutput object from the parse
3672 * @return string HTML
3673 */
3674 public static function getPreviewLimitReport( ParserOutput $output = null ) {
3675 global $wgLang;
3676
3677 if ( !$output || !$output->getLimitReportData() ) {
3678 return '';
3679 }
3680
3681 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3682 wfMessage( 'limitreport-title' )->parseAsBlock()
3683 );
3684
3685 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3686 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3687
3688 $limitReport .= Html::openElement( 'table', [
3689 'class' => 'preview-limit-report wikitable'
3690 ] ) .
3691 Html::openElement( 'tbody' );
3692
3693 foreach ( $output->getLimitReportData() as $key => $value ) {
3694 if ( Hooks::run( 'ParserLimitReportFormat',
3695 [ $key, &$value, &$limitReport, true, true ]
3696 ) ) {
3697 $keyMsg = wfMessage( $key );
3698 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3699 if ( !$valueMsg->exists() ) {
3700 $valueMsg = new RawMessage( '$1' );
3701 }
3702 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3703 $limitReport .= Html::openElement( 'tr' ) .
3704 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3705 Html::rawElement( 'td', null,
3706 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3707 ) .
3708 Html::closeElement( 'tr' );
3709 }
3710 }
3711 }
3712
3713 $limitReport .= Html::closeElement( 'tbody' ) .
3714 Html::closeElement( 'table' ) .
3715 Html::closeElement( 'div' );
3716
3717 return $limitReport;
3718 }
3719
3720 protected function showStandardInputs( &$tabindex = 2 ) {
3721 $out = $this->context->getOutput();
3722 $out->addHTML( "<div class='editOptions'>\n" );
3723
3724 if ( $this->section != 'new' ) {
3725 $this->showSummaryInput( false, $this->summary );
3726 $out->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3727 }
3728
3729 $checkboxes = $this->getCheckboxesWidget(
3730 $tabindex,
3731 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3732 );
3733 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3734
3735 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3736
3737 // Show copyright warning.
3738 $out->addWikiTextAsInterface( $this->getCopywarn() );
3739 $out->addHTML( $this->editFormTextAfterWarn );
3740
3741 $out->addHTML( "<div class='editButtons'>\n" );
3742 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3743
3744 $cancel = $this->getCancelLink();
3745
3746 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3747 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3748 $edithelp =
3749 Html::linkButton(
3750 $this->context->msg( 'edithelp' )->text(),
3751 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3752 [ 'mw-ui-quiet' ]
3753 ) .
3754 $this->context->msg( 'word-separator' )->escaped() .
3755 $this->context->msg( 'newwindow' )->parse();
3756
3757 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3758 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3759 $out->addHTML( "</div><!-- editButtons -->\n" );
3760
3761 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3762
3763 $out->addHTML( "</div><!-- editOptions -->\n" );
3764 }
3765
3766 /**
3767 * Show an edit conflict. textbox1 is already shown in showEditForm().
3768 * If you want to use another entry point to this function, be careful.
3769 */
3770 protected function showConflict() {
3771 $out = $this->context->getOutput();
3772 // Avoid PHP 7.1 warning of passing $this by reference
3773 $editPage = $this;
3774 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3775 $this->incrementConflictStats();
3776
3777 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3778 }
3779 }
3780
3781 protected function incrementConflictStats() {
3782 $this->getEditConflictHelper()->incrementConflictStats();
3783 }
3784
3785 /**
3786 * @return string
3787 */
3788 public function getCancelLink() {
3789 $cancelParams = [];
3790 if ( !$this->isConflict && $this->oldid > 0 ) {
3791 $cancelParams['oldid'] = $this->oldid;
3792 } elseif ( $this->getContextTitle()->isRedirect() ) {
3793 $cancelParams['redirect'] = 'no';
3794 }
3795
3796 return new OOUI\ButtonWidget( [
3797 'id' => 'mw-editform-cancel',
3798 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3799 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3800 'framed' => false,
3801 'infusable' => true,
3802 'flags' => 'destructive',
3803 ] );
3804 }
3805
3806 /**
3807 * Returns the URL to use in the form's action attribute.
3808 * This is used by EditPage subclasses when simply customizing the action
3809 * variable in the constructor is not enough. This can be used when the
3810 * EditPage lives inside of a Special page rather than a custom page action.
3811 *
3812 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3813 * @return string
3814 */
3815 protected function getActionURL( Title $title ) {
3816 return $title->getLocalURL( [ 'action' => $this->action ] );
3817 }
3818
3819 /**
3820 * Check if a page was deleted while the user was editing it, before submit.
3821 * Note that we rely on the logging table, which hasn't been always there,
3822 * but that doesn't matter, because this only applies to brand new
3823 * deletes.
3824 * @return bool
3825 */
3826 protected function wasDeletedSinceLastEdit() {
3827 if ( $this->deletedSinceEdit !== null ) {
3828 return $this->deletedSinceEdit;
3829 }
3830
3831 $this->deletedSinceEdit = false;
3832
3833 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3834 $this->lastDelete = $this->getLastDelete();
3835 if ( $this->lastDelete ) {
3836 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3837 if ( $deleteTime > $this->starttime ) {
3838 $this->deletedSinceEdit = true;
3839 }
3840 }
3841 }
3842
3843 return $this->deletedSinceEdit;
3844 }
3845
3846 /**
3847 * Get the last log record of this page being deleted, if ever. This is
3848 * used to detect whether a delete occurred during editing.
3849 * @return bool|stdClass
3850 */
3851 protected function getLastDelete() {
3852 $dbr = wfGetDB( DB_REPLICA );
3853 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
3854 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
3855 $data = $dbr->selectRow(
3856 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3857 [
3858 'log_type',
3859 'log_action',
3860 'log_timestamp',
3861 'log_namespace',
3862 'log_title',
3863 'log_params',
3864 'log_deleted',
3865 'user_name'
3866 ] + $commentQuery['fields'] + $actorQuery['fields'],
3867 [
3868 'log_namespace' => $this->mTitle->getNamespace(),
3869 'log_title' => $this->mTitle->getDBkey(),
3870 'log_type' => 'delete',
3871 'log_action' => 'delete',
3872 ],
3873 __METHOD__,
3874 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3875 [
3876 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3877 ] + $commentQuery['joins'] + $actorQuery['joins']
3878 );
3879 // Quick paranoid permission checks...
3880 if ( is_object( $data ) ) {
3881 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3882 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3883 }
3884
3885 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3886 $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
3887 $data->log_comment_data = null;
3888 }
3889 }
3890
3891 return $data;
3892 }
3893
3894 /**
3895 * Get the rendered text for previewing.
3896 * @throws MWException
3897 * @return string
3898 */
3899 public function getPreviewText() {
3900 $out = $this->context->getOutput();
3901 $config = $this->context->getConfig();
3902
3903 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk ) {
3904 // Could be an offsite preview attempt. This is very unsafe if
3905 // HTML is enabled, as it could be an attack.
3906 $parsedNote = '';
3907 if ( $this->textbox1 !== '' ) {
3908 // Do not put big scary notice, if previewing the empty
3909 // string, which happens when you initially edit
3910 // a category page, due to automatic preview-on-open.
3911 $parsedNote = Html::rawElement( 'div', [ 'class' => 'previewnote' ],
3912 $out->parseAsInterface(
3913 $this->context->msg( 'session_fail_preview_html' )->plain()
3914 ) );
3915 }
3916 $this->incrementEditFailureStats( 'session_loss' );
3917 return $parsedNote;
3918 }
3919
3920 $note = '';
3921
3922 try {
3923 $content = $this->toEditContent( $this->textbox1 );
3924
3925 $previewHTML = '';
3926 if ( !Hooks::run(
3927 'AlternateEditPreview',
3928 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3929 ) {
3930 return $previewHTML;
3931 }
3932
3933 # provide a anchor link to the editform
3934 $continueEditing = '<span class="mw-continue-editing">' .
3935 '[[#' . self::EDITFORM_ID . '|' .
3936 $this->context->getLanguage()->getArrow() . ' ' .
3937 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3938 if ( $this->mTriedSave && !$this->mTokenOk ) {
3939 if ( $this->mTokenOkExceptSuffix ) {
3940 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3941 $this->incrementEditFailureStats( 'bad_token' );
3942 } else {
3943 $note = $this->context->msg( 'session_fail_preview' )->plain();
3944 $this->incrementEditFailureStats( 'session_loss' );
3945 }
3946 } elseif ( $this->incompleteForm ) {
3947 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3948 if ( $this->mTriedSave ) {
3949 $this->incrementEditFailureStats( 'incomplete_form' );
3950 }
3951 } else {
3952 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3953 }
3954
3955 # don't parse non-wikitext pages, show message about preview
3956 if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
3957 if ( $this->mTitle->isUserConfigPage() ) {
3958 $level = 'user';
3959 } elseif ( $this->mTitle->isSiteConfigPage() ) {
3960 $level = 'site';
3961 } else {
3962 $level = false;
3963 }
3964
3965 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3966 $format = 'css';
3967 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3968 $format = false;
3969 }
3970 } elseif ( $content->getModel() == CONTENT_MODEL_JSON ) {
3971 $format = 'json';
3972 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3973 $format = false;
3974 }
3975 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3976 $format = 'js';
3977 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3978 $format = false;
3979 }
3980 } else {
3981 $format = false;
3982 }
3983
3984 # Used messages to make sure grep find them:
3985 # Messages: usercsspreview, userjsonpreview, userjspreview,
3986 # sitecsspreview, sitejsonpreview, sitejspreview
3987 if ( $level && $format ) {
3988 $note = "<div id='mw-{$level}{$format}preview'>" .
3989 $this->context->msg( "{$level}{$format}preview" )->plain() .
3990 ' ' . $continueEditing . "</div>";
3991 }
3992 }
3993
3994 # If we're adding a comment, we need to show the
3995 # summary as the headline
3996 if ( $this->section === "new" && $this->summary !== "" ) {
3997 $content = $content->addSectionHeader( $this->summary );
3998 }
3999
4000 $hook_args = [ $this, &$content ];
4001 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
4002
4003 $parserResult = $this->doPreviewParse( $content );
4004 $parserOutput = $parserResult['parserOutput'];
4005 $previewHTML = $parserResult['html'];
4006 $this->mParserOutput = $parserOutput;
4007 $out->addParserOutputMetadata( $parserOutput );
4008 if ( $out->userCanPreview() ) {
4009 $out->addContentOverride( $this->getTitle(), $content );
4010 }
4011
4012 if ( count( $parserOutput->getWarnings() ) ) {
4013 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4014 }
4015
4016 } catch ( MWContentSerializationException $ex ) {
4017 $m = $this->context->msg(
4018 'content-failed-to-parse',
4019 $this->contentModel,
4020 $this->contentFormat,
4021 $ex->getMessage()
4022 );
4023 $note .= "\n\n" . $m->plain(); # gets parsed down below
4024 $previewHTML = '';
4025 }
4026
4027 if ( $this->isConflict ) {
4028 $conflict = Html::rawElement(
4029 'h2', [ 'id' => 'mw-previewconflict' ],
4030 $this->context->msg( 'previewconflict' )->escaped()
4031 );
4032 } else {
4033 $conflict = '<hr />';
4034 }
4035
4036 $previewhead = Html::rawElement(
4037 'div', [ 'class' => 'previewnote' ],
4038 Html::rawElement(
4039 'h2', [ 'id' => 'mw-previewheader' ],
4040 $this->context->msg( 'preview' )->escaped()
4041 ) .
4042 $out->parseAsInterface( $note ) . $conflict
4043 );
4044
4045 $pageViewLang = $this->mTitle->getPageViewLanguage();
4046 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
4047 'class' => 'mw-content-' . $pageViewLang->getDir() ];
4048 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
4049
4050 return $previewhead . $previewHTML . $this->previewTextAfterContent;
4051 }
4052
4053 private function incrementEditFailureStats( $failureType ) {
4054 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
4055 $stats->increment( 'edit.failures.' . $failureType );
4056 }
4057
4058 /**
4059 * Get parser options for a preview
4060 * @return ParserOptions
4061 */
4062 protected function getPreviewParserOptions() {
4063 $parserOptions = $this->page->makeParserOptions( $this->context );
4064 $parserOptions->setIsPreview( true );
4065 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
4066 $parserOptions->enableLimitReport();
4067
4068 // XXX: we could call $parserOptions->setCurrentRevisionCallback here to force the
4069 // current revision to be null during PST, until setupFakeRevision is called on
4070 // the ParserOptions. Currently, we rely on Parser::getRevisionObject() to ignore
4071 // existing revisions in preview mode.
4072
4073 return $parserOptions;
4074 }
4075
4076 /**
4077 * Parse the page for a preview. Subclasses may override this class, in order
4078 * to parse with different options, or to otherwise modify the preview HTML.
4079 *
4080 * @param Content $content The page content
4081 * @return array with keys:
4082 * - parserOutput: The ParserOutput object
4083 * - html: The HTML to be displayed
4084 */
4085 protected function doPreviewParse( Content $content ) {
4086 $user = $this->context->getUser();
4087 $parserOptions = $this->getPreviewParserOptions();
4088
4089 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4090 // Parser::getRevisionObject() will return null in preview mode,
4091 // causing the context user to be used for {{subst:REVISIONUSER}}.
4092 // XXX: Alternatively, we could also call setupFakeRevision() a second time:
4093 // once before PST with $content, and then after PST with $pstContent.
4094 $pstContent = $content->preSaveTransform( $this->mTitle, $user, $parserOptions );
4095 $scopedCallback = $parserOptions->setupFakeRevision( $this->mTitle, $pstContent, $user );
4096 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
4097 ScopedCallback::consume( $scopedCallback );
4098 return [
4099 'parserOutput' => $parserOutput,
4100 'html' => $parserOutput->getText( [
4101 'enableSectionEditLinks' => false
4102 ] )
4103 ];
4104 }
4105
4106 /**
4107 * @return array
4108 */
4109 public function getTemplates() {
4110 if ( $this->preview || $this->section != '' ) {
4111 $templates = [];
4112 if ( !isset( $this->mParserOutput ) ) {
4113 return $templates;
4114 }
4115 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
4116 foreach ( array_keys( $template ) as $dbk ) {
4117 $templates[] = Title::makeTitle( $ns, $dbk );
4118 }
4119 }
4120 return $templates;
4121 } else {
4122 return $this->mTitle->getTemplateLinksFrom();
4123 }
4124 }
4125
4126 /**
4127 * Allow extensions to provide a toolbar.
4128 *
4129 * @return string|null
4130 */
4131 public static function getEditToolbar() {
4132 $startingToolbar = '<div id="toolbar"></div>';
4133 $toolbar = $startingToolbar;
4134
4135 if ( !Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4136 return null;
4137 }
4138 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4139 return ( $toolbar === $startingToolbar ) ? null : $toolbar;
4140 }
4141
4142 /**
4143 * Return an array of checkbox definitions.
4144 *
4145 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4146 *
4147 * Array values are associative arrays with the following keys:
4148 * - 'label-message' (required): message for label text
4149 * - 'id' (required): 'id' attribute for the `<input>`
4150 * - 'default' (required): default checkedness (true or false)
4151 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4152 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4153 * from messages like 'tooltip-foo', 'accesskey-foo'
4154 * - 'label-id' (optional): 'id' attribute for the `<label>`
4155 * - 'legacy-name' (optional): short name for backwards-compatibility
4156 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4157 * where bool indicates the checked status of the checkbox
4158 * @return array
4159 */
4160 public function getCheckboxesDefinition( $checked ) {
4161 $checkboxes = [];
4162
4163 $user = $this->context->getUser();
4164 // don't show the minor edit checkbox if it's a new page or section
4165 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
4166 if ( !$this->isNew && $permissionManager->userHasRight( $user, 'minoredit' ) ) {
4167 $checkboxes['wpMinoredit'] = [
4168 'id' => 'wpMinoredit',
4169 'label-message' => 'minoredit',
4170 // Uses messages: tooltip-minoredit, accesskey-minoredit
4171 'tooltip' => 'minoredit',
4172 'label-id' => 'mw-editpage-minoredit',
4173 'legacy-name' => 'minor',
4174 'default' => $checked['minor'],
4175 ];
4176 }
4177
4178 if ( $user->isLoggedIn() ) {
4179 $checkboxes['wpWatchthis'] = [
4180 'id' => 'wpWatchthis',
4181 'label-message' => 'watchthis',
4182 // Uses messages: tooltip-watch, accesskey-watch
4183 'tooltip' => 'watch',
4184 'label-id' => 'mw-editpage-watch',
4185 'legacy-name' => 'watch',
4186 'default' => $checked['watch'],
4187 ];
4188 }
4189
4190 $editPage = $this;
4191 Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4192
4193 return $checkboxes;
4194 }
4195
4196 /**
4197 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4198 * any other added by extensions.
4199 *
4200 * @param int &$tabindex Current tabindex
4201 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4202 * status of the checkbox
4203 *
4204 * @return array Associative array of string keys to OOUI\FieldLayout instances
4205 */
4206 public function getCheckboxesWidget( &$tabindex, $checked ) {
4207 $checkboxes = [];
4208 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4209
4210 foreach ( $checkboxesDef as $name => $options ) {
4211 $legacyName = $options['legacy-name'] ?? $name;
4212
4213 $title = null;
4214 $accesskey = null;
4215 if ( isset( $options['tooltip'] ) ) {
4216 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4217 $title = Linker::titleAttrib( $options['tooltip'] );
4218 }
4219 if ( isset( $options['title-message'] ) ) {
4220 $title = $this->context->msg( $options['title-message'] )->text();
4221 }
4222
4223 $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4224 new OOUI\CheckboxInputWidget( [
4225 'tabIndex' => ++$tabindex,
4226 'accessKey' => $accesskey,
4227 'id' => $options['id'] . 'Widget',
4228 'inputId' => $options['id'],
4229 'name' => $name,
4230 'selected' => $options['default'],
4231 'infusable' => true,
4232 ] ),
4233 [
4234 'align' => 'inline',
4235 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4236 'title' => $title,
4237 'id' => $options['label-id'] ?? null,
4238 ]
4239 );
4240 }
4241
4242 return $checkboxes;
4243 }
4244
4245 /**
4246 * Get the message key of the label for the button to save the page
4247 *
4248 * @since 1.30
4249 * @return string
4250 */
4251 protected function getSubmitButtonLabel() {
4252 $labelAsPublish =
4253 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4254
4255 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4256 $newPage = !$this->mTitle->exists();
4257
4258 if ( $labelAsPublish ) {
4259 $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4260 } else {
4261 $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4262 }
4263
4264 return $buttonLabelKey;
4265 }
4266
4267 /**
4268 * Returns an array of html code of the following buttons:
4269 * save, diff and preview
4270 *
4271 * @param int &$tabindex Current tabindex
4272 *
4273 * @return array
4274 */
4275 public function getEditButtons( &$tabindex ) {
4276 $buttons = [];
4277
4278 $labelAsPublish =
4279 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4280
4281 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
4282 $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
4283
4284 $buttons['save'] = new OOUI\ButtonInputWidget( [
4285 'name' => 'wpSave',
4286 'tabIndex' => ++$tabindex,
4287 'id' => 'wpSaveWidget',
4288 'inputId' => 'wpSave',
4289 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4290 'useInputTag' => true,
4291 'flags' => [ 'progressive', 'primary' ],
4292 'label' => $buttonLabel,
4293 'infusable' => true,
4294 'type' => 'submit',
4295 // Messages used: tooltip-save, tooltip-publish
4296 'title' => Linker::titleAttrib( $buttonTooltip ),
4297 // Messages used: accesskey-save, accesskey-publish
4298 'accessKey' => Linker::accesskey( $buttonTooltip ),
4299 ] );
4300
4301 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4302 'name' => 'wpPreview',
4303 'tabIndex' => ++$tabindex,
4304 'id' => 'wpPreviewWidget',
4305 'inputId' => 'wpPreview',
4306 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4307 'useInputTag' => true,
4308 'label' => $this->context->msg( 'showpreview' )->text(),
4309 'infusable' => true,
4310 'type' => 'submit',
4311 // Message used: tooltip-preview
4312 'title' => Linker::titleAttrib( 'preview' ),
4313 // Message used: accesskey-preview
4314 'accessKey' => Linker::accesskey( 'preview' ),
4315 ] );
4316
4317 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4318 'name' => 'wpDiff',
4319 'tabIndex' => ++$tabindex,
4320 'id' => 'wpDiffWidget',
4321 'inputId' => 'wpDiff',
4322 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4323 'useInputTag' => true,
4324 'label' => $this->context->msg( 'showdiff' )->text(),
4325 'infusable' => true,
4326 'type' => 'submit',
4327 // Message used: tooltip-diff
4328 'title' => Linker::titleAttrib( 'diff' ),
4329 // Message used: accesskey-diff
4330 'accessKey' => Linker::accesskey( 'diff' ),
4331 ] );
4332
4333 // Avoid PHP 7.1 warning of passing $this by reference
4334 $editPage = $this;
4335 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4336
4337 return $buttons;
4338 }
4339
4340 /**
4341 * Creates a basic error page which informs the user that
4342 * they have attempted to edit a nonexistent section.
4343 */
4344 public function noSuchSectionPage() {
4345 $out = $this->context->getOutput();
4346 $out->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4347
4348 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4349
4350 // Avoid PHP 7.1 warning of passing $this by reference
4351 $editPage = $this;
4352 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4353 $out->addHTML( $res );
4354
4355 $out->returnToMain( false, $this->mTitle );
4356 }
4357
4358 /**
4359 * Show "your edit contains spam" page with your diff and text
4360 *
4361 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4362 */
4363 public function spamPageWithContent( $match = false ) {
4364 $this->textbox2 = $this->textbox1;
4365
4366 if ( is_array( $match ) ) {
4367 $match = $this->context->getLanguage()->listToText( $match );
4368 }
4369 $out = $this->context->getOutput();
4370 $out->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4371
4372 $out->addHTML( '<div id="spamprotected">' );
4373 $out->addWikiMsg( 'spamprotectiontext' );
4374 if ( $match ) {
4375 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4376 }
4377 $out->addHTML( '</div>' );
4378
4379 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4380 $this->showDiff();
4381
4382 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4383 $this->showTextbox2();
4384
4385 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4386 }
4387
4388 /**
4389 * @since 1.29
4390 */
4391 protected function addEditNotices() {
4392 $out = $this->context->getOutput();
4393 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4394 if ( count( $editNotices ) ) {
4395 $out->addHTML( implode( "\n", $editNotices ) );
4396 } else {
4397 $msg = $this->context->msg( 'editnotice-notext' );
4398 if ( !$msg->isDisabled() ) {
4399 $out->addHTML(
4400 '<div class="mw-editnotice-notext">'
4401 . $msg->parseAsBlock()
4402 . '</div>'
4403 );
4404 }
4405 }
4406 }
4407
4408 /**
4409 * @since 1.29
4410 */
4411 protected function addTalkPageText() {
4412 if ( $this->mTitle->isTalkPage() ) {
4413 $this->context->getOutput()->addWikiMsg( 'talkpagetext' );
4414 }
4415 }
4416
4417 /**
4418 * @since 1.29
4419 */
4420 protected function addLongPageWarningHeader() {
4421 if ( $this->contentLength === false ) {
4422 $this->contentLength = strlen( $this->textbox1 );
4423 }
4424
4425 $out = $this->context->getOutput();
4426 $lang = $this->context->getLanguage();
4427 $maxArticleSize = $this->context->getConfig()->get( 'MaxArticleSize' );
4428 if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
4429 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4430 [
4431 'longpageerror',
4432 $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4433 $lang->formatNum( $maxArticleSize )
4434 ]
4435 );
4436 } elseif ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4437 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4438 [
4439 'longpage-hint',
4440 $lang->formatSize( strlen( $this->textbox1 ) ),
4441 strlen( $this->textbox1 )
4442 ]
4443 );
4444 }
4445 }
4446
4447 /**
4448 * @since 1.29
4449 */
4450 protected function addPageProtectionWarningHeaders() {
4451 $out = $this->context->getOutput();
4452 if ( $this->mTitle->isProtected( 'edit' ) &&
4453 MediaWikiServices::getInstance()->getPermissionManager()->getNamespaceRestrictionLevels(
4454 $this->getTitle()->getNamespace()
4455 ) !== [ '' ]
4456 ) {
4457 # Is the title semi-protected?
4458 if ( $this->mTitle->isSemiProtected() ) {
4459 $noticeMsg = 'semiprotectedpagewarning';
4460 } else {
4461 # Then it must be protected based on static groups (regular)
4462 $noticeMsg = 'protectedpagewarning';
4463 }
4464 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4465 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4466 }
4467 if ( $this->mTitle->isCascadeProtected() ) {
4468 # Is this page under cascading protection from some source pages?
4469 /** @var Title[] $cascadeSources */
4470 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4471 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4472 $cascadeSourcesCount = count( $cascadeSources );
4473 if ( $cascadeSourcesCount > 0 ) {
4474 # Explain, and list the titles responsible
4475 foreach ( $cascadeSources as $page ) {
4476 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4477 }
4478 }
4479 $notice .= '</div>';
4480 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4481 }
4482 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4483 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4484 [ 'lim' => 1,
4485 'showIfEmpty' => false,
4486 'msgKey' => [ 'titleprotectedwarning' ],
4487 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4488 }
4489 }
4490
4491 /**
4492 * @param OutputPage $out
4493 * @since 1.29
4494 */
4495 protected function addExplainConflictHeader( OutputPage $out ) {
4496 $out->addHTML(
4497 $this->getEditConflictHelper()->getExplainHeader()
4498 );
4499 }
4500
4501 /**
4502 * @param string $name
4503 * @param mixed[] $customAttribs
4504 * @param User $user
4505 * @return mixed[]
4506 * @since 1.29
4507 */
4508 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4509 return ( new TextboxBuilder() )->buildTextboxAttribs(
4510 $name, $customAttribs, $user, $this->mTitle
4511 );
4512 }
4513
4514 /**
4515 * @param string $wikitext
4516 * @return string
4517 * @since 1.29
4518 */
4519 protected function addNewLineAtEnd( $wikitext ) {
4520 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4521 }
4522
4523 /**
4524 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4525 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4526 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4527 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4528 * spread the new style links more efficiently.
4529 *
4530 * @param string $text
4531 * @return string
4532 */
4533 private function guessSectionName( $text ) {
4534 // Detect Microsoft browsers
4535 $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
4536 $parser = MediaWikiServices::getInstance()->getParser();
4537 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4538 // ...and redirect them to legacy encoding, if available
4539 return $parser->guessLegacySectionNameFromWikiText( $text );
4540 }
4541 // Meanwhile, real browsers get real anchors
4542 $name = $parser->guessSectionNameFromWikiText( $text );
4543 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4544 // otherwise Chrome double-escapes the rest of the URL.
4545 return '#' . urlencode( mb_substr( $name, 1 ) );
4546 }
4547
4548 /**
4549 * Set a factory function to create an EditConflictHelper
4550 *
4551 * @param callable $factory Factory function
4552 * @since 1.31
4553 */
4554 public function setEditConflictHelperFactory( callable $factory ) {
4555 $this->editConflictHelperFactory = $factory;
4556 $this->editConflictHelper = null;
4557 }
4558
4559 /**
4560 * @return TextConflictHelper
4561 */
4562 private function getEditConflictHelper() {
4563 if ( !$this->editConflictHelper ) {
4564 $this->editConflictHelper = call_user_func(
4565 $this->editConflictHelperFactory,
4566 $this->getSubmitButtonLabel()
4567 );
4568 }
4569
4570 return $this->editConflictHelper;
4571 }
4572
4573 /**
4574 * @param string $submitButtonLabel
4575 * @return TextConflictHelper
4576 */
4577 private function newTextConflictHelper( $submitButtonLabel ) {
4578 return new TextConflictHelper(
4579 $this->getTitle(),
4580 $this->getContext()->getOutput(),
4581 MediaWikiServices::getInstance()->getStatsdDataFactory(),
4582 $submitButtonLabel
4583 );
4584 }
4585 }