PhpSnip.com

User Stats

WriteConfigFile 2.5b - Manipulate PHP-conform config files

Class "WriteConfigFile" is a tool to manipulate simple config-files in php-script style. It is able to create or manipulate files which later can be included directly into php-scripts. It is able to write bool, numericals, string and (multi-dim) arrays. Code is designed to to avoid many different file writes. It also fixes problems with some permission-systems which reset attributes after modification.

Info

 Download  View Source (print view)
 Rating : 4.7  Views : 412

Source Code ( 438 lines )

<?
/*
Name:    Class WriteConfigFile
Author:  Nils Maier
Country: Germany
Lang:    None
Version: 2.6
Year:    2002-2003
License: Free / GPL-GNU

Description
-----------
Simple class to create and modify PHP-conform files
Please excuse my bad english!
*/

class WCFile
{
    
    // Vars
    var $filename;    // buffer for filename
    var $opened;      // State of file (bool)
    var $modified;    // State of modifications
    var $content;     // Virtual content buffer
    var $cid;         // unique ID
        
    // Constructor - a class instance for every file
    //
    // @syntax (void) WCFile ( (string)$_filename )
    // @param (string) $_filename
    // @return no
    //
    function WCFile($_filename)
    {
        $this->filename = $_filename;
        
        // No Filename
        if ($_filename == "")
            $this->_raiseErr(11);
        
        // Generate FUID    
        $this->cid = substr((string)time().md5(uniqid(rand(),true))."WriteCfg: $_filename",0,1023);
        
        $this->modified = false;
        $this->opened = false;
    }
    
    
    // Opens or creates file
    //
    // @syntax (bool) open ([( bool)$_validate], [ (bool)$_create ])
    // @param (bool) $_validate - Optional. File should get validated. Default = false
    // @param (bool) $_create   - Optional. Creates file if true and file doesnt exist or is not valid
    // @return (bool) Success
    //
    function open ($_validate = false, $_create = true)
    {
        $success = false;
        $created = false;

        // Lock file
        // Also checks if file was already locked!
        $this->_lock();
        
        // File exists
        if (file_exists($this->filename)) 
        {
            // File should get validated
            if ($_validate)
            {
                // File was opened successfully
                if ($fp = @fopen($this->filename, "r"))
                {
                    
                    $blnOpenTag = false;
                    $blnCloseTag= false;
                    
                    // Mini Validator Routine
                    // Only checks the the leading-in and leading-out php-tag
                    while($tmpLine = fgets($fp, 10240))
                    {
                        if (strstr($tmpLine,"<?php")) $blnOpenTag = true;
                        elseif(strstr($tmpLine,"?>") && $blnOpenTag) $blnCloseTag = true;
                    }
                    fclose($fp);
                    
                    // File is not valid
                    if (!$blnOpenTag || !$blnCloseTag)
                    {
                        // if file should created in order to invalidity
                        // try creating it
                        if ($_create)
                            $success = $created = $this->create();
                    }
                    // File is valid
                    else
                        $success = true;
                    
                }
            }
            // Validation not selected
            // return success
            else
                $success = true;
        }
        // File doesnt exist
        elseif ($_create)
            $success = $created = $this->create();
       
        $this->opened = $success;
        
        // File exists and is valid
        if (!$created && $success)
            $this->content = join(file($this->filename),"n");
        
        // Open failed!
        // So unlock file!
        if (!$success)
            $this->_unlock();
            
    return $success;
    }
    
    // Creates or resets file
    //
    // @syntax (bool) create(void)
    // @return (bool) Success
    // @comment Returns always true, course I was bored to set up a routine
    //          to check if file access is allowed
    //
    function create ()
    {
        $this->opened = true;
        $this->content="<?phpnn?>";
        $this->modified = true;
        
    return true;
    }
    
