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