aboutsummaryrefslogtreecommitdiffstats
path: root/include/dblayer/functions_mysql.inc.php
blob: 6a29a0e403457cb968ac8f97955dae2e4f9b2435 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based picture gallery                                  |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | 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                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

define('DB_ENGINE', 'MySQL');

define('DB_REGEX_OPERATOR', 'REGEXP');
define('DB_RANDOM_FUNCTION', 'RAND');

/**
 *
 * simple functions
 *
 */

function pwg_db_connect($host, $user, $password, $database)
{  
  $link = mysql_connect($host, $user, $password) or my_error('mysql_connect', true);
  mysql_select_db($database, $link) or my_error('mysql_select_db', true);

  return $link;
}

function pwg_db_check_charset() 
{
  defined('PWG_CHARSET') and defined('DB_CHARSET')
    or fatal_error('PWG_CHARSET and/or DB_CHARSET is not defined');
  if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') )
  {
    if (DB_CHARSET!='')
    {
      pwg_query('SET NAMES "'.DB_CHARSET.'"');
    }
  }
  elseif ( strtolower(PWG_CHARSET)!='iso-8859-1' )
  {
    fatal_error('PWG supports only iso-8859-1 charset on MySql version '.mysql_get_server_info());
  }
}

function pwg_get_db_version() 
{
  list($mysql_version) = pwg_db_fetch_row(pwg_query('SELECT VERSION();'));
  
  return $mysql_version;
}

function pwg_query($query)
{
  global $conf,$page,$debug,$t2;

  $start = get_moment();
  ($result = mysql_query($query)) or my_error($query, $conf['die_on_sql_error']);

  $time = get_moment() - $start;

  if (!isset($page['count_queries']))
  {
    $page['count_queries'] = 0;
    $page['queries_time'] = 0;
  }

  $page['count_queries']++;
  $page['queries_time']+= $time;

  if ($conf['show_queries'])
  {
    $output = '';
    $output.= '<pre>['.$page['count_queries'].'] ';
    $output.= "\n".$query;
    $output.= "\n".'(this query time : ';
    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
    $output.= "\n".'(total SQL time  : ';
    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
    $output.= "\n".'(total time      : ';
    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
    {
      $output.= "\n".'(num rows        : ';
      $output.= mysql_num_rows($result).' )';
    }
    elseif ( $result!=null
      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) )
    {
      $output.= "\n".'(affected rows   : ';
      $output.= mysql_affected_rows().' )';
    }
    $output.= "</pre>\n";

    $debug .= $output;
  }

  return $result;
}

function pwg_db_nextval($column, $table)
{
  $query = '
SELECT IF(MAX('.$column.')+1 IS NULL, 1, MAX('.$column.')+1)
  FROM '.$table;
  list($next) = pwg_db_fetch_row(pwg_query($query));

  return $next;
}

function pwg_db_changes($result) 
{
  return mysql_affected_rows($result);
}

function pwg_db_num_rows($result) 
{
  return mysql_num_rows($result);
}

function pwg_db_fetch_assoc($result)
{
  return mysql_fetch_assoc($result);
}

function pwg_db_fetch_row($result)
{
  return mysql_fetch_row($result);
}

function pwg_db_fetch_object($result)
{
  return mysql_fetch_object($result);
}

function pwg_db_free_result($result) 
{
  return mysql_free_result($result);
}

function pwg_db_real_escape_string($s)
{
  return mysql_real_escape_string($s);
}

function pwg_db_insert_id()
{
  return mysql_insert_id();
}

/**
 *
 * complex functions
 *
 */

/**
 * creates an array based on a query, this function is a very common pattern
 * used here
 *
 * @param string $query
 * @param string $fieldname
 * @return array
 */
function array_from_query($query, $fieldname)
{
  $array = array();

  $result = pwg_query($query);
  while ($row = mysql_fetch_assoc($result))
  {
    array_push($array, $row[$fieldname]);
  }

  return $array;
}

define('MASS_UPDATES_SKIP_EMPTY', 1);
/**
 * updates multiple lines in a table
 *
 * @param string table_name
 * @param array dbfields
 * @param array datas
 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
 * @return void
 */
