<?
function errout($txt){
    echo '<b>ERROR:</b> '.htmlentities($txt);
    exit;
}

ini_set('user_agent', 'Anomie BRFA automation script');

$bot=isset($_REQUEST['bot'])?$_REQUEST['bot']:'';
$u=null;
$err='';
if($bot){
    $res=file_get_contents('http://en.wikipedia.org/w/api.php?format=php&action=query&list=users&usprop=groups&ususers='.urlencode($bot));
    if(!$res) errout("Failed to query API for user existence");
    $x=unserialize($res);
    if(isset($x['query']['users'][0])) $u=$x['query']['users'][0];
}
if(!$u || isset($u['missing']) || isset($u['invalid'])){
    if(isset($u['missing'])) echo '<b>User does not exist</b><br />';
    if(isset($u['invalid'])) echo '<b>Username is invalid</b><br />';
?>
<form method="get">
<b>Bot name:</b> <input type="text" name="bot" value="<?=htmlentities($bot)?>" /><br />
<input type="submit" />
</form>
<?
    exit;
}

$bot=$u['name'];
$flagged='No';
if(isset($u['groups'])){
    foreach($u['groups'] as $g)
        if($g=='bot') $flagged='Yes';
}

$basepg="Wikipedia:Bots/Requests for approval/$bot";
$max=0;
$cont='';
do {
    $res=file_get_contents('http://en.wikipedia.org/w/api.php?format=php&action=query&list=allpages&aplimit=max&apnamespace=4&apprefix='.urlencode(substr($basepg,10)).$cont);
    if(!$res) errout("Failed to query API for BRFA page list");
    $x=unserialize($res);
    if(!$x) errout("Invalid API response while querying BRFA page list: $res");
    $cont='';
    if(isset($x['query-continue']['allpages'])){
        foreach($x['query-continue']['allpages'] as $k=>$v)
            $cont.="&$k=".urlencode($v);
    }
    foreach($x['query']['allpages'] as $v){
        if($v['title']==$basepg) $max=max($max,1);
        if(preg_match("/^".preg_quote($basepg,'/')." (\d+)$/", $v['title'], $m))
            $max=max($max,+$m[1]);
    }
} while($cont);

$num=$max?$max+1:'';
$pg=trim("$basepg $num");
?>
<body onload="for(var i=document.forms.length-1; i>=0; i--) document.forms[i].submit()">
<form action="http://en.wikipedia.org/w/index.php?title=Wikipedia:Bots/Requests_for_approval&action=submit" method="post">
<input type="hidden" name="wpSection" value="<?=$max?2:1?>">
<input type="hidden" name="wpSummary" value="Requesting approval: <?=trim("$bot $num")?>">
<input type="hidden" name="wpAutoSummary" value="d41d8cd98f00b204e9800998ecf8427e" />
<input type="hidden" name="wpWatchthis" value="1">
<input type="hidden" name="wpDiff" value="Show changes">
<?
$res=file_get_contents('http://en.wikipedia.org/w/api.php?format=php&action=query&titles=Wikipedia:Bots/Requests+for+approval&prop=revisions|info&rvprop=content|timestamp&intoken=edit&rvsection='.($max?2:1));
if(!$res) errout("Failed to query API for user existence");
$x=unserialize($res);
if(!isset($x['query']['pages'])) errout('No page data');
$x=array_values($x['query']['pages']);
$x=$x[0];
$txt=preg_replace('/(<!-- Add NEW entries here at the TOP of this section right BELOW this comment. -->)\s*/', "\$1\n{{BRFA|$bot|$num|Open}}\n", $x['revisions'][0]['*']);
?>
<input type="hidden" name="wpStarttime" value="<?=preg_replace('/[^0-9]/','',$x['starttimestamp'])?>">
<input type="hidden" name="wpEdittime" value="<?=preg_replace('/[^0-9]/','',$x['revisions'][0]['timestamp'])?>">
<input type="hidden" name="wpTextbox1" value="<?=htmlentities($txt)?>">
</form>
<form target="_blank" action="http://en.wikipedia.org/w/index.php?title=<?=urlencode($pg)?>&action=submit" method="post">
<?ob_start();?>
<noinclude>[[Category:Open Wikipedia bot requests for approval|<?=trim("$bot $num")?>]]</noinclude>
==[[User:<?=$bot?>|<?=trim("$bot $num")?>]]==
{{Newbot|<?=$bot?>|<?=$num?>}} 

'''Operator:''' ~~~

<!--Automatic: Specify whether supervised or unsupervised -->
<!--Manually Assisted: User must manually confirm every change -->
'''Automatic or Manually assisted:''' Automatic, unsupervised

<!--Programming Language: The computer language that this bot will be written in. E.g. Python, Java, C, VB, AutoWikiBrowser. NOT English etc -->
'''[[Programming language]](s):''' Perl

<!--Source code available: e.g. a link to the source code, "Standard pywikipedia"/"AWB"/etc. Be sure the bot account's password is not given out! -->
'''[[Source code]] available:''' [[User:<?=$bot?>/source/tasks/XXX.pm]]

<!--Please keep Function Overview SHORT (i.e. one or two lines) and put any in-depth explanation in the details section below-->
'''Function overview:''' 

<!--Bot tasks require consensus in order to be approved.  Please list any relevant discussions here to indicate consensus for the task.  If such input is not necessary (for instance, a task that is duplicating or closely matching an existing bot) leave this blank-->
'''Links to relevant discussions (where appropriate):''' 

<!-- e.g. Continuous, daily, one time run, etc. -->
'''Edit period(s):''' 

<!--Should be a reasonable guess as to how many distinct pages you'll be editing. For open-ended tasks, estimate pages per some reasonable time period.-->
'''Estimated number of pages affected:''' 

<!--If "no", please provide a reason in the Function details or Discussion.-->
'''[[Template:bots|Exclusion compliant]]''' ''(Y/N)''''':''' Yes 

<!--For existing bots only-->
'''Already has a bot flag''' ''(Y/N)''''':''' <?=$flagged?>


<!--List full function details here-->
'''Function details:''' 

===Discussion===
<!-- This is not a vote.  It is a discussion -->
<?$txt=ob_get_clean();?>
<input type="hidden" name="wpTextbox1" value="<?=htmlentities($txt)?>">
<input type="hidden" name="wpSummary" value="Requesting approval">
<input type="hidden" name="wpAutoSummary" value="d41d8cd98f00b204e9800998ecf8427e" />
<input type="hidden" name="wpWatchthis" value="1">
<input type="hidden" name="wpPreview" value="Preview">
</form>
</body>