Ravens PHP Scripts: Forums
 

 

View next topic
View previous topic
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> General/Other Stuff
Author Message
transit
Regular
Regular


Joined: Jun 01, 2010
Posts: 69

PostPosted: Thu Jun 17, 2010 12:42 pm Reply with quote

I am using Kemana directory and intergrating it as a module into my RN 2.40.1
Only registered users can see links on this board! Get registered or login!

I am trying to be able to add height and width parameters to resize an image. Now if you look at the bottom of the code it seems that height is defined as $2 and width as $1. So it looks as if the values area already accounted for I just dont know what I should change in this code! Thanks to any help anyone can give!

Specific BBCode in includes/function.php

Code:



// http://duncan.xtreme.net.nz/bbCode.php.txt
// convert bbcode to html, eg [b]bold[/b] to <b>bold</b>
function BBCode($Text)
{
   // Declare the format for layout
   $CodeLayout = '<div class="code"><b>Code:</b><br />$1</div>';

   // Declare the format for [quote] layout
   $QuoteLayout = '<blockquote><b>Quote:</b><br />$1</blockquote>';

   // Set up the parameters for a URL search string
   $URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";
   
   // Set up the parameters for a MAIL search string
   $MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";
   
   // BBCODE
   $match   = array ('<', '>', '[*]', '[/*]', '[p]', '[/p]');
   $replace = array ('&lt;', '&gt;', '<li>', '</li>', '<p>', '</p>');
   
   $match2   = array ("/\[url\]([$URLSearchString]*)\[\/url\]/", "(\[url\=([$URLSearchString]*)\](.+?)\[/url\])",
                      "(\[mail\]([$MAILSearchString]*)\[/mail\])", "/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/",
                  "(\[b\](.+?)\[\/b])is", "(\[i\](.+?)\[\/i\])is", "(\[u\](.+?)\[\/u\])is",
                  "(\[s\](.+?)\[\/s\])is", "(\[o\](.+?)\[\:clap:])is", "(\[color=(.+?)\](.+?)\[\/color\])is",
                  "(\[size=(.+?)\](.+?)\[\/size\])is",
                  "/\[list\](.+?)\[\/list\]/is", "/\[list=1\](.+?)\[\/list\]/is",
                  "/\[list=i\](.+?)\[\/list\]/s", "/\[list=I\](.+?)\[\/list\]/s",
                  "/\[list=a\](.+?)\[\/list\]/s", "/\[list=A\](.+?)\[\/list\]/s",
                  "(\[font=(.+?)\](.+?)\[\/font\])", "/\[code\](.+?)\[\/code\]/is",
                  "/\[quote\](.+?)\[\/quote\]/is",
                  "/\[img\](.+?)\[\/img\]/", "/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/");
                  
   $replace2 = array ('<a href="$1" target="_blank">$1</a>', '<a href="$1" target="_blank">$2</a>',
                      '<a href="mailto:$1">$1</a>', '<a href="mailto:$1">$2</a>',
                  '<b>$1</b>', '<i>$1</i>', '<u>$1</u>',
                  '<strike>$1</strike>', '<span style="text-decoration: overline">$1</span>', "<span style=\"color: $1\">$2</span>",
                  "<span style=\"font-size: $1px\">$2</span>",
                  '<ul>$1</ul>', '<ol>$1</ol>',
                  '<ol type="i">$1</ol>', '<ol type="I">$1</ol>',
                  '<ol type="a">$1</ol>', '<ol type="A">$1</ol>',
                  "<span style=\"font-family: $1;\">$2</span>", "$CodeLayout",
                  "$QuoteLayout",
                  '<img src="$1">', '<img src="$3" height="$2" width="$1">');

 
View user's profile Send private message
transit
PostPosted: Thu Jun 17, 2010 12:56 pm Reply with quote

[quote]

<?php
// part of qEngine
// copyright (c) C97.net, usage of this script outside C97 is strictly prohibited!
// please write to us for licensing: Only registered users can see links on this board! Get registered or login!

/* Strucure:
// Description
// Parameters - if no info, means the parameter is self explanatory
// Sample of usage - if no sample, means it's quite easy (title is self explanatory)
// Used in (this function is used by ??) - if no info, means used by many ---> used_by only indicates that the function is used within qEngine, so it may be used by other script not listed here
*/

/* ------- ( GENERAL FUNCTIONS ) ------- */


// sending message and just die
function msg_die ($msg_id = '', $msg_txt = '', $url = '')
{
global $config;
if (empty ($url)) @$url = $_SERVER['HTTP_REFERER'];
$msg_txt = safe_send ($msg_txt);
$url = urlencode ($url);
$foo = 'MSG|'.$msg_txt.'|'.$url;
ip_config_update ('system_msg', $foo);
redir ("$config[site_url]/msg.php?admin=0&id=$msg_id");
die ();
}


// like msg_die, but in popup template
function popup_die ($msg_id = '', $msg_txt = '')
{
global $config;
$msg_txt = safe_send ($msg_txt);
$foo = 'MSG|'.$msg_txt;
ip_config_update ('system_msg', $foo);
redir ("$config[site_url]/msg.php?admin=0&popup=1&id=$msg_id");
die ();
}


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


// get paramenter from GET, POST or COOKIE ... speedtype 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; $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 == 'bbcode') || ($cm == 'bbc')) && $config['bbcode'])
{
// filter notes
$s = array ('<b>', '</b>', '<i>', '</i>', '<u>', '</u>');
$r = array ('', '', '', '', '', '');
$param = strip_tags ($param, '<b><i><u>');
if (function_exists ('str_ireplace')) $param = str_ireplace ($s, $r, $param); else $param = str_replace ($s, $r, $param);
}

if (($cm == 'rte') && ($config['wysiwyg'])) $html = 1;
if (($cm == 'rte') && (!$config['wysiwyg'])) $html = 0;
}

if ($html)
return $param;
else
return htmlspecialchars ($param, ENT_QUOTES);
}


// 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 (" -> &quot;)!
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);
}


// like get_param but for POST method
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);
}
}


// like get_param but for COOKIE
function cookie_param ($var_name)
{
if (!isset ($_COOKIE[$var_name]))
return '';
else
{
$v = $_COOKIE[$var_name];
$v = filter_param ($v, '');
return trim ($v);
}
}


// like get_param but to get MODULE PARAMETER (eg: <!-- BEGINMODULE xyz --> param1 = value1 <!-- ENDMODULE -->)
// used in: mostly by modules
function mod_param ($var_name, $default = '')
{
global $mod_ini;
if (empty ($mod_ini[$var_name])) return $default; else return $mod_ini[$var_name];
}

// 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)
{
if ($l < 1) return $txt;
$ori = strlen ($txt);
$txt = str_replace ("\n", " ", $txt);
$txt = wordwrap ($txt, $l, "\n", 1);
$i = strpos ($txt, "\n");
if (empty($i)) $i = $l;
$foo = substr ($txt, 0, $i);
if (strlen ($foo) < $ori) $foo .= '...';
return $foo;
}


