<?php
error_reporting(E_ALL|E_STRICT);
//stuff to modify

$projectclasses = array('FA','A','GA','B','START','STUB','NA');
$sourcepage = 'User:Sambot/Tasks/Water polo';
$logpage = 'User:Sambot/Tasks/Water polo/Logged';
$registryfile = 'aquaticsregistry.pillar';
$modifytemplates = array('Template:WP Swimming','Template:WikiProject Swimming');
$dbtable = 'aquaticsprocessed';
$editsummary = '[[Wikipedia:Bots/Requests for approval/Sambot 10|BOT]]: modifying {{[[Template:WP Swimming|WP Swimming]]}} -- water polo workgroup';
$logsummary = '[[Wikipedia:Bots/Requests for approval/Sambot 10|BOT]]: more pages tagged';

//stuff that should be left alone

include('pillar/class.pillar.php');

$pillar = Pillar::ini_launch('templates.ini');

$source = new Page ($sourcepage,false,Page::LINKS);

$categories = explode("\n",$source->get_text());
for ($i = 0 ; $i < count($categories) ; $i++) {
    $categories[$i] = preg_replace("/.*Category:(.*)\]\]/i","Category:$1",$categories[$i]);
}

$shelltemplates = array('Template:WPBS','Template:WikiProjectBannerShell','Template:WPB','Template:WikiProjectBanners');

$facat = 'Category:Wikipedia featured articles';
$gacat = 'Category:GA-class Good articles';

$mycnf = parse_ini_file("/home/samkorn/.my.cnf");
$username = $mycnf['user'];
$password = $mycnf['password'];
unset($mycnf);
$fh = fopen ('registry.txt','w');
$dbuser = mysql_connect('sql',$username,$password)
        or print 'DB error ' . mysql_error();
$dbenwiki = mysql_connect('sql-s1',$username,$password)
        or print 'DB error ' . mysql_error();
        
unset($username);
unset($password);

mysql_select_db('u_samkorn_templates',$dbuser);
mysql_select_db('enwiki_p',$dbenwiki);

try {
    $logpage = new Page($pillar->cursite,$logpage);
} catch (PillarException $e) {
    die();
}

$registry = new Registry($registryfile);

