User:CommanderC/book-fix.pl

From CrawlWiki
Jump to: navigation, search

#!/usr/bin/perl

# Set the pause in seconds after each upload
my $pause = 1;

# List the wiki PHP scripts where you have the username/password pair
my $api_url = 'http://crawl.chaosforge.org/api.php';
my $upload_url = 'http://crawl.chaosforge.org/Special:Upload';

use strict;
use warnings;
use MediaWiki::API;
use File::Spec;
use IO::Dir;
use IO::Prompt;

my $username = prompt('Username:');
my $password = prompt('Password:', -e => '*');

my $mw = MediaWiki::API->new( {
    api_url => $api_url,
    upload_url => $upload_url,
    on_error => \&on_error
  } );

sub filter_articles {
    my $articles = shift;
    my @reject1 = ('Spell book', 'Starting books');
    my $r = [];

    foreach (@{$articles}) {
        my $title = $_->{title};
        if (contains($title, \@reject1)) {next;}
        if (substr($title, 0, 8) eq 'Category') {next;}
        push @$r, $_;
    }
    return $r;
}

sub handle_text {
    my $text = shift;
    $text =~ s/{{item\n/{{item-noicon\n/m;
    return $text; 
}

sub handle_article {
    my $article = shift;
    my $pagename = $article->{title};
    my $ref = $mw->get_page( { title => $pagename } );
    unless ( $ref->{missing} ) {
        my $text = $ref->{'*'};
        my $new_text = handle_text($text);
        my $timestamp = $ref->{timestamp};
        $mw->edit( {
          action => 'edit',
          title => $pagename,
          basetimestamp => $timestamp, # to avoid edit conflicts
          text => $new_text } )
    }
}

sub contains {
    my ($el, $arr) = @_;
    for (@$arr) {
        if ($el eq $_) {return 1;}
    }
    return 0;
}

sub on_error {
  print "Error code: " . $mw->{error}->{code} . "\n";
  print $mw->{error}->{stacktrace}."\n";
  die;
}

my $r = $mw->login( { lgname => $username, lgpassword => $password } );
die unless defined($r);

my $articles = $mw->list ( {
    action => 'query',
    list => 'categorymembers',
    cmtitle => 'Category:Book',
    cmlimit => 'max' } );


my $filtered_articles = filter_articles($articles);

for (sort(@$articles)) {
        #sleep $pause;
        handle_article($_);
}

$mw->logout();