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