<?
/*
*
* OSM.php - Organization Security Module
*
* Populates (and updates) Security Groups based on org rank.
* Provides check_security(). 
    check_security() is a simple security check function. 
    Usage: check_security(PlayerName, SecurityLevel);
    check_security() returns TRUE if PlayerName is in that SecurityLevel OR above,
    otherwise it returns FALSE. 
    Security Levels and their order of precidence are:
        SuperAdmin        Highest Security Level
        Admin            
        Raidleader
        Trainee
        ORGRANK0
        ORGRANK1
        ORGRANK2
        ORGRANK3
        ORGRANK4
        ORGRANK5
        ORGRANK6
        Member 
        Guest            Lowest Security Level        
*
* Settings: 
* - government
* - highgid - group number for rank0
* - lowgid  - group number for lowest org rank.
* - ORGRANK0 - ORGRANK6 = Group ID for Ranks 0 - 6.
*/
$osm = new OSM($bot);

/*
Bind the command to the bot.
*/

$commands["tell"]["osm"] = &$osm;
$commands["tell2"]["osm"] = &$osm;
$commands["pgmsg"]["osm"] = &$osm;
$commands["gc"]["osm"] = &$osm;
$commands["connect"][] = &$osm;
// $commands["disconnect"][] = &$osm;

/*
Bind the cronjobs.
Jobs can be executed every:
2sec
1min
1hour
12hour
24hour
*/
$cron["24hour"][] = &$osm;

// This could make it a core module so you can use check_security() from anywhere.
// $bot -> osm = &$osm;

/*
The Class itself...
*/
class OSM
// Start Class
    
var $bot;
    var 
$settings;



    
/*
    Constructor:
    Hands over a referance to the "Bot" class.
    */
    
function OSM (&$bot)
    { 
        
$this -> bot = &$bot;
        
$this -> settings = array();
    }



    
/*
    This gets called on a tell with the command
    */
    
function tell($name$msg)
    { 
// Start function tell()
        
$reply $this -> process_command($name$msg);
        if (
$reply <> FALSE)
            
$this -> bot -> send_tell($name$reply);
    } 
// End function tell()



    /*
    This gets called on a tell with the command from person outside guild
    */
    
function tell2($name$msg)
    { 
// Start function tell2()
        
$reply $this -> process_command($name$msg);
        if (
$reply <> FALSE)
            
$this -> bot -> send_tell($name$reply);
    } 
// End function tell2()



    /*
    This gets called on a msg in the privgroup with the command
    */
    
function pgmsg($name$msg)
    { 
// Start function pgmsg()
        
$reply $this -> process_command($name$msg);
        if (
$reply <> FALSE)
            
$this -> bot -> send_pgroup($reply);
    } 
// End function pgmsg()



    /*
    This gets called on a msg in the guildchat with the command
    */
    
function gc($name$msg)
    { 
// Start function gc()
        
$reply $this -> process_command($name$msg);
        if (
$reply <> FALSE)
            
$this -> bot -> send_gc($reply);
    } 
// End function gc()

    /*
    This gets called on cron
    */
    
function cron()
    { 
// Start function cron()
        
$this -> populate_groups("sa");
    } 
// End function cron()

    /*
    This gets called when bot connects
    */
    
