<?php
// local (script dependent) functions
// part of qEngine


// ----------- GENERAL ----------


// check if he's member
// return 1 = member; 0 = guest

function isMember ()
{
	global $config, $db_prefix, $db_name2, $db_name;

	$status = 0;
	$user_id = cookie_param ($db_prefix.'user_id');
	$user_passwd = cookie_param ($db_prefix.'password');

	if (!empty($user_id) && !empty($user_passwd))
	{
		// user id & passwd SET -> member
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."user WHERE
		                   user_id='$user_id' AND user_passwd = '$user_passwd' AND user_activation = '' LIMIT 1");
		$row = sql_fetch_array ($res);

		if (!empty($row['user_id']))
			$status = $row['user_level'];
		else
		{
			// forced to logout
			setcookie ($db_prefix."user_id", '', 0, "/");
			setcookie ($db_prefix."password", '', 0, "/");
			redir ($config['site_url']);
		}
   	}
   	elseif (!empty($user_id) && empty($user_passwd)) // registered guest
   	{
   		// username SET & password EMPTY -> temporary member
		$status = 0;
   	}
   	else
   	{	// create temporary username (session id)
		// guest temporary ID ... using '*' star, as star is not allowed for user ID
   		$status = 0;
		setcookie ($db_prefix."user_id", 'guest*'.random_str (32), time()+31536000, "/");
		setcookie ($db_prefix."password", '', 0, "/");
   	}
	return $status;
}


//-- get user detail
function get_user_info ($usrnm = '')
{
	global $current_user_id, $login, $db_prefix, $db_name2, $db_name;

	// if $usrnm not specified, get $usrnm from cookie ($username)
	if (empty ($usrnm)) $user = $current_user_id; else $user = $usrnm;

	if (empty ($usrnm) && !$login)
	{
		$user = create_blank_tbl ($db_prefix.'user');
	}
	else
	{
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."user WHERE user_id='$user' LIMIT 1");
		$user = sql_fetch_array ($res);
	}

	$user['ip'] = $_SERVER['REMOTE_ADDR'];

	return $user;
}


// create sql query (WHERE cat_id = '')
function create_sql_where ($cat_id, $cond = 'OR')
{
	global $sub_cat, $db_name2, $db_name;
	reset ($sub_cat[$cat_id]);
	$sql = '';
	while (list ($key, $val) = each($sub_cat[$cat_id])) $sql .= "cat_id = '$key' $cond ";
	$sql = substr ($sql, 0, (strlen ($cond) + 1) * -1);
	return $sql;
}


// get folder location (0, 1000, 2000, etc)
// $name = folder name, $item_id = item_id, $admin = 0: nothing, 1: add ../ on folder location
// featured or random product box
function make_promo ($item_id = 0, $mode = '')
{
	global $lang, $config, $tpl_section, $db_prefix, $dir_set_def, $db_name2, $db_name;

	// load section?
	if (empty ($tpl_section[$mode])) msg_die ('Load Section Not Defined!');

	// generate random item_id IF item_id not defined
	if (empty ($item_id))
	{
		$res = sql_query ("SELECT COUNT(*) AS total FROM  ".$db_name2.".".$db_prefix."link WHERE dir_id='4x4'");
		$row = sql_fetch_array ($res);
		$total = $row['total'];

		$rnd = mt_rand (1, $total);
	}
	else
	{
		$rnd = $item_id;
	}

	$res = sql_query ("SELECT * FROM  ".$db_name2.".".$db_prefix."link WHERE dir_id ='4x4' AND item_id >= $rnd LIMIT 1");
	$prod = sql_fetch_array ($res);

	// the rest
	$prod['directory'] = $dir_set_def[$prod['dir_id']];
	$prod['image'] = make_thumb ($prod['item_id'].'_1', 'feature');
	$prod['image_small'] = make_thumb ($prod['item_id'].'_1', 'small');
	$prod['short_note'] = strip_tags($prod['short_note']);
	
	if (empty($prod['short_note'])) $prod['short_note'] = $lang['l_no_description'];
	if ($config['enable_adp'] == 3) $prod['item_id'] = create_seo_url ($prod['item_id'], $prod['title']);
	if ($config['enable_adp'] == 3) $prod['dir_id'] = create_seo_url ($prod['dir_id'], $dir_set_def[$prod['dir_id']]);

	$prod['button'] = "<a href=\"detail.php?item_id=$prod[item_id]\"><img src=\"$config[skin]/images/detail.gif\" border=\"0\" alt=\"Second Hand Cars\" /></a>";

	// use template
	if ($mode == 'featured')
		$t = quick_tpl ($tpl_section['featured'], $prod);
	elseif ($mode == 'cat_featured')
		$t = quick_tpl ($tpl_section['cat_featured'], $prod);
	elseif ($mode == 'new')
		$t = quick_tpl ($tpl_section['new'], $prod);
	elseif ($mode == 'popular')
		$t = quick_tpl ($tpl_section['popular'], $prod);
	else
		$t = quick_tpl ($tpl_section['see_also'], $prod);

	return $t;
}


