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