Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 179
0.00% covered (danger)
0.00%
0 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialChangeContentModel
0.00% covered (danger)
0.00%
0 / 179
0.00% covered (danger)
0.00%
0 / 19
2652
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 doesWrites
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getTitle
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getStashKeyForTitle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handleRetrievedData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setParameter
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 execute
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 postHtml
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 getDisplayFormat
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 alterForm
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 checkPermissions
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 validateTitle
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 preHtml
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 getFormFields
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
42
 getOptionsForTitle
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 onSubmit
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
12
 onSuccess
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 prefixSearchSubpages
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace MediaWiki\Specials;
4
5use MediaWiki\Collation\CollationFactory;
6use MediaWiki\CommentStore\CommentStore;
7use MediaWiki\Content\ContentHandler;
8use MediaWiki\Content\IContentHandlerFactory;
9use MediaWiki\EditPage\DataStashTrait;
10use MediaWiki\EditPage\SpamChecker;
11use MediaWiki\Exception\ErrorPageError;
12use MediaWiki\Exception\PermissionsError;
13use MediaWiki\Html\Html;
14use MediaWiki\HTMLForm\HTMLForm;
15use MediaWiki\Language\RawMessage;
16use MediaWiki\Logging\LogEventsList;
17use MediaWiki\Logging\LogPage;
18use MediaWiki\Page\ContentModelChangeFactory;
19use MediaWiki\Page\WikiPageFactory;
20use MediaWiki\Permissions\PermissionManager;
21use MediaWiki\Revision\RevisionLookup;
22use MediaWiki\Revision\RevisionRecord;
23use MediaWiki\Revision\SlotRecord;
24use MediaWiki\Search\SearchEngineFactory;
25use MediaWiki\SpecialPage\FormSpecialPage;
26use MediaWiki\Status\Status;
27use MediaWiki\Title\Title;
28use StatusValue;
29
30/**
31 * @ingroup SpecialPage
32 */
33class SpecialChangeContentModel extends FormSpecialPage {
34    use DataStashTrait;
35
36    public function __construct(
37        private readonly IContentHandlerFactory $contentHandlerFactory,
38        private readonly ContentModelChangeFactory $contentModelChangeFactory,
39        private readonly SpamChecker $spamChecker,
40        private readonly RevisionLookup $revisionLookup,
41        private readonly WikiPageFactory $wikiPageFactory,
42        private readonly SearchEngineFactory $searchEngineFactory,
43        private readonly CollationFactory $collationFactory,
44        private readonly PermissionManager $permissionManager,
45    ) {
46        parent::__construct( 'ChangeContentModel' );
47    }
48
49    /** @inheritDoc */
50    public function doesWrites() {
51        return true;
52    }
53
54    /**
55     * @var Title|null
56     */
57    private $title;
58
59    /**
60     * @var RevisionRecord|bool|null
61     *
62     * A RevisionRecord object, false if no revision exists, null if not loaded yet
63     */
64    private $oldRevision;
65
66    private string $oldContentModel;
67
68    private bool $titleExisted;
69
70    private string $newContentModel;
71
72    private ?array $stashedData = null;
73
74    private bool $reauthInProgress = false;
75
76    protected function getTitle(): Title {
77        return $this->title
78            ? $this->getPageTitle( $this->title->getPrefixedText() )
79            : $this->getPageTitle();
80    }
81
82    private function getStashKeyForTitle( Title $title ): string {
83        return $this->getName() . ':' . $title->getPrefixedDBkey();
84    }
85
86    protected function handleRetrievedData( array $data ): void {
87        $this->stashedData = $data;
88    }
89
90    /** @inheritDoc */
91    protected function setParameter( $par ) {
92        $par = $this->getRequest()->getVal( 'pagetitle', $par );
93        $title = Title::newFromText( $par );
94        if ( $title ) {
95            $this->title = $title;
96            $this->par = $title->getPrefixedText();
97        } else {
98            $this->par = '';
99        }
100    }
101
102    /** @inheritDoc */
103    public function execute( $par ) {
104        $this->setParameter( $par );
105        if ( $this->title ) {
106            $this->setStashKey( $this->getStashKeyForTitle( $this->title ) );
107            if ( $this->retrieveStashedData() ) {
108                $this->setHeaders();
109                $this->outputHeader();
110                $this->checkExecutePermissions( $this->getUser() );
111
112                $result = $this->onSubmit( $this->stashedData );
113                if ( $this->reauthInProgress ) {
114                    return;
115                }
116                $this->destroyStashedData();
117                if ( $result === true || ( $result instanceof StatusValue && $result->isGood() ) ) {
118                    $this->onSuccess();
119                } else {
120                    $this->getForm()->prepareForm()->displayForm( $result );
121                }
122                return;
123            }
124        }
125
126        parent::execute( $par );
127    }
128
129    /** @inheritDoc */
130    protected function postHtml() {
131        $text = '';
132        if ( $this->title ) {
133            $contentModelLogPage = new LogPage( 'contentmodel' );
134            $text = Html::element( 'h2', [], $contentModelLogPage->getName()->text() );
135            $out = '';
136            LogEventsList::showLogExtract( $out, 'contentmodel', $this->title );
137            $text .= $out;
138        }
139        return $text;
140    }
141
142    /** @inheritDoc */
143    protected function getDisplayFormat() {
144        return 'ooui';
145    }
146
147    protected function alterForm( HTMLForm $form ) {
148        $this->addHelpLink( 'Help:ChangeContentModel' );
149
150        if ( $this->title ) {
151            $form->setFormIdentifier( 'modelform' );
152            if ( $this->title->exists() ) {
153                // T120576
154                $form->setSubmitTextMsg( 'changecontentmodel-submit' );
155            } else {
156                $form->setSubmitTextMsg( 'changecontentmodel-create-submit' );
157            }
158            $this->getOutput()->addBacklinkSubtitle( $this->title );
159        } else {
160            $form->setFormIdentifier( 'titleform' );
161            // T120576
162            $form->setSubmitTextMsg( 'changecontentmodel-submit' );
163        }
164    }
165
166    /** @inheritDoc */
167    public function checkPermissions() {
168        $user = $this->getUser();
169        if ( $this->title ) {
170            $perm = $this->title->exists() ? 'editcontentmodel' : 'createwithcontentmodel';
171            $this->permissionManager->throwPermissionErrors(
172                $perm,
173                $user,
174                $this->title,
175                PermissionManager::RIGOR_FULL
176            );
177        } elseif ( !$this->permissionManager->userHasAnyRight( $user, 'editcontentmodel', 'createwithcontentmodel' ) ) {
178            // The intended use case of this special page is to change the content model of an existing page
179            // nothing stops you from creating a new page with it but that's a hack so display the permission error
180            // for editing an existing page's content model if you can't do either
181            throw new PermissionsError( 'editcontentmodel' );
182        }
183    }
184
185    /**
186     * @param string $title
187     * @return string|bool
188     */
189    private function validateTitle( $title ) {
190        // Already validated by HTMLForm, but if not, throw
191        // an exception instead of a fatal
192        $titleObj = Title::newFromTextThrow( $title );
193
194        $this->oldRevision = $this->revisionLookup->getRevisionByTitle( $titleObj ) ?: false;
195
196        if ( $this->oldRevision ) {
197            $oldContent = $this->oldRevision->getContent( SlotRecord::MAIN );
198            if ( !$oldContent->getContentHandler()->supportsDirectEditing() ) {
199                return $this->msg( 'changecontentmodel-nodirectediting' )
200                    ->params( ContentHandler::getLocalizedName( $oldContent->getModel() ) )
201                    ->escaped();
202            }
203        }
204
205        return true;
206    }
207
208    /** @inheritDoc */
209    protected function preHtml() {
210        if ( $this->title ) {
211            // Checking permissions is handled by checkPermissions above
212            if ( $this->title->exists() ) {
213                $msg = $this->msg( 'changecontentmodel-editing', $this->title->getPrefixedText() );
214            } else {
215                $msg = $this->msg( 'changecontentmodel-create', $this->title->getPrefixedText() );
216            }
217        } elseif ( !$this->permissionManager->userHasRight( $this->getUser(), 'editcontentmodel' ) ) {
218            $msg = $this->msg( 'changecontentmodel-create-only' );
219        } else {
220            $msg = $this->msg( 'changecontentmodel-edit' );
221        }
222        return $msg->parseAsBlock();
223    }
224
225    /** @inheritDoc */
226    protected function getFormFields() {
227        $fields = [
228            'pagetitle' => [
229                'type' => 'title',
230                'creatable' => true,
231                'name' => 'pagetitle',
232                'default' => $this->par,
233                'label-message' => 'changecontentmodel-title-label',
234                'validation-callback' => $this->validateTitle( ... ),
235                // If you need to enter a non-existing page then don't show autocomplete for existing ones ...
236                'suggestions' => $this->permissionManager->userHasRight( $this->getUser(), 'editcontentmodel' ),
237            ],
238        ];
239        if ( $this->title ) {
240            $options = $this->getOptionsForTitle( $this->title );
241            if ( !$options ) {
242                throw new ErrorPageError(
243                    'changecontentmodel-emptymodels-title',
244                    'changecontentmodel-emptymodels-text',
245                    [ $this->title->getPrefixedText() ]
246                );
247            }
248            $fields['pagetitle']['readonly'] = true;
249            $fields += [
250                'model' => [
251                    'type' => 'select',
252                    'name' => 'model',
253                    'default' => $this->title->getContentModel(),
254                    'options' => $options,
255                    'label-message' => 'changecontentmodel-model-label'
256                ],
257                'reason' => [
258                    'type' => 'text',
259                    'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
260                    'name' => 'reason',
261                    'validation-callback' => function ( $reason ) {
262                        if ( $reason === null || $reason === '' ) {
263                            // Null on form display, or no reason given
264                            return true;
265                        }
266
267                        $match = $this->spamChecker->checkSummary( $reason );
268
269                        if ( $match ) {
270                            return $this->msg( 'spamprotectionmatch', $match )->parse();
271                        }
272
273                        return true;
274                    },
275                    'label-message' => 'changecontentmodel-reason-label',
276                ],
277            ];
278        }
279
280        return $fields;
281    }
282
283    /**
284     * @return array $options An array of data for an OOUI drop-down list. The array keys
285     * correspond to the human readable text in the drop-down list. The array values
286     * correspond to the <option value="">.
287     */
288    private function getOptionsForTitle( ?Title $title = null ) {
289        $models = $this->contentHandlerFactory->getContentModels();
290        $options = [];
291        foreach ( $models as $model ) {
292            $handler = $this->contentHandlerFactory->getContentHandler( $model );
293            if ( !$handler->supportsDirectEditing() ) {
294                continue;
295            }
296            if ( $title ) {
297                if ( !$handler->canBeUsedOn( $title ) ) {
298                    continue;
299                }
300            }
301            $options[ContentHandler::getLocalizedName( $model )] = $model;
302        }
303
304        // Put the options in the drop-down list in alphabetical order.
305        // Sort by array key, case insensitive.
306        $collation = $this->collationFactory->getCategoryCollation();
307        uksort( $options, static function ( $a, $b ) use ( $collation ) {
308            $a = $collation->getSortKey( $a );
309            $b = $collation->getSortKey( $b );
310            return strcmp( $a, $b );
311        } );
312
313        return $options;
314    }
315
316    /** @inheritDoc */
317    public function onSubmit( array $data ) {
318        $this->reauthInProgress = false;
319        $this->title = Title::newFromText( $data['pagetitle'] );
320        $this->titleExisted = $this->title->exists();
321        $this->oldContentModel = $this->title->getContentModel();
322        $this->newContentModel = $data['model'];
323        $page = $this->wikiPageFactory->newFromTitle( $this->title );
324
325        $changer = $this->contentModelChangeFactory->newContentModelChange(
326                $this->getContext()->getAuthority(),
327                $page,
328                $data['model']
329            );
330
331        $permissionStatus = $changer->authorizeChange();
332        if ( !$permissionStatus->isGood() ) {
333            if ( $permissionStatus->getReauthOperation() !== null ) {
334                $this->setStashKey( $this->getStashKeyForTitle( $this->title ) );
335                $queryParams = $this->stashDataOnPost();
336                $this->doReauthRedirect( $permissionStatus, $queryParams );
337                $this->reauthInProgress = true;
338                return false;
339            }
340            $out = $this->getOutput();
341            $wikitext = $out->formatPermissionStatus( $permissionStatus );
342            // Hack to get our wikitext parsed
343            return Status::newFatal( new RawMessage( '$1', [ $wikitext ] ) );
344        }
345
346        $status = $changer->doContentModelChange(
347            $this->getContext(),
348            $data['reason'],
349            true
350        );
351
352        return $status;
353    }
354
355    public function onSuccess() {
356        $out = $this->getOutput();
357        if ( $this->titleExisted ) {
358            $out->setPageTitleMsg( $this->msg( 'changecontentmodel-success-title' ) );
359            $out->addWikiMsg( 'changecontentmodel-success-text',
360                $this->title->getPrefixedText(),
361                ContentHandler::getLocalizedName( $this->oldContentModel, $this->getLanguage() ),
362                ContentHandler::getLocalizedName( $this->newContentModel, $this->getLanguage() )
363            );
364        } else {
365            $out->setPageTitleMsg( $this->msg( 'changecontentmodel-create-success-title' ) );
366            $out->addWikiMsg( 'changecontentmodel-create-success-text',
367                $this->title->getPrefixedText(),
368                ContentHandler::getLocalizedName( $this->newContentModel, $this->getLanguage() )
369            );
370        }
371    }
372
373    /**
374     * Return an array of subpages beginning with $search that this special page will accept.
375     *
376     * @param string $search Prefix to search for
377     * @param int $limit Maximum number of results to return (usually 10)
378     * @param int $offset Number of results to skip (usually 0)
379     * @return string[] Matching subpages
380     */
381    public function prefixSearchSubpages( $search, $limit, $offset ) {
382        return $this->prefixSearchString( $search, $limit, $offset, $this->searchEngineFactory );
383    }
384
385    /** @inheritDoc */
386    protected function getGroupName() {
387        return 'pagetools';
388    }
389}
390
391// @codeCoverageIgnoreStart
392/** @deprecated class alias since 1.41 */
393class_alias( SpecialChangeContentModel::class, 'SpecialChangeContentModel' );
394// @codeCoverageIgnoreEnd