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