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