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