Debian Codegraph @

includes/editpage/EditPage.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\EditPage;
22
23 use Article;
24 use BadMethodCallException;
25 use CategoryPage;
26 use ErrorPageError;
27 use LogPage;
28 use ManualLogEntry;
29 use MediaWiki\Auth\AuthManager;
30 use MediaWiki\Block\BlockErrorFormatter;
31 use MediaWiki\Cache\LinkBatchFactory;
32 use MediaWiki\CommentStore\CommentStore;
33 use MediaWiki\CommentStore\CommentStoreComment;
34 use MediaWiki\Config\Config;
35 use MediaWiki\Content\Content;
36 use MediaWiki\Content\ContentHandler;
37 use MediaWiki\Content\IContentHandlerFactory;
38 use MediaWiki\Content\TextContent;
39 use MediaWiki\Context\DerivativeContext;
40 use MediaWiki\Context\IContextSource;
41 use MediaWiki\Debug\DeprecationHelper;
42 use MediaWiki\Deferred\DeferredUpdates;
43 use MediaWiki\EditPage\Constraint\AccidentalRecreationConstraint;
44 use MediaWiki\EditPage\Constraint\ChangeTagsConstraint;
45 use MediaWiki\EditPage\Constraint\ContentModelChangeConstraint;
46 use MediaWiki\EditPage\Constraint\DefaultTextConstraint;
47 use MediaWiki\EditPage\Constraint\EditConstraintFactory;
48 use MediaWiki\EditPage\Constraint\EditConstraintRunner;
49 use MediaWiki\EditPage\Constraint\EditFilterMergedContentHookConstraint;
50 use MediaWiki\EditPage\Constraint\ExistingSectionEditConstraint;
51 use MediaWiki\EditPage\Constraint\IEditConstraint;
52 use MediaWiki\EditPage\Constraint\ImageRedirectConstraint;
53 use MediaWiki\EditPage\Constraint\MissingCommentConstraint;
54 use MediaWiki\EditPage\Constraint\NewSectionMissingSubjectConstraint;
55 use MediaWiki\EditPage\Constraint\PageSizeConstraint;
56 use MediaWiki\EditPage\Constraint\SelfRedirectConstraint;
57 use MediaWiki\EditPage\Constraint\SpamRegexConstraint;
58 use MediaWiki\EditPage\Constraint\UnicodeConstraint;
59 use MediaWiki\EditPage\Constraint\UserBlockConstraint;
60 use MediaWiki\HookContainer\HookRunner;
61 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
62 use MediaWiki\Html\Html;
63 use MediaWiki\Language\RawMessage;
64 use MediaWiki\Linker\Linker;
65 use MediaWiki\Linker\LinkRenderer;
66 use MediaWiki\Logger\LoggerFactory;
67 use MediaWiki\MainConfigNames;
68 use MediaWiki\MediaWikiServices;
69 use MediaWiki\Message\Message;
70 use MediaWiki\Page\PageIdentity;
71 use MediaWiki\Page\PageReference;
72 use MediaWiki\Page\RedirectLookup;
73 use MediaWiki\Page\WikiPageFactory;
74 use MediaWiki\Parser\ParserOptions;
75 use MediaWiki\Parser\ParserOutput;
76 use MediaWiki\Permissions\Authority;
77 use MediaWiki\Permissions\PermissionManager;
78 use MediaWiki\Permissions\PermissionStatus;
79 use MediaWiki\Permissions\RestrictionStore;
80 use MediaWiki\Request\WebRequest;
81 use MediaWiki\Revision\RevisionRecord;
82 use MediaWiki\Revision\RevisionStore;
83 use MediaWiki\Revision\RevisionStoreRecord;
84 use MediaWiki\Revision\SlotRecord;
85 use MediaWiki\Status\Status;
86 use MediaWiki\Storage\EditResult;
87 use MediaWiki\Title\Title;
88 use MediaWiki\User\ExternalUserNames;
89 use MediaWiki\User\Options\UserOptionsLookup;
90 use MediaWiki\User\TempUser\CreateStatus;
91 use MediaWiki\User\TempUser\TempUserCreator;
92 use MediaWiki\User\User;
93 use MediaWiki\User\UserFactory;
94 use MediaWiki\User\UserIdentity;
95 use MediaWiki\User\UserNameUtils;
96 use MediaWiki\Watchlist\WatchedItemStoreInterface;
97 use MediaWiki\Watchlist\WatchlistManager;
98 use MessageLocalizer;
99 use MWContentSerializationException;
100 use MWException;
101 use MWUnknownContentModelException;
102 use OOUI;
103 use OOUI\ButtonWidget;
104 use OOUI\CheckboxInputWidget;
105 use OOUI\DropdownInputWidget;
106 use OOUI\FieldLayout;
107 use PermissionsError;
108 use ReadOnlyError;
109 use RecentChange;
110 use RuntimeException;
111 use Skin;
112 use stdClass;
113 use ThrottledError;
114 use UserBlockedError;
115 use WatchAction;
116 use Wikimedia\Assert\Assert;
117 use Wikimedia\Message\MessageValue;
118 use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
119 use Wikimedia\Rdbms\IConnectionProvider;
120 use Wikimedia\Rdbms\IDBAccessObject;
121 use Wikimedia\Rdbms\SelectQueryBuilder;
122 use WikiPage;
123
124 /**
125 * The HTML user interface for page editing.
126 *
127 * This was originally split from the Article class, with some database and text
128 * munging logic still partly there.
129 *
130 * EditPage cares about two distinct titles:
131 * - $this->mContextTitle is the page that forms submit to, links point to,
132 * redirects go to, etc.
133 * - $this->mTitle (as well as $mArticle) is the page in the database that is
134 * actually being edited.
135 *
136 * These are usually the same, but they are now allowed to be different.
137 *
138 * Surgeon General's Warning: prolonged exposure to this class is known to cause
139 * headaches, which may be fatal.
140 *
141 * @newable
142 * @note marked as newable in 1.35 for lack of a better alternative,
143 * but should be split up into service objects and command objects
144 * in the future (T157658).
145 */
146 #[\AllowDynamicProperties]
147 class EditPage implements IEditObject {
148 use DeprecationHelper;
149 use ProtectedHookAccessorTrait;
150
151 /**
152 * Used for Unicode support checks
153 */
154 public const UNICODE_CHECK = UnicodeConstraint::VALID_UNICODE;
155
156 /**
157 * HTML id and name for the beginning of the edit form.
158 */
159 public const EDITFORM_ID = 'editform';
160
161 /**
162 * Prefix of key for cookie used to pass post-edit state.
163 * The revision id edited is added after this
164 */
165 public const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
166
167 /**
168 * Duration of PostEdit cookie, in seconds.
169 * The cookie will be removed on the next page view of this article (Article::view()).
170 *
171 * Otherwise, though, we don't want the cookies to accumulate.
172 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
173 * limit of only 20 cookies per domain. This still applies at least to some
174 * versions of IE without full updates:
175 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
176 *
177 * A value of 20 minutes should be enough to take into account slow loads and minor
178 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
179 *
180 * Some say this is too long (T211233), others say it is too short (T289538).
181 * The same value is used for client-side post-edit storage (in mediawiki.action.view.postEdit).
182 */
183 public const POST_EDIT_COOKIE_DURATION = 1200;
184
185 /**
186 * @var Article
187 */
188 private $mArticle;
189
190 /** @var WikiPage */
191 private $page;
192
193 /**
194 * @var Title
195 */
196 private $mTitle;
197
198 /** @var null|Title */
199 private $mContextTitle = null;
200
201 /**
202 * @deprecated since 1.38 for public usage; no replacement
203 * @var string
204 */
205 public $action = 'submit';
206
207 /** @var bool Whether an edit conflict needs to be resolved. Detected based on whether
208 * $editRevId is different than the latest revision. When a conflict has successfully
209 * been resolved by a 3-way-merge, this field is set to false.
210 */
211 public $isConflict = false;
212
213 /** @var bool New page or new section */
214 private $isNew = false;
215
216 /** @var bool */
217 private $deletedSinceEdit;
218
219 /** @var string */
220 public $formtype;
221
222 /** @var bool
223 * True the first time the edit form is rendered, false after re-rendering
224 * with diff, save prompts, etc.
225 */
226 public $firsttime;
227
228 /** @var stdClass|null */
229 private $lastDelete;
230
231 /** @var bool */
232 private $mTokenOk = false;
233
234 /** @var bool */
235 private $mTriedSave = false;
236
237 /** @var bool */
238 private $incompleteForm = false;
239
240 /** @var bool */
241 private $tooBig = false;
242
243 /** @var bool */
244 private $missingComment = false;
245
246 /** @var bool */
247 private $missingSummary = false;
248
249 /** @var bool */
250 private $allowBlankSummary = false;
251
252 /** @var bool */
253 protected $blankArticle = false;
254
255 /** @var bool */
256 private $allowBlankArticle = false;
257
258 /** @var bool */
259 private $selfRedirect = false;
260
261 /** @var bool */
262 private $allowSelfRedirect = false;
263
264 /** @var string */
265 private $autoSumm = '';
266
267 /** @var string */
268 private $hookError = '';
269
270 /** @var ParserOutput */
271 private $mParserOutput;
272
273 /**
274 * @var RevisionRecord|false|null
275 *
276 * A RevisionRecord corresponding to $this->editRevId or $this->edittime
277 */
278 private $mExpectedParentRevision = false;
279
280 /** @var bool */
281 public $mShowSummaryField = true;
282
283 # Form values
284
285 /** @var bool */
286 public $save = false;
287
288 /** @var bool */
289 public $preview = false;
290
291 /** @var bool */
292 private $diff = false;
293
294 /** @var bool */
295 private $minoredit = false;
296
297 /** @var bool */
298 private $watchthis = false;
299
300 /** @var bool Corresponds to $wgWatchlistExpiry */
301 private $watchlistExpiryEnabled;
302
303 private WatchedItemStoreInterface $watchedItemStore;
304
305 /** @var string|null The expiry time of the watch item, or null if it is not watched temporarily. */
306 private $watchlistExpiry;
307
308 /** @var bool */
309 private $recreate = false;
310
311 /** @var string
312 * Page content input field.
313 */
314 public $textbox1 = '';
315
316 /** @var string */
317 public $textbox2 = '';
318
319 /** @var string */
320 public $summary = '';
321
322 /**
323 * @var bool
324 * If true, hide the summary field.
325 */
326 private $nosummary = false;
327
328 /** @var string|null
329 * Timestamp of the latest revision of the page when editing was initiated
330 * on the client.
331 */
332 public $edittime = '';
333
334 /** @var int|null Revision ID of the latest revision of the page when editing
335 * was initiated on the client. This is used to detect and resolve edit
336 * conflicts.
337 *
338 * @note 0 if the page did not exist at that time.
339 * @note When starting an edit from an old revision, this still records the current
340 * revision at the time, not the one the edit is based on.
341 *
342 * @see $oldid
343 * @see getExpectedParentRevision()
344 */
345 private $editRevId = null;
346
347 /** @var string */
348 public $section = '';
349
350 /** @var string|null */
351 public $sectiontitle = null;
352
353 /** @var string|null */
354 private $newSectionAnchor = null;
355
356 /** @var string|null
357 * Timestamp from the first time the edit form was rendered.
358 */
359 public $starttime = '';
360
361 /** @var int Revision ID the edit is based on, or 0 if it's the current revision.
362 * FIXME: This isn't used in conflict resolution--provide a better
363 * justification or merge with parentRevId.
364 * @see $editRevId
365 */
366 public $oldid = 0;
367
368 /**
369 * @var int Revision ID the edit is based on, adjusted when an edit conflict is resolved.
370 * @see $editRevId
371 * @see $oldid
372 * @see getparentRevId()
373 */
374 private $parentRevId = 0;
375
376 /** @var int|null */
377 private $scrolltop = null;
378
379 /** @var bool */
380 private $markAsBot = true;
381
382 /** @var string */
383 public $contentModel;
384
385 /** @var null|string */
386 public $contentFormat = null;
387
388 /** @var null|array */
389 private $changeTags = null;
390
391 # Placeholders for text injection by hooks (must be HTML)
392 # extensions should take care to _append_ to the present value
393
394 /** @var string Before even the preview */
395 public $editFormPageTop = '';
396 /** @var string */
397 public $editFormTextTop = '';
398 /** @var string */
399 public $editFormTextBeforeContent = '';
400 /** @var string */
401 public $editFormTextAfterWarn = '';
402 /** @var string */
403 public $editFormTextAfterTools = '';
404 /** @var string */
405 public $editFormTextBottom = '';
406 /** @var string */
407 public $editFormTextAfterContent = '';
408 /** @var string */
409 public $previewTextAfterContent = '';
410
411 /** @var bool should be set to true whenever an article was successfully altered. */
412 public $didSave = false;
413 /** @var int */
414 public $undidRev = 0;
415 /** @var int */
416 private $undoAfter = 0;
417
418 /** @var bool */
419 public $suppressIntro = false;
420
421 /** @var bool */
422 private $edit;
423
424 /** @var int|false */
425 private $contentLength = false;
426
427 /**
428 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
429 */
430 private $enableApiEditOverride = false;
431
432 /**
433 * @var IContextSource
434 */
435 protected $context;
436
437 /**
438 * @var bool Whether an old revision is edited
439 */
440 private $isOldRev = false;
441
442 /**
443 * @var string|null What the user submitted in the 'wpUnicodeCheck' field
444 */
445 private $unicodeCheck;
446
447 /** @var callable|null */
448 private $editConflictHelperFactory = null;
449 private ?TextConflictHelper $editConflictHelper = null;
450
451 private IContentHandlerFactory $contentHandlerFactory;
452 private PermissionManager $permManager;
453 private RevisionStore $revisionStore;
454 private WikiPageFactory $wikiPageFactory;
455 private WatchlistManager $watchlistManager;
456 private UserNameUtils $userNameUtils;
457 private RedirectLookup $redirectLookup;
458 private UserOptionsLookup $userOptionsLookup;
459 private TempUserCreator $tempUserCreator;
460 private UserFactory $userFactory;
461 private IConnectionProvider $connectionProvider;
462 private BlockErrorFormatter $blockErrorFormatter;
463 private AuthManager $authManager;
464
465 /** @var User|null */
466 private $placeholderTempUser;
467
468 /** @var User|null */
469 private $unsavedTempUser;
470
471 /** @var User|null */
472 private $savedTempUser;
473
474 /** @var bool Whether temp user creation will be attempted */
475 private $tempUserCreateActive = false;
476
477 /** @var string|null If a temp user name was acquired, this is the name */
478 private $tempUserName;
479
480 /** @var bool Whether temp user creation was successful */
481 private $tempUserCreateDone = false;
482
483 /** @var bool Whether temp username acquisition failed (false indicates no failure or not attempted) */
484 private $unableToAcquireTempName = false;
485
486 private LinkRenderer $linkRenderer;
487 private LinkBatchFactory $linkBatchFactory;
488 private RestrictionStore $restrictionStore;
489 private CommentStore $commentStore;
490
491 /**
492 * @stable to call
493 * @param Article $article
494 */
495 public function __construct( Article $article ) {
496 $this->mArticle = $article;
497 $this->page = $article->getPage(); // model object
498 $this->mTitle = $article->getTitle();
499
500 // Make sure the local context is in sync with other member variables.
501 // Particularly make sure everything is using the same WikiPage instance.
502 // This should probably be the case in Article as well, but it's
503 // particularly important for EditPage, to make use of the in-place caching
504 // facility in WikiPage::prepareContentForEdit.
505 $this->context = new DerivativeContext( $article->getContext() );
506 $this->context->setWikiPage( $this->page );
507 $this->context->setTitle( $this->mTitle );
508
509 $this->contentModel = $this->mTitle->getContentModel();
510
511 $services = MediaWikiServices::getInstance();
512 $this->contentHandlerFactory = $services->getContentHandlerFactory();
513 $this->contentFormat = $this->contentHandlerFactory
514 ->getContentHandler( $this->contentModel )
515 ->getDefaultFormat();
516 $this->permManager = $services->getPermissionManager();
517 $this->revisionStore = $services->getRevisionStore();
518 $this->watchlistExpiryEnabled = $this->getContext()->getConfig() instanceof Config
519 && $this->getContext()->getConfig()->get( MainConfigNames::WatchlistExpiry );
520 $this->watchedItemStore = $services->getWatchedItemStore();
521 $this->wikiPageFactory = $services->getWikiPageFactory();
522 $this->watchlistManager = $services->getWatchlistManager();
523 $this->userNameUtils = $services->getUserNameUtils();
524 $this->redirectLookup = $services->getRedirectLookup();
525 $this->userOptionsLookup = $services->getUserOptionsLookup();
526 $this->tempUserCreator = $services->getTempUserCreator();
527 $this->userFactory = $services->getUserFactory();
528 $this->linkRenderer = $services->getLinkRenderer();
529 $this->linkBatchFactory = $services->getLinkBatchFactory();
530 $this->restrictionStore = $services->getRestrictionStore();
531 $this->commentStore = $services->getCommentStore();
532 $this->connectionProvider = $services->getConnectionProvider();
533 $this->blockErrorFormatter = $services->getFormatterFactory()
534 ->getBlockErrorFormatter( $this->context );
535 $this->authManager = $services->getAuthManager();
536
537 // XXX: Restore this deprecation as soon as TwoColConflict is fixed (T305028)
538 // $this->deprecatePublicProperty( 'textbox2', '1.38', __CLASS__ );
539 }
540
541 /**
542 * @return Article
543 */
544 public function getArticle() {
545 return $this->mArticle;
546 }
547
548 /**
549 * @since 1.28
550 * @return IContextSource
551 */
552 public function getContext() {
553 return $this->context;
554 }
555
556 /**
557 * @since 1.19
558 * @return Title
559 */
560 public function getTitle() {
561 return $this->mTitle;
562 }
563
564 /**
565 * @param Title|null $title
566 */
567 public function setContextTitle( $title ) {
568 $this->mContextTitle = $title;
569 }
570
571 /**
572 * @throws RuntimeException if no context title was set
573 * @return Title
574 */
575 public function getContextTitle() {
576 if ( $this->mContextTitle === null ) {
577 throw new RuntimeException( "EditPage does not have a context title set" );
578 } else {
579 return $this->mContextTitle;
580 }
581 }
582
583 /**
584 * Returns if the given content model is editable.
585 *
586 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
587 * @return bool
588 * @throws MWUnknownContentModelException If $modelId has no known handler
589 */
590 private function isSupportedContentModel( string $modelId ): bool {
591 return $this->enableApiEditOverride === true ||
592 $this->contentHandlerFactory->getContentHandler( $modelId )->supportsDirectEditing();
593 }
594
595 /**
596 * Allow editing of content that supports API direct editing, but not general
597 * direct editing. Set to false by default.
598 * @internal Must only be used by ApiEditPage
599 *
600 * @param bool $enableOverride
601 */
602 public function setApiEditOverride( $enableOverride ) {
603 $this->enableApiEditOverride = $enableOverride;
604 }
605
606 /**
607 * This is the function that gets called for "action=edit". It
608 * sets up various member variables, then passes execution to
609 * another function, usually showEditForm()
610 *
611 * The edit form is self-submitting, so that when things like
612 * preview and edit conflicts occur, we get the same form back
613 * with the extra stuff added. Only when the final submission
614 * is made and all is well do we actually save and redirect to
615 * the newly-edited page.
616 */
617 public function edit() {
618 // Allow extensions to modify/prevent this form or submission
619 if ( !$this->getHookRunner()->onAlternateEdit( $this ) ) {
620 return;
621 }
622
623 wfDebug( __METHOD__ . ": enter" );
624
625 $request = $this->context->getRequest();
626 // If they used redlink=1 and the page exists, redirect to the main article
627 if ( $request->getBool( 'redlink' ) && $this->mTitle->exists() ) {
628 $this->context->getOutput()->redirect( $this->mTitle->getFullURL() );
629 return;
630 }
631
632 $this->importFormData( $request );
633 $this->firsttime = false;
634
635 $readOnlyMode = MediaWikiServices::getInstance()->getReadOnlyMode();
636 if ( $this->save && $readOnlyMode->isReadOnly() ) {
637 // Force preview
638 $this->save = false;
639 $this->preview = true;
640 }
641
642 if ( $this->save ) {
643 $this->formtype = 'save';
644 } elseif ( $this->preview ) {
645 $this->formtype = 'preview';
646 } elseif ( $this->diff ) {
647 $this->formtype = 'diff';
648 } else { # First time through
649 $this->firsttime = true;
650 if ( $this->previewOnOpen() ) {
651 $this->formtype = 'preview';
652 } else {
653 $this->formtype = 'initial';
654 }
655 }
656
657 // Check permissions after possibly creating a placeholder temp user.
658 // This allows anonymous users to edit via a temporary account, if the site is
659 // configured to (1) disallow anonymous editing and (2) autocreate temporary
660 // accounts on edit.
661 $this->unableToAcquireTempName = !$this->maybeActivateTempUserCreate( !$this->firsttime )->isOK();
662
663 $status = $this->getEditPermissionStatus(
664 $this->save ? PermissionManager::RIGOR_SECURE : PermissionManager::RIGOR_FULL
665 );
666 if ( !$status->isGood() ) {
667 wfDebug( __METHOD__ . ": User can't edit" );
668
669 $user = $this->context->getUser();
670 if ( $user->getBlock() && !$readOnlyMode->isReadOnly() ) {
671 // Auto-block user's IP if the account was "hard" blocked
672 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
673 $user->spreadAnyEditBlock();
674 } );
675 }
676 $this->displayPermissionStatus( $status );
677
678 return;
679 }
680
681 $revRecord = $this->mArticle->fetchRevisionRecord();
682 // Disallow editing revisions with content models different from the current one
683 // Undo edits being an exception in order to allow reverting content model changes.
684 $revContentModel = $revRecord ?
685 $revRecord->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel() :
686 false;
687 if ( $revContentModel && $revContentModel !== $this->contentModel ) {
688 $prevRevRecord = null;
689 $prevContentModel = false;
690 if ( $this->undidRev ) {
691 $undidRevRecord = $this->revisionStore
692 ->getRevisionById( $this->undidRev );
693 $prevRevRecord = $undidRevRecord ?
694 $this->revisionStore->getPreviousRevision( $undidRevRecord ) :
695 null;
696
697 $prevContentModel = $prevRevRecord ?
698 $prevRevRecord
699 ->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )
700 ->getModel() :
701 '';
702 }
703
704 if ( !$this->undidRev
705 || !$prevRevRecord
706 || $prevContentModel !== $this->contentModel
707 ) {
708 $this->displayViewSourcePage(
709 $this->getContentObject(),
710 $this->context->msg(
711 'contentmodelediterror',
712 $revContentModel,
713 $this->contentModel
714 )->plain()
715 );
716 return;
717 }
718 }
719
720 $this->isConflict = false;
721
722 # Attempt submission here. This will check for edit conflicts,
723 # and redundantly check for locked database, blocked IPs, etc.
724 # that edit() already checked just in case someone tries to sneak
725 # in the back door with a hand-edited submission URL.
726
727 if ( $this->formtype === 'save' ) {
728 $resultDetails = null;
729 $status = $this->attemptSave( $resultDetails );
730 if ( !$this->handleStatus( $status, $resultDetails ) ) {
731 return;
732 }
733 }
734
735 # First time through: get contents, set time for conflict
736 # checking, etc.
737 if ( $this->formtype === 'initial' || $this->firsttime ) {
738 if ( !$this->initialiseForm() ) {
739 return;
740 }
741
742 if ( $this->mTitle->getArticleID() ) {
743 $this->getHookRunner()->onEditFormInitialText( $this );
744 }
745 }
746
747 // If we're displaying an old revision, and there are differences between it and the
748 // current revision outside the main slot, then we can't allow the old revision to be
749 // editable, as what would happen to the non-main-slot data if someone saves the old
750 // revision is undefined.
751 // When this is the case, display a read-only version of the page instead, with a link
752 // to a diff page from which the old revision can be restored
753 $curRevisionRecord = $this->page->getRevisionRecord();
754 if ( $curRevisionRecord
755 && $revRecord
756 && $curRevisionRecord->getId() !== $revRecord->getId()
757 && ( WikiPage::hasDifferencesOutsideMainSlot(
758 $revRecord,
759 $curRevisionRecord
760 ) || !$this->isSupportedContentModel(
761 $revRecord->getSlot(
762 SlotRecord::MAIN,
763 RevisionRecord::RAW
764 )->getModel()
765 ) )
766 ) {
767 $restoreLink = $this->mTitle->getFullURL(
768 [
769 'action' => 'mcrrestore',
770 'restore' => $revRecord->getId(),
771 ]
772 );
773 $this->displayViewSourcePage(
774 $this->getContentObject(),
775 $this->context->msg(
776 'nonmain-slot-differences-therefore-readonly',
777 $restoreLink
778 )->plain()
779 );
780 return;
781 }
782
783 $this->showEditForm();
784 }
785
786 /**
787 * Check the configuration and current user and enable automatic temporary
788 * user creation if possible.
789 *
790 * @param bool $doAcquire Whether to acquire a name for the temporary account
791 *
792 * @since 1.39
793 * @return Status Will return a fatal status if $doAcquire was true and the acquire failed.
794 */
795 public function maybeActivateTempUserCreate( $doAcquire ): Status {
796 if ( $this->tempUserCreateActive ) {
797 // Already done
798 return Status::newGood();
799 }
800 $user = $this->context->getUser();
801 if ( $this->tempUserCreator->shouldAutoCreate( $user, 'edit' ) ) {
802 if ( $doAcquire ) {
803 $name = $this->tempUserCreator->acquireAndStashName(
804 $this->context->getRequest()->getSession() );
805 if ( $name === null ) {
806 $status = Status::newFatal( 'temp-user-unable-to-acquire' );
807 $status->value = self::AS_UNABLE_TO_ACQUIRE_TEMP_ACCOUNT;
808 return $status;
809 }
810 $this->unsavedTempUser = $this->userFactory->newUnsavedTempUser( $name );
811 $this->tempUserName = $name;
812 } else {
813 $this->placeholderTempUser = $this->userFactory->newTempPlaceholder();
814 }
815 $this->tempUserCreateActive = true;
816 }
817 return Status::newGood();
818 }
819
820 /**
821 * If automatic user creation is enabled, create the user.
822 *
823 * This is a helper for internalAttemptSavePrivate().
824 *
825 * If the edit is a null edit, the user will not be created.
826 *
827 * @return Status
828 */
829 private function createTempUser(): Status {
830 if ( !$this->tempUserCreateActive ) {
831 return Status::newGood();
832 }
833 $status = $this->tempUserCreator->create(
834 $this->tempUserName,
835 $this->context->getRequest()
836 );
837 if ( $status->isOK() ) {
838 $this->placeholderTempUser = null;
839 $this->unsavedTempUser = null;
840 $this->savedTempUser = $status->getUser();
841 $this->authManager->setRequestContextUserFromSessionUser();
842 $this->tempUserCreateDone = true;
843 }
844 return $status;
845 }
846
847 /**
848 * Get the authority for permissions purposes.
849 *
850 * On an initial edit page GET request, if automatic temporary user creation
851 * is enabled, this may be a placeholder user with a fixed name. Such users
852 * are unsuitable for anything that uses or exposes the name, like
853 * throttling. The only thing a placeholder user is good for is fooling the
854 * permissions system into allowing edits by anons.
855 *
856 * @return Authority
857 */
858 private function getAuthority(): Authority {
859 return $this->getUserForPermissions();
860 }
861
862 /**
863 * Get the user for permissions purposes, with declared type User instead
864 * of Authority for compatibility with PermissionManager.
865 *
866 * @return User
867 */
868 private function getUserForPermissions() {
869 if ( $this->savedTempUser ) {
870 return $this->savedTempUser;
871 } elseif ( $this->unsavedTempUser ) {
872 return $this->unsavedTempUser;
873 } elseif ( $this->placeholderTempUser ) {
874 return $this->placeholderTempUser;
875 } else {
876 return $this->context->getUser();
877 }
878 }
879
880 /**
881 * Get the user for preview or PST purposes. During the temporary user
882 * creation flow this may be an unsaved temporary user.
883 *
884 * @return User
885 */
886 private function getUserForPreview() {
887 if ( $this->savedTempUser ) {
888 return $this->savedTempUser;
889 } elseif ( $this->unsavedTempUser ) {
890 return $this->unsavedTempUser;
891 } elseif ( $this->firsttime && $this->placeholderTempUser ) {
892 // Mostly a GET request and no temp user was aquired,
893 // but needed for pst or content transform for preview,
894 // fallback to a placeholder for this situation (T330943)
895 return $this->placeholderTempUser;
896 } elseif ( $this->tempUserCreateActive ) {
897 throw new BadMethodCallException(
898 "Can't use the request user for preview with IP masking enabled" );
899 } else {
900 return $this->context->getUser();
901 }
902 }
903
904 /**
905 * Get the user suitable for permanent attribution in the database. This
906 * asserts that an anonymous user won't be used in IP masking mode.
907 *
908 * @return User
909 */
910 private function getUserForSave() {
911 if ( $this->savedTempUser ) {
912 return $this->savedTempUser;
913 } elseif ( $this->tempUserCreateActive ) {
914 throw new BadMethodCallException(
915 "Can't use the request user for storage with IP masking enabled" );
916 } else {
917 return $this->context->getUser();
918 }
919 }
920
921 /**
922 * @param string $rigor PermissionManager::RIGOR_ constant
923 * @return PermissionStatus
924 */
925 private function getEditPermissionStatus( string $rigor = PermissionManager::RIGOR_SECURE ): PermissionStatus {
926 $user = $this->getUserForPermissions();
927 return $this->permManager->getPermissionStatus(
928 'edit',
929 $user,
930 $this->mTitle,
931 $rigor
932 );
933 }
934
935 /**
936 * Display a permissions error page, like OutputPage::showPermissionStatus(),
937 * but with the following differences:
938 * - If redlink=1, the user will be redirected to the page
939 * - If there is content to display or the error occurs while either saving,
940 * previewing or showing the difference, it will be a
941 * "View source for ..." page displaying the source code after the error message.
942 *
943 * @param PermissionStatus $status Permissions errors
944 * @throws PermissionsError
945 */
946 private function displayPermissionStatus( PermissionStatus $status ): void {
947 $out = $this->context->getOutput();
948 if ( $this->context->getRequest()->getBool( 'redlink' ) ) {
949 // The edit page was reached via a red link.
950 // Redirect to the article page and let them click the edit tab if
951 // they really want a permission error.
952 $out->redirect( $this->mTitle->getFullURL() );
953 return;
954 }
955
956 $content = $this->getContentObject();
957
958 // Use the normal message if there's nothing to display
959 // We used to only do this if $this->firsttime was truthy, and there was no content
960 // or the content was empty, but sometimes there was no content even if it not the
961 // first time, we can't use displayViewSourcePage if there is no content (T281400)
962 if ( !$content || ( $this->firsttime && $content->isEmpty() ) ) {
963 $action = $this->mTitle->exists() ? 'edit' :
964 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
965 throw new PermissionsError( $action, $status );
966 }
967
968 $this->displayViewSourcePage(
969 $content,
970 $out->formatPermissionStatus( $status, 'edit' )
971 );
972 }
973
974 /**
975 * Display a read-only View Source page
976 * @param Content $content
977 * @param string $errorMessage additional wikitext error message to display
978 */
979 private function displayViewSourcePage( Content $content, string $errorMessage ): void {
980 $out = $this->context->getOutput();
981 $this->getHookRunner()->onEditPage__showReadOnlyForm_initial( $this, $out );
982
983 $out->setRobotPolicy( 'noindex,nofollow' );
984 $out->setPageTitleMsg( $this->context->msg(
985 'viewsource-title'
986 )->plaintextParams(
987 $this->getContextTitle()->getPrefixedText()
988 ) );
989 $out->addBacklinkSubtitle( $this->getContextTitle() );
990 $out->addHTML( $this->editFormPageTop );
991 $out->addHTML( $this->editFormTextTop );
992
993 if ( $errorMessage !== '' ) {
994 $out->addWikiTextAsInterface( $errorMessage );
995 $out->addHTML( "<hr />\n" );
996 }
997
998 # If the user made changes, preserve them when showing the markup
999 # (This happens when a user is blocked during edit, for instance)
1000 if ( !$this->firsttime ) {
1001 $text = $this->textbox1;
1002 $out->addWikiMsg( 'viewyourtext' );
1003 } else {
1004 try {
1005 $text = $this->toEditText( $content );
1006 } catch ( MWException $e ) {
1007 # Serialize using the default format if the content model is not supported
1008 # (e.g. for an old revision with a different model)
1009 $text = $content->serialize();
1010 }
1011 $out->addWikiMsg( 'viewsourcetext' );
1012 }
1013
1014 $out->addHTML( $this->editFormTextBeforeContent );
1015 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
1016 $out->addHTML( $this->editFormTextAfterContent );
1017
1018 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
1019
1020 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
1021
1022 $out->addHTML( $this->editFormTextBottom );
1023 if ( $this->mTitle->exists() ) {
1024 $out->returnToMain( null, $this->mTitle );
1025 }
1026 }
1027
1028 /**
1029 * Should we show a preview when the edit form is first shown?
1030 *
1031 * @return bool
1032 */
1033 protected function previewOnOpen() {
1034 $config = $this->context->getConfig();
1035 $previewOnOpenNamespaces = $config->get( MainConfigNames::PreviewOnOpenNamespaces );
1036 $request = $this->context->getRequest();
1037 if ( $config->get( MainConfigNames::RawHtml ) ) {
1038 // If raw HTML is enabled, disable preview on open
1039 // since it has to be posted with a token for
1040 // security reasons
1041 return false;
1042 }
1043 if ( $request->getVal( 'preview' ) === 'yes' ) {
1044 // Explicit override from request
1045 return true;
1046 } elseif ( $request->getVal( 'preview' ) === 'no' ) {
1047 // Explicit override from request
1048 return false;
1049 } elseif ( $this->section === 'new' ) {
1050 // Nothing *to* preview for new sections
1051 return false;
1052 } elseif ( ( $request->getCheck( 'preload' ) || $this->mTitle->exists() )
1053 && $this->userOptionsLookup->getOption( $this->context->getUser(), 'previewonfirst' )
1054 ) {
1055 // Standard preference behavior
1056 return true;
1057 } elseif ( !$this->mTitle->exists()
1058 && isset( $previewOnOpenNamespaces[$this->mTitle->getNamespace()] )
1059 && $previewOnOpenNamespaces[$this->mTitle->getNamespace()]
1060 ) {
1061 // Categories are special
1062 return true;
1063 } else {
1064 return false;
1065 }
1066 }
1067
1068 /**
1069 * Section editing is supported when the page content model allows
1070 * section edit and we are editing current revision.
1071 *
1072 * @return bool True if this edit page supports sections, false otherwise.
1073 */
1074 private function isSectionEditSupported(): bool {
1075 $currentRev = $this->page->getRevisionRecord();
1076
1077 // $currentRev is null for non-existing pages, use the page default content model.
1078 $revContentModel = $currentRev
1079 ? $currentRev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel()
1080 : $this->page->getContentModel();
1081
1082 return (
1083 ( $this->mArticle->getRevIdFetched() === $this->page->getLatest() ) &&
1084 $this->contentHandlerFactory->getContentHandler( $revContentModel )->supportsSections()
1085 );
1086 }
1087
1088 /**
1089 * This function collects the form data and uses it to populate various member variables.
1090 * @param WebRequest &$request
1091 * @throws ErrorPageError
1092 */
1093 public function importFormData( &$request ) {
1094 # Section edit can come from either the form or a link
1095 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section', '' ) );
1096
1097 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
1098 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1099 }
1100
1101 $this->isNew = !$this->mTitle->exists() || $this->section === 'new';
1102
1103 if ( $request->wasPosted() ) {
1104 $this->importFormDataPosted( $request );
1105 } else {
1106 # Not a posted form? Start with nothing.
1107 wfDebug( __METHOD__ . ": Not a posted form." );
1108 $this->textbox1 = '';
1109 $this->summary = '';
1110 $this->sectiontitle = null;
1111 $this->edittime = '';
1112 $this->editRevId = null;
1113 $this->starttime = wfTimestampNow();
1114 $this->edit = false;
1115 $this->preview = false;
1116 $this->save = false;
1117 $this->diff = false;
1118 $this->minoredit = false;
1119 // Watch may be overridden by request parameters
1120 $this->watchthis = $request->getBool( 'watchthis', false );
1121 if ( $this->watchlistExpiryEnabled ) {
1122 $this->watchlistExpiry = null;
1123 }
1124 $this->recreate = false;
1125
1126 // When creating a new section, we can preload a section title by passing it as the
1127 // preloadtitle parameter in the URL (T15100)
1128 if ( $this->section === 'new' && $request->getCheck( 'preloadtitle' ) ) {
1129 $this->sectiontitle = $request->getVal( 'preloadtitle' );
1130 $this->setNewSectionSummary();
1131 } elseif ( $this->section !== 'new' && $request->getVal( 'summary' ) !== '' ) {
1132 $this->summary = $request->getText( 'summary' );
1133 if ( $this->summary !== '' ) {
1134 // If a summary has been preset using &summary= we don't want to prompt for
1135 // a different summary. Only prompt for a summary if the summary is blanked.
1136 // (T19416)
1137 $this->autoSumm = md5( '' );
1138 }
1139 }
1140
1141 if ( $request->getVal( 'minor' ) ) {
1142 $this->minoredit = true;
1143 }
1144 }
1145
1146 $this->oldid = $request->getInt( 'oldid' );
1147 $this->parentRevId = $request->getInt( 'parentRevId' );
1148
1149 $this->markAsBot = $request->getBool( 'bot', true );
1150 $this->nosummary = $request->getBool( 'nosummary' );
1151
1152 // May be overridden by revision.
1153 $this->contentModel = $request->getText( 'model', $this->contentModel );
1154 // May be overridden by revision.
1155 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1156
1157 try {
1158 $handler = $this->contentHandlerFactory->getContentHandler( $this->contentModel );
1159 } catch ( MWUnknownContentModelException $e ) {
1160 throw new ErrorPageError(
1161 'editpage-invalidcontentmodel-title',
1162 'editpage-invalidcontentmodel-text',
1163 [ wfEscapeWikiText( $this->contentModel ) ]
1164 );
1165 }
1166
1167 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1168 throw new ErrorPageError(
1169 'editpage-notsupportedcontentformat-title',
1170 'editpage-notsupportedcontentformat-text',
1171 [
1172 wfEscapeWikiText( $this->contentFormat ),
1173 wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1174 ]
1175 );
1176 }
1177
1178 // Allow extensions to modify form data
1179 $this->getHookRunner()->onEditPage__importFormData( $this, $request );
1180 }
1181
1182 /**
1183 * @param WebRequest $request
1184 */
1185 private function importFormDataPosted( WebRequest $request ): void {
1186 # These fields need to be checked for encoding.
1187 # Also remove trailing whitespace, but don't remove _initial_
1188 # whitespace from the text boxes. This may be significant formatting.
1189 $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
1190 if ( !$request->getCheck( 'wpTextbox2' ) ) {
1191 // Skip this if wpTextbox2 has input, it indicates that we came
1192 // from a conflict page with raw page text, not a custom form
1193 // modified by subclasses
1194 $textbox1 = $this->importContentFormData( $request );
1195 if ( $textbox1 !== null ) {
1196 $this->textbox1 = $textbox1;
1197 }
1198 }
1199
1200 $this->unicodeCheck = $request->getText( 'wpUnicodeCheck' );
1201
1202 if ( $this->section === 'new' ) {
1203 # Allow setting sectiontitle different from the edit summary.
1204 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
1205 # currently doing double duty as both edit summary and section title. Right now this
1206 # is just to allow API edits to work around this limitation, but this should be
1207 # incorporated into the actual edit form when EditPage is rewritten (T20654, T28312).
1208 if ( $request->getCheck( 'wpSectionTitle' ) ) {
1209 $this->sectiontitle = $request->getText( 'wpSectionTitle' );
1210 if ( $request->getCheck( 'wpSummary' ) ) {
1211 $this->summary = $request->getText( 'wpSummary' );
1212 }
1213 } else {
1214 $this->sectiontitle = $request->getText( 'wpSummary' );
1215 }
1216 } else {
1217 $this->sectiontitle = null;
1218 $this->summary = $request->getText( 'wpSummary' );
1219 }
1220
1221 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
1222 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
1223 # section titles. (T3600)
1224 # It is weird to modify 'sectiontitle', even when it is provided when using the API, but API
1225 # users have come to rely on it: https://github.com/wikimedia-gadgets/twinkle/issues/1625
1226 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
1227 if ( $this->sectiontitle !== null ) {
1228 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
1229 }
1230
1231 // @phan-suppress-next-line PhanSuspiciousValueComparison
1232 if ( $this->section === 'new' ) {
1233 $this->setNewSectionSummary();
1234 }
1235
1236 $this->edittime = $request->getVal( 'wpEdittime' );
1237 $this->editRevId = $request->getIntOrNull( 'editRevId' );
1238 $this->starttime = $request->getVal( 'wpStarttime' );
1239
1240 $undidRev = $request->getInt( 'wpUndidRevision' );
1241 if ( $undidRev ) {
1242 $this->undidRev = $undidRev;
1243 }
1244 $undoAfter = $request->getInt( 'wpUndoAfter' );
1245 if ( $undoAfter ) {
1246 $this->undoAfter = $undoAfter;
1247 }
1248
1249 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
1250
1251 if ( $this->textbox1 === '' && !$request->getCheck( 'wpTextbox1' ) ) {
1252 // wpTextbox1 field is missing, possibly due to being "too big"
1253 // according to some filter rules that may have been configured
1254 // for security reasons.
1255 $this->incompleteForm = true;
1256 } else {
1257 // If we receive the last parameter of the request, we can fairly
1258 // claim the POST request has not been truncated.
1259 $this->incompleteForm = !$request->getVal( 'wpUltimateParam' );
1260 }
1261 if ( $this->incompleteForm ) {
1262 # If the form is incomplete, force to preview.
1263 wfDebug( __METHOD__ . ": Form data appears to be incomplete" );
1264 wfDebug( "POST DATA: " . var_export( $request->getPostValues(), true ) );
1265 $this->preview = true;
1266 } else {
1267 $this->preview = $request->getCheck( 'wpPreview' );
1268 $this->diff = $request->getCheck( 'wpDiff' );
1269
1270 // Remember whether a save was requested, so we can indicate
1271 // if we forced preview due to session failure.
1272 $this->mTriedSave = !$this->preview;
1273
1274 if ( $this->tokenOk( $request ) ) {
1275 # Some browsers will not report any submit button
1276 # if the user hits enter in the comment box.
1277 # The unmarked state will be assumed to be a save,
1278 # if the form seems otherwise complete.
1279 wfDebug( __METHOD__ . ": Passed token check." );
1280 } elseif ( $this->diff ) {
1281 # Failed token check, but only requested "Show Changes".
1282 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested." );
1283 } else {
1284 # Page might be a hack attempt posted from
1285 # an external site. Preview instead of saving.
1286 wfDebug( __METHOD__ . ": Failed token check; forcing preview" );
1287 $this->preview = true;
1288 }
1289 }
1290 $this->save = !$this->preview && !$this->diff;
1291 if ( !$this->edittime || !preg_match( '/^\d{14}$/', $this->edittime ) ) {
1292 $this->edittime = null;
1293 }
1294
1295 if ( !$this->starttime || !preg_match( '/^\d{14}$/', $this->starttime ) ) {
1296 $this->starttime = null;
1297 }
1298
1299 $this->recreate = $request->getCheck( 'wpRecreate' );
1300
1301 $user = $this->context->getUser();
1302
1303 $this->minoredit = $request->getCheck( 'wpMinoredit' );
1304 $this->watchthis = $request->getCheck( 'wpWatchthis' );
1305 $expiry = $request->getText( 'wpWatchlistExpiry' );
1306 if ( $this->watchlistExpiryEnabled && $expiry !== '' ) {
1307 // This parsing of the user-posted expiry is done for both preview and saving. This
1308 // is necessary because ApiEditPage uses preview when it saves (yuck!). Note that it
1309 // only works because the unnormalized value is retrieved again below in
1310 // getCheckboxesDefinitionForWatchlist().
1311 $expiry = ExpiryDef::normalizeExpiry( $expiry, TS_ISO_8601 );
1312 if ( $expiry !== false ) {
1313 $this->watchlistExpiry = $expiry;
1314 }
1315 }
1316
1317 # Don't force edit summaries when a user is editing their own user or talk page
1318 if ( ( $this->mTitle->getNamespace() === NS_USER || $this->mTitle->getNamespace() === NS_USER_TALK )
1319 && $this->mTitle->getText() === $user->getName()
1320 ) {
1321 $this->allowBlankSummary = true;
1322 } else {
1323 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
1324 || !$this->userOptionsLookup->getOption( $user, 'forceeditsummary' );
1325 }
1326
1327 $this->autoSumm = $request->getText( 'wpAutoSummary' );
1328
1329 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
1330 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
1331
1332 $changeTags = $request->getVal( 'wpChangeTags' );
1333 if ( $changeTags === null || $changeTags === '' ) {
1334 $this->changeTags = [];
1335 } else {
1336 $this->changeTags = array_filter(
1337 array_map(
1338 'trim',
1339 explode( ',', $changeTags )
1340 )
1341 );
1342 }
1343 }
1344
1345 /**
1346 * Subpage overridable method for extracting the page content data from the
1347 * posted form to be placed in $this->textbox1, if using customized input
1348 * this method should be overridden and return the page text that will be used
1349 * for saving, preview parsing and so on...
1350 *
1351 * @param WebRequest &$request
1352 * @return string|null
1353 */
1354 protected function importContentFormData( &$request ) {
1355 return null; // Don't do anything, EditPage already extracted wpTextbox1
1356 }
1357
1358 /**
1359 * Initialise form fields in the object
1360 * Called on the first invocation, e.g. when a user clicks an edit link
1361 * @return bool If the requested section is valid
1362 */
1363 private function initialiseForm(): bool {
1364 $this->edittime = $this->page->getTimestamp();
1365 $this->editRevId = $this->page->getLatest();
1366
1367 $dummy = $this->contentHandlerFactory
1368 ->getContentHandler( $this->contentModel )
1369 ->makeEmptyContent();
1370 $content = $this->getContentObject( $dummy ); # TODO: track content object?!
1371 if ( $content === $dummy ) { // Invalid section
1372 $this->noSuchSectionPage();
1373 return false;
1374 }
1375
1376 if ( !$content ) {
1377 $out = $this->context->getOutput();
1378 $this->editFormPageTop .= Html::errorBox(
1379 $out->parseAsInterface( $this->context->msg( 'missing-revision-content',
1380 $this->oldid,
1381 Message::plaintextParam( $this->mTitle->getPrefixedText() )
1382 ) )
1383 );
1384 } elseif ( !$this->isSupportedContentModel( $content->getModel() ) ) {
1385 $modelMsg = $this->getContext()->msg( 'content-model-' . $content->getModel() );
1386 $modelName = $modelMsg->exists() ? $modelMsg->text() : $content->getModel();
1387
1388 $out = $this->context->getOutput();
1389 $out->showErrorPage(
1390 'modeleditnotsupported-title',
1391 'modeleditnotsupported-text',
1392 [ $modelName ]
1393 );
1394 return false;
1395 }
1396
1397 try {
1398 $this->textbox1 = $this->toEditText( $content );
1399 } catch ( MWException ) {
1400 // T391524: If the content format isn't supported, Content::serialize throws an exception
1401 $this->textbox1 = $content->serialize();
1402 }
1403
1404 $user = $this->context->getUser();
1405 // activate checkboxes if user wants them to be always active
1406 # Sort out the "watch" checkbox
1407 if ( $this->userOptionsLookup->getOption( $user, 'watchdefault' ) ) {
1408 # Watch all edits
1409 $this->watchthis = true;
1410 } elseif ( $this->userOptionsLookup->getOption( $user, 'watchcreations' ) && !$this->mTitle->exists() ) {
1411 # Watch creations
1412 $this->watchthis = true;
1413 } elseif ( $this->watchlistManager->isWatched( $user, $this->mTitle ) ) {
1414 # Already watched
1415 $this->watchthis = true;
1416 }
1417 if ( $this->watchthis && $this->watchlistExpiryEnabled ) {
1418 $watchedItem = $this->watchedItemStore->getWatchedItem( $user, $this->getTitle() );
1419 $this->watchlistExpiry = $watchedItem ? $watchedItem->getExpiry() : null;
1420 }
1421 if ( !$this->isNew && $this->userOptionsLookup->getOption( $user, 'minordefault' ) ) {
1422 $this->minoredit = true;
1423 }
1424 if ( $this->textbox1 === false ) {
1425 return false;
1426 }
1427 return true;
1428 }
1429
1430 /**
1431 * @param Content|null $defaultContent The default value to return
1432 * @return Content|false|null Content on success, $defaultContent for invalid sections
1433 * @since 1.21
1434 */
1435 protected function getContentObject( $defaultContent = null ) {
1436 $services = MediaWikiServices::getInstance();
1437 $request = $this->context->getRequest();
1438
1439 $content = false;
1440
1441 // For non-existent articles and new sections, use preload text if any.
1442 if ( !$this->mTitle->exists() || $this->section === 'new' ) {
1443 $content = $services->getPreloadedContentBuilder()->getPreloadedContent(
1444 $this->mTitle->toPageIdentity(),
1445 $this->context->getUser(),
1446 $request->getVal( 'preload' ),
1447 $request->getArray( 'preloadparams', [] ),
1448 $request->getVal( 'section' )
1449 );
1450 // For existing pages, get text based on "undo" or section parameters.
1451 } elseif ( $this->section !== '' ) {
1452 // Get section edit text (returns $def_text for invalid sections)
1453 $orig = $this->getOriginalContent( $this->getAuthority() );
1454 $content = $orig ? $orig->getSection( $this->section ) : null;
1455
1456 if ( !$content ) {
1457 $content = $defaultContent;
1458 }
1459 } else {
1460 $undoafter = $request->getInt( 'undoafter' );
1461 $undo = $request->getInt( 'undo' );
1462
1463 if ( $undo > 0 && $undoafter > 0 ) {
1464 // The use of getRevisionByTitle() is intentional, as allowing access to
1465 // arbitrary revisions on arbitrary pages bypass partial visibility restrictions (T297322).
1466 $undorev = $this->revisionStore->getRevisionByTitle( $this->mTitle, $undo );
1467 $oldrev = $this->revisionStore->getRevisionByTitle( $this->mTitle, $undoafter );
1468 $undoMsg = null;
1469
1470 # Make sure it's the right page,
1471 # the revisions exist and they were not deleted.
1472 # Otherwise, $content will be left as-is.
1473 if ( $undorev !== null && $oldrev !== null &&
1474 !$undorev->isDeleted( RevisionRecord::DELETED_TEXT ) &&
1475 !$oldrev->isDeleted( RevisionRecord::DELETED_TEXT )
1476 ) {
1477 if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
1478 || !$this->isSupportedContentModel(
1479 $oldrev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel()
1480 )
1481 ) {
1482 // Hack for undo while EditPage can't handle multi-slot editing
1483 $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [
1484 'action' => 'mcrundo',
1485 'undo' => $undo,
1486 'undoafter' => $undoafter,
1487 ] ) );
1488 return false;
1489 } else {
1490 $content = $this->getUndoContent( $undorev, $oldrev, $undoMsg );
1491 }
1492
1493 if ( $undoMsg === null ) {
1494 $oldContent = $this->page->getContent( RevisionRecord::RAW );
1495 $parserOptions = ParserOptions::newFromUserAndLang(
1496 $this->getUserForPreview(),
1497 $services->getContentLanguage()
1498 );
1499 $contentTransformer = $services->getContentTransformer();
1500 $newContent = $contentTransformer->preSaveTransform(
1501 $content, $this->mTitle, $this->getUserForPreview(), $parserOptions
1502 );
1503
1504 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1505 // The undo may change content
1506 // model if its reverting the top
1507 // edit. This can result in
1508 // mismatched content model/format.
1509 $this->contentModel = $newContent->getModel();
1510 $oldMainSlot = $oldrev->getSlot(
1511 SlotRecord::MAIN,
1512 RevisionRecord::RAW
1513 );
1514 $this->contentFormat = $oldMainSlot->getFormat();
1515 if ( $this->contentFormat === null ) {
1516 $this->contentFormat = $this->contentHandlerFactory
1517 ->getContentHandler( $oldMainSlot->getModel() )
1518 ->getDefaultFormat();
1519 }
1520 }
1521
1522 if ( $newContent->equals( $oldContent ) ) {
1523 # Tell the user that the undo results in no change,
1524 # i.e. the revisions were already undone.
1525 $undoMsg = 'nochange';
1526 $content = false;
1527 } else {
1528 # Inform the user of our success and set an automatic edit summary
1529 $undoMsg = 'success';
1530 $this->generateUndoEditSummary( $oldrev, $undo, $undorev, $services );
1531 $this->undidRev = $undo;
1532 $this->undoAfter = $undoafter;
1533 $this->formtype = 'diff';
1534 }
1535 }
1536 } else {
1537 // Failed basic checks.
1538 // Older revisions may have been removed since the link
1539 // was created, or we may simply have got bogus input.
1540 $undoMsg = 'norev';
1541 }
1542
1543 $out = $this->context->getOutput();
1544 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1545 // undo-nochange.
1546 $class = ( $undoMsg === 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1547 $this->editFormPageTop .= Html::rawElement(
1548 'div',
1549 [ 'class' => $class ],
1550 $out->parseAsInterface(
1551 $this->context->msg( 'undo-' . $undoMsg )->plain()
1552 )
1553 );
1554 }
1555
1556 if ( $content === false ) {
1557 $content = $this->getOriginalContent( $this->getAuthority() );
1558 }
1559 }
1560
1561 return $content;
1562 }
1563
1564 /**
1565 * When using the "undo" action, generate a default edit summary and save it
1566 * to $this->summary
1567 *
1568 * @param RevisionRecord|null $oldrev The revision in the URI "undoafter" field
1569 * @param int $undo The integer in the URI "undo" field
1570 * @param RevisionRecord|null $undorev The revision in the URI "undo" field
1571 * @param MediaWikiServices $services Service container
1572 * @return void
1573 */
1574 private function generateUndoEditSummary( ?RevisionRecord $oldrev, int $undo,
1575 ?RevisionRecord $undorev, MediaWikiServices $services
1576 ) {
1577 // If we just undid one rev, use an autosummary
1578 $firstrev = $this->revisionStore->getNextRevision( $oldrev );
1579 if ( $firstrev && $firstrev->getId() == $undo ) {
1580 $userText = $undorev->getUser() ?
1581 $undorev->getUser()->getName() :
1582 '';
1583 if ( $userText === '' ) {
1584 $undoSummary = $this->context->msg(
1585 'undo-summary-username-hidden',
1586 $undo
1587 )->inContentLanguage()->text();
1588 // Handle external users (imported revisions)
1589 } elseif ( ExternalUserNames::isExternal( $userText ) ) {
1590 $userLinkTitle = ExternalUserNames::getUserLinkTitle( $userText );
1591 if ( $userLinkTitle ) {
1592 $userLink = $userLinkTitle->getPrefixedText();
1593 $undoSummary = $this->context->msg(
1594 'undo-summary-import',
1595 $undo,
1596 $userLink,
1597 $userText
1598 )->inContentLanguage()->text();
1599 } else {
1600 $undoSummary = $this->context->msg(
1601 'undo-summary-import2',
1602 $undo,
1603 $userText
1604 )->inContentLanguage()->text();
1605 }
1606 } else {
1607 $undoIsAnon =
1608 !$undorev->getUser() ||
1609 !$undorev->getUser()->isRegistered();
1610 $disableAnonTalk = $services->getMainConfig()->get( MainConfigNames::DisableAnonTalk );
1611 $undoMessage = ( $undoIsAnon && $disableAnonTalk ) ?
1612 'undo-summary-anon' :
1613 'undo-summary';
1614 $undoSummary = $this->context->msg(
1615 $undoMessage,
1616 $undo,
1617 $userText
1618 )->inContentLanguage()->text();
1619 }
1620 if ( $this->summary === '' ) {
1621 $this->summary = $undoSummary;
1622 } else {
1623 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1624 ->inContentLanguage()->text() . $this->summary;
1625 }
1626 }
1627 }
1628
1629 /**
1630 * Returns the result of a three-way merge when undoing changes.
1631 *
1632 * @param RevisionRecord $undoRev Newest revision being undone. Corresponds to `undo`
1633 * URL parameter.
1634 * @param RevisionRecord $oldRev Revision that is being restored. Corresponds to
1635 * `undoafter` URL parameter.
1636 * @param ?string &$error If false is returned, this will be set to "norev"
1637 * if the revision failed to load, or "failure" if the content handler
1638 * failed to merge the required changes.
1639 *
1640 * @return Content|false
1641 */
1642 private function getUndoContent( RevisionRecord $undoRev, RevisionRecord $oldRev, &$error ) {
1643 $handler = $this->contentHandlerFactory
1644 ->getContentHandler( $undoRev->getSlot(
1645 SlotRecord::MAIN,
1646 RevisionRecord::RAW
1647 )->getModel() );
1648 $currentContent = $this->page->getRevisionRecord()
1649 ->getContent( SlotRecord::MAIN );
1650 $undoContent = $undoRev->getContent( SlotRecord::MAIN );
1651 $undoAfterContent = $oldRev->getContent( SlotRecord::MAIN );
1652 $undoIsLatest = $this->page->getRevisionRecord()->getId() === $undoRev->getId();
1653 if ( $currentContent === null
1654 || $undoContent === null
1655 || $undoAfterContent === null
1656 ) {
1657 $error = 'norev';
1658 return false;
1659 }
1660
1661 $content = $handler->getUndoContent(
1662 $currentContent,
1663 $undoContent,
1664 $undoAfterContent,
1665 $undoIsLatest
1666 );
1667 if ( $content === false ) {
1668 $error = 'failure';
1669 }
1670 return $content;
1671 }
1672
1673 /**
1674 * Get the content of the wanted revision, without section extraction.
1675 *
1676 * The result of this function can be used to compare user's input with
1677 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1678 * to the original text of the edit.
1679 *
1680 * This differs from Article::getContent() that when a missing revision is
1681 * encountered the result will be null and not the
1682 * 'missing-revision' message.
1683 *
1684 * @param Authority $performer to get the revision for
1685 * @return Content|null
1686 */
1687 private function getOriginalContent( Authority $performer ): ?Content {
1688 if ( $this->section === 'new' ) {
1689 return $this->getCurrentContent();
1690 }
1691 $revRecord = $this->mArticle->fetchRevisionRecord();
1692 if ( $revRecord === null ) {
1693 return $this->contentHandlerFactory
1694 ->getContentHandler( $this->contentModel )
1695 ->makeEmptyContent();
1696 }
1697 return $revRecord->getContent( SlotRecord::MAIN, RevisionRecord::FOR_THIS_USER, $performer );
1698 }
1699
1700 /**
1701 * Get the edit's parent revision ID
1702 *
1703 * The "parent" revision is the ancestor that should be recorded in this
1704 * page's revision history. It is either the revision ID of the in-memory
1705 * article content, or in the case of a 3-way merge in order to rebase
1706 * across a recoverable edit conflict, the ID of the newer revision to
1707 * which we have rebased this page.
1708 *
1709 * @return int Revision ID
1710 */
1711 private function getParentRevId() {
1712 if ( $this->parentRevId ) {
1713 return $this->parentRevId;
1714 } else {
1715 return $this->mArticle->getRevIdFetched();
1716 }
1717 }
1718
1719 /**
1720 * Get the current content of the page. This is basically similar to
1721 * WikiPage::getContent( RevisionRecord::RAW ) except that when the page doesn't
1722 * exist an empty content object is returned instead of null.
1723 *
1724 * @since 1.21
1725 * @return Content
1726 */
1727 protected function getCurrentContent() {
1728 $revRecord = $this->page->getRevisionRecord();
1729 $content = $revRecord ? $revRecord->getContent(
1730 SlotRecord::MAIN,
1731 RevisionRecord::RAW
1732 ) : null;
1733
1734 if ( $content === null ) {
1735 return $this->contentHandlerFactory
1736 ->getContentHandler( $this->contentModel )
1737 ->makeEmptyContent();
1738 }
1739
1740 return $content;
1741 }
1742
1743 /**
1744 * Make sure the form isn't faking a user's credentials.
1745 *
1746 * @param WebRequest $request
1747 * @return bool
1748 */
1749 private function tokenOk( WebRequest $request ): bool {
1750 $token = $request->getVal( 'wpEditToken' );
1751 $user = $this->context->getUser();
1752 $this->mTokenOk = $user->matchEditToken( $token );
1753 return $this->mTokenOk;
1754 }
1755
1756 /**
1757 * Sets post-edit cookie indicating the user just saved a particular revision.
1758 *
1759 * This uses a temporary cookie for each revision ID so separate saves will never
1760 * interfere with each other.
1761 *
1762 * Article::view deletes the cookie on server-side after the redirect and
1763 * converts the value to the global JavaScript variable wgPostEdit.
1764 *
1765 * If the variable were set on the server, it would be cached, which is unwanted
1766 * since the post-edit state should only apply to the load right after the save.
1767 *
1768 * @param int $statusValue The status value (to check for new article status)
1769 */
1770 private function setPostEditCookie( int $statusValue ): void {
1771 $revisionId = $this->page->getLatest();
1772 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1773
1774 $val = 'saved';
1775 if ( $statusValue === self::AS_SUCCESS_NEW_ARTICLE ) {
1776 $val = 'created';
1777 } elseif ( $this->oldid ) {
1778 $val = 'restored';
1779 }
1780 if ( $this->tempUserCreateDone ) {
1781 $val .= '+tempuser';
1782 }
1783
1784 $response = $this->context->getRequest()->response();
1785 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1786 }
1787
1788 /**
1789 * Attempt submission
1790 * @param array|false &$resultDetails See docs for $result in internalAttemptSavePrivate @phan-output-reference
1791 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1792 * @return Status
1793 */
1794 public function attemptSave( &$resultDetails = false ) {
1795 // Allow bots to exempt some edits from bot flagging
1796 $markAsBot = $this->markAsBot
1797 && $this->getAuthority()->isAllowed( 'bot' );
1798
1799 // Allow trusted users to mark some edits as minor
1800 $markAsMinor = $this->minoredit && !$this->isNew
1801 && $this->getAuthority()->isAllowed( 'minoredit' );
1802
1803 $status = $this->internalAttemptSavePrivate( $resultDetails, $markAsBot, $markAsMinor );
1804
1805 $this->getHookRunner()->onEditPage__attemptSave_after( $this, $status, $resultDetails );
1806
1807 return $status;
1808 }
1809
1810 /**
1811 * Log when a page was successfully saved after the edit conflict view
1812 */
1813 private function incrementResolvedConflicts(): void {
1814 if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1815 return;
1816 }
1817
1818 $this->getEditConflictHelper()->incrementResolvedStats( $this->context->getUser() );
1819 }
1820
1821 /**
1822 * Handle status, such as after attempt save
1823 *
1824 * @param Status $status
1825 * @param array|false $resultDetails
1826 *
1827 * @throws ErrorPageError
1828 * @return bool False, if output is done, true if rest of the form should be displayed
1829 */
1830 private function handleStatus( Status $status, $resultDetails ): bool {
1831 $statusValue = is_int( $status->value ) ? $status->value : 0;
1832
1833 /**
1834 * @todo FIXME: once the interface for internalAttemptSavePrivate() is made
1835 * nicer, this should use the message in $status
1836 */
1837 if ( $statusValue === self::AS_SUCCESS_UPDATE
1838 || $statusValue === self::AS_SUCCESS_NEW_ARTICLE
1839 ) {
1840 $this->incrementResolvedConflicts();
1841
1842 $this->didSave = true;
1843 if ( !$resultDetails['nullEdit'] ) {
1844 $this->setPostEditCookie( $statusValue );
1845 }
1846 }
1847
1848 $out = $this->context->getOutput();
1849
1850 // "wpExtraQueryRedirect" is a hidden input to modify
1851 // after save URL and is not used by actual edit form
1852 $request = $this->context->getRequest();
1853 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1854
1855 switch ( $statusValue ) {
1856 case self::AS_HOOK_ERROR_EXPECTED:
1857 case self::AS_CONTENT_TOO_BIG:
1858 case self::AS_ARTICLE_WAS_DELETED:
1859 case self::AS_CONFLICT_DETECTED:
1860 case self::AS_SUMMARY_NEEDED:
1861 case self::AS_TEXTBOX_EMPTY:
1862 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1863 case self::AS_END:
1864 case self::AS_BLANK_ARTICLE:
1865 case self::AS_SELF_REDIRECT:
1866 case self::AS_REVISION_WAS_DELETED:
1867 return true;
1868
1869 case self::AS_HOOK_ERROR:
1870 return false;
1871
1872 case self::AS_PARSE_ERROR:
1873 case self::AS_UNICODE_NOT_SUPPORTED:
1874 case self::AS_UNABLE_TO_ACQUIRE_TEMP_ACCOUNT:
1875 $out->wrapWikiTextAsInterface( 'error',
1876 $status->getWikiText( false, false, $this->context->getLanguage() )
1877 );
1878 return true;
1879
1880 case self::AS_SUCCESS_NEW_ARTICLE:
1881 $queryParts = [];
1882 if ( $resultDetails['redirect'] ) {
1883 $queryParts[] = 'redirect=no';
1884 }
1885 if ( $extraQueryRedirect ) {
1886 $queryParts[] = $extraQueryRedirect;
1887 }
1888 $anchor = $resultDetails['sectionanchor'] ?? '';
1889 $this->doPostEditRedirect( implode( '&', $queryParts ), $anchor );
1890 return false;
1891
1892 case self::AS_SUCCESS_UPDATE:
1893 $extraQuery = '';
1894 $sectionanchor = $resultDetails['sectionanchor'];
1895 // Give extensions a chance to modify URL query on update
1896 $this->getHookRunner()->onArticleUpdateBeforeRedirect( $this->mArticle,
1897 $sectionanchor, $extraQuery );
1898
1899 $queryParts = [];
1900 if ( $resultDetails['redirect'] ) {
1901 $queryParts[] = 'redirect=no';
1902 }
1903 if ( $extraQuery ) {
1904 $queryParts[] = $extraQuery;
1905 }
1906 if ( $extraQueryRedirect ) {
1907 $queryParts[] = $extraQueryRedirect;
1908 }
1909 $this->doPostEditRedirect( implode( '&', $queryParts ), $sectionanchor );
1910 return false;
1911
1912 case self::AS_SPAM_ERROR:
1913 $this->spamPageWithContent( $resultDetails['spam'] ?? false );
1914 return false;
1915
1916 case self::AS_BLOCKED_PAGE_FOR_USER:
1917 throw new UserBlockedError(
1918 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Block is checked and not null
1919 $this->context->getUser()->getBlock(),
1920 $this->context->getUser(),
1921 $this->context->getLanguage(),
1922 $request->getIP()
1923 );
1924
1925 case self::AS_IMAGE_REDIRECT_ANON:
1926 case self::AS_IMAGE_REDIRECT_LOGGED:
1927 throw new PermissionsError( 'upload' );
1928
1929 case self::AS_READ_ONLY_PAGE_ANON:
1930 case self::AS_READ_ONLY_PAGE_LOGGED:
1931 throw new PermissionsError( 'edit' );
1932
1933 case self::AS_READ_ONLY_PAGE:
1934 throw new ReadOnlyError;
1935
1936 case self::AS_RATE_LIMITED:
1937 $out->wrapWikiTextAsInterface( 'error',
1938 wfMessage( 'actionthrottledtext' )->plain()
1939 );
1940 return true;
1941
1942 case self::AS_NO_CREATE_PERMISSION:
1943 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1944 throw new PermissionsError( $permission );
1945
1946 case self::AS_NO_CHANGE_CONTENT_MODEL:
1947 throw new PermissionsError( 'editcontentmodel' );
1948
1949 default:
1950 // We don't recognize $statusValue. The only way that can happen
1951 // is if an extension hook aborted from inside ArticleSave.
1952 // Render the status object into $this->hookError
1953 // FIXME this sucks, we should just use the Status object throughout
1954 $this->hookError = Html::errorBox(
1955 "\n" . $status->getWikiText( false, false, $this->context->getLanguage() )
1956 );
1957 return true;
1958 }
1959 }
1960
1961 /**
1962 * Emit the post-save redirect. The URL is modifiable with a hook.
1963 *
1964 * @param string $query
1965 * @param string $anchor
1966 * @return void
1967 */
1968 private function doPostEditRedirect( $query, $anchor ) {
1969 $out = $this->context->getOutput();
1970 $url = $this->mTitle->getFullURL( $query ) . $anchor;
1971 $user = $this->getUserForSave();
1972 // If the temporary account was created in this request,
1973 // or if the temporary account has zero edits (implying
1974 // that the account was created during a failed edit
1975 // attempt in a previous request), perform the top-level
1976 // redirect to ensure the account is attached.
1977 // Note that the temp user could already have performed
1978 // the top-level redirect if this a first edit on
1979 // a wiki that is not the user's home wiki.
1980 $shouldRedirectForTempUser = $this->tempUserCreateDone ||
1981 ( $user->isTemp() && ( $user->getEditCount() === 0 ) );
1982 if ( $shouldRedirectForTempUser ) {
1983 $this->getHookRunner()->onTempUserCreatedRedirect(
1984 $this->context->getRequest()->getSession(),
1985 $user,
1986 $this->mTitle->getPrefixedDBkey(),
1987 $query,
1988 $anchor,
1989 $url
1990 );
1991 }
1992 $out->redirect( $url );
1993 }
1994
1995 /**
1996 * Set the edit summary and link anchor to be used for a new section.
1997 */
1998 private function setNewSectionSummary(): void {
1999 Assert::precondition( $this->section === 'new', 'This method can only be called for new sections' );
2000 Assert::precondition( $this->sectiontitle !== null, 'This method can only be called for new sections' );
2001
2002 $services = MediaWikiServices::getInstance();
2003 $parser = $services->getParser();
2004 $textFormatter = $services->getMessageFormatterFactory()->getTextFormatter(
2005 $services->getContentLanguage()->getCode()
2006 );
2007
2008 if ( $this->sectiontitle !== '' ) {
2009 $this->newSectionAnchor = $this->guessSectionName( $this->sectiontitle );
2010 // If no edit summary was specified, create one automatically from the section
2011 // title and have it link to the new section. Otherwise, respect the summary as
2012 // passed.
2013 if ( $this->summary === '' ) {
2014 $messageValue = MessageValue::new( 'newsectionsummary' )
2015 ->plaintextParams( $parser->stripSectionName( $this->sectiontitle ) );
2016 $this->summary = $textFormatter->format( $messageValue );
2017 }
2018 } else {
2019 $this->newSectionAnchor = '';
2020 }
2021 }
2022
2023 /**
2024 * Deprecated public access to attempting save, see documentation on
2025 * internalAttemptSavePrivate()
2026 *
2027 * @deprecated since 1.43
2028 * @param array &$result
2029 * @param bool $markAsBot
2030 * @param bool $markAsMinor
2031 * @return Status
2032 */
2033 public function internalAttemptSave( &$result, $markAsBot = false, $markAsMinor = false ) {
2034 wfDeprecated( __METHOD__, '1.43' );
2035 return $this->internalAttemptSavePrivate( $result, $markAsBot, $markAsMinor );
2036 }
2037
2038 /**
2039 * Attempt submission (no UI)
2040 *
2041 * @param array &$result Array to add statuses to, currently with the
2042 * possible keys:
2043 * - spam (string): Spam string from content if any spam is detected by
2044 * matchSpamRegex.
2045 * - sectionanchor (string): Section anchor for a section save.
2046 * - nullEdit (bool): Set if doUserEditContent is OK. True if null edit,
2047 * false otherwise.
2048 * - redirect (bool): Set if doUserEditContent is OK. True if resulting
2049 * revision is a redirect.
2050 * @param bool $markAsBot True if edit is being made under the bot right
2051 * and the bot wishes the edit to be marked as such.
2052 * @param bool $markAsMinor True if edit should be marked as minor.
2053 *
2054 * @return Status Status object, possibly with a message, but always with
2055 * one of the AS_* constants in $status->value,
2056 *
2057 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
2058 * various error display idiosyncrasies. There are also lots of cases
2059 * where error metadata is set in the object and retrieved later instead
2060 * of being returned, e.g. AS_CONTENT_TOO_BIG and
2061 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
2062 * time.
2063 */
2064 private function internalAttemptSavePrivate( &$result, $markAsBot = false, $markAsMinor = false ) {
2065 // If an attempt to acquire a temporary name failed, don't attempt to do anything else.
2066 if ( $this->unableToAcquireTempName ) {
2067 $status = Status::newFatal( 'temp-user-unable-to-acquire' );
2068 $status->value = self::AS_UNABLE_TO_ACQUIRE_TEMP_ACCOUNT;
2069 return $status;
2070 }
2071 // Auto-create the temporary account user, if the feature is enabled.
2072 // We create the account before any constraint checks or edit hooks fire, to ensure
2073 // that we have an actor and user account that can be used for any logs generated
2074 // by the edit attempt, and to ensure continuity in the user experience (if a constraint
2075 // denies an edit to a logged-out user, that history should be associated with the
2076 // eventually successful account creation)
2077 $tempAccountStatus = $this->createTempUser();
2078 if ( !$tempAccountStatus->isOK() ) {
2079 return $tempAccountStatus;
2080 }
2081 if ( $tempAccountStatus instanceof CreateStatus ) {
2082 $result['savedTempUser'] = $tempAccountStatus->getUser();
2083 }
2084
2085 $useNPPatrol = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseNPPatrol );
2086 $useRCPatrol = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::UseRCPatrol );
2087 if ( !$this->getHookRunner()->onEditPage__attemptSave( $this ) ) {
2088 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
2089 $status = Status::newFatal( 'hookaborted' );
2090 $status->value = self::AS_HOOK_ERROR;
2091 return $status;
2092 }
2093
2094 if ( !$this->getHookRunner()->onEditFilter( $this, $this->textbox1, $this->section,
2095 $this->hookError, $this->summary )
2096 ) {
2097 # Error messages etc. could be handled within the hook...
2098 $status = Status::newFatal( 'hookaborted' );
2099 $status->value = self::AS_HOOK_ERROR;
2100 return $status;
2101 } elseif ( $this->hookError ) {
2102 # ...or the hook could be expecting us to produce an error
2103 $status = Status::newFatal( 'hookaborted' );
2104 $status->value = self::AS_HOOK_ERROR_EXPECTED;
2105 return $status;
2106 }
2107
2108 try {
2109 # Construct Content object
2110 $textbox_content = $this->toEditContent( $this->textbox1 );
2111 } catch ( MWContentSerializationException $ex ) {
2112 $status = Status::newFatal(
2113 'content-failed-to-parse',
2114 $this->contentModel,
2115 $this->contentFormat,
2116 $ex->getMessage()
2117 );
2118 $status->value = self::AS_PARSE_ERROR;
2119 return $status;
2120 }
2121
2122 $this->contentLength = strlen( $this->textbox1 );
2123
2124 $requestUser = $this->context->getUser();
2125 $authority = $this->getAuthority();
2126 $pstUser = $this->getUserForPreview();
2127
2128 $changingContentModel = false;
2129 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
2130 $changingContentModel = true;
2131 $oldContentModel = $this->mTitle->getContentModel();
2132 }
2133
2134 // BEGINNING OF MIGRATION TO EDITCONSTRAINT SYSTEM (see T157658)
2135 /** @var EditConstraintFactory $constraintFactory */
2136 $constraintFactory = MediaWikiServices::getInstance()->getService( '_EditConstraintFactory' );
2137 $constraintRunner = new EditConstraintRunner();
2138
2139 // UnicodeConstraint: ensure that `$this->unicodeCheck` is the correct unicode
2140 $constraintRunner->addConstraint(
2141 new UnicodeConstraint( $this->unicodeCheck )
2142 );
2143
2144 // SimpleAntiSpamConstraint: ensure that the context request does not have
2145 // `wpAntispam` set
2146 // Use $user since there is no permissions aspect
2147 $constraintRunner->addConstraint(
2148 $constraintFactory->newSimpleAntiSpamConstraint(
2149 $this->context->getRequest()->getText( 'wpAntispam' ),
2150 $requestUser,
2151 $this->mTitle
2152 )
2153 );
2154
2155 // SpamRegexConstraint: ensure that the summary and text don't match the spam regex
2156 $constraintRunner->addConstraint(
2157 $constraintFactory->newSpamRegexConstraint(
2158 $this->summary,
2159 $this->sectiontitle,
2160 $this->textbox1,
2161 $this->context->getRequest()->getIP(),
2162 $this->mTitle
2163 )
2164 );
2165 $constraintRunner->addConstraint(
2166 new ImageRedirectConstraint(
2167 $textbox_content,
2168 $this->mTitle,
2169 $authority
2170 )
2171 );
2172 $constraintRunner->addConstraint(
2173 $constraintFactory->newUserBlockConstraint( $this->mTitle, $requestUser )
2174 );
2175 $constraintRunner->addConstraint(
2176 new ContentModelChangeConstraint(
2177 $authority,
2178 $this->mTitle,
2179 $this->contentModel
2180 )
2181 );
2182
2183 $constraintRunner->addConstraint(
2184 $constraintFactory->newReadOnlyConstraint()
2185 );
2186 $constraintRunner->addConstraint(
2187 $constraintFactory->newUserRateLimitConstraint(
2188 $requestUser->toRateLimitSubject(),
2189 $this->mTitle->getContentModel(),
2190 $this->contentModel
2191 )
2192 );
2193 $constraintRunner->addConstraint(
2194 // Same constraint is used to check size before and after merging the
2195 // edits, which use different failure codes
2196 $constraintFactory->newPageSizeConstraint(
2197 $this->contentLength,
2198 PageSizeConstraint::BEFORE_MERGE
2199 )
2200 );
2201 $constraintRunner->addConstraint(
2202 new ChangeTagsConstraint( $authority, $this->changeTags )
2203 );
2204
2205 // If the article has been deleted while editing, don't save it without
2206 // confirmation
2207 $constraintRunner->addConstraint(
2208 new AccidentalRecreationConstraint(
2209 $this->wasDeletedSinceLastEdit(),
2210 $this->recreate
2211 )
2212 );
2213
2214 // Load the page data from the primary DB. If anything changes in the meantime,
2215 // we detect it by using page_latest like a token in a 1 try compare-and-swap.
2216 $this->page->loadPageData( IDBAccessObject::READ_LATEST );
2217 $new = !$this->page->exists();
2218
2219 // We do this last, as some of the other constraints are more specific
2220 $constraintRunner->addConstraint(
2221 $constraintFactory->newEditRightConstraint( $this->getUserForPermissions(), $this->mTitle, $new )
2222 );
2223
2224 // Check the constraints
2225 if ( !$constraintRunner->checkConstraints() ) {
2226 $failed = $constraintRunner->getFailedConstraint();
2227
2228 // Need to check SpamRegexConstraint here, to avoid needing to pass
2229 // $result by reference again
2230 if ( $failed instanceof SpamRegexConstraint ) {
2231 $result['spam'] = $failed->getMatch();
2232 } else {
2233 $this->handleFailedConstraint( $failed );
2234 }
2235
2236 return Status::wrap( $failed->getLegacyStatus() );
2237 }
2238 // END OF MIGRATION TO EDITCONSTRAINT SYSTEM (continued below)
2239
2240 $flags = EDIT_AUTOSUMMARY |
2241 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2242 ( $markAsMinor ? EDIT_MINOR : 0 ) |
2243 ( $markAsBot ? EDIT_FORCE_BOT : 0 );
2244
2245 if ( $new ) {
2246 $content = $textbox_content;
2247
2248 $result['sectionanchor'] = '';
2249 if ( $this->section === 'new' ) {
2250 if ( $this->sectiontitle !== null ) {
2251 // Insert the section title above the content.
2252 $content = $content->addSectionHeader( $this->sectiontitle );
2253 }
2254 $result['sectionanchor'] = $this->newSectionAnchor;
2255 }
2256
2257 $pageUpdater = $this->page->newPageUpdater( $pstUser )
2258 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
2259 ->setContent( SlotRecord::MAIN, $content );
2260 $pageUpdater->prepareUpdate( $flags );
2261
2262 // BEGINNING OF MIGRATION TO EDITCONSTRAINT SYSTEM (see T157658)
2263 // Create a new runner to avoid rechecking the prior constraints, use the same factory
2264 $constraintRunner = new EditConstraintRunner();
2265
2266 // Don't save a new page if it's blank or if it's a MediaWiki:
2267 // message with content equivalent to default (allow empty pages
2268 // in this case to disable messages, see T52124)
2269 $constraintRunner->addConstraint(
2270 new DefaultTextConstraint(
2271 $this->mTitle,
2272 $this->allowBlankArticle,
2273 $this->textbox1
2274 )
2275 );
2276
2277 $constraintRunner->addConstraint(
2278 $constraintFactory->newEditFilterMergedContentHookConstraint(
2279 $content,
2280 $this->context,
2281 $this->summary,
2282 $markAsMinor,
2283 $this->context->getLanguage(),
2284 $pstUser
2285 )
2286 );
2287
2288 // Check the constraints
2289 if ( !$constraintRunner->checkConstraints() ) {
2290 $failed = $constraintRunner->getFailedConstraint();
2291 $this->handleFailedConstraint( $failed );
2292 return Status::wrap( $failed->getLegacyStatus() );
2293 }
2294 // END OF MIGRATION TO EDITCONSTRAINT SYSTEM (continued below)
2295 } else { # not $new
2296
2297 # Article exists. Check for edit conflict.
2298
2299 $timestamp = $this->page->getTimestamp();
2300 $latest = $this->page->getLatest();
2301
2302 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}" );
2303 wfDebug( "revision: {$latest}, editRevId: {$this->editRevId}" );
2304
2305 $editConflictLogger = LoggerFactory::getInstance( 'EditConflict' );
2306 // An edit conflict is detected if the current revision is different from the
2307 // revision that was current when editing was initiated on the client.
2308 // This is checked based on the timestamp and revision ID.
2309 // TODO: the timestamp based check can probably go away now.
2310 if ( ( $this->edittime !== null && $this->edittime != $timestamp )
2311 || ( $this->editRevId !== null && $this->editRevId != $latest )
2312 ) {
2313 $this->isConflict = true;
2314 if ( $this->section === 'new' ) {
2315 if ( $this->page->getUserText() === $requestUser->getName() &&
2316 $this->page->getComment() === $this->summary
2317 ) {
2318 // Probably a duplicate submission of a new comment.
2319 // This can happen when CDN resends a request after
2320 // a timeout but the first one actually went through.
2321 $editConflictLogger->debug(
2322 'Duplicate new section submission; trigger edit conflict!'
2323 );
2324 } else {
2325 // New comment; suppress conflict.
2326 $this->isConflict = false;
2327 $editConflictLogger->debug( 'Conflict suppressed; new section' );
2328 }
2329 } elseif ( $this->section === ''
2330 && $this->edittime
2331 && $this->revisionStore->userWasLastToEdit(
2332 $this->connectionProvider->getPrimaryDatabase(),
2333 $this->mTitle->getArticleID(),
2334 $requestUser->getId(),
2335 $this->edittime
2336 )
2337 ) {
2338 # Suppress edit conflict with self, except for section edits where merging is required.
2339 $editConflictLogger->debug( 'Suppressing edit conflict, same user.' );
2340 $this->isConflict = false;
2341 }
2342 }
2343
2344 if ( $this->isConflict ) {
2345 $editConflictLogger->debug(
2346 'Conflict! Getting section {section} for time {editTime}'
2347 . ' (id {editRevId}, article time {timestamp})',
2348 [
2349 'section' => $this->section,
2350 'editTime' => $this->edittime,
2351 'editRevId' => $this->editRevId,
2352 'timestamp' => $timestamp,
2353 ]
2354 );
2355 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2356 // ...or disable section editing for non-current revisions (not exposed anyway).
2357 if ( $this->editRevId !== null ) {
2358 $content = $this->page->replaceSectionAtRev(
2359 $this->section,
2360 $textbox_content,
2361 $this->sectiontitle,
2362 $this->editRevId
2363 );
2364 } else {
2365 $content = $this->page->replaceSectionContent(
2366 $this->section,
2367 $textbox_content,
2368 $this->sectiontitle,
2369 $this->edittime
2370 );
2371 }
2372 } else {
2373 $editConflictLogger->debug(
2374 'Getting section {section}',
2375 [ 'section' => $this->section ]
2376 );
2377 $content = $this->page->replaceSectionAtRev(
2378 $this->section,
2379 $textbox_content,
2380 $this->sectiontitle
2381 );
2382 }
2383
2384 if ( $content === null ) {
2385 $editConflictLogger->debug( 'Activating conflict; section replace failed.' );
2386 $this->isConflict = true;
2387 $content = $textbox_content; // do not try to merge here!
2388 } elseif ( $this->isConflict ) {
2389 // Attempt merge
2390 $mergedChange = $this->mergeChangesIntoContent( $content );
2391 if ( $mergedChange !== false ) {
2392 // Successful merge! Maybe we should tell the user the good news?
2393 $content = $mergedChange[0];
2394 $this->parentRevId = $mergedChange[1];
2395 $this->isConflict = false;
2396 $editConflictLogger->debug( 'Suppressing edit conflict, successful merge.' );
2397 } else {
2398 $this->section = '';
2399 $this->textbox1 = ( $content instanceof TextContent ) ? $content->getText() : '';
2400 $editConflictLogger->debug( 'Keeping edit conflict, failed merge.' );
2401 }
2402 }
2403
2404 if ( $this->isConflict ) {
2405 return Status::newGood( self::AS_CONFLICT_DETECTED )->setOK( false );
2406 }
2407
2408 $pageUpdater = $this->page->newPageUpdater( $pstUser )
2409 ->setContent( SlotRecord::MAIN, $content );
2410 $pageUpdater->prepareUpdate( $flags );
2411
2412 // BEGINNING OF MIGRATION TO EDITCONSTRAINT SYSTEM (see T157658)
2413 // Create a new runner to avoid rechecking the prior constraints, use the same factory
2414 $constraintRunner = new EditConstraintRunner();
2415 $constraintRunner->addConstraint(
2416 $constraintFactory->newEditFilterMergedContentHookConstraint(
2417 $content,
2418 $this->context,
2419 $this->summary,
2420 $markAsMinor,
2421 $this->context->getLanguage(),
2422 $pstUser
2423 )
2424 );
2425 $constraintRunner->addConstraint(
2426 new NewSectionMissingSubjectConstraint(
2427 $this->section,
2428 $this->sectiontitle ?? '',
2429 $this->allowBlankSummary
2430 )
2431 );
2432 $constraintRunner->addConstraint(
2433 new MissingCommentConstraint( $this->section, $this->textbox1 )
2434 );
2435 $constraintRunner->addConstraint(
2436 new ExistingSectionEditConstraint(
2437 $this->section,
2438 $this->summary,
2439 $this->autoSumm,
2440 $this->allowBlankSummary,
2441 $content,
2442 $this->getOriginalContent( $authority )
2443 )
2444 );
2445 // Check the constraints
2446 if ( !$constraintRunner->checkConstraints() ) {
2447 $failed = $constraintRunner->getFailedConstraint();
2448 $this->handleFailedConstraint( $failed );
2449 return Status::wrap( $failed->getLegacyStatus() );
2450 }
2451 // END OF MIGRATION TO EDITCONSTRAINT SYSTEM (continued below)
2452
2453 # All's well
2454 $sectionAnchor = '';
2455 if ( $this->section === 'new' ) {
2456 $sectionAnchor = $this->newSectionAnchor;
2457 } elseif ( $this->section !== '' ) {
2458 # Try to get a section anchor from the section source, redirect
2459 # to edited section if header found.
2460 # XXX: Might be better to integrate this into WikiPage::replaceSectionAtRev
2461 # for duplicate heading checking and maybe parsing.
2462 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2463 # We can't deal with anchors, includes, html etc in the header for now,
2464 # headline would need to be parsed to improve this.
2465 if ( $hasmatch && $matches[2] !== '' ) {
2466 $sectionAnchor = $this->guessSectionName( $matches[2] );
2467 }
2468 }
2469 $result['sectionanchor'] = $sectionAnchor;
2470
2471 // Save errors may fall down to the edit form, but we've now
2472 // merged the section into full text. Clear the section field
2473 // so that later submission of conflict forms won't try to
2474 // replace that into a duplicated mess.
2475 $this->textbox1 = $this->toEditText( $content );
2476 $this->section = '';
2477 }
2478
2479 // Check for length errors again now that the section is merged in
2480 $this->contentLength = strlen( $this->toEditText( $content ) );
2481
2482 // BEGINNING OF MIGRATION TO EDITCONSTRAINT SYSTEM (see T157658)
2483 // Create a new runner to avoid rechecking the prior constraints, use the same factory
2484 $constraintRunner = new EditConstraintRunner();
2485 $constraintRunner->addConstraint(
2486 new SelfRedirectConstraint(
2487 $this->allowSelfRedirect,
2488 $content,
2489 $this->getCurrentContent(),
2490 $this->getTitle()
2491 )
2492 );
2493 $constraintRunner->addConstraint(
2494 // Same constraint is used to check size before and after merging the
2495 // edits, which use different failure codes
2496 $constraintFactory->newPageSizeConstraint(
2497 $this->contentLength,
2498 PageSizeConstraint::AFTER_MERGE
2499 )
2500 );
2501 // Check the constraints
2502 if ( !$constraintRunner->checkConstraints() ) {
2503 $failed = $constraintRunner->getFailedConstraint();
2504 $this->handleFailedConstraint( $failed );
2505 return Status::wrap( $failed->getLegacyStatus() );
2506 }
2507 // END OF MIGRATION TO EDITCONSTRAINT SYSTEM
2508
2509 if ( $this->undidRev && $this->isUndoClean( $content ) ) {
2510 // As the user can change the edit's content before saving, we only mark
2511 // "clean" undos as reverts. This is to avoid abuse by marking irrelevant
2512 // edits as undos.
2513 $pageUpdater
2514 ->setOriginalRevisionId( $this->undoAfter ?: false )
2515 ->markAsRevert(
2516 EditResult::REVERT_UNDO,
2517 $this->undidRev,
2518 $this->undoAfter ?: null
2519 );
2520 }
2521
2522 $needsPatrol = $useRCPatrol || ( $useNPPatrol && !$this->page->exists() );
2523 if ( $needsPatrol && $authority->authorizeWrite( 'autopatrol', $this->getTitle() ) ) {
2524 $pageUpdater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
2525 }
2526
2527 $pageUpdater
2528 ->addTags( $this->changeTags )
2529 ->saveRevision(
2530 CommentStoreComment::newUnsavedComment( trim( $this->summary ) ),
2531 $flags
2532 );
2533 $doEditStatus = $pageUpdater->getStatus();
2534
2535 if ( !$doEditStatus->isOK() ) {
2536 // Failure from doEdit()
2537 // Show the edit conflict page for certain recognized errors from doEdit(),
2538 // but don't show it for errors from extension hooks
2539 if (
2540 $doEditStatus->failedBecausePageMissing() ||
2541 $doEditStatus->failedBecausePageExists() ||
2542 $doEditStatus->failedBecauseOfConflict()
2543 ) {
2544 $this->isConflict = true;
2545 // Destroys data doEdit() put in $status->value but who cares
2546 $doEditStatus->value = self::AS_END;
2547 }
2548 return $doEditStatus;
2549 }
2550
2551 $result['nullEdit'] = !$doEditStatus->wasRevisionCreated();
2552 if ( $result['nullEdit'] ) {
2553 // We didn't know if it was a null edit until now, so bump the rate limit now
2554 $limitSubject = $requestUser->toRateLimitSubject();
2555 MediaWikiServices::getInstance()->getRateLimiter()->limit( $limitSubject, 'linkpurge' );
2556 }
2557 $result['redirect'] = $content->isRedirect();
2558
2559 $this->updateWatchlist();
2560
2561 // If the content model changed, add a log entry
2562 if ( $changingContentModel ) {
2563 $this->addContentModelChangeLogEntry(
2564 $this->getUserForSave(),
2565 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
2566 // $oldContentModel is set when $changingContentModel is true
2567 $new ? false : $oldContentModel,
2568 $this->contentModel,
2569 $this->summary
2570 );
2571 }
2572
2573 // Instead of carrying the same status object throughout, it is created right
2574 // when it is returned, either at an earlier point due to an error or here
2575 // due to a successful edit.
2576 $statusCode = ( $new ? self::AS_SUCCESS_NEW_ARTICLE : self::AS_SUCCESS_UPDATE );
2577 return Status::newGood( $statusCode );
2578 }
2579
2580 /**
2581 * Apply the specific updates needed for the EditPage fields based on which constraint
2582 * failed, rather than interspersing this logic throughout internalAttemptSavePrivate at
2583 * each of the points the constraints are checked. Eventually, this will act on the
2584 * result from the backend.
2585 *
2586 * @param IEditConstraint $failed
2587 */
2588 private function handleFailedConstraint( IEditConstraint $failed ): void {
2589 if ( $failed instanceof PageSizeConstraint ) {
2590 // Error will be displayed by showEditForm()
2591 $this->tooBig = true;
2592 } elseif ( $failed instanceof UserBlockConstraint ) {
2593 // Auto-block user's IP if the account was "hard" blocked
2594 if ( !MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
2595 $this->context->getUser()->spreadAnyEditBlock();
2596 }
2597 } elseif ( $failed instanceof DefaultTextConstraint ) {
2598 $this->blankArticle = true;
2599 } elseif ( $failed instanceof EditFilterMergedContentHookConstraint ) {
2600 $this->hookError = $failed->getHookError();
2601 } elseif (
2602 // ExistingSectionEditConstraint also checks for revisions deleted
2603 // since the edit was loaded, which doesn't indicate a missing summary
2604 (
2605 $failed instanceof ExistingSectionEditConstraint
2606 && $failed->getLegacyStatus()->value === self::AS_SUMMARY_NEEDED
2607 ) ||
2608 $failed instanceof NewSectionMissingSubjectConstraint
2609 ) {
2610 $this->missingSummary = true;
2611 } elseif ( $failed instanceof MissingCommentConstraint ) {
2612 $this->missingComment = true;
2613 } elseif ( $failed instanceof SelfRedirectConstraint ) {
2614 $this->selfRedirect = true;
2615 }
2616 }
2617
2618 /**
2619 * Does checks and compares the automatically generated undo content with the
2620 * one that was submitted by the user. If they match, the undo is considered "clean".
2621 * Otherwise there is no guarantee if anything was reverted at all, as the user could
2622 * even swap out entire content.
2623 *
2624 * @param Content $content
2625 *
2626 * @return bool
2627 */
2628 private function isUndoClean( Content $content ): bool {
2629 // Check whether the undo was "clean", that is the user has not modified
2630 // the automatically generated content.
2631 $undoRev = $this->revisionStore->getRevisionById( $this->undidRev );
2632 if ( $undoRev === null ) {
2633 return false;
2634 }
2635
2636 if ( $this->undoAfter ) {
2637 $oldRev = $this->revisionStore->getRevisionById( $this->undoAfter );
2638 } else {
2639 $oldRev = $this->revisionStore->getPreviousRevision( $undoRev );
2640 }
2641
2642 if ( $oldRev === null ||
2643 $undoRev->isDeleted( RevisionRecord::DELETED_TEXT ) ||
2644 $oldRev->isDeleted( RevisionRecord::DELETED_TEXT )
2645 ) {
2646 return false;
2647 }
2648
2649 $undoContent = $this->getUndoContent( $undoRev, $oldRev, $undoError );
2650 if ( !$undoContent ) {
2651 return false;
2652 }
2653
2654 // Do a pre-save transform on the retrieved undo content
2655 $services = MediaWikiServices::getInstance();
2656 $contentLanguage = $services->getContentLanguage();
2657 $user = $this->getUserForPreview();
2658 $parserOptions = ParserOptions::newFromUserAndLang( $user, $contentLanguage );
2659 $contentTransformer = $services->getContentTransformer();
2660 $undoContent = $contentTransformer->preSaveTransform( $undoContent, $this->mTitle, $user, $parserOptions );
2661
2662 if ( $undoContent->equals( $content ) ) {
2663 return true;
2664 }
2665 return false;
2666 }
2667
2668 /**
2669 * @param UserIdentity $user
2670 * @param string|false $oldModel false if the page is being newly created
2671 * @param string $newModel
2672 * @param string $reason
2673 */
2674 private function addContentModelChangeLogEntry( UserIdentity $user, $oldModel, $newModel, $reason = "" ): void {
2675 $new = $oldModel === false;
2676 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2677 $log->setPerformer( $user );
2678 $log->setTarget( $this->mTitle );
2679 $log->setComment( is_string( $reason ) ? $reason : "" );
2680 $log->setParameters( [
2681 '4::oldmodel' => $oldModel,
2682 '5::newmodel' => $newModel
2683 ] );
2684 $logid = $log->insert();
2685 $log->publish( $logid );
2686 }
2687
2688 /**
2689 * Register the change of watch status
2690 */
2691 private function updateWatchlist(): void {
2692 if ( $this->tempUserCreateActive ) {
2693 return;
2694 }
2695 $user = $this->getUserForSave();
2696 if ( !$user->isNamed() ) {
2697 return;
2698 }
2699
2700 $title = $this->mTitle;
2701 $watch = $this->watchthis;
2702 $watchlistExpiry = $this->watchlistExpiry;
2703
2704 // This can't run as a DeferredUpdate due to a possible race condition
2705 // when the post-edit redirect happens if the pendingUpdates queue is
2706 // too large to finish in time (T259564)
2707 $this->watchlistManager->setWatch( $watch, $user, $title, $watchlistExpiry );
2708
2709 $this->watchedItemStore->maybeEnqueueWatchlistExpiryJob();
2710 }
2711
2712 /**
2713 * Attempts to do 3-way merge of edit content with a base revision
2714 * and current content, in case of edit conflict, in whichever way appropriate
2715 * for the content type.
2716 *
2717 * @param Content $editContent
2718 *
2719 * @return array|false either `false` or an array of the new Content and the
2720 * updated parent revision id
2721 */
2722 private function mergeChangesIntoContent( Content $editContent ) {
2723 // This is the revision that was current at the time editing was initiated on the client,
2724 // even if the edit was based on an old revision.
2725 $baseRevRecord = $this->getExpectedParentRevision();
2726 $baseContent = $baseRevRecord ?
2727 $baseRevRecord->getContent( SlotRecord::MAIN ) :
2728 null;
2729
2730 if ( $baseContent === null ) {
2731 return false;
2732 } elseif ( $baseRevRecord->isCurrent() ) {
2733 // Impossible to have a conflict when the user just edited the latest revision. This can
2734 // happen e.g. when $wgDiff3 is badly configured.
2735 return [ $editContent, $baseRevRecord->getId() ];
2736 }
2737
2738 // The current state, we want to merge updates into it
2739 $currentRevisionRecord = $this->revisionStore->getRevisionByTitle(
2740 $this->mTitle,
2741 0,
2742 IDBAccessObject::READ_LATEST
2743 );
2744 $currentContent = $currentRevisionRecord
2745 ? $currentRevisionRecord->getContent( SlotRecord::MAIN )
2746 : null;
2747
2748 if ( $currentContent === null ) {
2749 return false;
2750 }
2751
2752 $mergedContent = $this->contentHandlerFactory
2753 ->getContentHandler( $baseContent->getModel() )
2754 ->merge3( $baseContent, $editContent, $currentContent );
2755
2756 if ( $mergedContent ) {
2757 // Also need to update parentRevId to what we just merged.
2758 return [ $mergedContent, $currentRevisionRecord->getId() ];
2759 }
2760
2761 return false;
2762 }
2763
2764 /**
2765 * Returns the RevisionRecord corresponding to the revision that was current at the time
2766 * editing was initiated on the client even if the edit was based on an old revision
2767 *
2768 * @since 1.35
2769 * @return RevisionRecord|null Current revision when editing was initiated on the client
2770 */
2771 public function getExpectedParentRevision() {
2772 if ( $this->mExpectedParentRevision === false ) {
2773 $revRecord = null;
2774 if ( $this->editRevId ) {
2775 $revRecord = $this->revisionStore->getRevisionById(
2776 $this->editRevId,
2777 IDBAccessObject::READ_LATEST
2778 );
2779 } elseif ( $this->edittime ) {
2780 $revRecord = $this->revisionStore->getRevisionByTimestamp(
2781 $this->getTitle(),
2782 $this->edittime,
2783 IDBAccessObject::READ_LATEST
2784 );
2785 }
2786 $this->mExpectedParentRevision = $revRecord;
2787 }
2788 return $this->mExpectedParentRevision;
2789 }
2790
2791 public function setHeaders() {
2792 $out = $this->context->getOutput();
2793
2794 $out->addModules( 'mediawiki.action.edit' );
2795 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2796 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2797 $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
2798
2799 $user = $this->context->getUser();
2800
2801 if ( $this->userOptionsLookup->getOption( $user, 'uselivepreview' ) ) {
2802 $out->addModules( 'mediawiki.action.edit.preview' );
2803 }
2804
2805 if ( $this->userOptionsLookup->getOption( $user, 'useeditwarning' ) ) {
2806 $out->addModules( 'mediawiki.action.edit.editWarning' );
2807 }
2808
2809 if ( $this->context->getConfig()->get( MainConfigNames::EnableEditRecovery )
2810 && $this->userOptionsLookup->getOption( $user, 'editrecovery' )
2811 ) {
2812 $wasPosted = $this->getContext()->getRequest()->getMethod() === 'POST';
2813 $out->addJsConfigVars( 'wgEditRecoveryWasPosted', $wasPosted );
2814 $out->addModules( 'mediawiki.editRecovery.edit' );
2815 }
2816
2817 # Enabled article-related sidebar, toplinks, etc.
2818 $out->setArticleRelated( true );
2819
2820 $contextTitle = $this->getContextTitle();
2821 if ( $this->isConflict ) {
2822 $msg = 'editconflict';
2823 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2824 $msg = $this->section === 'new' ? 'editingcomment' : 'editingsection';
2825 } else {
2826 $msg = $contextTitle->exists()
2827 || ( $contextTitle->getNamespace() === NS_MEDIAWIKI
2828 && $contextTitle->getDefaultMessageText() !== false
2829 )
2830 ? 'editing'
2831 : 'creating';
2832 }
2833
2834 # Use the title defined by DISPLAYTITLE magic word when present
2835 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2836 # Escape ::getPrefixedText() so that we have HTML in all cases,
2837 # and pass as a "raw" parameter to ::setPageTitleMsg().
2838 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2839 if ( $displayTitle === false ) {
2840 $displayTitle = htmlspecialchars(
2841 $contextTitle->getPrefixedText(), ENT_QUOTES, 'UTF-8', false
2842 );
2843 } else {
2844 $out->setDisplayTitle( $displayTitle );
2845 }
2846
2847 // Enclose the title with an element. This is used on live preview to update the
2848 // preview of the display title.
2849 $displayTitle = Html::rawElement( 'span', [ 'id' => 'firstHeadingTitle' ], $displayTitle );
2850
2851 $out->setPageTitleMsg( $this->context->msg( $msg )->rawParams( $displayTitle ) );
2852
2853 $config = $this->context->getConfig();
2854
2855 # Transmit the name of the message to JavaScript. This was added for live preview.
2856 # Live preview doesn't use this anymore. The variable is still transmitted because
2857 # Edit Recovery and user scripts use it.
2858 $out->addJsConfigVars( [
2859 'wgEditMessage' => $msg,
2860 ] );
2861
2862 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2863 // editors, etc.
2864 $out->addJsConfigVars(
2865 'wgEditSubmitButtonLabelPublish',
2866 $config->get( MainConfigNames::EditSubmitButtonLabelPublish )
2867 );
2868 }
2869
2870 /**
2871 * Show all applicable editing introductions
2872 */
2873 private function showIntro(): void {
2874 $services = MediaWikiServices::getInstance();
2875
2876 // Hardcoded list of notices that are suppressable for historical reasons.
2877 // This feature was originally added for LiquidThreads, to avoid showing non-essential messages
2878 // when commenting in a thread, but some messages were included (or excluded) by mistake before
2879 // its implementation was moved to one place, and this list doesn't make a lot of sense.
2880 // TODO: Remove the suppressIntro feature from EditPage, and invent a better way for extensions
2881 // to skip individual intro messages.
2882 $skip = $this->suppressIntro ? [
2883 'editintro',
2884 'code-editing-intro',
2885 'sharedupload-desc-create',
2886 'sharedupload-desc-edit',
2887 'userpage-userdoesnotexist',
2888 'blocked-notice-logextract',
2889 'newarticletext',
2890 'newarticletextanon',
2891 'recreate-moveddeleted-warn',
2892 ] : [];
2893
2894 $messages = $services->getIntroMessageBuilder()->getIntroMessages(
2895 IntroMessageBuilder::MORE_FRAMES,
2896 $skip,
2897 $this->context,
2898 $this->mTitle->toPageIdentity(),
2899 $this->mArticle->fetchRevisionRecord(),
2900 $this->context->getUser(),
2901 $this->context->getRequest()->getVal( 'editintro' ),
2902 wfArrayToCgi(
2903 array_diff_key(
2904 $this->context->getRequest()->getValues(),
2905 [ 'title' => true, 'returnto' => true, 'returntoquery' => true ]
2906 )
2907 ),
2908 !$this->firsttime,
2909 $this->section !== '' ? $this->section : null
2910 );
2911
2912 foreach ( $messages as $message ) {
2913 $this->context->getOutput()->addHTML( $message );
2914 }
2915 }
2916
2917 /**
2918 * Gets an editable textual representation of $content.
2919 * The textual representation can be turned by into a Content object by the
2920 * toEditContent() method.
2921 *
2922 * If $content is null or false or a string, $content is returned unchanged.
2923 *
2924 * If the given Content object is not of a type that can be edited using
2925 * the text base EditPage, an exception will be raised. Set
2926 * $this->allowNonTextContent to true to allow editing of non-textual
2927 * content.
2928 *
2929 * @param Content|null|false|string $content
2930 * @return string The editable text form of the content.
2931 *
2932 * @throws MWException If $content is not an instance of TextContent and
2933 * $this->allowNonTextContent is not true.
2934 */
2935 private function toEditText( $content ) {
2936 if ( $content === null || $content === false ) {
2937 return '';
2938 }
2939 if ( is_string( $content ) ) {
2940 return $content;
2941 }
2942
2943 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2944 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2945 }
2946
2947 return $content->serialize( $this->contentFormat );
2948 }
2949
2950 /**
2951 * Turns the given text into a Content object by unserializing it.
2952 *
2953 * If the resulting Content object is not of a type that can be edited using
2954 * the text base EditPage, an exception will be raised. Set
2955 * $this->allowNonTextContent to true to allow editing of non-textual
2956 * content.
2957 *
2958 * @param string|null|false $text Text to unserialize
2959 * @return Content|false|null The content object created from $text. If $text was false
2960 * or null, then false or null will be returned instead.
2961 *
2962 * @throws MWException If unserializing the text results in a Content
2963 * object that is not an instance of TextContent and
2964 * $this->allowNonTextContent is not true.
2965 */
2966 protected function toEditContent( $text ) {
2967 if ( $text === false || $text === null ) {
2968 return $text;
2969 }
2970
2971 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2972 $this->contentModel, $this->contentFormat );
2973
2974 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2975 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2976 }
2977
2978 return $content;
2979 }
2980
2981 /**
2982 * Send the edit form and related headers to OutputPage
2983 */
2984 public function showEditForm() {
2985 # need to parse the preview early so that we know which templates are used,
2986 # otherwise users with "show preview after edit box" will get a blank list
2987 # we parse this near the beginning so that setHeaders can do the title
2988 # setting work instead of leaving it in getPreviewText
2989 $previewOutput = '';
2990 if ( $this->formtype === 'preview' ) {
2991 $previewOutput = $this->getPreviewText();
2992 }
2993
2994 $out = $this->context->getOutput();
2995
2996 // FlaggedRevs depends on running this hook before adding edit notices in showIntro() (T337637)
2997 $this->getHookRunner()->onEditPage__showEditForm_initial( $this, $out );
2998
2999 $this->setHeaders();
3000
3001 // Show applicable editing introductions
3002 $this->showIntro();
3003
3004 if ( !$this->isConflict &&
3005 $this->section !== '' &&
3006 !$this->isSectionEditSupported()
3007 ) {
3008 // We use $this->section to much before this and getVal('wgSection') directly in other places
3009 // at this point we can't reset $this->section to '' to fallback to non-section editing.
3010 // Someone is welcome to try refactoring though
3011 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
3012 return;
3013 }
3014
3015 $this->showHeader();
3016
3017 $out->addHTML( $this->editFormPageTop );
3018
3019 $user = $this->context->getUser();
3020 if ( $this->userOptionsLookup->getOption( $user, 'previewontop' ) ) {
3021 $this->displayPreviewArea( $previewOutput, true );
3022 }
3023
3024 $out->addHTML( $this->editFormTextTop );
3025
3026 if ( $this->formtype !== 'save' && $this->wasDeletedSinceLastEdit() ) {
3027 $out->addHTML( Html::errorBox(
3028 $out->msg( 'deletedwhileediting' )->parse(),
3029 '',
3030 'mw-deleted-while-editing'
3031 ) );
3032 }
3033
3034 // @todo add EditForm plugin interface and use it here!
3035 // search for textarea1 and textarea2, and allow EditForm to override all uses.
3036 $out->addHTML( Html::openElement(
3037 'form',
3038 [
3039 'class' => 'mw-editform',
3040 'id' => self::EDITFORM_ID,
3041 'name' => self::EDITFORM_ID,
3042 'method' => 'post',
3043 'action' => $this->getActionURL( $this->getContextTitle() ),
3044 'enctype' => 'multipart/form-data',
3045 'data-mw-editform-type' => $this->formtype
3046 ]
3047 ) );
3048
3049 // Add a check for Unicode support
3050 $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
3051
3052 // Add an empty field to trip up spambots
3053 $out->addHTML(
3054 Html::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
3055 . Html::rawElement(
3056 'label',
3057 [ 'for' => 'wpAntispam' ],
3058 $this->context->msg( 'simpleantispam-label' )->parse()
3059 )
3060 . Html::element(
3061 'input',
3062 [
3063 'type' => 'text',
3064 'name' => 'wpAntispam',
3065 'id' => 'wpAntispam',
3066 'value' => ''
3067 ]
3068 )
3069 . Html::closeElement( 'div' )
3070 );
3071
3072 $this->getHookRunner()->onEditPage__showEditForm_fields( $this, $out );
3073
3074 // Put these up at the top to ensure they aren't lost on early form submission
3075 $this->showFormBeforeText();
3076
3077 if ( $this->formtype === 'save' && $this->wasDeletedSinceLastEdit() ) {
3078 $username = $this->lastDelete->actor_name;
3079 $comment = $this->commentStore->getComment( 'log_comment', $this->lastDelete )->text;
3080
3081 // It is better to not parse the comment at all than to have templates expanded in the middle
3082 // TODO: can the label be moved outside of the div so that wrapWikiMsg could be used?
3083 $key = $comment === ''
3084 ? 'confirmrecreate-noreason'
3085 : 'confirmrecreate';
3086 $out->addHTML( Html::rawElement(
3087 'div',
3088 [ 'class' => 'mw-confirm-recreate' ],
3089 $this->context->msg( $key )
3090 ->params( $username )
3091 ->plaintextParams( $comment )
3092 ->parse() .
3093 Html::rawElement(
3094 'div',
3095 [],
3096 Html::check(
3097 'wpRecreate',
3098 false,
3099 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
3100 )
3101 . "\u{00A0}" .
3102 Html::label(
3103 $this->context->msg( 'recreate' )->text(),
3104 'wpRecreate',
3105 [ 'title' => Linker::titleAttrib( 'recreate' ) ]
3106 )
3107 )
3108 ) );
3109 }
3110
3111 # When the summary is hidden, also hide them on preview/show changes
3112 if ( $this->nosummary ) {
3113 $out->addHTML( Html::hidden( 'nosummary', true ) );
3114 }
3115
3116 # If a blank edit summary was previously provided, and the appropriate
3117 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
3118 # user being bounced back more than once in the event that a summary
3119 # is not required.
3120 # ####
3121 # For a bit more sophisticated detection of blank summaries, hash the
3122 # automatic one and pass that in the hidden field wpAutoSummary.
3123 if (
3124 $this->missingSummary ||
3125 // @phan-suppress-next-line PhanSuspiciousValueComparison
3126 ( $this->section === 'new' && $this->nosummary ) ||
3127 $this->allowBlankSummary
3128 ) {
3129 $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
3130 }
3131
3132 if ( $this->undidRev ) {
3133 $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
3134 }
3135 if ( $this->undoAfter ) {
3136 $out->addHTML( Html::hidden( 'wpUndoAfter', $this->undoAfter ) );
3137 }
3138
3139 if ( $this->selfRedirect ) {
3140 $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
3141 }
3142
3143 $autosumm = $this->autoSumm !== '' ? $this->autoSumm : md5( $this->summary );
3144 $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
3145
3146 $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
3147 $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
3148
3149 $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
3150 $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
3151
3152 $out->enableOOUI();
3153
3154 if ( $this->section === 'new' ) {
3155 $this->showSummaryInput( true );
3156 $out->addHTML( $this->getSummaryPreview( true ) );
3157 }
3158
3159 $out->addHTML( $this->editFormTextBeforeContent );
3160 if ( $this->isConflict ) {
3161 $currentText = $this->toEditText( $this->getCurrentContent() );
3162
3163 $editConflictHelper = $this->getEditConflictHelper();
3164 $editConflictHelper->setTextboxes( $this->textbox1, $currentText );
3165 $editConflictHelper->setContentModel( $this->contentModel );
3166 $editConflictHelper->setContentFormat( $this->contentFormat );
3167 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
3168
3169 $this->textbox2 = $this->textbox1;
3170 $this->textbox1 = $currentText;
3171 }
3172
3173 if ( !$this->mTitle->isUserConfigPage() ) {
3174 $out->addHTML( self::getEditToolbar() );
3175 }
3176
3177 if ( $this->blankArticle ) {
3178 $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
3179 }
3180
3181 if ( $this->isConflict ) {
3182 // In an edit conflict bypass the overridable content form method
3183 // and fallback to the raw wpTextbox1 since editconflicts can't be
3184 // resolved between page source edits and custom ui edits using the
3185 // custom edit ui.
3186 $conflictTextBoxAttribs = [];
3187 if ( $this->wasDeletedSinceLastEdit() ) {
3188 $conflictTextBoxAttribs['style'] = 'display:none;';
3189 } elseif ( $this->isOldRev ) {
3190 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
3191 }
3192
3193 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
3194 // $editConflictHelper is declard, when isConflict is true
3195 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
3196 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
3197 // $editConflictHelper is declard, when isConflict is true
3198 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
3199 } else {
3200 $this->showContentForm();
3201 }
3202
3203 $out->addHTML( $this->editFormTextAfterContent );
3204
3205 $this->showStandardInputs();
3206
3207 $this->showFormAfterText();
3208
3209 $this->showTosSummary();
3210
3211 $this->showEditTools();
3212
3213 $out->addHTML( $this->editFormTextAfterTools . "\n" );
3214
3215 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
3216
3217 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
3218 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
3219
3220 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
3221 self::getPreviewLimitReport( $this->mParserOutput ) ) );
3222
3223 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
3224
3225 if ( $this->isConflict ) {
3226 try {
3227 $this->showConflict();
3228 } catch ( MWContentSerializationException $ex ) {
3229 // this can't really happen, but be nice if it does.
3230 $msg = $this->context->msg(
3231 'content-failed-to-parse',
3232 $this->contentModel,
3233 $this->contentFormat,
3234 $ex->getMessage()
3235 );
3236 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3237 }
3238 }
3239
3240 // Set a hidden field so JS knows what edit form mode we are in
3241 if ( $this->isConflict ) {
3242 $mode = 'conflict';
3243 } elseif ( $this->preview ) {
3244 $mode = 'preview';
3245 } elseif ( $this->diff ) {
3246 $mode = 'diff';
3247 } else {
3248 $mode = 'text';
3249 }
3250 $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
3251
3252 // Marker for detecting truncated form data. This must be the last
3253 // parameter sent in order to be of use, so do not move me.
3254 $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
3255 $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
3256
3257 if ( !$this->userOptionsLookup->getOption( $user, 'previewontop' ) ) {
3258 $this->displayPreviewArea( $previewOutput, false );
3259 }
3260 }
3261
3262 /**
3263 * Wrapper around TemplatesOnThisPageFormatter to make
3264 * a "templates on this page" list.
3265 *
3266 * @param PageIdentity[] $templates
3267 * @return string HTML
3268 */
3269 public function makeTemplatesOnThisPageList( array $templates ) {
3270 $templateListFormatter = new TemplatesOnThisPageFormatter(
3271 $this->context,
3272 $this->linkRenderer,
3273 $this->linkBatchFactory,
3274 $this->restrictionStore
3275 );
3276
3277 // preview if preview, else section if section, else false
3278 $type = false;
3279 if ( $this->preview ) {
3280 $type = 'preview';
3281 } elseif ( $this->section !== '' ) {
3282 $type = 'section';
3283 }
3284
3285 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
3286 $templateListFormatter->format( $templates, $type )
3287 );
3288 }
3289
3290 /**
3291 * Extract the section title from current section text, if any.
3292 *
3293 * @param string $text
3294 * @return string|false
3295 */
3296 private static function extractSectionTitle( $text ) {
3297 if ( preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches ) ) {
3298 return MediaWikiServices::getInstance()->getParser()
3299 ->stripSectionName( trim( $matches[2] ) );
3300 } else {
3301 return false;
3302 }
3303 }
3304
3305 private function showHeader(): void {
3306 $out = $this->context->getOutput();
3307 $user = $this->context->getUser();
3308 if ( $this->isConflict ) {
3309 $this->addExplainConflictHeader();
3310 $this->editRevId = $this->page->getLatest();
3311 } else {
3312 if ( $this->section !== '' && $this->section !== 'new' && $this->summary === '' &&
3313 !$this->preview && !$this->diff
3314 ) {
3315 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
3316 if ( $sectionTitle !== false ) {
3317 $this->summary = "/* $sectionTitle */ ";
3318 }
3319 }
3320
3321 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
3322
3323 if ( $this->missingComment ) {
3324 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3325 }
3326
3327 if ( $this->missingSummary && $this->section !== 'new' ) {
3328 $out->wrapWikiMsg(
3329 "<div id='mw-missingsummary'>\n$1\n</div>",
3330 [ 'missingsummary', $buttonLabel ]
3331 );
3332 }
3333
3334 if ( $this->missingSummary && $this->section === 'new' ) {
3335 $out->wrapWikiMsg(
3336 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3337 [ 'missingcommentheader', $buttonLabel ]
3338 );
3339 }
3340
3341 if ( $this->blankArticle ) {
3342 $out->wrapWikiMsg(
3343 "<div id='mw-blankarticle'>\n$1\n</div>",
3344 [ 'blankarticle', $buttonLabel ]
3345 );
3346 }
3347
3348 if ( $this->selfRedirect ) {
3349 $out->wrapWikiMsg(
3350 "<div id='mw-selfredirect'>\n$1\n</div>",
3351 [ 'selfredirect', $buttonLabel ]
3352 );
3353 }
3354
3355 if ( $this->hookError !== '' ) {
3356 $out->addWikiTextAsInterface( $this->hookError );
3357 }
3358
3359 if ( $this->section != 'new' ) {
3360 $revRecord = $this->mArticle->fetchRevisionRecord();
3361 if ( $revRecord && $revRecord instanceof RevisionStoreRecord ) {
3362 // Let sysop know that this will make private content public if saved
3363
3364 if ( !$revRecord->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
3365 $out->addHTML(
3366 Html::warningBox(
3367 $out->msg( 'rev-deleted-text-permission', $this->mTitle->getPrefixedDBkey() )->parse(),
3368 'plainlinks'
3369 )
3370 );
3371 } elseif ( $revRecord->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
3372 $out->addHTML(
3373 Html::warningBox(
3374 // title used in wikilinks, should not contain whitespaces
3375 $out->msg( 'rev-deleted-text-view', $this->mTitle->getPrefixedDBkey() )->parse(),
3376 'plainlinks'
3377 )
3378 );
3379 }
3380
3381 if ( !$revRecord->isCurrent() ) {
3382 $this->mArticle->setOldSubtitle( $revRecord->getId() );
3383 $this->isOldRev = true;
3384 }
3385 } elseif ( $this->mTitle->exists() ) {
3386 // Something went wrong
3387
3388 $out->addHTML(
3389 Html::errorBox(
3390 $out->msg( 'missing-revision', $this->oldid )->parse()
3391 )
3392 );
3393 }
3394 }
3395 }
3396
3397 $this->addLongPageWarningHeader();
3398 }
3399
3400 /**
3401 * Helper function for summary input functions, which returns the necessary
3402 * attributes for the input.
3403 *
3404 * @param array $inputAttrs Array of attrs to use on the input
3405 * @return array
3406 */
3407 private function getSummaryInputAttributes( array $inputAttrs ): array {
3408 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3409 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3410 // Unicode codepoints.
3411 return $inputAttrs + [
3412 'id' => 'wpSummary',
3413 'name' => 'wpSummary',
3414 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
3415 'tabindex' => 1,
3416 'size' => 60,
3417 'spellcheck' => 'true',
3418 ];
3419 }
3420
3421 /**
3422 * Builds a standard summary input with a label.
3423 *
3424 * @param string $summary The value of the summary input
3425 * @param string $labelText The html to place inside the label
3426 * @param array $inputAttrs Array of attrs to use on the input
3427 *
3428 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3429 */
3430 private function getSummaryInputWidget( $summary, string $labelText, array $inputAttrs ): FieldLayout {
3431 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3432 $this->getSummaryInputAttributes( $inputAttrs )
3433 );
3434 $inputAttrs += [
3435 'title' => Linker::titleAttrib( 'summary' ),
3436 'accessKey' => Linker::accesskey( 'summary' ),
3437 ];
3438
3439 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3440 $inputAttrs['inputId'] = $inputAttrs['id'];
3441 $inputAttrs['id'] = 'wpSummaryWidget';
3442
3443 return new OOUI\FieldLayout(
3444 new OOUI\TextInputWidget( [
3445 'value' => $summary,
3446 'infusable' => true,
3447 ] + $inputAttrs ),
3448 [
3449 'label' => new OOUI\HtmlSnippet( $labelText ),
3450 'align' => 'top',
3451 'id' => 'wpSummaryLabel',
3452 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3453 ]
3454 );
3455 }
3456
3457 /**
3458 * @param bool $isSubjectPreview True if this is the section subject/title
3459 * up top, or false if this is the comment summary
3460 * down below the textarea
3461 */
3462 private function showSummaryInput( bool $isSubjectPreview ): void {
3463 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3464 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3465 if ( $isSubjectPreview ) {
3466 if ( $this->nosummary ) {
3467 return;
3468 }
3469 } elseif ( !$this->mShowSummaryField ) {
3470 return;
3471 }
3472
3473 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3474 $this->context->getOutput()->addHTML(
3475 $this->getSummaryInputWidget(
3476 $isSubjectPreview ? $this->sectiontitle : $this->summary,
3477 $labelText,
3478 [ 'class' => $summaryClass ]
3479 )
3480 );
3481 }
3482
3483 /**
3484 * @param bool $isSubjectPreview True if this is the section subject/title
3485 * up top, or false if this is the comment summary
3486 * down below the textarea
3487 * @return string
3488 */
3489 private function getSummaryPreview( bool $isSubjectPreview ): string {
3490 // avoid spaces in preview, gets always trimmed on save
3491 $summary = trim( $this->summary );
3492 if ( $summary === '' || ( !$this->preview && !$this->diff ) ) {
3493 return "";
3494 }
3495
3496 $commentFormatter = MediaWikiServices::getInstance()->getCommentFormatter();
3497 $summary = $this->context->msg( 'summary-preview' )->parse()
3498 . $commentFormatter->formatBlock( $summary, $this->mTitle, $isSubjectPreview );
3499 return Html::rawElement( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3500 }
3501
3502 private function showFormBeforeText(): void {
3503 $out = $this->context->getOutput();
3504 $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
3505 $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
3506 $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
3507 $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
3508 $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
3509 }
3510
3511 protected function showFormAfterText() {
3512 /**
3513 * To make it harder for someone to slip a user a page
3514 * which submits an edit form to the wiki without their
3515 * knowledge, a random token is associated with the login
3516 * session. If it's not passed back with the submission,
3517 * we won't save the page, or render user JavaScript and
3518 * CSS previews.
3519 *
3520 * For anon editors, who may not have a session, we just
3521 * include the constant suffix to prevent editing from
3522 * broken text-mangling proxies.
3523 */
3524 $this->context->getOutput()->addHTML(
3525 "\n" .
3526 Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
3527 "\n"
3528 );
3529 }
3530
3531 /**
3532 * Subpage overridable method for printing the form for page content editing
3533 * By default this simply outputs wpTextbox1
3534 * Subclasses can override this to provide a custom UI for editing;
3535 * be it a form, or simply wpTextbox1 with a modified content that will be
3536 * reverse modified when extracted from the post data.
3537 * Note that this is basically the inverse for importContentFormData
3538 */
3539 protected function showContentForm() {
3540 $this->showTextbox1();
3541 }
3542
3543 private function showTextbox1(): void {
3544 if ( $this->formtype === 'save' && $this->wasDeletedSinceLastEdit() ) {
3545 $attribs = [ 'style' => 'display:none;' ];
3546 } else {
3547 $builder = new TextboxBuilder();
3548 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3549
3550 # Is an old revision being edited?
3551 if ( $this->isOldRev ) {
3552 $classes[] = 'mw-textarea-oldrev';
3553 }
3554
3555 $attribs = [
3556 'aria-label' => $this->context->msg( 'edit-textarea-aria-label' )->text(),
3557 'tabindex' => 1
3558 ];
3559
3560 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3561 }
3562
3563 $this->showTextbox(
3564 $this->textbox1,
3565 'wpTextbox1',
3566 $attribs
3567 );
3568 }
3569
3570 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3571 $builder = new TextboxBuilder();
3572 $attribs = $builder->buildTextboxAttribs(
3573 $name,
3574 $customAttribs,
3575 $this->context->getUser(),
3576 $this->mTitle
3577 );
3578
3579 $this->context->getOutput()->addHTML(
3580 Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3581 );
3582 }
3583
3584 private function displayPreviewArea( string $previewOutput, bool $isOnTop ): void {
3585 $attribs = [ 'id' => 'wikiPreview' ];
3586 if ( $isOnTop ) {
3587 $attribs['class'] = 'ontop';
3588 }
3589 if ( $this->formtype !== 'preview' ) {
3590 $attribs['style'] = 'display: none;';
3591 }
3592
3593 $out = $this->context->getOutput();
3594 $out->addHTML( Html::openElement( 'div', $attribs ) );
3595
3596 if ( $this->formtype === 'preview' ) {
3597 $this->showPreview( $previewOutput );
3598 }
3599
3600 $out->addHTML( '</div>' );
3601
3602 if ( $this->formtype === 'diff' ) {
3603 try {
3604 $this->showDiff();
3605 } catch ( MWContentSerializationException $ex ) {
3606 $msg = $this->context->msg(
3607 'content-failed-to-parse',
3608 $this->contentModel,
3609 $this->contentFormat,
3610 $ex->getMessage()
3611 );
3612 $out->wrapWikiTextAsInterface( 'error', $msg->plain() );
3613 }
3614 }
3615 }
3616
3617 /**
3618 * Append preview output to OutputPage.
3619 * Includes category rendering if this is a category page.
3620 *
3621 * @param string $text The HTML to be output for the preview.
3622 */
3623 private function showPreview( string $text ): void {
3624 if ( $this->mArticle instanceof CategoryPage ) {
3625 $this->mArticle->openShowCategory();
3626 }
3627 # This hook seems slightly odd here, but makes things more
3628 # consistent for extensions.
3629 $out = $this->context->getOutput();
3630 $this->getHookRunner()->onOutputPageBeforeHTML( $out, $text );
3631 $out->addHTML( $text );
3632 if ( $this->mArticle instanceof CategoryPage ) {
3633 $this->mArticle->closeShowCategory();
3634 }
3635 }
3636
3637 /**
3638 * Get a diff between the current contents of the edit box and the
3639 * version of the page we're editing from.
3640 *
3641 * If this is a section edit, we'll replace the section as for final
3642 * save and then make a comparison.
3643 */
3644 public function showDiff() {
3645 $oldtitlemsg = 'currentrev';
3646 # if message does not exist, show diff against the preloaded default
3647 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3648 $oldtext = $this->mTitle->getDefaultMessageText();
3649 if ( $oldtext !== false ) {
3650 $oldtitlemsg = 'defaultmessagetext';
3651 $oldContent = $this->toEditContent( $oldtext );
3652 } else {
3653 $oldContent = null;
3654 }
3655 } else {
3656 $oldContent = $this->getCurrentContent();
3657 }
3658
3659 $textboxContent = $this->toEditContent( $this->textbox1 );
3660 if ( $this->editRevId !== null ) {
3661 $newContent = $this->page->replaceSectionAtRev(
3662 $this->section, $textboxContent, $this->sectiontitle, $this->editRevId
3663 );
3664 } else {
3665 $newContent = $this->page->replaceSectionContent(
3666 $this->section, $textboxContent, $this->sectiontitle, $this->edittime
3667 );
3668 }
3669
3670 if ( $newContent ) {
3671 $this->getHookRunner()->onEditPageGetDiffContent( $this, $newContent );
3672
3673 $user = $this->getUserForPreview();
3674 $parserOptions = ParserOptions::newFromUserAndLang( $user,
3675 MediaWikiServices::getInstance()->getContentLanguage() );
3676 $services = MediaWikiServices::getInstance();
3677 $contentTransformer = $services->getContentTransformer();
3678 $newContent = $contentTransformer->preSaveTransform( $newContent, $this->mTitle, $user, $parserOptions );
3679 }
3680
3681 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3682 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3683 $newtitle = $this->context->msg( 'yourtext' )->parse();
3684
3685 if ( !$oldContent ) {
3686 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3687 }
3688
3689 if ( !$newContent ) {
3690 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3691 }
3692
3693 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
3694 $de->setContent( $oldContent, $newContent );
3695
3696 $difftext = $de->getDiff( $oldtitle, $newtitle );
3697 $de->showDiffStyle();
3698 } else {
3699 $difftext = '';
3700 }
3701
3702 $this->context->getOutput()->addHTML( Html::rawElement( 'div', [ 'id' => 'wikiDiff' ], $difftext ) );
3703 }
3704
3705 /**
3706 * Give a chance for site and per-namespace customizations of
3707 * terms of service summary link that might exist separately
3708 * from the copyright notice.
3709 *
3710 * This will display between the save button and the edit tools,
3711 * so should remain short!
3712 */
3713 private function showTosSummary(): void {
3714 $msgKey = 'editpage-tos-summary';
3715 $this->getHookRunner()->onEditPageTosSummary( $this->mTitle, $msgKey );
3716 $msg = $this->context->msg( $msgKey );
3717 if ( !$msg->isDisabled() ) {
3718 $this->context->getOutput()->addHTML( Html::rawElement(
3719 'div',
3720 [ 'class' => 'mw-tos-summary' ],
3721 $msg->parseAsBlock()
3722 ) );
3723 }
3724 }
3725
3726 /**
3727 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3728 * characters not present on most keyboards for copying/pasting.
3729 */
3730 private function showEditTools(): void {
3731 $this->context->getOutput()->addHTML( Html::rawElement(
3732 'div',
3733 [ 'class' => 'mw-editTools' ],
3734 $this->context->msg( 'edittools' )->inContentLanguage()->parse()
3735 ) );
3736 }
3737
3738 /**
3739 * Get the copyright warning.
3740 *
3741 * @param PageReference $page
3742 * @param string $format Output format, valid values are any function of a Message object
3743 * (e.g. 'parse', 'plain')
3744 * @param MessageLocalizer $localizer
3745 * @return string
3746 */
3747 public static function getCopyrightWarning( PageReference $page, string $format, MessageLocalizer $localizer ) {
3748 $services = MediaWikiServices::getInstance();
3749 $rightsText = $services->getMainConfig()->get( MainConfigNames::RightsText );
3750 if ( $rightsText ) {
3751 $copywarnMsg = [ 'copyrightwarning',
3752 '[[' . $localizer->msg( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3753 $rightsText ];
3754 } else {
3755 $copywarnMsg = [ 'copyrightwarning2',
3756 '[[' . $localizer->msg( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3757 }
3758 // Allow for site and per-namespace customization of contribution/copyright notice.
3759 $title = Title::newFromPageReference( $page );
3760 ( new HookRunner( $services->getHookContainer() ) )->onEditPageCopyrightWarning( $title, $copywarnMsg );
3761 if ( !$copywarnMsg ) {
3762 return '';
3763 }
3764
3765 $msg = $localizer->msg( ...$copywarnMsg )->page( $page );
3766 return Html::rawElement( 'div', [ 'id' => 'editpage-copywarn' ], $msg->$format() );
3767 }
3768
3769 /**
3770 * Get the Limit report for page previews
3771 *
3772 * @since 1.22
3773 * @param ParserOutput|null $output ParserOutput object from the parse
3774 * @return string HTML
3775 */
3776 public static function getPreviewLimitReport( ?ParserOutput $output = null ) {
3777 if ( !$output || !$output->getLimitReportData() ) {
3778 return '';
3779 }
3780
3781 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3782 wfMessage( 'limitreport-title' )->parseAsBlock()
3783 );
3784
3785 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3786 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3787
3788 $limitReport .= Html::openElement( 'table', [
3789 'class' => 'preview-limit-report wikitable'
3790 ] ) .
3791 Html::openElement( 'tbody' );
3792
3793 $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
3794 foreach ( $output->getLimitReportData() as $key => $value ) {
3795 if ( $hookRunner->onParserLimitReportFormat( $key, $value, $limitReport, true, true ) ) {
3796 $keyMsg = wfMessage( $key );
3797 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3798 if ( !$valueMsg->exists() ) {
3799 // This is formatted raw, not as localized number.
3800 // If you want the parameter formatted as a number,
3801 // define the `$key-value` message.
3802 $valueMsg = ( new RawMessage( '$1' ) )->params( $value );
3803 } else {
3804 // If you define the `$key-value` or `$key-value-html`
3805 // message then the argument *must* be numeric.
3806 $valueMsg = $valueMsg->numParams( $value );
3807 }
3808 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3809 $limitReport .= Html::openElement( 'tr' ) .
3810 Html::rawElement( 'th', [], $keyMsg->parse() ) .
3811 Html::rawElement( 'td', [], $valueMsg->parse() ) .
3812 Html::closeElement( 'tr' );
3813 }
3814 }
3815 }
3816
3817 $limitReport .= Html::closeElement( 'tbody' ) .
3818 Html::closeElement( 'table' ) .
3819 Html::closeElement( 'div' );
3820
3821 return $limitReport;
3822 }
3823
3824 protected function showStandardInputs( &$tabindex = 2 ) {
3825 $out = $this->context->getOutput();
3826 $out->addHTML( "<div class='editOptions'>\n" );
3827
3828 if ( $this->section !== 'new' ) {
3829 $this->showSummaryInput( false );
3830 $out->addHTML( $this->getSummaryPreview( false ) );
3831 }
3832
3833 // When previewing, override the selected dropdown option to select whatever was posted
3834 // (if it's a valid option) rather than the current value for watchlistExpiry.
3835 // See also above in $this->importFormData().
3836 $expiryFromRequest = null;
3837 if ( $this->preview || $this->diff || $this->isConflict ) {
3838 $expiryFromRequest = $this->getContext()->getRequest()->getText( 'wpWatchlistExpiry' );
3839 }
3840
3841 $checkboxes = $this->getCheckboxesWidget(
3842 $tabindex,
3843 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis, 'wpWatchlistExpiry' => $expiryFromRequest ]
3844 );
3845 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => array_values( $checkboxes ) ] );
3846
3847 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3848
3849 // Show copyright warning.
3850 $out->addHTML( self::getCopyrightWarning( $this->mTitle, 'parse', $this->context ) );
3851 $out->addHTML( $this->editFormTextAfterWarn );
3852
3853 $out->addHTML( "<div class='editButtons'>\n" );
3854 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3855
3856 $cancel = $this->getCancelLink( $tabindex++ );
3857
3858 $edithelp = $this->getHelpLink() .
3859 $this->context->msg( 'word-separator' )->escaped() .
3860 $this->context->msg( 'newwindow' )->parse();
3861
3862 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3863 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3864 $out->addHTML( "</div><!-- editButtons -->\n" );
3865
3866 $this->getHookRunner()->onEditPage__showStandardInputs_options( $this, $out, $tabindex );
3867
3868 $out->addHTML( "</div><!-- editOptions -->\n" );
3869 }
3870
3871 /**
3872 * Show an edit conflict. textbox1 is already shown in showEditForm().
3873 * If you want to use another entry point to this function, be careful.
3874 */
3875 private function showConflict(): void {
3876 $out = $this->context->getOutput();
3877 if ( $this->getHookRunner()->onEditPageBeforeConflictDiff( $this, $out ) ) {
3878 $this->incrementConflictStats();
3879
3880 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3881 }
3882 }
3883
3884 private function incrementConflictStats(): void {
3885 $this->getEditConflictHelper()->incrementConflictStats( $this->context->getUser() );
3886 }
3887
3888 /**
3889 * @return string
3890 */
3891 private function getHelpLink(): string {
3892 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3893 $editHelpUrl = Skin::makeInternalOrExternalUrl( $message );
3894 return Html::element( 'a', [
3895 'href' => $editHelpUrl,
3896 'target' => 'helpwindow'
3897 ], $this->context->msg( 'edithelp' )->text() );
3898 }
3899
3900 /**
3901 * @param int $tabindex Current tabindex
3902 * @return ButtonWidget
3903 */
3904 private function getCancelLink( int $tabindex ): ButtonWidget {
3905 $cancelParams = [];
3906 if ( !$this->isConflict && $this->oldid > 0 ) {
3907 $cancelParams['oldid'] = $this->oldid;
3908 } elseif ( $this->getContextTitle()->isRedirect() ) {
3909 $cancelParams['redirect'] = 'no';
3910 }
3911
3912 return new OOUI\ButtonWidget( [
3913 'id' => 'mw-editform-cancel',
3914 'tabIndex' => $tabindex,
3915 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3916 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3917 'framed' => false,
3918 'infusable' => true,
3919 'flags' => 'destructive',
3920 ] );
3921 }
3922
3923 /**
3924 * Returns the URL to use in the form's action attribute.
3925 * This is used by EditPage subclasses when simply customizing the action
3926 * variable in the constructor is not enough. This can be used when the
3927 * EditPage lives inside of a Special page rather than a custom page action.
3928 *
3929 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3930 * @return string
3931 */
3932 protected function getActionURL( Title $title ) {
3933 return $title->getLocalURL( [ 'action' => $this->action ] );
3934 }
3935
3936 /**
3937 * Check if a page was deleted while the user was editing it, before submit.
3938 * Note that we rely on the logging table, which hasn't been always there,
3939 * but that doesn't matter, because this only applies to brand new
3940 * deletes.
3941 * @return bool
3942 */
3943 private function wasDeletedSinceLastEdit(): bool {
3944 if ( $this->deletedSinceEdit !== null ) {
3945 return $this->deletedSinceEdit;
3946 }
3947
3948 $this->deletedSinceEdit = false;
3949
3950 if ( !$this->mTitle->exists() && $this->mTitle->hasDeletedEdits() ) {
3951 $this->lastDelete = $this->getLastDelete();
3952 if ( $this->lastDelete ) {
3953 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3954 if ( $deleteTime > $this->starttime ) {
3955 $this->deletedSinceEdit = true;
3956 }
3957 }
3958 }
3959
3960 return $this->deletedSinceEdit;
3961 }
3962
3963 /**
3964 * Get the last log record of this page being deleted, if ever. This is
3965 * used to detect whether a delete occurred during editing.
3966 * @return stdClass|null
3967 */
3968 private function getLastDelete(): ?stdClass {
3969 $dbr = $this->connectionProvider->getReplicaDatabase();
3970 $commentQuery = $this->commentStore->getJoin( 'log_comment' );
3971 $data = $dbr->newSelectQueryBuilder()
3972 ->select( [
3973 'log_type',
3974 'log_action',
3975 'log_timestamp',
3976 'log_namespace',
3977 'log_title',
3978 'log_params',
3979 'log_deleted',
3980 'actor_name'
3981 ] )
3982 ->from( 'logging' )
3983 ->join( 'actor', null, 'actor_id=log_actor' )
3984 ->where( [
3985 'log_namespace' => $this->mTitle->getNamespace(),
3986 'log_title' => $this->mTitle->getDBkey(),
3987 'log_type' => 'delete',
3988 'log_action' => 'delete',
3989 ] )
3990 ->orderBy( [ 'log_timestamp', 'log_id' ], SelectQueryBuilder::SORT_DESC )
3991 ->queryInfo( $commentQuery )
3992 ->caller( __METHOD__ )
3993 ->fetchRow();
3994 // Quick paranoid permission checks...
3995 if ( $data !== false ) {
3996 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3997 $data->actor_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3998 }
3999
4000 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
4001 $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
4002 $data->log_comment_data = null;
4003 }
4004 }
4005
4006 return $data ?: null;
4007 }
4008
4009 /**
4010 * Get the rendered text for previewing.
4011 * @throws MWException
4012 * @return string
4013 */
4014 public function getPreviewText() {
4015 $out = $this->context->getOutput();
4016 $config = $this->context->getConfig();
4017
4018 if ( $config->get( MainConfigNames::RawHtml ) && !$this->mTokenOk ) {
4019 // Could be an offsite preview attempt. This is very unsafe if
4020 // HTML is enabled, as it could be an attack.
4021 $parsedNote = '';
4022 if ( $this->textbox1 !== '' ) {
4023 // Do not put big scary notice, if previewing the empty
4024 // string, which happens when you initially edit
4025 // a category page, due to automatic preview-on-open.
4026 $parsedNote = Html::rawElement( 'div', [ 'class' => 'previewnote' ],
4027 $out->parseAsInterface(
4028 $this->context->msg( 'session_fail_preview_html' )->plain()
4029 ) );
4030 }
4031 $this->incrementEditFailureStats( 'session_loss' );
4032 return $parsedNote;
4033 }
4034
4035 $note = '';
4036
4037 try {
4038 $content = $this->toEditContent( $this->textbox1 );
4039
4040 $previewHTML = '';
4041 if ( !$this->getHookRunner()->onAlternateEditPreview(
4042 $this, $content, $previewHTML, $this->mParserOutput )
4043 ) {
4044 return $previewHTML;
4045 }
4046
4047 # provide a anchor link to the editform
4048 $continueEditing = '<span class="mw-continue-editing">' .
4049 '[[#' . self::EDITFORM_ID . '|' .
4050 $this->context->getLanguage()->getArrow() . ' ' .
4051 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
4052 if ( $this->mTriedSave && !$this->mTokenOk ) {
4053 $note = $this->context->msg( 'session_fail_preview' )->plain();
4054 $this->incrementEditFailureStats( 'session_loss' );
4055 } elseif ( $this->incompleteForm ) {
4056 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
4057 if ( $this->mTriedSave ) {
4058 $this->incrementEditFailureStats( 'incomplete_form' );
4059 }
4060 } else {
4061 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
4062 }
4063
4064 # don't parse non-wikitext pages, show message about preview
4065 if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
4066 if ( $this->mTitle->isUserConfigPage() ) {
4067 $level = 'user';
4068 } elseif ( $this->mTitle->isSiteConfigPage() ) {
4069 $level = 'site';
4070 } else {
4071 $level = false;
4072 }
4073
4074 if ( $content->getModel() === CONTENT_MODEL_CSS ) {
4075 $format = 'css';
4076 if ( $level === 'user' && !$config->get( MainConfigNames::AllowUserCss ) ) {
4077 $format = false;
4078 }
4079 } elseif ( $content->getModel() === CONTENT_MODEL_JSON ) {
4080 $format = 'json';
4081 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
4082 $format = false;
4083 }
4084 } elseif ( $content->getModel() === CONTENT_MODEL_JAVASCRIPT ) {
4085 $format = 'js';
4086 if ( $level === 'user' && !$config->get( MainConfigNames::AllowUserJs ) ) {
4087 $format = false;
4088 }
4089 } else {
4090 $format = false;
4091 }
4092
4093 # Used messages to make sure grep find them:
4094 # Messages: usercsspreview, userjsonpreview, userjspreview,
4095 # sitecsspreview, sitejsonpreview, sitejspreview
4096 if ( $level && $format ) {
4097 $note = "<div id='mw-{$level}{$format}preview'>" .
4098 $this->context->msg( "{$level}{$format}preview" )->plain() .
4099 ' ' . $continueEditing . "</div>";
4100 }
4101 }
4102
4103 if ( $this->section === "new" ) {
4104 $content = $content->addSectionHeader( $this->sectiontitle );
4105 }
4106
4107 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
4108 $this->getHookRunner()->onEditPageGetPreviewContent( $this, $content );
4109
4110 $parserResult = $this->doPreviewParse( $content );
4111 $parserOutput = $parserResult['parserOutput'];
4112 $previewHTML = $parserResult['html'];
4113 $this->mParserOutput = $parserOutput;
4114 $out->addParserOutputMetadata( $parserOutput );
4115 if ( $out->userCanPreview() ) {
4116 $out->addContentOverride( $this->getTitle(), $content );
4117 }
4118
4119 if ( count( $parserOutput->getWarnings() ) ) {
4120 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
4121 }
4122
4123 } catch ( MWContentSerializationException $ex ) {
4124 $m = $this->context->msg(
4125 'content-failed-to-parse',
4126 $this->contentModel,
4127 $this->contentFormat,
4128 $ex->getMessage()
4129 );
4130 $note .= "\n\n" . $m->plain(); # gets parsed down below
4131 $previewHTML = '';
4132 }
4133
4134 if ( $this->isConflict ) {
4135 $conflict = Html::warningBox(
4136 $this->context->msg( 'previewconflict' )->escaped(),
4137 'mw-previewconflict'
4138 );
4139 } else {
4140 $conflict = '';
4141 }
4142
4143 $previewhead = Html::rawElement(
4144 'div', [ 'class' => 'previewnote' ],
4145 Html::rawElement(
4146 'h2', [ 'id' => 'mw-previewheader' ],
4147 $this->context->msg( 'preview' )->escaped()
4148 ) .
4149 Html::warningBox(
4150 $out->parseAsInterface( $note )
4151 ) . $conflict
4152 );
4153
4154 return $previewhead . $previewHTML . $this->previewTextAfterContent;
4155 }
4156
4157 private function incrementEditFailureStats( string $failureType ): void {
4158 MediaWikiServices::getInstance()->getStatsFactory()
4159 ->getCounter( 'edit_failure_total' )
4160 ->setLabel( 'cause', $failureType )
4161 ->setLabel( 'namespace', 'n/a' )
4162 ->setLabel( 'user_bucket', 'n/a' )
4163 ->copyToStatsdAt( 'edit.failures.' . $failureType )
4164 ->increment();
4165 }
4166
4167 /**
4168 * Get parser options for a preview
4169 * @return ParserOptions
4170 */
4171 protected function getPreviewParserOptions() {
4172 $parserOptions = $this->page->makeParserOptions( $this->context );
4173 $parserOptions->setRenderReason( 'page-preview' );
4174 $parserOptions->setIsPreview( true );
4175 $parserOptions->setIsSectionPreview( $this->section !== null && $this->section !== '' );
4176
4177 // XXX: we could call $parserOptions->setCurrentRevisionRecordCallback here to force the
4178 // current revision to be null during PST, until setupFakeRevision is called on
4179 // the ParserOptions. Currently, we rely on Parser::getRevisionRecordObject() to ignore
4180 // existing revisions in preview mode.
4181
4182 return $parserOptions;
4183 }
4184
4185 /**
4186 * Parse the page for a preview. Subclasses may override this class, in order
4187 * to parse with different options, or to otherwise modify the preview HTML.
4188 *
4189 * @param Content $content The page content
4190 * @return array with keys:
4191 * - parserOutput: The ParserOutput object
4192 * - html: The HTML to be displayed
4193 */
4194 protected function doPreviewParse( Content $content ) {
4195 $user = $this->getUserForPreview();
4196 $parserOptions = $this->getPreviewParserOptions();
4197
4198 // NOTE: preSaveTransform doesn't have a fake revision to operate on.
4199 // Parser::getRevisionRecordObject() will return null in preview mode,
4200 // causing the context user to be used for {{subst:REVISIONUSER}}.
4201 // XXX: Alternatively, we could also call setupFakeRevision()
4202 // before PST with $content.
4203 $services = MediaWikiServices::getInstance();
4204 $contentTransformer = $services->getContentTransformer();
4205 $contentRenderer = $services->getContentRenderer();
4206 $pstContent = $contentTransformer->preSaveTransform( $content, $this->mTitle, $user, $parserOptions );
4207 $parserOutput = $contentRenderer->getParserOutput( $pstContent, $this->mTitle, null, $parserOptions );
4208 $out = $this->context->getOutput();
4209 $skin = $out->getSkin();
4210 $skinOptions = $skin->getOptions();
4211 // TODO T371004 move runOutputPipeline out of $parserOutput
4212 // TODO T371022 ideally we clone here, but for now let's reproduce getText behaviour
4213 $oldHtml = $parserOutput->getRawText();
4214 $html = $parserOutput->runOutputPipeline( $parserOptions, [
4215 'allowClone' => 'false',
4216 'userLang' => $skin->getLanguage(),
4217 'injectTOC' => $skinOptions['toc'],
4218 'enableSectionEditLinks' => false,
4219 'includeDebugInfo' => true,
4220 ] )->getContentHolderText();
4221 $parserOutput->setRawText( $oldHtml );
4222 return [
4223 'parserOutput' => $parserOutput,
4224 'html' => $html
4225 ];
4226 }
4227
4228 /**
4229 * @return Title[]
4230 */
4231 public function getTemplates() {
4232 if ( $this->preview || $this->section !== '' ) {
4233 $templates = [];
4234 if ( !isset( $this->mParserOutput ) ) {
4235 return $templates;
4236 }
4237 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
4238 foreach ( $template as $dbk => $_ ) {
4239 $templates[] = Title::makeTitle( $ns, $dbk );
4240 }
4241 }
4242 return $templates;
4243 } else {
4244 return $this->mTitle->getTemplateLinksFrom();
4245 }
4246 }
4247
4248 /**
4249 * Allow extensions to provide a toolbar.
4250 *
4251 * @return string|null
4252 */
4253 public static function getEditToolbar() {
4254 $startingToolbar = '<div id="toolbar"></div>';
4255 $toolbar = $startingToolbar;
4256
4257 $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
4258 if ( !$hookRunner->onEditPageBeforeEditToolbar( $toolbar ) ) {
4259 return null;
4260 }
4261 // Don't add a pointless `<div>` to the page unless a hook caller populated it
4262 return ( $toolbar === $startingToolbar ) ? null : $toolbar;
4263 }
4264
4265 /**
4266 * Return an array of field definitions. Despite the name, not only checkboxes are supported.
4267 *
4268 * Array keys correspond to the `<input>` 'name' attribute to use for each field.
4269 *
4270 * Array values are associative arrays with the following keys:
4271 * - 'label-message' (required): message for label text
4272 * - 'id' (required): 'id' attribute for the `<input>`
4273 * - 'default' (required): default checkedness (true or false)
4274 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4275 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4276 * from messages like 'tooltip-foo', 'accesskey-foo'
4277 * - 'label-id' (optional): 'id' attribute for the `<label>`
4278 * - 'legacy-name' (optional): short name for backwards-compatibility
4279 * - 'class' (optional): PHP class name of the OOUI widget to use. Defaults to
4280 * CheckboxInputWidget.
4281 * - 'options' (optional): options to use for DropdownInputWidget,
4282 * ComboBoxInputWidget, etc. following the structure as given in the documentation for those
4283 * classes.
4284 * - 'value-attr' (optional): name of the widget config option for the "current value" of the
4285 * widget. Defaults to 'selected'; for some widget types it should be 'value'.
4286 * @param array<string,mixed> $values Map of field names (matching the 'legacy-name') to current field values.
4287 * For checkboxes, the value is a bool that indicates the checked status of the checkbox.
4288 * @return array[]
4289 */
4290 public function getCheckboxesDefinition( $values ) {
4291 $checkboxes = [];
4292
4293 $user = $this->context->getUser();
4294 // don't show the minor edit checkbox if it's a new page or section
4295 if ( !$this->isNew && $this->permManager->userHasRight( $user, 'minoredit' ) ) {
4296 $checkboxes['wpMinoredit'] = [
4297 'id' => 'wpMinoredit',
4298 'label-message' => 'minoredit',
4299 // Uses messages: tooltip-minoredit, accesskey-minoredit
4300 'tooltip' => 'minoredit',
4301 'label-id' => 'mw-editpage-minoredit',
4302 'legacy-name' => 'minor',
4303 'default' => $values['minor'],
4304 ];
4305 }
4306
4307 if ( $user->isNamed() ) {
4308 $checkboxes = array_merge(
4309 $checkboxes,
4310 $this->getCheckboxesDefinitionForWatchlist( $values['watch'], $values['wpWatchlistExpiry'] ?? null )
4311 );
4312 }
4313
4314 $this->getHookRunner()->onEditPageGetCheckboxesDefinition( $this, $checkboxes );
4315
4316 return $checkboxes;
4317 }
4318
4319 /**
4320 * Get the watchthis and watchlistExpiry form field definitions.
4321 *
4322 * @param bool $watch
4323 * @param string $watchexpiry
4324 * @return array[]
4325 */
4326 private function getCheckboxesDefinitionForWatchlist( $watch, $watchexpiry ): array {
4327 $fieldDefs = [
4328 'wpWatchthis' => [
4329 'id' => 'wpWatchthis',
4330 'label-message' => 'watchthis',
4331 // Uses messages: tooltip-watch, accesskey-watch
4332 'tooltip' => 'watch',
4333 'label-id' => 'mw-editpage-watch',
4334 'legacy-name' => 'watch',
4335 'default' => $watch,
4336 ]
4337 ];
4338 if ( $this->watchlistExpiryEnabled ) {
4339 $watchedItem = $this->watchedItemStore->getWatchedItem( $this->getContext()->getUser(), $this->getTitle() );
4340 $expiryOptions = WatchAction::getExpiryOptions( $this->getContext(), $watchedItem );
4341 if ( $watchexpiry && in_array( $watchexpiry, $expiryOptions['options'] ) ) {
4342 $expiryOptions['default'] = $watchexpiry;
4343 }
4344 // Reformat the options to match what DropdownInputWidget wants.
4345 $options = [];
4346 foreach ( $expiryOptions['options'] as $label => $value ) {
4347 $options[] = [ 'data' => $value, 'label' => $label ];
4348 }
4349 $fieldDefs['wpWatchlistExpiry'] = [
4350 'id' => 'wpWatchlistExpiry',
4351 'label-message' => 'confirm-watch-label',
4352 // Uses messages: tooltip-watchlist-expiry, accesskey-watchlist-expiry
4353 'tooltip' => 'watchlist-expiry',
4354 'label-id' => 'mw-editpage-watchlist-expiry',
4355 'default' => $expiryOptions['default'],
4356 'value-attr' => 'value',
4357 'class' => DropdownInputWidget::class,
4358 'options' => $options,
4359 'invisibleLabel' => true,
4360 ];
4361 }
4362 return $fieldDefs;
4363 }
4364
4365 /**
4366 * Returns an array of fields for the edit form, including 'minor' and 'watch' checkboxes and
4367 * any other added by extensions. Despite the name, not only checkboxes are supported.
4368 *
4369 * @param int &$tabindex Current tabindex
4370 * @param array<string,mixed> $values Map of field names to current field values.
4371 * For checkboxes, the value is a bool that indicates the checked status of the checkbox.
4372 * @return \OOUI\Element[] Associative array of string keys to \OOUI\Widget or \OOUI\Layout
4373 * instances
4374 */
4375 public function getCheckboxesWidget( &$tabindex, $values ) {
4376 $checkboxes = [];
4377 $checkboxesDef = $this->getCheckboxesDefinition( $values );
4378
4379 foreach ( $checkboxesDef as $name => $options ) {
4380 $legacyName = $options['legacy-name'] ?? $name;
4381
4382 $title = null;
4383 $accesskey = null;
4384 if ( isset( $options['tooltip'] ) ) {
4385 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4386 $title = Linker::titleAttrib( $options['tooltip'] );
4387 }
4388 if ( isset( $options['title-message'] ) ) {
4389 $title = $this->context->msg( $options['title-message'] )->text();
4390 }
4391 // Allow checkbox definitions to set their own class and value-attribute names.
4392 // See $this->getCheckboxesDefinition() for details.
4393 $className = $options['class'] ?? CheckboxInputWidget::class;
4394 $valueAttr = $options['value-attr'] ?? 'selected';
4395 $checkboxes[ $legacyName ] = new FieldLayout(
4396 new $className( [
4397 'tabIndex' => ++$tabindex,
4398 'accessKey' => $accesskey,
4399 'id' => $options['id'] . 'Widget',
4400 'inputId' => $options['id'],
4401 'name' => $name,
4402 $valueAttr => $options['default'],
4403 'infusable' => true,
4404 'options' => $options['options'] ?? null,
4405 ] ),
4406 [
4407 'align' => 'inline',
4408 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4409 'title' => $title,
4410 'id' => $options['label-id'] ?? null,
4411 'invisibleLabel' => $options['invisibleLabel'] ?? null,
4412 ]
4413 );
4414 }
4415
4416 return $checkboxes;
4417 }
4418
4419 /**
4420 * Get the message key of the label for the button to save the page
4421 *
4422 * @return string
4423 */
4424 private function getSubmitButtonLabel(): string {
4425 $labelAsPublish =
4426 $this->context->getConfig()->get( MainConfigNames::EditSubmitButtonLabelPublish );
4427
4428 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4429 $newPage = !$this->mTitle->exists();
4430
4431 if ( $labelAsPublish ) {
4432 $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4433 } else {
4434 $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4435 }
4436
4437 return $buttonLabelKey;
4438 }
4439
4440 /**
4441 * Returns an array of html code of the following buttons:
4442 * save, diff and preview
4443 *
4444 * @param int &$tabindex Current tabindex
4445 *
4446 * @return string[] Strings or objects with a __toString() implementation. Usually an array of
4447 * {@see ButtonInputWidget}, but EditPageBeforeEditButtons hook handlers might inject something
4448 * else.
4449 */
4450 public function getEditButtons( &$tabindex ) {
4451 $buttons = [];
4452
4453 $labelAsPublish =
4454 $this->context->getConfig()->get( MainConfigNames::EditSubmitButtonLabelPublish );
4455
4456 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
4457 $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
4458
4459 $buttons['save'] = new OOUI\ButtonInputWidget( [
4460 'name' => 'wpSave',
4461 'tabIndex' => ++$tabindex,
4462 'id' => 'wpSaveWidget',
4463 'inputId' => 'wpSave',
4464 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4465 'useInputTag' => true,
4466 'flags' => [ 'progressive', 'primary' ],
4467 'label' => $buttonLabel,
4468 'infusable' => true,
4469 'type' => 'submit',
4470 // Messages used: tooltip-save, tooltip-publish
4471 'title' => Linker::titleAttrib( $buttonTooltip ),
4472 // Messages used: accesskey-save, accesskey-publish
4473 'accessKey' => Linker::accesskey( $buttonTooltip ),
4474 ] );
4475
4476 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4477 'name' => 'wpPreview',
4478 'tabIndex' => ++$tabindex,
4479 'id' => 'wpPreviewWidget',
4480 'inputId' => 'wpPreview',
4481 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4482 'useInputTag' => true,
4483 'label' => $this->context->msg( 'showpreview' )->text(),
4484 'infusable' => true,
4485 'type' => 'submit',
4486 // Allow previewing even when the form is in invalid state (T343585)
4487 'formNoValidate' => true,
4488 // Message used: tooltip-preview
4489 'title' => Linker::titleAttrib( 'preview' ),
4490 // Message used: accesskey-preview
4491 'accessKey' => Linker::accesskey( 'preview' ),
4492 ] );
4493
4494 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4495 'name' => 'wpDiff',
4496 'tabIndex' => ++$tabindex,
4497 'id' => 'wpDiffWidget',
4498 'inputId' => 'wpDiff',
4499 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4500 'useInputTag' => true,
4501 'label' => $this->context->msg( 'showdiff' )->text(),
4502 'infusable' => true,
4503 'type' => 'submit',
4504 // Allow previewing even when the form is in invalid state (T343585)
4505 'formNoValidate' => true,
4506 // Message used: tooltip-diff
4507 'title' => Linker::titleAttrib( 'diff' ),
4508 // Message used: accesskey-diff
4509 'accessKey' => Linker::accesskey( 'diff' ),
4510 ] );
4511
4512 $this->getHookRunner()->onEditPageBeforeEditButtons( $this, $buttons, $tabindex );
4513
4514 return $buttons;
4515 }
4516
4517 /**
4518 * Creates a basic error page which informs the user that
4519 * they have attempted to edit a nonexistent section.
4520 */
4521 private function noSuchSectionPage(): void {
4522 $out = $this->context->getOutput();
4523 $out->prepareErrorPage();
4524 $out->setPageTitleMsg( $this->context->msg( 'nosuchsectiontitle' ) );
4525
4526 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4527
4528 $this->getHookRunner()->onEditPageNoSuchSection( $this, $res );
4529 $out->addHTML( $res );
4530
4531 $out->returnToMain( false, $this->mTitle );
4532 }
4533
4534 /**
4535 * Show "your edit contains spam" page with your diff and text
4536 *
4537 * @param string|array|false $match Text (or array of texts) which triggered one or more filters
4538 */
4539 public function spamPageWithContent( $match = false ) {
4540 $this->textbox2 = $this->textbox1;
4541
4542 $out = $this->context->getOutput();
4543 $out->prepareErrorPage();
4544 $out->setPageTitleMsg( $this->context->msg( 'spamprotectiontitle' ) );
4545
4546 $spamText = $this->context->msg( 'spamprotectiontext' )->parseAsBlock();
4547
4548 if ( $match ) {
4549 if ( is_array( $match ) ) {
4550 $matchText = $this->context->getLanguage()->listToText( array_map( 'wfEscapeWikiText', $match ) );
4551 } else {
4552 $matchText = wfEscapeWikiText( $match );
4553 }
4554
4555 $spamText .= $this->context->msg( 'spamprotectionmatch' )
4556 ->params( $matchText )
4557 ->parseAsBlock();
4558 }
4559 $out->addHTML( Html::rawElement(
4560 'div',
4561 [ 'id' => 'spamprotected' ],
4562 $spamText
4563 ) );
4564
4565 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4566 $this->showDiff();
4567
4568 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4569 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
4570
4571 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4572 }
4573
4574 private function addLongPageWarningHeader(): void {
4575 if ( $this->contentLength === false ) {
4576 $this->contentLength = strlen( $this->textbox1 );
4577 }
4578
4579 $out = $this->context->getOutput();
4580 $maxArticleSize = $this->context->getConfig()->get( MainConfigNames::MaxArticleSize );
4581 if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
4582 $lang = $this->context->getLanguage();
4583 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4584 [
4585 'longpageerror',
4586 $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4587 $lang->formatNum( $maxArticleSize )
4588 ]
4589 );
4590 } else {
4591 $longPageHint = $this->context->msg( 'longpage-hint' );
4592 if ( !$longPageHint->isDisabled() ) {
4593 $msgText = trim( $longPageHint->sizeParams( $this->contentLength )
4594 ->params( $this->contentLength ) // Keep this unformatted for math inside message
4595 ->text() );
4596 if ( $msgText !== '' && $msgText !== '-' ) {
4597 $out->addWikiTextAsInterface( "<div id='mw-edit-longpage-hint'>\n$msgText\n</div>" );
4598 }
4599 }
4600 }
4601 }
4602
4603 private function addExplainConflictHeader(): void {
4604 $this->context->getOutput()->addHTML(
4605 $this->getEditConflictHelper()->getExplainHeader()
4606 );
4607 }
4608
4609 /**
4610 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4611 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4612 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4613 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4614 * spread the new style links more efficiently.
4615 *
4616 * @param string $text
4617 * @return string
4618 */
4619 private function guessSectionName( $text ): string {
4620 // Detect Microsoft browsers
4621 $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
4622 $parser = MediaWikiServices::getInstance()->getParser();
4623 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4624 // ...and redirect them to legacy encoding, if available
4625 return $parser->guessLegacySectionNameFromWikiText( $text );
4626 }
4627 // Meanwhile, real browsers get real anchors
4628 $name = $parser->guessSectionNameFromWikiText( $text );
4629 // With one little caveat: per T216029, fragments in HTTP redirects need to be urlencoded,
4630 // otherwise Chrome double-escapes the rest of the URL.
4631 return '#' . urlencode( mb_substr( $name, 1 ) );
4632 }
4633
4634 /**
4635 * @param callable $factory Factory function to create a {@see TextConflictHelper}
4636 * @since 1.31
4637 */
4638 public function setEditConflictHelperFactory( callable $factory ) {
4639 Assert::precondition( !$this->editConflictHelperFactory,
4640 'Can only have one extension that resolves edit conflicts' );
4641 $this->editConflictHelperFactory = $factory;
4642 }
4643
4644 private function getEditConflictHelper(): TextConflictHelper {
4645 if ( !$this->editConflictHelper ) {
4646 $label = $this->getSubmitButtonLabel();
4647 if ( $this->editConflictHelperFactory ) {
4648 $this->editConflictHelper = ( $this->editConflictHelperFactory )( $label );
4649 } else {
4650 $this->editConflictHelper = new TextConflictHelper(
4651 $this->getTitle(),
4652 $this->getContext()->getOutput(),
4653 MediaWikiServices::getInstance()->getStatsFactory(),
4654 $label,
4655 MediaWikiServices::getInstance()->getContentHandlerFactory()
4656 );
4657 }
4658 }
4659 return $this->editConflictHelper;
4660 }
4661 }
4662
4663 /** @deprecated class alias since 1.40 */
4664 class_alias( EditPage::class, 'EditPage' );