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