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