// get microtime (ie. milisecond)
function getmicrotime ()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}


// 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'] = ' ';
if ($number < 0) $neg = TRUE; else $neg = FALSE;
$val = number_format (abs ($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;
if ($neg) $val = '-'.$val;
}
else
{
$val = number_format ($number, $comma, $config['num_dec_point'], $config['num_thousands_sep']);
}

return $val;
}


// 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')
// used in: load_form() & form.php
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;
}


// clean an array (single or multi dimension) from empty (0, '') values
// (c) alessandronunes at gmail dot com, based on Nimja's func (php.net)
// used in: real_url ()
function array_clean ($array)
{
foreach ($array as $index => $value)
{
if (is_array ($array[$index])) $array[$index] = array_clean ($array[$index]);
if (empty($value)) unset($array[$index]);
}
return $array;
}


// prepare random seed
// used in: usually in init.php
function make_seed()
{
list ($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}


// merge 2 arrays to 1 array, using array1 as key, array2 as val => new_array[array1] = array2
// used in: mostly by qadmin
function array_pair ($array1, $array2, $first = '')
{
$t1 = array_values ($array1);
$t2 = array_values ($array2);
$t = array ();
$l = count ($t1);
if (!empty ($first)) $t[0] = $first;
for ($i = 0; $i <= $l - 1; $i++) $t[$t1[$i]] = $t2[$i];
return $t;
}


// clean a url from some GET queries (eg. a.php?o=1&p=2&q=3 => clean 'o', 'p' => a.php?q=3)
// $needle = can be array ('o', 'p') or string
// used in: mostly by qadmin
function clean_get_query ($needle)
{
$foo = '';

// get active php
$t = parse_url (urldecode (cur_url()));
$script = basename ($t['path']);

// filter
if (is_array ($needle))
{
foreach ($_GET as $key => $val)
{
$val = urlencode ($val);
if (!in_array ($key, $needle)) $foo .= "&amp;$key=$val";
}
}
else
{
foreach ($_GET as $key => $val)
{
$val = urlencode ($val);
if ($key != $needle) $foo .= "&amp;$key=$val";
}
}

return $script.'?'.substr ($foo, 5);
}


// get abs url from rel url
function real_url ($absolute, $relative)
{
$absolute = str_replace ('%20', ' ', $absolute);
$relative = str_replace ('%20', ' ', $relative);
$relative = str_replace ('\\', '/', $relative);
$dir = parse_url ($absolute); // explode abs url to path info

$aparts = array_clean (explode ("/", $dir['path'])); // split each path level (level1/level2/level3) to array
$rparts = array_clean (explode ("/", $relative));

if($relative[0] == '/')
{
$aparts = array (); // if $relavtive => absolute => remove aparts array
}
else
{
$foo = $rparts; // otherwise, if current level = . => remove level; if .. => remove level and remove bottom level of abs path
foreach ($foo as $i => $part)
{
if($part == '.')
{
array_shift ($rparts);
}
if($part == '..')
{
array_pop ($aparts);
array_shift ($rparts);
}
}
}

$apath = implode("/", $aparts);
$path = implode("/", $rparts);

$url = "";
$url .= (!empty ($dir['scheme'])) ? $dir['scheme'].'://' : '';
$url .= (!empty ($dir['user'])) ? $dir['user'] : '';
$url .= (!empty ($dir['pass'])) ? ':'.$dir['pass'] : '';
$url .= (!empty ($dir['user'])) ? '@' : '';
$url .= (!empty ($dir['host'])) ? $dir['host'].'/' : '';
$url .= $apath;
if (substr ($url, -1, 1) != '/') $url .= '/'.$path; else $url .= $path;
return $url;
}


/* ------- ( MYSQL FUNCTIONS ) ------- */


// sending query to MySQL
function sql_query ($sql, $debug = 0)
{
global $dbh, $config, $db_prefix;

$config['total_mysql_query']++;

if ($debug) echo $sql.'<br />';
if (!$result = mysql_query ($sql, $dbh))
{
if ($config['debug_mode']) echo $sql,'<br />';
die (mysql_error ());
}
return $result;
}


// get one line quickly
function sql_qquery ($sql, $debug = 0)
{
$res = sql_query ($sql, $debug);
return sql_fetch_array ($res);
}


// 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 blank vars from a table (useful for creating empty fields in form)
function create_blank_tbl ($tbl)
{
global $db_name, $db_prefix;
$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;
}


// 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 (not used?)
// $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;
}

// generate page list
$txt['pagination'] = generate_pagination ($script_name, $pages, $p, $total);

// done
return $tmp;
}


// generate pagination
// $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, $num_item)
{
global $config, $tpl_block, $lang;

// clear $script_name from &p param
$base_url = clean_get_query ('p');
if (!strpos ($base_url, '?') && !strpos ($base_url, '&amp;')) $base_url .= '?';

// template
if (strpos (cur_url(), '%2Fadmin%2F')) $tpl = load_tpl ('admin', 'pagination.tpl'); else $tpl = load_tpl ('pagination.tpl');
$row['block_pagelist'] = '';

$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
$page_string[] = "<a href=\"$base_url&amp;p=$i\">$i</a>";
}

// previous & next page link
$pr = $cur_page - 1;
$nx = $cur_page + 1;

if ($cur_page > 1)
$row['pg_prev'] = "<a href=\"$base_url&amp;p=$pr\">".$lang['l_pp_prev']."</a>";
else
$row['pg_prev'] = $lang['l_pp_prev'];

if ($cur_page < $total_pages)
$row['pg_next'] = "<a href=\"$base_url&amp;p=$nx\">".$lang['l_pp_next']."</a>";
else
$row['pg_next'] = $lang['l_pp_next'];

// first & last pages
if ($cur_page == 1)
$row['pg_top'] = $lang['l_pp_top'];
else
$row['pg_top'] = "<a href=\"$base_url&amp;p=1\">".$lang['l_pp_top']."</a>";

if ($cur_page == $total_pages)
$row['pg_last'] = $lang['l_pp_last'];
else
$row['pg_last'] = "<a href=\"$base_url&amp;p=$total_pages\">".$lang['l_pp_last']."</a>";

// generate pagenumber
foreach ($page_string as $val)
{
$row['pp'] = $val;
$row['block_pagelist'] .= quick_tpl ($tpl_block['pagelist'], $row);
}

// generate list content
$row['pg_current_page'] = $cur_page;
$row['pg_total_pages'] = $total_pages;
$row['pg_total_items'] = num_format ($num_item);
$pagelist = quick_tpl ($tpl, $row);

// return $pagelist;
$pagelist .= '<!-- q E i s c r e at e d b y C 9 7 . n e t ( h t t p : / / w w w . c 9 7 . n e t ) -->
<!-- Contact us for more information -->';
return $pagelist;
}


// create SQL's where query
function create_where ($row, $query, $mode = 'AND')
{
$where = array ();
$keyword = strtok ($query, ' ');
while ($keyword)
{
$where[] = "$row LIKE '%".$keyword."%'";
$keyword = strtok (' ');
}

$where = implode (" $mode ", $where);
return "($where)";
}


// from php.net by: Only registered users can see links on this board! Get registered or login!
// $line: the csv line to be split
// $delim: the delimiter to split by
// $removeQuotes: if this is false, the quotation marks won't be removed from the fields
// used in: load_form (), form.php
function csv_split ($line, $delim=',', $removeQuotes=true)
{
$fields = array();
$fldCount = 0;
$inQuotes = false;
for ($i = 0; $i < strlen($line); $i++)
{
if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = substr ($line,$i,strlen($delim));
if ($tmp === $delim && !$inQuotes)
{
$fldCount++;
$i += strlen($delim)-1;
}
else
if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes)
{
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = true;
}
else
if ($line[$i] == '"')
{
if ($i+1 < strlen($line) && $line[$i+1] == '"')
{
$i++;
$fields[$fldCount] .= $line[$i];
}
else
{
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = false;
}
}
else
{
$fields[$fldCount] .= $line[$i];
}
}
return $fields;
}


/* ------- ( DATE & TIME FUNCTIONS ) ------- */


// 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') && ($mode != 'int' && $mode != 'unix')) return 'Invalid Date';
if (($sql_date == '0000-00-00') && ($mode == 'int' || $mode == 'unix')) return FALSE;
if (empty ($sql_date)) return '';
if (($sql_date == 'today') || ($sql_date == 'now')) $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 '0':
case 'short':
$tanggal = date ($lang['l_short_date_format'], $tglbener);
break;

case '1':
case 'long':
$tanggal = date ($lang['l_long_date_format'], $tglbener);
break;

case '2':
case 'mini':
$tanggal = date ('d/m', $tglbener);
break;

case '3':
case 'form':
$tanggal = date ($lang['l_form_date_format'], $tglbener);
break;

case 'sql':
$tanggal = date ('Y-m-d', $tglbener);
return $tanggal;
break;

case 'int':
case 'unix':
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;
}


// calculate 'how many days have passed since...' (different between 2 dates)
// 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);
}


/* ------- ( HTML FUNCTIONS ) ------- */


// 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 NOT SELECTABLE option, such as '--PLEASE SELECT--'
// $addtl_option = can be javascript, like: onchange=document.forms[0].submit()
// special array key: --- to disable, *** to add <optgroup>, /// to add </optgroup>; don't forget to add an
// index, eg: ---1, or ***a, or ///whatever.
function create_select_form ($select_name, $source, $selected_value = '', $first_line = '', $disabled = 0, $addtl_option = '')
{
if ($disabled) $disabled = 'disabled="disabled"'; else $disabled = '';
$t = "<select size=\"1\" name=\"$select_name\" $disabled $addtl_option>\n";
if (!empty($first_line)) $t .= "<option value=\"\">$first_line</option>\n";
foreach ($source as $key=>$val)
{
$foo = '';
$doh = substr ($key, 0, 3);
if ($doh == '***') $t .= "<optgroup label=\"$val\">";
elseif ($doh == '///') $t .= "</optgroup>";
else
{
if ($doh == '---') $foo .= " disabled=\"disabled\"";
if ($key == $selected_value) $foo .= " selected=\"selected\"";
$t .= "<option value=\"$key\" $foo>$val</option>\n";
}
}
$t .= "</select>\n";
return $t;
}


// create checkbox form, useful for multiple box ("i need box, lots of boxes" - Neo)
// $box_name = field name
// $source = array[$key] = $val, $key = field value, $val = text to display
// $selected = string: 1,5,8,9; or use array[] = $selected
// $col = number of colums to display
// $form_id = form name -- when defined, will display "Select/Deselect All" button
function create_checkbox_form ($box_name, $source, $selected = '', $col = 3, $form_id = '')
{
$t = array ();
for ($i = 1; $i <= $col; $i++) $t[$i] = '';
$i = 0;

// selected vals
if (!is_array ($selected)) $select = explode (',', $selected); else $select = $selected;
if ($selected == '') $select = array ();

foreach ($source as $key => $val)
{
$j = ($i % $col) + 1;
$k = $i + 1;
if (in_array ($key, $select))
$t[$j] .= "<label><input type=\"checkbox\" name=\"{$box_name}_{$k}\" value=\"$key\" checked=\"checked\" /> $val</label><br />\n";
else
$t[$j] .= "<label><input type=\"checkbox\" name=\"{$box_name}_{$k}\" value=\"$key\" /> $val</label><br />\n";
$i++;
}
for ($i = 1; $i <= $col; $i++) $t[$i] = substr ($t[$i], 0, -7);

if ($form_id)
$out = "<label><input name=\"checkall\" type=\"checkbox\" onclick=\"SetAllCheckBoxes('$form_id','div_$box_name',this.checked);\" /> Select/Deselect All</label><div id=\"div_$box_name\">";
else
$out = '<div>';
if ($col > 1)
{
$w = round (100 / $col);
$out .= "<table border=\"0\" width=\"100%\"><tr>\n";
for ($i = 1; $i <= $col; $i++) $out .= "<td valign=\"top\" width=\"$w%\">$t[$i]</td>\n";
$out .= "</tr></table>";
return $out."</div>";
}
else
return $out.$t[1]."</div>";
}



// 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 (only if col = 1)
// $col = number of column
function create_radio_form ($radio_name, $source, $selected_value = '', $mode = 'h', $col = 1)
{
$t = array ();
for ($i = 1; $i <= $col; $i++) $t[$i] = '';
$i = 0;

foreach ($source as $key => $val)
{
$j = ($i % $col) + 1;
if ($key == $selected_value)
$t[$j] .= "<label><input type=\"radio\" name=\"$radio_name\" value=\"$key\" checked=\"checked\" />$val</label>\n";
else
$t[$j] .= "<label><input type=\"radio\" name=\"$radio_name\" value=\"$key\" />$val</label>\n";

// if col == 1, then can have h or v formatting
if ($col == 1)
{
if ($mode == 'h')
$t[$j] .= '&nbsp;';
else
$t[$j] .= '<br />';
}
// if col > 1, only vertical formatting
else
$t[$j] .= "<br />\n";
$i++;
}

if ($col > 1)
{
for ($i = 1; $i <= $col; $i++) $t[$i] = substr ($t[$i], 0, -7);
$w = round (100 / $col);
$out = "<table border=\"0\" width=\"100%\"><tr>\n";
for ($i = 1; $i <= $col; $i++) $out .= "<td valign=\"top\" width=\"$w%\">$t[$i]</td>\n";
$out .= "</tr></table>";
return $out;
}
else
return $t[1];
}


// create a simple tickbox, it's different from create_checkbox_form, as this is easier
function create_tickbox_form ($name, $string = '', $toggle = 0)
{
$check = empty ($toggle) ? '' : 'checked="checked"';
return "<label><input type=\"checkbox\" name=\"$name\" value=\"1\" $check />$string</label>";
}


// 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'
// $yyrange = if today is 2010, then $yyrange = 10 will display year form: 2005-2015;
// - example: date_form ('mydate', 2005, 1, 1, 'today');
// example: date_form ('mydate') create form for today with Y-m-d
function date_form ($prefix, $show_year = '', $show_month = '', $show_date = '', $select = '', $yyrange = 6)
{
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 (empty ($show_year) && empty ($show_month) && empty ($show_date))
{ $show_date = 1; $show_month = 1; $show_year = date ('Y'); $select = 'now'; }
if (($select == 'now') || ($select == 'today')) $select = date ('Y-m-d');
if (empty ($select)) $select = '0000-00-00';
$f = explode ('-', $select);
if (empty ($f)) $f = explode ('/', $select);
if (empty ($f)) $f = explode ('.', $select);
if (empty ($f[1])) $f[1] = '00';
if (empty ($f[2])) $f[2] = '00';

$thn = $f[0];
$bln = strlen ($f[1]) > 1 ? $f[1] : '0'.$f[1];
$tgl = strlen ($f[2]) > 1 ? $f[2] : '0'.$f[2];

if ($show_date)
{
for ($d = 1; $d <= 31; $d++) $dt[$d] = $d;
$tmp['D'] = create_select_form ($prefix.'_dd', $dt, $tgl, '[ date ]');
}
else $tmp['D'] = '';

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, '[ month ]');
}
else $tmp['M'] = '';

if ($show_year)
{
if ($show_year < 1901) $show_year = date ('Y');
$ys = $show_year - round($yyrange / 2);
$ye = $show_year + round($yyrange / 2);
if ($ys < 1901) $ys = 1901;
for ($y = $ys; $y <= $ye; $y++) $yt[$y] = $y;
$tmp['Y'] = "<input type=\"text\" name=\"{$prefix}_yy\" value=\"$thn\" size=\"4\" />";
}
else $tmp['Y'] = '';

$output = '';
for ($i=0; $i<3; $i++)
{
$j = $lang['l_select_date_format'][$i];
$output .= $tmp[$j];
}

return $output;
}


// time form
// interval is for minutes, eg. interval 5 = show minute form: 00, 05, 10, 15, etc. interval 1 = 00, 01, 02, 03...
function time_form ($prefix, $select = '', $interval = 5)
{
global $lang;
$ok = FALSE;

// get default date
if (($select == 'now') || ($select == 'today')) $select = date ('H:i');
if (empty ($select)) $select = '00:00';
$hou = substr ($select, 0, 2);
$min = substr ($select, 3, 2);
$min = round ($min / $interval) * $interval;

// hour: 00-23
$hh = array ();
for ($h = 0; $h <= 23; $h++)
{
if (strlen ($h) < 1) $hh[$h] = '0'.$h; else $hh[$h] = $h;
}
$tmp['H'] = create_select_form ($prefix.'_hou', $hh, $hou);

// minute: 00-59
$mm = array ();
for ($m = 0; $m <= 59; $m=$m+$interval)
{
if (strlen ($m) < 2) $mm[$m] = '0'.$m; else $mm[$m] = $m;
}
$tmp['M'] = create_select_form ($prefix.'_min', $mm, $min);

$output = $tmp['H'].':'.$tmp['M'];

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 = '';
$method = strtolower ($method);
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');
}

$d = "$yy$mm$dd";
if (($d == "") || ($d == '0000')) 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 day 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;
}


// get time
function time_param ($prefix, $method = 'get')
{
$tmp = '';
$method = strtolower ($method);
if ($method == 'get')
{
$hh = get_param ($prefix.'_hou');
$mm = get_param ($prefix.'_min');
}
else
{
$hh = post_param ($prefix.'_hou');
$mm = post_param ($prefix.'_min');
}

if ("$hh$mm" == "") return FALSE;

if (($hh > 23) || ($hh < 0))
die ('Incorrect hour value for time_param()');
else
$tmp = $hh;

if (($mm > 59) || ($mm < 0))
die ('Incorrect minute value for time_param()');
else
$tmp .= ":$mm";

return $tmp;
}


// get checkbox value (built by create_checkbox_form)
// $as_array = 1 : return values in an array; 0 : return as string (1,2,3,4,5...)
function checkbox_param ($box_name, $method = 'get', $as_array = 0)
{
$method = strtolower ($method);
$foo = array ();
$l = strlen ($box_name) + 1;

if ($method == 'get')
{
foreach ($_GET as $key => $val) if (substr ($key, 0, $l) == $box_name.'_') $foo[] = get_param ($key);
}
else
{
foreach ($_POST as $key => $val) if (substr ($key, 0, $l) == $box_name.'_') $foo[] = post_param ($key);
}


if ($as_array)
return $foo;
else
return implode (',', $foo);
}


// this function will transform (convert?) a url query (eg: abc.php?var=val&yes=no) to array ('var' => 'val', 'yes' => 'no');
function url_query_to_array ($query)
{
$result = array ();
$x = strpos ($query, '?');
$xx = substr ($query, $x + 1, strlen ($query) - $x);
$tok = strtok($xx,"&");
while ($tok)
{
$y = 0;
$y = strpos ($tok, '=', $y);
$key = substr ($tok, 0, $y);
$val = substr ($tok, $y + 1, strlen ($tok) - $y);
$result[$key] = $val;
$tok = strtok('&');
}
return $result;
}


// 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'];
$txt['site_email'] = $config['site_email'];

if ($title == 'adm') $title = 'Administration Panel :: '.$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-5
function rating_img ($rating)
{
global $config, $inc_folder;
$img = "";
$s_rating = floor ($rating);
// full star
for ($i=1; $i<=$s_rating; $i++) $img .= "<img src=\"$inc_folder/$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=\"$inc_folder/$config[skin]/images/star_half.gif\" alt=\"half star\" />"; $s_rating++; }
}

// empty star
for ($i=$s_rating+1; $i<=5;$i++) $img .= "<img src=\"$inc_folder/$config[skin]/images/star_empty.gif\" alt=\"empty star\" />";
return $img;
}


