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