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