// create thumbnail
// mode = 'list' => medium size, non clickable
//        'detail' => medium size, clickable
//        'feature' => medium size, non clickable
function make_thumb ($image_id, $mode, $admin = 0, $index = 0)
{
	global $config, $db_name2, $db_name;
	$thumb_size = empty ($config['logo_thumb_size']) ? $config['thumb_size'] : $config['logo_thumb_size'];
	$quality = $config['thumb_quality'];

	$folder = get_folder ('link', $image_id, $admin);
	$tolder = get_folder ('link_thumb', $image_id, $admin);
	$img_src = "$folder/$image_id.jpg";
	$img_th  = empty ($config['logo_thumb']) ? $img_src : "$tolder/$image_id.jpg";	// if dirset's config == don't make thumb, then display original image!

	if (!file_exists ($img_src))   // if file not found
	{
		if ($mode == 'feature') $mode = 'list';
		if ($mode == 'newsletter')
			return '';
		elseif ($admin)
			return "<img border=\"0\" src=\"../skins/_admin/images/icon_$mode.gif\" title=\"No thumbnail1\" alt=\"No thumbnail1\" />";
		else

			return "<img border=\"0\" src=\"$config[skin]/images/icon_$mode.gif\" title=\"No thumbnail3\" alt=\"No thumbnail3\" />";
	}
	else
	{
		// if thumbnail image not exists -> create it
		if ($mode == 'small') { $img_th = "$tolder/small_$image_id.jpg"; $size = 120; } else $size = $thumb_size;
		if (!file_exists ($img_th)) image_optimizer ($img_src, $img_th, $quality, $size);
	}

	// get image size, and display it ...
	$img_tsize = GetImageSize ($img_th);
	$img_tx = $img_tsize[0];
	$img_ty = $img_tsize[1];

	// display it ...
	if (($mode == 'list') || ($mode == 'feature') || ($mode == 'small'))	// list.php; featured boxes (featured items, new items, etc) in welcome & list; small (50px)
	{
		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
		}
	elseif ($mode == 'newsletter')	// for newsletter (need absolute url)
	{
		$img_th = substr ($img_th, 5);
		$img_txt = "<img border=\"0\" src=\"$config[site_url]/$img_th\" alt=\"Second Hand Cars\" />";
	}
	elseif ($mode == 'detail')
	{
		$item_id = substr ($image_id, 0, (strpos ($image_id, '_')));

		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
		$img_txt = "<a href=\"#\" onclick=\"gallery()\" title=\"Click to open image gallery on this item.\">$img_txt</a>";
	}
	elseif ($mode == 'feature')
	{
		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
	}
	elseif ($mode == 'gallery')
	{
		$item_id = substr ($image_id, 0, (strpos ($image_id, '_')));
		$j = strpos ($image_id, '_');
		$x = substr ($image_id, $j+1);
		$img_txt = "<img border=\"0\" src=\"$img_th\" class=\"thumb_gallery\" alt=\"Second Hand Cars\" />";

		if ($index > 1)
			// show only image #1
			$img_txt = "<a href=\"$folder/{$item_id}_{$x}.jpg\" rel=\"#popup\" height=\"600\" width=\"800\"></a>";
		else
			$img_txt = "<a href=\"$folder/{$item_id}_{$x}.jpg\" rel=\"#popup\" height=\"600\" width=\"800\">$img_txt</a>";
	}

	return $img_txt;
}


// ----------- CATEGORY RELATED FUNCTIONS ----------


// get full category tree (instead of drilling down)
$full_category = ''; $full_category_lvl = 0;
function full_category_tree ($cat_id = 0)
{
	global $tmp_tbl, $full_category, $full_category_lvl, $config, $db_name2, $db_name;

	// create full tree; close_li = if an item exists (aka <li>) then it is needed to close by using </ul>
	// $full_cat_lvl = current category level, nothing useful, just to make code easier to read
	$close_li = false;
	
	// for top cat, give ID
	if (empty ($cat_id))
		$full_category = "<ul id=\"browse_category_tree\" class=\"category_browser\">\n";
	else
		$full_category .= str_repeat ('  ', $full_category_lvl)."<ul>\n";
	
	// scan from top, find any child for current $cat_id
	for ($i = 1; $i <= $tmp_tbl['parent'][0]; $i++)
	{
		$li_closed = false;

		// there it is the child, create output
		if ($tmp_tbl['parent'][$i] == $cat_id)
		{
			$full_category_lvl++;
			$close_li = true;
			$cn = $tmp_tbl['cat_name'][$i];
			$ci = $tmp_tbl['cat_id'][$i];
			$num = num_format ($tmp_tbl['cat_num'][$i]);
			if ($config['enable_adp'] == 3) $cu = create_seo_url ($ci, $cn); else $cu = $ci;
			$full_category .= str_repeat ('  ', $full_category_lvl)."<li><a href=\"list.php?cat_id=$cu\">$cn</a> <span class=\"category_browser_num\">($num)</span>\n";
			
			// repeat the function for child's child (and child's child's child, and so on)
			full_category_tree ($ci);
			$full_category .= str_repeat ('  ', $full_category_lvl)."</li>\n";
			$full_category_lvl--;
		}
	}
	
	// add </ul> to close <li>, otherwise (aka no item), remove the <ul> opener
	if ($close_li)
		$full_category .= str_repeat ('  ', $full_category_lvl)."</ul>\n";
	else
		$full_category = substr ($full_category, 0, -5);
}


// generate cat tree with info (parent, level, top_parent, parent, cat_id, cat_name)...
function get_cat_tree ($parent, $level, $top_parent)
{
	global $tmp_tbl, $tmp_tree, $j, $db_name2, $db_name;
	$ok = 0; $where = ''; $t = '';

	$cur_search_parent = $parent; // find parent

	for ($i = 1; $i <= $tmp_tbl['parent'][0]; $i++)
	{
		if ($tmp_tbl['parent'][$i] == $cur_search_parent)
		{
			$j++;
			if ($level == 1) $top_parent = $tmp_tbl['parent'][$i];

			$tmp_tree[0]['parent'] = $j;
			$tmp_tree[$j]['level'] = $level;
			$tmp_tree[$j]['top_parent'] = $top_parent;
			$tmp_tree[$j]['parent'] = $tmp_tbl['parent'][$i];
			$tmp_tree[$j]['cat_id'] = $tmp_tbl['cat_id'][$i];
			$tmp_tree[$j]['cat_name'] = $tmp_tbl['cat_name'][$i];
			$tmp_tree[$j]['cat_num'] = $tmp_tbl['cat_num'][$i];
			get_cat_tree ($tmp_tbl['cat_id'][$i], $level+1, $top_parent);
		}
	}
}