function mass_updates($tablename, $dbfields, $datas, $flags=0)
{
  if (count($datas) == 0)
    return;
  // depending on the MySQL version, we use the multi table update or N update queries
  if (count($datas) < 10 or version_compare(mysql_get_server_info(), '4.0.4') < 0)
  { // MySQL is prior to version 4.0.4, multi table update feature is not available
    foreach ($datas as $data)
    {
      $query = '
UPDATE '.$tablename.'
  SET ';
      $is_first = true;
      foreach ($dbfields['update'] as $key)
      {
        $separator = $is_first ? '' : ",\n    ";

        if (isset($data[$key]) and $data[$key] != '')
        {
          $query.= $separator.$key.' = \''.$data[$key].'\'';
        }
        else
        {
          if ($flags & MASS_UPDATES_SKIP_EMPTY )
            continue; // next field
          $query.= "$separator$key = NULL";
        }
        $is_first = false;
      }
      if (!$is_first)
      {// only if one field at least updated
        $query.= '
  WHERE ';
        $is_first = true;
        foreach ($dbfields['primary'] as $key)
        {
          if (!$is_first)
          {
            $query.= ' AND ';
          }
          if ( isset($data[$key]) )
          {
            $query.= $key.' = \''.$data[$key].'\'';
          }
          else
          {
            $query.= $key.' IS NULL';
          }
          $is_first = false;
        }
        pwg_query($query);
      }
    } // foreach update
  } // if mysql_ver or count<X
  else
  {
    // creation of the temporary table
    $query = '
SHOW FULL COLUMNS FROM '.$tablename;
    $result = pwg_query($query);
    $columns = array();
    $all_fields = array_merge($dbfields['primary'], $dbfields['update']);
    while ($row = pwg_db_fetch_assoc($result))
    {
      if (in_array($row['Field'], $all_fields))
      {
        $column = $row['Field'];
        $column.= ' '.$row['Type'];

        $nullable = true;
        if (!isset($row['Null']) or $row['Null'] == '' or $row['Null']=='NO')
        {
          $column.= ' NOT NULL';
          $nullable = false;
        }
        if (isset($row['Default']))
        {
          $column.= " default '".$row['Default']."'";
        }
        elseif ($nullable)
        {
          $column.= " default NULL";
        }
        if (isset($row['Collation']) and $row['Collation'] != 'NULL')
        {
          $column.= " collate '".$row['Collation']."'";
        }
        array_push($columns, $column);
      }
    }

    $temporary_tablename = $tablename.'_'.micro_seconds();

    $query = '
CREATE TABLE '.$temporary_tablename.'
(
  '.implode(",\n  ", $columns).',
  UNIQUE KEY the_key ('.implode(',', $dbfields['primary']).')
)';

    pwg_query($query);
    mass_inserts($temporary_tablename, $all_fields, $datas);
    if ( $flags & MASS_UPDATES_SKIP_EMPTY )
      $func_set = create_function('$s', 'return "t1.$s = IFNULL(t2.$s, t1.$s)";');
    else
      $func_set = create_function('$s', 'return "t1.$s = t2.$s";');

    // update of images table by joining with temporary table
    $query = '
UPDATE '.$tablename.' AS t1, '.$temporary_tablename.' AS t2
  SET '.
      implode(
        "\n    , ",
        array_map($func_set,$dbfields['update'])
        ).'
  WHERE '.
      implode(
        "\n    AND ",
        array_map(
          create_function('$s', 'return "t1.$s = t2.$s";'),
          $dbfields['primary']
          )
        );
    pwg_query($query);
    $query = '
DROP TABLE '.$temporary_tablename;
    pwg_query($query);
  }
}


/**
 * inserts multiple lines in a table
 *
 * @param string table_name
 * @param array dbfields
 * @param array inserts
 * @return void
 */
function mass_inserts($table_name, $dbfields, $datas)
{
  if (count($datas) != 0)
  {
    $first = true;

    $query = 'SHOW VARIABLES LIKE \'max_allowed_packet\'';
    list(, $packet_size) = pwg_db_fetch_row(pwg_query($query));
    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
    $query = '';

    foreach ($datas as $insert)
    {
      if (strlen($query) >= $packet_size)
      {
        pwg_query($query);
        $first = true;
      }

      if ($first)
      {
        $query = '
INSERT INTO '.$table_name.'
  ('.implode(',', $dbfields).')
  VALUES';
        $first = false;
      }
      else
      {
        $query .= '
  , ';
      }

      $query .= '(';
      foreach ($dbfields as $field_id => $dbfield)
      {
        if ($field_id > 0)
        {
          $query .= ',';
        }

        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
        {
          $query .= 'NULL';
        }
        else
        {
          $query .= "'".$insert[$dbfield]."'";
        }
      }
      $query .= ')';
    }
    pwg_query($query);
  }
}

/**
 * Do maintenance on all PWG tables
 *
 * @return none
 */
