Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
31.17% covered (danger)
31.17%
24 / 77
14.29% covered (danger)
14.29%
1 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
Hooks
31.17% covered (danger)
31.17%
24 / 77
14.29% covered (danger)
14.29%
1 / 7
344.39
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 onBeforePageDisplay
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 onEditFilterMergedContent
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
110
 onGetPreferences
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
5
 getLinksForUser
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 getLinksFromConfig
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 onOutputPageParserOutput
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
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 *
17 * @file
18 */
19
20namespace MediaWiki\Extension\RealMe;
21
22use Content;
23use FormatJson;
24use HTMLForm;
25use IContextSource;
26use JsonContent;
27use MediaWiki\Config\Config;
28use MediaWiki\Config\ServiceOptions;
29use MediaWiki\Hook\BeforePageDisplayHook;
30use MediaWiki\Hook\EditFilterMergedContentHook;
31use MediaWiki\Hook\OutputPageParserOutputHook;
32use MediaWiki\Parser\ParserOutput;
33use MediaWiki\Preferences\Hook\GetPreferencesHook;
34use MediaWiki\Status\Status;
35use MediaWiki\Title\Title;
36use MediaWiki\User\Options\UserOptionsLookup;
37use MediaWiki\User\User;
38use MediaWiki\User\UserFactory;
39use MediaWiki\Utils\UrlUtils;
40
41class Hooks implements
42    BeforePageDisplayHook,
43    EditFilterMergedContentHook,
44    GetPreferencesHook,
45    OutputPageParserOutputHook
46{
47    private const CONSTRUCTOR_OPTIONS = [
48        'RealMeUserPageUrlLimit',
49    ];
50
51    /** @var ServiceOptions */
52    private ServiceOptions $options;
53
54    /** @var UrlUtils */
55    private UrlUtils $urlUtils;
56
57    /** @var UserFactory */
58    private UserFactory $userFactory;
59
60    /** @var UserOptionsLookup */
61    private UserOptionsLookup $userOptionsLookup;
62
63    /**
64     * @param Config $mainConfig
65     * @param UrlUtils $urlUtils
66     * @param UserFactory $userFactory
67     * @param UserOptionsLookup $userOptionsLookup
68     */
69    public function __construct(
70        Config $mainConfig,
71        UrlUtils $urlUtils,
72        UserFactory $userFactory,
73        UserOptionsLookup $userOptionsLookup
74    ) {
75        $this->options = new ServiceOptions( self::CONSTRUCTOR_OPTIONS, $mainConfig );
76        $this->urlUtils = $urlUtils;
77        $this->userFactory = $userFactory;
78        $this->userOptionsLookup = $userOptionsLookup;
79    }
80
81    /** @inheritDoc */
82    public function onBeforePageDisplay( $out, $skin ): void {
83        // Add a help link on the JSON config page
84        $title = $out->getTitle();
85        if ( $title && $title->inNamespace( NS_MEDIAWIKI )
86            && $title->getText() === Constants::CONFIG_PAGE ) {
87            $out->addHelpLink( 'Help:Extension:RealMe' );
88        }
89    }
90
91    /** @inheritDoc */
92    public function onEditFilterMergedContent( IContextSource $context, Content $content, Status $status,
93        $summary, User $user, $minoredit
94    ) {
95        $title = $context->getTitle();
96        if ( !$title || !$title->inNamespace( NS_MEDIAWIKI )
97            || $title->getText() !== Constants::CONFIG_PAGE ) {
98            return;
99        }
100
101        if ( !$content instanceof JsonContent ) {
102            // Huh??
103            return;
104        }
105        if ( !$content->getData()->isGood() ) {
106            // Will error out anyways
107            return;
108        }
109
110        $validator = new Validator( $context, $this->urlUtils );
111        $errors = [];
112        $data = wfObjectToArray( $content->getData()->getValue() );
113        foreach ( $data as $title => $urls ) {
114            $errors = array_merge( $errors, $validator->checkTitle( $title ) );
115            foreach ( (array)$urls as $url ) {
116                $errors = array_merge( $errors, $validator->checkUrl( $url ) );
117            }
118        }
119
120        if ( $errors ) {
121            foreach ( $errors as $error ) {
122                $status->fatal( $error );
123            }
124            return false;
125        } else {
126            return true;
127        }
128    }
129
130    /** @inheritDoc */
131    public function onGetPreferences( $user, &$preferences ) {
132        $preferences[Constants::PREFERENCE_NAME] = [
133            'type'          => 'textarea',
134            'section'       => 'personal/userpage',
135            'label-message' => 'realme-preference-desc',
136            'help-message'  => 'realme-preference-help',
137            'rows'          => min( 5, $this->options->get( 'RealMeUserPageUrlLimit' ) ),
138
139            'validation-callback' => function ( $optionValue, $allData, HTMLForm $form ) {
140                $urls = explode( "\n", $optionValue ?? '' );
141
142                $errors = [];
143                $count = 0;
144                $validator = new Validator( $form, $this->urlUtils );
145
146                foreach ( $urls as $url ) {
147                    if ( trim( $url ) === '' ) {
148                        continue;
149                    }
150
151                    $count += 1;
152
153                    $errors = array_merge( $errors, $validator->checkUrl( $url ) );
154                }
155
156                if ( $count > $this->options->get( 'RealMeUserPageUrlLimit' ) ) {
157                    $errors[] = $form->msg( 'realme-preference-error-too-many' )
158                        ->params( $this->options->get( 'RealMeUserPageUrlLimit' ) );
159                }
160
161                if ( $errors ) {
162                    return $errors;
163                }
164
165                return true;
166            },
167        ];
168    }
169
170    /**
171     * Given a Title that corresponds to a User or User talk page, look up the links
172     * that should be added to that page
173     *
174     * @return ?array
175     */
176    private function getLinksForUser( Title $title, ParserOutput $parserOutput ) {
177        if ( $title->isSubpage() ) {
178            return;
179        }
180
181        $user = $this->userFactory->newFromName( $title->getText() );
182
183        if ( !$user ) {
184            return;
185        }
186
187        $linksPresent = array_keys( $parserOutput->getExternalLinks() );
188
189        if ( !$linksPresent ) {
190            return;
191        }
192
193        $option = $this->userOptionsLookup->getOption( $user, Constants::PREFERENCE_NAME, "" );
194        $allowedUrls = explode( "\n", $option );
195
196        return array_intersect( $linksPresent, $allowedUrls );
197    }
198
199    /**
200     * Given a non-user Title, look up the links that should be added to that page
201     *
202     * @return ?array
203     */
204    private function getLinksFromConfig( Title $title ) {
205        $config = FormatJson::decode( wfMessage( 'realme-config.json' )->inContentLanguage()->plain(), true );
206        if ( !is_array( $config ) ) {
207            return;
208        }
209
210        $urls = $config[$title->getPrefixedText()] ?? [];
211        return (array)$urls;
212    }
213
214    /** @inheritDoc */
215    public function onOutputPageParserOutput( $outputPage, $parserOutput ): void {
216        $title = $outputPage->getTitle();
217        if ( !$title ) {
218            return;
219        }
220
221        if ( !$title->inNamespaces( NS_USER, NS_USER_TALK ) ) {
222            // Check sitewide config
223            $urls = $this->getLinksFromConfig( $title );
224        } else {
225            $urls = $this->getLinksForUser( $title, $parserOutput );
226        }
227
228        if ( $urls ) {
229            foreach ( $urls as $url ) {
230                $outputPage->addLink( [ 'rel' => 'me', 'href' => $url ] );
231            }
232        }
233    }
234}