// get category tree for drill down mode (ie: all top category, all same level / current categories, and lower categories)
function get_cat_list ($cat_id)
{
	global $db_prefix, $config, $current_dir_set, $tmp_tree, $db_name2, $db_name;
	$t = ''; $p = 0; $parent_def = array ();
	if ($foo = qcache_get ($current_dir_set.':cat_drill_'.$cat_id)) return $foo;

	if (!empty ($cat_id))
	{
		// create full tree
		refetch_tmp_tbl ('', 'tree');
		get_cat_tree (0, 0, 0);
		
		// get parents
		$foo = sql_qquery ("SELECT cat_struct_id FROM ".$db_name2.".".$db_prefix."category WHERE cat_id='$cat_id' LIMIT 1");
		$par = explode (',', $foo[0]);
		array_pop ($par);	// remove current

		// display correspondent tree	
		for ($i = 1; $i <= $tmp_tree[0]['parent']; $i++)
		{
			if ($tmp_tree[$i]['cat_id'] == $cat_id)
			{
				$l  = $tmp_tree[$i]['level'];
				$tp = $tmp_tree[$i]['top_parent'];
				$cp = $tmp_tree[$i]['parent'];

				for ($j = 1; $j <= $tmp_tree[0]['parent']; $j++)
				{
					$tmp_cat_id = $tmp_tree[$j]['cat_id'];
					$tmp_cat_name = $tmp_tree[$j]['cat_name'];
					$tmp_parent = $tmp_tree[$j]['parent'];
					$tmp_top = $tmp_tree[$j]['top_parent'];
					$tmp_level = $tmp_tree[$j]['level'];
					$tmp_num = $tmp_tree[$j]['cat_num'];
					if ($config['enable_adp'] == 3) $cid = create_seo_url ($tmp_cat_id, $tmp_cat_name); else $cid = $tmp_cat_id;

					// 1 level under
					if ($tmp_parent == $cat_id)
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";

					// all same level
					if (($tmp_parent == $cp) && (!empty ($tmp_top)))
					{
						if ($tmp_cat_id == $cat_id)
							$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"cur_category\">"
								 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
						else
							$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
								 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
					}

					// all parents
					if (($tmp_top == $tp) && ($tmp_level < $l) && (!empty ($tmp_top)) && in_array ($tmp_parent, $par))
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";

					// all tops
					if ($tmp_level == 0)
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
				}
			}
		}
	}
	else	// if top category, simply take 'em all
	{
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."category WHERE dir_id='$current_dir_set' AND parent = '0' ORDER BY cat_structure");
		while ($row = sql_fetch_array ($res))
		{
			if ($config['enable_adp'] == 3) $curl = create_seo_url ($row['cat_id'], $row['cat_name']); else $curl = $row['cat_id'];
			$t .= str_repeat ('&nbsp;', $row['cat_level'])."<a href=\"list.php?cat_id=$curl\" class=\"category\">"
				.$row['cat_name']."</a> <span class=\"category_num\">(".num_format ($row['cat_num_links']).")</span><br />\n";
		}
	}

	qcache_update ($current_dir_set.':cat_drill_'.$cat_id, $t);
	return $t;
}


// create list of subcategories under category of $cat_id
// $mode =	list -> show categories & links to subcategory
//		form-> show categories to be used in <form> (select)
// $cat_id = 0 -> root
//           X -> in form_select -> auto select x
// $form_name = form name, leave empty for default 'cat_id'
// return: no RETURN! this function will return its value to global $txt['category_?'] or $txt['category_form_?']
function generate_category ($mode, $cat_id = 0, $form_name = 'cat_id')
{
	global $config, $db_prefix, $lang, $current_dir_set, $full_category, $cat_structure, $current_dir_set, $db_name2, $db_name;

	$i = $j = 0; $tmp_tree = array ();

	switch ($mode)
	{
		case 'list':
		 if ($config['browser_mode'] == 'tree')
		 {
			$full_category = qcache_get ('tree_'.$current_dir_set);
			if (!$full_category)
			{
				refetch_tmp_tbl ($current_dir_set, 'tree');
				full_category_tree ();
				qcache_update ('tree_'.$current_dir_set, $full_category);
			}
			return $full_category;
		 }
		 else
			return get_cat_list ($cat_id);
		break;

		// in add item 
		// using tmp_tbl, because we don't want to re-read the same table to create 6 form fields for multi-cat
		case 'form':
		 refetch_tmp_tbl ($current_dir_set, 'form');
		 $foo = $cat_structure;
		 asort ($foo);
		 return create_select_form ($form_name, $foo, $cat_id, '[ Pick a Category]');
		break;
	}
}


// get category name
// structure = return structure instead of name only
// link = with link
function cat_name ($cat_id, $structure = TRUE, $link = FALSE)
{
	global $db_prefix, $config, $db_name2, $db_name;
	if (empty ($cat_id)) return FALSE;
	
	// get cat name & info
	$row = sql_qquery ("SELECT cat_id, cat_name, cat_structure, cat_struct_id, cat_level FROM ".$db_name2.".".$db_prefix."category WHERE cat_id='$cat_id' LIMIT 1");
	
	// return cat name & info
	if ($config['enable_adp'] == 3) $url = create_seo_url ($row['cat_name'], $cat_id); else $url = $cat_id;
	if (!$structure && !$link) return $row['cat_name'];
	if (!$structure && $link) return "<a href=\"list.php?cat_id=$url\">$row[cat_name]</a>";
	if ($structure && !$link) return str_replace ("\r\n", " $config[cat_separator] ", $row['cat_structure']);
	if ($structure && $link)
	{
		$cid = explode (',', $row['cat_struct_id']);
		$nid = explode ("\r\n", $row['cat_structure']);
		$foo = array_pair ($cid, $nid);
		$t = array ();
		foreach ($foo as $key => $val) 
		{
			if ($config['enable_adp'] == 3) $ci = create_seo_url ($key, $val); else $ci = $key;
			$t[] = "<a href=\"list.php?cat_id=$ci\">$val</a>";
		}
		return implode (" $config[cat_separator] ", $t);
	}
}


// get list of categories on which the link is registered (see also admin/link.php)
// structure = with structure from top cat
// link = with link to relevant cat
// bullet = uses <ul><li>, otherwise uses comma
function cat_list ($item_id, $structure = TRUE, $link = FALSE, $bullet = TRUE)
{
	global $config, $db_prefix, $db_name2, $db_name;
	$row = sql_qquery ("SELECT * FROM  ".$db_name2.".".$db_prefix."link WHERE item_id='$item_id' AND dir_id='4x4' LIMIT 1");
	$cat = array ();
	for ($i = 1; $i <= $config['multiple_cat']; $i++)
	{
		$w = cat_name ($row['category_'.$i], $structure, $link);
		if (!empty ($w) && $bullet) $cat[] = '<li>'.$w.'</li>';
		if (!empty ($w) && !$bullet) $cat[] = $w;
	}
	if ($bullet)
		return '<ul class="list_1">'.implode ("\n", $cat).'</ul>';
	else
		return implode (", ", $cat);
}


