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