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