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