source: branches/2.2/include/dblayer/functions_mysql.inc.php @ 12009

Last change on this file since 12009 was 12009, checked in by plg, 13 years ago

bug 2416 fixed: the CAST function in MySQL seems to return unexpected results,
depending on MySQL version. As a consequence it was producing virtual years in
calendar display.

File size: 14.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24define('DB_ENGINE', 'MySQL');
25define('REQUIRED_MYSQL_VERSION', '5.0.0');
26
27define('DB_REGEX_OPERATOR', 'REGEXP');
28define('DB_RANDOM_FUNCTION', 'RAND');
29
30/**
31 *
32 * simple functions
33 *
34 */
35
36function pwg_db_connect($host, $user, $password, $database)
37{ 
38  $link = @mysql_connect($host, $user, $password);
39  if (!$link)
40  {
41    throw new Exception("Can't connect to server");
42  }
43  if (mysql_select_db($database, $link))
44  {
45    return $link;
46  }
47  else
48  {
49    throw new Exception('Connection to server succeed, but it was impossible to connect to database');
50  }
51}
52
53function pwg_db_check_charset() 
54{
55  $db_charset = 'utf8';
56  if (defined('DB_CHARSET') and DB_CHARSET != '')
57  {
58    $db_charset = DB_CHARSET;
59  }
60  pwg_query('SET NAMES "'.$db_charset.'"');
61}
62
63function pwg_db_check_version()
64{
65  $current_mysql = pwg_get_db_version();
66  if (version_compare($current_mysql, REQUIRED_MYSQL_VERSION, '<'))
67  {
68    fatal_error(
69      sprintf(
70        'your MySQL version is too old, you have "%s" and you need at least "%s"',
71        $current_mysql,
72        REQUIRED_MYSQL_VERSION
73        )
74      );
75  }
76}
77
78function pwg_get_db_version() 
79{
80  return mysql_get_server_info();
81}
82
83function pwg_query($query)
84{
85  global $conf,$page,$debug,$t2;
86
87  $start = get_moment();
88  ($result = mysql_query($query)) or my_error($query, $conf['die_on_sql_error']);
89
90  $time = get_moment() - $start;
91
92  if (!isset($page['count_queries']))
93  {
94    $page['count_queries'] = 0;
95    $page['queries_time'] = 0;
96  }
97
98  $page['count_queries']++;
99  $page['queries_time']+= $time;
100
101  if ($conf['show_queries'])
102  {
103    $output = '';
104    $output.= '<pre>['.$page['count_queries'].'] ';
105    $output.= "\n".$query;
106    $output.= "\n".'(this query time : ';
107    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
108    $output.= "\n".'(total SQL time  : ';
109    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
110    $output.= "\n".'(total time      : ';
111    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
112    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
113    {
114      $output.= "\n".'(num rows        : ';
115      $output.= mysql_num_rows($result).' )';
116    }
117    elseif ( $result!=null
118      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) )
119    {
120      $output.= "\n".'(affected rows   : ';
121      $output.= mysql_affected_rows().' )';
122    }
123    $output.= "</pre>\n";
124
125    $debug .= $output;
126  }
127
128  return $result;
129}
130
131function pwg_db_nextval($column, $table)
132{
133  $query = '
134SELECT IF(MAX('.$column.')+1 IS NULL, 1, MAX('.$column.')+1)
135  FROM '.$table;
136  list($next) = pwg_db_fetch_row(pwg_query($query));
137
138  return $next;
139}
140
141function pwg_db_changes($result) 
142{
143  return mysql_affected_rows();
144}
145
146function pwg_db_num_rows($result) 
147{
148  return mysql_num_rows($result);
149}
150
151function pwg_db_fetch_assoc($result)
152{
153  return mysql_fetch_assoc($result);
154}
155
156function pwg_db_fetch_row($result)
157{
158  return mysql_fetch_row($result);
159}
160
161function pwg_db_fetch_object($result)
162{
163  return mysql_fetch_object($result);
164}
165
166function pwg_db_free_result($result) 
167{
168  return mysql_free_result($result);
169}
170
171function pwg_db_real_escape_string($s)
172{
173  return mysql_real_escape_string($s);
174}
175
176function pwg_db_insert_id($table=null, $column='id')
177{
178  return mysql_insert_id();
179}
180
181/**
182 *
183 * complex functions
184 *
185 */
186
187/**
188 * creates an array based on a query, this function is a very common pattern
189 * used here
190 *
191 * @param string $query
192 * @param string $fieldname
193 * @return array
194 */
195function array_from_query($query, $fieldname)
196{
197  $array = array();
198
199  $result = pwg_query($query);
200  while ($row = mysql_fetch_assoc($result))
201  {
202    array_push($array, $row[$fieldname]);
203  }
204
205  return $array;
206}
207
208define('MASS_UPDATES_SKIP_EMPTY', 1);
209/**
210 * updates multiple lines in a table
211 *
212 * @param string table_name
213 * @param array dbfields
214 * @param array datas
215 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
216 * @return void
217 */
218function mass_updates($tablename, $dbfields, $datas, $flags=0)
219{
220  if (count($datas) == 0)
221    return;
222  // depending on the MySQL version, we use the multi table update or N update queries
223  if (count($datas) < 10)
224  {
225    foreach ($datas as $data)
226    {
227      $query = '
228UPDATE '.$tablename.'
229  SET ';
230      $is_first = true;
231      foreach ($dbfields['update'] as $key)
232      {
233        $separator = $is_first ? '' : ",\n    ";
234
235        if (isset($data[$key]) and $data[$key] !== '')
236        {
237          $query.= $separator.$key.' = \''.$data[$key].'\'';
238        }
239        else
240        {
241          if ($flags & MASS_UPDATES_SKIP_EMPTY )
242            continue; // next field
243          $query.= "$separator$key = NULL";
244        }
245        $is_first = false;
246      }
247      if (!$is_first)
248      {// only if one field at least updated
249        $query.= '
250  WHERE ';
251        $is_first = true;
252        foreach ($dbfields['primary'] as $key)
253        {
254          if (!$is_first)
255          {
256            $query.= ' AND ';
257          }
258          if ( isset($data[$key]) )
259          {
260            $query.= $key.' = \''.$data[$key].'\'';
261          }
262          else
263          {
264            $query.= $key.' IS NULL';
265          }
266          $is_first = false;
267        }
268        pwg_query($query);
269      }
270    } // foreach update
271  } // if mysql_ver or count<X
272  else
273  {
274    // creation of the temporary table
275    $query = '
276SHOW FULL COLUMNS FROM '.$tablename;
277    $result = pwg_query($query);
278    $columns = array();
279    $all_fields = array_merge($dbfields['primary'], $dbfields['update']);
280    while ($row = pwg_db_fetch_assoc($result))
281    {
282      if (in_array($row['Field'], $all_fields))
283      {
284        $column = $row['Field'];
285        $column.= ' '.$row['Type'];
286
287        $nullable = true;
288        if (!isset($row['Null']) or $row['Null'] == '' or $row['Null']=='NO')
289        {
290          $column.= ' NOT NULL';
291          $nullable = false;
292        }
293        if (isset($row['Default']))
294        {
295          $column.= " default '".$row['Default']."'";
296        }
297        elseif ($nullable)
298        {
299          $column.= " default NULL";
300        }
301        if (isset($row['Collation']) and $row['Collation'] != 'NULL')
302        {
303          $column.= " collate '".$row['Collation']."'";
304        }
305        array_push($columns, $column);
306      }
307    }
308
309    $temporary_tablename = $tablename.'_'.micro_seconds();
310
311    $query = '
312CREATE TABLE '.$temporary_tablename.'
313(
314  '.implode(",\n  ", $columns).',
315  UNIQUE KEY the_key ('.implode(',', $dbfields['primary']).')
316)';
317
318    pwg_query($query);
319    mass_inserts($temporary_tablename, $all_fields, $datas);
320    if ( $flags & MASS_UPDATES_SKIP_EMPTY )
321      $func_set = create_function('$s', 'return "t1.$s = IFNULL(t2.$s, t1.$s)";');
322    else
323      $func_set = create_function('$s', 'return "t1.$s = t2.$s";');
324
325    // update of images table by joining with temporary table
326    $query = '
327UPDATE '.$tablename.' AS t1, '.$temporary_tablename.' AS t2
328  SET '.
329      implode(
330        "\n    , ",
331        array_map($func_set,$dbfields['update'])
332        ).'
333  WHERE '.
334      implode(
335        "\n    AND ",
336        array_map(
337          create_function('$s', 'return "t1.$s = t2.$s";'),
338          $dbfields['primary']
339          )
340        );
341    pwg_query($query);
342    $query = '
343DROP TABLE '.$temporary_tablename;
344    pwg_query($query);
345  }
346}
347
348
349/**
350 * inserts multiple lines in a table
351 *
352 * @param string table_name
353 * @param array dbfields
354 * @param array inserts
355 * @return void
356 */
357function mass_inserts($table_name, $dbfields, $datas)
358{
359  if (count($datas) != 0)
360  {
361    $first = true;
362
363    $query = 'SHOW VARIABLES LIKE \'max_allowed_packet\'';
364    list(, $packet_size) = pwg_db_fetch_row(pwg_query($query));
365    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
366    $query = '';
367
368    foreach ($datas as $insert)
369    {
370      if (strlen($query) >= $packet_size)
371      {
372        pwg_query($query);
373        $first = true;
374      }
375
376      if ($first)
377      {
378        $query = '
379INSERT INTO '.$table_name.'
380  ('.implode(',', $dbfields).')
381  VALUES';
382        $first = false;
383      }
384      else
385      {
386        $query .= '
387  , ';
388      }
389
390      $query .= '(';
391      foreach ($dbfields as $field_id => $dbfield)
392      {
393        if ($field_id > 0)
394        {
395          $query .= ',';
396        }
397
398        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
399        {
400          $query .= 'NULL';
401        }
402        else
403        {
404          $query .= "'".$insert[$dbfield]."'";
405        }
406      }
407      $query .= ')';
408    }
409    pwg_query($query);
410  }
411}
412
413/**
414 * Do maintenance on all PWG tables
415 *
416 * @return none
417 */
418function do_maintenance_all_tables()
419{
420  global $prefixeTable, $page;
421
422  $all_tables = array();
423
424  // List all tables
425  $query = 'SHOW TABLES LIKE \''.$prefixeTable.'%\'';
426  $result = pwg_query($query);
427  while ($row = pwg_db_fetch_row($result))
428  {
429    array_push($all_tables, $row[0]);
430  }
431
432  // Repair all tables
433  $query = 'REPAIR TABLE '.implode(', ', $all_tables);
434  $mysql_rc = pwg_query($query);
435
436  // Re-Order all tables
437  foreach ($all_tables as $table_name)
438  {
439    $all_primary_key = array();
440
441    $query = 'DESC '.$table_name.';';
442    $result = pwg_query($query);
443    while ($row = pwg_db_fetch_assoc($result))
444    {
445      if ($row['Key'] == 'PRI')
446      {
447        array_push($all_primary_key, $row['Field']);
448      }
449    }
450
451    if (count($all_primary_key) != 0)
452    {
453      $query = 'ALTER TABLE '.$table_name.' ORDER BY '.implode(', ', $all_primary_key).';';
454      $mysql_rc = $mysql_rc && pwg_query($query);
455    }
456  }
457
458  // Optimize all tables
459  $query = 'OPTIMIZE TABLE '.implode(', ', $all_tables);
460  $mysql_rc = $mysql_rc && pwg_query($query);
461  if ($mysql_rc)
462  {
463    array_push(
464          $page['infos'],
465          l10n('All optimizations have been successfully completed.')
466          );
467  }
468  else
469  {
470    array_push(
471          $page['errors'],
472          l10n('Optimizations have been completed with some errors.')
473          );
474  }
475}
476
477function pwg_db_concat($array)
478{
479  $string = implode($array, ',');
480  return 'CONCAT('. $string.')';
481}
482
483function pwg_db_concat_ws($array, $separator)
484{
485  $string = implode($array, ',');
486  return 'CONCAT_WS(\''.$separator.'\','. $string.')';
487}
488
489function pwg_db_cast_to_text($string)
490{
491  return $string;
492}
493
494/**
495 * returns an array containing the possible values of an enum field
496 *
497 * @param string tablename
498 * @param string fieldname
499 */
500function get_enums($table, $field)
501{
502  // retrieving the properties of the table. Each line represents a field :
503  // columns are 'Field', 'Type'
504  $result = pwg_query('desc '.$table);
505  while ($row = pwg_db_fetch_assoc($result))
506  {
507    // we are only interested in the the field given in parameter for the
508    // function
509    if ($row['Field'] == $field)
510    {
511      // retrieving possible values of the enum field
512      // enum('blue','green','black')
513      $options = explode(',', substr($row['Type'], 5, -1));
514      foreach ($options as $i => $option)
515      {
516        $options[$i] = str_replace("'", '',$option);
517      }
518    }
519  }
520  pwg_db_free_result($result);
521  return $options;
522}
523
524// get_boolean transforms a string to a boolean value. If the string is
525// "false" (case insensitive), then the boolean value false is returned. In
526// any other case, true is returned.
527function get_boolean( $string )
528{
529  $boolean = true;
530  if ( 'false' == strtolower($string) )
531  {
532    $boolean = false;
533  }
534  return $boolean;
535}
536
537/**
538 * returns boolean string 'true' or 'false' if the given var is boolean
539 *
540 * @param mixed $var
541 * @return mixed
542 */
543function boolean_to_string($var)
544{
545  if (is_bool($var))
546  {
547    return $var ? 'true' : 'false';
548  }
549  else
550  {
551    return $var;
552  }
553}
554
555/**
556 *
557 * interval and date functions
558 *
559 */
560
561function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
562{
563  if ($date!='CURRENT_DATE')
564  {
565    $date = '\''.$date.'\'';
566  }
567
568  return 'SUBDATE('.$date.',INTERVAL '.$period.' DAY)';
569}
570
571function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
572{
573  $query = '
574SELECT '.pwg_db_get_recent_period_expression($period);
575  list($d) = pwg_db_fetch_row(pwg_query($query));
576
577  return $d;
578}
579
580function pwg_db_get_flood_period_expression($seconds)
581{
582  return 'SUBDATE(now(), INTERVAL '.$seconds.' SECOND)';
583}
584
585function pwg_db_get_hour($date) 
586{
587  return 'hour('.$date.')';
588}
589
590function pwg_db_get_date_YYYYMM($date)
591{
592  return 'DATE_FORMAT('.$date.', \'%Y%m\')';
593}
594
595function pwg_db_get_date_MMDD($date)
596{
597  return 'DATE_FORMAT('.$date.', \'%m%d\')';
598}
599
600function pwg_db_get_year($date)
601{
602  return 'YEAR('.$date.')';
603}
604
605function pwg_db_get_month($date)
606{
607  return 'MONTH('.$date.')';
608}
609
610function pwg_db_get_week($date, $mode=null)
611{
612  if ($mode)
613  {
614    return 'WEEK('.$date.', '.$mode.')';
615  }
616  else
617  {
618    return 'WEEK('.$date.')';
619  }
620}
621
622function pwg_db_get_dayofmonth($date)
623{
624  return 'DAYOFMONTH('.$date.')';
625}
626
627function pwg_db_get_dayofweek($date)
628{
629  return 'DAYOFWEEK('.$date.')';
630}
631
632function pwg_db_get_weekday($date)
633{
634  return 'WEEKDAY('.$date.')';
635}
636
637function pwg_db_date_to_ts($date) 
638{
639  return 'UNIX_TIMESTAMP('.$date.')';
640}
641
642// my_error returns (or send to standard output) the message concerning the
643// error occured for the last mysql query.
644function my_error($header, $die)
645{
646  $error = "[mysql error ".mysql_errno().'] '.mysql_error()."\n";
647  $error .= $header;
648
649  if ($die)
650  {
651    fatal_error($error);
652  }
653  echo("<pre>");
654  trigger_error($error, E_USER_WARNING);
655  echo("</pre>");
656}
657
658?>
Note: See TracBrowser for help on using the repository browser.