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