1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
|
<?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
use MediaWiki\Category\CategoriesRdf;
use MediaWiki\MainConfigNames;
use MediaWiki\Maintenance\Maintenance;
use MediaWiki\Utils\MWTimestamp;
use Wikimedia\Purtle\RdfWriter;
use Wikimedia\Purtle\TurtleRdfWriter;
use Wikimedia\Rdbms\IReadableDatabase;
// @codeCoverageIgnoreStart
require_once __DIR__ . '/Maintenance.php';
// @codeCoverageIgnoreEnd
/**
* Maintenance script to provide RDF representation of the recent changes in category tree.
*
* @ingroup Maintenance
* @since 1.30
*/
class CategoryChangesAsRdf extends Maintenance {
/**
* Insert query
*/
private const SPARQL_INSERT = <<<SPARQL
INSERT DATA {
%s
};
SPARQL;
/**
* Delete query
*/
private const SPARQL_DELETE = <<<SPARQLD
DELETE {
?category ?x ?y
} WHERE {
?category ?x ?y
VALUES ?category {
%s
}
};
SPARQLD;
/**
* @var RdfWriter
*/
private $rdfWriter;
/**
* Categories RDF helper.
* @var CategoriesRdf
*/
private $categoriesRdf;
/** @var string */
private $startTS;
/** @var string */
private $endTS;
/**
* List of processed page IDs,
* so we don't try to process same thing twice
* @var true[]
*/
protected $processed = [];
public function __construct() {
parent::__construct();
$this->addDescription( "Generate RDF dump of category changes in a wiki." );
$this->setBatchSize( 200 );
$this->addOption( 'output', "Output file (default is stdout). Will be overwritten.", false,
true, 'o' );
$this->addOption( 'start', 'Starting timestamp (inclusive), in ISO or MediaWiki format.',
true, true, 's' );
$this->addOption( 'end', 'Ending timestamp (exclusive), in ISO or MediaWiki format.', true,
true, 'e' );
}
/**
* Initialize external service classes.
*/
public function initialize() {
// SPARQL Update syntax is close to Turtle format, so we can use Turtle writer.
$this->rdfWriter = new TurtleRdfWriter();
$this->categoriesRdf = new CategoriesRdf( $this->rdfWriter );
}
public function execute() {
$this->initialize();
$startTS = new MWTimestamp( $this->getOption( "start" ) );
$endTS = new MWTimestamp( $this->getOption( "end" ) );
$now = new MWTimestamp();
$rcMaxAge = $this->getConfig()->get( MainConfigNames::RCMaxAge );
if ( (int)$now->getTimestamp( TS_UNIX ) - (int)$startTS->getTimestamp( TS_UNIX ) > $rcMaxAge ) {
$this->error( "Start timestamp too old, maximum RC age is $rcMaxAge!" );
}
if ( (int)$now->getTimestamp( TS_UNIX ) - (int)$endTS->getTimestamp( TS_UNIX ) > $rcMaxAge ) {
$this->error( "End timestamp too old, maximum RC age is $rcMaxAge!" );
}
$this->startTS = $startTS->getTimestamp();
$this->endTS = $endTS->getTimestamp();
$outFile = $this->getOption( 'output', 'php://stdout' );
if ( $outFile === '-' ) {
$outFile = 'php://stdout';
}
$output = fopen( $outFile, 'wb' );
$this->categoriesRdf->setupPrefixes();
$this->rdfWriter->start();
$prefixes = $this->getRdf();
// We have to strip @ from prefix, since SPARQL UPDATE doesn't use them
// Also strip dot at the end.
$prefixes = preg_replace( [ '/^@/m', '/\s*[.]$/m' ], '', $prefixes );
fwrite( $output, $prefixes );
$dbr = $this->getDB( DB_REPLICA, [ 'vslow' ] );
// Deletes go first because if the page was deleted, other changes
// do not matter. This only gets true deletes, i.e. not pages that were restored.
$this->handleDeletes( $dbr, $output );
// Moves go before additions because if category is moved, we should not process creation
// as it would produce wrong data - because create row has old title
$this->handleMoves( $dbr, $output );
// We need to handle restores too since delete may have happened in previous update.
$this->handleRestores( $dbr, $output );
// Process newly added pages
$this->handleAdds( $dbr, $output );
// Process page edits
$this->handleEdits( $dbr, $output );
// Process categorization changes
$this->handleCategorization( $dbr, $output );
// Update timestamp
fwrite( $output, $this->updateTS( $this->endTS ) );
}
/**
* Get the text of SPARQL INSERT DATA clause
* @return string
*/
private function getInsertRdf() {
$rdfText = $this->getRdf();
if ( !$rdfText ) {
return "";
}
return sprintf( self::SPARQL_INSERT, $rdfText );
}
/**
* Get SPARQL for updating set of categories
* @param IReadableDatabase $dbr
* @param string[] $deleteUrls List of URIs to be deleted, with <>
* @param string[] $pages List of categories: id => title
* @param string $mark Marks which operation requests the query
* @return string SPARQL query
*/
private function getCategoriesUpdate( IReadableDatabase $dbr, $deleteUrls, $pages, $mark ) {
if ( !$deleteUrls ) {
return "";
}
if ( $pages ) {
$this->writeParentCategories( $dbr, $pages );
}
return "# $mark\n" . sprintf( self::SPARQL_DELETE, implode( ' ', $deleteUrls ) ) .
$this->getInsertRdf();
}
/**
* Write parent data for a set of categories.
* The list has the child categories.
* @param IReadableDatabase $dbr
* @param string[] $pages List of child categories: id => title
*/
private function writeParentCategories( IReadableDatabase $dbr, $pages ) {
foreach ( $this->getCategoryLinksIterator( $dbr, array_keys( $pages ), __METHOD__ ) as $row ) {
$this->categoriesRdf->writeCategoryLinkData( $pages[$row->cl_from], $row->cl_to );
}
}
/**
* Generate SPARQL Update code for updating dump timestamp
* @param string|int $timestamp Timestamp for last change
* @return string SPARQL Update query for timestamp.
*/
public function updateTS( $timestamp ) {
$dumpUrl = '<' . $this->categoriesRdf->getDumpURI() . '>';
$ts = wfTimestamp( TS_ISO_8601, $timestamp );
$tsQuery = <<<SPARQL
DELETE {
$dumpUrl schema:dateModified ?o .
}
WHERE {
$dumpUrl schema:dateModified ?o .
};
INSERT DATA {
$dumpUrl schema:dateModified "$ts"^^xsd:dateTime .
}
SPARQL;
return $tsQuery;
}
/**
* Set up standard iterator for retrieving category changes.
* @param IReadableDatabase $dbr
* @param string[] $columns List of additional fields to get
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
private function setupChangesIterator(
IReadableDatabase $dbr,
array $columns,
string $fname
) {
$it = new BatchRowIterator( $dbr,
$dbr->newSelectQueryBuilder()
->from( 'recentchanges' )
->leftJoin( 'page_props', null, [ 'pp_propname' => 'hiddencat', 'pp_page = rc_cur_id' ] )
->leftJoin( 'category', null, [ 'cat_title = rc_title' ] )
->select( array_merge( $columns, [
'rc_title',
'rc_cur_id',
'pp_propname',
'cat_pages',
'cat_subcats',
'cat_files'
] ) )
->caller( $fname ),
[ 'rc_timestamp' ],
$this->mBatchSize
);
$this->addTimestampConditions( $it, $dbr );
return $it;
}
/**
* Fetch newly created categories
* @param IReadableDatabase $dbr
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
protected function getNewCatsIterator( IReadableDatabase $dbr, $fname ) {
$it = $this->setupChangesIterator( $dbr, [], $fname );
$it->sqb->conds( [
'rc_namespace' => NS_CATEGORY,
'rc_new' => 1,
] );
return $it;
}
/**
* Fetch moved categories
* @param IReadableDatabase $dbr
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
protected function getMovedCatsIterator( IReadableDatabase $dbr, $fname ) {
$it = $this->setupChangesIterator(
$dbr,
[ 'page_title', 'page_namespace' ],
$fname
);
$it->sqb->conds( [
'rc_namespace' => NS_CATEGORY,
'rc_new' => 0,
'rc_log_type' => 'move',
'rc_type' => RC_LOG,
] );
$it->sqb->join( 'page', null, 'rc_cur_id = page_id' );
$this->addIndex( $it );
return $it;
}
/**
* Fetch deleted categories
* @param IReadableDatabase $dbr
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
protected function getDeletedCatsIterator( IReadableDatabase $dbr, $fname ) {
$it = new BatchRowIterator( $dbr,
$dbr->newSelectQueryBuilder()
->from( 'recentchanges' )
->select( [ 'rc_cur_id', 'rc_title' ] )
->where( [
'rc_namespace' => NS_CATEGORY,
'rc_new' => 0,
'rc_log_type' => 'delete',
'rc_log_action' => 'delete',
'rc_type' => RC_LOG,
// We will fetch ones that do not have page record. If they do,
// this means they were restored, thus restoring handler will pick it up.
'NOT EXISTS (SELECT * FROM page WHERE page_id = rc_cur_id)',
] )
->caller( $fname ),
[ 'rc_timestamp' ],
$this->mBatchSize
);
$this->addTimestampConditions( $it, $dbr );
$this->addIndex( $it );
return $it;
}
/**
* Fetch restored categories
* @param IReadableDatabase $dbr
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
protected function getRestoredCatsIterator( IReadableDatabase $dbr, $fname ) {
$it = $this->setupChangesIterator( $dbr, [], $fname );
$it->sqb->conds( [
'rc_namespace' => NS_CATEGORY,
'rc_new' => 0,
'rc_log_type' => 'delete',
'rc_log_action' => 'restore',
'rc_type' => RC_LOG,
// We will only fetch ones that have page record
'EXISTS (SELECT page_id FROM page WHERE page_id = rc_cur_id)',
] );
$this->addIndex( $it );
return $it;
}
/**
* Fetch categorization changes or edits
* @param IReadableDatabase $dbr
* @param int $type
* @param string $fname Name of the calling function
* @return BatchRowIterator
*/
protected function getChangedCatsIterator( IReadableDatabase $dbr, $type, $fname ) {
$it = $this->setupChangesIterator( $dbr, [], $fname );
$it->sqb->conds( [
'rc_namespace' => NS_CATEGORY,
'rc_new' => 0,
'rc_type' => $type,
] );
$this->addIndex( $it );
return $it;
}
/**
* Add timestamp limits to iterator
* @param BatchRowIterator $it Iterator
* @param IReadableDatabase $dbr
*/
private function addTimestampConditions( BatchRowIterator $it, IReadableDatabase $dbr ) {
$it->sqb->conds( [
$dbr->expr( 'rc_timestamp', '>=', $dbr->timestamp( $this->startTS ) ),
$dbr->expr( 'rc_timestamp', '<', $dbr->timestamp( $this->endTS ) ),
] );
}
/**
* Need to force index, somehow on terbium the optimizer chooses wrong one
*/
private function addIndex( BatchRowIterator $it ) {
$it->sqb->options( [
'USE INDEX' => [ 'recentchanges' => 'rc_new_name_timestamp' ]
] );
}
/**
* Get iterator for links for categories.
* @param IReadableDatabase $dbr
* @param int[] $ids List of page IDs
* @param string $fname Name of the calling function
* @return Traversable
*/
protected function getCategoryLinksIterator( IReadableDatabase $dbr, array $ids, $fname ) {
$it = new BatchRowIterator(
$dbr,
$dbr->newSelectQueryBuilder()
->from( 'categorylinks' )
->select( [ 'cl_from', 'cl_to' ] )
->where( [
'cl_type' => 'subcat',
'cl_from' => $ids
] )
->caller( $fname ),
[ 'cl_from', 'cl_to' ],
$this->mBatchSize
);
return new RecursiveIteratorIterator( $it );
}
/**
* Get accumulated RDF.
* @return string
*/
public function getRdf() {
return $this->rdfWriter->drain();
}
/**
* Handle category deletes.
* @param IReadableDatabase $dbr
* @param resource $output File to write the output
*/
public function handleDeletes( IReadableDatabase $dbr, $output ) {
// This only does "true" deletes - i.e. those that the page stays deleted
foreach ( $this->getDeletedCatsIterator( $dbr, __METHOD__ ) as $batch ) {
$deleteUrls = [];
foreach ( $batch as $row ) {
// This can produce duplicates, we don't care
$deleteUrls[] = '<' . $this->categoriesRdf->labelToUrl( $row->rc_title ) . '>';
$this->processed[$row->rc_cur_id] = true;
}
fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, [], "Deletes" ) );
}
}
/**
* Write category data to RDF.
* @param stdclass $row Database row
*/
private function writeCategoryData( $row ) {
$this->categoriesRdf->writeCategoryData(
$row->rc_title,
$row->pp_propname === 'hiddencat',
(int)$row->cat_pages - (int)$row->cat_subcats - (int)$row->cat_files,
(int)$row->cat_subcats
);
}
/**
* @param IReadableDatabase $dbr
* @param resource $output
*/
public function handleMoves( IReadableDatabase $dbr, $output ) {
foreach ( $this->getMovedCatsIterator( $dbr, __METHOD__ ) as $batch ) {
$pages = [];
$deleteUrls = [];
foreach ( $batch as $row ) {
$deleteUrls[] = '<' . $this->categoriesRdf->labelToUrl( $row->rc_title ) . '>';
if ( isset( $this->processed[$row->rc_cur_id] ) ) {
// We already captured this one before
continue;
}
if ( $row->page_namespace != NS_CATEGORY ) {
// If page was moved out of Category:, we'll just delete
continue;
}
$row->rc_title = $row->page_title;
$this->writeCategoryData( $row );
$pages[$row->rc_cur_id] = $row->page_title;
$this->processed[$row->rc_cur_id] = true;
}
fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Moves" ) );
}
}
/**
* @param IReadableDatabase $dbr
* @param resource $output
*/
public function handleRestores( IReadableDatabase $dbr, $output ) {
fwrite( $output, "# Restores\n" );
// This will only find those restores that were not deleted later.
foreach ( $this->getRestoredCatsIterator( $dbr, __METHOD__ ) as $batch ) {
$pages = [];
foreach ( $batch as $row ) {
if ( isset( $this->processed[$row->rc_cur_id] ) ) {
// We already captured this one before
continue;
}
$this->writeCategoryData( $row );
$pages[$row->rc_cur_id] = $row->rc_title;
$this->processed[$row->rc_cur_id] = true;
}
if ( !$pages ) {
continue;
}
$this->writeParentCategories( $dbr, $pages );
fwrite( $output, $this->getInsertRdf() );
}
}
/**
* @param IReadableDatabase $dbr
* @param resource $output
*/
public function handleAdds( IReadableDatabase $dbr, $output ) {
fwrite( $output, "# Additions\n" );
foreach ( $this->getNewCatsIterator( $dbr, __METHOD__ ) as $batch ) {
$pages = [];
foreach ( $batch as $row ) {
if ( isset( $this->processed[$row->rc_cur_id] ) ) {
// We already captured this one before
continue;
}
$this->writeCategoryData( $row );
$pages[$row->rc_cur_id] = $row->rc_title;
$this->processed[$row->rc_cur_id] = true;
}
if ( !$pages ) {
continue;
}
$this->writeParentCategories( $dbr, $pages );
fwrite( $output, $this->getInsertRdf() );
}
}
/**
* Handle edits for category texts
* @param IReadableDatabase $dbr
* @param resource $output
*/
public function handleEdits( IReadableDatabase $dbr, $output ) {
// Editing category can change hidden flag and add new parents.
// TODO: it's pretty expensive to update all edited categories, and most edits
// aren't actually interesting for us. Some way to know which are interesting?
// We can capture recategorization on the next step, but not change in hidden status.
foreach ( $this->getChangedCatsIterator( $dbr, RC_EDIT, __METHOD__ ) as $batch ) {
$pages = [];
$deleteUrls = [];
foreach ( $batch as $row ) {
// Note that on categorization event, cur_id points to
// the child page, not the parent category!
if ( isset( $this->processed[$row->rc_cur_id] ) ) {
// We already captured this one before
continue;
}
$this->writeCategoryData( $row );
$pages[$row->rc_cur_id] = $row->rc_title;
$this->processed[$row->rc_cur_id] = true;
$deleteUrls[] = '<' . $this->categoriesRdf->labelToUrl( $row->rc_title ) . '>';
}
fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Edits" ) );
}
}
/**
* Handles categorization changes
* @param IReadableDatabase $dbr
* @param resource $output
*/
public function handleCategorization( IReadableDatabase $dbr, $output ) {
$processedTitle = [];
// Categorization change can add new parents and change counts
// for the parent category.
foreach ( $this->getChangedCatsIterator( $dbr, RC_CATEGORIZE, __METHOD__ ) as $batch ) {
/*
* Note that on categorization event, cur_id points to
* the child page, not the parent category!
* So we need to have a two-stage process, since we have ID from one
* category and title from another, and we need both for proper updates.
* TODO: For now, we do full update even though some data hasn't changed,
* e.g. parents for parent cat and counts for child cat.
*/
$childPages = [];
$parentCats = [];
foreach ( $batch as $row ) {
$childPages[$row->rc_cur_id] = true;
$parentCats[$row->rc_title] = true;
}
$pages = [];
$deleteUrls = [];
if ( $childPages ) {
// Load child rows by ID
$childRows = $dbr->newSelectQueryBuilder()
->select( [
'page_id',
'rc_title' => 'page_title',
'pp_propname',
'cat_pages',
'cat_subcats',
'cat_files',
] )
->from( 'page' )
->leftJoin( 'page_props', null, [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ] )
->leftJoin( 'category', null, [ 'cat_title = page_title' ] )
->where( [ 'page_namespace' => NS_CATEGORY, 'page_id' => array_keys( $childPages ) ] )
->caller( __METHOD__ )->fetchResultSet();
foreach ( $childRows as $row ) {
if ( isset( $this->processed[$row->page_id] ) ) {
// We already captured this one before
continue;
}
$this->writeCategoryData( $row );
if ( $row->page_id ) {
$pages[$row->page_id] = $row->rc_title;
$deleteUrls[] = '<' . $this->categoriesRdf->labelToUrl( $row->rc_title ) . '>';
$this->processed[$row->page_id] = true;
}
}
}
if ( $parentCats ) {
// Load parent rows by title
$parentRows = $dbr->newSelectQueryBuilder()
->select( [
'page_id',
'rc_title' => 'cat_title',
'pp_propname',
'cat_pages',
'cat_subcats',
'cat_files',
] )
->from( 'category' )
->leftJoin( 'page', null, [ 'page_title = cat_title', 'page_namespace' => NS_CATEGORY ] )
->leftJoin( 'page_props', null, [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ] )
->where( [ 'cat_title' => array_map( 'strval', array_keys( $parentCats ) ) ] )
->caller( __METHOD__ )->fetchResultSet();
foreach ( $parentRows as $row ) {
if ( $row->page_id && isset( $this->processed[$row->page_id] ) ) {
// We already captured this one before
continue;
}
if ( isset( $processedTitle[$row->rc_title] ) ) {
// We already captured this one before
continue;
}
$this->writeCategoryData( $row );
if ( $row->page_id ) {
$pages[$row->page_id] = $row->rc_title;
$deleteUrls[] = '<' . $this->categoriesRdf->labelToUrl( $row->rc_title ) . '>';
$this->processed[$row->page_id] = true;
}
$processedTitle[$row->rc_title] = true;
}
}
fwrite( $output, $this->getCategoriesUpdate( $dbr, $deleteUrls, $pages, "Changes" ) );
}
}
}
// @codeCoverageIgnoreStart
$maintClass = CategoryChangesAsRdf::class;
require_once RUN_MAINTENANCE_IF_MAIN;
// @codeCoverageIgnoreEnd
|