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