Switch some HTMLForms in special pages to OOUI
[lhc/web/wiklou.git] / includes / specials / SpecialMediaStatistics.php
1 <?php
2 /**
3 * Implements Special:MediaStatistics
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @author Brian Wolff
23 */
24
25 /**
26 * @ingroup SpecialPage
27 */
28 class MediaStatisticsPage extends QueryPage {
29 protected $totalCount = 0, $totalBytes = 0;
30
31 function __construct( $name = 'MediaStatistics' ) {
32 parent::__construct( $name );
33 // Generally speaking there is only a small number of file types,
34 // so just show all of them.
35 $this->limit = 5000;
36 $this->shownavigation = false;
37 }
38
39 function isExpensive() {
40 return true;
41 }
42
43 /**
44 * Query to do.
45 *
46 * This abuses the query cache table by storing mime types as "titles".
47 *
48 * This will store entries like [[Media:BITMAP;image/jpeg;200;20000]]
49 * where the form is Media type;mime type;count;bytes.
50 *
51 * This relies on the behaviour that when value is tied, the order things
52 * come out of querycache table is the order they went in. Which is hacky.
53 * However, other special pages like Special:Deadendpages and
54 * Special:BrokenRedirects also rely on this.
55 */
56 public function getQueryInfo() {
57 $dbr = wfGetDB( DB_SLAVE );
58 $fakeTitle = $dbr->buildConcat( array(
59 'img_media_type',
60 $dbr->addQuotes( ';' ),
61 'img_major_mime',
62 $dbr->addQuotes( '/' ),
63 'img_minor_mime',
64 $dbr->addQuotes( ';' ),
65 'COUNT(*)',
66 $dbr->addQuotes( ';' ),
67 'SUM( img_size )'
68 ) );
69 return array(
70 'tables' => array( 'image' ),
71 'fields' => array(
72 'title' => $fakeTitle,
73 'namespace' => NS_MEDIA, /* needs to be something */
74 'value' => '1'
75 ),
76 'conds' => array(
77 // WMF has a random null row in the db
78 'img_media_type IS NOT NULL'
79 ),
80 'options' => array(
81 'GROUP BY' => array(
82 'img_media_type',
83 'img_major_mime',
84 'img_minor_mime',
85 )
86 )
87 );
88 }
89
90 /**
91 * How to sort the results
92 *
93 * It's important that img_media_type come first, otherwise the
94 * tables will be fragmented.
95 * @return Array Fields to sort by
96 */
97 function getOrderFields() {
98 return array( 'img_media_type', 'count(*)', 'img_major_mime', 'img_minor_mime' );
99 }
100
101 /**
102 * Output the results of the query.
103 *
104 * @param $out OutputPage
105 * @param $skin Skin (deprecated presumably)
106 * @param $dbr IDatabase
107 * @param $res ResultWrapper Results from query
108 * @param $num integer Number of results
109 * @param $offset integer Paging offset (Should always be 0 in our case)
110 */
111 protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
112 $prevMediaType = null;
113 foreach ( $res as $row ) {
114 $mediaStats = $this->splitFakeTitle( $row->title );
115 if ( count( $mediaStats ) < 4 ) {
116 continue;
117 }
118 list( $mediaType, $mime, $totalCount, $totalBytes ) = $mediaStats;
119 if ( $prevMediaType !== $mediaType ) {
120 if ( $prevMediaType !== null ) {
121 // We're not at beginning, so we have to
122 // close the previous table.
123 $this->outputTableEnd();
124 }
125 $this->outputMediaType( $mediaType );
126 $this->outputTableStart( $mediaType );
127 $prevMediaType = $mediaType;
128 }
129 $this->outputTableRow( $mime, intval( $totalCount ), intval( $totalBytes ) );
130 }
131 if ( $prevMediaType !== null ) {
132 $this->outputTableEnd();
133 }
134 }
135
136 /**
137 * Output closing </table>
138 */
139 protected function outputTableEnd() {
140 $this->getOutput()->addHtml( Html::closeElement( 'table' ) );
141 }
142
143 /**
144 * Output a row of the stats table
145 *
146 * @param $mime String mime type (e.g. image/jpeg)
147 * @param $count integer Number of images of this type
148 * @param $totalBytes integer Total space for images of this type
149 */
150 protected function outputTableRow( $mime, $count, $bytes ) {
151 $mimeSearch = SpecialPage::getTitleFor( 'MIMEsearch', $mime );
152 $row = Html::rawElement(
153 'td',
154 array(),
155 Linker::link( $mimeSearch, htmlspecialchars( $mime ) )
156 );
157 $row .= Html::element(
158 'td',
159 array(),
160 $this->getExtensionList( $mime )
161 );
162 $row .= Html::rawElement(
163 'td',
164 // Make sure js sorts it in numeric order
165 array( 'data-sort-value' => $count ),
166 $this->msg( 'mediastatistics-nfiles' )
167 ->numParams( $count )
168 /** @todo Check to be sure this really should have number formatting */
169 ->numParams( $this->makePercentPretty( $count / $this->totalCount ) )
170 ->parse()
171 );
172 $row .= Html::rawElement(
173 'td',
174 // Make sure js sorts it in numeric order
175 array( 'data-sort-value' => $bytes ),
176 $this->msg( 'mediastatistics-nbytes' )
177 ->numParams( $bytes )
178 ->sizeParams( $bytes )
179 /** @todo Check to be sure this really should have number formatting */
180 ->numParams( $this->makePercentPretty( $bytes / $this->totalBytes ) )
181 ->parse()
182 );
183
184 $this->getOutput()->addHTML( Html::rawElement( 'tr', array(), $row ) );
185 }
186
187 /**
188 * @param float $decimal A decimal percentage (ie for 12.3%, this would be 0.123)
189 * @return String The percentage formatted so that 3 significant digits are shown.
190 */
191 protected function makePercentPretty( $decimal ) {
192 $decimal *= 100;
193 // Always show three useful digits
194 if ( $decimal == 0 ) {
195 return '0';
196 }
197 if ( $decimal >= 100 ) {
198 return '100';
199 }
200 $percent = sprintf( "%." . max( 0, 2 - floor( log10( $decimal ) ) ) . "f", $decimal );
201 // Then remove any trailing 0's
202 return preg_replace( '/\.?0*$/', '', $percent );
203 }
204
205 /**
206 * Given a mime type, return a comma separated list of allowed extensions.
207 *
208 * @param $mime String mime type
209 * @return String Comma separated list of allowed extensions (e.g. ".ogg, .oga")
210 */
211 private function getExtensionList( $mime ) {
212 $exts = MimeMagic::singleton()->getExtensionsForType( $mime );
213 if ( $exts === null ) {
214 return '';
215 }
216 $extArray = explode( ' ', $exts );
217 $extArray = array_unique( $extArray );
218 foreach ( $extArray as &$ext ) {
219 $ext = '.' . $ext;
220 }
221
222 return $this->getLanguage()->commaList( $extArray );
223 }
224
225 /**
226 * Output the start of the table
227 *
228 * Including opening <table>, and first <tr> with column headers.
229 */
230 protected function outputTableStart( $mediaType ) {
231 $this->getOutput()->addHTML(
232 Html::openElement(
233 'table',
234 array( 'class' => array(
235 'mw-mediastats-table',
236 'mw-mediastats-table-' . strtolower( $mediaType ),
237 'sortable',
238 'wikitable'
239 ) )
240 )
241 );
242 $this->getOutput()->addHTML( $this->getTableHeaderRow() );
243 }
244
245 /**
246 * Get (not output) the header row for the table
247 *
248 * @return String the header row of the able
249 */
250 protected function getTableHeaderRow() {
251 $headers = array( 'mimetype', 'extensions', 'count', 'totalbytes' );
252 $ths = '';
253 foreach ( $headers as $header ) {
254 $ths .= Html::rawElement(
255 'th',
256 array(),
257 // for grep:
258 // mediastatistics-table-mimetype, mediastatistics-table-extensions
259 // tatistics-table-count, mediastatistics-table-totalbytes
260 $this->msg( 'mediastatistics-table-' . $header )->parse()
261 );
262 }
263 return Html::rawElement( 'tr', array(), $ths );
264 }
265
266 /**
267 * Output a header for a new media type section
268 *
269 * @param $mediaType string A media type (e.g. from the MEDIATYPE_xxx constants)
270 */
271 protected function outputMediaType( $mediaType ) {
272 $this->getOutput()->addHTML(
273 Html::element(
274 'h2',
275 array( 'class' => array(
276 'mw-mediastats-mediatype',
277 'mw-mediastats-mediatype-' . strtolower( $mediaType )
278 ) ),
279 // for grep
280 // mediastatistics-header-unknown, mediastatistics-header-bitmap,
281 // mediastatistics-header-drawing, mediastatistics-header-audio,
282 // mediastatistics-header-video, mediastatistics-header-multimedia,
283 // mediastatistics-header-office, mediastatistics-header-text,
284 // mediastatistics-header-executable, mediastatistics-header-archive,
285 $this->msg( 'mediastatistics-header-' . strtolower( $mediaType ) )->text()
286 )
287 );
288 /** @todo Possibly could add a message here explaining what the different types are.
289 * not sure if it is needed though.
290 */
291 }
292
293 /**
294 * parse the fake title format that this special page abuses querycache with.
295 *
296 * @param $fakeTitle String A string formatted as <media type>;<mime type>;<count>;<bytes>
297 * @return Array The constituant parts of $fakeTitle
298 */
299 private function splitFakeTitle( $fakeTitle ) {
300 return explode( ';', $fakeTitle, 4 );
301 }
302
303 /**
304 * What group to put the page in
305 * @return string
306 */
307 protected function getGroupName() {
308 return 'media';
309 }
310
311 /**
312 * This method isn't used, since we override outputResults, but
313 * we need to implement since abstract in parent class.
314 *
315 * @param $skin Skin
316 * @param $result stdObject Result row
317 * @return bool|string|void
318 * @throws MWException
319 */
320 public function formatResult( $skin, $result ) {
321 throw new MWException( "unimplemented" );
322 }
323
324 /**
325 * Initialize total values so we can figure out percentages later.
326 *
327 * @param $dbr IDatabase
328 * @param $res ResultWrapper
329 */
330 public function preprocessResults( $dbr, $res ) {
331 $this->totalCount = $this->totalBytes = 0;
332 foreach ( $res as $row ) {
333 $mediaStats = $this->splitFakeTitle( $row->title );
334 $this->totalCount += isset( $mediaStats[2] ) ? $mediaStats[2] : 0;
335 $this->totalBytes += isset( $mediaStats[3] ) ? $mediaStats[3] : 0;
336 }
337 $res->seek( 0 );
338 }
339 }