SunQuest
 
       File Manipulation Code
  Home arrow File Manipulation Code arrow Bs_IniHandler
Try It Free
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
IBM developerWorks
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
FILE MANIPULATION CODE

Bs_IniHandler
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2002-11-27

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Try It Free
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    The IniHandler can read and write ini-style files (and strings). Many options can be set.
    example: http://www.blueshoes.org/en/framework/util/ini_handler/
    source: http://www.blueshoes.org/download/Bs_IniHandler.class.phps
    manual: http://developer.blueshoes.org/phpdoc/Bs_IniHandler.html
    this class is part of the blueshoes php application framework, see http://www.blueshoes.org/


    By : blueshoes

    <?php
    define('BS_INIHANDLER_VERSION', '4.0.$x$');

    define('BS_INIHANDLER_UNQUOTE_NONE', 0);
    define('BS_INIHANDLER_UNQUOTE_DOUBLE', 1);
    define('BS_INIHANDLER_UNQUOTE_SINGLE', 2);
    define('BS_INIHANDLER_UNQUOTE_ALL', 3);


    /*************************************************************************
    * This class provides methods to work with ini-style files.
    *
    *
    *
    * E.g.
    * # Comment
    * [Some test data]
    * one = hallo
    * two = "hallo"
    * food = "Tom's Pizza = 'good stuff'"
    * more food = Sam's Pizza's = 'best stuff'
    * empty = ""
    * noVal =
    * [more test data]
    * one = hi
    * two = 'hi'
    * food = 'Pizza = "good"'
    * empty = ''
    * noVal
    *
    * no dependencies here.
    *
    * @author andrej arn <andrej at blueshoes dot org>, Sam Blum <sam at blueshoes dot org>
    * @copyright blueshoes.org
    * @version 4.0.$id$
    * @package util
    * @access public
    */
    class Bs_IniHandler extends Bs_Object {


    /**
    * specifies which chars at the start of a line define a comment line.
    * the line is left-trimmed before the comparison is made.
    *
    * default: '#', '/', ';'
    *
    * note: you can only specify chars, not strings. so if you want '//' as
    * comment char, you need to define '/'. (which is done by default)
    *
    * @access public
    * @var array $commentChars (vector)
    */
    var $commentChars = array('#', '/', ';');

    /**
    * should quoted values be unquoted?
    *
    * 0 = no
    * BS_INIHANDLER_UNQUOTE_SINGLE = only single-quotes 'like this'
    * BS_INIHANDLER_UNQUOTE_DOUBLE = only double-quotes "like this"
    * BS_INIHANDLER_UNQUOTE_ALL = single and double quotes (default)
    *
    * @access public
    * @var int $unQuote
    */
    var $unQuote = BS_INIHANDLER_UNQUOTE_ALL;

    /**
    * vector with the sections as strings.
    *
    * note: since this var is not really needed, and all information is available in
    * $this->_params, this internal var may disappear in the future.
    *
    * @access private
    * @var array $_sections
    */
    var $_sections;

    /**
    * 2-dim hash where the first dim is a hash with the section names, the 2nd
    * is the key/value pair hash.
    * @access private
    * @var array $_params
    */
    var $_params;

    /**
    * @todo make private
    */
    var $comments;

    /**
    * the fullpath to the currently used file.
    * @var string $_fileFullPath
    */
    var $_fileFullPath;

    /**
    * the last error message of the error that occured. not set = no error.
    * @access private
    * @var string $_lastError
    */
    var $_lastError;


    /**
    * Constructor.
    * WARNING: please do not use the param $fileFullPath here, better call loadFile() yourself
    * because otherwise you won't know if it worked or not.
    * @param string $fileFullPath
    */
    function Bs_IniHandler($fileFullPath='') {
    parent::Bs_Object(__FILE__); //call parent constructor.
    if (!empty($fileFullPath)) {
    $this->loadFile($fileFullPath);
    }
    }


    /**
    * Loads the given file (read in and parse).
    * @access public
    * @param string $fileFullPath (a fullpath to the desired file.)
    * @return bool (see getLastError())
    */
    function loadFile($fileFullPath) {
    $this->reset();

    if (!file_exists($fileFullPath)) {
    $this->_lastError = "File doesn't exists: '{$fileFullPath}'";
    return FALSE;
    }
    if (!is_readable($fileFullPath)) {
    $this->_lastError = "File is not readable: '{$fileFullPath}'";
    return FALSE;
    }

    $this->_fileFullPath = $fileFullPath;

    $fileContent = file($fileFullPath);
    $this->_parseFromArray($fileContent);

    return TRUE;
    }


    /**
    * loads the ini stuff from the given string instead of a file (read in and parse).
    * @access public
    * @param string $str
    * @return bool (see getLastError())
    */
    function loadString($str) {
    $this->reset();

    $arr = explode("\n", $str);
    $this->_parseFromArray($arr);

    return TRUE;
    }


    /**
    * sets the quote handling.
    * @access public
    * @param int $mode (see constants)
    * @return void
    */
    function setQuoteHandling($mode=BS_INIHANDLER_UNQUOTE_ALL) {
    $this->unQuote = $mode;
    }


    /**
    * gets called from loadFile() and loadString() to parse the data.
    * @access private
    * @param array (vector filled with strings (lines))
    * @return void
    */
    function _parseFromArray($arr) {
    $this->comments = array();
    $comment = array();
    $section = '';

    foreach($arr as $line) {
    $sectionFound = $valueFound = FALSE;
    $param = array('key'=>'', 'val'=>'');
    do { // try
    $line = trim($line);

    # Skip empty lines
    if (empty($line)) break; // try

    # Comment
    if (in_array($line[0], $this->commentChars)) {
    $comment[] = $line;
    break; // try
    }

    # Section
    if (preg_match('/\[(.*)\]/', $line, $ar)) {
    $section = $ar[1];
    $sectionFound = TRUE;
    break; // try
    }

    # Parameter
    // split 1x at first '='
    $tmp = explode('=', $line);
    if (!is_array($tmp)) break; // try
    if (sizeOf($tmp) < 2) {
    //invalid comment line, whatever.
    //no good if we arrive here. that's some crappy line that should not be in the file.
    //we could issue a warning here.
    $comment[] = @$tmp[0];
    break;
    }

    $param['key'] = trim($tmp[0]);
    array_shift($tmp);
    if (sizeOf($tmp)>1) $tmp[0] = implode('=', $tmp);
    $param['val'] = isSet($tmp[0]) ? trim($tmp[0]) : '';
    if (empty($param['val'])) {
    $valueFound = TRUE;
    break; // try
    }


    $unQuote = '';
    if ($this->unQuote & BS_INIHANDLER_UNQUOTE_DOUBLE) $unQuote .= '"';
    if ($this->unQuote & BS_INIHANDLER_UNQUOTE_SINGLE) $unQuote .= "'";
    if (empty($unQuote)) {
    $valueFound = TRUE;
    break; // try
    }

    // trim quote
    $regEx = '/^(['.$unQuote.']?)(.*)\1$/';
    if (preg_match($regEx, $param['val'], $ar)) {
    $param['val'] = $ar[2];
    $valueFound = TRUE;
    break; // try
    } else {
    //the value had unmatching quotes, like "here' or 'here"
    break; // try
    }
    } while(FALSE);

    if ($sectionFound) {
    $this->_sections[] = $section;
    if (!empty($comment)) $this->comments[$section] = $comment;
    $comment = array();
    } else if ($valueFound) {
    $this->_params[$section][$param['key']] = $param['val'];
    if (!empty($comment)) $this->comments[$section .'__'. $param['key']] = $comment;
    $comment = array();
    }
    } // foreach
    if (!empty($comment)) $this->comments['__LastComment__'] = $comment;
    }


    /**
    *
    */
    function toString() {
    $outStr = "# Bs_IniHandler File generated by www.blueshoes.org\n\n";
    foreach ($this->_params as $section => $params) {
    if (isSet($this->comments[$section])) {
    foreach ($this->comments[$section] as $comment) $outStr .= "{$comment}\n";
    }
    $outStr .= "[".$section."]\n";
    foreach ($params as $key => $value) {
    if (isSet($this->comments[$section .'__'. $key])) {
    foreach ($this->comments[$section .'__'. $key] as $comment) $outStr .= " {$comment}\n";
    }
    $outStr .= " " .$key. " = " .$value. "\n";
    }
    $outStr .= "\n";
    }

    if (isSet($this->comments['__LastComment__'])) {
    foreach ($this->comments['__LastComment__'] as $comment) $outStr .= "{$comment}\n";
    }
    return $outStr;
    }


    /**
    * saves the ini settings to the file specified.
    * @access public
    * @param string $fileFullPath (see above)
    * @return bool (see getLastError())
    * @see saveString()
    */
    function saveFile($fileFullPath) {
    $outStr = $this->toString();
    if (!$fp = fopen($this->_fileFullPath, 'wb')) {
    $this->_lastError = "Failed open the file for writing: '{$fileFullPath}'";
    return FALSE;
    }
    if (!fwrite($fp, $outStr)){
    $this->_lastError = "Failed to write (but was able to open) the file: '{$fileFullPath}'";
    return FALSE;
    }

    @fclose($fp);
    return TRUE;
    }

    /**
    * resets this object so we can re-use it for something else.
    * some setting vars are not reset.
    *
    * resets:
    * _sections
    * _params
    * _fileFullPath
    * _lastError
    *
    * keeps:
    * commentChars
    * unQuote
    *
    * @access public
    * @return void
    */
    function reset() {
    unset($this->_sections);
    unset($this->_params);
    unset($this->_fileFullPath);
    unset($this->_lastError);
    }


    /**
    * returns [all parameters|parameter] [for the given section].
    *
    * examples:
    * get() => returns all sections with all params as 2-D hash.
    * array of [<section>][<key>] => <string>
    * get('section') => returns all params for the section specified as 1-D hash.
    * array of [<key>] => <string>
    * get('section', 'key') => returns the param specified of the section specified as string.
    *
    * note: if a param is defined in the 'global scope', use an empty string for the
    * $section name. example: get('', 'key')
    *
    * @access public
    * @param string $section if not given returns all sections
    * @param string $key if not given returns all keys
    * @return mixed (see above)
    * @throws null (if the given section or key does not exist)
    */
    function get($section=NULL, $key=NULL) {
    if (is_null($section)) return $this->_params;
    if (!isSet($this->_params[$section])) return NULL; //throw
    if (is_null($key)) return $this->_params[$section];
    if (!isSet($this->_params[$section][$key])) return NULL; //throw
    return $this->_params[$section][$key];
    }


    /**
    * tells if the section or key specified is set.
    *
    * examples:
    * has('mySection') => tells if 'mySection' is set
    * has('mySection', 'myKey' => tells if myKey in mySection is set.
    *
    * note: case matters!
    *
    * @access public
    * @param string $section
    * @param string $key (default is NULL)
    * @return bool
    */
    function has($section, $key=NULL) {
    if (is_null($key)) {
    return (isSet($this->_params[$section])); //using _params instead of _sections cause it's a hash. in_array is slower.
    } else {
    return (isSet($this->_params[$section]) && isSet($this->_params[$section][$key]));
    }
    }


    /**
    * returns the text message of the last error that occured.
    *
    * call this function if something failed, for example after getting
    * bool FALSE back from loadFile().
    *
    * @access public
    * @return mixed (string last error, or NULL if no error occured.)
    */
    function getLastError() {
    if (is_null($this->_lastError)) return NULL;
    return $this->_lastError;
    }
    }

    #####################################################
    # SELF - Test
    #####################################################
    if (basename($_SERVER['PHP_SELF']) == 'Bs_IniHandler.class.php') {


    $testData =<<<EOD
    # Comment 1
    # comment 2
    []
    globalData = foo

    # comment A
    [Some test data]
    # comment B
    one = hallo
    two = "hallo"
    # comment C
    food = "Tom's Pizza = 'good stuff'"
    more food = Sam's Pizza's = 'best stuff'
    empty = ""
    noVal =
    # comment D
    [more test data]
    one = hi
    two = 'hi'
    food = 'Pizza = "good"'
    empty = ''
    noVal
    # comment E
    EOD;

    $iniHandler = new Bs_IniHandler();
    $iniHandler->loadString($testData);

    #XR_dump($iniHandler->comments, __LINE__, '', __FILE__);
    XR_dump($iniHandler->toString(), __LINE__, '', __FILE__);
    }

    ?>
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More File Manipulation Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Tester for SOA Quality V7.0.1

    Get a free trial download of the latest version of IBM Rational Tester for SOA Quality V7.0.1, a functional and regression testing tool that enables the creation, comprehension, modification and execution of testing GUI-less Web services.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Connectivity

    Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic.
    FREE! Go There Now!


    NEW! Webcast: Calling All Testers! Find Application Vulnerabilities Early in the Development Process Where they are Easier to Fix and Less Risky to your Business

    In this webcast, IBM Rational will discuss the importance of Web application security and will share techniques and best practices to introduce application security testing into current QA processes including: understanding common security vulnerabilities and techniques to integrate security testing with defect tracking and remediation systems in an effort to safeguard sensitive online information.
    FREE! Go There Now!


    NEW! Webcast: Striking the right balance between manual and automated testing

    Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    FILE MANIPULATION CODE ARTICLES

    - Bandwidth Control with pure PHP
    - Eazy Gallery
    - file_get_contents for PHP < 4.3.0
    - PHP Class: Image Snapshot 1.3
    - Universal downloader
    - Image Gallery v2.0
    - Free/Used Disk Space
    - Directory Lister
    - Directory image view, with selective hidden
    - Move or Copy a Directory (and files and sub ...
    - Ensure_Sub_Directory_Exists
    - Wedit
    - Form Examples Text Boxes to Drop Downs
    - myFiles
    - List files in a directory, no subdirectories





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway