3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 use Wikimedia\Purtle\RdfWriter
;
20 use Wikimedia\Purtle\TurtleRdfWriter
;
21 use Wikimedia\Rdbms\IDatabase
;
23 require_once __DIR__
. '/Maintenance.php';
26 * Maintenance script to provide RDF representation of the recent changes in category tree.
28 * @ingroup Maintenance
31 class CategoryChangesAsRdf
extends Maintenance
{
35 const SPARQL_INSERT
= <<<SPARQL
45 const SPARQL_DELETE
= <<<SPARQLD
59 const SPARQL_DELETE_INSERT
= <<<SPARQLDI
77 * Categories RDF helper.
80 private $categoriesRdf;
86 * List of processed page IDs,
87 * so we don't try to process same thing twice
90 protected $processed = [];
92 public function __construct() {
93 parent
::__construct();
95 $this->addDescription( "Generate RDF dump of category changes in a wiki." );
97 $this->setBatchSize( 200 );
98 $this->addOption( 'output', "Output file (default is stdout). Will be overwritten.", false,
100 $this->addOption( 'start', 'Starting timestamp (inclusive), in ISO or Mediawiki format.',
102 $this->addOption( 'end', 'Ending timestamp (exclusive), in ISO or Mediawiki format.', true,
107 * Initialize external service classes.
109 public function initialize() {
110 // SPARQL Update syntax is close to Turtle format, so we can use Turtle writer.
111 $this->rdfWriter
= new TurtleRdfWriter();
112 $this->categoriesRdf
= new CategoriesRdf( $this->rdfWriter
);
115 public function execute() {
119 $startTS = new MWTimestamp( $this->getOption( "start" ) );
121 $endTS = new MWTimestamp( $this->getOption( "end" ) );
122 $now = new MWTimestamp();
124 if ( $now->getTimestamp() - $startTS->getTimestamp() > $wgRCMaxAge ) {
125 $this->error( "Start timestamp too old, maximum RC age is $wgRCMaxAge!" );
127 if ( $now->getTimestamp() - $endTS->getTimestamp() > $wgRCMaxAge ) {
128 $this->error( "End timestamp too old, maximum RC age is $wgRCMaxAge!" );
131 $this->startTS
= $startTS->getTimestamp();
132 $this->endTS
= $endTS->getTimestamp();
134 $outFile = $this->getOption( 'output', 'php://stdout' );
135 if ( $outFile === '-' ) {
136 $outFile = 'php://stdout';
139 $output = fopen( $outFile, 'wb' );
141 $this->categoriesRdf
->setupPrefixes();
142 $this->rdfWriter
->start();
144 $prefixes = $this->getRdf();
145 // We have to strip @ from prefix, since SPARQL UPDATE doesn't use them
146 // Also strip dot at the end.
147 $prefixes = preg_replace( [ '/^@/m', '/\s*[.]$/m' ], '', $prefixes );
148 fwrite( $output, $prefixes );
150 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
152 // Deletes go first because if the page was deleted, other changes
153 // do not matter. This only gets true deletes, i.e. not pages that were restored.
154 $this->handleDeletes( $dbr, $output );
155 // Moves go before additions because if category is moved, we should not process creation
156 // as it would produce wrong data - because create row has old title
157 $this->handleMoves( $dbr, $output );
158 // We need to handle restores too since delete may have happened in previous update.
159 $this->handleRestores( $dbr, $output );
160 $this->handleAdds( $dbr, $output );
161 $this->handleChanges( $dbr, $output );
164 fwrite( $output, $this->updateTS( $this->endTS
) );
168 * Get the text of SPARQL INSERT DATA clause
171 private function getInsertRdf() {
172 $rdfText = $this->getRdf();
176 return sprintf( self
::SPARQL_INSERT
, $rdfText );
180 * Get SPARQL for updating set of categories
181 * @param IDatabase $dbr
182 * @param string[] $deleteUrls List of URIs to be deleted, with <>
183 * @param string[] $pages List of categories: id => title
184 * @param string $mark Marks which operation requests the query
185 * @return string SPARQL query
187 private function getCategoriesUpdate( IDatabase
$dbr, $deleteUrls, $pages, $mark ) {
188 if ( empty( $deleteUrls ) ) {
192 if ( !empty( $pages ) ) {
193 $this->writeParentCategories( $dbr, $pages );
196 return "# $mark\n" . sprintf( self
::SPARQL_DELETE
, implode( ' ', $deleteUrls ) ) .
197 $this->getInsertRdf();
201 * Write data for a set of categories
202 * @param IDatabase $dbr
203 * @param string[] $pages List of categories: id => title
205 private function writeParentCategories( IDatabase
$dbr, $pages ) {
206 foreach ( $this->getCategoryLinksIterator( $dbr, array_keys( $pages ) ) as $row ) {
207 $this->categoriesRdf
->writeCategoryLinkData( $pages[$row->cl_from
], $row->cl_to
);
212 * Generate SPARQL Update code for updating dump timestamp
213 * @param string|int $timestamp Timestamp for last change
214 * @return string SPARQL Update query for timestamp.
216 public function updateTS( $timestamp ) {
217 $dumpUrl = '<' . $this->categoriesRdf
->getDumpURI() . '>';
218 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
221 $dumpUrl schema:dateModified ?o .
224 $dumpUrl schema:dateModified ?o .
227 $dumpUrl schema:dateModified "$ts"^^xsd:dateTime .
235 * Set up standard iterator for retrieving category changes.
236 * @param IDatabase $dbr
237 * @param string[] $columns List of additional fields to get
238 * @param string[] $extra_tables List of additional tables to join
239 * @return BatchRowIterator
241 private function setupChangesIterator(
244 array $extra_tables = []
246 $tables = [ 'recentchanges', 'page_props', 'category' ];
247 if ( $extra_tables ) {
248 $tables = array_merge( $tables, $extra_tables );
250 $it = new BatchRowIterator( $dbr,
255 $this->addTimestampConditions( $it, $dbr );
256 $it->addJoinConditions(
259 'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = rc_cur_id' ]
262 'LEFT JOIN', [ 'cat_title = rc_title' ]
266 $it->setFetchColumns( array_merge( $columns, [
278 * Fetch newly created categories
279 * @param IDatabase $dbr
280 * @return BatchRowIterator
282 protected function getNewCatsIterator( IDatabase
$dbr ) {
283 $it = $this->setupChangesIterator( $dbr );
284 $it->addConditions( [
285 'rc_namespace' => NS_CATEGORY
,
292 * Fetch moved categories
293 * @param IDatabase $dbr
294 * @return BatchRowIterator
296 protected function getMovedCatsIterator( IDatabase
$dbr ) {
297 $it = $this->setupChangesIterator( $dbr, [ 'page_title', 'page_namespace' ], [ 'page' ] );
298 $it->addConditions( [
299 'rc_namespace' => NS_CATEGORY
,
301 'rc_log_type' => 'move',
304 $it->addJoinConditions( [
305 'page' => [ 'INNER JOIN', 'rc_cur_id = page_id' ],
307 $this->addIndex( $it );
312 * Fetch deleted categories
313 * @param IDatabase $dbr
314 * @return BatchRowIterator
316 protected function getDeletedCatsIterator( IDatabase
$dbr ) {
317 $it = new BatchRowIterator( $dbr,
322 $this->addTimestampConditions( $it, $dbr );
323 $it->addConditions( [
324 'rc_namespace' => NS_CATEGORY
,
326 'rc_log_type' => 'delete',
327 'rc_log_action' => 'delete',
329 // We will fetch ones that do not have page record. If they do,
330 // this means they were restored, thus restoring handler will pick it up.
331 'NOT EXISTS (SELECT * FROM page WHERE page_id = rc_cur_id)',
333 $this->addIndex( $it );
334 $it->setFetchColumns( [ 'rc_cur_id', 'rc_title' ] );
339 * Fetch restored categories
340 * @param IDatabase $dbr
341 * @return BatchRowIterator
343 protected function getRestoredCatsIterator( IDatabase
$dbr ) {
344 $it = $this->setupChangesIterator( $dbr );
345 $it->addConditions( [
346 'rc_namespace' => NS_CATEGORY
,
348 'rc_log_type' => 'delete',
349 'rc_log_action' => 'restore',
351 // We will only fetch ones that have page record
352 'EXISTS (SELECT page_id FROM page WHERE page_id = rc_cur_id)',
354 $this->addIndex( $it );
359 * Fetch categorization changes
360 * @param IDatabase $dbr
361 * @return BatchRowIterator
363 protected function getChangedCatsIterator( IDatabase
$dbr ) {
364 $it = $this->setupChangesIterator( $dbr );
365 $it->addConditions( [
366 'rc_namespace' => NS_CATEGORY
,
368 'rc_type' => [ RC_EDIT
, RC_CATEGORIZE
],
370 $this->addIndex( $it );
375 * Add timestamp limits to iterator
376 * @param BatchRowIterator $it Iterator
377 * @param IDatabase $dbr
379 private function addTimestampConditions( BatchRowIterator
$it, IDatabase
$dbr ) {
380 $it->addConditions( [
381 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $this->startTS
) ),
382 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $this->endTS
) ),
387 * Need to force index, somehow on terbium the optimizer chooses wrong one
388 * @param BatchRowIterator $it
390 private function addIndex( BatchRowIterator
$it ) {
392 'USE INDEX' => [ 'recentchanges' => 'new_name_timestamp' ]
397 * Get iterator for links for categories.
398 * @param IDatabase $dbr
399 * @param array $ids List of page IDs
400 * @return Traversable
402 protected function getCategoryLinksIterator( IDatabase
$dbr, array $ids ) {
403 $it = new BatchRowIterator(
406 [ 'cl_from', 'cl_to' ],
409 $it->addConditions( [
410 'cl_type' => 'subcat',
413 $it->setFetchColumns( [ 'cl_from', 'cl_to' ] );
414 return new RecursiveIteratorIterator( $it );
418 * Get accumulated RDF.
421 public function getRdf() {
422 return $this->rdfWriter
->drain();
426 * Handle category deletes.
427 * @param IDatabase $dbr
428 * @param resource $output File to write the output
430 public function handleDeletes( IDatabase
$dbr, $output ) {
431 // This only does "true" deletes - i.e. those that the page stays deleted
432 foreach ( $this->getDeletedCatsIterator( $dbr ) as $batch ) {
434 foreach ( $batch as $row ) {
435 // This can produce duplicates, we don't care
436 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
437 $this->processed
[$row->rc_cur_id
] = true;
439 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, [], "Deletes" ) );
444 * Write category data to RDF.
445 * @param stdclass $row Database row
447 private function writeCategoryData( $row ) {
448 $this->categoriesRdf
->writeCategoryData(
450 $row->pp_propname
=== 'hiddencat',
451 (int)$row->cat_pages
- (int)$row->cat_subcats
- (int)$row->cat_files
,
452 (int)$row->cat_subcats
457 * @param IDatabase $dbr
458 * @param resource $output
460 public function handleMoves( IDatabase
$dbr, $output ) {
461 foreach ( $this->getMovedCatsIterator( $dbr ) as $batch ) {
464 foreach ( $batch as $row ) {
465 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
467 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
468 // We already captured this one before
472 if ( $row->page_namespace
!= NS_CATEGORY
) {
473 // If page was moved out of Category:, we'll just delete
476 $row->rc_title
= $row->page_title
;
477 $this->writeCategoryData( $row );
478 $pages[$row->rc_cur_id
] = $row->page_title
;
479 $this->processed
[$row->rc_cur_id
] = true;
482 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Moves" ) );
487 * @param IDatabase $dbr
488 * @param resource $output
490 public function handleRestores( IDatabase
$dbr, $output ) {
491 fwrite( $output, "# Restores\n" );
492 // This will only find those restores that were not deleted later.
493 foreach ( $this->getRestoredCatsIterator( $dbr ) as $batch ) {
495 foreach ( $batch as $row ) {
496 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
497 // We already captured this one before
500 $this->writeCategoryData( $row );
501 $pages[$row->rc_cur_id
] = $row->rc_title
;
502 $this->processed
[$row->rc_cur_id
] = true;
505 if ( empty( $pages ) ) {
509 $this->writeParentCategories( $dbr, $pages );
511 fwrite( $output, $this->getInsertRdf() );
516 * @param IDatabase $dbr
517 * @param resource $output
519 public function handleAdds( IDatabase
$dbr, $output ) {
520 fwrite( $output, "# Additions\n" );
521 foreach ( $this->getNewCatsIterator( $dbr ) as $batch ) {
523 foreach ( $batch as $row ) {
524 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
525 // We already captured this one before
528 $this->writeCategoryData( $row );
529 $pages[$row->rc_cur_id
] = $row->rc_title
;
530 $this->processed
[$row->rc_cur_id
] = true;
533 if ( empty( $pages ) ) {
537 $this->writeParentCategories( $dbr, $pages );
538 fwrite( $output, $this->getInsertRdf() );
543 * @param IDatabase $dbr
544 * @param resource $output
546 public function handleChanges( IDatabase
$dbr, $output ) {
547 foreach ( $this->getChangedCatsIterator( $dbr ) as $batch ) {
550 foreach ( $batch as $row ) {
551 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
552 // We already captured this one before
555 $this->writeCategoryData( $row );
556 $pages[$row->rc_cur_id
] = $row->rc_title
;
557 $this->processed
[$row->rc_cur_id
] = true;
558 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
561 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Changes" ) );
566 $maintClass = CategoryChangesAsRdf
::class;
567 require_once RUN_MAINTENANCE_IF_MAIN
;