// fetching category table to a temporary table to optimize _SOME_ processes
// you should avoid using this function, as this is memory hungry, and may be quite slow on a large category site
// BUT, yes, it does speed up some processes, like building a complete tree, or anything else
// $set = dir_set id
// $mode = determine which fields to be fetched
function refetch_tmp_tbl ($set = '', $mode = '')
{
	if (empty ($mode)) die ('Invalid mode for refetch_tmp_tbl!');
	global $db_prefix, $config, $tmp_tbl, $cat_structure, $cat_struct_id, $last_fetch_tbl, $current_dir_set, $db_name2, $db_name;
	
	// identifier, so, fetching only done once
	$fid = $current_dir_set ? $current_dir_set : '*';
	$fid = "$fid:$mode";
	if ($last_fetch_tbl == $fid) return TRUE; else $last_fetch_tbl = $fid;

	// init
	if (empty ($current_dir_set)) $w = ''; else $w = "WHERE dir_id='$current_dir_set'";
	$i = 0; $tmp_tbl = $cat_structure_top = $cat_structure = array ();
	
	// mode fields
	switch ($mode)
	{
		case 'form':
			$res = sql_query ("SELECT parent, cat_id, cat_name, cat_struct_id, cat_structure, cat_num_links FROM ".$db_name2.".".$db_prefix."category $w");
			while ($row = sql_fetch_array ($res)) $cat_structure[$row['cat_id']] = str_replace ("\r\n", " $config[cat_separator] ", $row['cat_structure']);
		break;

		case 'id':
			$res = sql_query ("SELECT parent, cat_id FROM ".$db_name2.".".$db_prefix."category $w");
			while ($row = sql_fetch_array ($res))
			{
				$i++;
				$tmp_tbl['parent'][$i] = $row['parent'];
				$tmp_tbl['cat_id'][$i] = $row['cat_id'];
			}
			$tmp_tbl['parent'][0] = $i;
		break;

		default:
			$res = sql_query ("SELECT parent, cat_id, cat_name, cat_struct_id, cat_structure, cat_num_links FROM ".$db_name2.".".$db_prefix."category $w ORDER BY cat_structure");
			while ($row = sql_fetch_array ($res))
			{
				$i++;
				$tmp_tbl['parent'][$i] = $row['parent'];
				$tmp_tbl['cat_id'][$i] = $row['cat_id'];
				$tmp_tbl['cat_name'][$i] = $row['cat_name'];
				$tmp_tbl['cat_num'][$i] = $row['cat_num_links'];
			}
			$tmp_tbl['parent'][0] = $i;
		break;
	}
}


// ----------- CUSTOM FIELDS ----------


// fetch cf to memory
// $search = TRUE: only searchable fields (for search.php)
function fetch_custom_field ($set, $search = FALSE)
{
	global $db_prefix, $tmp_spec, $tmp_priv, $db_name2, $db_name;

	// FETCH ALL CUSTOM FIELD DEF
	$tmp_spec = array (); $tmp_priv = array ();
	$sql = "dir_id='$set' AND "; 
	
	if ($search)
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_define WHERE $sql field_search='1' ORDER BY field_order");
	else
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_define WHERE $sql 1=1 ORDER BY field_order, field_title");
	while ($row = sql_fetch_array ($res))
	{
		$tmp_spec[$row['field_id']]['title'] = $row['field_title'];
		$tmp_spec[$row['field_id']]['help'] = $row['field_help'];
		$tmp_spec[$row['field_id']]['type'] = $row['field_type'];
		$tmp_spec[$row['field_id']]['option'] = $row['field_option'];

		if ($row['field_type'] == 'private') $tmp_priv[$row['field_id']] = $row['field_title'];
	}
}


// get custom field values from DB
// for: list.php & detail.php
function get_custom_field ($item_id)
{
	global $db_prefix, $tmp_spec, $tpl_section, $event_format, $lang, $recur_def, $db_name2, $db_name;
	$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_value WHERE item_id='$item_id' LIMIT 1");
<?php
// local (script dependent) functions
// part of qEngine


// ----------- GENERAL ----------


// check if he's member
// return 1 = member; 0 = guest

function isMember ()
{
	global $config, $db_prefix, $db_name2, $db_name;

	$status = 0;
	$user_id = cookie_param ($db_prefix.'user_id');
	$user_passwd = cookie_param ($db_prefix.'password');

	if (!empty($user_id) && !empty($user_passwd))
	{
		// user id & passwd SET -> member
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."user WHERE
		                   user_id='$user_id' AND user_passwd = '$user_passwd' AND user_activation = '' LIMIT 1");
		$row = sql_fetch_array ($res);

		if (!empty($row['user_id']))
			$status = $row['user_level'];
		else
		{
			// forced to logout
			setcookie ($db_prefix."user_id", '', 0, "/");
			setcookie ($db_prefix."password", '', 0, "/");
			redir ($config['site_url']);
		}
   	}
   	elseif (!empty($user_id) && empty($user_passwd)) // registered guest
   	{
   		// username SET & password EMPTY -> temporary member
		$status = 0;
   	}
   	else
   	{	// create temporary username (session id)
		// guest temporary ID ... using '*' star, as star is not allowed for user ID
   		$status = 0;
		setcookie ($db_prefix."user_id", 'guest*'.random_str (32), time()+31536000, "/");
		setcookie ($db_prefix."password", '', 0, "/");
   	}
	return $status;
}


//-- get user detail
function get_user_info ($usrnm = '')
{
	global $current_user_id, $login, $db_prefix, $db_name2, $db_name;

	// if $usrnm not specified, get $usrnm from cookie ($username)
	if (empty ($usrnm)) $user = $current_user_id; else $user = $usrnm;

	if (empty ($usrnm) && !$login)
	{
		$user = create_blank_tbl ($db_prefix.'user');
	}
	else
	{
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."user WHERE user_id='$user' LIMIT 1");
		$user = sql_fetch_array ($res);
	}

	$user['ip'] = $_SERVER['REMOTE_ADDR'];

	return $user;
}


// create sql query (WHERE cat_id = '')
function create_sql_where ($cat_id, $cond = 'OR')
{
	global $sub_cat, $db_name2, $db_name;
	reset ($sub_cat[$cat_id]);
	$sql = '';
	while (list ($key, $val) = each($sub_cat[$cat_id])) $sql .= "cat_id = '$key' $cond ";
	$sql = substr ($sql, 0, (strlen ($cond) + 1) * -1);
	return $sql;
}


