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