Source for file OCSP_DB_mySQL.phpclass

Documentation is available at OCSP_DB_mySQL.phpclass

  1. <?php
  2. /**
  3.   * Class file mySQL.phpclass
  4.   *
  5.   * @project    Open CSP-Management
  6.   * @package    dbms
  7.   * @category   mysql
  8.   *
  9.   * @author     Peter Krebs <pitlinz@users.sourceforge.net>
  10.   * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
  11.   *
  12.   * @todo       move the function in $PROJECT['PHPINCPATH']."db/mySQL.phpinc";
  13.   *              into the class to be able to server several database at once
  14.   *
  15.   * @version    pk-03-10-25
  16.   * @version    pk-04-12-21 $GLOBALS['PROJECT'] -> $GLOBALS['OCSP']
  17.   *
  18.   ***/
  19.  
  20. if (!interface_exists('INFA_OCSP_DBOBJ'))
  21. {
  22.     require dirname(__FILE___OCSP_DIRSEP_ "INFA_OCSP_DBOBJ.phpclass";
  23. }
  24.  
  25. require_once dirname(__FILE___OCSP_DIRSEP_ "OCSP_DB.phpclass";
  26. require_once dirname(__FILE___OCSP_DIRSEP_ "OCSP_CURSOR_mySQL.phpclass";
  27.  
  28.  
  29. /**
  30.   * handels  mySQL database connections / operations
  31.   *
  32.   * @project    Open CSP-Management
  33.   * @package    dbms
  34.   * @category   mysql
  35.   *
  36.   * @author     Peter Krebs <pitlinz@users.sourceforge.net>
  37.   * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
  38.   *
  39.   *  Version History:
  40.   *  ------------------------------------------------
  41.   *  pk-03-10-21
  42.   *  pk-03-10-24
  43.   *  pk-03-10-25
  44.   * @version pk-03-12-11
  45.   * @version pk-07-04-12 parent class OCSP_DB added
  46.   *
  47.   * @version pk-07-06-13
  48.   *
  49.   ***/
  50. class OCSP_DB_mySQL 
  51.     extends OCSP_DB 
  52.     implements INFA_OCSP_DBOBJ
  53. {
  54.  
  55.     /**
  56.      * array of already seen tables definitions
  57.      *
  58.      * @staticvar array $dbTableDefinitions 
  59.      */
  60.     static $dbTableDefinitions array();    
  61.  
  62.  
  63.     
  64.     
  65.     /**
  66.       * @var resource $myConnId 
  67.       * @access private
  68.       ***/
  69.     private $myConnId      ="";
  70.  
  71.     // ---------------------------------------------------------------------------
  72.     // factory / construct
  73.     // ---------------------------------------------------------------------------
  74.     
  75.     
  76.     /**
  77.      * disconnect from the database
  78.      *
  79.      */    
  80.     function disconnect(
  81.     {
  82.         @mysql_close($this->myConnId);
  83.         $this->myConnId      =False;
  84.         $this->isConnected   =False;
  85.         $this->isInit        =False;
  86.     }
  87.         
  88.     // ---------------------------------------------------------------------------
  89.     // getter / setter
  90.     // ---------------------------------------------------------------------------    
  91.  
  92.     
  93.     
  94.     /**
  95.      * returns the dbType
  96.      * 
  97.      * @return string 
  98.      */
  99.     public function getDBType()
  100.     {
  101.         return 'mySQL';
  102.     }    
  103.     
  104.  
  105.  
  106.     // ##############################################
  107.     /**
  108.       * connects to the database
  109.       *
  110.       * @param string $conffile file containing the database configuration
  111.       * @param boolean $asPublic use public user from the conf
  112.       * @param boolean $asAdmin use the admin user from the conf
  113.       * @param boolean $debug 
  114.       *
  115.       * @global $OCSP_CONF 
  116.       * @global $OCSP_OBJ 
  117.       *
  118.       * @returns boolean
  119.       * @access public
  120.       *
  121.       * @version pk-07-06-01
  122.       * @version pk-08-10-15
  123.       * 
  124.       */
  125.     function connect($conffile="",$asPublic=True,$asAdmin=False,$debug=False{
  126.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::connect()");
  127.         //global $OCSP_CONF;
  128.  
  129.         if (!empty($conffile&& file_exists($conffile))
  130.         {
  131.             include $conffile;
  132.         else {
  133.             $str_projPath OCSP_OBJ::getConf('PROJECTPATH');
  134.             if (!empty($conffile&& file_exists($str_projPath $conffile))
  135.             {
  136.                 $conffile $str_projPath $conffile;
  137.             else 
  138.                 // find conffile
  139.                 do {
  140.                     if (pcf_is_instance_of(OCSP_OBJ::currentUser(),'OCSP_USER'))
  141.                     {
  142.                         $conffile=OCSP_OBJ::currentUser()->getDBConfFile();
  143.                         if (file_exists($conffile))
  144.                         {
  145.                             break;
  146.                         }
  147.                     }
  148.                     
  149.                     if ($conffile OCSP_CONF::getInstance()->getValue('DBCONFFILE'))
  150.                     {
  151.                         if (file_exists($conffile))
  152.                         {
  153.                             break;                            
  154.                         }
  155.                         
  156.                         if (file_exists($str_projPath $conffile))
  157.                         {
  158.                             $conffile $str_projPath $conffile;
  159.                             break;
  160.                         }
  161.  
  162.                         if (file_exists($str_projPath "config/" $conffile))
  163.                         {
  164.                             $conffile $str_projPath "config/" $conffile;
  165.                             break;
  166.                         }
  167.                         
  168.                         // finaly try mysql (default)
  169.                         if (file_exists($str_projPath "config/mySQL.phpconf"))                        
  170.                         {
  171.                             $conffile $str_projPath "config/mySQL.phpconf";
  172.                             break;
  173.                         }
  174.  
  175.                         throw new Exception('no db confinguration file found (' . __FILE__ . " Line: " . __LINE__);
  176.                     }
  177.                 while (False);                
  178.             }
  179.             include $conffile;
  180.         // if (!empty($conffile) && file_exists($conffile)) -> else
  181.         
  182.         if ($asPublic{
  183.             $s_key="PUBLIC";
  184.         else if ($asAdmin{
  185.             $s_key="ADMIN";
  186.         else {
  187.             $s_key="USR";
  188.         }
  189.  
  190.         if (!isset($DBCONF[$s_key]['USR']))
  191.         {
  192.             die(get_class($this)." Line: ".__LINE__." ERROR no \$DBCONF[".$s_key."] array in ".basename($conffile)." ");
  193.         }
  194.  
  195.         $this->myServer =$DBCONF['SERVER'];
  196.         $this->myDB     =$DBCONF['DATABASE'];
  197.  
  198.         if ($debugechoDebugLine(__FILE__,__LINE__,"Connecting to ".$this->myServer." as ".$DBCONF[$s_key]['USR']." ($key)");
  199.  
  200.         if ($this->myConnId=mysql_pconnect($this->myServer,$DBCONF[$s_key]['USR'],$DBCONF[$s_key]['PWD'])) {
  201.             $this->isConnected=True;
  202.         else {
  203.             die(get_class($this)." Line: ".__LINE__." ERROR conffile ".basename($conffile)." ERROR connecting to ".$this->myServer." as $dbUser");
  204.         }
  205.  
  206.         if (!@mysql_select_db($this->myDB,$this->myConnId)) {
  207.             die(get_class($this)." Line: ".__LINE__." ERROR conffile ".basename($conffile)." using DB ".$this->myDB." as $dbUser");
  208.         }
  209.  
  210.         $this->iam_connected=True;
  211.         $this->iam_initialized=True;
  212.  
  213.         //echoDebugLine(__FILE__,__LINE__,get_class($this).": estabilshed a database connection");
  214.  
  215.         if ($debugecho "<p>done connecting</p>";
  216.         return True;
  217.     }
  218.  
  219.     ##############################################
  220.     function publicConnect($conffile="",$keepConnection=True{
  221.         if ($this->isConnected(&& $keepConnection)
  222.         {
  223.             return True;
  224.         }
  225.         return $this->connect($conffile,True,False,$debug);
  226.     }
  227.  
  228.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  229.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  230.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  231.  
  232.     /**
  233.       * initiates the connect
  234.       * this is not required for mysql
  235.       *
  236.       * @returns boolean
  237.       *
  238.       ***/
  239.     function initConn({
  240.         # not used for mySQL
  241.         $this->iam_initialized=True;
  242.         return True;
  243.     }
  244.  
  245.     /**
  246.       * returns an array with the main parts of an select
  247.       * the returned array has the following indexes
  248.       *
  249.       * - ['SELECT']
  250.       * - ['FROM']
  251.       * - ['WHERE']
  252.       * - ['ORDER']
  253.       * - ['GROUP']
  254.       * - ['LIMIT']
  255.       *
  256.       *
  257.       * @param string $query 
  258.       * @param boolean $debug 
  259.       *
  260.       * @return array 
  261.       *
  262.       * @since pk-06-09-28
  263.       *
  264.       ***/
  265.     function getQueryArray($query,$debug=False{
  266.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_MYSQL::getQueryArray()");
  267.  
  268.         $a_ret=array();
  269.         $a_elements=explode(" ",$query);
  270.  
  271.         if (strtoupper($a_elements[0]!= "SELECT"{
  272.             $s_curKey=$a_elements[0];
  273.         }
  274.  
  275.         foreach ($a_elements as $s_elem{
  276.             switch(strtoupper($s_elem)) {
  277.                 case "SELECT":
  278.                     $s_curKey='SELECT';
  279.                     $a_ret[$s_curKey]="";
  280.                     break;
  281.                 case "FROM":
  282.                     $s_curKey='FROM';
  283.                     $a_ret[$s_curKey]="";
  284.                     break;
  285.                 case "WHERE":
  286.                     $s_curKey='WHERE';
  287.                     $a_ret[$s_curKey]="";
  288.                     break;
  289.                 case "ORDER":
  290.                     $s_curKey='ORDER BY';
  291.                     $a_ret[$s_curKey]="";
  292.                     break;
  293.                 case "GROUP":
  294.                     $s_curKey='GROUP BY';
  295.                     $a_ret[$s_curKey]="";
  296.                     break;
  297.                 case "BY":
  298.                     // do nothing
  299.                     break;
  300.                 case "HAVING":
  301.                     $s_curKey='HAVING';
  302.                     $a_ret[$s_curKey]="";
  303.                     break;
  304.                 case "LIMIT":
  305.                     $s_curKey='LIMIT';
  306.                     $a_ret[$s_curKey]="";
  307.                     break;
  308.                 default:
  309.                     if (!empty($s_curKey)) {
  310.                         $a_ret[$s_curKey].=$s_elem." ";
  311.                     }
  312.             }
  313.         }
  314.  
  315.         return $a_ret;
  316.     }
  317.  
  318.  
  319.     /**
  320.       * checks a query string if it's save to use
  321.       *
  322.       * @param string $aQuery 
  323.       * @param int $type PQT_[querytype]
  324.       * @param boolean $debug 
  325.       *
  326.       * @returns string
  327.       *
  328.       * @todo only PQT_SELECT and PQT_UNION are checked for the moment
  329.       *
  330.       * @version pk-04-11-12
  331.       *
  332.       ***/
  333.     function checkQuery($aQuery,$type=PQT_SELECT,$debug=False{
  334.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::checkQuery($aQuery,$type)");
  335.  
  336.         if (($type==PQT_SELECT|| ($type==PQT_UNION)) {
  337.             if (strstr($aQuery,";")) {  // disable ; in query
  338.                 $tmp=explode(";",$aQuery);
  339.                 $ret=$tmp[0];
  340.             else {
  341.                 $ret=$aQuery;
  342.             }
  343.             if (!strstr(trim(strtoupper($ret)),strtoupper($type)) === {
  344.                 ocsp_logError(__FILE__,__LINE__,"$type not the first statement");
  345.                 return NULL;
  346.             }
  347.         else {
  348.             $ret=$aQuery;
  349.         }
  350.         return $ret;
  351.     }
  352.  
  353.     /**
  354.       * echos the last error
  355.       *
  356.       * @param string $msg  addintinal message to echo
  357.       *
  358.       ***/
  359.     function errorMsg($msg=""{
  360.         echo "<pre>mySQL-ERROR$msg\n".$this->getErrorNo().": ".$this->getErrorMsg()."<pre>";
  361.     }
  362.  
  363.  
  364.     /**
  365.       * returns the last mySQL error message
  366.       *
  367.       * @returns string
  368.       *
  369.       * @since pk-05-08-08
  370.       ***/
  371.     function getErrorMsg({
  372.         return mysql_error($this->myConnId);
  373.     }
  374.  
  375.     /**
  376.       * returns the last mySQL error nr
  377.       *
  378.       * @returns int
  379.       *
  380.       * @since pk-05-08-08
  381.       ***/
  382.     function getErrorNo({
  383.         return mysql_errno($this->myConnId);
  384.     }
  385.  
  386.  
  387.  
  388.     /**
  389.       * opens a cursor for a query
  390.       *
  391.       * @param string   $aQuery     the sql query
  392.       * @param boolean     $secMode 
  393.       * @param boolean     $withErrMsg 
  394.       * @param boolean     $autoFree 
  395.       * @param boolean     $useBuffer 
  396.       *
  397.       * @returns OCSP_CURSOR_mySQL
  398.       *
  399.       ***/
  400.     function query($aQuery="",$secMode=True,$withErrMsg=False,$autoFree=True,$useBuffer=True{
  401.         if ($secMode{
  402.            $aQuery $this->checkQuery($aQuery,PQT_SELECT);
  403.         }
  404.         if ($cursor new OCSP_CURSOR_mySQL($this->myConnId,$aQuery,$autoFree,$useBuffer)) {
  405.             return $cursor;
  406.         else {
  407.             if ($withErrMsg{
  408.                 $this->errorMsg("query: \n$aQuery");
  409.             }
  410.             return False;
  411.         }
  412.     }
  413.  
  414.     ####################
  415.  
  416.     /**
  417.       * returns (a column) of the first row match
  418.       *
  419.       * if $colNr > -1 the column value at position $colNr in
  420.       * the select statement is returned (NOTE: index starts at 0)
  421.       *
  422.       * if $colNr < 0 a array is returend
  423.       * if $usNames the DB-column names are the index otherwise
  424.       * the index of the returned are is the number in the select order
  425.       *
  426.       * @param string $aQuery 
  427.       * @param int $colNr 
  428.       * @param boolean $withErrMsg 
  429.       * @param boolean $useNames 
  430.       * @param boolean $secMode 
  431.       * @param boolean $debug 
  432.       *
  433.       * @returns mixed
  434.       *
  435.       ***/
  436.     function quickQuery($aQuery,$colNr=-1,$withErrMsg=False,$useNames=True,$secMode=True,$debug=False{
  437.         if ($debugecho "<p><b>DB_mySQL::quickQuery(\$aQuery,$colNr,$withErrMsg,$useNames,$secMode,$debug)</b> (".get_class($this).")</p>";
  438.         if ($secMode{
  439.            $aQuery $this->checkQuery($aQuery,PQT_SELECT,$debug);
  440.         }
  441.         $ret=NULL;
  442.         if ($debugecho "<blockquote><pre>quickQuery$aQuery</pre></blockquote>";
  443.  
  444.         if ($cursor new OCSP_CURSOR_mySQL($this->myConnId,$aQuery,True,False)) {
  445.            if ($colNr > -1{
  446.                $ret=$cursor->fetchArrayNum($colNr);
  447.            else if (!$useNames{
  448.                $ret=pcf_array_copy($cursor->fetchArrayNum());
  449.            else {
  450.                $ret=pcf_array_copy($cursor->fetchArrayFld());
  451.            }
  452.            $cursor->free();
  453.            unset($cursor);
  454.         else {
  455.             $ret=False;
  456.             if ($withErrMsg{
  457.                 $this->errorMsg("quickQuery: \n$aQuery");
  458.             }
  459.         }
  460.  
  461.         if ($debugecho "<blockquote>RETURNS: <pre>".pcf_print_r($ret)."</pre></blockquote>";
  462.         return $ret;
  463.     }
  464.  
  465.     ####################
  466.  
  467.     /**
  468.       * returns an array of table rows
  469.       *
  470.       * if $keyFld == $valueFld
  471.       * a simple array is returned
  472.       *    ( $array[]=$value )
  473.       *
  474.       * if $keyFld != $valueFld
  475.       * a simple array is returned where $keyFld is used as index
  476.       *    ( $array[$key]=$value )
  477.       *
  478.       * if $valueFld == -1
  479.       * a named 2 dimensonal array is returned
  480.       *     ( $array[$key]=$row )
  481.       *
  482.       * if $keyFld == -1 && $valueFld == -1
  483.       * a 2 dimensonal array is returned
  484.       *     ( $array[]=$row )
  485.       *
  486.       * @param string $aQuery   a sql select statement
  487.       * @param int $keyFld      index of the key field in the select result (starts at 0)
  488.       * @param int $valueFld    index of the value field in the select result (starts at 0)
  489.       * @param boolean $secMode check query whith DB_mySQL::checkQuery()
  490.       * @param boolean $debug   show debug info
  491.       *
  492.       * @returns array
  493.       *
  494.       */
  495.     function queryArray($aQuery,$keyFld=0,$valueFld=0,$secMode=True,$debug=False
  496.     {
  497.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::queryArray()","",0);
  498.         if ($secMode{
  499.            $aQuery $this->checkQuery($aQuery,PQT_SELECT,$debug);
  500.         }
  501.  
  502.         if ($debugechoDebug(__FILE__,"<p>Query:<br/>".$aQuery."</p>");
  503.         $ret=False;
  504.         if ($cursor new OCSP_CURSOR_mySQL($this->myConnId,$aQuery,True,False)) {
  505.             if ($valueFld == -1{
  506.                 if ($debugechoDebugLine(__FILE__,__LINE__,"returning row array");
  507.                 while ($row=$cursor->fetchArray()) {
  508.                     if ($debugechoDebugLine(__FILE__,__LINE__,"Row: <pre>".print_r(pcf_array_strIdx($row),True)."</pre>");
  509.                     unset($row['arrKey']);
  510.                     if ($keyFld > -1)
  511.                         $ret[$row[$keyFld]]=pcf_array_strIdx($row);
  512.                     else
  513.                         $ret[]=pcf_array_strIdx($row);
  514.                 }
  515.             else if ($keyFld == $valueFld{
  516.                 while ($val=$cursor->fetchArrayNum($keyFld)) {
  517.                     if ($debugechoDebug(__FILE__,"<p>Value$val</p>");
  518.                     $ret[]=$val;
  519.                 }
  520.             else {
  521.                 while ($row=$cursor->fetchArray()) {
  522.                     if ($debugecho $row[$keyFld]."==".$row[$valueFld]."<br />";
  523.                     $ret[$row[$keyFld]]=$row[$valueFld];
  524.                 }
  525.             }
  526.         else {
  527.             $this->errorMsg("queryArray: \n$aQuery");
  528.             if ($debugechoDebugLine(__FILE__,__LINE__,"$aQuery failed \n returning False");
  529.             return False;
  530.         }
  531.         return $ret;
  532.     }
  533.  
  534.  
  535.     /**
  536.       * generates a query and returns an array of the resultset
  537.       *
  538.       * limit <> a multidimensional array is returned (see queryArray)
  539.       * if limit = 1 a single array is returned (see quickQuery)
  540.       *
  541.       * conditions:
  542.       *     if the column starts with a ? the value is assumed to be an sql statement
  543.       *     else  column=slashedvalue(value) is added to the query
  544.       *
  545.       * @param string $aTable (the table name)
  546.       * @param array $conditions (array(COLUMN => VALUE)) if VALUE does not starts with a '¿' t
  547.       * @param int $offset 
  548.       * @param int $limit (0 is unlimeted)
  549.       * @param string $orderBy (comma seperated list of fields to order)
  550.       * @param boolean $debug 
  551.       *
  552.       * @return array 
  553.       * @access public
  554.       *
  555.       * @since pk-07-06-29
  556.       * @version pk-07-09-08 '?' coll added
  557.       *
  558.       */
  559.     function getArray($aTable,$conditions=NULL,$offset=0,$limit=0,$orderBy="",$debug=False)
  560.     {
  561.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::getArray($aTable)");
  562.  
  563.         $str_query="SELECT * FROM ".$aTable;
  564.         if ($conditions && sizeof($conditions))
  565.         {
  566.             $str_whereAnd=" WHERE ";
  567.             foreach($conditions as $str_col => $m_val)
  568.             {
  569.                 if (substr($str_col,0,1)=='?'// <pk-07-09-08>
  570.                 {
  571.                     //$str_query.=$str_whereAnd.substr($m_val,1);
  572.                     // <pk-08-01-25 why substr ????
  573.                     $str_query .= $str_whereAnd $m_val;
  574.                 else {
  575.                     $str_query.=$str_whereAnd.$str_col."=".$this->qs_getSlashedValue($m_val);
  576.                 }
  577.                 $str_whereAnd=" AND ";
  578.             }
  579.         }
  580.  
  581.         if (!empty($orderBy))
  582.         {
  583.             $str_query.=" ORDER BY ".$orderBy;
  584.         }
  585.  
  586.         if ($limit == 1)
  587.         {
  588.             return $this->quickQuery($str_query,-1,False,True,True,$debug);
  589.         else if ($limit 1{
  590.             $str_query.=" LIMIT ".intval($offset).",".intval($limit);
  591.         }
  592.  
  593.         return $this->queryArray($str_query,-1,-1,True,$debug);
  594.     }
  595.  
  596.     ####################
  597.  
  598.     function freeCursor($aCursor{
  599.         if ($aCursor{
  600.             $aCursor->free();
  601.         }
  602.     }
  603.  
  604.     ####################
  605.  
  606.     function numOfRows($aCursor{
  607.         return $aCursor->numOfRows();
  608.     }
  609.  
  610.     ####################
  611.  
  612.     function fetchArray($aCursor,$useNames=True{
  613.         if ($aCursor{
  614.             if ($useNames{
  615.                return $aCursor->fetchArrayFld();
  616.             else {
  617.                return $aCursor->fetchArray();
  618.             }
  619.         }
  620.         return False;
  621.     }
  622.  
  623.     ####################
  624.  
  625.     /**
  626.       * converts php variables to db save values adds slashes and " to enclose strings
  627.       *
  628.       * special values:
  629.       * - datetime,date,time: #NOW #NOW_DATE #NOW_TIME
  630.       * - timestamp:          NOW() CURRENT_TIMESTAMP
  631.       *
  632.       * @param string   $aType  database type
  633.       * @param mixed    $aValue column value
  634.       * @param int      $maxLen max Field Len
  635.       * @param boolean     $debug  show debug info
  636.       *
  637.       * @returns mixed
  638.       *
  639.       * @version pk-05-01-13 tinyint added
  640.       * @version pk-05-05-18 bugfix timestamp
  641.       * @version pk-05-11-25 special value added
  642.       * @version pk-06-11-28 double added changes in default
  643.       *
  644.       ***/
  645.     function checkValue($aType,$aValue,$maxLen=255,$debug=False{
  646.         if ($debugecho "<p><b>DB_mySQL::checkValue($aType,".htmlspecialchars(substr($aValue,0,10))."...,$maxLen)</b></p>";
  647.         switch (strtolower($aType)) /* <pk-05-01-13 strtolower() added /> */
  648.             case "tinyint"/* <pk-05-01-13 /> */
  649.             case "int":
  650.                  if (($aValue === False|| ($aValue === 0|| ($aValue === "0")) return 0;
  651.                         // NOTE === type compare because empty("0") returns True
  652.                  if (empty($aValue)) return $this->qs_getNullStmt();;
  653.                  return intval($aValue);
  654.             /*
  655.                 strings can be treaten as blob because
  656.                 mysql cuts the string if to it's to long
  657.             case "string":
  658.                  if (!strlen($aValue)) return "NULL";
  659.                  return "'".substr(addslashes($aValue),0,$maxLen)."'";
  660.             */
  661.             case "float"// <pk-06-09-06 />
  662.             case "double"// <pk-06-11-28 />
  663.                 if (strlen(strval($aValue)) == 0return $this->qs_getNullStmt();
  664.                 return doubleval($aValue)// <pk-06-10-10 />
  665.             case "blob":
  666.                 if (!strlen($aValue)) return "NULL";
  667.                 return "\"".pcf_escape_doubleQuote($aValue)."\"";  /* <pk-04-07-23/> */
  668.             case "timestamp"// <pk-05-10-04>
  669.                 if (empty($aValue)) {
  670.                     if ($debugecho "<p>Timestamp is NULL -> return 0 to avoid NOW()<p>";
  671.                     return 0;
  672.                 else if ((strtoupper($aValue)=="NOW()"|| (strtoupper($aValue)=="CURRENT_TIMESTAMP")) {
  673.                     if ($debugecho "<p>Returning: ".$this->qs_getNowStmt()."</p>";
  674.                     return $this->qs_getNowStmt()// <pk-05-05-18 />
  675.                 }
  676.                 $s_query="SELECT DATE_FORMAT(".$this->qs_getSlashedValue($aValue).",'%Y%m%d%H%i%s')";
  677.                 if ($debugecho "<p>Checking Timestamp$aValue -- ".$this->quickQuery($s_query,0)."</p>";
  678.                 if (($s_dbValue=$this->quickQuery($s_query,0)) && (strtoupper($s_dbValue!= "NULL")) {
  679.                     if ($debugecho "<p>DBVALUE$s_dbValue</p>";
  680.                     return $s_dbValue;
  681.                 else {
  682.                     if ($debugecho "<p>Returning: ".$this->qs_getNullStmt()."</p>";
  683.                     return $this->qs_getNullStmt();
  684.                 }
  685.  
  686.             case "date":        // <pk-05-11-25>
  687.             case "time":        // <pk-05-11-25>
  688.             case "datetime":    // <pk-05-11-25>
  689.                 if ($aValue=="NULL"// <pk-06-08-18>
  690.                     return "NULL";
  691.                 if ($aValue=="#NOW")
  692.                     return "'".date('Y-m-d H:i:s',time())."'";
  693.                 if ($aValue=="\$#NOW_DATE\$")
  694.                     return "'".date('Y-m-d',time())."'";
  695.                 if ($aValue=="#NOW_TIME")
  696.                     return "'".date('H:i:s',time())."'";
  697.  
  698.             default:
  699.                  if ((empty($aValue)) && (strval($aValue!== '0'))     // a string with only one 0 also is empty //<pk-06-11-28 />strval added
  700.                     return $this->qs_getNullStmt();
  701.                  else
  702.                     return "\"".pcf_escape_doubleQuote($aValue)."\"";  /* <pk-04-07-23/> */
  703.         }
  704.     }
  705.  
  706.     /**
  707.       * logs sql command (SELECTS ARE NOT LOGGED)
  708.       *
  709.       * if !empty($GLOBALS['PROJECT']['DBLOG'])
  710.       *     the query is add to:
  711.       *     $GLOBALS['PROJECT']['DBLOG'] logfile
  712.       *
  713.       * if ((!empty($GLOBALS['PROJECT']['DBADMINLOG'])) && (strpos($mystring, $findme) !== False))
  714.       *     the query is add to:
  715.       *     $GLOBALS['PROJECT']['DBADMINLOG'] logfile
  716.       *
  717.       * @param strint $aQuery the query
  718.       *
  719.       * @version pk-03-10-18
  720.       ***/
  721.     function logCmd($aQuery=""{
  722.         if (!empty($GLOBALS['PROJECT']['DBLOG'])) {
  723.             $aQuery=str_replace("\r","",$aQuery);
  724.             $aQuery=str_replace("\n","\\n",$aQuery);
  725.             if ($logFile=fopen($GLOBALS['PROJECT']['DBLOG'],'a')) {
  726.                 if (isset($_SESSION['USER']&& (is_object($_SESSION['USER']))) {
  727.                     fwrite($logFile,time()."\t".$_SESSION['USER']->userId."\t".$aQuery."\n");
  728.                 else {
  729.                     fwrite($logFile,time()."\t0\t".$aQuery."\n");
  730.                 }
  731.                 fclose($logFile);
  732.             }
  733.         }
  734.     }    
  735.  
  736.     /**
  737.       * executes a sql cmd
  738.       *
  739.       * @param string $aCmd     the cmd
  740.       * @param boolean $debug    show debug info
  741.       * @param boolean $secMode  test a aCmd - not used now
  742.       *
  743.       *  return mixed  mysql_query($aCmd,$this->myConnId)
  744.       *
  745.       * @todo check $aCmd in secMode
  746.       *
  747.       * @version pk-04-10-14
  748.       *
  749.       ***/
  750.     function executeCmd($aCmd,$debug=False,$secMode=True{
  751.         if ($debug{
  752.             echo "<p><b>DB_mySQL::executeCmd(\$aCmd,$debug,$secMode)</b> (".get_class($this).")</p>";
  753.             echo "<blockquote><pre style=\"font-size:9px\">".htmlspecialchars($aCmd)."</pre>";
  754.         }
  755.         if ($secMode{
  756.             /*FIX ME check $aCmd */
  757.             $aCmd $aCmd;
  758.         }
  759.  
  760.         if ($debug{
  761.             if (!($result=mysql_query($aCmd,$this->myConnId))) {
  762.                 $this->errorMsg();
  763.             }
  764.         else {
  765.             $result=@mysql_query($aCmd,$this->myConnId);
  766.         }
  767.         
  768.         if (!$result)
  769.         {
  770.             throw new Exception('MySQL Error: ' mysql_error(" (Query: " $aCmd ")");
  771.         }
  772.         
  773.         
  774.         if ($result{
  775.             $this->logCmd($aCmd);
  776.         }
  777.  
  778.         if ($debugecho "</blockquote>";
  779.         return $result;
  780.     }
  781.  
  782.  
  783.     /**
  784.       * execute an insert statement and returns True or generated auto-key
  785.       *
  786.       * inserts a new row with $aQuery
  787.       * returns the value of the auto_increment field or True
  788.       * in case of an error it returns False
  789.       *
  790.       * @param string $query a Insert statement
  791.       * @param string $aTable name of the table to insert the column
  792.       * @param string $keyfld auto-key (autoincremnt column)
  793.       * @param boolean $withLock lock table during insert (to get the key)
  794.       * @param boolean $debug show debug information
  795.       *
  796.       * @returns int    key of auto-key or True on success False in case of error
  797.       *
  798.       * @version pk-06-07-22 debug info
  799.       * @version pk-06-10-30 no lock without a keyfld
  800.       *
  801.       */
  802.     function insert($query,$aTable="",$keyfld="",$withLock=True,$debug=False{
  803.         if ($debug{
  804.             echoDebugMethod(__FILE__,get_class($this)."DB_mySQL::insert()",htmlspecialchars($query)."\n\$aTable=$aTable\n\$keyFld=$keyfld");
  805.             echo "<blockquote style=\"font-size:90%\">";
  806.         }
  807.  
  808.         if ((empty($aTable)) || (empty($keyfld))) // <pk-06-10-30 />
  809.             $withLock=False;
  810.         }
  811.  
  812.         if ($debug{
  813.            if ($withLockmysql_query("LOCK TABLES $aTable WRITE",$this->myConnId);
  814.            if (!($done=mysql_query($query,$this->myConnId))) {
  815.               $this->errorMsg();
  816.            }
  817.            if ($keyfld)    $newId=@mysql_insert_id($this->myConnId);
  818.            if ($withLockmysql_query("UNLOCK TABLES",$this->myConnId);
  819.         else {
  820.             if ($withLock@mysql_query("LOCK TABLES $aTable WRITE",$this->myConnId);
  821.             $done=@mysql_query($query,$this->myConnId);
  822.             if ($keyfld)   $newId=@mysql_insert_id($this->myConnId);
  823.             if ($withLock@mysql_query("UNLOCK TABLES",$this->myConnId);
  824.         }
  825.  
  826.         if (!$done{
  827.             if ($debugecho "<p color=red>False</p></blockquote><hr />";
  828.             return False;
  829.         }
  830.  
  831.         $this->logCmd($query);  // log only succesful commands
  832.         if ($keyfld{
  833.             if ($debugecho "<p color=green>Return$newId</p></blockquote>";
  834.             return $newId;
  835.         else {
  836.             if ($debugecho "<p color=green>Return: True</p></blockquote>";
  837.             return True;
  838.         }
  839.     }
  840.  
  841.     // ------------------------------------------------------
  842.     // data manipulation methods
  843.     // ------------------------------------------------------
  844.         
  845.     /**
  846.       * creates an insert statement and returns $this::insert()
  847.       *
  848.       * @see DB_mySQL::insert()
  849.       *
  850.       *iinserts a new row out of an array
  851.       *  returns the value of the auto_increment field or True
  852.       *  in case of an error it returns False
  853.       *
  854.       * @param string $table      name of the table to insert
  855.       * @param array $valueArr   key=>value array
  856.       * @param boolean $debug      show debug information
  857.       * @param string $idFld 
  858.       *
  859.       * @returns int    key of auto-key or True on success False in case of error
  860.       *
  861.       * @version pk-05-01-13 debuginfos
  862.       * @version pk-06-07-22 phpwarning
  863.       * @version pk-07-08-02 adding $idFld param
  864.       * 
  865.       */
  866.     function insertArray($table,$valueArr,$debug=False,$idFld=""
  867.     {
  868.         $debug=($debug $this->debugInsert);
  869.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::insertArray()","Table$table\n<pre style=\"font-size:75%;padding-left:20px;color: #FF0C0C\">".print_r($valueArr,True)."</pre>");
  870.  
  871.         if (!is_array($valueArr)) return False;
  872.         if (empty($table))        return False;
  873.  
  874.         $query="INSERT INTO $table (";
  875.         $values="(";
  876.         $sep="";
  877.  
  878.         $tblDesc=$this->getDBTblDesc($table);
  879.         if (empty($idFld))
  880.         {
  881.             while ((list($key,$fld)=each($tblDesc)) && empty($idFld)) {
  882.                 if ($fld['AUTO_INCREMENT']$idFld=$key;
  883.             }
  884.         }
  885.  
  886.         // while(list($key,$value) = each($valueArr)) {
  887.         foreach($valueArr as $key => $value{
  888.             if (isset($tblDesc[$key])) {
  889.                 if (!empty($value|| (strval($value)==="0")) // <pk-06-08-18> do not check NULL values
  890.                                                                 // the db should decide what to do if the column is not set.
  891.                     $query  .= $sep.$key;
  892.                     if ($debug 3echo "<pre>$key ($value)(".$tblDesc[$key]['TYPE'].")=".$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN'])."</pre>";
  893.                     /* <pk-05-01-13> */
  894.                     if ($debugecho "<p>$key:</p><blockquote><hr />";
  895.                     if (!isset($tblDesc[$key]['LEN'])) $tblDesc[$key]['LEN']=NULL// <pk-06-07-22 />
  896.                     $val=$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN'],$debug);
  897.                     if ($debugecho "<hr /></blockquote><pre style=\"font-size:75%\">Value: ".htmlspecialchars($val)."</pre>";
  898.                     $values.=$sep.$val;
  899.                     /* </pk-05-01-13> */
  900.                     $sep=",";
  901.                 else {
  902.                     if ($debugecho "<p>$key is NULL -&gtnot added into state</p>";
  903.                 }
  904.             else {
  905.                 if ($debugecho "<p>$key not in $table</p>";
  906.             }
  907.         }
  908.         $query .= ")  VALUES ".$values.")";
  909.         if ($debugecho "<p style=\"font-size:8px;\">$query</p></blockquote>";
  910.         return $this->insert($query,$table,$idFld,True,$debug);
  911.      }
  912.  
  913.     /**
  914.       * replace existing row or insert now if not exists
  915.       *
  916.       * inserts a row or update an existing row
  917.       * all existing values not in $valueArr (assoc)
  918.       * will be handeld by db spezifaction
  919.       * see mysql Doc: {@link http://www.mysql.com/doc/en/REPLACE.html}
  920.       *
  921.       * @param string $table name of the DBTABLE
  922.       * @param array $valueArr value array with FIELDNAME as Index
  923.       * @param boolean $debug show debug information
  924.       *
  925.       * @returns bool True on success False in case of error
  926.       *
  927.       * @version pk-04-08-10
  928.       * @version pk-05-12-28 set auto_increment column in valueArr on insert
  929.       *
  930.       ***/
  931.     function replaceArray($table,&$valueArr,$debug=False
  932.     {
  933.         if ($debugechoDebug(__FILE__,"<p><b>DB_mySQL::replaceArray($table,\$valueArr (".sizeof($valueArr)."),$debug)</b></p><blockquote style=\"font-size:90%\">",2);
  934.         if (!is_array($valueArr)) return False;
  935.         if (empty($table))        return False;
  936.  
  937.         $query="REPLACE INTO $table (";
  938.         $values="(";
  939.         $sep="";
  940.  
  941.         reset ($valueArr);
  942.         $tblDesc=$this->getDBTblDesc($table);
  943.  
  944.         // <pk-05-12-28>
  945.         foreach($tblDesc as $s_col=>$a_desc{
  946.             // check if we have to insert the row (empty primary_key)
  947.             if ($a_desc['PRIMARY_KEY'&& empty($valueArr[$s_col])) {
  948.                 // we have an empty primary key
  949.                 if ($a_desc['AUTO_INCREMENT']{
  950.                     // which is an auto_increment column
  951.                     if ($valueArr[$s_col]=$this->insertArray($table,$valueArr,$debug)) {
  952.                         // ok we have inserted a new row and set the new id to the valueArr
  953.                         return intval($valueArr[$s_col]);
  954.                     }
  955.                 }
  956.             }
  957.         }
  958.         // <pk-05-12-28>
  959.  
  960.         while(list($key,$valueeach($valueArr)) 
  961.         {
  962.             /* <pk-04-08-10 /> (is_array($tblDesc[$key]) added */
  963.             if ((isset($tblDesc[$key])) && (is_array($tblDesc[$key])) && (!intval($key)) && ($key !== 0)) {
  964.                 //if ($debug) echoDebug(__FILE__,"<p><b>COLUMN: </b>$key</p><blockquote>",2);
  965.                 $query  .= $sep.$key;
  966.                 if (!isset($tblDesc[$key]['LEN'])) $tblDesc[$key]['LEN']=NULL;
  967.                 $values .= $sep.$this->checkValue($tblDesc[$key]['TYPE'],$value,$tblDesc[$key]['LEN'],False);
  968.                 $sep=",";
  969.                 //if ($debug) echoDebug(__FILE__,"</blockquote>",2);
  970.             }
  971.         }
  972.  
  973.         if ($debugechoDebugLine(__FILE__,__LINE__,"<p>Query: ".$query.") <br /> VALUES ".$values.")");
  974.         $query .= ")  VALUES ".$values.")";
  975.         if ($this->executeCmd($query,False,False)) {
  976.             $this->logCmd($query);
  977.             if ($debugechoDebug(__FILE__,"<p>DONE</p></blockquote><hr>",2);
  978.             return True;
  979.         }
  980.         if ($debugecho echoDebug(__FILE__,"<p>ERROR</p></blockquote><hr>",2);
  981.         return False;
  982.     }
  983.  
  984.     /**
  985.      * updates $values in $aTable where $conditions
  986.      *
  987.      * @param string $aTable 
  988.      * @param array $conditions 
  989.      * @param array $values 
  990.      * @param int $limit 
  991.      * @param boolean $debug 
  992.      * 
  993.      * @return int number of effekted rows
  994.      * 
  995.      * @abstract
  996.      * 
  997.      */
  998.     function updateArray($aTable,$conditions,$values,$limit=0,$debug=False)
  999.     {
  1000.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::updateArray()");
  1001.         
  1002.         if (!is_array($conditions|| (sizeof($conditions1))
  1003.         {
  1004.             throw new Exception(_OCSP_EXCEP_NOID_ ": Update requires at least one condition");
  1005.         }
  1006.  
  1007.         if (!is_array($values)  || (sizeof($values1))
  1008.         {
  1009.             throw new Exception(_OCSP_EXCEP_NODATA_ ": Update requires at least one value to change");
  1010.         }        
  1011.         
  1012.         if (!($arr_tblDesc $this->getDBTblDesc($aTable)))
  1013.         {
  1014.             throw new Exception(_OCSP_EXCEP_TABLENOTFOUND_":" $aTable);
  1015.         }
  1016.  
  1017.         $str_query "UPDATE " $aTable " SET";
  1018.         $cha_sep "";
  1019.         
  1020.         foreach($values as $str_col => $mix_val)
  1021.         {
  1022.             if (isset($arr_tblDesc[$str_col]))
  1023.             {
  1024.                 $str_query .= $cha_sep " " $str_col "=" $this->qs_getSlashedValue($mix_val);
  1025.                 $cha_sep ",";
  1026.             }
  1027.         }
  1028.         if ($cha_sep == "")
  1029.         {
  1030.             throw new Exception(_OCSP_EXCEP_NODATA_ ": no update value in table " $aTable);            
  1031.         }
  1032.         
  1033.         $str_whereAnd " WHERE ";
  1034.         foreach($conditions as $str_col => $mix_val)
  1035.         {
  1036.             if (substr($str_col,0,1)=="?")
  1037.             {
  1038.                 $str_query.=$str_whereAnd.$mix_val;
  1039.             else if (substr($str_col,0,1)=="~"{
  1040.                 $str_query .= $str_whereAnd substr($str_col,1" " $this->qs_getLikeStmt($mix_val);
  1041.             else {
  1042.                 $str_query.=$str_whereAnd.$str_col "=" $this->qs_getSlashedValue($mix_val);
  1043.             }
  1044.             $str_whereAnd=" AND ";
  1045.         }     
  1046.         
  1047.           if ($debugechoDebugLine(__FILE__,__LINE__,"SQL-Command: \n".$str_query "\n");
  1048.         return $this->executeCmd($str_query,$debug,True);        
  1049.     }
  1050.         
  1051.     /**
  1052.      * deletes an existing row where the primary key must be set in $valueArr
  1053.      * 
  1054.      * @param string $table name of the DBTABLE
  1055.      * @param array $valueArr value array with FIELDNAME as Index
  1056.      * @param boolean $debug show debug information
  1057.      *
  1058.      * @returns bool True on success False in case of error
  1059.      * 
  1060.      * @since pk-08-02-02
  1061.      *
  1062.      */
  1063.     public function deleteArray($table,&$valueArr,$debug=False)
  1064.     {
  1065.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::updateArray()");
  1066.         
  1067.         if ($arr_tblDesc $this->getDBTblDesc($table))
  1068.         {
  1069.             $arr_conditions array();
  1070.             
  1071.             foreach($arr_tblDesc as $str_col => $arr_desc
  1072.             {
  1073.                 if ($arr_desc['PRIMARY_KEY'])
  1074.                 {
  1075.                     if (empty($valueArr[$str_col]))
  1076.                     {
  1077.                         // unable to identify the row
  1078.                         return False;
  1079.                     else {
  1080.                         $arr_conditions[$str_col=  $this->checkValue($arr_desc['TYPE'],$valueArr[$str_col],$arr_desc['LEN'],False);           
  1081.                     }
  1082.                 }
  1083.             }
  1084.             
  1085.             if (!sizeof($arr_conditions))
  1086.             {
  1087.                 // method requires to identify the row
  1088.                 return False;
  1089.             }
  1090.             
  1091.             $str_query "DELETE FROM " $table " WHERE";
  1092.             $str_sep   ""
  1093.             foreach($arr_conditions as $str_col => $str_val)
  1094.             {
  1095.                 $str_query .= $str_sep " " $str_col "=" $str_val;
  1096.                 $str_sep " AND";                
  1097.             }
  1098.             
  1099.             if ($debugechoDebugLine(__FILE__,__LINE__,"SQL-Command: ".$str_query);
  1100.             return $this->executeCmd($str_query,$debug,True);
  1101.             
  1102.         else {
  1103.             // no table desc
  1104.             return False;
  1105.         }              
  1106.     }
  1107.     
  1108.     /**
  1109.       * replace existing row or insert now if not exists
  1110.       *
  1111.       * calls: <code>return $this->replaceArray($table,$valueArr,$debug);</code>
  1112.       * @see DB_mySQL::replaceArray()
  1113.       *
  1114.       * @param string $table        name of the DBTABLE
  1115.       * @param array  $valueArr     value array with FIELDNAME as Index
  1116.       * @param boolean   $debug        show debug information
  1117.       *
  1118.       * @deprecated since pk-05-01-01
  1119.       *
  1120.       */
  1121.     function replace($table,$valueArr,$debug=False{
  1122.         if ($debugecho "<p><b>DB_mySQL::replace($table,\$valuArr,...)</b>(".get_class($this)."</p>";
  1123.         return $this->replaceArray($table,$valueArr,$debug);
  1124.     }
  1125.  
  1126.     /**
  1127.       * deletes a row form the database
  1128.       * note delKeys must have at least one key => value element
  1129.       *
  1130.       * @param string $table 
  1131.       * @param array $delKeys 
  1132.       * @param boolean $debug 
  1133.       *
  1134.       * @return boolean 
  1135.       *
  1136.       * @since pk-07-08-04
  1137.       */
  1138.     function deleteRows($table,$delKeys,$backup=True,$debug=False)
  1139.     {
  1140.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::deleteRow($table)",print_r($delKeys,True));
  1141.  
  1142.         if (!empty($table))
  1143.         {
  1144.             if (!sizeof($delKeys|| !is_array($delKeys)) {
  1145.                 ocsp_logError(__FILE__,__LINE__,"no delete keys submitted");
  1146.                 return False;
  1147.             }
  1148.             if ($backup)
  1149.             {
  1150.                 $str_backupDir=OCSP_CONF::getInstance('OCSP')->getValue('BACKUPPATH')._OCSP_DIRSEP_.$table;
  1151.                 if (!is_dir($str_backupDir)) {
  1152.                     if (!pcf_checkDir($str_backupDir,True,0770,$debug))
  1153.                     {
  1154.                         ocsp_logError(__FILE__,__LINE__,"could not create backupdir$str_backupDir");
  1155.                         return False;
  1156.                     }
  1157.                 }
  1158.                 $dbl_timestamp=time();
  1159.                 while (file_exists($str_backupDir."/".time().".bak")) $dbl_timestamp++;
  1160.  
  1161.                 if ($arr_backup=$this->getArray($table,$delKeys))
  1162.                 {
  1163.                     if ($r_fp=fopen($str_backupDir."/".$dbl_timestamp.".bak",'w')) {
  1164.                         fwrite($r_fp,json_encode($arr_backup));
  1165.                         fclose($r_fp);
  1166.                     }
  1167.                 else {
  1168.                     return True// the rows does not exists
  1169.                 }
  1170.             }
  1171.  
  1172.             $str_cmd="DELETE FROM $table WHERE ";
  1173.             $str_and="";
  1174.             foreach($delKeys as $str_col => $m_val)
  1175.             {
  1176.                 $str_cmd.=$str_and.$str_col."=".$this->qs_getSlashedValue($m_val);
  1177.                 $str_and=" AND ";
  1178.             }
  1179.  
  1180.             if ($debugechoDebugLine(__FILE__,__LINE__,"Delete Cmd: \n".$str_cmd."\n");
  1181.             return $this->executeCmd($str_cmd);
  1182.         else {
  1183.             ocsp_logError(__FILE__,__LINE__,"param \$table is empty");
  1184.             return False;
  1185.         }
  1186.  
  1187.     }
  1188.  
  1189.     
  1190.    /**
  1191.      * truncates a table
  1192.      *
  1193.      * @param string $aTable 
  1194.      * @param boolean $backup 
  1195.      * 
  1196.      * @todo backup
  1197.      */
  1198.     public function truncateTable($aTable,$backup=True,$debug=False)
  1199.     {
  1200.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::truncateTable("$aTable ")");
  1201.         if ($backup)
  1202.         {
  1203.             $str_backupFile OCSP_CONF::getInstance()->getValue('DBEXPORT');            
  1204.             $str_backupFile $aTable _OCSP_DIRSEP_;
  1205.             
  1206.             pcf_require_function('pcf_checkDir',__OCSP_PHPINCPATH__ "common/pcf_directory.phpinc");
  1207.             
  1208.             if (!pcf_checkDir($str_backupFile,True))
  1209.             {
  1210.                 throw new Exception(_OCSP_EXCEP_DIRNOTFOUND_.":" $str_backupFile);
  1211.             }
  1212.             
  1213.             $str_backupFile .= time(".unload";
  1214.             
  1215.             $str_cmd "SELECT * FROM " $aTable;
  1216.             $str_cmd.= " INTO OUTFILE '" $str_backupFile "'";
  1217.             
  1218.             if ($debugechoDebugLine(__FILE__,__LINE__,"cmd: " .$str_cmd);
  1219.             $this->executeCmd($str_cmd);
  1220.         }
  1221.            $str_cmd "TRUNCATE TABLE " $aTable;
  1222.            $this->executeCmd($str_cmd)
  1223.     
  1224.     
  1225.     /**
  1226.       * resorts orderfields in a table (remove gaps)
  1227.       *
  1228.       * orderfields are integers from 1 to ...
  1229.       * the are used to let the user change order
  1230.       *
  1231.       * @param string $table        the table
  1232.       * @param string $orderFld     the order column
  1233.       * @param string $where        the where clause with the keyword WHERE
  1234.       *                              do not add things like group by or limit ....
  1235.       * @param string $debug        show debug info
  1236.       * @param string $orderby      order by prepend (SELECT .... ORDER BY $orderby,$orderFld)
  1237.       * @param string $groupbyCol   restart index when col change
  1238.       * @param int $startIdx 
  1239.       *
  1240.       * @returns boolean
  1241.       *
  1242.       * @version pk-05-07-26
  1243.       * @version pk-06-01-03
  1244.       *
  1245.       ***/
  1246.     function resortTable($table,$orderFld,$where="",$debug=False,$orderby="",$groupbyCol="",$startIdx=1{
  1247.         if ($debugechoDebug(__FILE__,"<p><b>DB_mySQL::resortTable($table,$orderFld,$where,$debug)</b> (".get_class($this).")</p>",1);
  1248.  
  1249.         if ($tblDesc=$this->getDBTblDesc($table)) {
  1250.             // we got a table desc
  1251.  
  1252.             if (!stristr($tblDesc[$orderFld]['TYPE'],"int")) {
  1253.                 // $orderFld is not of a valid type or does not exists in the table
  1254.                 return False;
  1255.             }
  1256.  
  1257.             // get the primary_key columns
  1258.             $a_PKCols=array();
  1259.             foreach($tblDesc as $s_col => $a_colDesc{
  1260.                 if ($a_colDesc['PRIMARY_KEY']{
  1261.                     $a_PKCols[]=$s_col;
  1262.                 }
  1263.             }
  1264.  
  1265.             if ($debugechoDebug(__FILE__,"<p>Primary Key Column(s): ".implode(",",$a_PKCols)."</p>",2);
  1266.  
  1267.             // generate the query
  1268.             if (!empty($groupbyCol)) // <pk-07-08-08 /> E_ALL
  1269.             {
  1270.                 $s_grpBy=str_replace(",,",",",$groupbyCol.",");
  1271.             else {
  1272.                 $s_grpBy="";
  1273.             }
  1274.  
  1275.             if (!empty($orderby))    $orderby.=",";
  1276.             $s_query ="SELECT * FROM ".$table." ".$where;
  1277.             $s_query.=" ORDER BY ".str_replace(",,",",",$s_grpBy.$orderby).$orderFld;
  1278.             if ($debugechoDebug(__FILE__,"<p>$s_query</p>",2);
  1279.  
  1280.             if ($a_Rows=$this->queryArray($s_query,-1,-1,False,False)) {
  1281.                 // now we have an array of all rows
  1282.                 $i_idx=intval($startIdx);
  1283.                 $s_grpValue=NULL;
  1284.                 foreach($a_Rows as $i_nr => $a_curRow{
  1285.                     if ((!empty($groupbyCol)) && ($a_curRow[$groupbyCol!= $s_grpValue)) {
  1286.                         // new group -> restart index
  1287.                         $i_idx=intval($startIdx);
  1288.                         $s_grpValue=$a_curRow[$groupbyCol];
  1289.                     }
  1290.                     if (intval($a_curRow[$orderFld]!= $i_idx{
  1291.                         // we have to change the row
  1292.                         $s_cmd ="UPDATE $table SET $orderFld=$i_idx";
  1293.                         $s_cmd.=" WHERE $orderFld=".intval($a_curRow[$orderFld]);
  1294.                         foreach($a_PKCols as $s_PKCol{
  1295.                             $s_cmd.=" AND $s_PKCol=".$this->qs_getSlashedValue($a_curRow[$s_PKCol]);
  1296.                         }
  1297.                         if ($debugechoDebug(__FILE__,"<p>UPDATE$s_cmd</p>",1);
  1298.                         $this->executeCmd($s_cmd,$debug,False);
  1299.                     }
  1300.                     $i_idx++;
  1301.                 }
  1302.                 return True;
  1303.             }
  1304.         }
  1305.         return False;
  1306.     }
  1307.  
  1308.     /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1309.     /*  construct / init / objvar methods                                     */
  1310.     /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1311.  
  1312.     /**
  1313.       * returns the mysql server info()
  1314.       *
  1315.       * @since pk-07-02-22
  1316.       *
  1317.       * @returns string
  1318.       *
  1319.       ***/
  1320.     function server_info({
  1321.         if ($this->isConnected()) {
  1322.             return mysql_get_server_info($this->myConnId);
  1323.         else {
  1324.             return "-- NOT CONNECTED --";
  1325.         }
  1326.     }
  1327.  
  1328.     /**
  1329.       * returns an array with column description arrays for each column
  1330.       * where column name is the array index
  1331.       *
  1332.       * a column description array has the following elements
  1333.       *
  1334.       * - string ['TYPE'] (type of the column example varchar,int,...)
  1335.       * - int ['LEN'] (length of the column if supported by type)
  1336.       * - string ['FLAGS'] (mysql flags)
  1337.       * - boolean ['AUTO_INCREMENT'] (does the column use auto values on insert)
  1338.       * - boolean ['NULL'] (null allowed)
  1339.       * - boolean ['PRIMARY_KEY'] (the column is part of the primary key)
  1340.       * - boolean ['KEY'] (the column is part of a -none primary- key)
  1341.       * - string ['COLNAME'] (the name of the column - same as array index should be)
  1342.       *
  1343.       * @param  strint  $table 
  1344.       * @param  bool    $debug  pk-03-10-24
  1345.       *
  1346.       * @returns array
  1347.       *
  1348.       * @version pk-03-10-24
  1349.       * @version pk-05-01-12 php: function mysql_list_fields() is deprecated
  1350.       * @version pk-06-02-09 error handling
  1351.       * @version pk-07-08-04 ['TABLE'] added to the column desc
  1352.       * @version pk-08-03-11 use $dbTableDefinitions
  1353.       ***/
  1354.     function getDBTblDesc($table,$debug=False
  1355.     {
  1356.         if ($debugechoDebug(__FILE__,"<p><b>DB_mySQL::getDBTblDesc($table,$debug)</b> (".get_class($this).")</p>",0);
  1357.  
  1358.         if (empty($table)) return array();
  1359.         
  1360.         if (isset(OCSP_DB_mySQL::$dbTableDefinitions[$table]))
  1361.         {
  1362.             return OCSP_DB_mySQL::$dbTableDefinitions[$table];
  1363.         }
  1364.  
  1365.         $query="DESC $table";
  1366.         $descArr=$this->queryArray($query,0,-1,False,$debug);
  1367.  
  1368.         if (!is_array($descArr)) // <pk-06-02-09>
  1369.             if ($debugechoDebug(__FILE__,"<p>Query$query failed</p>",2);
  1370.             return array();
  1371.         }
  1372.  
  1373.         $ret=array();
  1374.         foreach($descArr as $colName => $colDesc{
  1375.             $typArr explode("(",$colDesc['Type']);
  1376.             $ret[$colName]['TYPE']          =$typArr[0];
  1377.             if (!empty($typArr[1])) {
  1378.                 $ret[$colName]['LEN']       =intval(substr($typArr[1],0,-1));
  1379.             }
  1380.             if (!empty($colDesc['Extra'])) {
  1381.                 $ret[$colName]['FLAGS']         explode(" ",$colDesc['Extra']);
  1382.             }
  1383.             $ret[$colName]['AUTO_INCREMENT'](strstr($colDesc['Extra'],"auto_increment")) True False;
  1384.             $ret[$colName]['NULL']          (substr($colDesc['Null'],0,1== "Y");
  1385.             $ret[$colName]['PRIMARY_KEY']   ($colDesc['Key']=="PRI");
  1386.             $ret[$colName]['DEFAULT']       $colDesc['Default'];
  1387.             $ret[$colName]['KEY']           $colDesc['Key'];
  1388.             $ret[$colName]['COLNAME']       $colName;
  1389.             $ret[$colName]['TABLE']         $table// <pk-07-08-04 />
  1390.  
  1391.             if (!$ret[$colName]['NULL'])       $ret[$colName]['FLAGS'][]="not_null";
  1392.             if ($ret[$colName]['PRIMARY_KEY']$ret[$colName]['FLAGS'][]="primary_key";
  1393.         }
  1394.  
  1395.         if ($debugechoDebug(__FILE__,"<pre style=\"font-size:50%\">".print_r($ret,True)."</pre>",1);
  1396.  
  1397.         OCSP_DB_mySQL::$dbTableDefinitions[$table$ret;
  1398.         return $ret;
  1399.  
  1400.         /* <pk-05-01-12> php: function mysql_list_fields() is deprecated */
  1401.     }
  1402.  
  1403.     /**
  1404.       * returns an array with all primary key column names
  1405.       *
  1406.       * @param string $aTbl 
  1407.       * @param boolean $debug 
  1408.       *
  1409.       * @returns array
  1410.       *
  1411.       * @since pk-06-02-09
  1412.       *
  1413.       ***/
  1414.     function getPrimaryKeys($aTbl,$debug=False{
  1415.         if ($debugechoDebug(__FILE__,"<p><b>DB_mySQL::getPrimaryKeys($aTbl)</b> (".get_class($this).")</p>",0);
  1416.  
  1417.         if ($a_tblDesc=$this->getDBTblDesc($aTbl,$debug)) {
  1418.             $a_pkeys=array();
  1419.             foreach($a_tblDesc as $s_colName => $a_colDesc{
  1420.                 if ($a_colDesc['PRIMARY_KEY']{
  1421.                     $a_pkeys[]=$s_colName;
  1422.                 }
  1423.             }
  1424.             return $a_pkeys;
  1425.         else {
  1426.             return array();
  1427.         }
  1428.     }
  1429.  
  1430.     /**
  1431.       * returns an array with all tables in the database
  1432.       *
  1433.       * @param  bool    $debug  since pk-03-10-25
  1434.       *
  1435.       * @returns array
  1436.       *
  1437.       * @version pk-05-01-12 (php: function mysql_list_tables() is deprecated)
  1438.       *
  1439.       ***/
  1440.     function getDBTblList($debug=False
  1441.     {
  1442.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::getDBTblList()");
  1443.         $query="SHOW TABLES FROM ".$this->myDB;
  1444.         if ($cursor=$this->query($query)) {
  1445.            $ret=array();
  1446.            while ($row=$cursor->fetchArray()) {
  1447.                $ret[]=$row[0];
  1448.            }
  1449.            $cursor->free();
  1450.         }
  1451.         if (!sizeof($ret|| empty($ret[0])) {
  1452.             if ($debug{
  1453.                 $this->errorMsg("DB_mySQL::getDBTblList");
  1454.             }
  1455.             $query="SHOW TABLES";
  1456.             $ret=$this->queryArray($query,0,0,True,$debug);
  1457.             if ($debugecho "<pre>$query\n";print_r($ret);echo "</pre>"}
  1458.         }
  1459.         if ($debug{echo "<blockquote><p>DB_mySQL::getDBTblList RETURN: array with ".count($ret)." elements</p></blockquote>";}
  1460.         return $ret;
  1461.     }
  1462.  
  1463.     /**
  1464.       * checks if a table exists
  1465.       *
  1466.       * @param string $aTable table name
  1467.       * @param boolean   $debug  since pk-03-10-24
  1468.       *
  1469.       * @returns bool
  1470.       *
  1471.       * @version pk-03-10-24
  1472.       * @version pk-03-10-30
  1473.       * @since   pk-03-10-21
  1474.       *
  1475.       ***/
  1476.     function tblExists($aTable,$debug=False{
  1477.         if ($debugecho "<hr /><p><b>DB_mySQL::tblExists($aTable,$debug)</b></p><blockquote>";
  1478.         if ($tblLst=$this->getDBTblList($debug)) {
  1479.             if (!$ret=in_array($aTable,$tblLst,False)) {
  1480.                 if ($debugecho "<pre style='font-size:10px;'>Searching $aTable in:\n";print_r($tblLst);echo "</pre>"}
  1481.  
  1482.                 // sometimes in_array fails
  1483.                 reset ($tblLst);
  1484.                 while ((!$ret&& (list($key,$tbl)=each($tblLst))) {
  1485.                     if (strtoupper(trim($aTable))==strtoupper(trim($tbl))) {
  1486.                         $ret=True;
  1487.                     }
  1488.                 }
  1489.             }
  1490.             if ($debugecho "<p>tblExists RETURN $ret</p></blockquote>";
  1491.             return $ret;
  1492.         }
  1493.         if ($debugecho "<p>RETURN False</p></blockquote>";
  1494.         return False;   // NO TABLES FOUND
  1495.     }
  1496.  
  1497.     public function createTable($tblName,$cols,$debug=False)
  1498.     {
  1499.         $str_cmd "CREATE TABLE " $tblName "(";
  1500.         $cha_sep "";
  1501.         foreach($cols as $str_colName => $arr_colDesc)
  1502.         {
  1503.             if ($str_colDesc=$this->getColumnDef($arr_colDesc,$debug))
  1504.             {
  1505.                 $str_cmd .= $cha_sep $str_colName " " $str_colDesc;
  1506.                 $cha_sep ',';
  1507.             }
  1508.         }
  1509.                 
  1510.         $str_cmd.= ")  ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_bin";
  1511.         
  1512.         $this->executeCmd($str_cmd);
  1513.         
  1514.     }
  1515.     
  1516.     /**
  1517.       * returns an array of table column names
  1518.       *
  1519.       * @param string $aTable 
  1520.       * @param boolean $debug 
  1521.       *
  1522.       * @returns array
  1523.       *
  1524.       * @since pk-06-02-20
  1525.       *
  1526.       ***/
  1527.     function getDBTblColNames($aTable,$debug=False{
  1528.         if ($debugechoDebugMethod(__FILE__,get_class($this)."DB_mySQL::getDBTblColNames($aTable)","",0);
  1529.  
  1530.         if ($a_tblDesc=$this->getDBTblDesc($aTable,$debug)) {
  1531.             return array_keys($a_tblDesc);
  1532.         else {
  1533.             return array();
  1534.         }
  1535.     }
  1536.  
  1537.     /**
  1538.       * returns if a table has a certain column
  1539.       *
  1540.       * @param string $table 
  1541.       * @param string $colName 
  1542.       * @param boolean $debug 
  1543.       *
  1544.       * @returns boolean
  1545.       *
  1546.       * @since pk-05-11-16
  1547.       *
  1548.       ***/
  1549.     function tblHasColumn($table,$colName,$debug=False{
  1550.         if ($debugecho "<p><b>DB_mySQL::tblHasColumn($table,$colName)</b> (".get_class($this).")</p>";
  1551.  
  1552.         $a_tblDesc=$this->getDBTblDesc($table,$debug);
  1553.         return (isset($a_tblDesc[$colName]));
  1554.     }
  1555.  
  1556.     /**
  1557.       * returns the database column definition to use in create table or alter column
  1558.       *
  1559.       * @param array $dbDesc  Column array generated with DB_MYSQL::getDBTblDesc()
  1560.       * @param boolean $debug 
  1561.       *
  1562.       * @returns string
  1563.       *
  1564.       * @since  pk-03-10-22
  1565.       *
  1566.       * @version pk-04-01-11
  1567.       * @version pk-04-10-08
  1568.       * @version pk-04-11-08
  1569.       * @version pk-05-11-09
  1570.       * @version pk-07-09-19
  1571.       * @version pk-07-10-30
  1572.       ***/
  1573.     function getColumnDef($dbDesc,$debug=False{
  1574.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::getColumnDef(\$dbDesc)",print_r($dbDesc,True));
  1575.         
  1576.         if (!is_array($dbDesc)) {
  1577.             return False;
  1578.         }
  1579.         
  1580.         if (!isset($dbDesc['TYPE']|| empty($dbDesc['TYPE']))
  1581.         {
  1582.             if ($debugocsp_logError(__FILE__,__LINE__,'no type set in \$dbDesc',E_WARNING);
  1583.             return False;
  1584.         }
  1585.  
  1586.         switch(strtolower($dbDesc['TYPE'])) {
  1587.             case "string":
  1588.             case "varchar":
  1589.                 if (!intval($dbDesc['LEN'])) $dbDesc['LEN']=255;
  1590.                 else $dbDesc['LEN']=intval($dbDesc['LEN']);                
  1591.                 $ret  " VARCHAR(".($dbDesc['LEN'255 255 $dbDesc['LEN']).") ";
  1592.                 $ret .= "CHARACTER SET utf8 COLLATE utf8_bin ";
  1593.                 break;
  1594.             case "blob":
  1595.                 $ret=" TEXT ";
  1596.                 $ret .= "CHARACTER SET utf8 COLLATE utf8_bin ";
  1597.                 break;
  1598.             case "text":
  1599.                 $ret=" TEXT ";
  1600.                 $ret .= "CHARACTER SET utf8 COLLATE utf8_bin ";
  1601.                 break;
  1602.             case "tinyint"// <pk-07-10-30>
  1603.                 if (!isset($dbDesc['LEN'])) 
  1604.                 {
  1605.                     $dbDesc['LEN']=4
  1606.                 elseif ((intval($dbDesc['LEN']4|| (!intval($dbDesc['LEN']))) {
  1607.                     $dbDesc['LEN']=4;
  1608.                 }
  1609.                 $ret=" TINYINT({$dbDesc['LEN']}";
  1610.                 break;                
  1611.             case "int":
  1612.                 /* <pk-04-11-08> */
  1613.                 if (intval($dbDesc['LEN']&& (intval($dbDesc['LEN']5))
  1614.                     $ret=" TINYINT ";
  1615.                 else
  1616.                     $ret=" INT ";
  1617.                 if ((intval($dbDesc['LEN']0&& (intval($dbDesc['LEN']32)) // <pk-05-11-09 />
  1618.                     $ret.="(".intval($dbDesc['LEN'].") ";
  1619.                 }
  1620.                 /* </pk-04-11-08> */
  1621.                 break;
  1622.             case "real":
  1623.             case "float":
  1624.             case "double"// <pk-06-05-09 />
  1625.                 $ret=" FLOAT ";
  1626.                 break;
  1627.             case "date":
  1628.                 $ret=" DATE ";
  1629.                 break;
  1630.             case "datetime":
  1631.                 $ret=" DATETIME ";
  1632.                 break;
  1633.             case "timestamp":
  1634.                 $ret=" TIMESTAMP ";
  1635.                 break;
  1636.             case "time":
  1637.                 $ret=" TIME ";
  1638.                 break;
  1639.  
  1640.             default:
  1641.                 if ($debugechoDebugLine(__FILE__,__LINE__,"unknown column type: ".strtolower($dbDesc['TYPE']));
  1642.                 return False;
  1643.         }
  1644.  
  1645.         if (isset($dbDesc['NULL']&& (!$dbDesc['NULL'])) {
  1646.             $ret.=" NOT NULL ";
  1647.         }
  1648.  
  1649.         if ($dbDesc['DEFAULT']{
  1650.             $ret.=" DEFAULT ".$this->qs_getSlashedValue($dbDesc['DEFAULT']);
  1651.         }
  1652.         
  1653.         if ($dbDesc['AUTO_INCREMENT']{
  1654.             $ret.=" AUTO_INCREMENT";
  1655.         }
  1656.         
  1657.         if ($dbDesc['PRIMARY_KEY']{
  1658.             $ret.=" PRIMARY KEY";
  1659.         }
  1660.         
  1661.         
  1662.         if ($debugechoDebugLine(__FILE__,__LINE__,"returning: ".$ret);
  1663.         return $ret;
  1664.     }
  1665.  
  1666.     /**
  1667.       * adds a column to a table
  1668.       *
  1669.       * @param string $aTable 
  1670.       * @param string $colName 
  1671.       * @param array $dbDesc 
  1672.       * @param boolean $debug 
  1673.       *
  1674.       * @since pk-04-10-08
  1675.       *
  1676.       ***/
  1677.     public function addColumn($aTable,$colName,&$dbDesc,$debug=False
  1678.     {
  1679.         if ($debugechoDebugMethod(__FILE__,get_class($this),"OCSP_DB_mySQL::addColumn($aTable,$colName,\$dbDesc)",print_r($dbDesc,True));
  1680.  
  1681.         if ($this->tblExists($aTable,$debug)) {
  1682.             $cmd ="ALTER TABLE $aTable ADD ".trim($colName);
  1683.             if ($colDesc=$this->getColumnDef($dbDesc,$debug)) {
  1684.                 $cmd.=$colDesc;
  1685.                 if ($debugechoDebugLine(__FILE__,__LINE__,"<blockquote><b>addColumn</bCMD:$cmd</blockquote>");
  1686.                 try {
  1687.                     $this->executeCmd($cmd);
  1688.                     return True;
  1689.                 catch (Exception $e{
  1690.                     if ($debugechoDebugLine(__FILE__,__LINE__,"<pre>" print_r($e));
  1691.                     return False;
  1692.                 }
  1693.             else {
  1694.                 ocsp_logError(__FILE__,__LINE__,"could not get column def",E_WARNING);
  1695.                 return False;
  1696.             }
  1697.         else {
  1698.             ocsp_logError(__FILE__,__LINE__,"table $aTable does not exist",E_WARNING);
  1699.             return False;
  1700.         }
  1701.     }
  1702.  
  1703.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1704.     // SQL Statement casts
  1705.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1706.  
  1707.     /**
  1708.       * returns the where clause for a select
  1709.       *
  1710.       * @param array $conditions 
  1711.       * @param boolean $debug 
  1712.       *
  1713.       * @return string 
  1714.       *
  1715.       * @since pk-07-08-14
  1716.       * @version pk-08-06-03
  1717.       */
  1718.     function qs_getWhereClause($conditions=NULL,$debug=False)
  1719.     {
  1720.         $str_ret "";
  1721.         if ($conditions && sizeof($conditions))
  1722.         {
  1723.             $str_whereAnd=" WHERE ";
  1724.             foreach($conditions as $str_col => $m_val)
  1725.             {
  1726.                 $str_ret .= $str_whereAnd.$str_col."=".$this->qs_getSlashedValue($m_val);
  1727.                 $str_whereAnd=" AND ";
  1728.             }
  1729.         }
  1730.         return $str_ret;
  1731.     }
  1732.  
  1733.     /**
  1734.       * returns $aValue with slashes to use to create query strings
  1735.       *
  1736.       * @param string $aValue 
  1737.       *
  1738.       * @returns string
  1739.       *
  1740.       * @since  pk-03-10-25
  1741.       * @version pk-05-07-05 mysql_real_escape_string added
  1742.       * @version pk-06-09-11 strval added
  1743.       *
  1744.       ***/
  1745.     function qs_getSlashedValue($aValue)
  1746.     {
  1747.         $aValue=strval($aValue);
  1748.         return "'".mysql_real_escape_string($aValue,$this->myConnId)."'";
  1749.     }
  1750.  
  1751.     /**
  1752.       * returns a password command $aValue
  1753.       *
  1754.       * @param string $aValue 
  1755.       *
  1756.       * @returns string
  1757.       *
  1758.       * @since  pk-04-01-13
  1759.       * @version pk-04-09-28
  1760.       *
  1761.       ***/
  1762.     function qs_getPassword($aValue){
  1763.         return "PASSWORD(".$this->qs_getSlashedValue($aValue).")";
  1764.     }
  1765.  
  1766.     /**
  1767.       * returns the db NULL statement for NULL values
  1768.       *
  1769.       * @returns string
  1770.       *
  1771.       * @since  pk-03-10-25
  1772.       *
  1773.       ***/
  1774.     function qs_getNullStmt({
  1775.         return "NULL";
  1776.     }
  1777.  
  1778.     /**
  1779.       * returns the db NOW() statement for date/time values
  1780.       *
  1781.       * @returns string
  1782.       *
  1783.       * @since  pk-03-10-25
  1784.       *
  1785.       ***/
  1786.     function qs_getNowStmt({
  1787.         return "NOW()";
  1788.     }
  1789.  
  1790.     /**
  1791.       * returns the db IFNULL/nvl statement
  1792.       *
  1793.       * @param string $column 
  1794.       * @param string $default 
  1795.       *
  1796.       * @returns string
  1797.       *
  1798.       * @since  pk-03-10-25
  1799.       *
  1800.       ***/
  1801.     function qs_ifNullStmt($column,$default=""{
  1802.         return " IFNULL($column,".$this->qs_getSlashedValue($default).") ";
  1803.     }
  1804.  
  1805.     /**
  1806.       * returns a Date object in string representation
  1807.       *
  1808.       * Exceptions:
  1809.       * if $aDateObj is NULL $this->qs_getNullStmt() is returned
  1810.       * if $aDateObj in not an object $aDataObj is retured with or without slashes
  1811.       *
  1812.       * @param OCSP_DATE $aDateObj 
  1813.       * @param boolean $slashed  use slashes
  1814.       *
  1815.       * @returns string
  1816.       *
  1817.       * @since   pk-03-10-25
  1818.       * @version pk-03-12-13
  1819.       * @version pk-06-08-08 sprintf as mktime returns on some (32bit) systems wrong values if the year is greater then 2037
  1820.       * @version pk-07-10-01 no need to require date class as it passed within a parameter
  1821.       *
  1822.       ***/
  1823.     function qs_getDateStmt($aDateObj,$slashed=True{
  1824.         if (pcf_is_instance_of($aDateObj,'OCSP_DATE')) {
  1825.             if ($aDateObj->isNULL()) return "NULL";
  1826.             if ($slashed$slashes="'"else $slashes="";
  1827.             $s_date=sprintf("%04d-%02d-%02d",$aDateObj->getYear(),$aDateObj->getMonth(),$aDateObj->getDay());
  1828.             $s_time=sprintf("%02d:%02d:%02d",$aDateObj->getHour(),$aDateObj->getMinutes(),$aDateObj->getSeconds());
  1829.             return $slashes.$s_date." ".$s_time.$slashes;
  1830.         else {
  1831.             if (!empty($aDateobj)) {
  1832.                 if ($slashedreturn $this->qs_getSlashedValue($aDateObj);
  1833.                 else return $aDateObj;
  1834.             else {
  1835.                 return $this->qs_getNullStmt();
  1836.             }
  1837.         }
  1838.     }
  1839.  
  1840.     /**
  1841.       * returns a sql statement for use in search
  1842.       *
  1843.       * @param string $searchStr 
  1844.       * @param boolean $toUpper convert the searchStr to upper cases or leave it as is
  1845.       * @param boolean $inline enclose the searchStr in placeholders (%search%)
  1846.       * @param boolean $debug 
  1847.       *
  1848.       * @returns string
  1849.       *
  1850.       */
  1851.     public function qs_getLikeStmt($searchStr,$toUpper=False,$inline=True,$debug=False{
  1852.         if ($debugechoDebug(__FILE__,"<p><b>DB_mySQL::qs_getLikeStmt($searchStr)</b> (".get_class($this)."</p>");
  1853.  
  1854.         // first trim the searchStr
  1855.         $searchStr=trim($searchStr);
  1856.  
  1857.         if ($toUpper{
  1858.             // convert to uppercase
  1859.             $searchStr=strtoupper($searchStr);
  1860.         }
  1861.  
  1862.         // replace all special chars
  1863.         $searchStr=preg_replace('/[^A-Za-z0-9_\-\.]/i'"%"$searchStr);
  1864.  
  1865.         if ($inline)
  1866.         {
  1867.             $searchStr="%".$searchStr."%";
  1868.         }
  1869.         return " LIKE ".$this->qs_getSlashedValue($searchStr);
  1870.  
  1871.     }
  1872.  
  1873.     /**
  1874.       * returns WHERE col IN($valArr)
  1875.       *
  1876.       * @param string $col 
  1877.       * @param array $valArr 
  1878.       * @param boolean $valuesAreString 
  1879.       *
  1880.       * @return string 
  1881.       * @access public
  1882.       *
  1883.       * @since pk-07-06-15
  1884.       * @version pk-07-08-20
  1885.       *
  1886.       */
  1887.     function qs_getWhereIn($col,$valArr,$valuesAreString=True)
  1888.     {
  1889.  
  1890.         $str_ret=" ".$col." IN (";
  1891.         if ($valuesAreString)
  1892.         {
  1893.             $c_sep="";
  1894.             foreach($valArr as $m_val)
  1895.             {
  1896.                 $str_val=strval($m_val)// ensure we have a string
  1897.                 //echoDebugLine(__FILE__,__LINE__,"adding value: $str_val");
  1898.                 if (strlen($str_val0// <pk-07-08-20 /> bugfix
  1899.                 {
  1900.                     $str_ret.=$c_sep.$this->qs_getSlashedValue($str_val);
  1901.                     $c_sep=",";
  1902.                 }
  1903.             }
  1904.         else {
  1905.             $str_ret.=implode(',',$valArr);
  1906.         }
  1907.         $str_ret.=") ";
  1908.         return $str_ret;
  1909.     }
  1910.  
  1911.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1912.     // sql value cast
  1913.     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1914.  
  1915.     /**
  1916.       * returns the linux timestamp (mktime) of a date column
  1917.       *
  1918.       * @param stirng $aDateVal 
  1919.       * @param boolean $debug 
  1920.       *
  1921.       * @return double 
  1922.       * @access public
  1923.       */
  1924.     function getTimeStamp($aDateVal,$debug=True)
  1925.     {
  1926.         if ($debugechoDebugMethod(__FILE__,get_class($this),"DB_mySQL::getTimeStamp()");
  1927.         if (empty($aDateVal|| (substr($aDateVal,0,4)=="0000"))
  1928.         {
  1929.             return 0;
  1930.         }
  1931.  
  1932.         return strtotime($aDateVal);
  1933.     }
  1934.  
  1935. }
  1936.  
  1937. /**
  1938.   *
  1939.   * @deprecated since pk-10-03-21
  1940.   *
  1941.   * @returns string
  1942.   *
  1943.   * @todo   delete function when sure that it is not used
  1944.   *
  1945.   ***/
  1946. function MYSQL_getNowValue({
  1947.     return OCSP_OBJ::defaultReadDBObj()->qs_getNowStmt();
  1948. }
  1949.  
  1950. ?>

Documentation generated on Thu, 08 Jan 2009 17:45:33 +0100 by phpDocumentor 1.4.0a2