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
60 const SPARQL_DELETE_INSERT
= <<<SPARQLDI
79 * Categories RDF helper.
82 private $categoriesRdf;
88 * List of processed page IDs,
89 * so we don't try to process same thing twice
92 protected $processed = [];
94 public function __construct() {
95 parent
::__construct();
97 $this->addDescription( "Generate RDF dump of category changes in a wiki." );
99 $this->setBatchSize( 200 );
100 $this->addOption( 'output', "Output file (default is stdout). Will be overwritten.", false,
102 $this->addOption( 'start', 'Starting timestamp (inclusive), in ISO or Mediawiki format.',
104 $this->addOption( 'end', 'Ending timestamp (exclusive), in ISO or Mediawiki format.', true,
109 * Initialize external service classes.
111 public function initialize() {
112 // SPARQL Update syntax is close to Turtle format, so we can use Turtle writer.
113 $this->rdfWriter
= new TurtleRdfWriter();
114 $this->categoriesRdf
= new CategoriesRdf( $this->rdfWriter
);
117 public function execute() {
121 $startTS = new MWTimestamp( $this->getOption( "start" ) );
123 $endTS = new MWTimestamp( $this->getOption( "end" ) );
124 $now = new MWTimestamp();
126 if ( $now->getTimestamp() - $startTS->getTimestamp() > $wgRCMaxAge ) {
127 $this->error( "Start timestamp too old, maximum RC age is $wgRCMaxAge!" );
129 if ( $now->getTimestamp() - $endTS->getTimestamp() > $wgRCMaxAge ) {
130 $this->error( "End timestamp too old, maximum RC age is $wgRCMaxAge!" );
133 $this->startTS
= $startTS->getTimestamp();
134 $this->endTS
= $endTS->getTimestamp();
136 $outFile = $this->getOption( 'output', 'php://stdout' );
137 if ( $outFile === '-' ) {
138 $outFile = 'php://stdout';
141 $output = fopen( $outFile, 'wb' );
143 $this->categoriesRdf
->setupPrefixes();
144 $this->rdfWriter
->start();
146 $prefixes = $this->getRdf();
147 // We have to strip @ from prefix, since SPARQL UPDATE doesn't use them
148 // Also strip dot at the end.
149 $prefixes = preg_replace( [ '/^@/m', '/\s*[.]$/m' ], '', $prefixes );
150 fwrite( $output, $prefixes );
152 $dbr = $this->getDB( DB_REPLICA
, [ 'vslow' ] );
154 // Deletes go first because if the page was deleted, other changes
155 // do not matter. This only gets true deletes, i.e. not pages that were restored.
156 $this->handleDeletes( $dbr, $output );
157 // Moves go before additions because if category is moved, we should not process creation
158 // as it would produce wrong data - because create row has old title
159 $this->handleMoves( $dbr, $output );
160 // We need to handle restores too since delete may have happened in previous update.
161 $this->handleRestores( $dbr, $output );
162 // Process newly added pages
163 $this->handleAdds( $dbr, $output );
164 // Process page edits
165 $this->handleEdits( $dbr, $output );
166 // Process categorization changes
167 $this->handleCategorization( $dbr, $output );
170 fwrite( $output, $this->updateTS( $this->endTS
) );
174 * Get the text of SPARQL INSERT DATA clause
177 private function getInsertRdf() {
178 $rdfText = $this->getRdf();
182 return sprintf( self
::SPARQL_INSERT
, $rdfText );
186 * Get SPARQL for updating set of categories
187 * @param IDatabase $dbr
188 * @param string[] $deleteUrls List of URIs to be deleted, with <>
189 * @param string[] $pages List of categories: id => title
190 * @param string $mark Marks which operation requests the query
191 * @return string SPARQL query
193 private function getCategoriesUpdate( IDatabase
$dbr, $deleteUrls, $pages, $mark ) {
194 if ( empty( $deleteUrls ) ) {
198 if ( !empty( $pages ) ) {
199 $this->writeParentCategories( $dbr, $pages );
202 return "# $mark\n" . sprintf( self
::SPARQL_DELETE
, implode( ' ', $deleteUrls ) ) .
203 $this->getInsertRdf();
207 * Write parent data for a set of categories.
208 * The list has the child categories.
209 * @param IDatabase $dbr
210 * @param string[] $pages List of child categories: id => title
212 private function writeParentCategories( IDatabase
$dbr, $pages ) {
213 foreach ( $this->getCategoryLinksIterator( $dbr, array_keys( $pages ) ) as $row ) {
214 $this->categoriesRdf
->writeCategoryLinkData( $pages[$row->cl_from
], $row->cl_to
);
219 * Generate SPARQL Update code for updating dump timestamp
220 * @param string|int $timestamp Timestamp for last change
221 * @return string SPARQL Update query for timestamp.
223 public function updateTS( $timestamp ) {
224 $dumpUrl = '<' . $this->categoriesRdf
->getDumpURI() . '>';
225 $ts = wfTimestamp( TS_ISO_8601
, $timestamp );
228 $dumpUrl schema:dateModified ?o .
231 $dumpUrl schema:dateModified ?o .
234 $dumpUrl schema:dateModified "$ts"^^xsd:dateTime .
242 * Set up standard iterator for retrieving category changes.
243 * @param IDatabase $dbr
244 * @param string[] $columns List of additional fields to get
245 * @param string[] $extra_tables List of additional tables to join
246 * @return BatchRowIterator
248 private function setupChangesIterator(
251 array $extra_tables = []
253 $tables = [ 'recentchanges', 'page_props', 'category' ];
254 if ( $extra_tables ) {
255 $tables = array_merge( $tables, $extra_tables );
257 $it = new BatchRowIterator( $dbr,
262 $this->addTimestampConditions( $it, $dbr );
263 $it->addJoinConditions(
266 'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = rc_cur_id' ]
269 'LEFT JOIN', [ 'cat_title = rc_title' ]
273 $it->setFetchColumns( array_merge( $columns, [
285 * Fetch newly created categories
286 * @param IDatabase $dbr
287 * @return BatchRowIterator
289 protected function getNewCatsIterator( IDatabase
$dbr ) {
290 $it = $this->setupChangesIterator( $dbr );
291 $it->addConditions( [
292 'rc_namespace' => NS_CATEGORY
,
299 * Fetch moved categories
300 * @param IDatabase $dbr
301 * @return BatchRowIterator
303 protected function getMovedCatsIterator( IDatabase
$dbr ) {
304 $it = $this->setupChangesIterator( $dbr, [ 'page_title', 'page_namespace' ], [ 'page' ] );
305 $it->addConditions( [
306 'rc_namespace' => NS_CATEGORY
,
308 'rc_log_type' => 'move',
311 $it->addJoinConditions( [
312 'page' => [ 'JOIN', 'rc_cur_id = page_id' ],
314 $this->addIndex( $it );
319 * Fetch deleted categories
320 * @param IDatabase $dbr
321 * @return BatchRowIterator
323 protected function getDeletedCatsIterator( IDatabase
$dbr ) {
324 $it = new BatchRowIterator( $dbr,
329 $this->addTimestampConditions( $it, $dbr );
330 $it->addConditions( [
331 'rc_namespace' => NS_CATEGORY
,
333 'rc_log_type' => 'delete',
334 'rc_log_action' => 'delete',
336 // We will fetch ones that do not have page record. If they do,
337 // this means they were restored, thus restoring handler will pick it up.
338 'NOT EXISTS (SELECT * FROM page WHERE page_id = rc_cur_id)',
340 $this->addIndex( $it );
341 $it->setFetchColumns( [ 'rc_cur_id', 'rc_title' ] );
346 * Fetch restored categories
347 * @param IDatabase $dbr
348 * @return BatchRowIterator
350 protected function getRestoredCatsIterator( IDatabase
$dbr ) {
351 $it = $this->setupChangesIterator( $dbr );
352 $it->addConditions( [
353 'rc_namespace' => NS_CATEGORY
,
355 'rc_log_type' => 'delete',
356 'rc_log_action' => 'restore',
358 // We will only fetch ones that have page record
359 'EXISTS (SELECT page_id FROM page WHERE page_id = rc_cur_id)',
361 $this->addIndex( $it );
366 * Fetch categorization changes or edits
367 * @param IDatabase $dbr
368 * @return BatchRowIterator
370 protected function getChangedCatsIterator( IDatabase
$dbr, $type ) {
372 $this->setupChangesIterator( $dbr );
373 $it->addConditions( [
374 'rc_namespace' => NS_CATEGORY
,
378 $this->addIndex( $it );
383 * Add timestamp limits to iterator
384 * @param BatchRowIterator $it Iterator
385 * @param IDatabase $dbr
387 private function addTimestampConditions( BatchRowIterator
$it, IDatabase
$dbr ) {
388 $it->addConditions( [
389 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $this->startTS
) ),
390 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $this->endTS
) ),
395 * Need to force index, somehow on terbium the optimizer chooses wrong one
396 * @param BatchRowIterator $it
398 private function addIndex( BatchRowIterator
$it ) {
400 'USE INDEX' => [ 'recentchanges' => 'new_name_timestamp' ]
405 * Get iterator for links for categories.
406 * @param IDatabase $dbr
407 * @param int[] $ids List of page IDs
408 * @return Traversable
410 protected function getCategoryLinksIterator( IDatabase
$dbr, array $ids ) {
411 $it = new BatchRowIterator(
414 [ 'cl_from', 'cl_to' ],
417 $it->addConditions( [
418 'cl_type' => 'subcat',
421 $it->setFetchColumns( [ 'cl_from', 'cl_to' ] );
422 return new RecursiveIteratorIterator( $it );
426 * Get accumulated RDF.
429 public function getRdf() {
430 return $this->rdfWriter
->drain();
434 * Handle category deletes.
435 * @param IDatabase $dbr
436 * @param resource $output File to write the output
438 public function handleDeletes( IDatabase
$dbr, $output ) {
439 // This only does "true" deletes - i.e. those that the page stays deleted
440 foreach ( $this->getDeletedCatsIterator( $dbr ) as $batch ) {
442 foreach ( $batch as $row ) {
443 // This can produce duplicates, we don't care
444 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
445 $this->processed
[$row->rc_cur_id
] = true;
447 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, [], "Deletes" ) );
452 * Write category data to RDF.
453 * @param stdclass $row Database row
455 private function writeCategoryData( $row ) {
456 $this->categoriesRdf
->writeCategoryData(
458 $row->pp_propname
=== 'hiddencat',
459 (int)$row->cat_pages
- (int)$row->cat_subcats
- (int)$row->cat_files
,
460 (int)$row->cat_subcats
465 * @param IDatabase $dbr
466 * @param resource $output
468 public function handleMoves( IDatabase
$dbr, $output ) {
469 foreach ( $this->getMovedCatsIterator( $dbr ) as $batch ) {
472 foreach ( $batch as $row ) {
473 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
475 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
476 // We already captured this one before
480 if ( $row->page_namespace
!= NS_CATEGORY
) {
481 // If page was moved out of Category:, we'll just delete
484 $row->rc_title
= $row->page_title
;
485 $this->writeCategoryData( $row );
486 $pages[$row->rc_cur_id
] = $row->page_title
;
487 $this->processed
[$row->rc_cur_id
] = true;
490 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Moves" ) );
495 * @param IDatabase $dbr
496 * @param resource $output
498 public function handleRestores( IDatabase
$dbr, $output ) {
499 fwrite( $output, "# Restores\n" );
500 // This will only find those restores that were not deleted later.
501 foreach ( $this->getRestoredCatsIterator( $dbr ) as $batch ) {
503 foreach ( $batch as $row ) {
504 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
505 // We already captured this one before
508 $this->writeCategoryData( $row );
509 $pages[$row->rc_cur_id
] = $row->rc_title
;
510 $this->processed
[$row->rc_cur_id
] = true;
513 if ( empty( $pages ) ) {
517 $this->writeParentCategories( $dbr, $pages );
519 fwrite( $output, $this->getInsertRdf() );
524 * @param IDatabase $dbr
525 * @param resource $output
527 public function handleAdds( IDatabase
$dbr, $output ) {
528 fwrite( $output, "# Additions\n" );
529 foreach ( $this->getNewCatsIterator( $dbr ) as $batch ) {
531 foreach ( $batch as $row ) {
532 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
533 // We already captured this one before
536 $this->writeCategoryData( $row );
537 $pages[$row->rc_cur_id
] = $row->rc_title
;
538 $this->processed
[$row->rc_cur_id
] = true;
541 if ( empty( $pages ) ) {
545 $this->writeParentCategories( $dbr, $pages );
546 fwrite( $output, $this->getInsertRdf() );
551 * Handle edits for category texts
552 * @param IDatabase $dbr
553 * @param resource $output
555 public function handleEdits( IDatabase
$dbr, $output ) {
556 // Editing category can change hidden flag and add new parents.
557 // TODO: it's pretty expensive to update all edited categories, and most edits
558 // aren't actually interesting for us. Some way to know which are interesting?
559 // We can capture recategorization on the next step, but not change in hidden status.
560 foreach ( $this->getChangedCatsIterator( $dbr, RC_EDIT
) as $batch ) {
563 foreach ( $batch as $row ) {
564 // Note that on categorization event, cur_id points to
565 // the child page, not the parent category!
566 if ( isset( $this->processed
[$row->rc_cur_id
] ) ) {
567 // We already captured this one before
570 $this->writeCategoryData( $row );
571 $pages[$row->rc_cur_id
] = $row->rc_title
;
572 $this->processed
[$row->rc_cur_id
] = true;
573 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
576 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Edits" ) );
581 * Handles categorization changes
582 * @param IDatabase $dbr
583 * @param resource $output
585 public function handleCategorization( IDatabase
$dbr, $output ) {
586 $processedTitle = [];
587 // Categorization change can add new parents and change counts
588 // for the parent category.
589 foreach ( $this->getChangedCatsIterator( $dbr, RC_CATEGORIZE
) as $batch ) {
591 * Note that on categorization event, cur_id points to
592 * the child page, not the parent category!
593 * So we need to have a two-stage process, since we have ID from one
594 * category and title from another, and we need both for proper updates.
595 * TODO: For now, we do full update even though some data hasn't changed,
596 * e.g. parents for parent cat and counts for child cat.
600 foreach ( $batch as $row ) {
601 $childPages[$row->rc_cur_id
] = true;
602 $parentCats[$row->rc_title
] = true;
608 [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ],
612 [ 'cat_title = page_title' ],
620 // Load child rows by ID
621 $childRows = $dbr->select(
622 [ 'page', 'page_props', 'category' ],
625 'rc_title' => 'page_title',
631 [ 'page_namespace' => NS_CATEGORY
, 'page_id' => array_keys( $childPages ) ],
636 foreach ( $childRows as $row ) {
637 if ( isset( $this->processed
[$row->page_id
] ) ) {
638 // We already captured this one before
641 $this->writeCategoryData( $row );
642 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
643 $this->processed
[$row->page_id
] = true;
648 // Load parent rows by title
652 [ 'page_title = cat_title', 'page_namespace' => NS_CATEGORY
],
656 [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ],
660 $parentRows = $dbr->select(
661 [ 'category', 'page', 'page_props' ],
664 'rc_title' => 'cat_title',
670 [ 'cat_title' => array_keys( $parentCats ) ],
675 foreach ( $parentRows as $row ) {
676 if ( $row->page_id
&& isset( $this->processed
[$row->page_id
] ) ) {
677 // We already captured this one before
680 if ( isset( $processedTitle[$row->rc_title
] ) ) {
681 // We already captured this one before
684 $this->writeCategoryData( $row );
685 $deleteUrls[] = '<' . $this->categoriesRdf
->labelToUrl( $row->rc_title
) . '>';
686 if ( $row->page_id
) {
687 $this->processed
[$row->page_id
] = true;
689 $processedTitle[$row->rc_title
] = true;
693 fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Changes" ) );
698 $maintClass = CategoryChangesAsRdf
::class;
699 require_once RUN_MAINTENANCE_IF_MAIN
;