Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.59% covered (success)
91.59%
207 / 226
71.43% covered (warning)
71.43%
15 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
SetEntitySchemaLabelDescriptionAliases
91.59% covered (success)
91.59%
207 / 226
71.43% covered (warning)
71.43%
15 / 21
44.10
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 submitEditFormCallback
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
2
 getDescription
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getIdFromSubpageOrRequest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getLanguageFromSubpageOrRequestOrUI
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 displaySchemaLanguageSelectionForm
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 displayEditForm
65.52% covered (warning)
65.52%
19 / 29
0.00% covered (danger)
0.00%
0 / 1
4.66
 isSecondForm
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSchemaNameBadge
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
3.43
 getSchemaSelectionFormFields
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
2
 getEditFormFields
100.00% covered (success)
100.00%
73 / 73
100.00% covered (success)
100.00%
1 / 1
1
 isSelectionDataValid
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 displayCopyright
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 displayWarnings
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 buildLanguageAndSchemaNotice
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 getSchemaDisplayLabel
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 getWarnings
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getRestriction
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 checkBlocked
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
1<?php
2
3declare( strict_types = 1 );
4
5namespace EntitySchema\MediaWiki\Specials;
6
7use EntitySchema\DataAccess\EntitySchemaStatus;
8use EntitySchema\DataAccess\MediaWikiRevisionEntitySchemaUpdater;
9use EntitySchema\Domain\Model\EntitySchemaId;
10use EntitySchema\MediaWiki\EntitySchemaRedirectTrait;
11use EntitySchema\Presentation\InputValidator;
12use EntitySchema\Services\Converter\EntitySchemaConverter;
13use EntitySchema\Services\Converter\NameBadge;
14use InvalidArgumentException;
15use MediaWiki\Exception\PermissionsError;
16use MediaWiki\Html\Html;
17use MediaWiki\HTMLForm\HTMLForm;
18use MediaWiki\Linker\LinkTarget;
19use MediaWiki\MediaWikiServices;
20use MediaWiki\Message\Message;
21use MediaWiki\Output\OutputPage;
22use MediaWiki\Request\WebRequest;
23use MediaWiki\Revision\SlotRecord;
24use MediaWiki\SpecialPage\SpecialPage;
25use MediaWiki\Status\Status;
26use MediaWiki\Title\Title;
27use MediaWiki\User\TempUser\TempUserConfig;
28use StatusValue;
29use Wikibase\Lib\SettingsArray;
30use Wikibase\Repo\CopyrightMessageBuilder;
31use Wikibase\Repo\Specials\SpecialPageCopyrightView;
32
33/**
34 * Page for editing label, description and aliases of a Schema
35 *
36 * @license GPL-2.0-or-later
37 */
38class SetEntitySchemaLabelDescriptionAliases extends SpecialPage {
39
40    use EntitySchemaRedirectTrait;
41
42    public const FIELD_ID = 'ID';
43    public const FIELD_LANGUAGE = 'languagecode';
44    public const FIELD_DESCRIPTION = 'description';
45    public const FIELD_LABEL = 'label';
46    public const FIELD_ALIASES = 'aliases';
47    public const FIELD_BASE_REV = 'base-rev';
48    private const SUBMIT_SELECTION_NAME = 'submit-selection';
49    private const SUBMIT_EDIT_NAME = 'submit-edit';
50
51    private string $htmlFormProvider;
52
53    private SpecialPageCopyrightView $copyrightView;
54
55    private TempUserConfig $tempUserConfig;
56
57    public function __construct(
58        TempUserConfig $tempUserConfig,
59        SettingsArray $repoSettings,
60        string $htmlFormProvider = HTMLForm::class
61    ) {
62        parent::__construct( 'SetEntitySchemaLabelDescriptionAliases' );
63
64        $this->htmlFormProvider = $htmlFormProvider;
65        $this->copyrightView = new SpecialPageCopyrightView(
66            new CopyrightMessageBuilder(),
67            $repoSettings->getSetting( 'dataRightsUrl' ),
68            $repoSettings->getSetting( 'dataRightsText' )
69        );
70        $this->tempUserConfig = $tempUserConfig;
71    }
72
73    /** @inheritDoc */
74    public function execute( $subPage ): void {
75        parent::execute( $subPage );
76
77        $request = $this->getRequest();
78        $subPage = $subPage ?: '';
79        $id = $this->getIdFromSubpageOrRequest( $subPage, $request );
80        $language = $this->getLanguageFromSubpageOrRequestOrUI( $subPage, $request );
81
82        if ( $this->isSelectionDataValid( $id, $language ) ) {
83            $baseRevId = $request->getInt( self::FIELD_BASE_REV );
84            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable isSelectionDataValid() guarantees $id !== null
85            $this->displayEditForm( new EntitySchemaId( $id ), $language, $baseRevId );
86            return;
87        }
88
89        $this->displaySchemaLanguageSelectionForm( $id, $language );
90    }
91
92    public function submitEditFormCallback( array $data ): StatusValue {
93        try {
94            $id = new EntitySchemaId( $data[self::FIELD_ID] );
95        } catch ( InvalidArgumentException ) {
96            return StatusValue::newFatal( 'entityschema-error-schemaupdate-failed' );
97        }
98        $title = Title::makeTitle( NS_ENTITYSCHEMA_JSON, $id->getId() );
99        $this->checkBlocked( $title );
100        $aliases = array_map( 'trim', explode( '|', $data[self::FIELD_ALIASES] ) );
101        $schemaUpdater = MediaWikiRevisionEntitySchemaUpdater::newFromContext( $this->getContext() );
102
103        $status = $schemaUpdater->updateSchemaNameBadge(
104            $id,
105            $data[self::FIELD_LANGUAGE],
106            $data[self::FIELD_LABEL],
107            $data[self::FIELD_DESCRIPTION],
108            $aliases,
109            (int)$data[self::FIELD_BASE_REV]
110        );
111        $status->replaceMessage( 'edit-conflict', 'entityschema-error-namebadge-conflict' );
112        return $status;
113    }
114
115    public function getDescription(): Message {
116        return $this->msg( 'entityschema-special-setlabeldescriptionaliases' );
117    }
118
119    private function getIdFromSubpageOrRequest( string $subpage, WebRequest $request ): ?string {
120        $subpageParts = array_filter( explode( '/', $subpage, 2 ) );
121        if ( count( $subpageParts ) > 0 ) {
122            return $subpageParts[0];
123        }
124        return $request->getText( self::FIELD_ID ) ?: null;
125    }
126
127    private function getLanguageFromSubpageOrRequestOrUI( string $subpage, WebRequest $request ): string {
128        $subpageParts = array_filter( explode( '/', $subpage, 2 ) );
129        if ( count( $subpageParts ) === 2 ) {
130            return $subpageParts[1];
131        }
132
133        return $request->getText( self::FIELD_LANGUAGE ) ?: $this->getLanguage()->getCode();
134    }
135
136    private function displaySchemaLanguageSelectionForm( ?string $defaultId, string $defaultLanguage ): void {
137        $formDescriptor = $this->getSchemaSelectionFormFields( $defaultId, $defaultLanguage );
138
139        $form = $this->htmlFormProvider::factory( 'ooui', $formDescriptor, $this->getContext() )
140            ->setSubmitName( self::SUBMIT_SELECTION_NAME )
141            ->setSubmitID( 'entityschema-special-schema-id-submit' )
142            ->setSubmitTextMsg( 'entityschema-special-id-submit' )
143            ->setTitle( $this->getPageTitle() );
144        $form->prepareForm();
145        $submitStatus = $form->tryAuthorizedSubmit();
146        $form->displayForm( $submitStatus ?: Status::newGood() );
147    }
148
149    private function displayEditForm( EntitySchemaId $id, string $langCode, int $baseRevId ): void {
150        $output = $this->getOutput();
151        $title = Title::makeTitle( NS_ENTITYSCHEMA_JSON, $id->getId() );
152        $schemaNameBadge = $this->getSchemaNameBadge( $title, $langCode, $baseRevId );
153        $formDescriptor = $this->getEditFormFields( $id, $langCode, $schemaNameBadge, $baseRevId );
154
155        $form = $this->htmlFormProvider::factory( 'ooui', $formDescriptor, $this->getContext() )
156            ->setSubmitName( self::SUBMIT_EDIT_NAME )
157            ->setSubmitID( 'entityschema-special-schema-id-submit' )
158            ->setSubmitTextMsg( 'entityschema-special-id-submit' )
159            ->setValidationErrorMessage( [ [
160                'entityschema-error-possibly-multiple-messages-available',
161            ] ] );
162        $form->prepareForm();
163
164        if ( !$this->isSecondForm() ) {
165            $form->setSubmitCallback( [ $this, 'submitEditFormCallback' ] );
166
167            $submitStatus = $form->tryAuthorizedSubmit();
168            if ( $submitStatus && $submitStatus->isGood() ) {
169                // cast it, in case HTMLForm turned it into a generic Status
170                $submitStatus = EntitySchemaStatus::cast( $submitStatus );
171                $this->redirectToEntitySchema( $submitStatus );
172                return;
173            }
174        }
175
176        $output->addModules( [
177            'ext.EntitySchema.special.setEntitySchemaLabelDescriptionAliases.edit',
178        ] );
179        $output->addJsConfigVars(
180            'wgEntitySchemaNameBadgeMaxSizeChars',
181            intval( $this->getConfig()->get( 'EntitySchemaNameBadgeMaxSizeChars' ) )
182        );
183        $this->displayWarnings( $output );
184        $form->displayForm( $submitStatus ?? Status::newGood() );
185        $this->displayCopyright( $output );
186    }
187
188    /**
189     * Check if the second form is requested.
190     */
191    private function isSecondForm(): bool {
192        return $this->getContext()->getRequest()->getCheck( self::SUBMIT_SELECTION_NAME );
193    }
194
195    /**
196     * Gets the Schema NameBadge (label, desc, aliases) by interface language
197     *
198     * @param Title $title instance of Title for a specific Schema
199     * @param string $langCode
200     * @param int &$revId the revision from which to load data, or 0 to load the latest revision
201     * of $title, in which case &$revId will be replaced with that revision's ID
202     *
203     * @return NameBadge
204     */
205    private function getSchemaNameBadge( Title $title, string $langCode, int &$revId ): NameBadge {
206        if ( $revId > 0 ) {
207            $revision = MediaWikiServices::getInstance()->getRevisionLookup()
208                ->getRevisionById( $revId );
209            if ( $revision->getPageId() !== $title->getArticleID() ) {
210                throw new InvalidArgumentException( 'revision does not match title' );
211            }
212        } else {
213            $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
214            $revision = $wikiPage->getRevisionRecord();
215            $revId = $revision->getId();
216        }
217        // @phan-suppress-next-line PhanUndeclaredMethod
218        $schema = $revision->getContent( SlotRecord::MAIN )->getText();
219        $converter = new EntitySchemaConverter();
220        return $converter->getMonolingualNameBadgeData( $schema, $langCode );
221    }
222
223    private function getSchemaSelectionFormFields( ?string $defaultId, string $defaultLanguage ): array {
224        $inputValidator = InputValidator::newFromGlobalState();
225        return [
226            self::FIELD_ID => [
227                'name' => self::FIELD_ID,
228                'type' => 'text',
229                'id' => 'entityschema-special-schema-id',
230                'required' => true,
231                'default' => $defaultId ?: '',
232                'placeholder-message' => 'entityschema-special-id-placeholder',
233                'label-message' => 'entityschema-special-id-inputlabel',
234                'validation-callback' => [
235                    $inputValidator,
236                    'validateIDExists',
237                ],
238            ],
239            self::FIELD_LANGUAGE => [
240                'name' => self::FIELD_LANGUAGE,
241                'type' => 'text',
242                'id' => 'entityschema-language-code',
243                'required' => true,
244                'default' => $defaultLanguage,
245                'label-message' => 'entityschema-special-language-inputlabel',
246                'validation-callback' => [
247                    $inputValidator,
248                    'validateLangCodeIsSupported',
249                ],
250            ],
251        ];
252    }
253
254    private function getEditFormFields(
255        EntitySchemaId $id,
256        string $badgeLangCode,
257        NameBadge $nameBadge,
258        int $baseRevId
259    ): array {
260        $label = $nameBadge->label;
261        $description = $nameBadge->description;
262        $aliases = implode( '|', $nameBadge->aliases );
263        $uiLangCode = $this->getLanguage()->getCode();
264        $langName = MediaWikiServices::getInstance()->getLanguageNameUtils()
265            ->getLanguageName( $badgeLangCode, $uiLangCode );
266        $inputValidator = InputValidator::newFromGlobalState();
267        return [
268            'notice' => [
269                'type' => 'info',
270                'raw' => true,
271                'default' => $this->buildLanguageAndSchemaNotice( $langName, $label, $id ),
272            ],
273            self::FIELD_ID => [
274                'name' => self::FIELD_ID,
275                'type' => 'hidden',
276                'id' => 'entityschema-id',
277                'required' => true,
278                'default' => $id->getId(),
279            ],
280            self::FIELD_LANGUAGE => [
281                'name' => self::FIELD_LANGUAGE,
282                'type' => 'hidden',
283                'id' => 'entityschema-language-code',
284                'required' => true,
285                'default' => $badgeLangCode,
286            ],
287            self::FIELD_LABEL => [
288                'name' => self::FIELD_LABEL,
289                'type' => 'text',
290                'id' => 'entityschema-title-label',
291                'default' => $label,
292                'placeholder-message' => $this->msg( 'entityschema-label-edit-placeholder' )
293                    ->params( $langName ),
294                'label-message' => 'entityschema-special-label',
295                'validation-callback' => [
296                    $inputValidator,
297                    'validateStringInputLength',
298                ],
299            ],
300            self::FIELD_DESCRIPTION => [
301                'name' => self::FIELD_DESCRIPTION,
302                'type' => 'text',
303                'default' => $description,
304                'id' => 'entityschema-heading-description',
305                'placeholder-message' => $this->msg( 'entityschema-description-edit-placeholder' )
306                    ->params( $langName ),
307                'label-message' => 'entityschema-special-description',
308                'validation-callback' => [
309                    $inputValidator,
310                    'validateStringInputLength',
311                ],
312            ],
313            self::FIELD_ALIASES => [
314                'name' => self::FIELD_ALIASES,
315                'type' => 'text',
316                'default' => $aliases,
317                'id' => 'entityschema-heading-aliases',
318                'placeholder-message' => $this->msg( 'entityschema-aliases-edit-placeholder' )
319                    ->params( $langName ),
320                'label-message' => 'entityschema-special-aliases',
321                'validation-callback' => [
322                    $inputValidator,
323                    'validateAliasesLength',
324                ],
325            ],
326            self::FIELD_BASE_REV => [
327                'name' => self::FIELD_BASE_REV,
328                'type' => 'hidden',
329                'required' => true,
330                'default' => $baseRevId,
331            ],
332        ];
333    }
334
335    /**
336     * Validate ID and Language Code values
337     *
338     * @param string|null $id ID of the Schema
339     * @param string|null $language language code of the Schema
340     *
341     * @return bool
342     */
343    private function isSelectionDataValid( ?string $id, ?string $language ): bool {
344        if ( $id === null || $language === null ) {
345            return false;
346        }
347        $inputValidator = InputValidator::newFromGlobalState();
348
349        return $inputValidator->validateIDExists( $id ) === true &&
350            $inputValidator->validateLangCodeIsSupported( $language ) === true;
351    }
352
353    private function displayCopyright( OutputPage $output ): void {
354        $output->addHTML( $this->copyrightView
355            ->getHtml( $this->getLanguage(), 'entityschema-special-id-submit' ) );
356    }
357
358    private function displayWarnings( OutputPage $output ): void {
359        foreach ( $this->getWarnings() as $warning ) {
360            $output->addHTML( Html::rawElement( 'div', [ 'class' => 'warning' ], $warning ) );
361        }
362    }
363
364    /**
365     * Build the info message atop of the second form
366     *
367     * @return string HTML
368     */
369    private function buildLanguageAndSchemaNotice(
370        string $langName,
371        string $label,
372        EntitySchemaId $entitySchemaId
373    ): string {
374        $title = Title::makeTitle( NS_ENTITYSCHEMA_JSON, $entitySchemaId->getId() );
375        return $this->msg( 'entityschema-special-setlabeldescriptionaliases-info' )
376            ->params( $langName )
377            ->params( $this->getSchemaDisplayLabel( $label, $entitySchemaId ) )
378            ->params( $title->getPrefixedText() )
379            ->parse();
380    }
381
382    private function getSchemaDisplayLabel( string $label, EntitySchemaId $entitySchemaId ): string {
383        if ( !$label ) {
384            return $entitySchemaId->getId();
385        }
386
387        return $label . ' ' . $this->msg( 'parentheses' )->params( $entitySchemaId->getId() )->escaped();
388    }
389
390    private function getWarnings(): array {
391        if ( $this->getUser()->isAnon() && !$this->tempUserConfig->isEnabled() ) {
392            return [
393                $this->msg(
394                    'entityschema-anonymouseditwarning'
395                )->parse(),
396            ];
397        }
398
399        return [];
400    }
401
402    protected function getGroupName(): string {
403        return 'wikibase';
404    }
405
406    public function getRestriction(): string {
407        return 'edit';
408    }
409
410    private function checkBlocked( LinkTarget $title ): void {
411        $errors = MediaWikiServices::getInstance()->getPermissionManager()
412            ->getPermissionErrors( $this->getRestriction(), $this->getUser(), $title );
413        if ( $errors !== [] ) {
414            throw new PermissionsError( $this->getRestriction(), $errors );
415        }
416    }
417
418}