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