User:Sambot/Code/Aquatics

From Wikipedia, the free encyclopedia
<?php

define ('PILLAR','PILLAR');

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

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

$source = new Page('User:Sambot/Tasks/Aquatics');

$categories = explode("\n",$source->get_text());

$projectclasses = array('FA','A','GA','B','START','STUB','NA');

$shelltemplates = array('Template:WPBS','Template:WikiProjectBannerShell','Template:WPB','Template:WikiProjectBanners');
$modifytemplates = array('Template:WP Swimming','Template:WikiProject Swimming');

$mycnf = parse_ini_file("/home/samkorn/.my.cnf");
$username = $mycnf['user'];
$password = $mycnf['password'];
unset($mycnf);

$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);

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

try {
    $logpage = new Page($pillar->cursite,'User:Sambot/Tasks/Aquatics/Tagged');
} catch (PillarException $e) {
    Pillar::report($e->getMessage());
    die();
}

foreach ($categories as $cat) {
    do {
        try {
            $pages = $pillar->cursite->get_categorymembers($cat,500,$continue,null,true);
        } catch (PillarException $e) {
            if ($j++ < 5) {
                continue;
            }
            Pillar::report($e->getMessage(),PILLAR_ERROR);
            die();
        }
        
        for ($f = 0 ; $f < count($pages) ; $f++) {
            $page =& $pages[$f]; //mimicking foreach but with the ability to go back as well as forwards
            
            $sql = "SELECT id FROM aquaticsprocessed WHERE name='{$page['title']}' LIMIT 1";
            $result = mysql_query($sql,$dbuser);
            
            if (mysql_num_rows($result) == 1) {
                continue; //don't do things multiple times
            }
            
            if ($pillar->cursite->namespaceistalk($page['namespace'])) {
                continue;
            }
            
            if ($page['namespace'] != 10) { // page is not a category
                $isstub = 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['tl_title'],'templatename')) {
                                $isstub = true;
                            }
                        }
                    }
                }
                
                try {
                    $talkpage = new Page($pillar->cursite->get_talkname($page['title'],$page['namespace']),false,Page::TEMPLATES);
                } catch (PillarException $e) {
                    --$f;
                    continue;
                }
                
                if (count(array_intersect($modifytemplates,$talkpage->get_templates()))) {
                    $templatefound = substr(array_pop(array_intersect($modifytemplates,$talkpage->get_templates())),9);
                    $list = Template::separatetemplate($talkpage->get_text(),$templatefound);
                    $template = Template::templatesplit($list['template']);
                    $class = $stubmarked = false;
                    
                    if ($isstub) {
                        if (!isset($template['fieldnames']['class'])) {
                            $template['fieldnames'][] = 'class = stub';
                        } elseif (preg_match('/^class\s*=\s*$/is',$template['fieldnames']['class'])) {
                            $template['fieldnames']['class'] = 'class = stub';
                        }
                    } elseif (preg_match_all('/class\s*=([^\|\}]*?)\s*(?:\||(?:\}\}))/i',$talkpage->get_text(),$match)) {
                        $ratings = array_map('strtoupper',$match[1]);
                        
                        for ($i = 0 ; $i < count($projectclasses) ; $i++) {
                            if (false !== ($rating = array_search($projectclasses[$i],$ratings))) {
                                break;
                            }
                        }
                        
                        if (preg_match('/^class\s*=\s*$/is',$template['fieldnames']['class'])) {
                            $template['fieldnames']['class'] .= $rating;
                        } elseif (!isset($template['fieldnames']['class'])) {
                            $template['fieldnames']['class'] = 'class = ' . $rating;
                        }
                    }
                    
                    $newtext = $list['start'] . Template::templatebuild($template) . $list['end'];
                } else {
                    if ($isstub) {
                        $class = 'stub';
                    } elseif (preg_match_all('/class\s*=([^\|\}]*?)\s*(?:\||(?:\}\}))/i',$talkpage->get_text(),$match)) {
                        $class = false;
                        $ratings = array_map('strtoupper',$match[1]);
                        for ($i = 0 ; $i < count($projectclasses) ; $i++) {
                            if (false !== ($rating = array_search($projectclasses[$i],$ratings))) {
                                $class = $match[1][$rating];
                            }
                        }
                    } else {
                        $class = false;
                    }
                    
                    $templateadd = '{{WP Swimming' . ($class ? " | class=$class" : '') . "}}\n" ;
                    
                    if (count(array_intersect($shelltemplates,$talkpage->get_templates()))) {
                        $templatefound = substr(array_pop(array_intersect($shelltemplates,$talkpage->get_templates())),9);
                        $list = Template::separatetemplate($talkpage->get_text(),$templatefound);
                        $shell = Template::templatesplit($list['template']);
                        
                        $shell['fieldnames'][count($shell['fields']) - 1] .= "\n$templateadd";
                        $newtext = $list['start'] . Template::templatebuild($shell) . $list['end'];
                    } else {
                        $position = 0;
                        
                        if (false === strpos($talkpage->get_text(),'{{')) {
                            $position = 0;
                        } else {
                            $list['end'] = $talkpage->get_text();
                            while ((preg_match('/^(\s*)\{\{(.*?)(?:\||(?:\}\}))/s',$list['end'],$match)) && ($i++ != 100)) {                         
                                $list = Template::separatetemplate($list['end'],$match[2]);
                                $template = Template::templatesplit($list['template']);
                                
                                $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($list['start'] . $list['template'] . $match[1]);
                            }
                        }
                        
                        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(trim($newtext),'[[Wikipedia:Bots/Requests for approval/Sambot 4|BOT]]: add {{WP Swimming}}',1,false)) {
                    Pillar::report("Edited " . $talkpage->get_title(),PILLAR_ACTION);
                    $sql = "INSERT INTO aquaticsprocessed (name) ('" . $talkpage->get_title() . "')";
                    mysql_query($sql);
                }
            } catch (PillarActionCancelled $e) {
                Pillar::report($e->getMessage(),PILLAR_ERROR);
            } catch (PillarException $e) {
                continue;
            }
            
            if (($pillar->cursite->get_edits_made() > 0) && ($pillar->cursite->get_edits_made() % 100 == 0)) {
                try {
                    $logpage->put($logpage->get_text() . $logpagetext,'BOT: More pages tagged',1);
                    $logpagetext = "\n";
                } catch (PillarException $e) {
                    Pillar::report($e->getMessage(),PILLAR_ERROR);
                }
            }
        }
    } while ($continue);
}

try {
    $logpage->put($logpage->get_text() . $logpagetext,'BOT: More pages tagged',1);
} catch (PillarException $e) {
    Pillar::report($e->getMessage(),PILLAR_ERROR);
}