// 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 => &lt;img => &amp;lt;img, which converted to <img directly, when it suppose to be &lt;img.
// used by: email(), update_wordmatch(), user_init.php
function html_unentities ($text, $quote_style = ENT_QUOTES)
{
$trans_table = array_reverse (array_flip (get_html_translation_table (HTML_SPECIALCHARS, $quote_style)));
$trans_table = array ('&amp;' => '&tmp;', '&#039' => '\'', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>');
$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 without zero (123, 234, etc)
$text = preg_replace ('/&#x([a-f0-9]+);/mei', "chr(0x\\1)", $text);#hex notation
return $text;
}


// convert smilies code to smilies images (see lang.php for list)
function convert_smilies ($text)
{
global $smilies;
$parent_dir = get_inc_folder ();

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;
$parent_dir = get_inc_folder ();

$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=\"$parent_dir/$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);
}


// $mode = 0 (default) : use header then html. 1 : html only
function redir ($url = '', $mode = 0)
{
global $config;

if (empty ($url)) $url = @$_SERVER['HTTP_REFERER'];
if (empty ($url)) $url = $config['site_url'];

if ((headers_sent () && $config['force_redir']) || ($mode))
{
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!
}


/* ------- ( FILE FUNCTIONS ) ------- */


// get file list from a path
function get_file_list ($path)
{
$list = array ();
if (substr ($path, -1) != '/') $path .= '/';
$handle=opendir($path);

while (false !== ($file = readdir($handle)))
{
if (is_file ($path.$file)) $list[] = $file;
}

closedir($handle);

return $list;
}


// convert a string to a filename, removing invalid characters
// used by: create_filename ()
function safe_filename ($fn, $len = 50)
{
$fn = strtolower ($fn);
$foo = pathinfo ($fn);

// get only filename
if (empty ($foo['extension'])) $foo['extension'] = '';
$foo['filename'] = substr ($foo['basename'], 0, -1 * strlen ($foo['extension']) -1);

$fn = preg_replace ("/[^a-zA-Z0-9]/", "_", substr ($foo['filename'], 0, $len)).'.'.preg_replace ("/[^a-zA-Z0-9]/", "_", $foo['extension']);
return $fn;
}


// create a file name that doesn't exist in $folder folder
// $folder = folder location
// $fn = original filename (required even if random filename to determine extension)
// $rnd = TRUE: create random name; FALSE: create safe filename
function create_filename ($folder, $fn, $rnd = TRUE)
{
$ok = FALSE;
$foo = pathinfo ($fn);
$ext = $foo['extension'];
$add = ''; // addtional random string(for safe filename), eg: 3c1_somename.ext, '3c1_' is additional string
while (!$ok)
{
if ($rnd)
$tmp_name = random_str (16).'.'.$ext;
else
$tmp_name = $add.safe_filename ($fn);

if (!file_exists ($folder.'/'.$tmp_name)) $ok = TRUE;
$add = random_str (3).'_';
}
return $tmp_name;
}


// safe file upload: 1. limit uploadable files (by extension); 2. disabled in demo mode
// $field = form field name; can be array
// $target = target folder OR target folder and name (= needs file extension); can be array
// $overwrite = TRUE to overwrite same filename; FALSE to save as different name
// return = true if uploaded, false if failed; if inputs are array, it will return array corresponding with each upload status (eg: $return = array (1 => TRUE, 2 => FALSE, 3 => TRUE, 'summary' => 'T')
// --- where $return['success'] is TRUE if all uploaded, FALSE if any failure
function upload_file ($field, $target, $allow_overwrite = FALSE)
{
global $config;
$overwrite = FALSE; $count = $size = 0;
$result = array (); $result['success'] = TRUE; $result['demo_mode'] = FALSE; $result['count'] = $result['size'] = 0;

// for demo mode, return FALSE, explaining, it's in demo mode
if ($config['demo_mode'])
{
$result['success'] = FALSE;
$result['demo_mode'] = TRUE;
return $result;
}

// if not array, create as array
if (!is_array ($field))
{
$field = array ($field);
$target = array ($target);
$array = FALSE;
}
else
$array = TRUE;

// process
foreach ($field as $k => $v)
{
$count++;

if (!empty ($_FILES[$v]['tmp_name']) && !$_FILES[$v]['error'])
{
$result[$k]['source'] = $_FILES[$v]['name'];
$src = $_FILES[$v]['tmp_name'];
$tgt = $target[$k];
$err = FALSE;

if (is_dir ($tgt)) // if folder, use it
{
$tgt_folder = $tgt;
$tgt_name = $_FILES[$v]['name'];
}
else // if not folder, is it an existing file, a new file, or invalid path?
{
$foo = pathinfo ($tgt);
$tgt_folder = $foo['dirname'];
$tgt_name = $foo['basename'];

// not existing file & invalid path => die!
if (is_file ($tgt)) $overwrite = TRUE;
if (!is_file ($tgt) && !is_dir ($tgt_folder)) { $result[$k]['err'] = 'NoTarget'; $result['success'] = FALSE; }
}

// fix file name
if (substr ($tgt_folder, -1, 1) == '/') $tgt_folder = substr ($tgt_folder, 0, -1);
if (!$allow_overwrite) $tgt_name = create_filename ($tgt_folder, $tgt_name, FALSE); // if not allow overwrite = create a safe & non-existing name
if ($allow_overwrite) $tgt_name = safe_filename ($tgt_name); // if allow overwrite = only make sure it's a safe name
$path = $tgt_folder.'/'.$tgt_name;
$result[$k]['path'] = $path;
$result[$k]['filename'] = $tgt_name;

// is it allowable files?
$dis = explode (',', $config['disallow_file']);
foreach ($dis as $dv)
{
$foo = pathinfo ($tgt_name);
$ext = empty ($foo['extension']) ? '' : $foo['extension'];
if (in_array ($ext, $dis)) $err = TRUE;
}

// upload!
if (!$err)
{
move_uploaded_file ($src, $path);
@chmod ($path, 0644);
if (file_exists ($path))
{
$size = $size + $_FILES[$v]['size'];
$result[$k]['err'] = '';
}
else
$result[$k]['err'] = 'NotWriteable';
}
else
{
$result['success'] = FALSE;
$result[$k]['err'] = 'Disallow';
}
}
}

// if $field is not array, return simpler result
$result['count'] = $count;
$result['size'] = $size;
return $result;
}


// to open a remote file (file in different host or url)
// generally we can use fopen ($url), but in some host, it's not allowed
function remote_fopen ($site_url)
{
// if remote fopen allow, use it (it's faster)
if (ini_get ('allow_url_fopen')) return file_get_contents ($site_url);

// if not allowed, use curl
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $site_url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

ob_start();
curl_exec($ch);
curl_close($ch);
$file_contents = ob_get_contents();
ob_end_clean();

return $file_contents;
}


/* ------- ( EMAIL FUNCTIONS ) ------- */


// send email (advanced feature)
// $html : 0 : send only plain text | 1 : send HTML email
// $log; log this email?
// $debug : 0 : display nothing | 1 : display email information (NOT SENDING EMAIL!)
function email ($to, $subject, $body, $html = 0, $log = 0, $debug = 0)
{
global $config, $db_prefix;

// 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 = html_entity_decode ($body);
$body = str_replace (''', "'", $body);
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
{
if (!$html)
{
// reverse &amp -> &; &quot; -> ", etc
$b = html_entity_decode ($body);
$b = str_replace (''', "'", $b);
mail ($to, $subject, html_unentities ($b), $headers);
}
else
mail ($to, $subject, $body, $headers);
$subject = addslashes ($subject);
$body = addslashes ($body);
$to = addslashes ($to);
if ($log) sql_query ("INSERT INTO ".$db_prefix."mailog VALUES ('', '$to', '$subject', '$body', UNIX_TIMESTAMP(), '$html')");
}
}


