home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / xampp-win32-1.6.7-installer.exe / php / PEAR / DB / Sqlite / Tools / DBC.php < prev    next >
Encoding:
PHP Script  |  2008-07-02  |  14.0 KB  |  511 lines

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
  3.  
  4. // {{{ Header
  5.  
  6. /**
  7.  * DB_Sqlite_Tools_DBC, the security class for manipulate SQLite database.
  8.  *
  9.  * PHP version 5
  10.  *
  11.  * LICENSE:
  12.  *
  13.  * BSD License
  14.  *
  15.  * Copyright (c) 2004-2006 David Costa
  16.  * All rights reserved.
  17.  *
  18.  * Redistribution and use in source and binary forms, with or without
  19.  * modification, are permitted provided that the following conditions
  20.  * are met:
  21.  *
  22.  * 1. Redistributions of source code must retain the above copyright
  23.  *    notice, this list of conditions and the following disclaimer.
  24.  * 2. Redistributions in binary form must reproduce the above
  25.  *    copyright notice, this list of conditions and the following
  26.  *    disclaimer in the documentation and/or other materials provided
  27.  *    with the distribution.
  28.  * 3. Neither the name of David Costa nor the names of
  29.  *    contributors may be used to endorse or promote products derived
  30.  *    from this software without specific prior written permission.
  31.  *
  32.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  33.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  34.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  35.  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  36.  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  37.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  38.  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  41.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  42.  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  43.  * POSSIBILITY OF SUCH DAMAGE.
  44.  *
  45.  * @category Database
  46.  * @package  DB_Sqlite_Tools
  47.  * @author David Costa <gurugeek@php.net>
  48.  * @author Ashley Hewson <morbidness@gmail.com>
  49.  * @author Radu Negoescu <negora@dawnideas.com>
  50.  * @copyright Copyright (c) 2004-2006 David Costa
  51.  * @license http://www.opensource.org/licenses/bsd-license.php
  52.  *          BSD License
  53.  * @version CVS: $Id: DBC.php,v 13 2006/08/18 17:22:31 gurugeek Exp $
  54.  */
  55.  
  56. // }}}
  57. // {{{ Dependencies
  58.  
  59. /**
  60.  * Load the PEAR_Exception
  61.  */
  62. require_once 'PEAR/Exception.php';
  63.  
  64. // }}}
  65. // {{{ Class: DB_Sqlite_Tools_DBC
  66.  
  67. /**
  68.  * This class, part of DB_Sqlite_Tools allows to insert on an sqlite database
  69.  * securely encrypted data and retrieve and decript on the fly the encrypted
  70.  * data. Since Sqlite might be seen as voulnerable, encrypted database will
  71.  * ensure the data integrity. It doesn't require PHP to be compiled with MCrypt
  72.  * but it uses Crypt_ArcFour, embedded (ported to PHP 5 the original PEAR
  73.  * package).
  74.  *
  75.  * @category Database
  76.  * @package  DB_Sqlite_Tools
  77.  * @author David Costa <gurugeek@php.net>
  78.  * @author Ashley Hewson <morbidness@gmail.com>
  79.  * @author Radu Negoescu <negora@dawnideas.com>
  80.  * @copyright Copyright (c) 2004-2006 David Costa
  81.  * @license http://www.opensource.org/licenses/bsd-license.php
  82.  *          BSD License
  83.  * @version Release: 0.1.5
  84.  */
  85. class DB_Sqlite_Tools_DBC
  86. {
  87.     // {{{ Properties
  88.  
  89.     /**
  90.      * The database object.
  91.      *
  92.      * @var object
  93.      */
  94.     private $dbobj;
  95.  
  96.     /**
  97.      * The results object.
  98.      *
  99.      * @var object
  100.      */
  101.     public $result;
  102.  
  103.     /**
  104.      * Whether turn on debug mode or not.
  105.      *
  106.      * @var bool
  107.      */
  108.     public $debug = false;
  109.  
  110.     /**
  111.      * ArcFour crypt object.
  112.      *
  113.      * @var object
  114.      */
  115.     public $matrix;
  116.  
  117.     /**
  118.      * An encryption key.
  119.      *
  120.      * @var string
  121.      */
  122.     public $key;
  123.  
  124.     // }}}
  125.     // {{{ Constants
  126.  
  127.     /**
  128.      * Delimiter for autoExec.
  129.      */
  130.     const DB_STRING_DELIMITER = "'";
  131.  
  132.     /**
  133.      * Insert mode constant.
  134.      */
  135.     const DB_AUTOQUERY_INSERT = 1;
  136.  
  137.     /**
  138.      * Update mode constant.
  139.      */
  140.     const DB_AUTOQUERY_UPDATE = 2;
  141.  
  142.     // }}}
  143.     // {{{ Constructor
  144.  
  145.     /**
  146.      * Constructor.
  147.      */
  148.     public function __construct()
  149.     {
  150.         // instantiate a new ArcFour object
  151.         $this->matrix = new DB_Sqlite_Tools_ArcFour;
  152.     }
  153.  
  154.     // }}}
  155.     // {{{ liteAutoExec()
  156.  
  157.     /**
  158.      * Auto Execute an insert or update query.
  159.      *
  160.      * @param string $tableName DB table name
  161.      * @param string $tableFields DB fields name
  162.      * @param string $tableValues DB table value
  163.      * @param string $querytype Type of query, insert by default
  164.      * @param string $crypt Crypt with ArcFour before inserting the data, default true
  165.      * @param string $whereString Necessary for UPDATE, default null
  166.      *
  167.      * @return mixed
  168.      * @throws PEAR_Exception
  169.      */
  170.     public function liteautoExec($tableName = null,
  171.                                  $tableFields = null,
  172.                                  $dataValues = null,
  173.                                  $queryType = self::DB_AUTOQUERY_INSERT,
  174.                                  $crypt = true,
  175.                                  $whereString = null)
  176.     {
  177.         if ($this->key === null) {
  178.             throw new PEAR_Exception('You need to specify an encryption key', -1);
  179.         }
  180.  
  181.         if ($crypt === true) {
  182.             foreach($dataValues as $matrix => &$value) {
  183.                 $this->matrix->setkey($this->key);
  184.                 $this->matrix->crypt($value);
  185.             }
  186.         }
  187.  
  188.         if (empty($tableName)) {
  189.             throw new PEAR_Exception('You need to specify a table', -1);
  190.         }
  191.  
  192.         if (empty($tableFields)) {
  193.             throw new PEAR_Exception('You need to specify the table fields', -1);
  194.         }
  195.  
  196.         if (empty($dataValues)) {
  197.             throw new  PEAR_Exception('You need to specify the values', -1);
  198.         }
  199.  
  200.         if (!is_array($tableFields)) {
  201.             $tableFields = array($tableFields);
  202.         }
  203.  
  204.         if (!is_array($dataValues)) {
  205.             $tableFields = array($dataValues);
  206.         }
  207.  
  208.         $numberFields = count($tableFields);
  209.         if ($numberFields != count($dataValues)) {
  210.             $multiData = false;
  211.             if (!$multiData) {
  212.                 // it's not multidata, so the array supplied is no good
  213.                 throw new PEAR_Exception(
  214.                     'The array supplied as values does not match the number '.
  215.                     'of fields you have provided', -1
  216.                 );
  217.             }
  218.         }
  219.  
  220.         if ($queryType == self::DB_AUTOQUERY_INSERT) {
  221.             $queryString = 'INSERT INTO ' . $tableName
  222.                          . ' (#fields#) VALUES (#values#)';
  223.             $fieldsString = join(',', $tableFields);
  224.             $valuesString = join(
  225.                 self::DB_STRING_DELIMITER . ',' . self::DB_STRING_DELIMITER,
  226.                 self::safeQuote($dataValues)
  227.             );
  228.  
  229.             if ($this->debug == true) print_r($dataValues);
  230.             $queryString = str_replace(
  231.                 array(
  232.                     '#fields#',
  233.                     '#values#'
  234.                 ),
  235.                 array($fieldsString,
  236.                     self::DB_STRING_DELIMITER
  237.                     . $valuesString
  238.                     . self::DB_STRING_DELIMITER
  239.                 ),
  240.                 $queryString
  241.             );
  242.         } elseif ($queryType == self::DB_AUTOQUERY_UPDATE) {
  243.             $queryString = 'UPDATE ' . $tableName . ' SET #setFields#';
  244.  
  245.             for ($i = 0; $i < $numberFields; $i++) {
  246.                 $setFields[] = $tableFields[$i] . '='
  247.                              . self::DB_STRING_DELIMITER
  248.                              . self::safeQuote($dataValues[$i])
  249.                              .self::DB_STRING_DELIMITER;
  250.             }
  251.  
  252.             $queryString = str_replace(
  253.                 '#setFields#', join(',', $setFields), $queryString
  254.             );
  255.  
  256.             if (!empty($whereString)) {
  257.                 $queryString .= ' WHERE ' . $whereString;
  258.             }
  259.         } else {
  260.             // Unknown queryType
  261.             throw new PEAR_Exception(
  262.                 'Unknown query type, please use ' .
  263.                 'DB_Sqlite_Tools_DBC::DB_AUTOQUERY_INSERT or '.
  264.                 'DB_Sqlite_Tools_DBC::DB_AUTOQUERY_UPDATE', -1
  265.             );
  266.         }
  267.  
  268.         $r = $this->liteQuery($queryString);
  269.         if ($r == false) {
  270.             throw new PEAR_Exception(
  271.                 $this->liteLastError($queryString), -1
  272.             );
  273.         }
  274.     }
  275.  
  276.     // }}}
  277.     // {{{ safeQuote()
  278.  
  279.     /**
  280.      * Safety value(s) for query execution.
  281.      *
  282.      * @param mixed $mixedVar A string value or an associative array contain
  283.      *                        list of values.
  284.      *
  285.      * @return mixed Result
  286.      */
  287.     public static function safeQuote($mixedVar) {
  288.         if (is_array($mixedVar)) {
  289.             foreach($mixedVar as $i => &$val) {
  290.                 $val = self::safeQuote($val);
  291.             }
  292.         } else {
  293.             if (get_magic_quotes_gpc()) {
  294.                 $mixedVar = stripslashes($mixedVar);
  295.             }
  296.             return sqlite_escape_string($mixedVar);
  297.         }
  298.         return $mixedVar;
  299.     }
  300.  
  301.     // }}}
  302.     // {{{ liteConnect()
  303.  
  304.     /**
  305.      * Connects to the Sqlite DB.
  306.      *
  307.      * @param string $db The database name.
  308.      *
  309.      * @return bool TRUE on succeed.
  310.      * @throws PEAR_Exception
  311.      */
  312.     public function liteConnect($db)
  313.     {
  314.         $this->debug('Connecting to' .  $db . "\n");
  315.  
  316.         $obj = false;
  317.  
  318.         try {
  319.             $obj = $this->dbobj = new SQLiteDatabase($db);
  320.         } catch (Exception $obj) {
  321.             throw new PEAR_Exception(
  322.                 'Cannot open database: errorcode'. $obj->getCode() . ': '
  323.                  . $obj->getMessage() . "\n\t" .
  324.                  ' in ' . $obj->getFile() . ': ' . $obj->getLine() . "\n"
  325.             );
  326.         }
  327.         return true;
  328.     }
  329.  
  330.     // }}}
  331.     // {{{ liteQuery()
  332.  
  333.     /**
  334.      * Executes the query and return the results objects if available.
  335.      *
  336.      * @param string $sql Query to execute.
  337.      *
  338.      * @return true
  339.      */
  340.     public function liteQuery($sql)
  341.     {
  342.         $this->debug(print_r($sql, true));
  343.  
  344.         $results = $this->dbobj->query("$sql");
  345.         if ($results != false) {
  346.             $this->result = $results->fetchObject();
  347.           
  348.     }
  349.  
  350.         return true;
  351.     }
  352.  
  353.     // }}}
  354.     // {{{ liteAutoFetch()
  355.  
  356.     /**
  357.      * Executes the query and return the decrypted results single object
  358.      * if available.
  359.      *
  360.      * @param string $sql SQL to execute.
  361.      * @param string $crypt Default true, decrypts the result.
  362.      *
  363.      * @return object Result
  364.      * @throws PEAR_Exception
  365.      * @see DB_Sqlite_Tools_DBC::$result
  366.      */
  367.     public function liteAutoFetch($sql, $crypt = true)
  368.     {
  369.         if ($this->key === null) {
  370.             throw new PEAR_Exception('You need to specify an encryption key', -1);
  371.         }
  372.  
  373.         $this->debug(print_r($sql, true));
  374.  
  375.         $results = $this->dbobj->query("$sql");
  376.         if ($results != false) {
  377.             $this->result = $results->fetchObject();
  378.         }
  379.  
  380.         foreach($this->result as $propertyName => &$value) {
  381.             if (!is_numeric($value)) {
  382.                 if ($crypt == true) {
  383.                     $this->matrix->setkey($this->key);
  384.                     $this->matrix->decrypt($value);
  385.                 }
  386.             }
  387.         }
  388.  
  389.             $this->debug(print_r($this->result, true));
  390.  
  391.         return $this->result;
  392.     }
  393.  
  394.     // }}}
  395.     // {{{ liteAll()
  396.  
  397.     /**
  398.      * Executes the query and return the decrypted results ALL the objects
  399.      * in an array.
  400.      *
  401.      * @param string $sql SQL to execute.
  402.      * @param string $crypt Default true, decrypts the result.
  403.      *
  404.      * @return object Result
  405.      * @throws PEAR_Exception
  406.      * @see DB_Sqlite_Tools_DBC::$result
  407.      */
  408.     public function liteAll($sql, $crypt = true)
  409.     {
  410.         if ($this->key === null) {
  411.             throw new PEAR_Exception('You need to specify an encryption key',-1);
  412.         }
  413.  
  414.         $this->debug(print_r($sql, true));
  415.  
  416.         $results = $this->dbobj->query("$sql");
  417.         if ($results != false) {
  418.             $this->result = array();
  419.             while ($result = $results->fetchObject()) {
  420.                 foreach($result as $index => &$value) {
  421.                     if (!is_numeric($value)) {
  422.                         if ($crypt == true) {
  423.                             $this->matrix->setkey($this->key);
  424.                             $this->matrix->decrypt($value);
  425.                         }
  426.                     }
  427.                 }
  428.                 $this->result[] = $result;
  429.             }
  430.         }
  431.  
  432.         $this->debug(print_r($this->result, true));
  433.         
  434.         return $this->result;
  435.     }
  436.  
  437.     // }}}
  438.     // {{{ liteLastError()
  439.  
  440.     /**
  441.      * returns the last DB error string.
  442.      *
  443.      * @param string $queryString The query string.
  444.      *
  445.      * @return string
  446.      */
  447.     public function liteLastError($queryString = '')
  448.     {
  449.         return sqlite_error_string($this->dbobj->lastError()) . "\n"
  450.                . $queryString;
  451.     }
  452.  
  453.     // }}}
  454.     // {{{ liteLastID()
  455.  
  456.     /**
  457.      * Returns the last inserted row id.
  458.      *
  459.      * @return int
  460.      */
  461.     public function liteLastID ()
  462.     {
  463.         return $this->dbobj->lastInsertRowid();
  464.     }
  465.  
  466.     // }}}
  467.     // {{{ debug()
  468.  
  469.     /**
  470.      * Set and display debug message if debug is On.
  471.      *
  472.      * @param string $msg Debug message.
  473.      */
  474.     private function debug($msg)
  475.     {
  476.         if ($this->debug) {
  477.             // Web context.
  478.             if (isset($_SERVER['REQUEST_URI'])) {
  479.                 $msg = nl2br($msg);
  480.             }
  481.  
  482.             echo 'DB_Sqlite_Tools debug: ' . $msg;
  483.         }
  484.     }
  485.  
  486.     // }}}
  487.     // {{{ Destructor
  488.  
  489.     /**
  490.      * Destructor.
  491.      */
  492.     public function __destruct()
  493.     {
  494.         unset($this->dbobj);
  495.     }
  496.  
  497.     // }}}
  498. }
  499.  
  500. // }}}
  501.  
  502. /*
  503.  * Local variables:
  504.  * mode: php
  505.  * tab-width: 4
  506.  * c-basic-offset: 4
  507.  * c-hanging-comment-ender-p: nil
  508.  * End:
  509.  */
  510. ?>
  511.