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