<?php
// sending message and just die
function msg_die ($msg_id = '', $msg_txt = '', $url = '')
{
global $config;
$url = urlencode ($url);
redir ("$config[site_url]/msg.php?admin=0&id=$msg_id&msg=$msg_txt&url=$url");
die ();
}
// sending message and just die (for admin)
function admin_die ($msg_id = '', $msg_txt = '', $url = '')
{
global $config;
$url = urlencode ($url);
redir ("$config[site_url]/msg.php?admin=1&id=$msg_id&msg=$msg_txt&url=$url");
die ();
}
// sending query to MySQL with security concern
function sql_query ($sql, $debug = 0)
{
global $dbh, $config;
$config['total_mysql_query']++;
if ($debug) echo $sql.'<br />';
if (!$result = mysql_query ($sql, $dbh))
{
if ($debug)
die (mysql_error ());
else
msg_die ('SQL_ERROR', mysql_error ());
}
return $result;
}
// input: $slash => add (keep) slash (\) for special chars, such as ' -> \'
// 0 equal to stripslashes
// $html => allow html
// 0 equal to strip_tags
function sql_fetch_array ($res_id, $allow_html = 1, $slash = 1)
{
global $config;
$row = mysql_fetch_array ($res_id);
if (!$slash && is_array ($row))
{ reset ($row); while (list ($key, $val) = each ($row)) $row[$key] = stripslashes ($val); }
if (!$allow_html && is_array ($row))
{ reset ($row); while (list ($key, $val) = each ($row)) $row[$key] = strip_tags ($val); }
return $row;
}
// generate random string
// param: $l = string length
// $lower = 1 -> lower case only (i.e: abcdef). use $lower = 0 for mixed case (i.e: AbCdEf)
// $hex = 1 -> 0-9, A-F; $hex = 0 -> 0-9, A-Z
function random_str ($len, $lower = 1, $hex = 1)
{
if ($hex)
$ch = "ABCDEF1234567890";
else
$ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz1234567890";
$l = strlen ($ch) - 1;
$str = "";
for ($i=0; $i < $len; $i++)
{
$x = rand (0, $l);
$str .= $ch[$x];
}
if ($lower) $str = strtolower ($str);
return $str;
}
// converting SQL Formatted date to HUMAN UNDERSTANDABLE & READABLE DATE (HURT)
// $sql_date = date in sql format (yyyy-mm-dd)
// $mode = [sql = sql formatted; 1 = dayname, monthname dd, yyyy; 0/else = mm/dd/yyyy]
// $days = [0 / blank = return specified date; X = return X days after specified date]
// and translate it to other language (if configured) ... still, much more easier than i though! REALLY!
function convert_date ($sql_date, $mode = '0', $days = 0)
{
global $config, $lang;
if ($sql_date == '0000-00-00') return 'Invalid Date';
if (empty ($sql_date) || ($sql_date == 'today')) $sql_date = date ('Y-m-d');
$thn = substr($sql_date, 0, 4);
$bln = substr($sql_date, 5, 2);
$tgl = substr($sql_date, 8, 2);
$tglbener = mktime(0, 0, 0, $bln, $tgl, $thn);
if ($days != 0) { $tglbener = $tglbener + ($days * 24 * 3600); }
switch ((string) $mode)
{
case '1':
case 'long':
$tanggal = date ($lang['l_long_date_format'], $tglbener);
break;
case '0':
case 'short':
$tanggal = date ($lang['l_short_date_format'], $tglbener);
break;
case 'sql':
$tanggal = date ('Y-m-d', $tglbener);
return $tanggal;
break;
case 'int':
return $tglbener;
break;
default:
$tanggal = date ($mode, $tglbener);
break;
}
// translate (if configured)
if ($config['multi_lang'])
{
$i = 0;
@reset($lang['datetime']);
while (list($key, $val) = @each($lang['datetime']))
{
$i++;
$search[$i] = $key;
$replace[$i] = $val;
}
return str_replace ($search, $replace, $tanggal);
}
else
{
return $tanggal;
}
}
// verify SQL formatted date (yyyy-mm-dd)
function verify_date ($sql_date)
{
$thn = substr($sql_date, 0, 4);
$bln = substr($sql_date, 5, 2);
$tgl = substr($sql_date, 8, 2);
$bener = checkdate($bln, $tgl, $thn);
return $bener;
}
// destroy all hacking attempt!
function hacker_die ()
{
global $config;
echo "<B>WARNING! You not authorized!</B><br />"
."You may have to re-login, or "
."if the problem persist, <a href=\"mailto:$config[site_email]\">contact us</a>.";
die ();
}
// get paramenter from GET, POST or COOKIE ... >>> see also date_param()
// $mode = 'noslash' = ' & " will not be slashed !!!!
// 'nohtml' = remove all HTML tags
// 'filterhtml' = remove selected HTML tags (defined in config), '
// 'html' = allow html (be ware of XSS)
// DEFAULT = add slash, convert html, sql ready
function filter_param ($param, $mode)
{
global $config, $lang; $html = 0;
if (!$config['gpc_quotes']) $param = addslashes ($param);
$param = trim ($param);
$cmd = explode (" ", $mode);
reset ($cmd);
while (list ($key, $cm) = each ($cmd))
{
if ($cm == 'noslash') $param = stripslashes ($param);
if ($cm == 'nohtml') $param = strip_tags ($param);
if ($cm == 'filterhtml') { $param = strip_tags ($param, $config['allowed_html_tags']); $html = 1; }
if ($cm == 'html') $html = 1;
if (($cm == 'rte') && ($config['wysiwyg']))
{
$html = 1;
$param = str_replace ('<br>', '<br />', $param);
if ($config['rte_rpc'])
{
$param = str_replace ($config['site_url'].'/', '', $param);
$param = str_replace ($config['site_url'].'//', $config['site_url'].'/', $param);
}
}
if (($cm == 'rte') && (!$config['wysiwyg'])) $html = 0;
}
if ($html)
return $param;
else
{
// quick multi-byte support (need to test the security!)
$tmp = htmlentities ($param, ENT_QUOTES, $lang['l_encoding']);
return str_replace ('&#', '&#', $tmp);
}
}
// get_param, post_param & cookie_param will extract vars => WE CAN'T TRY EXTERNAL INPUT (incl. COOKIE's)
// $var_name -> if integer will extract in this fashion: index.php?var1,var2,var3 (0: var1,var2,var3; 1: var1; 2: var2...)
// $mode -> see filter_param ()
// default: in sql ready (' -> \'), convert all HTML tags (" -> ")!
function get_param ($var_name, $default = '', $mode = '')
{
if (is_integer ($var_name))
{
if (!isset ($_SERVER['QUERY_STRING'])) return $default;
$p = $_SERVER['QUERY_STRING'];
$g = explode (',', $p);
array_unshift ($g, $p);
if (empty ($g[$var_name])) return $default;
$v = $g[$var_name];
}
else
{
if (!isset ($_GET[$var_name])) return $default;
$v = $_GET[$var_name];
}
$v = filter_param ($v, $mode);
return trim ($v);
}
function post_param ($var_name, $default = '', $mode = '')
{
if (!isset ($_POST[$var_name]))
return $default;
else
{
$v = $_POST[$var_name];
$v = filter_param ($v, $mode);
return trim ($v);
}
}
function cookie_param ($var_name)
{
if (!isset ($_COOKIE[$var_name]))
return '';
else
{
$v = $_COOKIE[$var_name];
$v = filter_param ($v, '');
return trim ($v);
}
}
// calculate 'how many days have passed since...'
// parameters are in SQL formatted date
function diff_date ($sql_date1, $sql_date2 = 'now')
{
if ($sql_date1 == "now") { $sql_date1 = date ("Y/m/d", time ()); }
if ($sql_date2 == "now") { $sql_date2 = date ("Y/m/d", time ()); }
$thn1 = substr($sql_date1, 0, 4);
$bln1 = substr($sql_date1, 5, 2);
$tgl1 = substr($sql_date1, 8, 2);
$thn2 = substr($sql_date2, 0, 4);
$bln2 = substr($sql_date2, 5, 2);
$tgl2 = substr($sql_date2, 8, 2);
$tanggal1 = mktime(0, 0, 0, $bln1, $tgl1, $thn1);
$tanggal2 = mktime(0, 0, 0, $bln2, $tgl2, $thn2);
$tanggal = ($tanggal2 - $tanggal1) / 86400;
return ($tanggal);
}
// cut long line to short line, but cut it nicely!
// regular cut: "this is a very bor..."
// line_wrap: "this is a very ..."
function line_wrap ($txt, $l)
{
$txt = str_replace ("\n", " ", $txt);
$txt = wordwrap ($txt, $l, "\n", 1);
$i = strpos ($txt, "\n");
if (empty($i)) $i = $l;
return substr ($txt, 0, $i);
}
// add $w with comma to $s
// i.e: This is an apple, a book, and.....
// $c = comma style
function add_comma ($s, $w, $c = ',')
{
if (!empty($s))
return "$c $w";
else
return $w;
}
// stopwatch
function getmicrotime ()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
// generate blank vars from a table (useful for creating empty fields in form)
function create_blank_tbl ($tbl)
{
global $db_name;
$res = mysql_list_fields ($db_name, $tbl);
$l = mysql_num_fields ($res);
for ($i = 0; $i < $l; $i++)
{
$name = mysql_field_name ($res, $i);
$row[$name] = '';
}
return $row;
}
// to generate <select> for a <form>, and automatically select the 'selected' value.
// $source = array of data for <select>
// $select_name = name for <select>
// $selected_value = selected value
// $first_line = should be UNSELECTABLE option, such as '--PLEASE SELECT--'
function create_select_form ($select_name, $source, $selected_value = '', $first_line = '', $disabled = 0)
{
if ($disabled) $disabled = 'disabled'; else $disabled = '';
$t = "<select size=\"1\" name=\"$select_name\" $disabled>\n";
if (!empty($first_line)) $t .= "<option value=\"\">$first_line</option>\n";
reset ($source);
while (list ($key, $val) = each ($source))
{
if ($key == $selected_value)
$t .= "<option value=\"$key\" selected=\"selected\">$val</option>\n";
else
$t .= "<option value=\"$key\">$val</option>\n";
}
$t .= "</select>\n";
return $t;
}
// to generate <radio> for a <form>, and automatically select the 'selected' value.
// $source = array of data for <select>
// $radio_name = name for <select>
// $selected_value = selected value
// $mode = 'h' - horizontal, 'v' - vertical
function create_radio_form ($radio_name, $source, $selected_value = '', $mode = 'h')
{
$t = '';
reset ($source);
while (list ($key, $val) = each ($source))
{
if ($key == $selected_value)
$t .= "<input type=\"radio\" name=\"$radio_name\" value=\"$key\" checked=\"checked\" />$val\n";
else
$t .= "<input type=\"radio\" name=\"$radio_name\" value=\"$key\" />$val\n";
if ($mode == 'h') $t .= ' '; else $t .= '<br />';
}
return $t;
}
// create HTML header (title, description, keywords, etc)
// return nothing
// output directly into global $txt
function generate_html_header ($title = '', $description = '', $keywords = '')
{
global $txt, $lang, $config;
$txt['site_name'] = $config['site_name'];
if (!empty ($title)) $txt['head_title'] = $title;
else $txt['head_title'] = $config['site_name'];
if (!empty ($description)) $txt['site_description'] = $description;
else $txt['site_description'] = $config['site_description'];
if (!empty ($keywords)) $txt['site_keywords'] = $keywords;
else $txt['site_keywords'] = $config['site_keywords'];
}
// create rating image (star)
// show 5 stars, input: 0-10
function rating_img ($rating)
{
global $config;
$img = "";
$s_rating = floor ($rating);
// full star
for ($i=1; $i<=$s_rating; $i++) $img .= "<img src=\"$config[skin]/images/star_full.gif\" alt=\"full star\" />";
// half star
if ($s_rating < $rating)
{
$h_rating = $rating * 10;
if (($h_rating / 5) % 2) { $img .= "<img src=\"$config[skin]/images/star_half.gif\" alt=\"half star\" />"; $s_rating++; }
}
// empty star
for ($i=$s_rating+1; $i<=5;$i++) $img .= "<img src=\"$config[skin]/images/star_empty.gif\" alt=\"empty star\" />";
return $img;
}
// send email (advanced feature)
// $html = 0 : send only plain text | 1 : send HTML email
// $debug = 0 : display nothing | 1 : display email information (NOT SENDING EMAIL!)
function email ($to, $subject, $body, $html = 0, $debug = 0)
{
global $config;
// remove double new line under Windows
$body = str_replace("\r",'', stripslashes ($body));
if ($html) $content_type = 'text/html'; else $content_type = 'text/plain';
// prepare headers
$headers = "From: $config[site_email]\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: $content_type; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-MSMail-Priority: \r\n";
$headers .= "X-Mailer: PHP-mailer\r\n";
// and now mail it
if ($debug)
{
if (!$html) $body = '<font face="Courier New" size="2">'.nl2br ($body).'</font>';
echo "<table width='100%' border='1' style='border-collapse: collapse;' bgcolor='lightblue'>\n";
echo "<tr><td colspan='2' width='100%' align='center'><b>Email Debug</b></td></tr>\n";
echo "<tr><td nowrap><b>Email type</b></td><td width='90%'>$content_type</td></tr>\n";
echo "<tr><td nowrap><b>Send to</b></td><td width='90%'>$to</td></tr>\n";
echo "<tr><td nowrap><b>Subject</b></td><td width='90%'>$subject</td></tr>\n";
echo "<tr><td nowrap><b>Additional Headers</b></td><td width='90%'>".nl2br($headers)."</td></tr>\n";
echo "<tr><td nowrap><b>Message</b></td><td width='90%'>$body</td></tr>\n";
echo "</table>\n";
}
else
{
mail ($to, $subject, $body, $headers);
}
}
function validate_email_address ($address)
{
// check address format
$address = stripslashes($address);
if (!ereg ("^.+@.+\\..+$", $address) || empty ($address)) return FALSE;
if (eregi ("\r", $address) || eregi ("\n", $address)) return FALSE;
// safe
return TRUE;
}
// format num using predefined $config
// $currency = 1 : display currency formatting (ie. $config['num_*'])
function num_format ($number, $comma = 0, $currency = 0)
{
global $config;
if ($currency)
{
if (empty ($config['num_thousands_sep'])) $config['num_thousands_sep'] = ' ';
$val = number_format ($number, $config['num_decimals'], $config['num_dec_point'], $config['num_thousands_sep']);
if ($config['num_curr_pos']) $val .= $config['num_currency']; else $val = $config['num_currency'].$val;
}
else
{
$val = number_format ($number, $comma, $config['num_dec_point'], $config['num_thousands_sep']);
}
return $val;
}
function redir ($url)
{
global $config;
if (headers_sent () && $config['force_redir'])
{
echo "<html>\n<head>\n";
echo " <meta http-equiv=\"refresh\" content=\"0;url=$url\">\n";
echo " </head>\n<body>Redirecting to <a href=\"$url\">$url</a></body><html>";
}
else
{
header ("Location: $url");
}
die; // <<- IMPORTANT!
}
// convert string from html_entities () into original html (esp. values from <form>)
// we don't use html_entity_decode (which is only available from php 4.3.0), because it wrongly convert a double
// html_entities, e.g <img => <img => &lt;img, which converted to <img directly, when it suppose to be <img.
function html_unentities ($text, $quote_style = ENT_QUOTES)
{
$trans_table = array_reverse (array_flip (get_html_translation_table (HTML_SPECIALCHARS, $quote_style)));
$trans_table['&'] = '&tmp;';
$s = array_keys ($trans_table);
$r = array_values ($trans_table);
$text = str_replace ($s, $r, $text);
$text = str_replace ('&tmp;', '&', $text);
$text= preg_replace ('/&#(\d+);/me', "chr(\\1)", $text); #decimal notation
$text= preg_replace ('/&#x([a-f0-9]+);/mei', "chr(0x\\1)", $text);#hex notation
return $text;
}
// prepare random seed
function make_seed()
{
list ($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
// RTE support to display image in RTE editor, no matter where you put RTE
function rte_to_abs ()
{
global $config;
$abs_path = $config['site_url'];
$args = func_get_args();
if ((strpos ($args[0][3], 'http://') === false) && (strpos ($args[0][3], 'mailto:') === false) &&
(strpos ($args[0][3], 'https://') === false) && ($args[0][3][0] != '/'))
{
return $args[0][1].$args[0][2].'"'.$abs_path.'/'.$args[0][3].'"'.$args[0][4].'>';
}
else
{
return $args[0][0];
}
}
// create rte_safe text
function rte_safe ($input)
{
global $config;
if (!$config['wysiwyg']) return htmlentities ($input);
$s = '<img|<frame|<script|<style';
if ($config['rte_rpc']) $input = preg_replace_callback ('/(['.$s.'][^>]+)(src=)["|\']([^"|^\']+)["|\'^]([^\>]*)>/i', 'rte_to_abs', $input);
$search = array (chr(13), chr(10), chr(145), chr(146), chr(39) , chr(34), '</');
$replace = array ('\r' , '\n' , '‘', '’', ''', '"' , '<\\/');
$input = (str_replace ($search, $replace, $input));
return $input;
}
// prepare RTE area
// when using RTE don't forget to add <form action="[action.php]" method="post" onsubmit="return submitForm();">
function rte_area ($id, $text = '', $width = 500, $height = 200)
{
global $config, $txt, $mode;
if ($config['wysiwyg'])
{
$mode = 'rte_init';
if ($config['multi_rte']) $mode = 'rte_multi'; else $config['multi_rte'] = 1;
}
else
{
$mode = 'text';
}
if (strpos (Cur_Url (), 'includes%2F') OR strpos (Cur_Url (), 'admin%2F'))
$rte['basedir'] = '../'.$config['rte_basedir'];
else
$rte['basedir'] = $config['rte_basedir'];
$rte['f_textarea'] = $id;
$rte['f_width'] = $width;
$rte['f_height'] = $height;
$rte['f_html'] = rte_safe ($text);
return quick_tpl (load_tpl ($config['rte_skin']), $rte);
}
// convert smilies code to smilies images (see lang.php for list)
function convert_smilies ($text, $parent_dir = '')
{
global $smilies;
foreach ($smilies as $key => $val)
{
$smile_key[] = $key;
$smile_val[] = "<img src=\"$parent_dir$val\" alt=\"$key\" />";
}
return str_replace ($smile_key, $smile_val, $text);
}
// display smilies list
// f_id = form name, i_id = input text -or- textarea name
function get_smilies ($f_id, $i_id)
{
global $smilies;
$tmp = "<script type=\"text/javascript\">\nfunction insert_smilies (id)\n{ document.forms['$f_id'].$i_id.value+=' '+id+' ' }\n</script>\n";
$tmp .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\"><tr>\n";
foreach ($smilies as $key => $val)
{
$tmp .= "<td width=\"17\"><img src=\"$val\" alt=\"$key\" title=\"$key\" onclick=\"insert_smilies ('$key')\" /></td>\n";
}
$tmp .= '</tr></table>';
return $tmp;
}
// censor some words (see lang.php for list)
function word_censor ($text)
{
global $censor;
foreach ($censor as $key => $val)
{
$censor_key[] = "/$key/i";
$censor_val[] = $val;
}
return preg_replace ($censor_key, $censor_val, $text);
}
// generate pagination
// well, it's easier than i thought.....
// $base_url = url link to use. this func will add '&p=xx' at the end of $base_url
function generate_pagination ($base_url, $total_pages, $cur_page)
{
global $config;
$per_page = $config['list_ppp'];
$mid = floor ($per_page / 2);
$page_string = array ();
if ($total_pages == 1) return '';
if ($cur_page <= $mid)
$start = 1;
else
{
if ($cur_page + $mid > $total_pages)
$start = $total_pages - $per_page + 1;
else
$start = $cur_page - $mid;
}
$finish = $start + $per_page - 1;
if ($finish > $total_pages) $finish = $total_pages;
if ($start < 1) $start = 1;
for ($i = $start; $i <= $finish; $i++)
{
if ($i == $cur_page)
$page_string[] = "<b>$i</b> ";
else
if ($config['short_query'])
$page_string[] = "<a href=\"$base_url,$i\">$i</a>";
else
$page_string[] = "<a href=\"$base_url&p=$i\">$i</a>";
}
return $page_string;
}
// create multipage sql result ... only display item #1 to #X in page Y (see $config['list_ipp'] & $config['list_ppp'])
// $table = table name | $columns = columns to select (use * or col_name, col_name, col_name) | $where = where query
// $order_by = order by query | $cur_page = current page | $script_name = script to handle list
// $per_page = number of item per page (if empty -> $config['list_ipp'])
function sql_multipage ($table, $columns, $where, $order_by, $cur_page, $script_name, $per_page = '')
{
global $config, $txt, $lang, $tpl_block;
$tmp = array ();
$i = 0;
$p = $cur_page;
if (empty ($per_page)) $ipp = $config['list_ipp']; else $ipp = $per_page; // ipp = items per page
if (!empty ($where)) $where = 'WHERE '.$where;
if (!empty ($order_by)) $order_by = 'ORDER BY '.$order_by;
// get total pages
$res = sql_query ("SELECT COUNT(*) AS total FROM $table $where");
$row = sql_fetch_array ($res);
$total = $row['total'];
$pages = ceil($total / $ipp); // number of pages of list
// verify vars
// if $p is not defined or $p > number_of_pages
if (empty ($p) or ($p > $pages) or ($p < 1)) $p = "1";
$start = ($p-1) * $ipp;
$sql = "SELECT $columns FROM $table $where $order_by LIMIT $start, $ipp";
$res = sql_query ($sql);
while ($row = sql_fetch_array ($res))
{
$i++;
$tmp[$i] = $row;
}
// previous & next page link
$pr = $p - 1;
$nx = $p + 1;
// generate list pages link
if (!strpos ($script_name, '?') && !strpos ($script_name, '&')) $script_name .= '?';
// else $script_name .= '&';
if ($p > 1)
{
if ($config['short_query'])
$row['pg_prev'] = "<a href=\"$script_name,$pr\">".$lang['l_pp_prev']."</a>";
else
$row['pg_prev'] = "<a href=\"$script_name&p=$pr\">".$lang['l_pp_prev']."</a>";
}
else
{
$row['pg_prev'] = $lang['l_pp_prev'];
}
if ($p < $pages)
{
if ($config['short_query'])
$row['pg_next'] = "<a href=\"$script_name,$nx\">".$lang['l_pp_next']."</a>";
else
$row['pg_next'] = "<a href=\"$script_name&p=$nx\">".$lang['l_pp_next']."</a>";
}
else
{
$row['pg_next'] = $lang['l_pp_next'];
}
// generate page list
$tpl = load_tpl ($config['skin'].'/pagination.tpl');
$row['block_pagelist'] = '';
$t = generate_pagination ("$script_name", $pages, $p);
if (is_array ($t) && !empty ($t))
{
foreach ($t as $val)
{
$row['pp'] = $val;
$row['block_pagelist'] .= quick_tpl ($tpl_block['pagelist'], $row);
}
// generate list content
if ($p == 1)
$row['pg_top'] = $lang['l_pp_top'];
else
if ($config['short_query'])
$row['pg_top'] = "<a href=\"$script_name,1\">".$lang['l_pp_top']."</a>";
else
$row['pg_top'] = "<a href=\"$script_name&p=1\">".$lang['l_pp_top']."</a>";
if ($p == $pages)
$row['pg_last'] = $lang['l_pp_last'];
else
if ($config['short_query'])
$row['pg_last'] = "<a href=\"$script_name,$pages\">".$lang['l_pp_last']."</a>";
else
$row['pg_last'] = "<a href=\"$script_name&p=$pages\">".$lang['l_pp_last']."</a>";
$row['pg_current_page'] = $p;
$row['pg_total_pages'] = $pages;
$row['pg_total_items'] = num_format ($total);
$txt['pagination'] = quick_tpl ($tpl, $row);
}
else
{
$txt['pagination'] = '';
}
// done
return $tmp;
}
// split string or array.... eg. string '1;abc;2;def' -> array (array ('1', 'abc'), array ('2', 'def'))
// $as_key: use odd value as key (array[1] = 'abc'; array[2] = 'def')
function array_split ($source, $divider, $as_key = 0)
{
$ok = TRUE; $i = 0;
$output = array ();
if (!is_array ($source))
{
if (substr ($source, -1) != $divider) $source .= $divider;
$source = explode ($divider, $source);
}
reset ($source);
while ($ok)
{
$i++;
if ($as_key)
{
$k = current ($source); $v = next ($source);
$output[$k] = $v;
}
else
{
$output[1][$i] = current ($source);
$output[2][$i] = next ($source);
}
if (!next ($source)) $ok = FALSE;
}
return $output;
}
// create date (dd-mmm-yyyy) select form
// - return: a form field to select date-month-year
// - input:
// $prefix = add prefix to form field (prefix_dd, prefix_mm, prefix_yy)
// $show_year = self explanatory, also to indicate start year
// $show_date, $show_month = self explanatory
// $select = default $select date (format: Y-m-d), or use 'now' or 'today'
// - example: date_form ('mydate', 2005, 1, 1, 'today');
function date_form ($prefix, $show_year, $show_month = '', $show_date = '', $select = '')
{
global $lang;
$ok = FALSE;
$mi = array ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'); // define month index
// get default date
if (($select == 'now') || ($select == 'today')) $select = date ('Y-m-d');
if (empty ($select)) $select = '0000-00-00';
$thn = substr ($select, 0, 4);
$bln = substr ($select, 5, 2);
$tgl = substr ($select, 8, 2);
if ($show_date)
{
for ($d = 1; $d <= 31; $d++) $dt[$d] = $d;
$tmp['D'] = create_select_form ($prefix.'_dd', $dt, $tgl);
}
if ($show_month)
{
for ($m = 1; $m <= 12; $m++)
{
$i = current ($mi);
$mt[$m] = $lang['datetime'][$i];
next ($mi);
}
$tmp['M'] = create_select_form ($prefix.'_mm', $mt, $bln);
}
if ($show_year)
{
if ($show_year < 1901) $show_year = 1901;
$yn = date ('Y');
for ($y = $show_year; $y <= $yn; $y++) $yt[$y] = $y;
$tmp['Y'] = create_select_form ($prefix.'_yy', $yt, $thn);
}
$output = '';
for ($i=0; $i<3; $i++)
{
$j = $lang['l_select_date_format'][$i];
$output .= $tmp[$j];
}
return $output;
}
// get date input from date_form() function
// - return: date in Y-m-d format (sql ready)
// false if invalid date (2005-02-31)
// die() if out-of-bound date (2005-13-32)
// - note: if all field exists (complete YYYY-MM-DD) also check date validity (2005-02-29 will return FALSE); otherwise
// (only YYYY-MM or YYYY) return as-is.
function date_param ($prefix, $method = 'get')
{
$tmp = '';
if ($method == 'get')
{
$yy = get_param ($prefix.'_yy');
$mm = get_param ($prefix.'_mm');
$dd = get_param ($prefix.'_dd');
}
else
{
$yy = post_param ($prefix.'_yy');
$mm = post_param ($prefix.'_mm');
$dd = post_param ($prefix.'_dd');
}
if ("$yy$mm$dd" == "") return FALSE;
if (strlen ($yy) != 4)
die ('Incorrect year value for date_param()');
else
$tmp = $yy;
if (($yy < 1901) || ($yy > 2038)) die ('Out of bound for date_param()');
if ($mm)
{
if (strlen ($mm) < 2) $mm = "0$mm";
if (strlen ($mm) > 2) die ('Incorrect month value for date_param()');
if (($mm > 12) || ($mm < 1)) die ('Out of bound for date_param()');
$tmp .= "-$mm";
}
if ($dd)
{
if (strlen ($dd) < 2) $dd = "0$dd";
if (strlen ($dd) > 2) die ('Incorrect month value for date_param()');
if (($dd > 31) || ($dd < 1)) die ('Out of bound for date_param()');
$tmp .= "-$dd";
if (!verify_date ($tmp)) return FALSE;
}
return $tmp;
}
// optimize image without sacrificing image quality (only in GD 2)
// $source = file source; $target = file output;
// $target_x = output x size; $target_y = output y size; $target_q = output quality
function image_optimizer ($source, $target, $target_q, $target_x = 0, $target_y = 0)
{
global $config;
$gd_version = $config['gd_library'];
// works only on JPEG
$inf = getimagesize ($source);
if ($inf[2] == 2 && !empty ($target_q))
{
$img_size = GetImageSize ($source);
$img_in = ImageCreateFromJPEG ($source);
$quality = $target_q;
if (empty ($target_x)) $target_x = $inf[0];
if (empty ($target_y)) $target_y = $inf[1];
if ($gd_version == '1')
{
$img_out = ImageCreate ($target_x, $target_y);
ImageCopyResized ($img_out, $img_in, 0, 0, 0, 0, $target_x, $target_y, $img_size[0], $img_size[1]);
}
elseif ($gd_version == '2')
{
$img_out = ImageCreateTrueColor ($target_x, $target_y);
ImageCopyResampled ($img_out, $img_in, 0, 0, 0, 0, $target_x, $target_y, $img_size[0], $img_size[1]);
}
ImageJPEG ($img_out, $target, $quality);
ImageDestroy ($img_out);
ImageDestroy ($img_in);
return true;
}
else
{
return false;
}
}
// internal use
function iparam ($mode='', $tbl='')
{
global $db_name;
$res = mysql_list_fields ($db_name, $tbl);
$l = mysql_num_fields ($res);
switch ($mode)
{
case 'get':
case 'post':
for ($i = 0; $i < $l; $i++)
{
$name = mysql_field_name ($res, $i);
echo "\$$name = ".$mode."_param ('$name');<BR />";
}
break;
case 'sql':
echo "INSERT INTO $tbl SET<BR />";
for ($i = 0; $i < $l; $i++)
{
$name = mysql_field_name ($res, $i);
echo "$name = '\$$name',<BR />";
}
echo '"';
break;
}
}
?>