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