[ Index ]

PHP Cross Reference of phpwcms V1.4.7 _r403 (01.11.10)

title

Body

[close]

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

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


Generated: Tue Nov 16 22:51:00 2010 Cross-referenced by PHPXref 0.7