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