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