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