Location: PHPKode > scripts > Installation Automation > installation-automation/install.php
<?php
/*
 * install.php
 *      A global installation class created to be used with any kind of application.
 * 
 * Before doing anything with this class, I recommend you read the documentation to figure out
 *  what you are doing. That's so you won't accidentally mess something up.
 */

class install {

    /*
     * The stages that the script would have in it's overall installation process.
     *      This is to ensure that the user wouldn't just put anything random into the 
     *      url and try to do something. Also for automation.
     */
    
    var $stages = array('stage 1','stage 2','stage 3');
    
    /*
     * This determines if we would have anything to do with SQL
     */
    
    var $use_sql = true;
    
    /*
     * This would store the SQL information once/if recieved (For the stage submitted on... later on, uses $_SESSION)
     */
    
    var $sql = array('HOST'  => null,       // MySQL Host
                     'USER'  => null,       // MySQL Username
                     'PASS'  => null,       // MySQL Passowrd
                     'DBASE' => null,       // MySQL Database Name
                     'TBL_PRE' => null);    // MySQL Table Prefix

    /*
     * Determines if a global file would be created at the end.
     * 
     * The global file would consist of the MySQL host, username, password and the database name
     */
    
    var $create_global = true;
    
    /*
     * Determines the location that the configuration file would be saved to (Make sure it exists)
     */
    
    var $gl_loc = 'includes/';
    
    /*
     * Determines the name for the global file
     */
    
    var $globals = 'global';
    
    /*
     * Determines the global file type (also used as the extension for the global file)
     * 
     *  Possible types:
     *      XML, PHP
     * 
     * NOTE: If you know PHP it would be easy for you to add more types here
     */
    
    var $global_type = 'XML';
    
    /*
     * location where the forms are located (Set the filename equal to their stage)
     */
    
    var $forms = 'forms/';
    
    /*
     * Location of the SQL file holding the SQL queries to be made
     * 
     * NOTE:
     *      Make sure that every CREATE query is set into an array called $create even if there is only one query.
     *      Make sure that every INSERT query is set into an array called $insert even if there is only one query.
     */
    
    var $sqls = 'sql/queries.php';
    
    /*
     * The following forces the class to die on error and print the error
     */
    
    var $force_errors = false;
    
    /*
     * Set the following true if you want the script to debug at each error
     */
    
    var $debug = true;
    
    /*
     * Determines weather you want a HEADER redirect or one by JavaScript
     * 
     *  Possible values:
     *      HEADER (PHP Header redirection)
     *      JavaScript (Javascript Window redirection)
     */
    
    var $redirect_type = 'JavaScript';
    
    /*
     * Redirection place where users would go to upon finishing installation
     */
    
    var $redirect_loc = 'documentation.html';
    
    /*
     * The following variables are variables for this class. Configure them at your own risk
     */
    
    var $error = array();               // Silent errors returned by this class
    var $errno = 0;                     // Number of errors generated by the class
    var $global_loc = null;             // The location of the global file created
    var $add = array();                 // An additional variable for additional needs
    
    /*
     * function setup( [ string $stage ] )
     *      @string $stage - The current stage of the installation. (Includes the form)
     * 
     * Includes the form for the current setup stage
     */
    
    function setup()
    {
        // Making sure we've got the right stage
        $stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
        
        // Including the corrent stage's form
        include_once($this->forms . $stage . '.php');
    }
    
    /*
     * function cont( VOID )
     * 
     * Checks the current stage and determines what the next stage should be
     */
    
    function cont()
    {
        // Getting the current stage the user is on
        $stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
        
        // Advancing to the next stage
        $stage = $this->advance($stage);
        
        // Checking if the installation process was finished
        if($stage == sizeof($this->stages) || $stage == false)
        {
            // Checking if we need to create the global file
            if($this->create_global == true)
            {
                $this->create_global();
            }
            else
            {
                /*
                 * The redirect type here is set to JavaScript to over-ride HEADER.
                 *  Reason being, is when the installation is done and the script
                 *  is supposed to redirect the user to the page you specified,
                 *  then the HEADER tries to look for a class that isn't there,
                 *  but JavaScript does it correctly. Don't know why.
                 */
                $this->redirect_type = "JavaScript";
                
                // Redirecting the user to the page you specified
                $this->redirect($this->redirect_loc);
            }
            break;
        }
        
        // Getting the page the user is on (The installation page)
        $page = $_SERVER['PHP_SELF'];
        
        // Redirecting the user to the next stage
        $this->redirect("{$page}?stage={$this->stages[$stage]}");
    }
    
    /*
     * function advance( string $stage )
     *      @string $stage - Current stage that the function would determine the next from
     * 
     * Redirects the user to the next stage after one is done
     */
    
    function advance($stage)
    {
        // Going through the stages array and looking for the current stage
        foreach($this->stages as $id => $st)
        {
            // Adding 1 to the current stage key
            if($stage == $st)
            {
                return $id + 1;
            }
        }
        
        // Getting the amount of stages there are
        $stage_size = sizeof($this->stages);
        
        // Checking if this is the last stage or if the stage doesn't exist
        if($id == $stage_size)
        {
            return false;
        }
        else
        {
            // Neither found... we don't need to advance since the installation is done!
            $this->error('STAGE_ADVANCE', "An unknown error occured in " . (__FILE__) . ' - (<strong>' . (__LINE__) . '</strong>)');
            
            return $id;
        }
    }
    
