(bug 5250) Introduce Special:Unusedtemplates
[lhc/web/wiklou.git] / includes / QueryPage.php
1 <?php
2 /**
3 * Contain a class for special pages
4 * @package MediaWiki
5 */
6
7 /**
8 *
9 */
10 require_once 'Feed.php';
11
12 /**
13 * List of query page classes and their associated special pages, for periodic update purposes
14 */
15 global $wgQueryPages; // not redundant
16 $wgQueryPages = array(
17 // QueryPage subclass Special page name Limit (false for none, none for the default)
18 //----------------------------------------------------------------------------
19 array( 'AncientPagesPage', 'Ancientpages' ),
20 array( 'BrokenRedirectsPage', 'BrokenRedirects' ),
21 array( 'CategoriesPage', 'Categories' ),
22 array( 'DeadendPagesPage', 'Deadendpages' ),
23 array( 'DisambiguationsPage', 'Disambiguations' ),
24 array( 'DoubleRedirectsPage', 'DoubleRedirects' ),
25 array( 'ListUsersPage', 'Listusers' ),
26 array( 'ListredirectsPage', 'Listredirects' ),
27 array( 'LonelyPagesPage', 'Lonelypages' ),
28 array( 'LongPagesPage', 'Longpages' ),
29 array( 'MostcategoriesPage', 'Mostcategories' ),
30 array( 'MostimagesPage', 'Mostimages' ),
31 array( 'MostlinkedCategoriesPage', 'Mostlinkedcategories' ),
32 array( 'MostlinkedPage', 'Mostlinked' ),
33 array( 'MostrevisionsPage', 'Mostrevisions' ),
34 array( 'NewPagesPage', 'Newpages' ),
35 array( 'ShortPagesPage', 'Shortpages' ),
36 array( 'UncategorizedCategoriesPage', 'Uncategorizedcategories' ),
37 array( 'UncategorizedPagesPage', 'Uncategorizedpages' ),
38 array( 'UnusedCategoriesPage', 'Unusedcategories' ),
39 array( 'UnusedimagesPage', 'Unusedimages' ),
40 array( 'WantedCategoriesPage', 'Wantedcategories' ),
41 array( 'WantedPagesPage', 'Wantedpages' ),
42 array( 'UnwatchedPagesPage', 'Unwatchedpages' ),
43 array( 'UnusedtemplatesPage', 'Unusedtemplates' ),
44 );
45 wfRunHooks( 'wgQueryPages', array( &$wgQueryPages ) );
46
47 global $wgDisableCounters;
48 if ( !$wgDisableCounters )
49 $wgQueryPages[] = array( 'PopularPagesPage', 'Popularpages' );
50
51
52 /**
53 * This is a class for doing query pages; since they're almost all the same,
54 * we factor out some of the functionality into a superclass, and let
55 * subclasses derive from it.
56 *
57 * @package MediaWiki
58 */
59 class QueryPage {
60 /**
61 * Whether or not we want plain listoutput rather than an ordered list
62 *
63 * @var bool
64 */
65 var $listoutput = false;
66
67 /**
68 * A mutator for $this->listoutput;
69 *
70 * @param bool $bool
71 */
72 function setListoutput( $bool ) {
73 $this->listoutput = $bool;
74 }
75
76 /**
77 * Subclasses return their name here. Make sure the name is also
78 * specified in SpecialPage.php and in Language.php as a language message
79 * param.
80 */
81 function getName() {
82 return '';
83 }
84
85 /**
86 * Subclasses return an SQL query here.
87 *
88 * Note that the query itself should return the following four columns:
89 * 'type' (your special page's name), 'namespace', 'title', and 'value'
90 * *in that order*. 'value' is used for sorting.
91 *
92 * These may be stored in the querycache table for expensive queries,
93 * and that cached data will be returned sometimes, so the presence of
94 * extra fields can't be relied upon. The cached 'value' column will be
95 * an integer; non-numeric values are useful only for sorting the initial
96 * query.
97 *
98 * Don't include an ORDER or LIMIT clause, this will be added.
99 */
100 function getSQL() {
101 return "SELECT 'sample' as type, 0 as namespace, 'Sample result' as title, 42 as value";
102 }
103
104 /**
105 * Override to sort by increasing values
106 */
107 function sortDescending() {
108 return true;
109 }
110
111 function getOrder() {
112 return ' ORDER BY value ' .
113 ($this->sortDescending() ? 'DESC' : '');
114 }
115
116 /**
117 * Is this query expensive (for some definition of expensive)? Then we
118 * don't let it run in miser mode. $wgDisableQueryPages causes all query
119 * pages to be declared expensive. Some query pages are always expensive.
120 */
121 function isExpensive( ) {
122 global $wgDisableQueryPages;
123 return $wgDisableQueryPages;
124 }
125
126 /**
127 * Whether or not the output of the page in question is retrived from
128 * the database cache.
129 *
130 * @return bool
131 */
132 function isCached() {
133 global $wgMiserMode;
134
135 return $this->isExpensive() && $wgMiserMode;
136 }
137
138 /**
139 * Sometime we dont want to build rss / atom feeds.
140 */
141 function isSyndicated() {
142 return true;
143 }
144
145 /**
146 * Formats the results of the query for display. The skin is the current
147 * skin; you can use it for making links. The result is a single row of
148 * result data. You should be able to grab SQL results off of it.
149 * If the function return "false", the line output will be skipped.
150 */
151 function formatResult( $skin, $result ) {
152 return '';
153 }
154
155 /**
156 * The content returned by this function will be output before any result
157 */
158 function getPageHeader( ) {
159 return '';
160 }
161
162 /**
163 * If using extra form wheely-dealies, return a set of parameters here
164 * as an associative array. They will be encoded and added to the paging
165 * links (prev/next/lengths).
166 * @return array
167 */
168 function linkParameters() {
169 return array();
170 }
171
172 /**
173 * Some special pages (for example SpecialListusers) might not return the
174 * current object formatted, but return the previous one instead.
175 * Setting this to return true, will call one more time wfFormatResult to
176 * be sure that the very last result is formatted and shown.
177 */
178 function tryLastResult( ) {
179 return false;
180 }
181
182 /**
183 * Clear the cache and save new results
184 */
185 function recache( $limit, $ignoreErrors = true ) {
186 $fname = get_class($this) . '::recache';
187 $dbw =& wfGetDB( DB_MASTER );
188 $dbr =& wfGetDB( DB_SLAVE, array( $this->getName(), 'QueryPage::recache', 'vslow' ) );
189 if ( !$dbw || !$dbr ) {
190 return false;
191 }
192
193 $querycache = $dbr->tableName( 'querycache' );
194
195 if ( $ignoreErrors ) {
196 $ignoreW = $dbw->ignoreErrors( true );
197 $ignoreR = $dbr->ignoreErrors( true );
198 }
199
200 # Clear out any old cached data
201 $dbw->delete( 'querycache', array( 'qc_type' => $this->getName() ), $fname );
202 # Do query
203 $sql = $this->getSQL() . $this->getOrder();
204 if ($limit !== false)
205 $sql = $dbr->limitResult($sql, $limit, 0);
206 $res = $dbr->query($sql, $fname);
207 $num = false;
208 if ( $res ) {
209 $num = $dbr->numRows( $res );
210 # Fetch results
211 $insertSql = "INSERT INTO $querycache (qc_type,qc_namespace,qc_title,qc_value) VALUES ";
212 $first = true;
213 while ( $res && $row = $dbr->fetchObject( $res ) ) {
214 if ( $first ) {
215 $first = false;
216 } else {
217 $insertSql .= ',';
218 }
219 if ( isset( $row->value ) ) {
220 $value = $row->value;
221 } else {
222 $value = '';
223 }
224
225 $insertSql .= '(' .
226 $dbw->addQuotes( $row->type ) . ',' .
227 $dbw->addQuotes( $row->namespace ) . ',' .
228 $dbw->addQuotes( $row->title ) . ',' .
229 $dbw->addQuotes( $value ) . ')';
230 }
231
232 # Save results into the querycache table on the master
233 if ( !$first ) {
234 if ( !$dbw->query( $insertSql, $fname ) ) {
235 // Set result to false to indicate error
236 $dbr->freeResult( $res );
237 $res = false;
238 }
239 }
240 if ( $res ) {
241 $dbr->freeResult( $res );
242 }
243 if ( $ignoreErrors ) {
244 $dbw->ignoreErrors( $ignoreW );
245 $dbr->ignoreErrors( $ignoreR );
246 }
247
248 # Update the querycache_info record for the page
249 $dbw->delete( 'querycache_info', array( 'qci_type' => $this->getName() ), $fname );
250 $dbw->insert( 'querycache_info', array( 'qci_type' => $this->getName(), 'qci_timestamp' => $dbw->timestamp() ), $fname );
251
252 }
253 return $num;
254 }
255
256 /**
257 * This is the actual workhorse. It does everything needed to make a
258 * real, honest-to-gosh query page.
259 *
260 * @param $offset database query offset
261 * @param $limit database query limit
262 * @param $shownavigation show navigation like "next 200"?
263 */
264 function doQuery( $offset, $limit, $shownavigation=true ) {
265 global $wgUser, $wgOut, $wgLang, $wgContLang;
266
267 $sname = $this->getName();
268 $fname = get_class($this) . '::doQuery';
269 $sql = $this->getSQL();
270 $dbr =& wfGetDB( DB_SLAVE );
271 $querycache = $dbr->tableName( 'querycache' );
272
273 $wgOut->setSyndicated( $this->isSyndicated() );
274
275 if ( $this->isCached() ) {
276 $type = $dbr->strencode( $sname );
277 $sql =
278 "SELECT qc_type as type, qc_namespace as namespace,qc_title as title, qc_value as value
279 FROM $querycache WHERE qc_type='$type'";
280
281 if( !$this->listoutput ) {
282
283 # Fetch the timestamp of this update
284 $tRes = $dbr->select( 'querycache_info', array( 'qci_timestamp' ), array( 'qci_type' => $type ), $fname );
285 $tRow = $dbr->fetchObject( $tRes );
286
287 if( $tRow ) {
288 $updated = $wgLang->timeAndDate( $tRow->qci_timestamp, true, true );
289 $cacheNotice = wfMsg( 'perfcachedts', $updated );
290 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
291 $wgOut->addScript( '<script language="JavaScript">var dataCacheTime = \'' . $tRow->qci_timestamp . '\';</script>' );
292 } else {
293 $cacheNotice = wfMsg( 'perfcached' );
294 }
295
296 $wgOut->addWikiText( $cacheNotice );
297 }
298
299 }
300
301 $sql .= $this->getOrder();
302 $sql = $dbr->limitResult($sql, $limit, $offset);
303 $res = $dbr->query( $sql );
304 $num = $dbr->numRows($res);
305
306 $this->preprocessResults( $dbr, $res );
307
308 $sk = $wgUser->getSkin( );
309
310 if($shownavigation) {
311 $wgOut->addHTML( $this->getPageHeader() );
312 $top = wfShowingResults( $offset, $num);
313 $wgOut->addHTML( "<p>{$top}\n" );
314
315 # often disable 'next' link when we reach the end
316 $atend = $num < $limit;
317
318 $sl = wfViewPrevNext( $offset, $limit ,
319 $wgContLang->specialPage( $sname ),
320 wfArrayToCGI( $this->linkParameters() ), $atend );
321 $wgOut->addHTML( "<br />{$sl}</p>\n" );
322 }
323 if ( $num > 0 ) {
324 $s = array();
325 if ( ! $this->listoutput )
326 $s[] = "<ol start='" . ( $offset + 1 ) . "' class='special'>";
327
328 # Only read at most $num rows, because $res may contain the whole 1000
329 for ( $i = 0; $i < $num && $obj = $dbr->fetchObject( $res ); $i++ ) {
330 $format = $this->formatResult( $sk, $obj );
331 if ( $format ) {
332 $attr = ( isset ( $obj->usepatrol ) && $obj->usepatrol &&
333 $obj->patrolled == 0 ) ? ' class="not-patrolled"' : '';
334 $s[] = $this->listoutput ? $format : "<li{$attr}>{$format}</li>\n";
335 }
336 }
337
338 if($this->tryLastResult()) {
339 // flush the very last result
340 $obj = null;
341 $format = $this->formatResult( $sk, $obj );
342 if( $format ) {
343 $attr = ( isset ( $obj->usepatrol ) && $obj->usepatrol &&
344 $obj->patrolled == 0 ) ? ' class="not-patrolled"' : '';
345 $s[] = "<li{$attr}>{$format}</li>\n";
346 }
347 }
348
349 $dbr->freeResult( $res );
350 if ( ! $this->listoutput )
351 $s[] = '</ol>';
352 $str = $this->listoutput ? $wgContLang->listToText( $s ) : implode( '', $s );
353 $wgOut->addHTML( $str );
354 }
355 if($shownavigation) {
356 $wgOut->addHTML( "<p>{$sl}</p>\n" );
357 }
358 return $num;
359 }
360
361 /**
362 * Do any necessary preprocessing of the result object.
363 * You should pass this by reference: &$db , &$res
364 */
365 function preprocessResults( $db, $res ) {}
366
367 /**
368 * Similar to above, but packaging in a syndicated feed instead of a web page
369 */
370 function doFeed( $class = '', $limit = 50 ) {
371 global $wgFeedClasses;
372
373 if( isset($wgFeedClasses[$class]) ) {
374 $feed = new $wgFeedClasses[$class](
375 $this->feedTitle(),
376 $this->feedDesc(),
377 $this->feedUrl() );
378 $feed->outHeader();
379
380 $dbr =& wfGetDB( DB_SLAVE );
381 $sql = $this->getSQL() . $this->getOrder();
382 $sql = $dbr->limitResult( $sql, $limit, 0 );
383 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
384 while( $obj = $dbr->fetchObject( $res ) ) {
385 $item = $this->feedResult( $obj );
386 if( $item ) $feed->outItem( $item );
387 }
388 $dbr->freeResult( $res );
389
390 $feed->outFooter();
391 return true;
392 } else {
393 return false;
394 }
395 }
396
397 /**
398 * Override for custom handling. If the titles/links are ok, just do
399 * feedItemDesc()
400 */
401 function feedResult( $row ) {
402 if( !isset( $row->title ) ) {
403 return NULL;
404 }
405 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
406 if( $title ) {
407 $date = isset( $row->timestamp ) ? $row->timestamp : '';
408 $comments = '';
409 if( $title ) {
410 $talkpage = $title->getTalkPage();
411 $comments = $talkpage->getFullURL();
412 }
413
414 return new FeedItem(
415 $title->getPrefixedText(),
416 $this->feedItemDesc( $row ),
417 $title->getFullURL(),
418 $date,
419 $this->feedItemAuthor( $row ),
420 $comments);
421 } else {
422 return NULL;
423 }
424 }
425
426 function feedItemDesc( $row ) {
427 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
428 }
429
430 function feedItemAuthor( $row ) {
431 return isset( $row->user_text ) ? $row->user_text : '';
432 }
433
434 function feedTitle() {
435 global $wgLanguageCode, $wgSitename;
436 $page = SpecialPage::getPage( $this->getName() );
437 $desc = $page->getDescription();
438 return "$wgSitename - $desc [$wgLanguageCode]";
439 }
440
441 function feedDesc() {
442 return wfMsg( 'tagline' );
443 }
444
445 function feedUrl() {
446 $title = Title::MakeTitle( NS_SPECIAL, $this->getName() );
447 return $title->getFullURL();
448 }
449 }
450
451 /**
452 * This is a subclass for very simple queries that are just looking for page
453 * titles that match some criteria. It formats each result item as a link to
454 * that page.
455 *
456 * @package MediaWiki
457 */
458 class PageQueryPage extends QueryPage {
459
460 function formatResult( $skin, $result ) {
461 global $wgContLang;
462 $nt = Title::makeTitle( $result->namespace, $result->title );
463 return $skin->makeKnownLinkObj( $nt, htmlspecialchars( $wgContLang->convert( $nt->getPrefixedText() ) ) );
464 }
465 }
466
467 ?>