[ Index ]

PHP Cross Reference of phpwcms V1.4.3 _r380 (23.11.09)

title

Body

[close]

/include/inc_lib/ -> dbcon.inc.php (source)

   1  <?php
   2  /*************************************************************************************
   3     Copyright notice
   4     
   5     (c) 2002-2009 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.
   6   
   7     This script is part of PHPWCMS. The PHPWCMS web content management system is
   8     free software; you can redistribute it and/or modify it under the terms of
   9     the GNU General Public License as published by the Free Software Foundation;
  10     either version 2 of the License, or (at your option) any later version.
  11    
  12     The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
  13     A copy is found in the textfile GPL.txt and important notices to the license 
  14     from the author is found in LICENSE.txt distributed with these scripts.
  15    
  16     This script is distributed in the hope that it will be useful, but WITHOUT ANY 
  17     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  18     PARTICULAR PURPOSE.  See the GNU General Public License for more details.
  19   
  20     This copyright notice MUST APPEAR in all copies of the script!
  21  *************************************************************************************/
  22  
  23  // ----------------------------------------------------------------
  24  // obligate check for phpwcms constants
  25  if (!defined('PHPWCMS_ROOT')) {
  26     die("You Cannot Access This Script Directly, Have a Nice Day.");
  27  }
  28  // ----------------------------------------------------------------
  29  
  30  // build the database table prepend part
  31  define ('DB_PREPEND', $phpwcms["db_prepend"] ? $phpwcms["db_prepend"].'_' : '');
  32  
  33  // open the connection to MySQL database
  34  $is_mysql_error = false;
  35  
  36  if($phpwcms["db_pers"] == 1) {
  37      $db = @mysql_pconnect($phpwcms["db_host"], $phpwcms["db_user"], $phpwcms["db_pass"]) or ($is_mysql_error = true);
  38  } else {
  39      $db = @mysql_connect($phpwcms["db_host"], $phpwcms["db_user"], $phpwcms["db_pass"]) or ($is_mysql_error = true);
  40  }
  41  @mysql_select_db($phpwcms["db_table"], $db) or ($is_mysql_error = true);
  42  
  43  if($is_mysql_error) {
  44      header('Location: '.PHPWCMS_URL.'dbdown.php');
  45      exit();
  46  
  47  }
  48  
  49  // set DB to compatible mode
  50  // for compatibility issues try to check for MySQL version and charset
  51  $phpwcms['db_version'] = _dbInitialize();
  52  define('PHPWCMS_DB_VERSION', $phpwcms['db_version']);
  53  
  54  if(!function_exists('mysql_real_escape_string')) {
  55      if(function_exists('mysql_escape_string')) {
  56  		function mysql_real_escape_string($string) {
  57              return mysql_escape_string( $string );
  58          }
  59      } else {
  60  		function mysql_real_escape_string($string) {
  61              return aporeplace( $string );
  62          }
  63      }
  64  }
  65  
  66  function _dbQuery($query='', $_queryMode='ASSOC') {
  67  
  68      if(empty($query)) return false;
  69      
  70      global $db;
  71      $queryResult    = array();
  72      $queryCount        = 0;
  73      
  74      if($result = @mysql_query($query, $db)) {
  75      
  76          switch($_queryMode) {
  77  
  78              // INSERT, UPDATE, DELETE
  79              case 'INSERT':    $queryResult['INSERT_ID']        = mysql_insert_id($db);
  80              case 'DELETE':    
  81              case 'UPDATE':    
  82                              $queryResult['AFFECTED_ROWS']    = mysql_affected_rows($db);
  83                              return $queryResult;
  84                              break;
  85              
  86              // INSERT ... ON DUPLICATE KEY
  87              case 'ON_DUPLICATE':
  88                              $queryResult['AFFECTED_ROWS']    = mysql_affected_rows($db);
  89                              $queryResult['INSERT_ID']        = mysql_insert_id($db);
  90                              if($queryResult['AFFECTED_ROWS'] == 2) {
  91                                  $queryResult['INSERT_ID']        = 0;
  92                                  $queryResult['AFFECTED_ROWS']    = 1;
  93                              }
  94                              return $queryResult;
  95                              break;                
  96  
  97              // SELECT Queries    
  98              case 'ROW':        $_queryMode = 'mysql_fetch_row';    break;
  99              case 'ARRAY':    $_queryMode = 'mysql_fetch_array';    break;
 100              
 101              // COUNT
 102              case 'COUNT':    // first check if SQL COUNT() is used
 103                              $query = strtoupper($query);
 104                              if(strpos($query, 'SELECT COUNT(') !== false) {
 105                                  $row = mysql_fetch_row($result);
 106                                  return $row ? $row[0] : 0;
 107                              } else {
 108                                  return mysql_num_rows($result);
 109                              }
 110                              break;
 111              
 112              // SET, CREATE
 113              case 'SET':
 114              case 'CREATE':    return true;
 115                              break;
 116              
 117              default:         $_queryMode = 'mysql_fetch_assoc';
 118      
 119          }
 120      
 121          while($row = $_queryMode($result)) {
 122              
 123              $queryResult[$queryCount] = $row;
 124              $queryCount++;
 125  
 126          }
 127          mysql_free_result($result);
 128      
 129          return $queryResult;
 130      
 131      } else {
 132          return false;
 133      }
 134  
 135  }
 136  
 137  function _dbCount($query='') {
 138      return _dbQuery($query, 'COUNT');
 139  }
 140  
 141  // function for simplified insert
 142  function _dbInsert($table='', $data=array(), $special='', $prefix=NULL) {
 143      
 144      if(empty($table)) return false;
 145      if(!is_array($data) || !count($data)) return false;
 146      
 147      $table    = (is_string($prefix) ? $prefix : DB_PREPEND).$table;
 148      $fields    = array();
 149      $values    = array();
 150      $x        = 0;
 151      
 152      foreach($data as $key => $value) {
 153          $fields[$x]    = '`'.$key.'`';
 154          $values[$x]    = is_numeric($value) ? "'".$value."'" : "'".mysql_real_escape_string($value)."'";
 155          $x++;
 156      }
 157      
 158      if($special) {
 159          $special = strtoupper(trim($special));
 160          if($special != 'LOW_PRIORITY' || $special != 'DELAYED') {
 161              $special = 'DELAYED';
 162          }
 163          $special .= ' ';
 164      }
 165      
 166      $query  = 'INSERT '.$special.'INTO ' . $table . ' (';
 167      $query .= implode(',', $fields) . ') VALUES (' . implode(',', $values) . ')';
 168      
 169      return _dbQuery($query, 'INSERT');
 170  
 171  }
 172  
 173  function _dbInsertOrUpdate($table='', $data=array(), $where='', $prefix=NULL) {
 174  
 175      // INSERT ... ON DUPLICATE KEY UPDATE is available for MySQL >= 4.1.0
 176      // $where is necessary OR if $where is empty first array $data element
 177      // have to be the primary OR a unique key otherwise this will fail
 178      
 179      global $phpwcms;
 180      
 181      if(empty($table)) return false;
 182      if(!is_array($data) || !count($data)) return false;
 183      
 184      $table    = (is_string($prefix) ? $prefix : DB_PREPEND).$table;
 185      $fields    = array();
 186      $values    = array();
 187      $set    = array();
 188      $x        = 0;
 189      
 190      foreach($data as $key => $value) {
 191          $fields[$x]    = '`'.$key.'`';
 192          $values[$x]    = is_numeric($value) ? "'".$value."'" : "'".mysql_real_escape_string($value)."'";
 193          $set[$x]    = $fields[$x].'='.$values[$x];
 194          $x++;
 195      }
 196      
 197      $insert  = 'INSERT INTO ' . $table . ' (';
 198      $insert .= implode(',', $fields) . ') VALUES (' . implode(',', $values) . ')';
 199      
 200      if($phpwcms['db_version'] < 40100) {
 201          // the old way
 202          
 203          // 1st send INSERT
 204          $result = _dbQuery($insert, 'INSERT');
 205          
 206          if($result === false) {
 207          
 208              // INSERT was false, now try UPDATE
 209              $update  = 'UPDATE ' . $table . ' SET ';
 210              $update .= implode(',', $set) . ' WHERE ';
 211              if($where === '' || strpos($where, '=') === false) {
 212                  reset($data);
 213                  $key    = key($data);
 214                  $value     = current($data);
 215                  $update .= '`'.$key.'`=';
 216                  $update .= is_numeric($value) ? "'".$value."'" : "'".mysql_real_escape_string($value)."'";
 217              } else {
 218                  $update .= trim($where);
 219              }
 220              
 221              return _dbQuery($update, 'UPDATE');
 222  
 223          } else {
 224          
 225              return $result;
 226          }
 227      
 228      } else {
 229          // the new way
 230          $insert .= ' ON DUPLICATE KEY UPDATE ';
 231          $insert .= implode(',', $set);
 232          
 233          return _dbQuery($insert, 'ON_DUPLICATE');
 234      }
 235      
 236      return false;
 237  
 238  }
 239  
 240  // simplified db select
 241  function _dbGet($table='', $select='*', $where='', $group_by='', $order_by='', $limit='', $prefix=NULL) {
 242      
 243      if(empty($table)) return false;
 244      
 245      $table        = (is_string($prefix) ? $prefix : DB_PREPEND).$table;
 246      $sets        = array();
 247      $select        = trim($select);
 248      $limit        = trim($limit);
 249      $group_by    = trim($group_by);
 250      $order_by    = trim($order_by);
 251      
 252      if($select === '') {
 253          $select = '*';
 254      }
 255      if($limit !== '') {
 256          if(is_int($limit)) {
 257              $limit = ' LIMIT ' . $limit;
 258          } else {
 259              $limit = explode(',', $limit);
 260              $limit[0] = intval(trim($limit[0]));
 261              $limit[1] = isset($limit[1]) ? intval(trim($limit[1])) : 0;
 262              if($limit[0] && $limit[1]) {
 263                  $limit = ' LIMIT ' . $limit[0] . ',' . $limit[1];
 264              } elseif($limit[0] === 0 && $limit[1]) {
 265                  $limit = ' LIMIT ' . $limit[1];
 266              } elseif($limit[0]) {
 267                  $limit = ' LIMIT ' . $limit[0];
 268              } else {
 269                  $limit = '';
 270              }
 271          }
 272      }
 273      if($group_by !== '') {
 274          $group_by = ' GROUP BY '.aporeplace($group_by);
 275      } else {
 276          $group_by = '';
 277      }
 278      
 279      if($order_by !== '') {
 280          $order_by = ' ORDER BY '.aporeplace($order_by);
 281      } else {
 282          $order_by = '';
 283      }
 284      
 285      if($where != '') {
 286          $where = trim($where);
 287          if( substr(strtoupper($where), 0, 5) !== 'WHERE' ) {
 288              $where = 'WHERE '.$where;
 289          }
 290          $where = ' '.$where;
 291      }
 292  
 293      $query = trim( 'SELECT ' . $select . ' FROM ' . $table . $where . $group_by . $order_by . $limit);
 294  
 295      return _dbQuery($query);
 296  }
 297  
 298  // function for simplified update
 299  function _dbUpdate($table='', $data=array(), $where='', $special='', $prefix=NULL) {
 300      
 301      if(empty($table)) return false;
 302      if(!is_array($data) || !count($data)) return false;
 303      
 304      $table    = (is_string($prefix) ? $prefix : DB_PREPEND).$table;
 305      $sets    = array();
 306      
 307      foreach($data as $key => $value) {
 308          $sets[]    = '`'.$key.'`=' .( is_numeric($value) ? "'".$value."'" : "'".mysql_real_escape_string($value)."'" );
 309      }
 310      
 311      if($special) {
 312          $special = strtoupper(trim($special));
 313          if($special != 'LOW_PRIORITY') $special = 'LOW_PRIORITY';
 314          $special .= ' ';
 315      }
 316      
 317      if($where != '') {
 318          $where = trim($where);
 319          if( substr(strtoupper($where), 0, 5) !== 'WHERE' ) {
 320              $where = 'WHERE '.$where;
 321          }
 322      }
 323  
 324      $query = trim( 'UPDATE ' . $special . $table . ' SET ' . implode(',', $sets) . ' ' . $where );
 325  
 326      return _dbQuery($query, 'UPDATE');
 327  
 328  }
 329  
 330  function _dbGetCreateCharsetCollation() {
 331      global $phpwcms;
 332      $value = '';
 333      if($phpwcms['db_version'] > 40100 && $phpwcms['db_charset']) {
 334          $value .= ' DEFAULT';
 335          $value .= ' CHARACTER SET '.$phpwcms['db_charset'];
 336          if(!empty($phpwcms['db_collation'])) {
 337              $value .= ' COLLATE '.$phpwcms['db_collation'];
 338          }
 339      }
 340      return $value;
 341  }
 342  
 343  function _report_error($error_type='DB', $query='') {
 344      global $db;
 345      $error = mysql_error($db);
 346      if($query) {
 347          $query  = str_replace(',', ",\n", $query);
 348          $error .= '<pre>' . $query .'</pre>';
 349      }
 350      return $error;
 351  }
 352  
 353  function _dbInitialize() {
 354  
 355      global $phpwcms;
 356  
 357      // check if mysql version is set
 358      if(empty($phpwcms['db_version'])) {
 359          $version = _dbQuery('SELECT VERSION()', 'ROW');
 360          if(isset($version[0][0])) {
 361              $version = explode('.', $version[0][0]);
 362              $version[0] = intval($version[0]);
 363              $version[1] = empty($version[1]) ? 0 : intval($version[1]);
 364              $version[2] = empty($version[2]) ? 0 : intval($version[2]);
 365              $phpwcms["db_version"] = (int)sprintf('%d%02d%02d', $version[0], $version[1], $version[2]);
 366          } else {
 367              return 0;
 368          }
 369      }
 370      if($phpwcms['db_version'] > 40000) {
 371          
 372          if(empty($phpwcms['db_charset'])) {
 373              $mysql_charset_map = array(    'big5'         => 'big5',    'cp-866'       => 'cp866',    'euc-jp'       => 'ujis',
 374                                          'euc-kr'       => 'euckr',    'gb2312'       => 'gb2312',    'gbk'          => 'gbk',
 375                                          'iso-8859-1'   => 'latin1',    'iso-8859-2'   => 'latin2',    'iso-8859-7'   => 'greek',
 376                                          'iso-8859-8'   => 'hebrew',    'iso-8859-8-i' => 'hebrew',    'iso-8859-9'   => 'latin5',
 377                                          'iso-8859-13'  => 'latin7',    'iso-8859-15'  => 'latin1',    'koi8-r'       => 'koi8r',
 378                                          'shift_jis'    => 'sjis',    'tis-620'      => 'tis620',    'utf-8'        => 'utf8',
 379                                          'windows-1250' => 'cp1250',    'windows-1251' => 'cp1251',    'windows-1252' => 'latin1',
 380                                          'windows-1256' => 'cp1256',    'windows-1257' => 'cp1257'   );
 381              $phpwcms['db_charset'] = $mysql_charset_map[ strtolower($phpwcms['charset']) ];
 382          }
 383          
 384          // Send charset used in phpwcms for every query
 385          $sql = "SET NAMES '".$phpwcms['db_charset']."'";
 386          if($phpwcms['db_version'] > 40100 && !empty($phpwcms['db_collation'])) {
 387              $sql .= " COLLATE '".$phpwcms['db_collation']."'";
 388          }
 389          _dbQuery($sql, 'SET');
 390  
 391      }
 392      
 393      return $phpwcms['db_version'];
 394  }
 395  
 396  // duplicate a DB record based on 1 unique column
 397  function _dbDuplicateRow($table='', $unique_field='', $id_value=0, $exception=array(), $prefix=NULL) {
 398  
 399      // use exceptions to define duplicate values: 'field_name' => 'value' (INT/STRING)
 400      // to avoid problems with UNIQUE/auto increment columns set 'field_name' => '--UNIQUE--'
 401      // to overwrite a unique value use excpetions 'unique_field_name' => 'new_value'
 402      // to use simple SQL functions for exceptions define it like 'field_name' => 'SQL:NOW()'
 403      // for simple string operations use '--SELF--' like 'field_name' => 'Copy --SELF--'
 404      // --SELF-- will be replaced by current value of the field
 405  
 406      if(empty($table) || empty($unique_field) || empty($id_value)) return false;
 407      if(!is_array($exception)) $exception = array();
 408      
 409      $table    = (is_string($prefix) ? $prefix : DB_PREPEND).$table;
 410      
 411      $where_value = is_string($id_value) ? "'".aporeplace($id_value)."'" : $id_value;
 412      $row = _dbQuery('SELECT * FROM '.$table.' WHERE '.$unique_field.'='.$where_value.' LIMIT 1');
 413  
 414      // check against result
 415      if(isset($row[0]) && is_array($row[0]) && count($row[0])) {
 416          $row = $row[0];
 417          unset($row[$unique_field]);
 418      } else {
 419          return false;
 420      }
 421          
 422      // check eceptions
 423      foreach($exception as $key => $value) {
 424          if(isset($row[$key])) {
 425              if($value === '--UNIQUE--') {
 426                  unset($row[$key]);
 427              } else {
 428                  if(is_string($value) && strpos($value, '--SELF--') !== false) {
 429                      $value = str_replace('--SELF--', $row[$key], $value);
 430                  }
 431                  $row[$key] = $value;
 432              }
 433          }
 434      }
 435      
 436      $_VALUE    = array();
 437      $_SET    = array();
 438      $c        = 0;
 439      
 440      // build INSERT query
 441      foreach($row as $key => $value) {
 442          $_VALUE[$c]    = $key;
 443          if(is_string($value)) {
 444              if(strpos($value, 'SQL:') === 0) {
 445                  $_SET[$c] = str_replace('SQL:', '', $value);
 446              } else {
 447                  $_SET[$c] = "'".mysql_real_escape_string($value)."'";
 448              }
 449          } else {
 450              $_SET[$c] = $value;
 451          }
 452          $c++;
 453      }
 454      
 455      $sql  = 'INSERT INTO '.$table.' (';
 456      $sql .= implode(', ', $_VALUE);
 457      $sql .= ') VALUES (';
 458      $sql .= implode(', ', $_SET);
 459      $sql .= ')';
 460  
 461      $new_id = _dbQuery($sql, 'INSERT');
 462  
 463      if(!empty($new_id['INSERT_ID'])) {
 464  
 465          // fine - auto increment returns new ID
 466          return $new_id['INSERT_ID'];
 467  
 468      } elseif(isset($new_id['INSERT_ID']) && $new_id['INSERT_ID'] === 0) {
 469  
 470          // hm - maybe no auto increment - but insert was done
 471          // so lets check against $unique_field and its possible new value
 472          if(!empty($exception[$unique_field]) && $exception[$unique_field] != '__UNIQUE__') {
 473              return $exception[$unique_field];
 474          }
 475  
 476      }
 477      return false;
 478      
 479  }
 480  
 481  /*
 482   * Set Config - store given key/value in config database
 483   *
 484   * 2008/03/13 Thiemo Mättig, fixed for MySQL 4.0, use _dbInsertOrUpdate()
 485   */
 486  function _setConfig($key, $value=NULL, $group='', $status=1) {
 487  
 488      $time        = now();
 489      $group        = trim($group);
 490      $status     = intval($status);
 491  
 492      if (! is_array($key)) {
 493          $key = array($key => $value);
 494      }
 495  
 496      foreach($key as $k => $value) {
 497  
 498          if( is_string($value) ) {
 499              $vartype = 'string';
 500          } elseif( is_int($value) ) {
 501              $vartype = 'int';
 502          } elseif( is_float($value) ) {
 503              $vartype = 'float';
 504          } elseif( is_bool($value) ) {
 505              $vartype = 'bool';
 506          } elseif( is_array($value) ) {
 507               $vartype = 'array';
 508              $value   = serialize($value);
 509          } elseif( is_object($value) ) {
 510              $vartype = 'object';
 511              $value   = serialize($value);
 512          } else {
 513              $vartype = '';
 514              $value   = '';
 515          }
 516          
 517          $data = array(    'sysvalue_key'            => $k,
 518                          'sysvalue_group'        => $group,
 519                          'sysvalue_lastchange'    => $time,
 520                          'sysvalue_status'        => $status,
 521                          'sysvalue_vartype'        => $vartype,
 522                          'sysvalue_value'        => $value     );
 523  
 524          if ( ! _dbInsertOrUpdate('phpwcms_sysvalue', $data) ) {
 525              trigger_error("_setConfig failed", E_USER_ERROR);
 526          }
 527  
 528      }
 529  
 530      return true;
 531  }
 532  
 533  function _dbEscape($value='', $quoted=TRUE) {
 534      if(!is_string($value) && !is_numeric($value)) {
 535          if(is_array($value) || is_object($value)) {
 536              $value = serialize($value);
 537          } elseif(is_bool($value)) {
 538              return $value ? 'true' : 'false';
 539          } elseif(is_null($value)) {
 540              return 'NULL';
 541          } else {
 542              $value = strval($value);
 543          }
 544      }
 545      $value = mysql_real_escape_string($value);
 546      return $quoted === TRUE ? "'".$value."'" : $value;
 547  }
 548  
 549  /*
 550   * Get Config - retrieve Config value from database
 551   *
 552   * If $key is string, single value will be returned.
 553   * If $key given as array - array containing values will be returned.
 554   * If $set_global is set config value will be registered in $GLOBALS[$set_global],
 555   * set $set_global = FALSE and var will not be registered in $GLOBALS
 556   */
 557  function _getConfig($key, $set_global='phpwcms') {
 558      $return = 'array';
 559      $string = '';
 560      if(is_string($key)) {
 561          if($set_global && isset($GLOBALS[$set_global][$key])) {
 562              return $GLOBALS[$set_global][$key];
 563          }
 564          $return = 'value';
 565          $string = $key;
 566          $key = array($key);
 567      }
 568      if(is_array($key) && count($key)) {
 569          $result = array();
 570          foreach($key as $value) {
 571              if($set_global && isset($GLOBALS[$set_global][$value])) {
 572                  $result[ $value ] = $GLOBALS[$set_global][$value];
 573                  continue;
 574              }
 575              $sql = 'SELECT * FROM '.DB_PREPEND."phpwcms_sysvalue WHERE sysvalue_status=1 AND sysvalue_key='".mysql_real_escape_string($value)."'";
 576              $row = _dbQuery($sql);
 577              if(isset($row[0])) {
 578                  switch($row[0]['sysvalue_vartype']) {
 579                      case 'string':    $result[ $value ] = (string) $row[0]['sysvalue_value'];                    break;
 580                      case 'int':        $result[ $value ] = (int) $row[0]['sysvalue_value'];                    break;
 581                      case 'float':    $result[ $value ] = (float) $row[0]['sysvalue_value'];                    break;
 582                      case 'bool':    $result[ $value ] = (bool) $row[0]['sysvalue_value'];                    break;
 583                      case 'array':    $result[ $value ] = (array) @unserialize($row[0]['sysvalue_value']);    break;
 584                      case 'object':    $result[ $value ] = (object) @unserialize($row[0]['sysvalue_value']);    break;
 585                      default:        $result[ $value ] = $row[0]['sysvalue_value'];
 586                  }
 587              }
 588          }
 589          if($set_global && count($result)) {
 590              foreach($result as $key => $value) {
 591                  $GLOBALS[$set_global][$key] = $result[$key];
 592              }
 593          }
 594          if($return === 'array')    {
 595              return $result;
 596          } elseif(isset($result[$string])) {
 597              return $result[$string];
 598          }        
 599      }
 600      return false;
 601  }
 602  
 603  ?>


Generated: Wed Dec 30 05:55:15 2009 Cross-referenced by PHPXref 0.7