// get folder location (0, 1000, 2000, etc)
// $name = folder name, $item_id = item_id, $admin = 0: nothing, 1: add ../ on folder location
// featured or random product box
function make_promo ($item_id = 0, $mode = '')
{
	global $lang, $config, $tpl_section, $db_prefix, $dir_set_def, $db_name2, $db_name;

	// load section?
	if (empty ($tpl_section[$mode])) msg_die ('Load Section Not Defined!');

	// generate random item_id IF item_id not defined
	if (empty ($item_id))
	{
		$res = sql_query ("SELECT COUNT(*) AS total FROM  ".$db_name2.".".$db_prefix."link WHERE dir_id='4x4'");
		$row = sql_fetch_array ($res);
		$total = $row['total'];

		$rnd = mt_rand (1, $total);
	}
	else
	{
		$rnd = $item_id;
	}

	$res = sql_query ("SELECT * FROM  ".$db_name2.".".$db_prefix."link WHERE dir_id ='4x4' AND item_id >= $rnd LIMIT 1");
	$prod = sql_fetch_array ($res);

	// the rest
	$prod['directory'] = $dir_set_def[$prod['dir_id']];
	$prod['image'] = make_thumb ($prod['item_id'].'_1', 'feature');
	$prod['image_small'] = make_thumb ($prod['item_id'].'_1', 'small');
	$prod['short_note'] = strip_tags($prod['short_note']);
	
	if (empty($prod['short_note'])) $prod['short_note'] = $lang['l_no_description'];
	if ($config['enable_adp'] == 3) $prod['item_id'] = create_seo_url ($prod['item_id'], $prod['title']);
	if ($config['enable_adp'] == 3) $prod['dir_id'] = create_seo_url ($prod['dir_id'], $dir_set_def[$prod['dir_id']]);

	$prod['button'] = "<a href=\"detail.php?item_id=$prod[item_id]\"><img src=\"$config[skin]/images/detail.gif\" border=\"0\" alt=\"Second Hand Cars\" /></a>";

	// use template
	if ($mode == 'featured')
		$t = quick_tpl ($tpl_section['featured'], $prod);
	elseif ($mode == 'cat_featured')
		$t = quick_tpl ($tpl_section['cat_featured'], $prod);
	elseif ($mode == 'new')
		$t = quick_tpl ($tpl_section['new'], $prod);
	elseif ($mode == 'popular')
		$t = quick_tpl ($tpl_section['popular'], $prod);
	else
		$t = quick_tpl ($tpl_section['see_also'], $prod);

	return $t;
}


// create thumbnail
// mode = 'list' => medium size, non clickable
//        'detail' => medium size, clickable
//        'feature' => medium size, non clickable
function make_thumb ($image_id, $mode, $admin = 0, $index = 0)
{
	global $config, $db_name2, $db_name;
	$thumb_size = empty ($config['logo_thumb_size']) ? $config['thumb_size'] : $config['logo_thumb_size'];
	$quality = $config['thumb_quality'];

	$folder = get_folder ('link', $image_id, $admin);
	$tolder = get_folder ('link_thumb', $image_id, $admin);
	$img_src = "$folder/$image_id.jpg";
	$img_th  = empty ($config['logo_thumb']) ? $img_src : "$tolder/$image_id.jpg";	// if dirset's config == don't make thumb, then display original image!

	if (!file_exists ($img_src))   // if file not found
	{
		if ($mode == 'feature') $mode = 'list';
		if ($mode == 'newsletter')
			return '';
		elseif ($admin)
			return "<img border=\"0\" src=\"../skins/_admin/images/icon_$mode.gif\" title=\"No thumbnail1\" alt=\"No thumbnail1\" />";
		else

			return "<img border=\"0\" src=\"$config[skin]/images/icon_$mode.gif\" title=\"No thumbnail3\" alt=\"No thumbnail3\" />";
	}
	else
	{
		// if thumbnail image not exists -> create it
		if ($mode == 'small') { $img_th = "$tolder/small_$image_id.jpg"; $size = 120; } else $size = $thumb_size;
		if (!file_exists ($img_th)) image_optimizer ($img_src, $img_th, $quality, $size);
	}

	// get image size, and display it ...
	$img_tsize = GetImageSize ($img_th);
	$img_tx = $img_tsize[0];
	$img_ty = $img_tsize[1];

	// display it ...
	if (($mode == 'list') || ($mode == 'feature') || ($mode == 'small'))	// list.php; featured boxes (featured items, new items, etc) in welcome & list; small (50px)
	{
		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
		}
	elseif ($mode == 'newsletter')	// for newsletter (need absolute url)
	{
		$img_th = substr ($img_th, 5);
		$img_txt = "<img border=\"0\" src=\"$config[site_url]/$img_th\" alt=\"Second Hand Cars\" />";
	}
	elseif ($mode == 'detail')
	{
		$item_id = substr ($image_id, 0, (strpos ($image_id, '_')));

		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
		$img_txt = "<a href=\"#\" onclick=\"gallery()\" title=\"Click to open image gallery on this item.\">$img_txt</a>";
	}
	elseif ($mode == 'feature')
	{
		$img_txt = "<img border=\"0\" src=\"$img_th\" alt=\"Second Hand Cars\" />";
	}
	elseif ($mode == 'gallery')
	{
		$item_id = substr ($image_id, 0, (strpos ($image_id, '_')));
		$j = strpos ($image_id, '_');
		$x = substr ($image_id, $j+1);
		$img_txt = "<img border=\"0\" src=\"$img_th\" class=\"thumb_gallery\" alt=\"Second Hand Cars\" />";

		if ($index > 1)
			// show only image #1
			$img_txt = "<a href=\"$folder/{$item_id}_{$x}.jpg\" rel=\"#popup\" height=\"600\" width=\"800\"></a>";
		else
			$img_txt = "<a href=\"$folder/{$item_id}_{$x}.jpg\" rel=\"#popup\" height=\"600\" width=\"800\">$img_txt</a>";
	}

	return $img_txt;
}


// ----------- CATEGORY RELATED FUNCTIONS ----------


