/
deleteBrokenRedirects.php
58 lines (50 loc) · 1.61 KB
/
deleteBrokenRedirects.php
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
<?php
/**
* Delete broken redirects
*/
$IP = getenv( 'MW_INSTALL_PATH' );
if ( $IP === false ) {
$IP = __DIR__ . '/../../..';
}
require_once "$IP/maintenance/Maintenance.php";
use MediaWiki\MediaWikiServices;
class DeleteBrokenRedirects extends Maintenance {
public function __construct() {
parent::__construct();
$this->addDescription( 'Delete broken redirects' );
$this->addOption( 'delete', 'Actually do the deletions' );
}
public function execute() {
// Get all the redirects
$lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
$dbr = $lb->getConnectionRef( DB_REPLICA );
$results = $dbr->newSelectQueryBuilder()
->select( [ 'rd_from', 'rd_namespace', 'rd_title' ] )
->from( 'redirect' )
->where( [
'rd_namespace > -1', // Exclude special pages
'rd_interwiki IS NULL OR rd_interwiki = ""', // Exclude interwiki links
] )
->fetchResultSet();
// Delete the ones that point to a page that doesn't exist
$delete = $this->getOption( 'delete' );
$user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
foreach ( $results as $result ) {
$target = Title::newFromText( $result->rd_title, $result->rd_namespace );
if ( $target->exists() ) {
continue;
}
$title = Title::newFromID( $result->rd_from );
$url = $title->getFullUrl();
$this->output( $url );
if ( $delete ) {
$page = WikiPage::factory( $title );
$page->doDeleteArticleReal( 'Broken redirect', $user );
$this->output( ' .. deleted!' );
}
$this->output( PHP_EOL );
}
}
}
$maintClass = DeleteBrokenRedirects::class;
require_once RUN_MAINTENANCE_IF_MAIN;