Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 107
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecialGadgetUsage
0.00% covered (danger)
0.00%
0 / 107
0.00% covered (danger)
0.00%
0 / 11
506
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 isExpensive
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getQueryInfo
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
2
 getOrderFields
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 outputTableStart
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 outputTableEnd
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 formatResult
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 getDefaultGadgets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 outputResults
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
56
 getGroupName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
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
21namespace MediaWiki\Extension\Gadgets\Special;
22
23use MediaWiki\Extension\Gadgets\GadgetRepo;
24use MediaWiki\Html\Html;
25use MediaWiki\MainConfigNames;
26use MediaWiki\Output\OutputPage;
27use MediaWiki\Skin\Skin;
28use MediaWiki\SpecialPage\QueryPage;
29use MediaWiki\Title\TitleValue;
30use stdClass;
31use Wikimedia\Rdbms\IConnectionProvider;
32use Wikimedia\Rdbms\IExpression;
33use Wikimedia\Rdbms\IReadableDatabase;
34use Wikimedia\Rdbms\IResultWrapper;
35use Wikimedia\Rdbms\LikeValue;
36
37/**
38 * Special:GadgetUsage lists all the gadgets on the wiki along with number of users.
39 *
40 * @copyright 2015 Niharika Kohli
41 */
42class SpecialGadgetUsage extends QueryPage {
43    public function __construct(
44        private readonly GadgetRepo $gadgetRepo,
45        private readonly IConnectionProvider $dbProvider,
46    ) {
47        parent::__construct( 'GadgetUsage' );
48        // Show all gadgets
49        $this->limit = 1000;
50        $this->shownavigation = false;
51    }
52
53    /**
54     * @inheritDoc
55     */
56    public function execute( $par ) {
57        parent::execute( $par );
58        $this->addHelpLink( 'Extension:Gadgets' );
59    }
60
61    /** @inheritDoc */
62    public function isExpensive() {
63        return true;
64    }
65
66    /**
67     * Define the database query that is used to generate the stats table.
68     * The query is essentially:
69     *
70     * SELECT up_property, COUNT(*), count(qcc_title)
71     * FROM user_properties
72     * LEFT JOIN user ON up_user = user_id
73     * LEFT JOIN querycachetwo ON user_name = qcc_title AND qcc_namespace = 2 AND qcc_type = 'activeusers'
74     * WHERE up_property LIKE 'gadget-%' AND up_value NOT IN ('0','')
75     * GROUP BY up_property;
76     *
77     * @return array
78     */
79    public function getQueryInfo() {
80        $dbr = $this->dbProvider->getReplicaDatabase();
81
82        return [
83            'tables' => [ 'user_properties', 'user', 'querycachetwo' ],
84            'fields' => [
85                'title' => 'up_property',
86                'value' => 'COUNT(*)',
87                // Need to pick fields existing in the querycache table so that the results are cachable
88                'namespace' => 'COUNT( qcc_title )'
89            ],
90            'conds' => [
91                $dbr->expr( 'up_property', IExpression::LIKE, new LikeValue( 'gadget-', $dbr->anyString() ) ),
92                // Simulate php falsy condition to ignore disabled user preferences
93                $dbr->expr( 'up_value', '!=', [ '0', '' ] ),
94            ],
95            'options' => [
96                'GROUP BY' => [ 'up_property' ]
97            ],
98            'join_conds' => [
99                'user' => [
100                    'LEFT JOIN', [
101                        'up_user = user_id'
102                    ]
103                ],
104                'querycachetwo' => [
105                    'LEFT JOIN', [
106                        'user_name = qcc_title',
107                        'qcc_namespace' => NS_USER,
108                        'qcc_type' => 'activeusers',
109                    ]
110                ]
111            ]
112        ];
113    }
114
115    /** @inheritDoc */
116    public function getOrderFields() {
117        return [ 'value' ];
118    }
119
120    /**
121     * Output the start of the table
122     * Including opening <table>, the thead element with column headers
123     * and the opening <tbody>.
124     */
125    protected function outputTableStart() {
126        $html = '';
127        $headers = [ 'gadgetusage-gadget', 'gadgetusage-usercount', 'gadgetusage-activeusers' ];
128        foreach ( $headers as $h ) {
129            if ( $h === 'gadgetusage-gadget' ) {
130                $html .= Html::element( 'th', [], $this->msg( $h )->text() );
131            } else {
132                $html .= Html::element( 'th', [ 'data-sort-type' => 'number' ],
133                    $this->msg( $h )->text() );
134            }
135        }
136
137        $this->getOutput()->addHTML(
138            Html::openElement( 'table', [ 'class' => [ 'sortable', 'wikitable' ] ] ) .
139            Html::rawElement( 'thead', [], Html::rawElement( 'tr', [], $html ) ) .
140            Html::openElement( 'tbody', [] )
141        );
142        $this->getOutput()->addModuleStyles( 'jquery.tablesorter.styles' );
143        $this->getOutput()->addModules( 'jquery.tablesorter' );
144    }
145
146    /**
147     * Output the end of the table
148     * </tbody></table>
149     */
150    protected function outputTableEnd() {
151        $this->getOutput()->addHTML(
152            Html::closeElement( 'tbody' ) .
153            Html::closeElement( 'table' )
154        );
155    }
156
157    /**
158     * @param Skin $skin
159     * @param stdClass $result Result row
160     * @return string|bool String of HTML
161     */
162    public function formatResult( $skin, $result ) {
163        $gadgetTitle = substr( $result->title, 7 );
164        $gadgetUserCount = $this->getLanguage()->formatNum( $result->value );
165        if ( $gadgetTitle ) {
166            $html = '';
167            // "Gadget" column
168            $link = $this->getLinkRenderer()->makeLink(
169                new TitleValue( NS_SPECIAL, 'Gadgets', 'gadget-' . $gadgetTitle ),
170                $gadgetTitle
171            );
172            $html .= Html::rawElement( 'td', [], $link );
173            // "Number of users" column
174            $html .= Html::element( 'td', [], $gadgetUserCount );
175            // "Active users" column
176            $activeUserCount = $this->getLanguage()->formatNum( $result->namespace );
177            $html .= Html::element( 'td', [], $activeUserCount );
178            return Html::rawElement( 'tr', [], $html );
179        }
180        return false;
181    }
182
183    /**
184     * Get a list of default gadgets
185     * @param array $gadgetIds list of gagdet ids registered in the wiki
186     * @return array
187     */
188    protected function getDefaultGadgets( $gadgetIds ) {
189        $gadgetsList = [];
190        foreach ( $gadgetIds as $g ) {
191            $gadget = $this->gadgetRepo->getGadget( $g );
192            if ( $gadget->isOnByDefault() ) {
193                $gadgetsList[] = $gadget->getName();
194            }
195        }
196        asort( $gadgetsList, SORT_STRING | SORT_FLAG_CASE );
197        return $gadgetsList;
198    }
199
200    /**
201     * Format and output report results using the given information plus
202     * OutputPage
203     *
204     * @param OutputPage $out OutputPage to print to
205     * @param Skin $skin User skin to use
206     * @param IReadableDatabase $dbr Database (read) connection to use
207     * @param IResultWrapper $res Result pointer
208     * @param int $num Number of available result rows
209     * @param int $offset Paging offset
210     */
211    protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
212        $gadgetIds = $this->gadgetRepo->getGadgetIds();
213        $defaultGadgets = $this->getDefaultGadgets( $gadgetIds );
214        $out->addHtml(
215            $this->msg( 'gadgetusage-intro' )
216                ->numParams( $this->getConfig()->get( MainConfigNames::ActiveUserDays ) )->parseAsBlock()
217        );
218        if ( $num > 0 ) {
219            $this->outputTableStart();
220            // Append default gadgets to the table with 'default' in the total and active user fields
221            foreach ( $defaultGadgets as $default ) {
222                $html = '';
223                // "Gadget" column
224                $link = $this->getLinkRenderer()->makeLink(
225                    new TitleValue( NS_SPECIAL, 'Gadgets', 'gadget-' . $default ),
226                    $default
227                );
228                $html .= Html::rawElement( 'td', [], $link );
229                // "Number of users" column
230                $html .= Html::element( 'td', [ 'data-sort-value' => 'Infinity' ],
231                    $this->msg( 'gadgetusage-default' )->text() );
232                // "Active users" column
233                // @phan-suppress-next-line PhanPluginDuplicateAdjacentStatement
234                $html .= Html::element( 'td', [ 'data-sort-value' => 'Infinity' ],
235                    $this->msg( 'gadgetusage-default' )->text() );
236                $out->addHTML( Html::rawElement( 'tr', [], $html ) );
237            }
238            foreach ( $res as $row ) {
239                // Remove the 'gadget-' part of the result string and compare if it's present
240                // in $defaultGadgets, if not we format it and add it to the output
241                $name = substr( $row->title, 7 );
242
243                // Only pick gadgets which are in the list $gadgetIds to make sure they exist
244                if ( !in_array( $name, $defaultGadgets, true ) && in_array( $name, $gadgetIds, true ) ) {
245                    $line = $this->formatResult( $skin, $row );
246                    if ( $line ) {
247                        $out->addHTML( $line );
248                    }
249                }
250            }
251            // Close table element
252            $this->outputTableEnd();
253        } else {
254            $out->addHtml(
255                $this->msg( 'gadgetusage-noresults' )->parseAsBlock()
256            );
257        }
258    }
259
260    /**
261     * @inheritDoc
262     */
263    protected function getGroupName() {
264        return 'wiki';
265    }
266}