New special page Special:NewbieContributions to replace Special:Contributions/newbies
[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[] = "<ol start='" . ( $offset + 1 ) . "' class='special'>";
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[] = '</ol>';
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 /**
380 * Do any necessary preprocessing of the result object.
381 * You should pass this by reference: &$db , &$res [although probably no longer necessary in PHP5]
382 */
383 function preprocessResults( &$db, &$res ) {}
384
385 /**
386 * Similar to above, but packaging in a syndicated feed instead of a web page
387 */
388 function doFeed( $class = '', $limit = 50 ) {
389 global $wgFeedClasses;
390
391 if( isset($wgFeedClasses[$class]) ) {
392 $feed = new $wgFeedClasses[$class](
393 $this->feedTitle(),
394 $this->feedDesc(),
395 $this->feedUrl() );
396 $feed->outHeader();
397
398 $dbr =& wfGetDB( DB_SLAVE );
399 $sql = $this->getSQL() . $this->getOrder();
400 $sql = $dbr->limitResult( $sql, $limit, 0 );
401 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
402 while( $obj = $dbr->fetchObject( $res ) ) {
403 $item = $this->feedResult( $obj );
404 if( $item ) $feed->outItem( $item );
405 }
406 $dbr->freeResult( $res );
407
408 $feed->outFooter();
409 return true;
410 } else {
411 return false;
412 }
413 }
414
415 /**
416 * Override for custom handling. If the titles/links are ok, just do
417 * feedItemDesc()
418 */
419 function feedResult( $row ) {
420 if( !isset( $row->title ) ) {
421 return NULL;
422 }
423 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
424 if( $title ) {
425 $date = isset( $row->timestamp ) ? $row->timestamp : '';
426 $comments = '';
427 if( $title ) {
428 $talkpage = $title->getTalkPage();
429 $comments = $talkpage->getFullURL();
430 }
431
432 return new FeedItem(
433 $title->getPrefixedText(),
434 $this->feedItemDesc( $row ),
435 $title->getFullURL(),
436 $date,
437 $this->feedItemAuthor( $row ),
438 $comments);
439 } else {
440 return NULL;
441 }
442 }
443
444 function feedItemDesc( $row ) {
445 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
446 }
447
448 function feedItemAuthor( $row ) {
449 return isset( $row->user_text ) ? $row->user_text : '';
450 }
451
452 function feedTitle() {
453 global $wgContLanguageCode, $wgSitename;
454 $page = SpecialPage::getPage( $this->getName() );
455 $desc = $page->getDescription();
456 return "$wgSitename - $desc [$wgContLanguageCode]";
457 }
458
459 function feedDesc() {
460 return wfMsg( 'tagline' );
461 }
462
463 function feedUrl() {
464 $title = SpecialPage::getTitleFor( $this->getName() );
465 return $title->getFullURL();
466 }
467 }
468
469 /**
470 * This is a subclass for very simple queries that are just looking for page
471 * titles that match some criteria. It formats each result item as a link to
472 * that page.
473 *
474 * @package MediaWiki
475 */
476 class PageQueryPage extends QueryPage {
477
478 function formatResult( $skin, $result ) {
479 global $wgContLang;
480 $nt = Title::makeTitle( $result->namespace, $result->title );
481 return $skin->makeKnownLinkObj( $nt, htmlspecialchars( $wgContLang->convert( $nt->getPrefixedText() ) ) );
482 }
483 }
484
485 ?>