User:AnomieBOT/source/tasks/TemplateReplacer6.pm

package tasks::TemplateReplacer6;

=pod

=for warning
Due to breaking changes in AnomieBOT::API, this task will probably not run
anymore. If you really must run it, try getting a version from before
2009-03-23.

=begin metadata

Bot:     AnomieBOT
Task:    TemplateReplacer6
BRFA:    Wikipedia:Bots/Requests for approval/AnomieBOT 12
Status:  Completed 2008-12-02
Created: 2008-11-18

Convert {{tl|Infobox Aircraft}} in article space to the new
{{tl|Infobox Aircraft Begin}}{{tl|Infobox Aircraft Type}} system.

=end metadata

=cut

use utf8;
use strict;

use AnomieBOT::Task;
use vars qw/@ISA/;
@ISA=qw/AnomieBOT::Task/;

my @begin_params=(
    'name',
    'image',
    'caption',
    'long caption',
    'logo',
);
my @type_params=(
    'type',
    'national origin',
    'manufacturer',
    'manufacturers',
    'designer',
    'first flight',
    'introduction',
    'introduced',
    'retired',
    'status',
    'primary user',
    'more users',
    'produced',
    'number built',
    'program cost',
    'unit cost',
    'developed from',
    'variants with their own articles',
);
my $req="[[Wikipedia:Bot requests#Template substitution|request]]";

sub new {
    my $class=shift;
    my $self=$class->SUPER::new();
    bless $self, $class;
    return $self;
}

=pod

=for info
Approved 2008-12-01, Completed 2008-12-02.<br />[[Wikipedia:Bots/Requests for approval/AnomieBOT 12]]

=cut

sub approved {
    return -1;
}

sub run {
    my ($self, $api)=@_;
    my $res;

    $api->task('TemplateReplacer6');
    $api->read_throttle(0);
    $api->edit_throttle(10);

    # List of templates to replace in this task
    my @templates=('Infobox Aircraft');

    # Spend a max of 5 minutes on this task before restarting
    my $endtime=time()+300;

    # Get a list of templates redirecting to our targets
    my %templates=();
    foreach my $template (@templates){
        $templates{"Template:$template"}=1;
        $res=$api->query([],
            list          => 'backlinks',
            bltitle       => "Template:$template",
            blfilterredir => 'redirects',
            bllimit       => 'max',
        );
        $templates{$_->{'title'}}=1 foreach (@{$res->{'query'}{'backlinks'}});
    }

    foreach my $template (@templates){
        # Get the list of pages to check
        my %q=(
            list        => 'embeddedin',
            eititle     => "Template:$template",
            einamespace => 0,
            eilimit     => 'max',
        );
        do {
            $res=$api->query(%q);
            if($res->{'code'} ne 'success'){
                $self->warn("Failed to retrieve transclusion list for $template: ".$res->{'error'}."\n");
                return 60;
            }
            if(exists($res->{'query-continue'})){
                $q{'eicontinue'}=$res->{'query-continue'}{'embeddedin'}{'eicontinue'};
            } else {
                delete $q{'eicontinue'};
            }

            # Process found pages
            foreach (@{$res->{'query'}{'embeddedin'}}){
                my $title=$_->{'title'};
                $self->warn("Checking for $template in $title\n");

                # WTF?
                if(exists($_->{'missing'})){
                    $self->warn("$title is missing? WTF?\n");
                    next;
                }

                # Ok, check the page
                my $tok=$api->edittoken($title);
                if($tok->{'code'} eq 'shutoff'){
                    $self->warn("Task disabled: ".$tok->{'content'}."\n");
                    return 300;
                }
                if($tok->{'code'} ne 'success'){
                    $self->warn("Failed to get edit token for $title: ".$tok->{'error'}."\n");
                    next;
                }
                next if exists($tok->{'missing'});

                # Get page text
                my $intxt=$tok->{'revisions'}[0]{'*'};
                my ($outtxt,$nowiki)=$self->strip_nowiki($intxt);

                # Now, we actually perform the replacement
                my $summary="Replacing {{$template}} with {{Infobox Aircraft Begin}}{{Infobox Aircraft Type}} per $req";
                $outtxt=$self->process_templates($outtxt, sub {
                    my $name=shift;
                    my @params=@{shift()};
                    shift; # $wikitext
                    shift; # $data
                    my $oname=shift;

                    return undef unless exists($templates{"Template:$name"});
                    my $k;
                    ($k=$oname)=~s/\Q$name\E/Infobox Aircraft Begin/i;
                    my @begin=($k);
                    ($k=$oname)=~s/\Q$name\E/Infobox Aircraft Type/i;
                    my @type=($k);
                    foreach (@params){
                        $k=$_;
                        next unless $k=~s/=.*//s;
                        $k=~s/^\s+|\s+$//g;
                        next if $k eq '';
                        push @begin, $_ if grep { $_ eq $k } @begin_params;
                        push @type, $_ if grep { $_ eq $k } @type_params;
                    }
                    my $out="{|";
                    $out.="{{".join('|', @begin)."}}";
                    $out.="{{".join('|', @type)."}}";
                    $out.="\n|}";

                    $out=~s/\n\s+}}/\n}}/g;

                    # Ok, return the new template code now.
                    return $out;
                });
                $outtxt=~s/(?:^|(?<!\n))\Q{|{{\E\s*Infobox Aircraft Begin/\n{|{{Infobox Aircraft Begin/;
                $outtxt=$self->replace_nowiki($outtxt, $nowiki);

                # Need to edit?
                if($outtxt ne $intxt){
                    $self->warn("$summary in $title\n");
                    my $r=$api->edit($tok, $outtxt, $summary, 1, 1);
                    if($r->{'code'} ne 'success'){
                        $self->warn("Write failed on $title: ".$r->{'error'}."\n");
                        next;
                    }
                } else {
                    $self->warn("Nothing to do in $title\n");
                }

                # If we've been at it long enough, let another task have a go.
                return 0 if time()>=$endtime;
            }
        } while(exists($q{'eicontinue'}));
    }

    # No more pages to check, try again in 10 minutes or so in case of errors.
    return 600;
}

1;