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