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