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