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