// validate email address (eg: need to be Only registered users can see links on this board! Get registered or login!
function validate_email_address ($address)
{
if (empty ($address)) return FALSE;

// check address format
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' .
'(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
return preg_match ($pattern, $address);
}


/* ------- ( RTE - WYSIWYG EDITOR & BBCODE EDITOR) ------- */
// We are using TinyMCE as wysiwyg editor
// You can obtain full TinyMCE source in Only registered users can see links on this board! Get registered or login!
// TinyMCE is (c)copyright Moxiecode


// display wysiwyg editor
// $id = ID of form field
// $text = initial value
// $pagebreak = display pagebreak button ( <!-- pagebreak --> )
function rte_area ($id, $text = '', $width = 400, $height = 350, $pagebreak = false)
{
global $config, $txt, $rte_mode;
if ($config['wysiwyg'])
{
$rte_mode = 'rte_init';
if ($config['multi_rte']) $rte_mode = 'rte_multi'; else $config['multi_rte'] = 1;
}
else
{
$rte_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'];

if ($pagebreak) $rte['pagebreak'] = 'pagebreak,'; else $rte['pagebreak'] = '';
$rte['f_textarea'] = $id;
$rte['f_width'] = $width;
$rte['f_height'] = $height;
$rte['f_html'] = htmlentities ($text);
$rte['site_url'] = $config['site_url'];
return quick_tpl (load_tpl ('etc', $config['rte_skin']), $rte);
}

// Only registered users can see links on this board! Get registered or login!
// convert bbcode to html, eg bold to <b>bold</b>
function BBCode($Text)
{
// Declare the format for [code] layout
$CodeLayout = '<div class="code"><b>Code:</b><br />$1</div>';

// Declare the format for
Quote:
layout
$QuoteLayout = '<blockquote><b>Quote:</b><br />$1</blockquote>';

// Set up the parameters for a URL search string
$URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";

// Set up the parameters for a MAIL search string
$MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";

// BBCODE
$match = array ('<', '>', '[*]', '[/*]', '[p]', '[/p]');
$replace = array ('&lt;', '&gt;', '<li>', '</li>', '<p>', '</p>');

$match2 = array ("/\[url\]([$URLSearchString]*)\[\/url\]/", "(\[url\=([$URLSearchString]*)\](.+?)\[/url\])",
"(\[mail\]([$MAILSearchString]*)\[/mail\])", "/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/",
"(\[b\](.+?)\[\/b])is", "(\[i\](.+?)\[\/i\])is", "(\[u\](.+?)\[\/u\])is",
"(\[s\](.+?)\[\/s\])is", "(\[o\](.+?)\[\:clap:])is", "(\[color=(.+?)\](.+?)\[\/color\])is",
"(\[size=(.+?)\](.+?)\[\/size\])is",
"/\[list\](.+?)\[\/list\]/is", "/\[list=1\](.+?)\[\/list\]/is",
"/\[list=i\](.+?)\[\/list\]/s", "/\[list=I\](.+?)\[\/list\]/s",
"/\[list=a\](.+?)\[\/list\]/s", "/\[list=A\](.+?)\[\/list\]/s",
"(\[font=(.+?)\](.+?)\[\/font\])", "/\[code\](.+?)\[\/code\]/is",
"/\[quote\](.+?)\[\/quote\]/is",
"/\[img\](.+?)\[\/img\]/", "/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/");

$replace2 = array ('<a href="$1" target="_blank">$1</a>', '<a href="$1" target="_blank">$2</a>',
'<a href="mailto:$1">$1</a>', '<a href="mailto:$1">$2</a>',
'<b>$1</b>', '<i>$1</i>', '<u>$1</u>',
'<strike>$1</strike>', '<span style="text-decoration: overline">$1</span>', "<span style=\"color: $1\">$2</span>",
"<span style=\"font-size: $1px\">$2</span>",
'<ul>$1</ul>', '<ol>$1</ol>',
'<ol type="i">$1</ol>', '<ol type="I">$1</ol>',
'<ol type="a">$1</ol>', '<ol type="A">$1</ol>',
"<span style=\"font-family: $1;\">$2</span>", "$CodeLayout",
"$QuoteLayout",
'<img src="$1">', '<img src="$3" height="$2" width="$1">');


// Perform search & replace
$Text = str_replace ($match, $replace, $Text);
$Text = preg_replace($match2, $replace2, $Text);
$Text = nl2br($Text);
return convert_smilies ($Text);
}


// display bbcode editor
function bbc_area ($id, $text = '', $width = 450, $height = 100)
{
global $config, $txt, $rte_mode;
if ($config['bbcode'])
{
$rte_mode = 'bbcode_init';
if ($config['multi_bbc']) $rte_mode = 'bbc_multi'; else $config['multi_bbc'] = 1;
}
else
{
$rte_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'] = $text;
return quick_tpl (load_tpl ('etc', $config['rte_skin']), $rte);
}


/* ------- ( IMAGE FUNCTIONS ) ------- */
// require GD version 2.0.28 or later


// 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
// $target_x can be 'thumb' to create thumbnail, or empty to smart-resize
function image_optimizer ($source, $target, $target_q = 0, $target_x = 0, $target_y = 0)
{
global $config;
$gd_version = $config['gd_library'];
$thumb_size = $config['thumb_size'];

// quality
if (empty ($target_q)) $target_q = $config['optimizer'];

// works only on JPEG
$inf = getimagesize ($source);
$format = $inf[2];

if (($format >= 1) && ($format <= 3) && (!empty ($target_q)))
{
$img_size = GetImageSize ($source);

if ($format == 1)
$img_in = ImageCreateFromGIF ($source);
elseif ($format == 2)
$img_in = ImageCreateFromJPEG ($source);
elseif ($format == 3)
$img_in = ImageCreateFromPNG ($source);
else
die ('Unrecognized Format');

// if $x & $y empty -> original size
if (empty ($target_x) && empty ($target_y)) { $target_x = $inf[0]; $target_y = $inf[1]; }

// if $x = any (not 'thumb') & y = empty -> resize
if (!empty ($target_x) && empty ($target_y))
{
if ($target_x != 'thumb')
{
$thumb_size = $target_x;
$target_x = 'thumb';
}
}

// if $x thumb -> create thumb
if ($target_x == 'thumb')
{
if (empty ($target_q)) $target_q = $config['thumb_quality'];

if ($img_size[0] > $img_size[1]) $thumb_on = 'x'; else $thumb_on = 'y';

if ($thumb_on == 'y')
{
$target_x = ($thumb_size/$img_size[1]) * $img_size[0];
$target_y = $thumb_size;
}
else
{
$target_y = ($thumb_size/$img_size[0]) * $img_size[1];
$target_x = $thumb_size;
}
}

// create optimized version
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]);
}

// optimized (output)
if ($format == 1)
ImageGIF ($img_out, $target, $target_q);
elseif ($format == 2)
ImageJPEG ($img_out, $target, $target_q);
elseif ($format == 3)
ImagePNG ($img_out, $target, round ($target_q / 10));
else
die ('Unrecognized Format');

ImageDestroy ($img_out);
ImageDestroy ($img_in);
@chmod ($target, 0644);

return true;
}
else
{
return false;
}
}


