Skip to content

Commit

Permalink
Feature 1255: modification in sql queries
Browse files Browse the repository at this point in the history
    - manage random function
    - manage regex syntax
    - manage quote (single instead of double)
    - manage interval

git-svn-id: http://piwigo.org/svn/trunk@4367 68402e56-0260-453c-a942-63ccdbb3a9ee
  • Loading branch information
nikrou committed Nov 25, 2009
1 parent d30639e commit 13ea9d5
Show file tree
Hide file tree
Showing 20 changed files with 134 additions and 112 deletions.
2 changes: 1 addition & 1 deletion admin/cat_modify.php
Expand Up @@ -67,7 +67,7 @@
array(
'id' => $_GET['cat_id'],
'name' => @$_POST['name'],
'commentable' => $_POST['commentable'],
'commentable' => isset($_POST['commentable'])?$_POST['commentable']:'false',
'uploadable' =>
isset($_POST['uploadable']) ? $_POST['uploadable'] : 'false',
'comment' =>
Expand Down
2 changes: 1 addition & 1 deletion admin/element_set.php
Expand Up @@ -196,7 +196,7 @@
{
$query = 'SELECT id
FROM '.IMAGES_TABLE.'
WHERE date_available BETWEEN DATE_SUB("'.$row['date'].'", INTERVAL 1 DAY) AND "'.$row['date'].'"';
WHERE date_available BETWEEN '.pwg_db_get_recent_period_expression(1, $row['date']).' AND \''.$row['date'].'\'';
$page['cat_elements_id'] = array_from_query($query, 'id');
}
}
Expand Down
2 changes: 1 addition & 1 deletion admin/include/functions_metadata.php
Expand Up @@ -246,7 +246,7 @@ function get_filelist($category_id = '', $site_id=1, $recursive = false,
if ($recursive)
{
$query.= '
AND uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'
AND uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$category_id.'(,|$)\'
';
}
else
Expand Down
10 changes: 5 additions & 5 deletions admin/menubar.php
Expand Up @@ -69,8 +69,8 @@ function make_consecutive( &$orders, $step=50 )
$mb_conf = array();
$query = '
UPDATE '.CONFIG_TABLE.'
SET value=""
WHERE param="blk_'.addslashes($menu->get_id()).'"
SET value=\'\'
WHERE param=\'blk_'.addslashes($menu->get_id()).'\'
LIMIT 1';
pwg_query($query);
}
Expand Down Expand Up @@ -143,9 +143,9 @@ function make_consecutive( &$orders, $step=50 )
*/
$query = '
UPDATE '.CONFIG_TABLE.'
SET value="'.addslashes(serialize($mb_conf_db)).'"
WHERE param="blk_'.addslashes($menu->get_id()).'"
LIMIT 1';
SET value=\''.addslashes(serialize($mb_conf_db)).'\'
WHERE param=\'blk_'.addslashes($menu->get_id()).'\'
';
pwg_query($query);
}

Expand Down
12 changes: 3 additions & 9 deletions admin/site_update.php
Expand Up @@ -148,7 +148,7 @@
if (isset($_POST['subcats-included']) and $_POST['subcats-included'] == 1)
{
$query.= '
AND uppercats REGEXP \'(^|,)'.$_POST['cat'].'(,|$)\'
AND uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$_POST['cat'].'(,|$)\'
';
}
else
Expand Down Expand Up @@ -207,10 +207,7 @@
}

// next category id available
$query = '
SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_id
FROM '.CATEGORIES_TABLE;
list($next_id) = pwg_db_fetch_row(pwg_query($query));
$next_id = pwg_db_nextval('id', CATEGORIES_TABLE);

// retrieve sub-directories fulldirs from the site reader
$fs_fulldirs = $site_reader->get_full_directories($basedir);
Expand Down Expand Up @@ -399,10 +396,7 @@
}

// next element id available
$query = '
SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
FROM '.IMAGES_TABLE;
list($next_element_id) = pwg_db_fetch_row(pwg_query($query));
$next_element_id = pwg_db_nextval('id', IMAGES_TABLE);

$start = get_moment();

Expand Down
8 changes: 4 additions & 4 deletions comments.php
Expand Up @@ -51,11 +51,11 @@
//
$since_options = array(
1 => array('label' => l10n('today'),
'clause' => 'date > SUBDATE(CURDATE(), INTERVAL 1 DAY)'),
'clause' => 'date > '.pwg_db_get_recent_period_expression(1)),
2 => array('label' => sprintf(l10n('last %d days'), 7),
'clause' => 'date > SUBDATE(CURDATE(), INTERVAL 7 DAY)'),
'clause' => 'date > '.pwg_db_get_recent_period_expression(7)),
3 => array('label' => sprintf(l10n('last %d days'), 30),
'clause' => 'date > SUBDATE(CURDATE(), INTERVAL 30 DAY)'),
'clause' => 'date > '.pwg_db_get_recent_period_expression(30)),
4 => array('label' => l10n('the beginning'),
'clause' => '1=1') // stupid but generic
);
Expand Down Expand Up @@ -138,7 +138,7 @@
// which status to filter on ?
if ( !is_admin() )
{
$page['where_clauses'][] = 'validated="true"';
$page['where_clauses'][] = 'validated=\'true\'';
}

