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