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