// get full category tree (instead of drilling down)
$full_category = ''; $full_category_lvl = 0;
function full_category_tree ($cat_id = 0)
{
	global $tmp_tbl, $full_category, $full_category_lvl, $config, $db_name2, $db_name;

	// create full tree; close_li = if an item exists (aka <li>) then it is needed to close by using </ul>
	// $full_cat_lvl = current category level, nothing useful, just to make code easier to read
	$close_li = false;
	
	// for top cat, give ID
	if (empty ($cat_id))
		$full_category = "<ul id=\"browse_category_tree\" class=\"category_browser\">\n";
	else
		$full_category .= str_repeat ('  ', $full_category_lvl)."<ul>\n";
	
	// scan from top, find any child for current $cat_id
	for ($i = 1; $i <= $tmp_tbl['parent'][0]; $i++)
	{
		$li_closed = false;

		// there it is the child, create output
		if ($tmp_tbl['parent'][$i] == $cat_id)
		{
			$full_category_lvl++;
			$close_li = true;
			$cn = $tmp_tbl['cat_name'][$i];
			$ci = $tmp_tbl['cat_id'][$i];
			$num = num_format ($tmp_tbl['cat_num'][$i]);
			if ($config['enable_adp'] == 3) $cu = create_seo_url ($ci, $cn); else $cu = $ci;
			$full_category .= str_repeat ('  ', $full_category_lvl)."<li><a href=\"list.php?cat_id=$cu\">$cn</a> <span class=\"category_browser_num\">($num)</span>\n";
			
			// repeat the function for child's child (and child's child's child, and so on)
			full_category_tree ($ci);
			$full_category .= str_repeat ('  ', $full_category_lvl)."</li>\n";
			$full_category_lvl--;
		}
	}
	
	// add </ul> to close <li>, otherwise (aka no item), remove the <ul> opener
	if ($close_li)
		$full_category .= str_repeat ('  ', $full_category_lvl)."</ul>\n";
	else
		$full_category = substr ($full_category, 0, -5);
}


// generate cat tree with info (parent, level, top_parent, parent, cat_id, cat_name)...
function get_cat_tree ($parent, $level, $top_parent)
{
	global $tmp_tbl, $tmp_tree, $j, $db_name2, $db_name;
	$ok = 0; $where = ''; $t = '';

	$cur_search_parent = $parent; // find parent

	for ($i = 1; $i <= $tmp_tbl['parent'][0]; $i++)
	{
		if ($tmp_tbl['parent'][$i] == $cur_search_parent)
		{
			$j++;
			if ($level == 1) $top_parent = $tmp_tbl['parent'][$i];

			$tmp_tree[0]['parent'] = $j;
			$tmp_tree[$j]['level'] = $level;
			$tmp_tree[$j]['top_parent'] = $top_parent;
			$tmp_tree[$j]['parent'] = $tmp_tbl['parent'][$i];
			$tmp_tree[$j]['cat_id'] = $tmp_tbl['cat_id'][$i];
			$tmp_tree[$j]['cat_name'] = $tmp_tbl['cat_name'][$i];
			$tmp_tree[$j]['cat_num'] = $tmp_tbl['cat_num'][$i];
			get_cat_tree ($tmp_tbl['cat_id'][$i], $level+1, $top_parent);
		}
	}
}


// get category tree for drill down mode (ie: all top category, all same level / current categories, and lower categories)
function get_cat_list ($cat_id)
{
	global $db_prefix, $config, $current_dir_set, $tmp_tree, $db_name2, $db_name;
	$t = ''; $p = 0; $parent_def = array ();
	if ($foo = qcache_get ($current_dir_set.':cat_drill_'.$cat_id)) return $foo;

	if (!empty ($cat_id))
	{
		// create full tree
		refetch_tmp_tbl ('', 'tree');
		get_cat_tree (0, 0, 0);
		
		// get parents
		$foo = sql_qquery ("SELECT cat_struct_id FROM ".$db_name2.".".$db_prefix."category WHERE cat_id='$cat_id' LIMIT 1");
		$par = explode (',', $foo[0]);
		array_pop ($par);	// remove current

		// display correspondent tree	
		for ($i = 1; $i <= $tmp_tree[0]['parent']; $i++)
		{
			if ($tmp_tree[$i]['cat_id'] == $cat_id)
			{
				$l  = $tmp_tree[$i]['level'];
				$tp = $tmp_tree[$i]['top_parent'];
				$cp = $tmp_tree[$i]['parent'];

				for ($j = 1; $j <= $tmp_tree[0]['parent']; $j++)
				{
					$tmp_cat_id = $tmp_tree[$j]['cat_id'];
					$tmp_cat_name = $tmp_tree[$j]['cat_name'];
					$tmp_parent = $tmp_tree[$j]['parent'];
					$tmp_top = $tmp_tree[$j]['top_parent'];
					$tmp_level = $tmp_tree[$j]['level'];
					$tmp_num = $tmp_tree[$j]['cat_num'];
					if ($config['enable_adp'] == 3) $cid = create_seo_url ($tmp_cat_id, $tmp_cat_name); else $cid = $tmp_cat_id;

					// 1 level under
					if ($tmp_parent == $cat_id)
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";

					// all same level
					if (($tmp_parent == $cp) && (!empty ($tmp_top)))
					{
						if ($tmp_cat_id == $cat_id)
							$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"cur_category\">"
								 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
						else
							$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
								 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
					}

					// all parents
					if (($tmp_top == $tp) && ($tmp_level < $l) && (!empty ($tmp_top)) && in_array ($tmp_parent, $par))
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"sub_category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";

					// all tops
					if ($tmp_level == 0)
					$t .= str_repeat ('&nbsp;', $tmp_level)."<a href=\"list.php?cat_id=$cid\" class=\"category\">"
						 .$tmp_cat_name."</a> <span class=\"category_num\">(".num_format ($tmp_num).")</span><br />";
				}
			}
		}
	}
	else	// if top category, simply take 'em all
	{
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."category WHERE dir_id='$current_dir_set' AND parent = '0' ORDER BY cat_structure");
		while ($row = sql_fetch_array ($res))
		{
			if ($config['enable_adp'] == 3) $curl = create_seo_url ($row['cat_id'], $row['cat_name']); else $curl = $row['cat_id'];
			$t .= str_repeat ('&nbsp;', $row['cat_level'])."<a href=\"list.php?cat_id=$curl\" class=\"category\">"
				.$row['cat_name']."</a> <span class=\"category_num\">(".num_format ($row['cat_num_links']).")</span><br />\n";
		}
	}

	qcache_update ($current_dir_set.':cat_drill_'.$cat_id, $t);
	return $t;
}