/* ------- ( IP CONFIG ) ------- */


// IP CONFIG is not the same with Windows' ipconfig, instead it means 'User-IP based configuration'. Each user can store
// his configuration (skin, language, etc) without opening an account or saving in cookie.
// Config is only stored for 120 minutes.


// update config value
// $what = field name in ip_config table (optional)
function ip_config_update ($what = '', $value = '')
{
global $current_user_id, $db_prefix;
$now = mktime ();
$was = $now - 7200; // 7200 seconds = 2 hours
$ip = $_SERVER['REMOTE_ADDR'];
sql_query ("DELETE FROM ".$db_prefix."ip_config WHERE last_update < $was");
sql_query ("INSERT IGNORE INTO ".$db_prefix."ip_config (ip, username, last_update) VALUES ('$ip', '$current_user_id', '$now')");

if (!empty ($what)) sql_query ("UPDATE ".$db_prefix."ip_config SET $what='$value', username='$current_user_id' WHERE ip='$ip' LIMIT 1");
}


// get ip_config value of $what from ip_config table
function ip_config_value ($what)
{
global $db_prefix;
$ip = $_SERVER['REMOTE_ADDR'];
$res = sql_query ("SELECT $what FROM ".$db_prefix."ip_config WHERE ip='$ip' LIMIT 1");
$row = sql_fetch_array ($res);
return $row[$what];
}


// count numbers of stored ip_config ==> can be used as 'Number of online users' (but time range too big, 60 minutes)!
function ip_config_count ()
{
$res = sql_query ("SELECT SUM(username!='') AS member, SUM(username='') AS guest FROM ".$db_prefix."ip_config LIMIT 1");
$row = sql_fetch_array ($res);
$row['total'] = $row['member'] + $row['guest'];
return $row;
}


/* ------- ( QVC - VISUAL CONFIRMATION FUNCTIONS aka CAPTCHA ) ------- */


// qVC - the simplest visual confirmation engine yet
// use qvc_init() --> <img src="visual.php"> --> compare qvc_value() == sha1 (strtolower($user_input) )?
// qVC uses db to communicate with visual.php, then set user cookie using sha1, then db not used!
// $num = either 3 or 5, 3 => only 0-9, 5 => 0-F
function qvc_init ($num = 5)
{
if ($num == 3)
$value = mt_rand (100, 999);
else
$value = random_str (5);
ip_config_update ('visual', $value);
setcookie ('qvc_value', sha1 ($value), 0, '/');
}


// return qvc value (it's sha1'd, so be sure to compare with sha1'd value)
function qvc_value ()
{
$correct_val = cookie_param ('qvc_value');

// block browser BACK
qvc_init ();
return $correct_val;
}


/* ------- ( AXSRF - Anti Cross Site Request Forgery ) ------- */
// Google the web for XSRF
// So, to fight XSRF, we have to generate random token for each form & user, and compare it with stored token in db
// qTPL cleverly & automatically add hidden field to all forms, but only if you use flush_tpl()


// create AXSRF token value, this function called upon user login/register
function AXSRF_init ()
{
global $login, $db_prefix, $current_user_id, $current_admin_id;
$value = random_str (32);
if ($login)
sql_query ("UPDATE ".$db_prefix."user SET axsrf_token='$value' WHERE user_id='$current_user_id' LIMIT 1");
elseif (!empty ($current_admin_id))
sql_query ("UPDATE ".$db_prefix."user SET axsrf_token='$value' WHERE user_id='$current_admin_id' LIMIT 1");
else
return FALSE;
return $value;
}


// get AXSRF token value
function AXSRF_value ()
{
global $login, $db_prefix, $current_user_id, $current_admin_id;

if ($login)
$res = sql_query ("SELECT axsrf_token FROM ".$db_prefix."user WHERE user_id='$current_user_id' LIMIT 1");
elseif (!empty ($current_admin_id))
$res = sql_query ("SELECT axsrf_token FROM ".$db_prefix."user WHERE user_id='$current_admin_id' LIMIT 1");
else
return FALSE;
$row = sql_fetch_array ($res);

return $row['axsrf_token'];
}


// get & compare token ID automatically
// it automatically get token and do comparison, if failed => die
// $field = hidden form field name (default: AXSRF_token) - both get & post method
// call this function before processing any forms
function AXSRF_check ($field = 'AXSRF_token')
{
global $config;

$db = AXSRF_value ();
if (empty ($db)) die ("Invalid token ID. If this problem occurs, please <a href=\"mailto:$config[site_email]\">contact us.</a>");

$foo = post_param ($field);
if (empty ($foo)) $foo = get_param ($field);

// AXSRF in DB doesn't match with hidden field => die
if ($foo != $db) die ("Invalid token ID. If this problem occurs, please <a href=\"mailto:$config[site_email]\">contact us.</a>");

// safe
return TRUE;
}


/* ------- ( FORM LOADER ) ------- */


// save_form saves user input values for form, so it can be used in form loader
// ONLY 1 FORM can be saved at a time, new save will overwrite old one
function save_form ($form_id, $method = 'post')
{
$tmp = '"form","'.$form_id.'",';
if ($method == 'post')
foreach ($_POST as $key => $val) $tmp .= '"'.$key.'","'.post_param ($key).'",';
else
foreach ($_GET as $key => $val) $tmp .= '"'.$key.'","'.get_param ($key).'",';

$tmp = addslashes (substr ($tmp, 0, -1));
ip_config_update ('saved_form', $tmp);
}


// load_form loads user input values from db, so user doesn't need to re-input values
// return array to be used in tpl
function load_form ($form_id)
{
$foo = ip_config_value ('saved_form');
$tmp = csv_split ($foo);
if (empty ($tmp)) return FALSE;
if ($tmp[1] != $form_id) return FALSE;
foreach ($tmp as $var) $doh[] = stripslashes ($var);
return array_split ($doh, '', TRUE);
}


// empty saved values
function reset_form ()
{
ip_config_update ('saved_form', '');
}


/* ------- ( FAST SEARCH ) ------- */
// Fast Search (FS) is a search alternative for traditional SQL search (SELECT * FROM table WHERE body LIKE '%keywords%')
// FS offers much faster search result, up to 20x faster (or more, on large database)
// to use it: register article using update_wordmatch, then find it using fast_search
// also using FS db, we can create tag cloud (cloud tag?)
// FS uses word_match function's result(see admin_func.php)