    /*
     * function set_sql( string $host, string $user, string $pass, string $dbname, string $tbl_pre )
     *      @string $host - The MySQL Host
     *      @string $user - The MySQL User
     *      @string $pass - The MySQL Password
     *      @string $dbname - The Database Name
     *      @string $tbl_pre - The MySQL Table Prefix
     * 
     * Function that sets the class sql array to their appropriate values
     */
    
    function set_sql($host, $user, $pass, $dbname, $tbl_pre)
    {
        // Setting the SQL array to it's appropriate values
        $this->sql = array('HOST'  => $host,
                                  'USER'  => $user,
                                  'PASS'  => $pass,
                                  'DBASE' => $dbname,
                                  'TBL_PRE' => $tbl_pre);
        
        // Setting the SQL session
        $_SESSION['sql'] = $this->sql;
        
        // Checking if the values submitted were valid
        if($this->check_sql($host, $user, $pass, $dbname) == true)
        {
            // Values were correct
            return true;
        }
        
        // Values were incorrect
        $this->error('SETTING_SQL', "Values submitted weren't valid");
        return false;
    }
    
    /*
     * function create_global( VOID )
     * 
     * Function that creates the global file.
     */
    
    function create_global()
    {
        // Creating the location where the global would be and it's name with extension type
        $global_loc = $this->gl_loc . $this->globals . '.' . strtolower($this->global_type);
        
        // Checking what kind of global file it would be... PHP or XML
        switch($this->global_type)
        {
            case 'XML':
                // The XML content
                $content = <<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<database>
    <host>{$_SESSION['sql']['HOST']}</host>
    <user>{$_SESSION['sql']['USER']}</user>
    <pass>{$_SESSION['sql']['PASS']}</pass>
    <dbname>{$_SESSION['sql']['DBASE']}</dbname>
    <table_prefix>{$_SESSION['sql']['TBL_PRE']}</table_prefix>
</database>
EOT;
                
                break;
            case 'PHP':
                // The PHP content
                $content = <<<EOT
<?php

/* The global configuration file */

// The MySQL Host
\$host = "{$_SESSION['sql']['HOST']}";

// The MySQL User
\$user = "{$_SESSION['sql']['USER']}";

// The MySQL password
\$pass = "{$_SESSION['sql']['PASS']}";

// The MySQL Database Name
\$dbname = "{$_SESSION['sql']['DBASE']}";

// The MySQL Table Prefix
\$tbl_pre = "{$_SESSION['sql']['TBL_PRE']}";

?>
EOT;
                break;
            default:
                // Neither of the correct options were given. Defaulting to XML
                $this->global_type = 'XML';
                $this->create_global();
                break;
        }
        
        // Setting the location of the global file into the class variable
        $this->global_loc = $global_loc;
        
        // Creating the Global File
        if(touch($this->global_loc) != false)
        {
            // Putting the contents into the global file
            if(file_put_contents($global_loc, $content) != false)
            {
                // Checking if we are to create SQL tables into the created database
                if($this->use_sql == true)
                {
                    // Doing the SQL portion of the installation
                    $this->do_sql();
                }
                else
                {
                    // Redirecting the user to the finish page
                    $this->redirect($this->redirect_loc);
                }
            }
        }
        else
        {
            // The contents weren't put into the global file. Set the error and return false
            $this->error('GLOBAL_FILE_CONTENT', "Contents were failed to be put into the global file  {$this->global_loc}");
            return false;
        }
    }
    
    /*
     * function do_sql( VOID )
     * 
     * Function that carries out the available SQL queries provided in the SQL file
     */
    
