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