Glossword PHP Cross Reference Learning Management Systems

Source: /lib/class.db.mysql.php - 522 lines - 13295 bytes - Summary - Text - Print

Description: Glossword - glossary compiler (http://glossword.biz/) 2008 Glossword.biz team 2002-2008 Dmitry N. Shilnikov <dev at glossword dot info> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. (see `http://creativecommons.org/licenses/GPL/2.0/' for details)

   1  <?php
   2  /**

   3   *  Glossword - glossary compiler (http://glossword.biz/)

   4   *   2008 Glossword.biz team

   5   *   2002-2008 Dmitry N. Shilnikov <dev at glossword dot info>

   6   *

   7   *  This program is free software; you can redistribute it and/or modify

   8   *  it under the terms of the GNU General Public License as published by

   9   *  the Free Software Foundation; either version 2 of the License, or

  10   *  (at your option) any later version.

  11   *  (see `http://creativecommons.org/licenses/GPL/2.0/' for details)

  12   */
  13  // --------------------------------------------------------

  14  /**

  15   * Database class.

  16   *

  17   * uses also: class gw_timer;

  18   * @version $Id: class.db.mysql.php 492 2008-06-13 22:58:27Z glossword_team $

  19   */
  20  // --------------------------------------------------------

  21  if (!defined('IS_CLASS_DB'))
  22  {
  23      define('IS_CLASS_DB', 1);
  24      //

  25      define('IS_FREE_RESULT', 1);
  26      /* halt with message */

  27      define('ON_ERROR_HALT', 1);
  28      /* ignore errors quietly */

  29      define('ON_ERROR_IGNORE', 2);
  30      /* ignore error, but spit a warning */

  31      define('ON_ERROR_MSG', 3);
  32  class gwtkDataBase
  33  {
  34      var $host         = '';
  35      var $database     = '';
  36      var $user         = '';
  37      var $password     = '';
  38      var $connect_type = '';
  39      var $connect_time = 0;
  40      var $query_time   = 0;
  41      var $query_array  = array();
  42      var $on_error_default = ON_ERROR_MSG;
  43      var $max_queries_debug = 100;
  44      var $cnt_queries_debug = 0;
  45      
  46      /**

  47       * Transparent query caching

  48       */
  49      var $is_cache = 0;
  50      var $cache_lifetime = 5;
  51      var $is_print_events = 0;
  52      /**

  53       * public: result array and current row number

  54       */
  55      var $record   = array();
  56      var $row      = 0;
  57      var $errno    = 0;
  58      var $error    = '';
  59      /**

  60       * private: Link and query handles

  61       */
  62      var $link_id  = 0;
  63      var $query_id = 0;
  64      /**

  65       * Calls Universal query-caching engine (is exist)

  66       * by Dmitry Shilnikov <dev at glossword dot info>

  67       */
  68  	function setCache($dir = '')
  69      {
  70          if (defined("IS_CLASS_CACHE"))
  71          {
  72              global $oCh;
  73              $oCh = new gwtkCache;
  74              $oCh->setPath($dir);
  75              $this->is_cache = 1;
  76              $oCh->cache_lifetime = $this->cache_lifetime;
  77          }
  78      }
  79      /**

  80       *

  81       */
  82  	function connect($db_host = '', $db_user = '', $db_password = '', $db_name = '', $is_pconnect = 0)
  83      {
  84          if ($db_host != '') $this->host = $db_host;
  85          if ($db_user != '') $this->user = $db_user;
  86          if ($db_password != '') $this->password = $db_password;
  87          if ($db_name != '') $this->database = $db_name;
  88          /* */

  89          if (!$this->link_id)
  90          {
  91              $this->database = trim(str_replace('`', '', $this->database));
  92              if (defined("GW_DEBUG_SQL_TIME") && defined("IS_CLASS_TIMER") && GW_DEBUG_SQL_TIME == 1)
  93              {
  94                  $t = new gw_timer('q');
  95              }
  96              $connect_type = ($is_pconnect) ? 'mysql_pconnect' : 'mysql_connect';
  97              $this->connect_type = $connect_type . '('.$this->host.');';
  98              if (!$this->link_id = @$connect_type($this->host, $this->user, $this->password))
  99              {
 100                  $this->halt("Could not " . $this->connect_type . " to the database server ($this->host, $this->user).", $this->on_error_default);
 101              }
 102              if (!@mysql_select_db($this->database))
 103              {
 104                  @mysql_close($this->link_id);
 105                  $this->halt('Could not select database ('.$this->database.').', $this->on_error_default);
 106              }
 107              @mysql_query('SET NAMES \'utf8\'', $this->link_id);
 108              if (defined("GW_DEBUG_SQL_TIME") && defined("IS_CLASS_TIMER") && GW_DEBUG_SQL_TIME == 1)
 109              {
 110                  $this->connect_time = $t->end();
 111              }
 112          }
 113          return $this->link_id;
 114      } // end of connect();

 115      /**

 116       * Post a query to database

 117       */
 118  	function query($query = '')
 119      {
 120          if ($query != '')
 121          {
 122              $time_end = 0;
 123              if (!$this->connect())
 124              {
 125                  return false;
 126              }
 127              if (isset($this->query_id))
 128              {
 129                  $this->free_result();
 130              }
 131              if (defined("GW_DEBUG_SQL_TIME") && defined("IS_CLASS_TIMER") && GW_DEBUG_SQL_TIME == 1)
 132              {
 133                  $t = new gw_timer('q');
 134              }
 135              if (!$this->query_id = @mysql_query($query, $this->link_id))
 136              {
 137                  $this->halt('Invalid SQL: ' . $query, $this->on_error_default);
 138              }
 139              if (defined("GW_DEBUG_SQL_TIME") && defined("IS_CLASS_TIMER") && GW_DEBUG_SQL_TIME == 1)
 140              {
 141                  $time_end = $t->end();
 142                  $this->query_time += $time_end;
 143              }
 144              if (sizeof($this->query_array) < $this->max_queries_debug 
 145                  && defined("GW_DEBUG_SQL_QUERY") 
 146                  && defined("IS_CLASS_TIMER") 
 147                  && GW_DEBUG_SQL_QUERY == 1)
 148              {
 149                  // faster than htmlspecialchars()

 150                  $this->query_array[] = sprintf('<strong>%1.5f</strong> %s', $time_end,  htmlspecialchars_ltgt($query) );
 151              }
 152              $this->cnt_queries_debug++;
 153              return $this->query_id;
 154          } // query is not empty

 155          return false;
 156      } // end of query();

 157      /**

 158       *

 159       */
 160  	function isDuplicate($query = '')
 161      {
 162          if ($query != '')
 163          {
 164              if (!$this->query_id = @mysql_query($query, $this->link_id))
 165              {
 166                  return preg_match("/Duplicate entry/i", @mysql_error($this->link_id));
 167              }
 168          }
 169          return false;
 170      }
 171      /**

 172       *

 173       */
 174  	function next_record()
 175      {
 176          if (!$this->query_id)
 177          {
 178              $this->halt("next_record() called with no query pending.", $this->on_error_default);
 179              return 0;
 180          }
 181          $this->record = @mysql_fetch_assoc($this->query_id);
 182          $this->row   += 1;
 183          $stat = is_array($this->record);
 184          if (!$stat && IS_FREE_RESULT)
 185          {
 186              $this->free_result();
 187          }
 188          return $stat;
 189      } //

 190      /**

 191       *

 192       */
 193  	function free_result($query_id = -1)
 194      {
 195          if ($query_id != -1)
 196          {
 197              $this->query_id = $query_id;
 198              if ($this->is_print_events)
 199              {
 200                  print '<br/>DB: free ' . $query_id;
 201              }
 202          }
 203          return @mysql_free_result($this->query_id);
 204      } // end of free_result();

 205      /**

 206       *

 207       */
 208  	function close()
 209      {
 210          if ($this->link_id)
 211          {
 212              if ($this->is_print_events)
 213              {
 214                  print '<br>DB: close';
 215              }
 216              if ($this->query_id)
 217              {
 218                  $this->free_result($this->query_id);
 219              }
 220              return @mysql_close($this->link_id);
 221          }
 222          else
 223          {
 224              return false;
 225          }
 226      } // end of close();

 227      /* private: error handling */

 228      ## ------------------------------------------

 229      ##

 230  	function halt($msg, $errMode = 1)
 231      {
 232          $this->Error = @mysql_error($this->link_id);
 233          $this->Errno = @mysql_errno($this->link_id);
 234          if ($errMode == ON_ERROR_IGNORE) { return; }
 235          $this->haltmsg($msg);
 236          if ($errMode == ON_ERROR_HALT)
 237          {
 238              die("Session halted.");
 239          }
 240      }
 241  	function haltmsg($msg)
 242      {
 243          echo '<div style="margin:3px 0;border:3px solid #EEE;font:10pt sans-serif;width:98%;overflow:hidden">',
 244               '<dl><dt style="padding:0 1em;color:#C80"><strong>Database error</strong></dt> <dd>', substr($msg, 0, 1024), '<br /><em style="color:#888">(', strlen($msg), ' characters)</em></dd></dl>',
 245               '<dl><dt style="padding:0 1em;color:#C08"><strong>MySQL Error</strong></dt> <dd>', $this->Errno, ' (', $this->Error,')</dd></dl></div>';
 246      }
 247      ##

 248      ## ------------------------------------------

 249      /* public: table locking */

 250  	function lock($table, $mode = "WRITE")
 251      {
 252          $this->connect();
 253          $sql = 'LOCK TABLES ';
 254          if (is_array($table)) // many tables
 255          {
 256              while (list($k, $v) = each($table))
 257              {
 258                  if (($k == "read") && ($k != 0))
 259                  {
 260                      $sql .= $v .' READ, ';
 261                  }
 262                  else
 263                  {
 264                      $sql .= $v .' ' . $mode . ', ';
 265                  }
 266              }
 267              $sql = substr($sql, 0, -2);
 268          }
 269          else
 270          {
 271              $sql .= $table . ' ' . $mode;
 272          }
 273          // $this->query($sql);

 274          $res = @mysql_query($sql, $this->link_id);
 275          if (!$res)
 276          {
 277              $str = is_array($table) ? implode(', ', $table) : $table;
 278              $this->halt("Can't lock($str, $mode)");
 279              return 0;
 280          }
 281          return $res;
 282      }
 283  	function unlock()
 284      {
 285          $this->connect();
 286          $res = @mysql_query("UNLOCK TABLES", $this->link_id);
 287          if (!$res)
 288          {
 289              $this->halt("Can't unlock().");
 290              return 0;
 291          }
 292          return $res;
 293      }
 294      //

 295  	function num_fields()
 296      {
 297          return @mysql_num_fields($this->query_id);
 298      }
 299  	function num_rows()
 300      {
 301          return @mysql_num_rows($this->query_id);
 302      }
 303      /* public: evaluate the result (size, width) */

 304  	function affected_rows()
 305      {
 306          return (@mysql_affected_rows($this->link_id) > 0) ? mysql_affected_rows($this->link_id) : 0;
 307      }
 308      /* public: shorthand notation */

 309      function r($name)
 310      {
 311          return isset($this->record[$name]) ? $this->record[$name] : 0;
 312      }
 313      /* Get the list of databases */

 314  	function get_databases()
 315      {
 316          $this->database = trim(str_replace('`', '', $this->database));
 317          if ($this->link_id)
 318          {
 319              $db_list = mysql_list_dbs($this->link_id);
 320              $ar = array();
 321              while ($row = mysql_fetch_array($db_list))
 322              {
 323                  $ar[$row['Database']] = $row['Database'];
 324              }
 325          }
 326          else
 327          {
 328              $sql = 'SHOW DATABASES';
 329              $this->query($sql);
 330              $ar = array();
 331              if ($this->query_id)
 332              {
 333                  while ($row = mysql_fetch_array($this->query_id, MYSQL_NUM))
 334                  {
 335                      $ar[$row[0]] = $row[0];
 336                  }
 337              }
 338          }
 339          return $ar;
 340      }
 341      /* Get the list of tables from current database */

 342  	function table_names($tablename = '')
 343      {
 344          $this->database = trim(str_replace('`', '', $this->database));
 345          $sql = 'SHOW TABLES FROM `' . $this->database.'`';
 346          $ar = array();
 347          if ($tablename != '')
 348          {
 349              $sql = 'SHOW TABLES FROM `' . $this->database . '` LIKE "' . $tablename . '"';
 350          }
 351          $this->query($sql);
 352          while ($row = mysql_fetch_array($this->query_id, MYSQL_NUM))
 353          {
 354              $ar[] = $row[0];
 355          }
 356          return $ar;
 357      }
 358      /*

 359       * Get all information about table

 360       * works with MySQL version 3.23.10 or above

 361       */
 362  	function table_info($tablename = '')
 363      {
 364          if ($tablename != '')
 365          {
 366              $this->database = trim(str_replace('`', '', $this->database));
 367              $this->query('SHOW TABLE STATUS FROM `' . $this->database . '` LIKE "' . $tablename . '";');
 368              if ($this->query_id)
 369              {
 370                  return mysql_fetch_assoc($this->query_id);
 371              }
 372          }
 373          return array();
 374      }
 375      /* get last known maximum value */

 376  	function MaxId($tablename, $field = 'id')
 377      {
 378          if ($tablename != '')
 379          {
 380              $this->query('SELECT MAX(' . $field . ') AS n FROM `' . $tablename . '`;');
 381              $arID = mysql_fetch_assoc($this->query_id);
 382              return ($arID['n'] + 1);
 383          }
 384          return 1;
 385      }
 386      // New from Glossword 2.0

 387      /**

 388       * All queries for cache

 389       *

 390       * @access  public

 391       */
 392  	function sqlRun($q, $cache_prefix = '')
 393      {
 394          return ( $this->_sql_is_cached($q, $cache_prefix) ) ? $this->_sql_return($q, $cache_prefix) : $this->sqlExec($q, $cache_prefix, 1);
 395          /* 02 feb 2006: Memory cache 

 396          global $gw_ar_cache_sql;

 397          $qkey = sprintf("%u", crc32($q));

 398          if (!isset($gw_ar_cache_sql['cnt']))

 399          {

 400              $gw_ar_cache_sql['cnt'] = 0;

 401          }

 402          if (isset($gw_ar_cache_sql[$qkey]))

 403          {

 404              $gw_ar_cache_sql['cnt']++;

 405              return unserialize($gw_ar_cache_sql[$qkey]);

 406          }

 407          else

 408          {

 409              $o = $this->_sql_is_cached($q, $cache_prefix) 

 410                  ? ($this->_sql_return($q, $cache_prefix)) 

 411                  : ($this->sqlExec($q, $cache_prefix, 1));

 412              $gw_ar_cache_sql[$qkey] = serialize($o);

 413              return $o;

 414          }

 415          */
 416      }
 417      /**

 418       * Executes query without cache

 419       *

 420       * @access  public

 421       * @see gw_fixslash();

 422       */
 423  	function sqlExec($q, $cache_prefix = '', $is_cache_def = 0)
 424      {
 425          // on error: Only `SELECT' query returns empty array, other returns FALSE

 426          $empty_value = preg_match("/^SELECT/", $q) ? array() : false;
 427          //

 428          // Connect and post query

 429          $this->query($q);
 430          //

 431          // on error: returned status for UPDATE, DELETE etc. (not SELECT)

 432          if (($this->affected_rows() > 0) && !$empty_value)
 433          {
 434              $empty_value = true;
 435          }
 436          // on error: DELETE returns true when no affected rows

 437          elseif (($this->affected_rows() == 0) && preg_match("/^(DELETE|DROP|CREATE|ALTER)/", $q))
 438          {
 439              $empty_value = true;
 440          }
 441          $ar = array();
 442  
 443          // Is here any returned data row?

 444          if ($this->num_rows() > 0)
 445          {
 446              while ($this->next_record())
 447              {
 448                  $ar[] = $this->record;
 449              }
 450          }
 451          // Fix quotes in array

 452          gw_fixslash($ar, 'runtime');
 453          //

 454          // Put query into cache

 455          if ($this->is_cache && $is_cache_def && preg_match("/^SELECT/", $q))
 456          {
 457              global $oCh;
 458              $oCh->setKey($q, $cache_prefix);
 459              $oCh->save($ar, 'array');
 460          }
 461          //

 462          if ( empty($ar) ) { $ar = $empty_value; }
 463          return $ar;
 464      }
 465      /**

 466       * @access  private

 467       */
 468  	function _sql_is_cached($q, $cache_prefix = '')
 469      {
 470          // only SELECT can be cached

 471          $is_cache = preg_match("/^SELECT/", $q) ? $this->is_cache : 0;
 472          if ($is_cache)
 473          {
 474              global $oCh;
 475              $oCh->setKey($q, $cache_prefix);
 476              $is_cache = $oCh->checkout();
 477          }
 478          return $is_cache;
 479      }
 480      /**

 481       * @access  private

 482       */
 483  	function _sql_return($q, $cache_prefix = '')
 484      {
 485          global $oCh;
 486          $oCh->setKey($q, $cache_prefix);
 487          return $oCh->load('array');
 488      }
 489      /**

 490       * Builds query "LIMIT n,n" for database

 491       *

 492       * @param    int   $total    total number of items

 493       * @param    int   $page     current page number

 494       * @param    int   $perpage  items per page

 495       * @return   string  part of database query

 496       */
 497  	function prn_limit($total, $page, $perpage)
 498      {
 499          $numpages = ceil($total / $perpage);
 500          for ($i = 1; $i <= $numpages; $i++)
 501          {
 502              $position = ($i * $perpage);
 503              if ($i == ($page - 1))
 504              {
 505                  return ' LIMIT '.$position.', '.$perpage;
 506              }
 507          }
 508          return ' LIMIT 0, '.$perpage;
 509      }
 510  
 511  } // end of class

 512  } // defined IS_CLASS_DB

 513  //

 514  class gwtkDb extends gwtkDataBase
 515  {
 516      var $host     = GW_DB_HOST;
 517      var $user     = GW_DB_USER;
 518      var $password = GW_DB_PASSWORD;
 519      var $database = GW_DB_DATABASE;
 520      var $is_print_events = 0;
 521  }
 522  ?>

title

Description

title

Description

title

Description

title

title

Body