    // Sets a variable (virtual content)
    //
    // @syntax (bool)write ((string)$name, (mixed)$varWrite)
    // @param (string) $_name  - Name of the var to set
    // @param (string) $_value - value (allowed: bool, numerics, string, array)
    // @return none
    //
    function write($_name, $_value)
    {
        // Load virtual content into lines-array
        $file = Array();
        $items = explode("n", $this->content);

        $newexpr = "";
        
        // Sets up new expression
        // Boolean
        if(is_bool($_value))
            $newexpr = "$$name=" . ($_value ? "true" : "false" ). ";";
            
        // Numerical
        elseif (
            is_int($_value)
            || is_integer($_value)
            || is_real($_value)
            || is_double($_value)
        )
            $newexpr = "$$_name=".(string)$_value.";";
        
        // String
        elseif(is_string($_value))
            $newexpr = "$$_name="$_value";";
        
        // Array
        elseif (is_array($_value))
            $newexpr = "$$_name=".$this->_p_array($_value).";";
        
        // Not supported
        else
            $this->_raiseErr(32);
        
        
        // check validity of value to set
        if ($this->opened)
        {
            $written = false;
            
            // Process whole file for the varname
            foreach ($items as $current)
            {
                if (strstr($current, "$$_name="))
                {
                    $written = true;
                    $current = $newexpr;
                }
                array_push($file, $current);
            }
            
            // Var was not found (set yet)
            // So set it up
            if(!$written)
            {
                // Search leading-out php tag
                for($t = 0; $t < count($file); $t++)
                {
                    if(strstr($file[$t], "?>"))
                    {
                        $written = true;
                        $file[$t] = "$newexprn?>";
                    }
                }
            }
            // Set new file content
            $this->content = implode("n",$file);
            
            // Set return value
            // Only false if no leading-out php-tag was found
            if(!$written)
                $this->_raiseErr(14);
            else
                $this->modified = true;
            
        }
        // Fail
        else
            $this->_raiseErr(12);
            
    }
    
    // Unlink file
    //
    // @syntax (bool)unlink (void)
    // @return (bool) Success if unlinked or not there
    //
    function unlink()
    {
        $success = false;
        
        if (file_exists($this->filename))
            if(!$success = @unlink($this->filename))
                $this->_raiseErr(13);
        else
            $success = true;
            
    return $success;
    }
    
    // Saves virtual content to file
    //
    // @syntax (bool) save (void)
    // @return (bool) Success (obsolete in order to _raiseErr)
    //
    function save()
    {
        $success = true;
        
        if($this->opened && $this->modified)
        {
            $success = $this->unlink();
            $success = ($fp = @fopen($this->filename,"w")) ? true : false;
            $success = @fputs($fp,$this->content);
            
            if (!$success)
                $this->_raiseErr(31);
                
            $this->modified = false;
        }
        elseif ($this->opened)
            $this->_raiseErr(12);
            
    return $success;
    }
    
    // Closes file 
    //
    // @syntax (void) close ([(bool)$_save])
    // @param $_save - Optional. Save file before closing. Default = false
    // @return (bool) Success - return always true if !$_save 
    //
    function close($_save = false)
    {
        $success = true;
        
        if (!$this->opened)
            $this->_raiseErr(12);
            
        if ($_save)
            $success = $this->save();
         
        $this->opened = false;
        $this->_unlock();        
    
    if ($_save)
        return $success;
    else
        return true;
    }
    
