<?php

define ('PILLAR','PILLAR');

require('pillar/class.pillar.php');
// require('modules/class.template.php');
// require('modules/class.pageverbose.php');

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

$source = new Page($pillar->cursite,'User:Sambot/Tasks/Egypt');

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

$disambigtemplates = array('Disambig', 'Hndis', 'Mathdab', 'Mountainindex', 'Roaddis', 'Schooldis', 'Shipindex');
$mergetemplates = array ('Merge', 'Merge-multiple', 'Mergeto', 'Mergefrom', 'Mergefrom-multiple', 'Merge-multiple-to', 'Mergesection', 'Mergesections', 'Merging', 'Mergeto-multiple', 'Mergetomultiple-with', 'Merge from', 'Merge-from', 'Include', 'Mergefrom', 'Merging from', 'Mergefrommulti', 'Mergefrommultiple', 'Multimergefrom', 'Merge to', 'Merge-to', 'Mergeinto', 'MergePartial', 'Merge into', 'Mergesectionto', 'MergetoCat', 'Mergeto-disputed', 'Merging to');

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

$shelltemplates = array('Template:WPBS','Template:WikiProjectBannerShell','Template:WPB','Template:WikiProjectBanners');
$excludetemplates = array('Template:WikiProject Ancient Egypt', 'Template:AncientEgyptBanner', 'Template:WikiProject Egyptian Religion', 'Template:KMTbanner');
$modifytemplates = array('Template:WikiProject Egypt','Template:WPEGYPT','Template:WPEgypt');

$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('enwiki-p.db.toolserver.org',$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);
// mysql_close();

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

$logpage = new Page($pillar->cursite,'User:Sambot/Tasks/Egypt/Tagged');

foreach ($categories as $cat) {
    do {
        $pages = $pillar->cursite->get_categorymembers($cat,500,$continue,null,true);
        
        foreach ($pages as $page) {
            $page = array('namespace'=>0,'title'=>'Egyptian piastre');
            if ($page['namespace'] == 14) {
                continue; //ignore categories
            }
            
            if ($pillar->cursite->namespaceistalk($page['namespace'])) {
                continue;
            }
            
            if ($page['namespace'] != 10) { // page is not a category
                $disambig = $merge = false;
                
                if ($page['namespace'] == 0) {
                    $sql = "SELECT tl_title AS templatename FROM templatelinks WHERE tl_from = (SELECT page_id FROM page WHERE page_title = '" . 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 (in_array($row['templatename'],$disambigtemplates)) {
                                $disambig = true;
                            }
                            if (in_array($row['templatename'],$mergetemplates)) {
                                $mergefound = true;
                            }
                        }
                    }
                }
                
                $talkpage = new PageVerbose($pillar->cursite,$pillar->cursite->get_talkname($page['title'],$page['namespace']));
                
                if (count(array_intersect($excludetemplates,$talkpage->get_templates()))) {
                    continue; //ignore pages tagged with "Ancient Egypt"
                }
                
                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 = $mergefound = false;
                    
                    if ($disambig) {
                        for ($i = 0 ; $i < count($template['fields']) ; $i++) {
                            if (preg_match("/^\s*class\s*=/i",$field)) {
                                $class = true;
                                $template['fields'][$i] = preg_replace("/^(\s*class\s*=)[^\|\}]*?(\s*)$/","$1Disambiguation$2",$template['fields'][$i]);
                                break;
                            }
                        }
                        if (!$class) {
                            $template['fields'][] = 'class=Disambiguation';
                        }
                    } 
                    
                    if ($merge) {
                        for ($i = 0 ; $i < count($template['fields']) ; $i++) {
                            if (preg_match("/^\s*merge\s*=/i",$field)) {
                                $mergefound = true;
                                $template['fields'][$i] = preg_replace("/^(\s*merge\s*=)[^\|\}]*?(\s*)$/","$1yes$2",$template['fields'][$i]);
                                break;
                            }
                        }
                        if (!$mergefound) {
                            $template['fields'][] = 'merge=yes';
                        }
                    }
                    
                    if ($page['namespace'] == 10) { //is a template
                        for ($i = 0 ; $i < count($template['fields']) ; $i++) {
                            if (preg_match("/^\s*class\s*=/i",$field)) {
                                $class = true;
                                $template['fields'][$i] = preg_replace("/^(\s*class\s*=)[^\|\}]*?(\s*)$/","$1Template$2",$template['fields'][$i]);
                                break;
                            }
                        }
                    }
                    
                    if (!$class) {
                        for ($i = 0 ; $i < count($template['fields']) ; $i++) {
                            if (preg_match("/^\s*class\s*=\s*([^\|\}]*?)\s*$/i",$template['fields'][$i])) {
                                $class = true;
                                break;
                            }
                        }
                    }
                    
                    if (!$class && preg_match("/^\s*class\s*=\s*([^\|\}]*?)\s*$/i",$list['end'],$match)) {
                        $template['fields'][] = "class={$match[1]}";
                    }
                    
                    $newtext = $list['start'] . Template::templatebuild($template) . $list['end'];
                } else {
                    if ($disambig) {
                        $class = "Disambiguation";
                    } elseif ($page['namespace'] == 14) {
                        $class = "Template";
                    } elseif (preg_match('/class\s*=([^\|\}]*?)\s*(?:\||(?:\}\}))/i',$talkpage->get_text(),$match)) {
                        if (in_array(strtoupper($match[1]),$projectclasses)) {
                            $class = $match[1];
                        }
                    } else {
                        $class = false;
                    }
                    
                    $templateadd = '{{WikiProject Egypt' . ($class ? " | class=$class" : '') . ($mergefound ? " | merge=yes" : '') . "}}\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['fields'][count($shell['fields']) - 1] .= "\n$templateadd";
                        $newtext = $list['open'] . 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['open'] . $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 {
                $talkpage->put(trim($newtext),'BOT: cleanup {{WikiProject Egypt}}',1);
            } catch (PillarActionCancelled $e) {
                Pillar::report($e->getMessage(),PILLAR_ERROR);
            }
            
            if (($pillar->cursite->get_edits_made() > 0) && ($pillar->cursite->get_edits_made() % 100 == 0)) {
                try {
                    $logpage->put($logpagetext,'BOT: More pages tagged',1);
                } catch (PillarException $e) {
                    Pillar::report($e->getMessage(),PILLAR_ERROR);
                }
            }
        }
    } while ($continue);
}

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