function connect()
    { 
// Start function connect()
        
$this -> settings $this -> bot -> settings -> get_all("OSM");
        if (!isset(
$this -> settings['setup']))
            
$this -> setup(); // Only call setup() on the first module load. 
    
// End function connect()

    /*
    This gets called when bot disconnects
    */
    
function disconnect()
    { 
// Start function disconnect()

    
// End function disconnect()

/* --------------------------------------------------
 *
 * Custom Functions Below
 *
 * --------------------------------------------------
*/   

    /*
        This function handles all the inputs and returns output
        sutible for send_tell, send_pgroup, and send_gc.  
    */
    
function process_command($name$msg)
    {
       if (
preg_match("/^" $this -> bot -> commpre "osm populate$/i"$msg$info)) 
               return 
$this -> populate_groups($name);
       else
            
$this -> bot -> osm_show($name);
    }

    
/*
        Setup - does the initial setup
    */
    
function setup()
    { 
// Start function setup()
        
$setup $this -> bot -> settings -> get("OSM""setup");
        
// settings -> get returns false if the setting doesn't exisit or returns an array if it does.
        // If the setting exisits, setup() is not needed. 
        
if (!$setup
        {
            
$warnings "Setup Warnings:\n\n";
            
// Add primiary key. 
            
$sql "ALTER TABLE admin_members ADD PRIMARY KEY (name, admin_group)";
            if (!
$this -> bot -> db -> returnQuery($sql))
                
$warnings .= "Error creating primary key for table admin_members. Primary key may already exisit.\n";
            
            
$this -> settings['government'] = $this -> get_government();
            
$this -> bot -> settings -> save("OSM""government"$this -> settings['government']);
            
$this -> create_groups();
            
$this -> set_ranks();
            
$this -> populate_groups("sa");            
            
$this -> bot -> log("OSM""SETUP"$warnings);
            
$this -> bot -> settings -> save("OSM""setup"TRUE);
        }
        else
            return 
FALSE;
    } 
// End function setup()

    /*
        Create the Security Groups
        Changing $highnum changes the number of groups that are created.
        I've made assumptions that all possible groups will be created, 
        and will be in sequence even for an Anarchism government, so 
        don't mess with this. :-)
        I put it here in case FunCom adds more org government forms.
    */
    
function create_groups($highnum=6)
    {
        
$i 0;
        while (
$i <= $highnum):
               
$values .= "('ORGRANK".$i."'),";
               
$i++;
        endwhile; 
        
$values rtrim($values","); // Adds commas between values, but not at the end. 
        
echo "\nDEBUG function create_groups() values: ".$values."\n";
        
$sql "INSERT IGNORE INTO admin_groups (name) VALUES ".$values// Creates groups if they do not exist. 
        
echo "\nDEBUG function create_groups() sql: ".$sql."\n";
        
$this -> bot -> db -> query($sql);        
    }     
    
    
/*
        Adds the Group IDs for rank into the settings array.
        Adds the Group Names for each rank into the settings array.
    */
    
function set_ranks($highnum=6)
    { 
// Start function set_ranks()
        
$i 0;
        
$ranks $this -> get_ranknames();
        while (
$i <= $highnum):            
            
// Get the group id number
            
$sql "SELECT id FROM admin_groups WHERE name = 'ORGRANK".$i."'"
            
$result $this -> bot -> db -> select($sql);
            
$gid intval($result[0][0]);
            
// Save the GIDs to settings
            
$settingname "GIDORGRANK".$i;
            
$this -> settings[$settingname] = $gid;
            
$this -> bot -> settings -> save("OSM"$settingname$gid);
            
// Save the Rank Names to settings
            
$settingname "NAMEORGRANK".$i;
            if (isset(
$ranks[$i])) {$rank $ranks[$i];}
            else {
$rank NULL;}
            
$this -> settings[$settingname] = $rank;
            
$this -> bot -> settings -> save("OSM"$settingname$rank);
            
// Increment $i. 
               
$i++;
        endwhile; 
    } 
// End function set_ranks()

    /*
        Returns array of ranknames for the configured government form.
    */          
    
function get_ranknames()
    { 
// Start function get_ranknames()
        
$government strtoupper($this -> settings['government']);
        switch (
$government)
        { 
// Start switch ($government)
            
case "ANARCHISM":
                
$ranks = array(=> "Anarchist"); // Really there is no point to this. 
            
break;
            case 
"DEPARTMENT":
                
$ranks = array(=> "President"=> "General"=> "Squad Commander"=> "Unit Commander"=> "Unit Leader"=> "Unit Member"=> "Applicant");
            break;
            case 
"FACTION":
                
$ranks = array(=> "Director"=> "Board Member"=> "Executive"=> "Member"=> "Applicant");
            break;
            case 
"FEUDALISM":
                
$ranks = array(=> "Lord"=> "Knight"=> "Vassal"=> "Peasant");
            break;
            case 
"MONARCHY":
                
$ranks = array(=> "Monarch"=> "Counsel"=> "Follower");            
            break;
            case 
"REPUBLIC":
                
$ranks = array(=> "President"=> "Advisor"=> "Veteran"=> "Member"=> "Aplicant");            
            break;
        } 
// End switch ($government)
        
return $ranks;
        
    } 
// End function get_ranknames()
           
    /*
        Populate Groups.
    */
    
function populate_groups($name="sa")
    { 
// Start function populate_groups()
        
if (($name == "sa") || ($this -> check_security($name"SUPERADMIN")))
        {
            
$org $this -> bot -> get_site("http://www.anarchy-online.com/org/stats/d/".$this -> bot -> dimension."/name/".$this -> bot -> guildid."/basicstats.xml");
            if (empty(
$org)) {return FALSE;} // Bail if get_site didn't return anything. 
            
            // Remove current ORGRANK memberships
            
$sql "DELETE FROM admin_members WHERE admin_group >= ".$this -> settings['GIDORGRANK0']." AND admin_group <= ".$this -> settings['GIDORGRANK6'];
            
$this -> bot -> db -> query($sql);
            
            
$org explode("<member>"$org);
            
// Parse members, $org[0] is no org member!
            
for ($i 1$i count($org); $i++)
            {
                
$content $org[$i];
                
$nickname $this -> xmlparse($content"nickname");
                   
$rankid $this -> xmlparse($content"rank");
                   
$groupname "ORGRANK".$rankid
                
$groupid $this -> settings["GID".$groupname];
                            
                
$sql "INSERT INTO admin_members (name, admin_group) ";
                
$sql .= "VALUES ('".$nickname."', $groupid)";
                
$this -> bot -> db -> query($sql);
            }
            return 
"Security Groups Populated.";
        }
        else 
            return 
"You must be the super administrator in order to populate the security groups.";
        
    } 
// End function populate_groups()
 
    /*
        Shows teh groups and their members, better than !admin groups. ;)        
    */
    
function osm_show($name);
    { 
// Start function osm_show()
        
if ($this -> check_security($name"MEMBER"))
        {
            
$group "<font color=CCInfoHeadline>::::: Org Security Groups :::::</font><font color=CCInfoText>\n\n";
    
            
$result $this -> bot -> db -> select("SELECT id, name FROM admin_groups WHERE id >= ".$this -> settings['GIDORGRANK0']." AND id <= ".$this -> settings['GIDORGRANK6']." ORDER BY id ASC");
    
            foreach(
$result as $grp)
            {
                
$group .= "<font color=CCInfoHeader>" ucfirst($grp[1]) . "</font>\n";
    
                
$result2 $this -> bot -> db -> select("SELECT admin_members.name FROM admin_members, admin_groups WHERE " .
                
"admin_members.admin_group = admin_groups.id AND admin_groups.id = " $grp[0]);
                if (!empty(
$result2))
                foreach (
$result2 as $res)
                
$group .= " - " $res[0] . "\n";
    
                
$group .= "\n";
            }
    
            
$group .= "</font>";
    
            return 
$this -> bot -> make_blob("Bot Administrators"$group);            
        }
    } 
// End function osm_show()
           
    /* --------------------------------------------------
    *
    * Get Info Stuff
    *
    * --------------------------------------------------
    */     
    
    /*
        Returns the Group ID of a group 
    */
    
function get_groupid($group)
    {
        
$sql "SELECT id FROM admin_groups WHERE name = ".$group;
        
$result $this -> bot -> db -> select($sql);
        return 
$result[0][0];
    }    
    
    
/*
        Gets the Governing Form from FunCom's servers
    */
    
function get_government()
    { 
// Start function get_government()
            // Have to get the HTML, not XML. XML doesn't show the Government type. :-/
            
$content file_get_contents("http://www.anarchyonline.com/org/stats/d/".$this -> bot -> dimension."/name/".$this -> bot -> guildid);
            
// Make sure we got content from the server. 
            
if (!$content)
            {
                return 
FALSE;
            }
            else
            {
                
preg_match("/<p><b>Government:<\/b> (.+)<\/p>/i"$content$info);
                return 
$info[1];
            }
    } 
// End function get_government()
    
    /*
        Borrowed from whois cache ;-)
    */
    
function xmlparse($xml$tag)
    {
        
$tmp explode("<" $tag ">"$xml);
        
$tmp explode("</" $tag ">"$tmp[1]);
        return 
$tmp[0];
    }        
    
    
/* --------------------------------------------------
    *
    * Settings Managment
    *
    * --------------------------------------------------
    */      
           
    /*
        Check Security v1.0.2
            Returns TRUE if $name is in $level or above.
            Otherwise Returns False.
    */
    
function check_security($name$level)
    { 
// Start function check_security()
        
$name ucfirst(strtolower($name));
        
$level strtoupper($level);

        switch (
$level)
        {
        
// is_member($name) : returns if person is a member of the bot (true = member, 2 = guest, false = unknown)
            
case "GUEST":
                if ( (
$this -> bot -> is_member($name) == 2)
                      || (
$this -> bot -> is_member($name) == 1) )
                    return 
TRUE;
                else
                    return 
FALSE;
            break;
            case 
"MEMBER":
                if (
$this -> bot -> is_member($name) == 1)
                    return 
TRUE;
                 else
                    return 
FALSE;
            break;
            case 
"ORGRANK6":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK6")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK5")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK4")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK3")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK2")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;            
            break;
            case 
"ORGRANK5":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK5")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK4")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK3")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK2")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"ORGRANK4":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK4")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK3")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK2")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"ORGRANK3":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK3")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK2")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"ORGRANK2":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK2")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"ORGRANK1":
                if (
$this -> bot -> admin -> in_group($name"ORGRANK1")
                    || 
$this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"ORGRANK0"// Org Leader/Founder
                
if ($this -> bot -> admin -> in_group($name"ORGRANK0")
                    || 
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;                   
            break;
            case 
"TRAINEE":
                if (
$this -> bot -> admin -> in_group($name"trainee")
                    || 
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;
            break;
            case 
"RAIDLEADER":
                if (
$this -> bot -> admin -> in_group($name"raidleader")
                    || 
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;
            break;
            case 
"ADMIN":
                if (
$this -> bot -> admin -> in_group($name"admin")
                    || 
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;
                break;
            case 
"SUPERADMIN":
                if (
$this -> bot -> admin -> in_group($name"superadmin"))
                    return 
TRUE;
                else
                    return 
FALSE;
            break;
            default:
                return 
FALSE;
            break;
        }
    } 
// End function check_security()    
            
// End of Class
?>