// create list of subcategories under category of $cat_id
// $mode =	list -> show categories & links to subcategory
//		form-> show categories to be used in <form> (select)
// $cat_id = 0 -> root
//           X -> in form_select -> auto select x
// $form_name = form name, leave empty for default 'cat_id'
// return: no RETURN! this function will return its value to global $txt['category_?'] or $txt['category_form_?']
function generate_category ($mode, $cat_id = 0, $form_name = 'cat_id')
{
	global $config, $db_prefix, $lang, $current_dir_set, $full_category, $cat_structure, $current_dir_set, $db_name2, $db_name;

	$i = $j = 0; $tmp_tree = array ();

	switch ($mode)
	{
		case 'list':
		 if ($config['browser_mode'] == 'tree')
		 {
			$full_category = qcache_get ('tree_'.$current_dir_set);
			if (!$full_category)
			{
				refetch_tmp_tbl ($current_dir_set, 'tree');
				full_category_tree ();
				qcache_update ('tree_'.$current_dir_set, $full_category);
			}
			return $full_category;
		 }
		 else
			return get_cat_list ($cat_id);
		break;

		// in add item 
		// using tmp_tbl, because we don't want to re-read the same table to create 6 form fields for multi-cat
		case 'form':
		 refetch_tmp_tbl ($current_dir_set, 'form');
		 $foo = $cat_structure;
		 asort ($foo);
		 return create_select_form ($form_name, $foo, $cat_id, '[ Pick a Category]');
		break;
	}
}


// get category name
// structure = return structure instead of name only
// link = with link
function cat_name ($cat_id, $structure = TRUE, $link = FALSE)
{
	global $db_prefix, $config, $db_name2, $db_name;
	if (empty ($cat_id)) return FALSE;
	
	// get cat name & info
	$row = sql_qquery ("SELECT cat_id, cat_name, cat_structure, cat_struct_id, cat_level FROM ".$db_name2.".".$db_prefix."category WHERE cat_id='$cat_id' LIMIT 1");
	
	// return cat name & info
	if ($config['enable_adp'] == 3) $url = create_seo_url ($row['cat_name'], $cat_id); else $url = $cat_id;
	if (!$structure && !$link) return $row['cat_name'];
	if (!$structure && $link) return "<a href=\"list.php?cat_id=$url\">$row[cat_name]</a>";
	if ($structure && !$link) return str_replace ("\r\n", " $config[cat_separator] ", $row['cat_structure']);
	if ($structure && $link)
	{
		$cid = explode (',', $row['cat_struct_id']);
		$nid = explode ("\r\n", $row['cat_structure']);
		$foo = array_pair ($cid, $nid);
		$t = array ();
		foreach ($foo as $key => $val) 
		{
			if ($config['enable_adp'] == 3) $ci = create_seo_url ($key, $val); else $ci = $key;
			$t[] = "<a href=\"list.php?cat_id=$ci\">$val</a>";
		}
		return implode (" $config[cat_separator] ", $t);
	}
}


// get list of categories on which the link is registered (see also admin/link.php)
// structure = with structure from top cat
// link = with link to relevant cat
// bullet = uses <ul><li>, otherwise uses comma
function cat_list ($item_id, $structure = TRUE, $link = FALSE, $bullet = TRUE)
{
	global $config, $db_prefix, $db_name2, $db_name;
	$row = sql_qquery ("SELECT * FROM  ".$db_name2.".".$db_prefix."link WHERE item_id='$item_id' AND dir_id='4x4' LIMIT 1");
	$cat = array ();
	for ($i = 1; $i <= $config['multiple_cat']; $i++)
	{
		$w = cat_name ($row['category_'.$i], $structure, $link);
		if (!empty ($w) && $bullet) $cat[] = '<li>'.$w.'</li>';
		if (!empty ($w) && !$bullet) $cat[] = $w;
	}
	if ($bullet)
		return '<ul class="list_1">'.implode ("\n", $cat).'</ul>';
	else
		return implode (", ", $cat);
}


// fetching category table to a temporary table to optimize _SOME_ processes
// you should avoid using this function, as this is memory hungry, and may be quite slow on a large category site
// BUT, yes, it does speed up some processes, like building a complete tree, or anything else
// $set = dir_set id
// $mode = determine which fields to be fetched
function refetch_tmp_tbl ($set = '', $mode = '')
{
	if (empty ($mode)) die ('Invalid mode for refetch_tmp_tbl!');
	global $db_prefix, $config, $tmp_tbl, $cat_structure, $cat_struct_id, $last_fetch_tbl, $current_dir_set, $db_name2, $db_name;
	
	// identifier, so, fetching only done once
	$fid = $current_dir_set ? $current_dir_set : '*';
	$fid = "$fid:$mode";
	if ($last_fetch_tbl == $fid) return TRUE; else $last_fetch_tbl = $fid;

	// init
	if (empty ($current_dir_set)) $w = ''; else $w = "WHERE dir_id='$current_dir_set'";
	$i = 0; $tmp_tbl = $cat_structure_top = $cat_structure = array ();
	
	// mode fields
	switch ($mode)
	{
		case 'form':
			$res = sql_query ("SELECT parent, cat_id, cat_name, cat_struct_id, cat_structure, cat_num_links FROM ".$db_name2.".".$db_prefix."category $w");
			while ($row = sql_fetch_array ($res)) $cat_structure[$row['cat_id']] = str_replace ("\r\n", " $config[cat_separator] ", $row['cat_structure']);
		break;

		case 'id':
			$res = sql_query ("SELECT parent, cat_id FROM ".$db_name2.".".$db_prefix."category $w");
			while ($row = sql_fetch_array ($res))
			{
				$i++;
				$tmp_tbl['parent'][$i] = $row['parent'];
				$tmp_tbl['cat_id'][$i] = $row['cat_id'];
			}
			$tmp_tbl['parent'][0] = $i;
		break;

		default:
			$res = sql_query ("SELECT parent, cat_id, cat_name, cat_struct_id, cat_structure, cat_num_links FROM ".$db_name2.".".$db_prefix."category $w ORDER BY cat_structure");
			while ($row = sql_fetch_array ($res))
			{
				$i++;
				$tmp_tbl['parent'][$i] = $row['parent'];
				$tmp_tbl['cat_id'][$i] = $row['cat_id'];
				$tmp_tbl['cat_name'][$i] = $row['cat_name'];
				$tmp_tbl['cat_num'][$i] = $row['cat_num_links'];
			}
			$tmp_tbl['parent'][0] = $i;
		break;
	}
}


