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