function do_maintenance_all_tables()
{
  global $prefixeTable, $page;

  $all_tables = array();

  // List all tables
  $query = 'SHOW TABLES LIKE \''.$prefixeTable.'%\'';
  $result = pwg_query($query);
  while ($row = pwg_db_fetch_row($result))
  {
    array_push($all_tables, $row[0]);
  }

  // Repair all tables
  $query = 'REPAIR TABLE '.implode(', ', $all_tables);
  $mysql_rc = pwg_query($query);

  // Re-Order all tables
  foreach ($all_tables as $table_name)
  {
    $all_primary_key = array();

    $query = 'DESC '.$table_name.';';
    $result = pwg_query($query);
    while ($row = pwg_db_fetch_assoc($result))
    {
      if ($row['Key'] == 'PRI')
      {
        array_push($all_primary_key, $row['Field']);
      }
    }

    if (count($all_primary_key) != 0)
    {
      $query = 'ALTER TABLE '.$table_name.' ORDER BY '.implode(', ', $all_primary_key).';';
      $mysql_rc = $mysql_rc && pwg_query($query);
    }
  }

  // Optimize all tables
  $query = 'OPTIMIZE TABLE '.implode(', ', $all_tables);
  $mysql_rc = $mysql_rc && pwg_query($query);
  if ($mysql_rc)
  {
    array_push(
          $page['infos'],
          l10n('Optimizations completed')
          );
  }
  else
  {
    array_push(
          $page['errors'],
          l10n('Optimizations errors')
          );
  }
}

function pwg_db_concat($array)
{
  $string = implode($array, ',');
  return 'CONCAT('. $string.')';
}

function pwg_db_concat_ws($array, $separator)
{
  $string = implode($array, ',');
  return 'CONCAT_WS(\''.$separator.'\','. $string.')';
}

function pwg_db_cast_to_text($string)
{
  return 'CAST('.$string.' AS CHAR)';
}

/**
 * returns an array containing the possible values of an enum field
 *
 * @param string tablename
 * @param string fieldname
 */
function get_enums($table, $field)
{
  // retrieving the properties of the table. Each line represents a field :
  // columns are 'Field', 'Type'
  $result = pwg_query('desc '.$table);
  while ($row = pwg_db_fetch_assoc($result))
  {
    // we are only interested in the the field given in parameter for the
    // function
    if ($row['Field'] == $field)
    {
      // retrieving possible values of the enum field
      // enum('blue','green','black')
      $options = explode(',', substr($row['Type'], 5, -1));
      foreach ($options as $i => $option)
      {
        $options[$i] = str_replace("'", '',$option);
      }
    }
  }
  pwg_db_free_result($result);
  return $options;
}

// get_boolean transforms a string to a boolean value. If the string is
// "false" (case insensitive), then the boolean value false is returned. In
// any other case, true is returned.
function get_boolean( $string )
{
  $boolean = true;
  if ( 'false' == strtolower($string) )
  {
    $boolean = false;
  }
  return $boolean;
}

/**
 * returns boolean string 'true' or 'false' if the given var is boolean
 *
 * @param mixed $var
 * @return mixed
 */
function boolean_to_string($var)
{
  if (is_bool($var))
  {
    return $var ? 'true' : 'false';
  }
  else
  {
    return $var;
  }
}

/**
 *
 * interval and date functions 
 *
 */


function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
{
  if ($date!='CURRENT_DATE')
  {
    $date = '\''.$date.'\'';
  }

  return 'SUBDATE('.$date.',INTERVAL '.$period.' DAY)';
}

function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
{
  $query = '
SELECT '.pwg_db_get_recent_period_expression($period);
  list($d) = pwg_db_fetch_row(pwg_query($query));

  return $d;
}

function pwg_db_get_date_YYYYMM($date)
{
  return 'DATE_FORMAT('.$date.', \'%Y%m\')';
}

function pwg_db_get_date_MMDD($date)
{
  return 'DATE_FORMAT('.$date.', \'%m%d\')';
}

function pwg_db_get_year($date)
{
  return 'YEAR('.$date.')';
}

function pwg_db_get_month($date)
{
  return 'MONTH('.$date.')';
}

function pwg_db_get_week($date, $mode=null)
{
  if ($mode)
  {
    return 'WEEK('.$date.', '.$mode.')';
  }
  else
  {
    return 'WEEK('.$date.')';
  }
}

function pwg_db_get_dayofmonth($date)
{
  return 'DAYOFMONTH('.$date.')';
}

function pwg_db_get_dayofweek($date)
{
  return 'DAYOFWEEK('.$date.')';
}

function pwg_db_get_weekday($date)
{
  return 'WEEKDAY('.$date.')';
}

// my_error returns (or send to standard output) the message concerning the
// error occured for the last mysql query.
function my_error($header, $die)
{
  $error = "[mysql error ".mysql_errno().'] '.mysql_error()."\n";
  $error .= $header;

  if ($die)
  {
    fatal_error($error);
  }
  echo("<pre>");
  trigger_error($error, E_USER_WARNING);
  echo("</pre>");
}

?>