// ----------- CUSTOM FIELDS ----------


// fetch cf to memory
// $search = TRUE: only searchable fields (for search.php)
function fetch_custom_field ($set, $search = FALSE)
{
	global $db_prefix, $tmp_spec, $tmp_priv, $db_name2, $db_name;

	// FETCH ALL CUSTOM FIELD DEF
	$tmp_spec = array (); $tmp_priv = array ();
	$sql = "dir_id='$set' AND "; 
	
	if ($search)
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_define WHERE $sql field_search='1' ORDER BY field_order");
	else
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_define WHERE $sql 1=1 ORDER BY field_order, field_title");
	while ($row = sql_fetch_array ($res))
	{
		$tmp_spec[$row['field_id']]['title'] = $row['field_title'];
		$tmp_spec[$row['field_id']]['help'] = $row['field_help'];
		$tmp_spec[$row['field_id']]['type'] = $row['field_type'];
		$tmp_spec[$row['field_id']]['option'] = $row['field_option'];

		if ($row['field_type'] == 'private') $tmp_priv[$row['field_id']] = $row['field_title'];
	}
}


// get custom field values from DB
// for: list.php & detail.php
function get_custom_field ($item_id)
{
	global $db_prefix, $tmp_spec, $tpl_section, $event_format, $lang, $recur_def, $db_name2, $db_name;
	$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."cf_value WHERE item_id='$item_id' LIMIT 1");
	$row = sql_fetch_array ($res);
	$custom = array ();
	$design = '';

	// 1. start creating output based on cf type
	foreach ($tmp_spec as $key => $info)
	{
		$foo = $tmp_spec[$key]['type'];
		$val = $row[$key];
		$custom[$key] = $val;
		$custom[$key.'_raw'] = $val;	// you can use this raw field to create your own output (eg. $custom['logo_raw'] = 'somefile.jpg')

		switch ($foo)
		{
			case 'wysiwyg':
				if (!empty ($val)) $custom[$key] = bbcode ($val);
			break;

			case 'file':
				if (!empty ($val)) $custom[$key] = "<a href=\"$val\">$val</a>";				
			break;

			case 'img':
				if (!empty ($val))
				{
					$opt = explode ('|', $tmp_spec[$key]['option']);
					$thumb = dirname ($val).'/thumb_'.basename ($val);
					if ($opt[2])
						$custom[$key] = "<a href=\"$val\" rel=\"#popup\" height=\"600\" width=\"800\" title=\"Second Hand Cars\"><img src=\"$thumb\" alt=\"Second Hand Cars\" /></a>";
					else
						$custom[$key] = "<img src=\"$val\" alt=\"SecondHandCars\" title=\"SecondHandCars\" />";
				}
			break;

			case 'rating':
				if (!empty ($val)) $custom[$key] = rating_img ($val);
			break;

			case 'multi':
				$fii = explode ("\r\n", $val);
				$custom[$key] = implode (', ', $fii);
			break;
			
			case 'date':
				if (($val == '0000-00-00') || empty ($val)) $custom[$key] = ''; else $custom[$key] = convert_date ($val, 1);
			break;
			
			case 'time':
				$custom[$key] = date ('g:ia', mktime (substr ($val, 0, 2), substr ($val,3,2)));
			break;
			
			case 'event':
				if (!empty ($val) && ($val != '0000-00-00'))
				{
					$r = $row[$key.'_recur'];
					$f = $row[$key.'_end'];
					$ds = convert_date ($val, 'long');
					$df = convert_date ($f, 'long');
					$ux = convert_date ($val, 'int');
					$y1 = substr ($val, 0, 4);
					$y2 = substr ($f, 0, 4);
					$dayname = date ('l', $ux);
					$datenumber = date ('jS', $ux);
					$month = date ('F', $ux);			

					if ($r == 'x') $custom[$key] = sprintf ($event_format['detail_once'], $ds);
					elseif ($r == 'd') $custom[$key] = sprintf ($event_format['detail_daily'], $ds, $df);
					elseif ($r == 'w') $custom[$key] = sprintf ($event_format['detail_weekly'], $lang['datetime'][$dayname], $ds, $df);
					elseif ($r == 'm') $custom[$key] = sprintf ($event_format['detail_monthly'], $datenumber, $ds, $df);
					else $custom[$key] = sprintf ($event_format['detail_yearly'], $month, $datenumber, $y1, $y2);
				}
				else
					$custom[$key] = '';
			break;
			
			case '_recur':
			case '_event_end':
				$custom[$key] = '';
			break;
		}

		// 2. create design (auto)
		$row['title'] = $tmp_spec[$key]['title'];
		$row['value'] = $custom[$key];
		if (!empty ($row['value'])) $design .= quick_tpl ($tpl_section['detail_format'], $row);
	}

	$custom['auto_design'] = $design;
	return $custom;
}


function remove_user_file ($opt_file)
{
	$foo = explode (',', $opt_file);
	foreach ($foo as $val)
	{
		$fn = safe_receive ($val);
		@unlink ($fn);
	}
}


// get folder location (0, 1000, 2000, etc)
// $name = folder name, $item_id = item_id, $admin = 0: nothing, 1: add ../ on folder location
function get_folder ($name, $item_id, $admin = 0)
{
	$fold = floor ($item_id / 1000) * 1000;
	if ($admin)
		$folder = "./../public/$name/$fold";
	else
		$folder = "./public/$name/$fold";
	if (!@file_exists ($folder)) mkdir ($folder);
	@chmod ($folder, 0777);
	return $folder;
}


// ----------- MISC ----------


// create country list
function get_country_list ($idx = '', $by_name = '', $selectable = 0)
{
	global $db_prefix, $db_name2, $db_name;

	$tmp = array ();
	if ($selectable)
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."country WHERE selectable = 1 ORDER BY country_name ASC");
	else
		$res = sql_query ("SELECT * FROM ".$db_name2.".".$db_prefix."country ORDER BY country_name ASC");

	while ($row = sql_fetch_array ($res))
	{
		if ($by_name)
			$tmp[$row['country_name']] = $row['country_name'];

		else
			$tmp[$row['idx']] = $row['country_name'];
	}

	if ($by_name)
		return create_select_form ('country', $tmp, $by_name, '');
	else
		return create_select_form ('country_idx', $tmp, $idx, '');
}
?>