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