QueryPage.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. <?php
  2. /**
  3. * Base code for "query" special pages.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup SpecialPage
  22. */
  23. use MediaWiki\Linker\LinkTarget;
  24. use MediaWiki\MediaWikiServices;
  25. use Wikimedia\Rdbms\IResultWrapper;
  26. use Wikimedia\Rdbms\IDatabase;
  27. use Wikimedia\Rdbms\DBError;
  28. /**
  29. * This is a class for doing query pages; since they're almost all the same,
  30. * we factor out some of the functionality into a superclass, and let
  31. * subclasses derive from it.
  32. * @ingroup SpecialPage
  33. */
  34. abstract class QueryPage extends SpecialPage {
  35. /** @var bool Whether or not we want plain listoutput rather than an ordered list */
  36. protected $listoutput = false;
  37. /** @var int The offset and limit in use, as passed to the query() function */
  38. protected $offset = 0;
  39. /** @var int */
  40. protected $limit = 0;
  41. /**
  42. * The number of rows returned by the query. Reading this variable
  43. * only makes sense in functions that are run after the query has been
  44. * done, such as preprocessResults() and formatRow().
  45. *
  46. * @var int
  47. */
  48. protected $numRows;
  49. /**
  50. * @var string|null
  51. */
  52. protected $cachedTimestamp = null;
  53. /**
  54. * @var bool Whether to show prev/next links
  55. */
  56. protected $shownavigation = true;
  57. /**
  58. * Get a list of query page classes and their associated special pages,
  59. * for periodic updates.
  60. *
  61. * DO NOT CHANGE THIS LIST without testing that
  62. * maintenance/updateSpecialPages.php still works.
  63. *
  64. * @return string[][]
  65. */
  66. public static function getPages() {
  67. static $qp = null;
  68. if ( $qp === null ) {
  69. // QueryPage subclass, Special page name
  70. $qp = [
  71. [ SpecialAncientPages::class, 'Ancientpages' ],
  72. [ SpecialBrokenRedirects::class, 'BrokenRedirects' ],
  73. [ SpecialDeadendPages::class, 'Deadendpages' ],
  74. [ SpecialDoubleRedirects::class, 'DoubleRedirects' ],
  75. [ SpecialFileDuplicateSearch::class, 'FileDuplicateSearch' ],
  76. [ SpecialListDuplicatedFiles::class, 'ListDuplicatedFiles' ],
  77. [ SpecialLinkSearch::class, 'LinkSearch' ],
  78. [ SpecialListRedirects::class, 'Listredirects' ],
  79. [ SpecialLonelyPages::class, 'Lonelypages' ],
  80. [ SpecialLongPages::class, 'Longpages' ],
  81. [ SpecialMediaStatistics::class, 'MediaStatistics' ],
  82. [ SpecialMIMESearch::class, 'MIMEsearch' ],
  83. [ SpecialMostCategories::class, 'Mostcategories' ],
  84. [ MostimagesPage::class, 'Mostimages' ],
  85. [ SpecialMostInterwikis::class, 'Mostinterwikis' ],
  86. [ SpecialMostLinkedCategories::class, 'Mostlinkedcategories' ],
  87. [ SpecialMostLinkedTemplates::class, 'Mostlinkedtemplates' ],
  88. [ SpecialMostLinked::class, 'Mostlinked' ],
  89. [ SpecialMostRevisions::class, 'Mostrevisions' ],
  90. [ SpecialFewestRevisions::class, 'Fewestrevisions' ],
  91. [ SpecialShortPages::class, 'Shortpages' ],
  92. [ SpecialUncategorizedCategories::class, 'Uncategorizedcategories' ],
  93. [ SpecialUncategorizedPages::class, 'Uncategorizedpages' ],
  94. [ SpecialUncategorizedImages::class, 'Uncategorizedimages' ],
  95. [ SpecialUncategorizedTemplates::class, 'Uncategorizedtemplates' ],
  96. [ SpecialUnusedCategories::class, 'Unusedcategories' ],
  97. [ SpecialUnusedImages::class, 'Unusedimages' ],
  98. [ SpecialWantedCategories::class, 'Wantedcategories' ],
  99. [ WantedFilesPage::class, 'Wantedfiles' ],
  100. [ WantedPagesPage::class, 'Wantedpages' ],
  101. [ SpecialWantedTemplates::class, 'Wantedtemplates' ],
  102. [ SpecialUnwatchedPages::class, 'Unwatchedpages' ],
  103. [ SpecialUnusedTemplates::class, 'Unusedtemplates' ],
  104. [ SpecialWithoutInterwiki::class, 'Withoutinterwiki' ],
  105. ];
  106. Hooks::run( 'wgQueryPages', [ &$qp ] );
  107. }
  108. return $qp;
  109. }
  110. /**
  111. * Get a list of query pages disabled and with it's run mode
  112. * @param Config $config
  113. * @return string[]
  114. */
  115. public static function getDisabledQueryPages( Config $config ) {
  116. $disableQueryPageUpdate = $config->get( 'DisableQueryPageUpdate' );
  117. if ( !is_array( $disableQueryPageUpdate ) ) {
  118. return [];
  119. }
  120. $pages = [];
  121. foreach ( $disableQueryPageUpdate as $name => $runMode ) {
  122. if ( is_int( $name ) ) {
  123. // The run mode may be omitted
  124. $pages[$runMode] = 'disabled';
  125. } else {
  126. $pages[$name] = $runMode;
  127. }
  128. }
  129. return $pages;
  130. }
  131. /**
  132. * A mutator for $this->listoutput;
  133. *
  134. * @param bool $bool
  135. */
  136. function setListoutput( $bool ) {
  137. $this->listoutput = $bool;
  138. }
  139. /**
  140. * Subclasses return an SQL query here, formatted as an array with the
  141. * following keys:
  142. * tables => Table(s) for passing to Database::select()
  143. * fields => Field(s) for passing to Database::select(), may be *
  144. * conds => WHERE conditions
  145. * options => options
  146. * join_conds => JOIN conditions
  147. *
  148. * Note that the query itself should return the following three columns:
  149. * 'namespace', 'title', and 'value'. 'value' is used for sorting.
  150. *
  151. * These may be stored in the querycache table for expensive queries,
  152. * and that cached data will be returned sometimes, so the presence of
  153. * extra fields can't be relied upon. The cached 'value' column will be
  154. * an integer; non-numeric values are useful only for sorting the
  155. * initial query (except if they're timestamps, see usesTimestamps()).
  156. *
  157. * Don't include an ORDER or LIMIT clause, they will be added.
  158. *
  159. * If this function is not overridden or returns something other than
  160. * an array, getSQL() will be used instead. This is for backwards
  161. * compatibility only and is strongly deprecated.
  162. * @return array
  163. * @since 1.18
  164. */
  165. public function getQueryInfo() {
  166. return null;
  167. }
  168. /**
  169. * For back-compat, subclasses may return a raw SQL query here, as a string.
  170. * This is strongly deprecated; getQueryInfo() should be overridden instead.
  171. * @throws MWException
  172. * @return string
  173. */
  174. function getSQL() {
  175. /* Implement getQueryInfo() instead */
  176. throw new MWException( "Bug in a QueryPage: doesn't implement getQueryInfo() nor "
  177. . "getQuery() properly" );
  178. }
  179. /**
  180. * Subclasses return an array of fields to order by here. Don't append
  181. * DESC to the field names, that'll be done automatically if
  182. * sortDescending() returns true.
  183. * @return string[]
  184. * @since 1.18
  185. */
  186. function getOrderFields() {
  187. return [ 'value' ];
  188. }
  189. /**
  190. * Does this query return timestamps rather than integers in its
  191. * 'value' field? If true, this class will convert 'value' to a
  192. * UNIX timestamp for caching.
  193. * NOTE: formatRow() may get timestamps in TS_MW (mysql), TS_DB (pgsql)
  194. * or TS_UNIX (querycache) format, so be sure to always run them
  195. * through wfTimestamp()
  196. * @return bool
  197. * @since 1.18
  198. */
  199. public function usesTimestamps() {
  200. return false;
  201. }
  202. /**
  203. * Override to sort by increasing values
  204. *
  205. * @return bool
  206. */
  207. function sortDescending() {
  208. return true;
  209. }
  210. /**
  211. * Is this query expensive (for some definition of expensive)? Then we
  212. * don't let it run in miser mode. $wgDisableQueryPages causes all query
  213. * pages to be declared expensive. Some query pages are always expensive.
  214. *
  215. * @return bool
  216. */
  217. public function isExpensive() {
  218. return $this->getConfig()->get( 'DisableQueryPages' );
  219. }
  220. /**
  221. * Is the output of this query cacheable? Non-cacheable expensive pages
  222. * will be disabled in miser mode and will not have their results written
  223. * to the querycache table.
  224. * @return bool
  225. * @since 1.18
  226. */
  227. public function isCacheable() {
  228. return true;
  229. }
  230. /**
  231. * Whether or not the output of the page in question is retrieved from
  232. * the database cache.
  233. *
  234. * @return bool
  235. */
  236. public function isCached() {
  237. return $this->isExpensive() && $this->getConfig()->get( 'MiserMode' );
  238. }
  239. /**
  240. * Sometime we don't want to build rss / atom feeds.
  241. *
  242. * @return bool
  243. */
  244. function isSyndicated() {
  245. return true;
  246. }
  247. /**
  248. * Formats the results of the query for display. The skin is the current
  249. * skin; you can use it for making links. The result is a single row of
  250. * result data. You should be able to grab SQL results off of it.
  251. * If the function returns false, the line output will be skipped.
  252. * @param Skin $skin
  253. * @param object $result Result row
  254. * @return string|bool String or false to skip
  255. */
  256. abstract function formatResult( $skin, $result );
  257. /**
  258. * The content returned by this function will be output before any result
  259. *
  260. * @return string
  261. */
  262. function getPageHeader() {
  263. return '';
  264. }
  265. /**
  266. * Outputs some kind of an informative message (via OutputPage) to let the
  267. * user know that the query returned nothing and thus there's nothing to
  268. * show.
  269. *
  270. * @since 1.26
  271. */
  272. protected function showEmptyText() {
  273. $this->getOutput()->addWikiMsg( 'specialpage-empty' );
  274. }
  275. /**
  276. * If using extra form wheely-dealies, return a set of parameters here
  277. * as an associative array. They will be encoded and added to the paging
  278. * links (prev/next/lengths).
  279. *
  280. * @return array
  281. */
  282. function linkParameters() {
  283. return [];
  284. }
  285. /**
  286. * Clear the cache and save new results
  287. *
  288. * @param int|bool $limit Limit for SQL statement
  289. * @param bool $ignoreErrors Whether to ignore database errors
  290. * @throws DBError|Exception
  291. * @return bool|int
  292. */
  293. public function recache( $limit, $ignoreErrors = true ) {
  294. if ( !$this->isCacheable() ) {
  295. return 0;
  296. }
  297. $fname = static::class . '::recache';
  298. $dbw = wfGetDB( DB_MASTER );
  299. if ( !$dbw ) {
  300. return false;
  301. }
  302. try {
  303. # Do query
  304. $res = $this->reallyDoQuery( $limit, false );
  305. $num = false;
  306. if ( $res ) {
  307. $num = $res->numRows();
  308. # Fetch results
  309. $vals = [];
  310. foreach ( $res as $i => $row ) {
  311. if ( isset( $row->value ) ) {
  312. if ( $this->usesTimestamps() ) {
  313. $value = wfTimestamp( TS_UNIX,
  314. $row->value );
  315. } else {
  316. $value = intval( $row->value ); // T16414
  317. }
  318. } else {
  319. $value = $i;
  320. }
  321. $vals[] = [
  322. 'qc_type' => $this->getName(),
  323. 'qc_namespace' => $row->namespace,
  324. 'qc_title' => $row->title,
  325. 'qc_value' => $value
  326. ];
  327. }
  328. $dbw->doAtomicSection(
  329. __METHOD__,
  330. function ( IDatabase $dbw, $fname ) use ( $vals ) {
  331. # Clear out any old cached data
  332. $dbw->delete( 'querycache',
  333. [ 'qc_type' => $this->getName() ],
  334. $fname
  335. );
  336. # Save results into the querycache table on the master
  337. if ( count( $vals ) ) {
  338. $dbw->insert( 'querycache', $vals, $fname );
  339. }
  340. # Update the querycache_info record for the page
  341. $dbw->delete( 'querycache_info',
  342. [ 'qci_type' => $this->getName() ],
  343. $fname
  344. );
  345. $dbw->insert( 'querycache_info',
  346. [ 'qci_type' => $this->getName(),
  347. 'qci_timestamp' => $dbw->timestamp() ],
  348. $fname
  349. );
  350. }
  351. );
  352. }
  353. } catch ( DBError $e ) {
  354. if ( !$ignoreErrors ) {
  355. throw $e; // report query error
  356. }
  357. $num = false; // set result to false to indicate error
  358. }
  359. return $num;
  360. }
  361. /**
  362. * Get a DB connection to be used for slow recache queries
  363. * @return IDatabase
  364. */
  365. function getRecacheDB() {
  366. return wfGetDB( DB_REPLICA, [ $this->getName(), 'QueryPage::recache', 'vslow' ] );
  367. }
  368. /**
  369. * Remove a cached result.
  370. * Useful for interactive backlogs where the user can fix problems in-place.
  371. * @param LinkTarget $title The page to remove.
  372. * @since 1.34
  373. */
  374. public function delete( LinkTarget $title ) {
  375. if ( $this->isCached() ) {
  376. $dbw = wfGetDB( DB_MASTER );
  377. $dbw->delete( 'querycache', [
  378. 'qc_type' => $this->getName(),
  379. 'qc_namespace' => $title->getNamespace(),
  380. 'qc_title' => $title->getDBkey(),
  381. ], __METHOD__ );
  382. }
  383. }
  384. /**
  385. * Run the query and return the result
  386. * @param int|bool $limit Numerical limit or false for no limit
  387. * @param int|bool $offset Numerical offset or false for no offset
  388. * @return IResultWrapper
  389. * @since 1.18
  390. */
  391. public function reallyDoQuery( $limit, $offset = false ) {
  392. $fname = static::class . '::reallyDoQuery';
  393. $dbr = $this->getRecacheDB();
  394. $query = $this->getQueryInfo();
  395. $order = $this->getOrderFields();
  396. if ( $this->sortDescending() ) {
  397. foreach ( $order as &$field ) {
  398. $field .= ' DESC';
  399. }
  400. }
  401. if ( is_array( $query ) ) {
  402. $tables = isset( $query['tables'] ) ? (array)$query['tables'] : [];
  403. $fields = isset( $query['fields'] ) ? (array)$query['fields'] : [];
  404. $conds = isset( $query['conds'] ) ? (array)$query['conds'] : [];
  405. $options = isset( $query['options'] ) ? (array)$query['options'] : [];
  406. $join_conds = isset( $query['join_conds'] ) ? (array)$query['join_conds'] : [];
  407. if ( $order ) {
  408. $options['ORDER BY'] = $order;
  409. }
  410. if ( $limit !== false ) {
  411. $options['LIMIT'] = intval( $limit );
  412. }
  413. if ( $offset !== false ) {
  414. $options['OFFSET'] = intval( $offset );
  415. }
  416. $res = $dbr->select( $tables, $fields, $conds, $fname,
  417. $options, $join_conds
  418. );
  419. } else {
  420. // Old-fashioned raw SQL style, deprecated
  421. $sql = $this->getSQL();
  422. $sql .= ' ORDER BY ' . implode( ', ', $order );
  423. $sql = $dbr->limitResult( $sql, $limit, $offset );
  424. $res = $dbr->query( $sql, $fname );
  425. }
  426. return $res;
  427. }
  428. /**
  429. * Somewhat deprecated, you probably want to be using execute()
  430. * @param int|bool $offset
  431. * @param int|bool $limit
  432. * @return IResultWrapper
  433. */
  434. public function doQuery( $offset = false, $limit = false ) {
  435. if ( $this->isCached() && $this->isCacheable() ) {
  436. return $this->fetchFromCache( $limit, $offset );
  437. } else {
  438. return $this->reallyDoQuery( $limit, $offset );
  439. }
  440. }
  441. /**
  442. * Fetch the query results from the query cache
  443. * @param int|bool $limit Numerical limit or false for no limit
  444. * @param int|bool $offset Numerical offset or false for no offset
  445. * @return IResultWrapper
  446. * @since 1.18
  447. */
  448. public function fetchFromCache( $limit, $offset = false ) {
  449. $dbr = wfGetDB( DB_REPLICA );
  450. $options = [];
  451. if ( $limit !== false ) {
  452. $options['LIMIT'] = intval( $limit );
  453. }
  454. if ( $offset !== false ) {
  455. $options['OFFSET'] = intval( $offset );
  456. }
  457. $order = $this->getCacheOrderFields();
  458. if ( $this->sortDescending() ) {
  459. foreach ( $order as &$field ) {
  460. $field .= " DESC";
  461. }
  462. }
  463. if ( $order ) {
  464. $options['ORDER BY'] = $order;
  465. }
  466. return $dbr->select( 'querycache',
  467. [ 'qc_type',
  468. 'namespace' => 'qc_namespace',
  469. 'title' => 'qc_title',
  470. 'value' => 'qc_value' ],
  471. [ 'qc_type' => $this->getName() ],
  472. __METHOD__,
  473. $options
  474. );
  475. }
  476. /**
  477. * Return the order fields for fetchFromCache. Default is to always use
  478. * "ORDER BY value" which was the default prior to this function.
  479. * @return array
  480. * @since 1.29
  481. */
  482. function getCacheOrderFields() {
  483. return [ 'value' ];
  484. }
  485. /**
  486. * @return string
  487. */
  488. public function getCachedTimestamp() {
  489. if ( is_null( $this->cachedTimestamp ) ) {
  490. $dbr = wfGetDB( DB_REPLICA );
  491. $fname = static::class . '::getCachedTimestamp';
  492. $this->cachedTimestamp = $dbr->selectField( 'querycache_info', 'qci_timestamp',
  493. [ 'qci_type' => $this->getName() ], $fname );
  494. }
  495. return $this->cachedTimestamp;
  496. }
  497. /**
  498. * Returns limit and offset, as returned by $this->getRequest()->getLimitOffset().
  499. * Subclasses may override this to further restrict or modify limit and offset.
  500. *
  501. * @note Restricts the offset parameter, as most query pages have inefficient paging
  502. *
  503. * Its generally expected that the returned limit will not be 0, and the returned
  504. * offset will be less than the max results.
  505. *
  506. * @since 1.26
  507. * @return int[] list( $limit, $offset )
  508. */
  509. protected function getLimitOffset() {
  510. list( $limit, $offset ) = $this->getRequest()->getLimitOffset();
  511. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  512. $maxResults = $this->getMaxResults();
  513. // Can't display more than max results on a page
  514. $limit = min( $limit, $maxResults );
  515. // Can't skip over more than the end of $maxResults
  516. $offset = min( $offset, $maxResults + 1 );
  517. }
  518. return [ $limit, $offset ];
  519. }
  520. /**
  521. * What is limit to fetch from DB
  522. *
  523. * Used to make it appear the DB stores less results then it actually does
  524. * @param int $uiLimit Limit from UI
  525. * @param int $uiOffset Offset from UI
  526. * @return int Limit to use for DB (not including extra row to see if at end)
  527. */
  528. protected function getDBLimit( $uiLimit, $uiOffset ) {
  529. $maxResults = $this->getMaxResults();
  530. if ( $this->getConfig()->get( 'MiserMode' ) ) {
  531. $limit = min( $uiLimit + 1, $maxResults - $uiOffset );
  532. return max( $limit, 0 );
  533. } else {
  534. return $uiLimit + 1;
  535. }
  536. }
  537. /**
  538. * Get max number of results we can return in miser mode.
  539. *
  540. * Most QueryPage subclasses use inefficient paging, so limit the max amount we return
  541. * This matters for uncached query pages that might otherwise accept an offset of 3 million
  542. *
  543. * @since 1.27
  544. * @return int
  545. */
  546. protected function getMaxResults() {
  547. // Max of 10000, unless we store more than 10000 in query cache.
  548. return max( $this->getConfig()->get( 'QueryCacheLimit' ), 10000 );
  549. }
  550. /**
  551. * This is the actual workhorse. It does everything needed to make a
  552. * real, honest-to-gosh query page.
  553. * @param string|null $par
  554. */
  555. public function execute( $par ) {
  556. $user = $this->getUser();
  557. if ( !$this->userCanExecute( $user ) ) {
  558. $this->displayRestrictionError();
  559. return;
  560. }
  561. $this->setHeaders();
  562. $this->outputHeader();
  563. $out = $this->getOutput();
  564. if ( $this->isCached() && !$this->isCacheable() ) {
  565. $out->addWikiMsg( 'querypage-disabled' );
  566. return;
  567. }
  568. $out->setSyndicated( $this->isSyndicated() );
  569. if ( $this->limit == 0 && $this->offset == 0 ) {
  570. list( $this->limit, $this->offset ) = $this->getLimitOffset();
  571. }
  572. $dbLimit = $this->getDBLimit( $this->limit, $this->offset );
  573. // @todo Use doQuery()
  574. if ( !$this->isCached() ) {
  575. # select one extra row for navigation
  576. $res = $this->reallyDoQuery( $dbLimit, $this->offset );
  577. } else {
  578. # Get the cached result, select one extra row for navigation
  579. $res = $this->fetchFromCache( $dbLimit, $this->offset );
  580. if ( !$this->listoutput ) {
  581. # Fetch the timestamp of this update
  582. $ts = $this->getCachedTimestamp();
  583. $lang = $this->getLanguage();
  584. $maxResults = $lang->formatNum( $this->getConfig()->get( 'QueryCacheLimit' ) );
  585. if ( $ts ) {
  586. $updated = $lang->userTimeAndDate( $ts, $user );
  587. $updateddate = $lang->userDate( $ts, $user );
  588. $updatedtime = $lang->userTime( $ts, $user );
  589. $out->addMeta( 'Data-Cache-Time', $ts );
  590. $out->addJsConfigVars( 'dataCacheTime', $ts );
  591. $out->addWikiMsg( 'perfcachedts', $updated, $updateddate, $updatedtime, $maxResults );
  592. } else {
  593. $out->addWikiMsg( 'perfcached', $maxResults );
  594. }
  595. # If updates on this page have been disabled, let the user know
  596. # that the data set won't be refreshed for now
  597. $disabledQueryPages = self::getDisabledQueryPages( $this->getConfig() );
  598. if ( isset( $disabledQueryPages[$this->getName()] ) ) {
  599. $runMode = $disabledQueryPages[$this->getName()];
  600. if ( $runMode === 'disabled' ) {
  601. $out->wrapWikiMsg(
  602. "<div class=\"mw-querypage-no-updates\">\n$1\n</div>",
  603. 'querypage-no-updates'
  604. );
  605. } else {
  606. // Messages used here: querypage-updates-periodical
  607. $out->wrapWikiMsg(
  608. "<div class=\"mw-querypage-updates-" . $runMode . "\">\n$1\n</div>",
  609. 'querypage-updates-' . $runMode
  610. );
  611. }
  612. }
  613. }
  614. }
  615. $this->numRows = $res->numRows();
  616. $dbr = $this->getRecacheDB();
  617. $this->preprocessResults( $dbr, $res );
  618. $out->addHTML( Xml::openElement( 'div', [ 'class' => 'mw-spcontent' ] ) );
  619. # Top header and navigation
  620. if ( $this->shownavigation ) {
  621. $out->addHTML( $this->getPageHeader() );
  622. if ( $this->numRows > 0 ) {
  623. $out->addHTML( $this->msg( 'showingresultsinrange' )->numParams(
  624. min( $this->numRows, $this->limit ), # do not show the one extra row, if exist
  625. $this->offset + 1, ( min( $this->numRows, $this->limit ) + $this->offset ) )->parseAsBlock() );
  626. # Disable the "next" link when we reach the end
  627. $miserMaxResults = $this->getConfig()->get( 'MiserMode' )
  628. && ( $this->offset + $this->limit >= $this->getMaxResults() );
  629. $atEnd = ( $this->numRows <= $this->limit ) || $miserMaxResults;
  630. $paging = $this->buildPrevNextNavigation( $this->offset,
  631. $this->limit, $this->linkParameters(), $atEnd, $par );
  632. $out->addHTML( '<p>' . $paging . '</p>' );
  633. } else {
  634. # No results to show, so don't bother with "showing X of Y" etc.
  635. # -- just let the user know and give up now
  636. $this->showEmptyText();
  637. $out->addHTML( Xml::closeElement( 'div' ) );
  638. return;
  639. }
  640. }
  641. # The actual results; specialist subclasses will want to handle this
  642. # with more than a straight list, so we hand them the info, plus
  643. # an OutputPage, and let them get on with it
  644. $this->outputResults( $out,
  645. $this->getSkin(),
  646. $dbr, # Should use IResultWrapper for this
  647. $res,
  648. min( $this->numRows, $this->limit ), # do not format the one extra row, if exist
  649. $this->offset );
  650. # Repeat the paging links at the bottom
  651. if ( $this->shownavigation ) {
  652. $out->addHTML( '<p>' . $paging . '</p>' );
  653. }
  654. $out->addHTML( Xml::closeElement( 'div' ) );
  655. }
  656. /**
  657. * Format and output report results using the given information plus
  658. * OutputPage
  659. *
  660. * @param OutputPage $out OutputPage to print to
  661. * @param Skin $skin User skin to use
  662. * @param IDatabase $dbr Database (read) connection to use
  663. * @param IResultWrapper $res Result pointer
  664. * @param int $num Number of available result rows
  665. * @param int $offset Paging offset
  666. */
  667. protected function outputResults( $out, $skin, $dbr, $res, $num, $offset ) {
  668. if ( $num > 0 ) {
  669. $html = [];
  670. if ( !$this->listoutput ) {
  671. $html[] = $this->openList( $offset );
  672. }
  673. # $res might contain the whole 1,000 rows, so we read up to
  674. # $num [should update this to use a Pager]
  675. for ( $i = 0; $i < $num && $row = $res->fetchObject(); $i++ ) {
  676. $line = $this->formatResult( $skin, $row );
  677. if ( $line ) {
  678. $html[] = $this->listoutput
  679. ? $line
  680. : "<li>{$line}</li>\n";
  681. }
  682. }
  683. if ( !$this->listoutput ) {
  684. $html[] = $this->closeList();
  685. }
  686. $html = $this->listoutput
  687. ? MediaWikiServices::getInstance()->getContentLanguage()->listToText( $html )
  688. : implode( '', $html );
  689. $out->addHTML( $html );
  690. }
  691. }
  692. /**
  693. * @param int $offset
  694. * @return string
  695. */
  696. function openList( $offset ) {
  697. return "\n<ol start='" . ( $offset + 1 ) . "' class='special'>\n";
  698. }
  699. /**
  700. * @return string
  701. */
  702. function closeList() {
  703. return "</ol>\n";
  704. }
  705. /**
  706. * Do any necessary preprocessing of the result object.
  707. * @param IDatabase $db
  708. * @param IResultWrapper $res
  709. */
  710. function preprocessResults( $db, $res ) {
  711. }
  712. /**
  713. * Creates a new LinkBatch object, adds all pages from the passed result wrapper (MUST include
  714. * title and optional the namespace field) and executes the batch. This operation will pre-cache
  715. * LinkCache information like page existence and information for stub color and redirect hints.
  716. *
  717. * @param IResultWrapper $res The result wrapper to process. Needs to include the title
  718. * field and namespace field, if the $ns parameter isn't set.
  719. * @param null $ns Use this namespace for the given titles in the result wrapper,
  720. * instead of the namespace value of $res.
  721. */
  722. protected function executeLBFromResultWrapper( IResultWrapper $res, $ns = null ) {
  723. if ( !$res->numRows() ) {
  724. return;
  725. }
  726. $batch = new LinkBatch;
  727. foreach ( $res as $row ) {
  728. $batch->add( $ns ?? $row->namespace, $row->title );
  729. }
  730. $batch->execute();
  731. $res->seek( 0 );
  732. }
  733. }