    // Internal processor for arrays
    // Recursive array processing (for multi-dim array support)
    //
    // @syntax (string) _p_array ((array)$_array)
    // @param $_array - array to process
    // @return (string) Array constructor (one-line)
    //
    function _p_array($_array)
    {
        $constructor = "Array(";
        
        while(list($key, $value) = each($_array))
        {
            // Insert key
            if (is_int($key))
                $constructor .= (string)$key."=>";
            else
                $constructor .= ""$key"=>";
            
            // Insert value
            // Boolean
            if(is_bool($value))
                $constructor .= ($value ? "true" : "false") . ",";
            
            // Numerical    
            elseif (
                is_int($value)
                || is_integer($value)
                || is_real($value)
                || is_double($value)
            )
                $constructor .= (string)$value.",";
            
            // String    
            elseif (is_string($value))
                $constructor.=""$value",";
            
            // Array (recurse)
            elseif (is_array($value))
                $constructor .= $this->_p_array($value).",";
                
            // Unsupported
            else
                $this->_raiseErr(32);
        }
        
        // Finish constructor
        $constructor = substr($constructor, 0, -1) . ")";
        
    return $constructor;    
    }
    
    // Generic file locker
    // Since I do not believe in flock() I've done my own routines
    // Tries to gain access for 10 intervals (à 1s)
    //
    // @syntax (bool) _lock(void)
    // @return (bool) Success (obsolete)
    //
    function _lock()
    {
        $gainerrs = 0;
        // Wait for access
        while (file_exists($this->filename.".lck"))
        {
            sleep(1);
            if (++$gainerrs == 10)
                $this->_raiseErr(21);
        }
        
        if (!$fp = fopen($this->filename.".lck","w"))
            $this->_raiseErr(24);
            
        fputs($fp, $this->cid."nWriteCfg lock file...nThis file was created for a portable locking processnIf there are no processes running you can delete this file, otherwise do NOT delete to prevent scripting errors!");
        fclose($fp);
        
    return true;
    }
    
    // Generic file locker
    // Since I do not believe in flock() I've done my own routines
    // Unlocks file
    //
    // @syntax (void) _unlock(void)
    //
    function _unlock()
    {
        if (!file_exists($this->filename.".lck"))
            $this->_raiseErr(23);
        
        if (!$fp = @fopen($this->filename.".lck","r"))
            $this->_raiseErr(25);
        
        // Checks if this session has locked the file!
        // We dont want to unlock another session
        if (chop(fgets($fp,1024)) != $this->cid)
            $this->_raiseErr(26);
        
        @fclose($fp);
        
        if (!@unlink($this->filename.".lck"))
            $this->_errRaise(27);
    }
    
    // Raises internal error
    // Also terminates execution
    //
    // @syntax (void) _raiseErr($_num)
    // @param (int) $_num Specified error code
    //
    function _raiseErr($_num)
    {
        $errormsg    = Array();
        
        $errormsg[0] = "Unkown error!";
        $errormsg[11]= "No filename was given!";
        $errormsg[12]= "File was not opened or (re)created!";
        $errormsg[13]= "File was NOT unlinked due to inactive permission for file deletions";
        $errormsg[14]= "File is not valid (leading-out tag required)";
        $errormsg[21]= "Unable to lock file! File is already locked by another instance!";
        $errormsg[22]= "Unable to unlock file! Perhaps no permissions!";
        $errormsg[23]= "Unable to unlock file! File was NOT locked!";
        $errormsg[24]= "Unable to lock file! No write permissions to ".$this->filename.".lck!";
        $errormsg[25]= "Unable to unlock file! No read permissions to ".$this->filename.".lck!";
        $errormsg[26]= "Unable to unlock file! File was NOT locked by this instance!";
        $errormsg[27]= "Unable to unlock file! No permissions to unlink file ".$this->filename.".lck!";
        $errormsg[31]= "Unable to save file! Perhaps no permissions!";
        $errormsg[32]= "Unable to write values! Type is not supported!";
        
        
        if (!in_array($_num, array_keys($errormsg)))
            $_num=0;
        
        // Write out error message!
        echo "<P style="width=100%; font-size:2em; color=white; background:red;font-weight:900;">WriteCfg Error $_num: $errormsg[$_num] Terminating scripting-process!</P>";
        
        // Terminate!!!
        exit();
    }
}
?>

Search

Subscribe

  Rss Feeds

Sponsors

Advertise