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