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