refreshLinks.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. /**
  3. * Refresh link tables.
  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 Maintenance
  22. */
  23. require_once __DIR__ . '/Maintenance.php';
  24. /**
  25. * Maintenance script to refresh link tables.
  26. *
  27. * @ingroup Maintenance
  28. */
  29. class RefreshLinks extends Maintenance {
  30. public function __construct() {
  31. parent::__construct();
  32. $this->addDescription( 'Refresh link tables' );
  33. $this->addOption( 'dfn-only', 'Delete links from nonexistent articles only' );
  34. $this->addOption( 'new-only', 'Only affect articles with just a single edit' );
  35. $this->addOption( 'redirects-only', 'Only fix redirects, not all links' );
  36. $this->addOption( 'old-redirects-only', 'Only fix redirects with no redirect table entry' );
  37. $this->addOption( 'e', 'Last page id to refresh', false, true );
  38. $this->addOption( 'dfn-chunk-size', 'Maximum number of existent IDs to check per ' .
  39. 'query, default 100000', false, true );
  40. $this->addArg( 'start', 'Page_id to start from, default 1', false );
  41. $this->setBatchSize( 100 );
  42. }
  43. public function execute() {
  44. // Note that there is a difference between not specifying the start
  45. // and end IDs and using the minimum and maximum values from the page
  46. // table. In the latter case, deleteLinksFromNonexistent() will not
  47. // delete entries for nonexistent IDs that fall outside the range.
  48. $start = (int)$this->getArg( 0 ) ?: null;
  49. $end = (int)$this->getOption( 'e' ) ?: null;
  50. $dfnChunkSize = (int)$this->getOption( 'dfn-chunk-size', 100000 );
  51. if ( !$this->hasOption( 'dfn-only' ) ) {
  52. $new = $this->getOption( 'new-only', false );
  53. $redir = $this->getOption( 'redirects-only', false );
  54. $oldRedir = $this->getOption( 'old-redirects-only', false );
  55. $this->doRefreshLinks( $start, $new, $end, $redir, $oldRedir );
  56. $this->deleteLinksFromNonexistent( null, null, $this->mBatchSize, $dfnChunkSize );
  57. } else {
  58. $this->deleteLinksFromNonexistent( $start, $end, $this->mBatchSize, $dfnChunkSize );
  59. }
  60. }
  61. /**
  62. * Do the actual link refreshing.
  63. * @param int|null $start Page_id to start from
  64. * @param bool $newOnly Only do pages with 1 edit
  65. * @param int|null $end Page_id to stop at
  66. * @param bool $redirectsOnly Only fix redirects
  67. * @param bool $oldRedirectsOnly Only fix redirects without redirect entries
  68. */
  69. private function doRefreshLinks( $start, $newOnly = false,
  70. $end = null, $redirectsOnly = false, $oldRedirectsOnly = false
  71. ) {
  72. $reportingInterval = 100;
  73. $dbr = $this->getDB( DB_SLAVE );
  74. if ( $start === null ) {
  75. $start = 1;
  76. }
  77. // Give extensions a chance to optimize settings
  78. Hooks::run( 'MaintenanceRefreshLinksInit', [ $this ] );
  79. $what = $redirectsOnly ? "redirects" : "links";
  80. if ( $oldRedirectsOnly ) {
  81. # This entire code path is cut-and-pasted from below. Hurrah.
  82. $conds = [
  83. "page_is_redirect=1",
  84. "rd_from IS NULL",
  85. self::intervalCond( $dbr, 'page_id', $start, $end ),
  86. ];
  87. $res = $dbr->select(
  88. [ 'page', 'redirect' ],
  89. 'page_id',
  90. $conds,
  91. __METHOD__,
  92. [],
  93. [ 'redirect' => [ "LEFT JOIN", "page_id=rd_from" ] ]
  94. );
  95. $num = $res->numRows();
  96. $this->output( "Refreshing $num old redirects from $start...\n" );
  97. $i = 0;
  98. foreach ( $res as $row ) {
  99. if ( !( ++$i % $reportingInterval ) ) {
  100. $this->output( "$i\n" );
  101. wfWaitForSlaves();
  102. }
  103. $this->fixRedirect( $row->page_id );
  104. }
  105. } elseif ( $newOnly ) {
  106. $this->output( "Refreshing $what from " );
  107. $res = $dbr->select( 'page',
  108. [ 'page_id' ],
  109. [
  110. 'page_is_new' => 1,
  111. self::intervalCond( $dbr, 'page_id', $start, $end ),
  112. ],
  113. __METHOD__
  114. );
  115. $num = $res->numRows();
  116. $this->output( "$num new articles...\n" );
  117. $i = 0;
  118. foreach ( $res as $row ) {
  119. if ( !( ++$i % $reportingInterval ) ) {
  120. $this->output( "$i\n" );
  121. wfWaitForSlaves();
  122. }
  123. if ( $redirectsOnly ) {
  124. $this->fixRedirect( $row->page_id );
  125. } else {
  126. self::fixLinksFromArticle( $row->page_id );
  127. }
  128. }
  129. } else {
  130. if ( !$end ) {
  131. $maxPage = $dbr->selectField( 'page', 'max(page_id)', false );
  132. $maxRD = $dbr->selectField( 'redirect', 'max(rd_from)', false );
  133. $end = max( $maxPage, $maxRD );
  134. }
  135. $this->output( "Refreshing redirects table.\n" );
  136. $this->output( "Starting from page_id $start of $end.\n" );
  137. for ( $id = $start; $id <= $end; $id++ ) {
  138. if ( !( $id % $reportingInterval ) ) {
  139. $this->output( "$id\n" );
  140. wfWaitForSlaves();
  141. }
  142. $this->fixRedirect( $id );
  143. }
  144. if ( !$redirectsOnly ) {
  145. $this->output( "Refreshing links tables.\n" );
  146. $this->output( "Starting from page_id $start of $end.\n" );
  147. for ( $id = $start; $id <= $end; $id++ ) {
  148. if ( !( $id % $reportingInterval ) ) {
  149. $this->output( "$id\n" );
  150. wfWaitForSlaves();
  151. }
  152. self::fixLinksFromArticle( $id );
  153. }
  154. }
  155. }
  156. }
  157. /**
  158. * Update the redirect entry for a given page.
  159. *
  160. * This methods bypasses the "redirect" table to get the redirect target,
  161. * and parses the page's content to fetch it. This allows to be sure that
  162. * the redirect target is up to date and valid.
  163. * This is particularly useful when modifying namespaces to be sure the
  164. * entry in the "redirect" table points to the correct page and not to an
  165. * invalid one.
  166. *
  167. * @param int $id The page ID to check
  168. */
  169. private function fixRedirect( $id ) {
  170. $page = WikiPage::newFromID( $id );
  171. $dbw = $this->getDB( DB_MASTER );
  172. if ( $page === null ) {
  173. // This page doesn't exist (any more)
  174. // Delete any redirect table entry for it
  175. $dbw->delete( 'redirect', [ 'rd_from' => $id ],
  176. __METHOD__ );
  177. return;
  178. }
  179. $rt = null;
  180. $content = $page->getContent( Revision::RAW );
  181. if ( $content !== null ) {
  182. $rt = $content->getUltimateRedirectTarget();
  183. }
  184. if ( $rt === null ) {
  185. // The page is not a redirect
  186. // Delete any redirect table entry for it
  187. $dbw->delete( 'redirect', [ 'rd_from' => $id ], __METHOD__ );
  188. $fieldValue = 0;
  189. } else {
  190. $page->insertRedirectEntry( $rt );
  191. $fieldValue = 1;
  192. }
  193. // Update the page table to be sure it is an a consistent state
  194. $dbw->update( 'page', [ 'page_is_redirect' => $fieldValue ],
  195. [ 'page_id' => $id ], __METHOD__ );
  196. }
  197. /**
  198. * Run LinksUpdate for all links on a given page_id
  199. * @param int $id The page_id
  200. */
  201. public static function fixLinksFromArticle( $id ) {
  202. $page = WikiPage::newFromID( $id );
  203. LinkCache::singleton()->clear();
  204. if ( $page === null ) {
  205. return;
  206. }
  207. $content = $page->getContent( Revision::RAW );
  208. if ( $content === null ) {
  209. return;
  210. }
  211. $updates = $content->getSecondaryDataUpdates( $page->getTitle() );
  212. DataUpdate::runUpdates( $updates );
  213. }
  214. /**
  215. * Removes non-existing links from pages from pagelinks, imagelinks,
  216. * categorylinks, templatelinks, externallinks, interwikilinks, langlinks and redirect tables.
  217. *
  218. * @param int|null $start Page_id to start from
  219. * @param int|null $end Page_id to stop at
  220. * @param int $batchSize The size of deletion batches
  221. * @param int $chunkSize Maximum number of existent IDs to check per query
  222. *
  223. * @author Merlijn van Deen <valhallasw@arctus.nl>
  224. */
  225. private function deleteLinksFromNonexistent( $start = null, $end = null, $batchSize = 100,
  226. $chunkSize = 100000
  227. ) {
  228. wfWaitForSlaves();
  229. $this->output( "Deleting illegal entries from the links tables...\n" );
  230. $dbr = $this->getDB( DB_SLAVE );
  231. do {
  232. // Find the start of the next chunk. This is based only
  233. // on existent page_ids.
  234. $nextStart = $dbr->selectField(
  235. 'page',
  236. 'page_id',
  237. self::intervalCond( $dbr, 'page_id', $start, $end ),
  238. __METHOD__,
  239. [ 'ORDER BY' => 'page_id', 'OFFSET' => $chunkSize ]
  240. );
  241. if ( $nextStart !== false ) {
  242. // To find the end of the current chunk, subtract one.
  243. // This will serve to limit the number of rows scanned in
  244. // dfnCheckInterval(), per query, to at most the sum of
  245. // the chunk size and deletion batch size.
  246. $chunkEnd = $nextStart - 1;
  247. } else {
  248. // This is the last chunk. Check all page_ids up to $end.
  249. $chunkEnd = $end;
  250. }
  251. $fmtStart = $start !== null ? "[$start" : '(-INF';
  252. $fmtChunkEnd = $chunkEnd !== null ? "$chunkEnd]" : 'INF)';
  253. $this->output( " Checking interval $fmtStart, $fmtChunkEnd\n" );
  254. $this->dfnCheckInterval( $start, $chunkEnd, $batchSize );
  255. $start = $nextStart;
  256. } while ( $nextStart !== false );
  257. }
  258. /**
  259. * @see RefreshLinks::deleteLinksFromNonexistent()
  260. * @param int|null $start Page_id to start from
  261. * @param int|null $end Page_id to stop at
  262. * @param int $batchSize The size of deletion batches
  263. */
  264. private function dfnCheckInterval( $start = null, $end = null, $batchSize = 100 ) {
  265. $dbw = $this->getDB( DB_MASTER );
  266. $dbr = $this->getDB( DB_SLAVE );
  267. $linksTables = [ // table name => page_id field
  268. 'pagelinks' => 'pl_from',
  269. 'imagelinks' => 'il_from',
  270. 'categorylinks' => 'cl_from',
  271. 'templatelinks' => 'tl_from',
  272. 'externallinks' => 'el_from',
  273. 'iwlinks' => 'iwl_from',
  274. 'langlinks' => 'll_from',
  275. 'redirect' => 'rd_from',
  276. 'page_props' => 'pp_page',
  277. ];
  278. foreach ( $linksTables as $table => $field ) {
  279. $this->output( " $table: 0" );
  280. $tableStart = $start;
  281. $counter = 0;
  282. do {
  283. $ids = $dbr->selectFieldValues(
  284. $table,
  285. $field,
  286. [
  287. self::intervalCond( $dbr, $field, $tableStart, $end ),
  288. "$field NOT IN ({$dbr->selectSQLText( 'page', 'page_id' )})",
  289. ],
  290. __METHOD__,
  291. [ 'DISTINCT', 'ORDER BY' => $field, 'LIMIT' => $batchSize ]
  292. );
  293. $numIds = count( $ids );
  294. if ( $numIds ) {
  295. $counter += $numIds;
  296. $dbw->delete( $table, [ $field => $ids ], __METHOD__ );
  297. $this->output( ", $counter" );
  298. $tableStart = $ids[$numIds - 1] + 1;
  299. wfWaitForSlaves();
  300. }
  301. } while ( $numIds >= $batchSize && ( $end === null || $tableStart <= $end ) );
  302. $this->output( " deleted.\n" );
  303. }
  304. }
  305. /**
  306. * Build a SQL expression for a closed interval (i.e. BETWEEN).
  307. *
  308. * By specifying a null $start or $end, it is also possible to create
  309. * half-bounded or unbounded intervals using this function.
  310. *
  311. * @param IDatabase $db Database connection
  312. * @param string $var Field name
  313. * @param mixed $start First value to include or null
  314. * @param mixed $end Last value to include or null
  315. */
  316. private static function intervalCond( IDatabase $db, $var, $start, $end ) {
  317. if ( $start === null && $end === null ) {
  318. return "$var IS NOT NULL";
  319. } elseif ( $end === null ) {
  320. return "$var >= {$db->addQuotes( $start )}";
  321. } elseif ( $start === null ) {
  322. return "$var <= {$db->addQuotes( $end )}";
  323. } else {
  324. return "$var BETWEEN {$db->addQuotes( $start )} AND {$db->addQuotes( $end )}";
  325. }
  326. }
  327. }
  328. $maintClass = 'RefreshLinks';
  329. require_once RUN_MAINTENANCE_IF_MAIN;