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