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