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