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