// do fast search
// $query = keywords to find
// $identifier = unique ID to identify owner, eg. news, media, shop, etc
// $mode = search mode, OR || AND
// returned is $result (array) containing article id.
// used by: search.php
function fast_search ($query, $identifier, $mode = 'or')
{
global $db_prefix;
$foo = array ();
$i = 0;

$keyword = strtok ($query, ' ');
while ($keyword)
{
$keyword = strtolower ($keyword);
$res = sql_query ("SELECT * FROM ".$db_prefix."wordlist WHERE word_text LIKE '%$keyword%' LIMIT 20");
while ($row = sql_fetch_array ($res))
{
if (!empty ($identifier))
$res2 = sql_query ("SELECT article_id FROM ".$db_prefix."wordmatch WHERE word_id = '$row[word_id]' AND identifier = '$identifier'");
else
$res2 = sql_query ("SELECT article_id FROM ".$db_prefix."wordmatch WHERE word_id = '$row[word_id]'");
while ($row2 = sql_fetch_array ($res2)) $foo[$i][] = $row2['article_id'];
if (!empty ($row2)) $i++;
}
$keyword = strtok (' ');
}

$j = count ($foo);
if (@is_null ($foo[0])) $j = 0;

if ($j > 1)
{
if ($mode == 'and')
// if $mode = 'and', we need to find which article_id has all word_id, by finding similar (intersection) values. Only similar values return
$result = call_user_func_array ('array_intersect', $foo);
else
// if $mode = 'or', we simply takes all value, but remove double values (merge it, not remove)
$result = call_user_func_array ('array_merge', $foo);
}
elseif ($j == 1)
{
$result = $foo[0];
}
else
{
$result = array ();
}
return array_unique ($result);
}


// we can tag cloud using wordlist db
// $url = url to link (eg. index.php?cmd=open&amp;tag=)
// $num = number of top tags
// used by: index.php
function create_tag_cloud ($url = '', $num = 100)
{
global $db_prefix, $config;

$tmp = qcache_get ('cloud');
if (!$tmp)
{
$foo = array (); $total = $i = $max_count = $min_count = 0;
$max_size = 16;
$min_size = 8;
$tmp = '';

// get tags collection & max count
$res = sql_query ("SELECT word_text, count FROM ".$db_prefix."wordlist ORDER BY count DESC LIMIT $num");
while ($row = sql_fetch_array ($res)) $foo[$row['word_text']][] = $row;

sort ($foo);
foreach ($foo as $row)
{
$total = $total + $row[0]['count'];
if ($max_count < $row[0]['count']) $max_count = $row[0]['count'];
if ($min_count > $row[0]['count']) $min_count = $row[0]['count'];
$i++;
$foo[$i]['word'] = $row[0]['word_text'];
$foo[$i]['count'] = $row[0]['count'];
}

// create cloud
for ($j = 1; $j <= $i; $j++)
{
$s = ($foo[$j]['count'] / $max_count) * $max_size;
if ($s < $min_size) $s = $min_size;
$size = round ($s).'pt';
$word = $foo[$j]['word'];
$tmp .= "<span style=\"font-size:$size\"><a href=\"$url$word\">$word</a></span>\n";
}

// save to cache
qcache_update ('cloud', $tmp);
}
return $tmp;
}


/* ------- ( SEO URL ) ------- */

// create the URL for SEO
// $item_id = real item_id
// $label = title of article, eg "Welcome To Our Forum" -> will become "welcome-to-our-forum"
// used by: qadmin.php (and by other scripts that doesn't use qadmin)
function create_seo_url ($item_id, $label)
{
// create new item_id
return $item_id.'-'.preg_replace ("/[^a-zA-Z0-9]/", "-", substr (strtolower (html_unentities ($label)), 0, 255));
}

// get param for SEO URL; eg. page.php?pid=welcome --> page,pid,1-welcome.php (original item_id is 1) from table qe_page
// $item_id = the item_id from URL ('welcome')
function seo_param ($item_id)
{
global $config;

// seo url only for ADP 3
if ($config['enable_adp'] != 3) return $item_id;
$foo = explode ('-', $item_id);
if (!empty ($foo[0])) return $foo[0]; else return $item_id;
}


/* ------- ( qCACHE ) ------- */


// the easiest cache ever
// get cache from database, $id = identifier
function qcache_get ($id)
{
global $config, $db_prefix;
$id = $id.':'.$config['skin'];
$c = sql_qquery ("SELECT * FROM ".$db_prefix."cache WHERE cache_id='_cache:$id' LIMIT 1");
if (empty ($c['cache_id']))
{
sql_query ("INSERT INTO ".$db_prefix."cache SET cache_id='_cache:$id'");
$c[1] = '';
}
$lu = substr ($c[1], 0, 10);
$cc = substr ($c[1], 11);
if (time () - $lu > $config['cache']) return FALSE; else return $cc;
}


// update cache to db, $id = identifier; $content = cached content to save (must be clean from slashes)
function qcache_update ($id, $content)
{
global $config, $db_prefix;
$id = $id.':'.$config['skin'];
$cc = time().'|'.addslashes ($content);
sql_query ("UPDATE ".$db_prefix."cache SET cache_value='$cc' WHERE cache_id='_cache:$id' LIMIT 1");
}


// clear cache
function qcache_clear ()
{
global $config, $db_prefix;
sql_query ('TRUNCATE `'.$db_prefix.'cache');
}


/* ------- ( MISC ) ------- */


// (c) forceone at justduck.net [ php.net ]
// get varname & value from .ini formatted vars, eg:
// [ Section ]
// var = value
// var2 = value2
// used by: tpl.php for modules
function parse_ini_str ($Str, $ProcessSections = TRUE)
{
$Section = NULL;
$Data = array();
if ($Temp = strtok($Str,"\r\n"))
{
do
{
$Temp = trim ($Temp);
if (empty ($Temp)) $Temp = ';dummy';
switch ($Temp[0])
{
case ';':
case '#':
break;

case '[':
if (!$ProcessSections) { break; }

$Pos = strpos($Temp,'[');
$Section = substr($Temp,$Pos+1,strpos($Temp,']',$Pos)-1);
$Data[$Section] = array();
break;

default:
$Pos = strpos($Temp,'=');
if ($Pos === FALSE) { break; }
$Value = array();
$name = trim(substr($Temp,0,$Pos));
$val = trim(substr($Temp,$Pos+1),' "');
if ($ProcessSections)
{
if (empty($Section))
$Data[$name] = $val;
else
$Data[$Section][$name] = $val;
}
else
$Data[$name] = $val;

break;
}
}
while ($Temp = strtok("\r\n"));
}

return $Data;
}


// safely send string via url (without the risk of 'simple injection' or 'lost in translation').... IT'S NOT A SAFE METHOD!
function safe_send ($string)
{
if (empty ($string)) re
 
Display posts from previous:       
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> General/Other Stuff

View next topic
View previous topic
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum


Powered by phpBB © 2001-2007 phpBB Group
All times are GMT - 6 Hours