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