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