$page['where_clauses'][] = get_sql_condition_FandF
Expand Down
2 changes: 1 addition & 1 deletion feed.php
Expand Up @@ -156,7 +156,7 @@ function ts_to_iso8601($ts)
{
$query = '
UPDATE '.USER_FEED_TABLE.'
SET last_check = DATE_ADD(\''.$dbnow.'\', INTERVAL -15 DAY )
SET last_check = '.pwg_db_get_recent_period_expression(-15, $dbnow).'
WHERE id = \''.$feed_id.'\'
;';
pwg_query($query);
Expand Down
2 changes: 1 addition & 1 deletion include/calendar_base.class.php
Expand Up @@ -268,7 +268,7 @@ function build_next_prev()
$prev = $next =null;
if ( empty($page['chronology_date']) )
return;
$query = 'SELECT CONCAT_WS("-"';
$query = 'SELECT CONCAT_WS(\'-\'';
for ($i=0; $i<count($page['chronology_date']); $i++)
{
if ( 'any' === $page['chronology_date'][$i] )
Expand Down
2 changes: 1 addition & 1 deletion include/calendar_monthly.class.php
Expand Up @@ -347,7 +347,7 @@ function build_month_calendar(&$tpl_var)
$query.= $this->inner_sql;
$query.= $this->get_date_where();
$query.= '
ORDER BY RAND()
ORDER BY '.DB_RANDOM_FUNCTION.'()
LIMIT 1';
unset ( $page['chronology_date'][CDAY] );

Expand Down
8 changes: 3 additions & 5 deletions include/category_cats.inc.php
Expand Up @@ -35,9 +35,7 @@
c.*, nb_images, date_last, max_date_last, count_images, count_categories
FROM '.CATEGORIES_TABLE.' c INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
ON id = cat_id and user_id = '.$user['id'].'
WHERE date_last >= SUBDATE(
CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY
)
WHERE date_last >= '.pwg_db_get_recent_period_expression($user['recent_period']).'
'.get_sql_condition_FandF
(
array
Expand Down Expand Up @@ -104,7 +102,7 @@
),
"\n AND"
).'
ORDER BY RAND()
ORDER BY '.DB_RANDOM_FUNCTION.'()
LIMIT 1
;';
$subresult = pwg_query($query);
Expand Down Expand Up @@ -132,7 +130,7 @@
),
"\n AND"
).'
ORDER BY RAND()
ORDER BY '.DB_RANDOM_FUNCTION.'()
LIMIT 1
;';
$subresult = pwg_query($query);
Expand Down
95 changes: 95 additions & 0 deletions include/dblayer/functions_mysql.inc.php
Expand Up @@ -21,6 +21,11 @@
// | USA. |
// +-----------------------------------------------------------------------+

define('DB_ENGINE', 'MySQL');

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

/**
*
* simple functions
Expand Down Expand Up @@ -107,6 +112,16 @@ function pwg_query($query)
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);
Expand Down Expand Up @@ -443,6 +458,86 @@ function do_maintenance_all_tables()
}
}

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;
}

/**
* 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;
}
}

// my_error returns (or send to standard output) the message concerning the
// error occured for the last mysql query.
function my_error($header, $die)
Expand Down
3 changes: 1 addition & 2 deletions include/filter.inc.php
Expand Up @@ -96,8 +96,7 @@
category_id IN ('.$filter['visible_categories'].') and';
}
$query.= '
date_available >= SUBDATE(
CURRENT_DATE,INTERVAL '.$filter['recent_period'].' DAY)';
date_available >= '.pwg_db_get_recent_period_expression($filter['recent_period']);

$filter['visible_images'] = implode(',', array_from_query($query, 'image_id'));

Expand Down
69 changes: 3 additions & 66 deletions include/functions.inc.php
Expand Up @@ -33,67 +33,6 @@

//----------------------------------------------------------- generic functions

/**
* 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;
}
}

// The function get_moment returns a float value coresponding to the number
// of seconds since the unix epoch (1st January 1970) and the microseconds
// are precised : e.g. 1052343429.89276600
Expand Down Expand Up @@ -540,8 +479,8 @@ function pwg_log($image_id = null, $image_type = null)
)
VALUES
(
CURDATE(),
CURTIME(),
CURRENT_DATE,
CURRENT_TIME,
'.$user['id'].',
\''.$_SERVER['REMOTE_ADDR'].'\',
'.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
Expand Down Expand Up @@ -1497,9 +1436,7 @@ function get_icon($date, $is_child_date = false)
if (!isset($cache['get_icon']['sql_recent_date']))
{
// Use MySql date in order to standardize all recent "actions/queries"
list($cache['get_icon']['sql_recent_date']) =
pwg_db_fetch_row(pwg_query('select SUBDATE(
CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)'));
$cache['get_icon']['sql_recent_date'] = pwg_db_get_recent_period($user['recent_period']);
}

$cache['get_icon'][$date] = $date > $cache['get_icon']['sql_recent_date'];
Expand Down
2 changes: 1 addition & 1 deletion include/functions_category.inc.php
Expand Up @@ -377,7 +377,7 @@ function get_subcat_ids($ids)
$query.= '
OR ';
}
$query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
$query.= 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$category_id.'(,|$)\'';
}
$query.= '
;';
Expand Down
2 changes: 1 addition & 1 deletion include/functions_notification.inc.php
Expand Up @@ -463,7 +463,7 @@ function get_recent_post_dates($max_dates, $max_elements, $max_cats)
'.$where_sql.'
AND date_available="'.$dates[$i]['date_available'].'"
AND tn_ext IS NOT NULL
ORDER BY RAND(NOW())
ORDER BY '.DB_RANDOM_FUNCTION.'())
LIMIT '.$max_elements.'
;';
$dates[$i]['elements'] = array();
Expand Down

0 comments on commit 13ea9d5

Please sign in to comment.