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