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