source: trunk/include/dblayer/functions_pdo-sqlite.inc.php @ 6463

Last change on this file since 6463 was 6463, checked in by nikrou, 14 years ago

Fix bug 1717 : SQLite: access failure on Admin > Tools > History
hour function doesn't exists

File size: 13.1 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 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('REQUIRED_PDO_SQLITE_VERSION', '3.0.0');
25define('DB_ENGINE', 'SQLite');
26
27define('DB_REGEX_OPERATOR', 'REGEXP');
28define('DB_RANDOM_FUNCTION', 'RANDOM');
29
30/**
31 *
32 * simple functions
33 *
34 */
35
36function pwg_db_connect($host, $user, $password, $database)
37{
38  global $conf;
39
40  $db_file = sprintf('sqlite:%s/%s.db', $conf['local_data_dir'], $database);
41
42  $link = new PDO($db_file);
43  if (!$link)
44  {
45    throw new  Exception('Connection to server succeed, but it was impossible to connect to database');
46  }
47
48  $link->sqliteCreateFunction('now', 'pwg_now', 0);
49  $link->sqliteCreateFunction('hour', 'pwg_hour', 1);
50  $link->sqliteCreateFunction('unix_timestamp', 'pwg_unix_timestamp', 0);
51  $link->sqliteCreateFunction('md5', 'md5', 1);
52  $link->sqliteCreateFunction('if', 'pwg_if', 3);
53
54  $link->sqliteCreateFunction('regexp', 'pwg_regexp', 2);
55
56  return $link;
57}
58
59function pwg_db_check_version()
60{
61  $current_version = pwg_get_db_version();
62  if (version_compare($current_version, REQUIRED_PDO_SQLITE_VERSION, '<'))
63  {
64    fatal_error(
65      sprintf(
66        'your database version is too old, you have "%s" and you need at least "%s"',
67        $current_version,
68        REQUIRED_PDO_SQLITE_VERSION
69        )
70      );
71  }
72}
73
74function pwg_db_check_charset() 
75{
76  return true;
77}
78
79function pwg_get_db_version() 
80{
81  global $pwg_db_link;
82
83  return $pwg_db_link->getAttribute(PDO::ATTR_SERVER_VERSION);
84}
85
86function pwg_query($query)
87{
88  global $conf,$page,$debug,$t2,$pwg_db_link;
89
90  $start = get_moment();
91
92  $truncate_pattern = '`truncate(.*)`i';
93  $insert_pattern = '`(INSERT INTO [^)]*\)\s*VALUES)(\([^)]*\))\s*,\s*(.*)`mi'; 
94
95  if (preg_match($truncate_pattern, $query, $matches))
96  {
97    $query = str_replace('TRUNCATE TABLE', 'DELETE FROM', $query);
98    $truncate_query = true;
99    ($result = $pwg_db_link->exec($query)) or die($query."\n<br>".$pwg_db_link->errorInfo());
100  }
101  elseif (preg_match($insert_pattern, $query, $matches))
102  {
103    $base_query = substr($query, 0, strlen($matches[1])+1);
104    $values_pattern = '`\)\s*,\s*\(`';
105    $values = preg_split($values_pattern, substr($query, strlen($matches[1])+1));
106    $values[0] = substr($values[0], 1);
107    $values[count($values)-1] = substr($values[count($values)-1], 
108                                     0, 
109                                     strlen($values[count($values)-1])-1
110                                     );
111    for ($n=0;$n<count($values);$n++)
112    {
113      $query = $base_query . '('. $values[$n] . ")\n;";
114      ($result = $pwg_db_link->query($query)) 
115        or die($query."\n<br>".$pwg_db_link->lastErrorMsg());
116    }
117  }
118  else 
119  {
120    ($result = $pwg_db_link->query($query)) 
121      or die($query."\n<br>".$pwg_db_link->errorInfo());
122  }
123
124  $time = get_moment() - $start;
125
126  if (!isset($page['count_queries']))
127  {
128    $page['count_queries'] = 0;
129    $page['queries_time'] = 0;
130  }
131
132  $page['count_queries']++;
133  $page['queries_time']+= $time;
134
135  if ($conf['show_queries'])
136  {
137    $output = '';
138    $output.= '<pre>['.$page['count_queries'].'] ';
139    $output.= "\n".$query;
140    $output.= "\n".'(this query time : ';
141    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
142    $output.= "\n".'(total SQL time  : ';
143    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
144    $output.= "\n".'(total time      : ';
145    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
146    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
147    {
148      $output.= "\n".'(num rows        : ';
149      $output.= pwg_db_num_rows($result).' )';
150    }
151    elseif ( $result!=null
152      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) 
153      and !isset($truncate_query))
154    {
155      $output.= "\n".'(affected rows   : ';
156      $output.= pwg_db_changes($result).' )';
157    }
158    $output.= "</pre>\n";
159
160    $debug .= $output;
161  }
162
163  return $result;
164}
165
166function pwg_db_nextval($column, $table)
167{
168  $query = '
169SELECT MAX('.$column.')+1
170  FROM '.$table;
171  list($next) = pwg_db_fetch_row(pwg_query($query));
172  if (is_null($next))
173  {
174    $next = 1;
175  }
176  return $next;
177}
178
179/**
180 *
181 * complex functions
182 *
183 */
184
185function pwg_db_changes(PDOStatement $result=null) 
186{
187  return $result->rowCount();
188}
189
190function pwg_db_num_rows(PDOStatement $result) 
191{ 
192  return $result->rowCount();
193}
194
195function pwg_db_fetch_assoc($result)
196{
197  return $result->fetch(PDO::FETCH_ASSOC);
198}
199
200function pwg_db_fetch_row($result)
201{
202  return $result->fetch(PDO::FETCH_NUM);
203}
204
205function pwg_db_fetch_object($result)
206{
207  return $result;
208}
209
210function pwg_db_free_result($result) 
211{
212}
213
214function pwg_db_real_escape_string($s)
215{
216  global $pwg_db_link;
217
218  return trim($pwg_db_link->quote($s), "'");
219}
220
221function pwg_db_insert_id($table=null, $column='id')
222{
223  global $pwg_db_link;
224
225  return $pwg_db_link->lastInsertRowID();
226}
227
228/**
229 *
230 * complex functions
231 *
232 */
233
234/**
235 * creates an array based on a query, this function is a very common pattern
236 * used here
237 *
238 * @param string $query
239 * @param string $fieldname
240 * @return array
241 */
242function array_from_query($query, $fieldname)
243{
244  $array = array();
245
246  $result = pwg_query($query);
247  while ($row = pwg_db_fetch_assoc($result))
248  {
249    array_push($array, $row[$fieldname]);
250  }
251
252  return $array;
253}
254
255define('MASS_UPDATES_SKIP_EMPTY', 1);
256/**
257 * updates multiple lines in a table
258 *
259 * @param string table_name
260 * @param array dbfields
261 * @param array datas
262 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
263 * @return void
264 */
265function mass_updates($tablename, $dbfields, $datas, $flags=0)
266{
267  if (count($datas) == 0)
268    return;
269
270  foreach ($datas as $data)
271  {
272    $query = '
273UPDATE '.$tablename.'
274  SET ';
275    $is_first = true;
276    foreach ($dbfields['update'] as $key)
277    {
278      $separator = $is_first ? '' : ",\n    ";
279     
280      if (isset($data[$key]) and $data[$key] != '')
281      {
282        $query.= $separator.$key.' = \''.$data[$key].'\'';
283      }
284      else
285      {
286        if ($flags & MASS_UPDATES_SKIP_EMPTY )
287          continue; // next field
288        $query.= "$separator$key = NULL";
289      }
290      $is_first = false;
291    }
292    if (!$is_first)
293    {// only if one field at least updated
294      $query.= '
295  WHERE ';
296      $is_first = true;
297      foreach ($dbfields['primary'] as $key)
298      {
299        if (!$is_first)
300        {
301          $query.= ' AND ';
302        }
303        if ( isset($data[$key]) )
304        {
305          $query.= $key.' = \''.$data[$key].'\'';
306        }
307        else
308        {
309          $query.= $key.' IS NULL';
310        }
311        $is_first = false;
312      }
313      pwg_query($query);
314    }
315  }
316}
317
318
319/**
320 * inserts multiple lines in a table
321 *
322 * @param string table_name
323 * @param array dbfields
324 * @param array inserts
325 * @return void
326 */
327
328function mass_inserts($table_name, $dbfields, $datas)
329{
330  if (count($datas) != 0)
331  {
332    $first = true;
333
334    $packet_size = 16777216;
335    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
336    $query = '';
337
338    foreach ($datas as $insert)
339    {
340      if (strlen($query) >= $packet_size)
341      {
342        pwg_query($query);
343        $first = true;
344      }
345
346      if ($first)
347      {
348        $query = '
349INSERT INTO '.$table_name.'
350  ('.implode(',', $dbfields).')
351  VALUES';
352        $first = false;
353      }
354      else
355      {
356        $query .= '
357  , ';
358      }
359
360      $query .= '(';
361      foreach ($dbfields as $field_id => $dbfield)
362      {
363        if ($field_id > 0)
364        {
365          $query .= ',';
366        }
367
368        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
369        {
370          $query .= 'NULL';
371        }
372        else
373        {
374          $query .= "'".$insert[$dbfield]."'";
375        }
376      }
377      $query .= ')';
378    }
379    pwg_query($query);
380  }
381}
382
383/**
384 * Do maintenance on all PWG tables
385 *
386 * @return none
387 */
388function do_maintenance_all_tables()
389{
390  global $prefixeTable, $page;
391
392  $all_tables = array();
393
394  // List all tables
395  $query = 'SELECT name FROM SQLITE_MASTER
396WHERE name LIKE \''.$prefixeTable.'%\'';
397
398  $all_tables = array_from_query($query, 'name');
399  foreach ($all_tables as $table_name)
400  {
401    $query = 'VACUUM '.$table_name.';';
402    $result = pwg_query($query);
403  }
404 
405  array_push($page['infos'],
406             l10n('All optimizations have been successfully completed.')
407             );
408}
409
410function pwg_db_concat($array)
411{
412  return implode($array, ' || ');
413}
414
415function pwg_db_concat_ws($array, $separator)
416{
417  $glue = sprintf(' || \'%s\' || ', $separator);
418
419  return implode($array, $glue);
420}
421
422function pwg_db_cast_to_text($string)
423{
424  return $string;
425}
426
427/**
428 * returns an array containing the possible values of an enum field
429 *
430 * @param string tablename
431 * @param string fieldname
432 */
433function get_enums($table, $field)
434{
435  $Enums['categories']['status'] = array('public', 'private');
436  $Enums['history']['section'] = array('categories','tags','search','list','favorites','most_visited','best_rated','recent_pics','recent_cats');
437  $Enums['user_infos']['status'] = array('webmaster','admin','normal','generic','guest');
438  $Enums['image']['type'] = array('picture','high','other');
439  $Enums['plugins']['state'] = array('active', 'inactive');
440  $Enums['user_cache_image']['access_type'] = array('NOT IN','IN');
441
442  $table = str_replace($GLOBALS['prefixeTable'], '', $table);
443  if (isset($Enums[$table][$field])) {
444    return $Enums[$table][$field];
445  } else {
446    return array();
447  }
448}
449
450// get_boolean transforms a string to a boolean value. If the string is
451// "false" (case insensitive), then the boolean value false is returned. In
452// any other case, true is returned.
453function get_boolean( $string )
454{
455  $boolean = true;
456  if ('f' === $string || 'false' === $string)
457  {
458    $boolean = false;
459  }
460  return $boolean;
461}
462
463/**
464 * returns boolean string 'true' or 'false' if the given var is boolean
465 *
466 * @param mixed $var
467 * @return mixed
468 */
469function boolean_to_string($var)
470{
471  if (is_bool($var))
472  {
473    return $var ? 'true' : 'false';
474  }
475  else
476  {
477    return $var;
478  }
479}
480
481/**
482 *
483 * interval and date functions
484 *
485 */
486
487function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
488{
489  if ($date!='CURRENT_DATE')
490  {
491    $date = '\''.$date.'\'';
492  }
493
494  return 'date('.$date.',\''.-$period.' DAY\')';
495}
496
497function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
498{
499  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
500  list($d) = pwg_db_fetch_row(pwg_query($query));
501
502  return $d;
503}
504
505function pwg_db_get_date_YYYYMM($date)
506{
507  return 'strftime(\'%Y%m\','.$date.')';
508}
509
510function pwg_db_get_date_MMDD($date)
511{
512  return 'strftime(\'%m%d\','.$date.')';
513}
514
515function pwg_db_get_year($date)
516{
517  return 'strftime(\'%Y\','.$date.')';
518}
519
520function pwg_db_get_month($date)
521{
522  return 'strftime(\'%m\','.$date.')';
523}
524
525function pwg_db_get_week($date, $mode=null)
526{
527  return 'strftime(\'%W\','.$date.')';
528}
529
530function pwg_db_get_dayofmonth($date)
531{
532  return 'strftime(\'%d\','.$date.')';
533}
534
535function pwg_db_get_dayofweek($date)
536{
537  return 'strftime(\'%w\','.$date.')';
538}
539
540function pwg_db_get_weekday($date)
541{
542  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
543}
544
545// my_error returns (or send to standard output) the message concerning the
546// error occured for the last mysql query.
547function my_error($header, $die)
548{
549  global $pwg_db_link;
550
551  $error = '';
552  if (isset($pwg_db_link)) 
553  {
554    $error .= '[sqlite error]'.$pwg_db_link->errorInfo()."\n";
555  }
556
557  $error .= $header;
558
559  if ($die)
560  {
561    fatal_error($error);
562  }
563  echo("<pre>");
564  trigger_error($error, E_USER_WARNING);
565  echo("</pre>");
566}
567
568// sqlite create functions
569function pwg_now()
570{
571  return date('Y-m-d H:i:s');
572}
573
574function pwg_hour($datetime)
575{
576  return strftime('%H', $datetime);
577}
578
579function pwg_unix_timestamp()
580{
581  return time();
582}
583
584function pwg_if($expression, $value1, $value2) 
585{
586  if ($expression)
587  {
588    return $value1;
589  }
590  else
591  {
592    return $value2;
593  }
594} 
595
596function pwg_regexp($pattern, $string)
597{
598  $pattern = sprintf('`%s`', $pattern);
599  return preg_match($pattern, $string);
600}
601?>
Note: See TracBrowser for help on using the repository browser.