User:AnomieBOT/source/tasks/IFDCloser.pm

package tasks::IFDCloser;

=pod

=begin metadata

Bot:     AnomieBOT
Task:    IFDCloser
BRFA:    Wikipedia:Bots/Requests for approval/AnomieBOT 11
Status:  Approved 2008-12-01
+BRFA:   Wikipedia:Bots/Requests for approval/AnomieBOT 67
+Status: Approved 2012-08-29
Created: 2008-11-16

Peform the following tasks at [[WP:FFD]]:
* Create the daily FFD subpage.
* Fix the headers on the daily PUF subpages, if they get removed or damaged.
* [[Wikipedia:Deletion process#FFD|Close]] nominations where the file has been deleted.
* Close nominations where the file does not exist.
* Close nominations where the file is on Commons.
* Subst {{tl|ffd top}} and {{tl|ffd bottom}}, when editing the page anyway.
* Maintain the page [[Wikipedia:Files for discussion/Old unclosed discussions]].

=end metadata

=cut

use utf8;
use strict;

use AnomieBOT::Task qw/:time/;
use URI::Escape;
use Data::Dumper;
use vars qw/@ISA/;
@ISA=qw/AnomieBOT::Task/;

my @months=('','January','February','March','April','May','June','July','August','September','October','November','December');
my $is_closed_re=qr(<div class="[^"]*(?<=[" ])xfd-closed[ "]);

my %db=(
    nonsense       => 'G1',
    test           => 'G2',
    vandalism      => 'G3',
    pagemove       => 'G3',
    hoax           => 'G3',
    repost         => 'G4',
    banned         => 'G5',
    histmerge      => 'G6',
    move           => 'G6',
    copypaste      => 'G6',
    xfd            => 'G6',
    maintenance    => 'G6',
    house          => 'G6',
    disambig       => 'G6',
    movedab        => 'G6',
    unpatrolled    => 'G6',
    author         => 'G7',
    self           => 'G7',
    blanked        => 'G7',
    talk           => 'G8',
    subpage        => 'G8',
    imagepage      => 'G8',
    redirnone      => 'G8',
    templatecat    => 'G8',
    attack         => 'G10',
    blp            => 'G10',
    attackorg      => 'G10',
    spam           => 'G11',
    promo          => 'G11',
    copyvio        => 'G12',
    redundantfile  => 'F1',
    redundantimage => 'F1',
    nofile         => 'F2',
    noimage        => 'F2',
    noncom         => 'F3',
    unksource      => 'F4',
    unfree         => 'F5',
    norat          => 'F6',
    badfairuse     => 'F7',
    nowcommons     => 'F8',
    imgcopyvio     => 'F9',
    filecopyvio    => 'F9',
    badfiletype    => 'F10',
    nopermission   => 'F11',
);

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

=pod

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

=for info
First supplemental BFRA approved 2012-08-29<br />[[Wikipedia:Bots/Requests for approval/AnomieBOT 67]]

=cut

sub approved {
    return 2;
}

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

    $api->task('IFDCloser', 0, 10, qw/d::Talk d::Timestamp d::Redirects d::Sections/);

    my %p=$api->redirects_to_resolved('Template:Delrevxfd');
    if(exists($p{''})){
        if($p{''}{'code'} eq 'shutoff'){
            $api->warn("Task disabled: ".$p{''}{'content'}."\n");
            return 300;
        }
        $api->warn("Failed to get notice template redirects: ".$p{''}{'error'}."\n");
        return 60;
    }
    my @p=map { s/^Template://; my ($a,$b)=split(//,$_,2); "(?i:\Q$a\E)\Q$b\E"; } keys %p;
    my $p=join('|',@p);
    my $noticere=qr/(?:(?i:<noinclude>\s*)?\{\{\s*(?i:Template\s*:\s*)?(?:$p)\s*(?:\|.*?)?\}\}\s*(?i:<\/noinclude>\s*)?)/;

    my %tosubst=$api->redirects_to_resolved('Template:Ffd top', 'Template:Ffd bottom');
    if(exists($tosubst{''})){
        if($tosubst{''}{'code'} eq 'shutoff'){
            $api->warn("Task disabled: ".$tosubst{''}{'content'}."\n");
            return 300;
        }
        $api->warn("Failed to get top/bottom template redirects: ".$tosubst{''}{'error'}."\n");
        return 60;
    }

    # Only check once per hour, except make sure we run as soon after
    # 23:00 and 00:00 as possible.
    if($self->{'lasttime'}==0){
        if(exists($api->store->{'lasttime'})){
            my $t=$api->store->{'lasttime'};
            $self->{'lasttime'}=$t if($t=~/^\d+$/ && $t<=time());
        }
        $self->{'broken'}=$api->store->{'broken'} if(exists($api->store->{'broken'}));
    }
    my $starttime=time();
    my $t=$self->{'lasttime'}+($self->{'broken'}?300:3600);
    if(($self->{'lasttime'}%86400)<82800 && ($t%86400)>=82500){
        # Past or close enough to 23:00, set next run time to 23:00
        $t=$t+82800-($t%86400);
    } elsif(($t%86400)<($self->{'lasttime'}%86400)){
        # Past 00:00, set to 00:00
        $t=$t-($t%86400);
    } elsif(($t%86400)>=86100){
        # Close enough to 00:00, set to 00:00
        $t=$t+86400-($t%86400);
    }
    $t-=time();
    return $t if $t>0;

    my $startdate=[1,7,2017];
    $startdate=$api->store->{'startdate'} if exists($api->store->{'startdate'});

    my $screwup=' Errors? [[User:'.$api->user.'/shutoff/IFDCloser]]';

    # Get the content of all versions of "ifd top" since the startdate
    my $re='\{\{\s*[iIfF]fd[ _]?top\s*(?s:\|.*?)?\}\}';
    my %cont=();
    my $first=1;
    while($first || %cont) {
        my $t=$api->query(
            titles  => 'Template:ffd top',
            prop    => 'revisions',
            rvprop  => 'timestamp|content',
            rvslots => 'main',
            rvlimit => 1,
            %cont,
        );
        if($t->{'code'} ne 'success'){
            $api->warn("Failed to load revisions for Template:ffd top: ".$t->{'error'}."\n");
            return 60;
        }
        %cont=exists($t->{'query-continue'})?%{$t->{'query-continue'}{'revisions'}}:();
        $t=(values(%{$t->{'query'}{'pages'}}))[0]{'revisions'}[0];
        %cont=() if $t->{'timestamp'} lt sprintf("%04d-%02d-%02d", reverse @$startdate);
        $t=$t->{'slots'}{'main'}{'*'};
        $t=~s!<noinclude>.*</noinclude>!!gs;
        $t=~s!</?includeonly>!!g;
        $t=~s!\{\{\{1\|\}\}\}!\x07!g;
        unless($t =~ m/^\s*$is_closed_re/o){
            next unless $first;
            $api->whine("[[Template:Ffd top]] is broken", "Help! The template {{tl|ffd top}} is missing the \"is_closed\" regex, or this regex is not at the beginning of the template's output. To avoid confusion, I'm not going to process any FFDs until it's fixed or I'm fixed.");
            return 300;
        }
        if($t =~ m/\x07\s*$/){
            next unless $first;
            $api->whine("[[Template:Ffd top]] is broken", "Help! The template {{tl|ffd top}} does not end with some constant text, i.e. <nowiki>{{{1|}}}</nowiki> is at the very end of the template. To avoid confusion, I'm not going to process any FFDs until it's fixed or I'm fixed.");
            return 300;
        }
        if($t =~ m/\{\{\{/){
            next unless $first;
            $api->whine("[[Template:Ffd top]] is broken", "Help! The template {{tl|ffd top}} contains unknown parameters. To avoid confusion, I'm not going to process any FFDs until it's fixed or I'm fixed.");
            return 300;
        }
        $t=quotemeta($t);
        $t=~s/\\\x07/(?s:.*?)/g;
        $re.="|$t";
        $first=0;
    }

    # Add {{ffd top}} templates to 'is_closed' regex.
    my @tops = grep { $tosubst{$_} eq "Template:Ffd top" } keys %tosubst;
    map { s/^Template://; s/(\p{Pattern_Syntax})/\\$1/g; s/ /[ _]/g; s/^([IF])/(?i:$1)/; } @tops;
    my $tops = join( '|', @tops );
    $is_closed_re = qr(\{\{\s*(?:$tops)\s*[|}]|$is_closed_re);

    # Iterate over all our pages
    my $broken=0;
    my $new_start=_make_date();
    my $sevendays=_date_add(_make_date(),-7,0,0);
    my @old=();
    my @oldsumm=();
    MAINLOOP: for(my $date=_make_date(time+3600); _cmp_date($startdate,$date)<=0; $date=_date_add($date,-1,0,0)){
        return 0 if $api->halting;
        my $title;
        if ( _cmp_date([3,11,2015],$date)<0 ) {
            $title='Wikipedia:Files for discussion/'.$date->[2].' '.$months[$date->[1]].' '.$date->[0];
        } else {
            $title='Wikipedia:Files for deletion/'.$date->[2].' '.$months[$date->[1]].' '.$date->[0];
        }

        $api->log("Checking FFDs in $title");
        my $tok=$api->edittoken($title);
        if($tok->{'code'} eq 'shutoff'){
            $api->warn("Task disabled: ".$tok->{'content'}."\n");
            return 300;
        }
        if($tok->{'code'} ne 'success'){
            $api->warn("Failed to get edit token for $title: ".$tok->{'error'}."\n");
            return 60;
        }
        my $intxt=$tok->{'revisions'}[0]{'slots'}{'main'}{'*'} // '';
        my $outtxt=$intxt;

        # Fix header if necessary
        my $fixedhead=0;
        my ($pageheader,$err)=_makepagehead($api,$title,$date);
        if ( ! defined( $pageheader ) ) {
            $api->warn("Failed to get page header for $title: $err\n");
            return 60;
        }
        if($outtxt!~/^\Q$pageheader\E/){
            my $dt=$months[$date->[1]].' '.$date->[0];
            my $oldtxt;
            do {
                $oldtxt=$outtxt;
                $outtxt=~s/^(?:|.*?\n)===\s*\Q$dt\E\s*===[^\n]*(?:\n|$)//s;
                $outtxt=~s/^\s*//;
            } while($oldtxt ne $outtxt);
            $outtxt="$pageheader\n$outtxt";
        }
        $fixedhead=($outtxt ne $intxt);

        # If the page has been edited in the last day, keep watching it in case
        # the last closing gets reverted.
        my $ts=$api->ISO2timestamp($tok->{'revisions'}[0]{'timestamp'}) // time;
        $new_start=[@$date] if(time()-$ts<86400);

        # Fix any simple mispositioned headers: armor any good headers, then
        # fix any mispositioned ones, then unarmor.
        my ($marker, $i)=('', 0);
        do {
            $marker = "\x02--$i--\x03";
            $i++;
        } while($outtxt=~/$marker/);
        $outtxt=~s/(?:^|(?<=\n))((====+)[^=](?:.*[^=])?\2\s*?\n\s*$noticere*$is_closed_re)/$1$marker/go;
        my $fixed=($outtxt=~s/(?:^|(?<=\n))((?>$re).*\n)\s*((====+)[^=](?:.*[^=])?\3\s*?\n)/$2$1/go);
        $outtxt=~s/$marker//go;

        # Split into level-4+ sections, and check if each is closed
        my @sections=$api->split_sections($outtxt, "456");
        my %img=();
        my $ct=0;
        my @closed=();
        my @moved=();
        for(my $i=0; $i<@sections; $i++){
            my $s=$sections[$i];
            if($s->{'body'}=~m/^\s*$noticere*$is_closed_re/o){
                # Someone closed a section, so merge in all its subsections
                my $j;
                for($j=$i+1; $j<@sections && $sections[$j]->{'level'} > $s->{'level'}; $j++){}
                if($j>$i+1){
                    $s->{'body'}=~s/\s*$/\n\n/;
                    $s->{'body'}.=$api->join_sections(splice(@sections, $i+1, $j-$i-1));
                }
            }

            $_ = $s->{'body'};
            my $bad=/(?>^\s*$noticere*\S).*$is_closed_re/so;
            next if !$bad && m/^\s*$noticere*$is_closed_re/o;
            if($bad || /$is_closed_re/so){
                $api->log("Crap, $title is b0rken");
                $api->warn("Crap, $title is b0rken\n");
                $api->whine("[[$title]] is broken", "Help! A section in [[$title]] contains the \"is_closed\" regex but not at the beginning of the section. Probably someone put the {{tl|ffd top}} before a section header instead of after. Anyway, I can't do anything to that page until someone fixes it.");
                if(_cmp_date($date,$sevendays)<0){
                    unshift @old, "* <b>[[$title]] is broken</b>\n";
                    unshift @oldsumm, [@$date];
                }
                $new_start=[@$date];
                $broken=1;
                next MAINLOOP;
            }

            next unless defined($s->{'level'});
            $s->{'isopen'} = 1;
            $ct++;
            next unless $s->{'title'}=~/^\s*\[\[(?:: *Image|:? *Media|: *File) *:((?:[^#<>\[\]{|}]|&#0*(?:3[489]|61);|&#x0*(?:2[267]|3[dD]);|&amp;|&quot;|&apos;)*)(?>(?:\|.*?)?\]\])\s*$/io;
            my $img=$1;

            # Skip multi-image nominations for now. At some point in the future it would be nice to handle these somehow, although IMO that'll need a {{ffd links}} template (cf. {{tfd links}})
            next if ( ( $s->{'body'} =~ /(?:\n|^):\s*<span class="(?:[^"]*\s)?ffd-file(?>\s[^"]*)?"/g ) > 1 );

            $img=~s/&#0*34;|&#x0*22;|&quot;/"/g;
            $img=~s/&#0*39;|&#x0*27;|&apos;/'/g;
            $img=~s/&#0*61;|&#x0*3[dD];/=/g;
            $img=~s/&#0*38;|&#x0*26;|&amp;/&/g;
            $img=uri_unescape($img);
            $img=~s/^\s*|\s*$//g;
            if($img eq 'File_name.ext' || $img eq 'File name.ext'){
                $s->{'body'}=~s/^\s*|\s*$//g;
                $s->{'body'}="{{subst:ffd top|1='''Erroneous Nomination'''. When following the [[WP:FFD#Instructions for listing files for deletion|listing instructions (step 2)]], you need to replace \"<code>File_name.ext</code>\" with the actual name of the file. You'll also want to put the name of the uploader just after \"<code>Uploader=</code>\", and your reason just after \"<code>Reason=</code>\". Feel free to just replace this entire section with the corrected template. If you are still having trouble, ask for help at [[WT:FFD]] or at my talk page. ~~~~}}\n".$s->{'body'}."\n{{subst:ffd bottom}}\n";
                $ct--;
                $s->{'isopen'} = 0;
                push @closed, "[[:File:$img]]";
            } elsif($img eq ''){
                $s->{'body'}=~s/^\s*|\s*$//g;
                $s->{'body'}="{{subst:ffd top|1='''Erroneous Nomination'''. No image name is specified. Feel free to just replace this entire section with the corrected template. If you are still having trouble, ask for help at [[WT:FFD]] or at my talk page. ~~~~}}\n".$s->{'body'}."\n{{subst:ffd bottom}}\n";
                $ct--;
                $s->{'isopen'} = 0;
                push @closed, "[[:File:$img]]";
            } else {
                $img{"File:$img"}=$s;
            }
        }
        next if($ct==0 && @closed==0 && !$fixedhead && !$fixed);

        # Check if the unclosed files still exist. If not, close the
        # discussion.
        my @titles=keys %img;
        while(@titles){
            my @img=splice(@titles, 0, 500);
            $res=$api->query(
                titles => join('|', @img),
                prop   => 'info|imageinfo',
                iiprop => 'canonicaltitle',
            );
            if($res->{'code'} ne 'success'){
                $api->warn("Failed to retrieve file info for $title: ".$res->{'error'}."\n");
                return 60;
            }
            my %map=();
            %map=map { $_->{'to'}, $_->{'from'} } @{$res->{'query'}{'normalized'}} if exists($res->{'query'}{'normalized'});
            PAGE: foreach (values %{$res->{'query'}{'pages'}}){
                # File exists here?
                next PAGE if $_->{'imagerepository'} eq 'local' && $_->{'imageinfo'}[0]{'canonicaltitle'} eq $_->{'title'};

                my $img=$api->apply_redirect_map( $_->{'title'}, \%map );
                if(!exists($img{$img})){
                    my $d=Dumper($_); $d=~s/\s+/ /g;
                    $api->warn("How odd, this was apparently returned even though it wasn't requested: $d\n");
                    next PAGE;
                }

                my $msg=undef;
                # First, check for a deletion.
                my $r=$api->query(
                    letitle => $_->{'title'},
                    list    => 'logevents',
                    letype  => 'delete',
                    lelimit => 1,
                    leprop  => 'user|timestamp|comment',
                );
                if($r->{'code'} ne 'success'){
                    $api->warn("Failed to retrieve logs for ".$_->{'title'}.": ".$r->{'error'}."\n");
                    return 60;
                }
                if(exists($r->{'query'}{'logevents'}[0])){
                    my $log=$r->{'query'}{'logevents'}[0];

                    # Skip for now if it was deleted within the past hour, to
                    # give the closing admin a chance to close it themself.
                    my $t=$api->ISO2timestamp($log->{'timestamp'});
                    next PAGE if(time()-$t<3600);

                    # Check whether the deletion log entry could reasonably
                    # belong to this FFD: the deletion log entry should be
                    # dated on or after the FFD page date. Give them a day of
                    # leeway just in case.
                    $t=_date_add(_make_date($t),1,0,0);
                    if(_cmp_date($t,$date)>=0){
                        # Close it!
                        $msg="'''Delete'''; deleted";
                        if($log->{'comment'}=~/CSD(?:#|\]\] | )([GIF]\d+)/i ||
                           $log->{'comment'}=~/db-([gif]\d+)/){
                            my $c=uc($1);
                            $msg.=" as [[WP:CSD#$c|$c]]";
                        } elsif($log->{'comment'}=~/db-([a-z])/ && exists($db{$1})){
                            my $c=$db{$1};
                            $msg.=" as [[WP:CSD#$c|$c]]";
                        } elsif($log->{'comment'}=~/\x7b\x7b\s*isd\s*[|\x7d]/){
                            $msg.=" as [[WP:CSD#F1|F1]]";
                        }
                        $msg.=" by {{admin|".$log->{'user'}."}}";
                        $msg.=' A file with this name on [[commons:|Commons]] is now visible.' if $_->{'imagerepository'} eq 'shared';
                    }
                }
                if(!defined($msg) && $_->{'imageinfo'}[0]{'canonicaltitle'} ne $_->{'title'} && exists($_->{'redirect'})){
                    # It's a redirect. Is it because it was moved, or because
                    # it was created that way?

                    # Get target
                    my %targets=$api->resolve_redirects($_->{'title'});
                    if(exists($targets{''})){
                        $api->log("Could not resolve redirect ".$_->{'title'}.": ".$targets{''}{'error'});
                        next PAGE;
                    }
                    my $target=$targets{$_->{'title'}};

                    my $r=$api->query(
                        letitle => $_->{'title'},
                        list    => 'logevents',
                        letype  => 'move',
                        lelimit => 1,
                    );
                    if($r->{'code'} ne 'success'){
                        $api->warn("Failed to retrieve logs for ".$_->{'title'}.": ".$r->{'error'}."\n");
                        return 60;
                    }
                    if(exists($r->{'query'}{'logevents'}[0])){
                        my $log=$r->{'query'}{'logevents'}[0];

                        # Skip for now if it was moved within the past hour,
                        # to see if the mover closes it themself.
                        my $ts=$api->ISO2timestamp($log->{'timestamp'});
                        next PAGE if(time()-$ts<3600);

                        # Check whether the move log entry could reasonably
                        # belong to this FFD: the move log entry should be
                        # dated on or after the FFD page date. Give them a day
                        # of leeway just in case.
                        my $t=_date_add(_make_date($ts),1,0,0);
                        if(_cmp_date($t,$date)>=0){
                            # Yes: comment and change the title, but don't
                            # actually close.
                            my $from=$log->{'title'};
                            my $to=$log->{'params'}{'target_title'};
                            my $user=$log->{'user'};
                            my $ts=strftime("%H:%M, %d %B %Y (UTC)", gmtime $ts);
                            $ts=~s/, 0/, /;
                            $img{$img}{'title'} = "[[:$target]]";
                            $img{$img}{'body'}=~s/\s*$//;
                            $img{$img}{'body'}.="\n* '''Note:''' The file was moved from [[:$from]] to [[:$to]] by {{user|1=$user}} at $ts";
                            $img{$img}{'body'}.="; it now redirects to [[:$target]]" if $target ne $to;
                            $img{$img}{'body'}.=". ~~~~\n";
                            push @moved, "[[:$from]]→[[:$target]]";
                            next PAGE;
                        }
                    }

                    # Redirect, but not because of a move. Close it.
                    my $iter=$api->iterator(
                        titles    => $_->{'title'},
                        prop      => 'revisions',
                        rvprop    => 'timestamp|content',
                        rvslots   => 'main',
                        rvsection => 0,
                        rvlimit   => 5,
                    );
                    my $ts=0;
                    my $redir_re=$api->redirect_regex;
                    while(my $res=$iter->next){
                        if(!$res->{'_ok_'}){
                            $api->warn("Could not retrieve revisions from iterator: ".$res->{'error'}."\n");
                            return 60;
                        }
                        $res=$res->{'revisions'}[0];
                        last unless $res->{'slots'}{'main'}{'*'}=~$redir_re;
                        $ts=$api->ISO2timestamp($res->{'timestamp'});
                    }

                    # WTF?
                    if($ts==0){
                        my $t=$_->{'title'};
                        $api->warn("$t claims it's a redirect, but no #REDIRECT found?\n");
                        $api->whine("[[:$t]] confuses me", "When checking [[:$t]], the API prop=info reported it's a redirect, but the top revision does not match $redir_re. Which probably means my code needs fixing.");
                        next PAGE;
                    }

                    # Skip if it was redirectified too recently
                    next PAGE if(time()-$ts<3600);

                    if($target=~/^(?:File|Image):/i){
                        $msg="'''Redirect'''. The file nominated is a redirect. If you are trying to nominate the redirect for deletion, list it at [[WP:RFD]]. If you are trying to nominate [[:$target]] for discussion, please nominate it by that name.";
                    } else {
                        $msg="'''Bad Redirect'''. The file nominated is a redirect to [[:$target]], which is outside the File namespace. Please fix it, or tag it with {{tl|db-imagepage}} if it cannot be fixed.";
                    }
                }
                if(!defined($msg)){
                    # If we get here, there was no (valid) deletion log for
                    # this file, but it still doesn't exist locally.
                    if(!exists($_->{'missing'}) && $_->{'imagerepository'} eq 'shared'){
                        $msg="'''Wrong forum'''. The file is on [[commons:|Commons]], but a local image description page exists. If you are wanting the image deleted, please [[commons:Commons:Deletion requests|nominate it for deletion on Commons]]. If you are requesting deletion of the local image description page only, use {{tl|db-nofile}} if possible; if that is not possible, list it at [[WP:MFD]].";
                    } elsif($_->{'imagerepository'} eq 'shared'){
                        $msg="'''Wrong forum'''. The file is on [[commons:|Commons]]. Please [[commons:Commons:Deletion requests|nominate it for deletion there]] if you still feel it should be deleted.";
                    } elsif(!exists($_->{'missing'})){
                        $msg="'''Wrong forum'''. No file exists by this name, but a local image description page does exist. If you are trying to nominate this description page for deletion, use {{tl|db-imagepage}} if possible; if that is not possible, list it at [[WP:MFD]]. If the file name in the header contains a typo, feel free to correct the typo and un-close this discussion.";
                    } else {
                        $msg="'''Image does not exist'''. If the file name in the header contains a typo, feel free to correct the typo and un-close this discussion.";
                    }
                }
                next if !defined($msg);
                $img{$img}{'body'}=~s/^\s+|\s+$//g;
                $img{$img}{'body'}="{{subst:ffd top|1=$msg ~~~~}}\n".$img{$img}{'body'}."\n{{subst:ffd bottom}}\n";
                $ct--;
                $img{$img}{'isopen'} = 0;
                push @closed, "[[:".$_->{'title'}."]]";
            }
        }

        # Mark for entry on the list of old FFDs, if applicable
        if($ct>0){
            if(_cmp_date($date,$sevendays)<0){
                unshift @old, map { "* [[$title#{{anchorencode:" . $_->{'title'} . "}}]]\n" } grep { $_->{'isopen'} // 0 } @sections;
                unshift @oldsumm, [@$date];
            }
            $new_start=[@$date];
        }

        # Need to edit?
        next unless(@closed || @moved || $fixed || $fixedhead);

        # Processed, now reconstruct the page
        $outtxt=$api->join_sections(@sections);

        # Subst templates, if necessary
        my $subst=0;
        $outtxt=$api->process_templates($outtxt, sub {
            my $name=shift;
            shift; #$params
            my $wikitext=shift;

            return undef unless exists($tosubst{"Template:$name"});
            $subst++;
            $wikitext=~s/^\{\{\s*/\{\{subst:/;
            return $wikitext;
        });

        # Create summary
        my @summary=();
        if($fixedhead){
            if(exists($tok->{'missing'})){
                push @summary, "new discussion page: ".$date->[2].' '.$months[$date->[1]].' '.$date->[0];
            } else {
                push @summary, "fix page header";
            }
        }
        push @summary, "subst {{ffd top}} and/or {{ffd bottom}}" if $subst>0;
        push @summary, 'move closing box'.(($fixed>1)?'es':'').' per [[WP:DPR#FFD]]' if $fixed;
        push @summary, 'close discussions for deleted/nonexistent files: '.join(', ', @closed) if @closed;
        push @summary, 'rename discussions for moved files: '.join(', ', @moved) if @moved;
        my $summary='(BOT) '.ucfirst(join('; ', @summary)).$screwup;
        $api->log("$summary in $title");
        if(length($summary)>500){
            @summary=();
            if($fixedhead){
                if(exists($tok->{'missing'})){
                    push @summary, "new discussion page: ".$date->[2].' '.$months[$date->[1]].' '.$date->[0];
                } else {
                    push @summary, "fix page header";
                }
            }
            push @summary, "subst {{ffd top}} and/or {{ffd bottom}}" if $subst>0;
            push @summary, 'move closing box'.(($fixed>1)?'es':'').' per [[WP:DPR#FFD]]' if $fixed;
            push @summary, 'close discussions for deleted/nonexistent files: [too many to list]' if @closed;
            push @summary, 'rename discussions for moved files: [too many to list]' if @moved;
            $summary='(BOT) '.ucfirst(join('; ', @summary)).$screwup;
        }
        my $r=$api->edit($tok, $outtxt, $summary, 0, 1);
        if($r->{'code'} ne 'success'){
            $api->warn("Write failed on $title: ".$r->{'error'}."\n");
            return 60;
        }
    }

    # Ok, we've processed all the subpages. Now update the list of old FFDs on
    # the main page.
    my $title='Wikipedia:Files for discussion/Old unclosed discussions';
    $api->log("Updating Old discussions list on $title");
    my $tok=$api->edittoken($title);
    if($tok->{'code'} eq 'shutoff'){
        $api->warn("Task disabled: ".$tok->{'content'}."\n");
        return 300;
    }
    if($tok->{'code'} ne 'success'){
        $api->warn("Failed to get edit token for $title: ".$tok->{'error'}."\n");
        return 60;
    }
    my $intxt=$tok->{'revisions'}[0]{'slots'}{'main'}{'*'} // '';
    $intxt=~s/Last updated .*?<!-- Bot edit date -->/Last updated ~~~~~<!-- Bot edit date -->/;
    $intxt=~s/\s*$/\n/;
    my $outtxt="This is a list of unclosed FfDs over 7 days old. It is automatically maintained by a bot, but humans are free to remove lines when closing discussions if they'd like. Last updated ~~~~~<!-- Bot edit date -->.\n\n";
    if ( @old ) {
        $outtxt .= join( '', @old );
    } else {
        $outtxt .= "* None at this time\n";
    }
    if($intxt ne $outtxt){
        my $summary;
        if(@oldsumm){
            my $m=0;
            my @oldsumm2=map {
                my $ret;
                if($_->[1]!=$m){
                    $m=$_->[1];
                    $ret=substr($months[$_->[1]],0,3).' '.$_->[0];
                } else {
                    $ret=$_->[0];
                }
                $ret
            } @oldsumm;
            $oldsumm2[-1].='.';
            $summary='(BOT) Updating discussions: '.join(', ', @oldsumm2).$screwup;
            $api->log("$summary in $title");
            $summary='(BOT) Updating discussions: major backlog!'.$screwup if length($summary)>500;
        } else {
            $summary='(BOT) Updating discussions: no old discussions'.$screwup;
        }
        my $r=$api->edit($tok, $outtxt, $summary, 0, 1);
        if($r->{'code'} ne 'success'){
            $api->warn("Write failed on $title: ".$r->{'error'}."\n");
            return 60;
        }
    }

    # Create redirect after rename
    {
        my $date = _make_date(time+3600);
        my $enddate=[17,11,2015];
        if(_cmp_date($enddate,$date)>=0){
            my $re=$api->redirect_regex();
            my $redir='Wikipedia:Files for deletion/'.$date->[2].' '.$months[$date->[1]].' '.$date->[0];
            my $target='Wikipedia:Files for discussion/'.$date->[2].' '.$months[$date->[1]].' '.$date->[0];
            my $tok=$api->edittoken($redir, EditRedir => 1);
            if($tok->{'code'} eq 'shutoff'){
                $api->warn("Task disabled: ".$tok->{'content'}."\n");
                return 300;
            }
            if($tok->{'code'} ne 'success'){
                $api->warn("Failed to get edit token for $redir: ".$tok->{'error'}."\n");
                return 60;
            }
            next unless exists($tok->{'missing'});
            $api->log("Creating FFD redirect for recent rename: [[$redir]] → [[$target]]");
            my $outtxt = "#REDIRECT [[$target]]\n\nPer [[Special:PermanentLink/687715317#Time to shut down WP:NFCR by merging it into WP:FFD?|consensus]], \"Files for deletion\" has been renamed \"Files for discussion\". These redirects will be created by the bot until 2015-11-17 to ease the transition.";
            my $r=$api->edit($tok, $outtxt, "Creating FFD redirect for recent rename", 0, 1);
            if($r->{'code'} ne 'success'){
                $api->warn("Write failed on $redir: ".$r->{'error'}."\n");
                return 60;
            }
        }
    }

    # Save checked revision
    $self->{'lasttime'}=$starttime;
    $self->{'broken'}=$broken;
    $api->store->{'startdate'}=$new_start;
    $api->store->{'lasttime'}=$starttime;
    $api->store->{'broken'}=$broken;

    my $dt=($self->{'broken'}?300:3600);
    $t=82800-($starttime%86400);
    return $starttime+$t-time() if($t>0 && $t<$dt);
    $t=86400-($starttime%86400);
    return $starttime+$t-time() if($t>0 && $t<$dt);
    return $starttime+$dt-time();
}

sub _make_date {
    my $t=shift || time;
    if(ref($t) eq 'ARRAY'){
        return _fix_date([@$t]);
    } else {
        my @t=gmtime($t);
        @t=@t[3..5];
        $t[1]+=1;
        $t[2]+=1900;
        return [@t];
    }
}

sub _date_add {
    my @t=@{$_[0]};
    $t[0]+=$_[1];
    $t[1]+=$_[2];
    $t[2]+=$_[3];
    return _fix_date([@t]);
}

sub _fix_date {
    my $t=shift;
    my @t=gmtime(timegm(0,0,0,$t->[0],$t->[1]-1,$t->[2]-1900));
    @t=@t[3..5];
    $t[1]+=1;
    $t[2]+=1900;
    return [@t];
}

sub _cmp_date {
    my $a=shift;
    my $b=shift;
    my $x;

    $x=$a->[2]-$b->[2];
    $x=$a->[1]-$b->[1] if $x==0;
    $x=$a->[0]-$b->[0] if $x==0;
    return $x;
}

sub _makepagehead {
    my $api = shift;
    my $title = shift;
    my $date = shift;

    my $res = $api->query(
        action => 'parse',
        title => $title,
        text => '{{subst:Ffd log day|' . $date->[2] . '|' . $months[$date->[1]] . '|' . $date->[0] . '}}',
        onlypst => 1,
        formatversion => 2,
    );
    return ( undef, $res->{'error'} ) if $res->{'code'} ne 'success';

    my $txt = $res->{'parse'}{'text'};
    $txt =~ s/\s*$/\n/s;

    return ($txt, undef);
}

1;