LoopThrough::pagelinks($source,'loopthrucat',$registry);
function loopthrucat($title) {
    global $registry;
    LoopThrough::category($title,'dealwithpage',$registry);
    return true;
}
function dealwithpage($page) {
    global $dbuser,$dbenwiki,$dbtable,$modifytemplates,$shelltemplates,$projectclasses,$editsummary,$logsummary,$facat,$gacat;
    static $logpagetext;
    $pillar = Pillar::get_instance();
    
    $sql = "SELECT id FROM $dbtable WHERE name='" . mysql_real_escape_string(str_replace(' ','_',$page['title'])) . "' LIMIT 1";
    $result = mysql_query($sql,$dbuser);
    if (mysql_num_rows($result) == 1) {
        return true;
    }
    
    if ($pillar->cursite->namespaceistalk($page['namespace'])) {
        return true;
    }
    
    $isstub = $isga = $isfa = $rating = false;
    
    if ($page['namespace'] == 0) {
        $sql = "SELECT tl_title AS templatename FROM templatelinks WHERE tl_from = (SELECT page_id FROM page WHERE page_title = '" . mysql_real_escape_string(str_replace(' ','_',$page['title'])) . "' AND page_namespace = {$page['namespace']} LIMIT 1)";
        $result = mysql_query($sql,$dbenwiki);
        
        if (mysql_num_rows($result)) {
            while (false !== ($row = mysql_fetch_assoc($result))) {
                if (false !== stripos ($row['templatename'],'stub')) {
                    $isstub = true;
                }
            }
        }
    }
    
    try {
        $talkpage = new Page($pillar->cursite->get_talkname($page['title'],$page['namespace']),false,Page::TEMPLATES | Page::CATEGORIES);
    } catch (PillarException $e) {
        return false;
    }
    
    if ($talkpage->checkexcluded()) {
        return true;
    }
    
    $isfa = in_array($facat,$talkpage->get_categories());
    $isga = in_array($gacat,$talkpage->get_categories());
    
    if (!$isfa && !$isga) {
        if (preg_match_all('/class\s*=([^\|\}]*?)\s*(?:\||(?:\}\})|\s)/i',$talkpage->get_text(),$match)) {
            $ratingsearch = array_map('strtoupper',$match[1]);
            
            for ($k = 0 ; $k < count($projectclasses) ; $k++) {
                if (false !== ($num = array_search($projectclasses[$k],$ratingsearch))) {
                    $rating = $match[1][$num];
                    break;
                }
            }
        }
    }
    
    if (count(array_intersect($modifytemplates,$talkpage->get_templates()))) {
        $templatesfound = array_intersect($modifytemplates,$talkpage->get_templates());
        $templatefound = substr(array_pop($templatesfound),9);
        
        $template = new Template($talkpage->get_text(),$templatefound);
        
        $class = $stubmarked = $rating = false;
        
        if (!$template->fieldvalue('class')) {
            if ($isfa) {
                $template->updatefield('class','FA');
            } elseif ($isga) {
                $template->updatefield('class','GA');
            } elseif ($isstub) {
                $template->updatefield('class','stub');
            } elseif ($rating) {
                $template->updatefield('class',$rating);
            }
        }
        
        if (!$template->fieldvalue('water-polo')) {
            $template->updatefield('water-polo','yes');
        }
        
        $newtext = $template->wholePage();
    } else {
        $class = ($isfa ? 'FA' : ($isga ? 'GA' : ($isstub ? 'stub' : ($rating ? $rating : false))));
        
        $templateadd = '{{WP Swimming' . ($class ? " |class = $class" : '') . "|water-polo = yes}}\n" ;
        
        if (count(array_intersect($shelltemplates,$talkpage->get_templates()))) {
            $templatefound = substr(array_pop(array_intersect($shelltemplates,$talkpage->get_templates())),9);
            
            $template = new Template($talkpage->get_text(),$templatefound);
            
            if (count($template->fields) > 1) {
                $template->addfield($templateadd);
            } else {
                $template->updatefield(1,$template->fieldvalue(1) . "\n$templateadd");
            }
            
            $newtext = $template->wholePage();
        } else {
            $position = 0;
            
            if (false === strpos($talkpage->get_text(),'{{')) {
                $position = 0;
            } else {
                $after = $talkpage->get_text();
                while (preg_match('/^(\s*)\{\{(.*?)(?:\||(?:\}\}))/s',$after,$match)) {                         
                    $template = new Template ($after,$match[2]);
                    
                    $sql = "SELECT id FROM talkpageheaders WHERE name='" . mysql_real_escape_string(ucfirst(trim($template->name))) . "'";
                    $result = mysql_query($sql,$dbuser);
                    
                    if (mysql_num_rows($result) === 0) {
                        break;
                    }
                    $position += strlen($template->before . $template->templatestring . $match[1]);
                    $after = $template->after;
                }
            }
            
            if ($position == 0) {
                $templateadd = trim($templateadd) . "\n";
            }
            
            $newtext = substr($talkpage->get_text(),0,$position) . "\n$templateadd" . substr($talkpage->get_text(),$position);
            $logpagetext .= "\n* [[" . $talkpage->get_title() . ']]';
        }
    }       
    
    try {
        if ($talkpage->put($newtext,$editsummary,true,false)) {
            Pillar::report("Edited " . $talkpage->get_title(),PILLAR_ACTION);
        }
        $sql = "INSERT INTO $dbtable (name) ('" . mysql_real_escape_string($talkpage->get_title()) . "')";
        mysql_query($sql,$dbuser);
    } catch (PillarActionCancelled $e) {
        Pillar::report($e->getMessage(),PILLAR_ERROR);
        return true;
    } catch (PillarEditAssertion $e) {
        $pillar->cursite->login();
        return false;
    } catch (PillarException $e) {
        return false;
    }
    
    if (($pillar->cursite->get_edits_made() > 0) && ($pillar->cursite->get_edits_made() % 100 == 0)) {
        try {
            $logpage->put($logpage->get_text() . $logpagetext,$logsummary,1);
            $logpagetext = "\n";
        } catch (PillarException $e) {
            Pillar::report($e->getMessage(),PILLAR_ERROR);
        }
    }
    
    return true;
}