    function do_sql()
    {
        // Requiring the SQLs page
        require $this->sqls;
        
        // Connecting to MySQL
        $link = mysql_connect($_SESSION['sql']['HOST'], $_SESSION['sql']['USER'], $_SESSION['sql']['PASS']) or die(mysql_error());
        
        // Selecting the database
        $db = mysql_select_db($_SESSION['sql']['DBASE']) or die(mysql_error());
        
        // Checking if CREATE array exists
        if(isset($create))
        {
            // Doing the SQL table creation
            foreach($create as $query)
            {
                // executing the create queries
                $result = mysql_query($query, $link);
                
                // Checking of one of the queries failed
                if($result == false)
                {
                    $this->error('SQL_QUERY_CREATE',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
                    return false;
                    break;
                }
            }
        }
        
        // Checking if INSERT array exists
        if(isset($insert))
        {
            // Looping through each insert query and doing them
            foreach($insert as $query)
            {
                // Executing the queries
                $result = mysql_query($query, $link);
                
                // Checking if one of them failed.
                if($result == false)
                {
                    $this->error('SQL_QUERY_INSERT',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
                    return false;
                    break;
                }
            }
        }
        
        // Making sure there were no possible errors
        if(!isset($create) && !isset($insert))
        {
            $this->error('DO_SQL_EXECUTION',"The SQL file provided doesn't have the required arrays set.");
            return false;
        }
        
        // Everything carried out correctly. Redirect to the homepage
        $this->redirect($this->redirect_loc);
    }
    
    function redirect($page)
    {
        // Redirecting the user to the next stage based on the preferable redirection type
        switch($this->redirect_type)
        {
            case "HEADER":
                // It's header... turning the output buffering on
                ob_start();
                
                // Redirecting the user
                header("LOCATION: {$page}");
                
                // Sending the content and turning the output buffer off
                ob_end_flush();
                break;
            case "JavaScript":
                // Redirecting the user with JavaScript
                echo "<script language=\"JavaScript\">window.location=\"{$page}\";</script>";
                break;
            default:
                // Not one possible redirection type is given... using JavaScript by default
                $this->redirect_type = 'JavaScript';
                $this->redirect($page);
                break;
        }
    }
    
    /*
     * function error( string $key, string $msg )
     *      @string $key - The key to the error array
     *      @string $msg - The message to the error array associated to the given $key
     * 
     * Sets the error array and checks on farther error/debugging options
     */
    
    function error($key, $msg)
    {
        // Setting the error array
        $this->error[$key] = $msg;
        
        // Incrementing the error number value
        $this->errno += 1;
        
        // Checking if we should debug the error(s)
        if($this->debug == true)
        {
            echo $this->debug();
            
            // Checking if we have to force this error
            if($this->force_errors == true)
            {
                exit;
            }
        }
        
        // Checking if we should force the error to be shown
        if($this->force_errors == true)
        {
            die("<strong>$key</strong> $msg");
        }
    }
    
    /*
     * function debug( VOID )
     * 
     * Function that does some debugging options on produced/generated errors
     */
    
    function debug()
    {
        // Starting the debug text generation
        $text = "<p>You got {$this->errno} error" . ((sizeof($this->error) > 1) ? '\'s' : null) . " generated from the installation:<br />\n<br />\n";
        
        // Going through each error recieved and generating the rest of the debugging text
        foreach($this->error as $err_name => $err_msg)
        {
            $text .= "<strong>$err_name</strong>: $err_msg<br />\n";
        }
        
        // Finishing off the debugging text
        $text .= "</p>";
        
        // Returning the generated text
        return $text;
    }
    
    /************************************************************************************************
     * The following functions are a functions repository                                           *
     *  To what you may need for the installation                                                   *
     *  process.                                                                                    *
     ************************************************************************************************/
     
    /*
     * function check_sql( [ string $db ] )
     *      @string $db - Whether or not we should check the validicy of the database
     * 
     * Checks if the MySQL credentials are correct
     */
    
    function check_sql($db = true)
    {
        // Connecting to MySQL and capturing the resource handler
        $link = @mysql_connect($this->sql['HOST'], $this->sql['USER'], $this->sql['PASS']);
        
        // Checking if we are not connected
        if($link == false)
        {
            $this->error('SQL_CONNECTION', mysql_errno() . ' - ' . mysql_error());
        }
        
        // Checking if we should select the database
        if($db == true)
        {
            // Selecting the database and capturing the resource handler
            $db = @mysql_select_db($this->sql['DBASE']);
            
            // Checking if there were any errors in the connection
            if($db == false)
            {
                $this->error('SQL_DB_SELECT', mysql_errno() . ' - ' . mysql_error());
            }
        }
        
        // Closing the MySQL Connection if we are connected
        if($link != false)
        {
            @mysql_close($link);
        }
        
        // Returning the result.
        return (($link != false || $db != false) ? true : false);
    }
    
    /*
     * function get_xml( string $what )
     *      @string $what - The variable to take from an XML File
     * 
     * Retrieves a variable from the global file
     */
    
    function get_xml($what)
    {
        // Loading the global XML file
        $db = (array) simplexml_load_file($this->global_file);
        
        // Returing the requested variable to the user
        return (string) $db[$what];
    }
    
    /*
     * function add( string $value [, mix $key] )
     *      @string $value - The value to add to the additional variable
     *      @mix $key - This variable could be set to the following possible values
     *          * 00 (2 zeros) - If you want a numeric, automatically-set keys
     *          * Anything else - If the key is not set to 00, then the key would be what you put it. (string value and key only)
     * 
     * Creates an additional array for whatever needs you may need.
     */
    
    function add($value, $key = 00)
    {
        // Checking if the key should be numeric
        if($key == 00)
        {
            // Getting the next available numeric key so we wouldn't over ride a value
            foreach($this->add as $id => $val)
            {
                // Checking if the key is numeric
                if(is_numeric($id))
                {
                    $keyed = $id;
                }
            }
            
            // Incrementing the last numeric key by one
            $key = $keyed + 1;
            
            // Unsetting the useless $val
            unset($val);
        }
        
        // Generating the array 
        $this->add[$key] = $value;
        
        // Returning the entire array
        return $this->add;
    }
}
?>
Return current item: Installation Automation