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