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