79ce0ba66747d3144ab7a00b870e309028c95cf3
[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 $wgOut->addMeta( 'Data-Cache-Time', $tRow->qci_timestamp );
290 $wgOut->addScript( '<script language="JavaScript">var dataCacheTime = \'' . $tRow->qci_timestamp . '\';</script>' );
291 } else {
292 $cacheNotice = wfMsg( 'perfcached' );
293 }
294
295 $wgOut->addWikiText( $cacheNotice );
296 }
297
298 }
299
300 $sql .= $this->getOrder();
301 $sql = $dbr->limitResult($sql, $limit, $offset);
302 $res = $dbr->query( $sql );
303 $num = $dbr->numRows($res);
304
305 $this->preprocessResults( $dbr, $res );
306
307 $sk = $wgUser->getSkin( );
308
309 if($shownavigation) {
310 $wgOut->addHTML( $this->getPageHeader() );
311 $top = wfShowingResults( $offset, $num);
312 $wgOut->addHTML( "<p>{$top}\n" );
313
314 # often disable 'next' link when we reach the end
315 $atend = $num < $limit;
316
317 $sl = wfViewPrevNext( $offset, $limit ,
318 $wgContLang->specialPage( $sname ),
319 wfArrayToCGI( $this->linkParameters() ), $atend );
320 $wgOut->addHTML( "<br />{$sl}</p>\n" );
321 }
322 if ( $num > 0 ) {
323 $s = array();
324 if ( ! $this->listoutput )
325 $s[] = "<ol start='" . ( $offset + 1 ) . "' class='special'>";
326
327 # Only read at most $num rows, because $res may contain the whole 1000
328 for ( $i = 0; $i < $num && $obj = $dbr->fetchObject( $res ); $i++ ) {
329 $format = $this->formatResult( $sk, $obj );
330 if ( $format ) {
331 $attr = ( isset ( $obj->usepatrol ) && $obj->usepatrol &&
332 $obj->patrolled == 0 ) ? ' class="not-patrolled"' : '';
333 $s[] = $this->listoutput ? $format : "<li{$attr}>{$format}</li>\n";
334 }
335 }
336
337 if($this->tryLastResult()) {
338 // flush the very last result
339 $obj = null;
340 $format = $this->formatResult( $sk, $obj );
341 if( $format ) {
342 $attr = ( isset ( $obj->usepatrol ) && $obj->usepatrol &&
343 $obj->patrolled == 0 ) ? ' class="not-patrolled"' : '';
344 $s[] = "<li{$attr}>{$format}</li>\n";
345 }
346 }
347
348 $dbr->freeResult( $res );
349 if ( ! $this->listoutput )
350 $s[] = '</ol>';
351 $str = $this->listoutput ? $wgContLang->listToText( $s ) : implode( '', $s );
352 $wgOut->addHTML( $str );
353 }
354 if($shownavigation) {
355 $wgOut->addHTML( "<p>{$sl}</p>\n" );
356 }
357 return $num;
358 }
359
360 /**
361 * Do any necessary preprocessing of the result object.
362 * You should pass this by reference: &$db , &$res
363 */
364 function preprocessResults( $db, $res ) {}
365
366 /**
367 * Similar to above, but packaging in a syndicated feed instead of a web page
368 */
369 function doFeed( $class = '', $limit = 50 ) {
370 global $wgFeedClasses;
371
372 if( isset($wgFeedClasses[$class]) ) {
373 $feed = new $wgFeedClasses[$class](
374 $this->feedTitle(),
375 $this->feedDesc(),
376 $this->feedUrl() );
377 $feed->outHeader();
378
379 $dbr =& wfGetDB( DB_SLAVE );
380 $sql = $this->getSQL() . $this->getOrder();
381 $sql = $dbr->limitResult( $sql, $limit, 0 );
382 $res = $dbr->query( $sql, 'QueryPage::doFeed' );
383 while( $obj = $dbr->fetchObject( $res ) ) {
384 $item = $this->feedResult( $obj );
385 if( $item ) $feed->outItem( $item );
386 }
387 $dbr->freeResult( $res );
388
389 $feed->outFooter();
390 return true;
391 } else {
392 return false;
393 }
394 }
395
396 /**
397 * Override for custom handling. If the titles/links are ok, just do
398 * feedItemDesc()
399 */
400 function feedResult( $row ) {
401 if( !isset( $row->title ) ) {
402 return NULL;
403 }
404 $title = Title::MakeTitle( intval( $row->namespace ), $row->title );
405 if( $title ) {
406 $date = isset( $row->timestamp ) ? $row->timestamp : '';
407 $comments = '';
408 if( $title ) {
409 $talkpage = $title->getTalkPage();
410 $comments = $talkpage->getFullURL();
411 }
412
413 return new FeedItem(
414 $title->getPrefixedText(),
415 $this->feedItemDesc( $row ),
416 $title->getFullURL(),
417 $date,
418 $this->feedItemAuthor( $row ),
419 $comments);
420 } else {
421 return NULL;
422 }
423 }
424
425 function feedItemDesc( $row ) {
426 return isset( $row->comment ) ? htmlspecialchars( $row->comment ) : '';
427 }
428
429 function feedItemAuthor( $row ) {
430 return isset( $row->user_text ) ? $row->user_text : '';
431 }
432
433 function feedTitle() {
434 global $wgLanguageCode, $wgSitename;
435 $page = SpecialPage::getPage( $this->getName() );
436 $desc = $page->getDescription();
437 return "$wgSitename - $desc [$wgLanguageCode]";
438 }
439
440 function feedDesc() {
441 return wfMsg( 'tagline' );
442 }
443
444 function feedUrl() {
445 $title = Title::MakeTitle( NS_SPECIAL, $this->getName() );
446 return $title->getFullURL();
447 }
448 }
449
450 /**
451 * This is a subclass for very simple queries that are just looking for page
452 * titles that match some criteria. It formats each result item as a link to
453 * that page.
454 *
455 * @package MediaWiki
456 */
457 class PageQueryPage extends QueryPage {
458
459 function formatResult( $skin, $result ) {
460 global $wgContLang;
461 $nt = Title::makeTitle( $result->namespace, $result->title );
462 return $skin->makeKnownLinkObj( $nt, htmlspecialchars( $wgContLang->convert( $nt->getPrefixedText() ) ) );
463 }
464 }
465
466 ?>