i am problem with line 3462 ?! :@

<?php
function trigger_db_error($obj)
	{
		global $CFG;

		$error_arr = debug_backtrace();

		$subject = 'Report bug - Sql error - {site_url}';
		$content = '<u><b>Url :</b></u>
		{current_url}

		<u><b>Error File :</b></u>
		{file}

		<u><b>Error Line No :</b></u>
		{line}

		<u><b>Error Description:</b></u>
		{error}';

		$frmobj = new FormHandler();
		if(isset($CFG['site']['current_url']))
			$frmobj->setEmailTemplateValue('current_url', $CFG['site']['current_url']);
		$frmobj->setEmailTemplateValue('file', $error_arr[0]['file']);
		$frmobj->setEmailTemplateValue('line', $error_arr[0]['line']);

		$frmobj->setEmailTemplateValue('error', $error_arr[0]['args'][0]->debug_output);
		$frmobj->buildEmailTemplate($subject, $content, false, true);

		sendBugEmail($frmobj);
		trigger_error('Error at '.$error_arr[0]['file'].' on line '.$error_arr[0]['line']."<br>".$obj->ErrorNo().' '.$obj->ErrorMsg(), E_USER_ERROR);
	}

function sendBugEmail($frmobj)
	{
		global $CFG;
		$EasySwift = new EasySwift($frmobj->getSwiftConnection());
		$EasySwift->flush();
		$EasySwift->addPart($frmobj->getEmailContent(), "text/html");
		$from_email = $CFG['site']['noreply_email'];
		$EasySwift->send($CFG['site']['dev_bug_email'], $from_email, $frmobj->getEmailSubject());
	}

function getCurrentMemberUrl()
	{
		global $CFG;
		return str_replace($CFG['site']['url'],$CFG['site']['url'].'members/',$CFG['site']['current_url']);
	}

function postForm($url, $post_value)
	{
		$ch = curl_init();

		// set the target url
		curl_setopt($ch, CURLOPT_URL,$url);

		// howmany parameter to post
		curl_setopt($ch, CURLOPT_POST, 1);

		// the parameter 'username' with its value 'johndoe'
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_value);

		$result= curl_exec ($ch);
		curl_close ($ch);
	}

/**
 * Check the site is under maintenance
 *
 * @access	public
 * @return	boolean
 */
function chkIsSiteUnderMaintenance()
	{
		global $CFG;

		if(!isAdmin())
			{
				$currentPage = strtolower($CFG['html']['current_script_name']);
				if($CFG['admin']['module']['site_maintenance'] AND $currentPage != 'maintenance')
					{
						// Unset all of the session variables.
						$_SESSION = array();
						// If it's desired to kill the session, also delete the session cookie.
						// Note: This will destroy the session, and not just the session data!
						if (isset($_COOKIE[session_name()]))
							{
							   setcookie(session_name(), '', time()-42000, '/');
							}
						// Finally, destroy the session.
						session_destroy();
						session_write_close();
						setcookie($CFG['cookie']['starting_text'].'_bba', '', time()-42000, '/');
						$murl = getUrl($CFG['redirect']['maintenance_module_url']['file_name'], $CFG['redirect']['maintenance_module_url']['normal'], $CFG['redirect']['maintenance_module_url']['htaccess'], 'root');
						$CFG['site']['current_url'];
						if($CFG['site']['current_url']!=$murl)
							{
								Redirect2Url($murl);
								exit;
							}

					}
			}
		else
			{
				$value_array = explode('/', $CFG['site']['relative_url']);
				if(!in_array('admin', $value_array) and $CFG['admin']['module']['site_maintenance'])
					{
						$admin_url = $CFG['site']['url'].'admin/index.php';
						Redirect2URL($admin_url);
					}
			}
	}

/**
 * Check the allowed country user
 *
 * @access	public
 * @return	boolean
 */
function chkIsAllowedCountry()
	{
		global $CFG;
		$country_code = apache_note("GEOIP_COUNTRY_CODE");
		if(in_array($country_code, $CFG['admin']['geo_country']))
			return false;
		return true;
	}

/**
 * Return the matched pattern list from given string
 *
 * @access	public
 * @param	string	pattern to search
 * @param	string	content
 * @param	integer	to return the particular array value
 * @return	array
 */
function MatchPattern($PATTERN = '', $CONTENT = '', $KEY = '')
	{
		if ($PATTERN && $CONTENT)
			{
				preg_match_all ($PATTERN, $CONTENT, $Match);
			}
		if ($KEY != '')
			{
				return $Match[$KEY];
			}
		return $Match;
	}
/**
$varrfile = '<filename class="class1">test<filename class="class2">dsfsd fsd<filename class="class3">';
$pattern2 ='~<filename class="([^"]+)">~i';
$lang_value = MatchPattern($pattern2, $varrfile);
echo '<pre>';print_r($lang_value);echo '</pre>';
*/

/**
 * used to get the image with and height
 *
 * @access	public
 * @param	integer required width
 * @param	integer required height
 * @param	integer	image original width
 * @param	integer	image original height
 * @return	string
 */
function DISP_IMAGE($cfg_width = 0, $cfg_height = 0, $img_width = 0, $img_height = 0)
	{
	   	 $relative_height='';
	   	 $relative_width='';
		if ($cfg_width > 0 AND $cfg_height > 0 AND ($cfg_width < $img_width) AND ($cfg_height < $img_height))
			$attr = ($img_width > $img_height)? " width=\"".$cfg_width."\"" : " height=\"".$cfg_height."\"";
			else if ($cfg_width > 0 AND $cfg_width < $img_width)
			{
			   	$ratio = $img_height / $img_width;
			    $relative_height=$cfg_width*$ratio;
				$attr = " width=\"".$cfg_width."\" height=\"".$relative_height."\"";
			 }
				else if ($cfg_height > 0 AND $cfg_height < $img_height)
				{
				   	$ratio = $img_width / $img_height;
			        $relative_width=$cfg_height*$ratio;
					$attr = " width=\"".$relative_width."\" height=\"".$cfg_height."\"";
				}
					else
						$attr = "";
			return $attr;
	}

/**
 * Word Limiter
 *
 * Limits a string to X number of words.
 *
 * @access	public
 * @param	string
 * @param	integer
 * @param	string	the end character. Usually an ellipsis
 * @return	string
 */
function word_limiter($str, $limit = 100, $end_char = '…')
	{
		if (trim($str) == '')
			{
				return $str;
			}
		preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
		if (strlen($str) == strlen($matches[0]))
			{
				$end_char = '';
			}
		return rtrim($matches[0]).$end_char;
	}

/**
 * Character Limiter
 *
 * Limits the string based on the character count.  Preserves complete words
 * so the character count may not be exactly as specified.
 *
 * @access	public
 * @param	string
 * @param	integer
 * @param	string	the end character. Usually an ellipsis
 * @return	string
 */
function character_limiter($str, $n = 500, $end_char = '…')
	{
		if (strlen($str) < $n)
			{
				return $str;
			}
		$str = preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str));
		if (strlen($str) <= $n)
			{
				return $str;
			}
		$out = "";
		foreach (explode(' ', trim($str)) as $val)
			{
				$out .= $val.' ';
				if (strlen($out) >= $n)
					{
						return trim($out).$end_char;
					}
			}
	}

/**
 * Word Censoring Function
 *
 * Supply a string and an array of disallowed words and any
 * matched words will be converted to #### or to the replacement
 * word you've submitted.
 *
 * @access	public
 * @param	string	the text string
 * @param	string	the array of censoered words
 * @param	string	the optional replacement value
 * @return	string
 */
function word_censor($str, $censored, $replacement = '')
	{
		if ( ! is_array($censored))
			{
				return $str;
			}
		$str = ' '.$str.' ';
		foreach ($censored as $badword)
			{
				if ($replacement != '')
					{
						$str = preg_replace("/\b(".str_replace('\*', '\w*?', preg_quote($badword)).")\b/i", $replacement, $str);
					}
				else
					{
						$str = preg_replace("/\b(".str_replace('\*', '\w*?', preg_quote($badword)).")\b/ie", "str_repeat('#', strlen('\\1'))", $str);
					}
			}
		return trim($str);
	}

/**
 * Code Highlighter
 *
 * Colorizes code strings
 *
 * @access	public
 * @param	string	the text string
 * @return	string
 */
function highlight_code($str)
	{
		// The highlight string function encodes and highlights
		// brackets so we need them to start raw
		$str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str);

		// Replace any existing PHP tags to temporary markers so they don't accidentally
		// break the string out of PHP, and thus, thwart the highlighting.

		$str = str_replace(array('<?', '?>', '<%', '%>', '\\', '</script>'),
							array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str);

		// The highlight_string function requires that the text be surrounded
		// by PHP tags.  Since we don't know if A) the submitted text has PHP tags,
		// or B) whether the PHP tags enclose the entire string, we will add our
		// own PHP tags around the string along with some markers to make replacement easier later

		$str = '<?php tempstart'."\n".$str.'tempend ?>';

		// All the magic happens here, baby!
		$str = highlight_string($str, TRUE);

		// Prior to PHP 5, the highlight function used icky font tags
		// so we'll replace them with span tags.
		if (abs(phpversion()) < 5)
			{
				$str = str_replace(array('<font ', ',',',',',',',','</font>'), array('<span ', ',',',',',',',','</span>'), $str);
				$str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
			}

		// Remove our artificially added PHP
		$str = preg_replace("#\<code\>.+?tempstart\<br />(?:\</span\>)?#is", "<code>\n", $str);
		$str = preg_replace("#tempend.+#is", "</span>\n</code>", $str);

		// Replace our markers back to PHP tags.
		$str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
							array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'), $str);

		return $str;
	}

/**
 * Phrase Highlighter
 *
 * Highlights a phrase within a text string
 *
 * @access	public
 * @param	string	the text string
 * @param	string	the phrase you'd like to highlight
 * @param	string	the openging tag to precede the phrase with
 * @param	string	the closing tag to end the phrase with
 * @return	string
 */
 function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>')
	{
		if ($str == '')
			{
				return '';
			}
		if ($phrase != '')
			{
				return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str);
			}
		return $str;
	}

/**
 * Word Wrap
 *
 * Wraps text at the specified character.  Maintains the integrity of words.
 * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
 * will URLs.
 *
 * @access	public
 * @param	string	the text string
 * @param	integer	the number of characters to wrap at
 * @return	string
 */
function word_wrap($str, $charlim = '76')
	{
		// Se the character limit
		if ( ! is_numeric($charlim))
			$charlim = 76;

		// Reduce multiple spaces
		$str = preg_replace("| +|", " ", $str);

		// Standardize newlines
		$str = preg_replace("/\r\n|\r/", "\n", $str);

		// If the current word is surrounded by {unwrap} tags we'll
		// strip the entire chunk and replace it with a marker.
		$unwrap = array();
		if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
			{
				for ($i = 0; $i < count($matches['0']); $i++)
					{
						$unwrap[] = $matches['1'][$i];
						$str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
					}
			}

		// Use PHP's native function to do the initial wordwrap.
		// We set the cut flag to FALSE so that any individual words that are
		// too long get left alone.  In the next step we'll deal with them.
		$str = wordwrap($str, $charlim, "\n", FALSE);

		// Split the string into individual lines of text and cycle through them
		$output = "";
		foreach (explode("\n", $str) as $line)
			{
				// Is the line within the allowed character count?
				// If so we'll join it to the output and continue
				if (strlen($line) <= $charlim)
					{
						$output .= $line."\n";
						continue;
					}

				$temp = '';
				while((strlen($line)) > $charlim)
					{
						// If the over-length word is a URL we won't wrap it
						if (preg_match("!\[url.+\]|://|wwww.!", $line))
							{
								break;
							}

						// Trim the word down
						$temp .= substr($line, 0, $charlim-1);
						$line = substr($line, $charlim-1);
					}

				// If $temp contains data it means we had to split up an over-length
				// word into smaller chunks so we'll add it back to our current line
				if ($temp != '')
					{
						$output .= $temp . "\n" . $line;
					}
				else
					{
						$output .= $line;
					}

				$output .= "\n";
			}

		// Put our markers back
		if (count($unwrap) > 0)
			{
				foreach ($unwrap as $key => $val)
					{
						$output = str_replace("{{unwrapped".$key."}}", $val, $output);
					}
			}

		// Remove the unwrap tags
		$output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output);

		return $output;
	}

/**
 * Create a Directory Map
 *
 * Reads the specified directory and builds an array
 * representation of it.  Sub-folders contained with the
 * directory will be mapped as well.
 *
 * @access	public
 * @param	string	path to source
 * @param	bool	whether to limit the result to the top level only
 * @return	array
 */
function directory_map($source_dir, $top_level_only = FALSE)
	{
		if ($fp = @opendir($source_dir))
		{
			$filedata = array();
			while (FALSE !== ($file = readdir($fp)))
			{
				if (@is_dir($source_dir.$file) && substr($file, 0, 1) != '.' AND $top_level_only == FALSE)
				{
					$temp_array = array();

					$temp_array = directory_map($source_dir.$file."/");

					$filedata[$file] = $temp_array;
				}
				elseif (substr($file, 0, 1) != ".")
				{
					$filedata[] = $file;
				}
			}
			return $filedata;
		}
	}

/**
 * Read File
 *
 * Opens the file specfied in the path and returns it as a string.
 *
 * @access	public
 * @param	string	path to file
 * @return	string
 */
 function read_file($file)
	{
		if ( ! file_exists($file))
			{
				return FALSE;
			}

		if (function_exists('file_get_contents'))
			{
				return file_get_contents($file);
			}

		if ( ! $fp = @fopen($file, 'rb'))
			{
				return FALSE;
			}

		flock($fp, LOCK_SH);

		$data = '';
		if (filesize($file) > 0)
			{
				$data =& fread($fp, filesize($file));
			}

		flock($fp, LOCK_UN);
		fclose($fp);

		return $data;
	}

/**
 * Write File
 *
 * Writes data to the file specified in the path.
 * Creates a new file if non-existent.
 *
 * @access	public
 * @param	string	path to file
 * @param	string	file data
 * @return	bool
 */
 function write_file($path, $data, $mode = 'w+')
	{
		if ( ! $fp = @fopen($path, $mode))
			{
				return FALSE;
			}
		flock($fp, LOCK_EX);
		fwrite($fp, $data);
		@chmod($path, 0777);
		flock($fp, LOCK_UN);
		fclose($fp);
		return TRUE;
	}

/**
 * read Directory
 *
 * read to the file specified in the path.
 *
 * @access	public
 * @param	string	$dir_path to file
 * @param	string	return (dir, file, both)
 * @return	bool
 */
function readDirectory($dir_path, $return = 'both')
	{
		$return_arr = array();
		if ($handle = opendir($dir_path))
			{
    			while (false !== ($file = readdir($handle)))
					{
				        if ($file != "." && $file != ".." && $file != ".svn")
							{
				            	if((is_file($dir_path.$file) and $return=='file') or (is_dir($dir_path.$file) and $return=='dir') or ($return=='both'))
									{
										$return_arr[] = $file;
									}
        					}
    				}
    			closedir($handle);
			}
		return $return_arr;
	}

/**
 * Force Download
 *
 * Generates headers that force a download to happen
 *
 * @access	public
 * @param	string	filename
 * @param	mixed	the data to be downloaded
 * @return	void
 */
function force_download($filename = '', $data = '')
	{
		global $CFG;
		if ($filename == '' OR $data == '')
			{
				return FALSE;
			}

		// Try to determine if the filename includes a file extension.
		// We need it in order to set the MIME type
		if (FALSE === strpos($filename, '.'))
			{
				return FALSE;
			}

		// Grab the file extension
		$x = explode('.', $filename);
		$extension = end($x);

		// Load the mime types
		@include($CFG['site']['project_path'].'common/configs/config_mimes.inc..php');

		// Set a default mime if we can't find it
		if ( ! isset($mimes[$extension]))
			{
				$mime = 'application/octet-stream';
			}
		else
			{
				$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
			}

		// Generate the server headers
		if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
			{
				header('Content-Type: "'.$mime.'"');
				header('Content-Disposition: attachment; filename="'.$filename.'"');
				header('Expires: 0');
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header("Content-Transfer-Encoding: binary");
				header('Pragma: public');
				header("Content-Length: ".strlen($data));
			}
		else
			{
				header('Content-Type: "'.$mime.'"');
				header('Content-Disposition: attachment; filename="'.$filename.'"');
				header("Content-Transfer-Encoding: binary");
				header('Expires: 0');
				header('Pragma: no-cache');
				header("Content-Length: ".strlen($data));
			}
		echo $data;
	}

/**
 * Strip Slashes
 *
 * Removes slashes contained in a string or in an array
 *
 * @access	public
 * @param	mixed	string or array
 * @return	mixed	string or array
 */
function strip_slashes($str)
	{
		if (is_array($str))
			{
				foreach ($str as $key => $val)
					{
						$str[$key] = strip_slashes($val);
					}
			}
		else
			{
				$str = stripslashes($str);
			}
		return $str;
	}

/**
 * check particular cron file running status
 *
 * @access	public
 * @param	string	script name to check
 * @return	boolean
 */
function isCronRunning($script_name = '')
	{
		global $CFG;
		if(strstr($CFG['site']['url'], '/localhost/'))
			{
				return false;
			}
		$max_cron_allowed = 1;
		$cronRunning = false;
		if ($script_name)
			{
				$command = ' ps -eaf | grep '.$script_name;
				$result  = @shell_exec($command);
				$scriptCount = intval(@substr_count($result, $script_name));
				$max_cron_allowed = ($max_cron_allowed + 3);// 1 for ps, 1 for grep, 1 for the current /usr/bin/php cron.php
				$cronRunning = ($scriptCount >= $max_cron_allowed);
			}
		return $cronRunning;
	}

/**
 * to control the cron file running
 *
 * @access	public
 * @return	static
 */
function callMultipleCronCheck()
	{
		global $CFG;
		$cronUrl = $CFG['site']['current_url'];
		$time = date('d-m-y H:i:s');
		print "\n CRON:\t$cronUrl:\nTIME:$time\n";
		if (isCronRunning($cronUrl))
			{
				print "CRON : $cronUrl\nTIME:$cronUrl\nConcurrent Process Detected\nSo Skipping ".$cronUrl." CRON at ".date('d-M-y H:i:s')."\n\n";
				die();
			}
	}

/**
 * get the md5 text with number of characters
 *
 * @access	public
 * @param	string
 * @param	integer
 * @return	boolean
 */
function getMD5Text($text, $count = 15)
	{
		$text = md5($text);
		return substr($text, 0, $count-1);
	}

/**
 * to encode purpose, we can change it as per requirement
 *
 * @access	public
 * @param	string
 * @param	integer
 * @return	boolean
 */
function doEncode($text, $size=0)
	{
		$text = str_pad($text, $size, '0', STR_PAD_LEFT);
		$text = base64_encode($text);
		$text = urlencode($text);
		return $text;
	}

/**
 * to decode purpose, we can change it as per requirement
 *
 * @access	public
 * @param	string
 * @return	boolean
 */
function doDecode($text)
	{
		$text = urldecode($text);
		$text = base64_decode($text);
		return $text;
	}

/**
 * to get the seconds difference b/w current time and given time
 *
 * @access	public
 * @param	integer
 * @return	integer
 */
function getTimeDiffInSeconds($date)
	{
		global $CFG;
		global $db;

		$sql = 'SELECT TIMEDIFF(NOW(), \''.$date.'\') AS date_added';

		$stmt = $db->Prepare($sql);
		$rs = $db->Execute($stmt);
		    if (!$rs)
				trigger_db_error($db);

		$row = $rs->FetchRow();
		return $row['date_added'];
	}

/**
 * to get the time difference b/w current time and given time
 *
 * @access	public
 * @param	integer
 * @return	string
 */
function getTimeDiffernce($time)
	{
		global $LANG;
		$date_added_pc = array();

		$date_added_pc = explode(':', $time);

		if(sizeof($date_added_pc)!=3)
			return '0 '.$LANG['timediff_seconds_ago'];

		$date_added_pc[0] = intval($date_added_pc[0]);
		$date_added_pc[1] = intval($date_added_pc[1]);
		$date_added_pc[2] = intval($date_added_pc[2]);

		if($date_added_pc[0])
			{
				$day = floor($date_added_pc[0]/24);
				if($day>365)
					{
						$year = floor($day/365);
						if($year>1)
							$time = $year.' '.$LANG['timediff_years_ago'];
						else
							$time = $year.' '.$LANG['timediff_year_ago'];
					}
				else if($day>30)
					{
						$month = floor($day/30);
						if($month>1)
							$time = $month.' '.$LANG['timediff_months_ago'];
						else
							$time = $month.' '.$LANG['timediff_month_ago'];
					}
				else if($day)
					{
						if($day>1)
							$time = $day.' '.$LANG['timediff_days_ago'];
						else
							$time = $day.' '.$LANG['timediff_day_ago'];
					}
				else
					{
						if($date_added_pc[0]>1)
							$time = $date_added_pc[0].' '.$LANG['timediff_hours_ago'];
						else
							$time = $date_added_pc[0].' '.$LANG['timediff_hour_ago'];
					}
			}
		else if($date_added_pc[1])
			{
				if($date_added_pc[1]>1)
					$time = $date_added_pc[1].' '.$LANG['timediff_minutes_ago'];
				else
					$time = $date_added_pc[1].' '.$LANG['timediff_minute_ago'];
			}
		else
			{
				if($date_added_pc[2]>1)
					$time = $date_added_pc[2].' '.$LANG['timediff_seconds_ago'];
				else
					$time = $date_added_pc[2].' '.$LANG['timediff_second_ago'];
			}

		return $time;
	}

	function getDateTimeDiff($date,$today)
		{
			list($year, $month, $day, $hrs, $min, $sec) = split('[ \:-]', $date);

			list($year1, $month1, $day1, $hrs1, $min1, $sec1) = split('[ \:-]', $today);

			$secs = mktime($hrs1, $min1, $sec1, $month1, $day1, $year1)-mktime($hrs, $min, $sec, $month, $day, $year);
			$mins = floor($secs/60);
			$hrs  = floor($mins/60);
			$secs = $secs % 60;
			$mins = $mins % 60;
			return $row['date_added'] = $hrs.':'.$mins.':'.$secs;
		}

/**
 * Looks for the first occurence of $needle in $haystack and replaces it with $replace.
 *
 * @access	public
 * @param	string	search string
 * @param	string	replace string
 * @param	string	given string
 * @return	string
 */
function str_replace_once($needle, $replace, $haystack)
	{
	    $pos = strpos($haystack, $needle);
	    if ($pos === false)
			{
		        return $haystack;
		    }
	    return substr_replace($haystack, $replace, $pos, strlen($needle));
	}

/**
 * get full text format of given string
 *
 * @access	public
 * @param	string	given string
 * @return	string
 */
function getFullTextSearchString($tags)
	{
		$tags= rawurlencode($tags);
		return $tags = '[[:<:]]'.preg_replace('/\s+/', '|', addslashes($tags)).'[[:>:]]';

		$tags = trim($tags);
		while(strpos($tags, '  '))
			{
				$tags = str_replace('  ', ' ', $tags);
			}
		$tags = addslashes($tags);
		$tags_arr = explode(' ', $tags);
		$tags = '[[:<:]]'.implode('[[:>:]]|[[:<:]]', $tags_arr).'[[:>:]]';
		return $tags;
	}

/**
 * to get search qurey like full text search query.
 *
 * @access	public
 * @param	string	tags to search
 * @param	string	search field
 * @param	string	additional string to add (AND, OR)
 * @return	string
 */
function getSearchRegularExpressionQueryForums($tags, $field_name, $extra = '')
	{
		global $CFG;
		$not_allowed_search_array = $CFG['admin']['not_allowed_chars'];
		$tags = replaceCharacter($not_allowed_search_array, '-', $tags);
		$tags = addslashes($tags);
		$additional_query = ' ('.$field_name.' REGEXP \''.formatSearchString($tags).'\') '.$extra.' ';
		return $additional_query;
	}

function replaceCharacter($search_value, $replace, $text)
	{
		if(is_array($search_value))
			{
				foreach($search_value as $key=>$value)
					$text = str_replace ($value, $replace, $text);
				return $text;
			}
		return str_replace ($char, $replace, $text);
	}
function formatSearchString($tags)
	{
		return $tags = '[[:<:]]'.preg_replace('/\s+/', '|', $tags).'[[:>:]]';

		$tags = trim($tags);
		while(strpos($tags, '  '))
			{
				$tags = str_replace('  ', ' ', $tags);
			}
		$tags = addslashes($tags);
		$tags_arr = explode(' ', $tags);
		$tags = '[[:<:]]'.implode('[[:>:]]|[[:<:]]', $tags_arr).'[[:>:]]';
		return $tags;
	}


/**
 * to get search qurey like full text search query.
 *
 * @access	public
 * @param	string	tags to search
 * @param	string	search field
 * @param	string	additional string to add (AND, OR)
 * @return	string
 */
function getSearchRegularExpressionQuery($tags, $field_name, $extra = '')
	{
		global $CFG;
		$tags = addslashes($tags);
		if($CFG['admin']['search']['regular_expression'])
			{
				$additional_query = ' ('.$field_name.' REGEXP \''.getFullTextSearchString($tags).'\') '.$extra.' ';
			}
		else
			{
				$additional_query = ' MATCH('.$field_name.') AGAINST (\''.$tags.'\' IN BOOLEAN MODE) '.$extra.' ';
			}
		return $additional_query;
	}

/**
 * to create the multi level folder.
 *
 * @access	public
 * @param	string	folder name to create (root/sub/test/)
 * @return	static
 */
function createMultiLevelFolder($folderName)
	{
		$folder_arr = explode('/', $folderName);
		$folderName = '';
		foreach($folder_arr as $key=>$value)
			{
				$folderName .= $value.'/';
				if($value == '..' or $value == '.')
					continue;
				if (!is_dir($folderName))
					{
						mkdir($folderName);
						@chmod($folderName, 0777);
					}
			}
	}

/**
 * to remove the directory, if sub folders or file is in given directory,
 * this function will remove all the files
 *
 * @access	public
 * @param	string	directory name to delete
 * @return	boolean
 */
function removeDirectory($dirname)
	{
		if (is_dir($dirname))
	   		{
		       	$result = array();
		   		if (substr($dirname,-1) != '/')
					{
						$dirname.='/';
					}
			  	$handle = opendir($dirname);
			    while (false !== ($file = readdir($handle)))
				   {
			   			if ($file != '.' && $file != '..')
					   		{    //Ignore . and ..
				               $path = $dirname.$file;
				               	if (is_dir($path))
							   		{    //Recurse if subdir, Delete if file
				                   		$result=array_merge($result, $this->removeDirectory($path));
				            		}
								else
									{
						            	unlink($path);
						                $result[].=$path;
			               			}
		           			}
	       			}
			     closedir($handle);
			     rmdir($dirname);
			     $result[].=$dirname;
			     return $result;
	   		}
		else
			{
		       return false;
		   	}
	}

/**
 * used to top of the ajax pages
 *
 * @access	public
 * @param
 * @return	static
 */
function setHeaderStart($check_login=false)
	{
		global $CFG;
		ob_start();
		header("Pragma: no-cache");
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
		header("Expires: 0"); // Date in the past
		header("Content-type: text/xml; charset=\"".$CFG['site']['charset']."\"");
		if($check_login)
			echo 'check|||||||||valid|||||||||login';
	}

/**
 * used to bottom of the ajax pages
 *
 * @access	public
 * @param
 * @return	static
 */
function setHeaderEnd()
	{
		ob_end_flush();
	}

/**
 * to check given url valid or not with using curl
 *
 * @access	public
 * @param	string
 * @return	boolean
 */
function chkIsValidUrlUsingCurl($url)
	{
		if(!strstr($url, '://'))
			$url = 'http://'.$url;

		if (function_exists('curl_init'))
			{
				$ch = @curl_init();
				if ($ch)
				    {
						curl_setopt($ch, CURLOPT_URL, $url);
						curl_setopt($ch, CURLOPT_HEADER, 0);
						curl_setopt($ch, CURLOPT_NOBODY, 1);
						curl_setopt($ch, CURLOPT_RANGE, "0-1");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
						curl_setopt($ch, CURLOPT_TIMEOUT, 10);
						$result = curl_exec($ch);
						$errno = curl_errno($ch);
						curl_close($ch);
						if ($errno!=0)
							{
								return false;
							}
				    }
			}
		return true;
	}

function getContents($url)
	{
		$result = '';

		if(!strstr($url, '://'))
			$url = 'http://'.$url;

		if (function_exists('curl_init'))
			{
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2');
			    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			    $result = curl_exec($ch);
			    if (!curl_errno($ch))
			        curl_close($ch);
			     else
			        $result = false;
			}
		else
			{
				set_time_limit(180);
				$result = file_get_contents($url) ;
			}
		return $result;
	}

/**
 * used to get the font size of based on count(like search count)
 *
 * @access	public
 * @param	array
 * @return	array
 */
function setFontSizeForTagCloud($tag_array=array())
	{
		$formattedArray = $tag_array;
		$max_qty = max(array_values($formattedArray));
		$min_qty = min(array_values($formattedArray));
		$max_font_size = 28;
		$min_font_size = 12;
		$spread = $max_qty - $min_qty;
		if (0 == $spread) { // Divide by zero
			$spread = 1;
		}
		$step = ($max_font_size - $min_font_size)/($spread);
			foreach ($tag_array as $catname => $count)
			{
				$size = $min_font_size + ($count - $min_qty) * $step;
				$formattedArray[$catname] = ceil($size);
			}
		return $formattedArray;
	}

/**
 * intialize the template folder
 *
 * @access	public
 * @param	string	value may be ('', 'members/', 'admin/')
 * @return	static
 */
function setTemplateFolder($template_for = '',$module='')
	{
		global $smartyObj, $CFG;


		if($module)
			{

				if($template_for == 'admin/')
					{
						$smartyObj->template_dir 	= $CFG['site']['project_path'].'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for.$module.'/';
						$smartyObj->compile_dir  	= $CFG['site']['project_path'].'/design/templates/'.$CFG['html']['template']['default'].'/'.getTplFolder().$module.'/templates_c/';
						$smartyObj->css_path  		= $CFG['site']['url'].'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for.$module.'/css/'.$CFG['html']['stylesheet']['screen']['default'].'/';
					}
				else
					{
						if(isAdmin())
							{
								$smartyObj->template_dir 	= $CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for;
								$smartyObj->compile_dir  	= $CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/members/templates_c/';
								$smartyObj->css_path  		= $CFG['site']['url'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for.'css/'.$CFG['html']['stylesheet']['screen']['default'].'/';
							}
						else
							{
								$smartyObj->template_dir 	= $CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for;
								$smartyObj->compile_dir  	= $CFG['site']['project_path'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.getTplFolder().'templates_c/';
								$smartyObj->css_path  		= $CFG['site']['url'].$module.'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for.'css/'.$CFG['html']['stylesheet']['screen']['default'].'/';
							}
						//Check whether template is available for current module, if not available change template to available template
						if(!is_dir($smartyObj->template_dir))
							{
								foreach($CFG['html']['template']['allowed'] as $available_template)
									{
										$available_template_dir = $CFG['site']['project_path'].$module.'/design/templates/'.$available_template.'/'.$template_for;
										if(is_dir($available_template_dir))
											{
												foreach($CFG['html']['stylesheet'][$available_template]['allowed'] as $available_css)
													{
														$available_css_path  = $CFG['site']['project_path'].$module.'/design/templates/'.$available_template.'/root/css/'.$available_css.'/';
														if(is_dir($available_css_path))
															{
																$smartyObj->template_dir 	= $available_template_dir;
																$smartyObj->compile_dir  	= $CFG['site']['project_path'].$module.'/design/templates/'.$available_template.'/'.getTplFolder().'templates_c/';
																$smartyObj->css_path  		= $CFG['site']['url'].$module.'/design/templates/'.$available_template.'/'.$template_for.'css/'.$available_css.'/';
																break;
															}

													}
											}
									}
							}
					}


			}
		else
			{
				$smartyObj->template_dir = $CFG['site']['project_path'].'design/templates/'.$CFG['html']['template']['default'].'/'.$template_for;
				$smartyObj->compile_dir  = $CFG['site']['project_path'].'design/templates/'.$CFG['html']['template']['default'].'/'.getTplFolder().'templates_c/';
				$smartyObj->css_path  = $CFG['site']['url'].'design/templates/'.$CFG['html']['template']['default'].'/'.$template_for.'css/'.$CFG['html']['stylesheet']['screen']['default'].'/';
				//Check whether template is available for current module, if not available change template to available template
				if(!empty($CFG['site']['is_module_page']))
					{
						//check whether directory exists or not for the current module & current template
						$template_dir_module = $CFG['site']['project_path'].$CFG['site']['is_module_page'].'/design/templates/'.$CFG['html']['template']['default'].'/'.$template_for;
						if(!is_dir($template_dir_module))
							{
								foreach($CFG['html']['template']['allowed'] as $available_template)
									{
										$available_template_dir = $CFG['site']['project_path'].$CFG['site']['is_module_page'].'/design/templates/'.$available_template.'/'.$template_for;
										if(is_dir($available_template_dir))
											{
												$CFG['html']['template']['default'] = $available_template;
												foreach($CFG['html']['stylesheet'][$available_template]['allowed'] as $available_css)
													{
														$available_css_path  = $CFG['site']['project_path'].$CFG['site']['is_module_page'].'/design/templates/'.$available_template.'/root/css/'.$available_css.'/';
														if(is_dir($available_css_path))
															{
																$CFG['html']['stylesheet']['screen']['default'] = $available_css;
																$smartyObj->template_dir 	= $CFG['site']['project_path'].'design/templates/'.$available_template.'/'.$template_for;;
																$smartyObj->compile_dir  	= $CFG['site']['project_path'].'design/templates/'.$available_template.'/'.getTplFolder().'templates_c/';
																$smartyObj->css_path  		= $CFG['site']['url'].'design/templates/'.$available_template.'/'.$template_for.'css/'.$available_css.'/';
																break;
															}

													}
											}
									}
							}
					}
			}
		$smartyObj->cache_dir  = $CFG['site']['project_path'].'design/templates/'.$CFG['html']['template']['default'].'/'.getTplFolder().'cache/';
		$image_path = $CFG['site']['url'].'design/templates/'.$CFG['html']['template']['default'].'/root/images/'.$CFG['html']['stylesheet']['screen']['default'].'/';
		$smartyObj->assign('html_stylesheet', $smartyObj->css_path.$CFG['html']['stylesheet']['screen']['default_file'].'.css');
		$smartyObj->css_defalut_path=$smartyObj->css_path.$CFG['html']['stylesheet']['screen']['default_file'].'.css';

		$smartyObj->assign('images_path', $image_path);
		$smartyObj->assign('html_stylesheet_path', $smartyObj->css_path);
	}

/**
 * return the url
 *
 * @access	public
 * @param	string
 * @return	string
 */
function URL($url)
	{
		return $url;
	}

/**
 * check the current page is ajax request
 *
 * @access	public
 * @param
 * @return	boolean
 */
function isAjaxPage()
	{
		return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
		    $_SERVER ['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest';
	}

/**
 * used to show the help tip
 *
 * @access	public
 * @param	string	key in help file
 * @param	string	name for smarty
 * @return	static
 */
function ShowHelpTip($tip_key, $tipfor = '')
	{
		global $LANG, $CFG;
		$tipfor = $tipfor?$tipfor:$tip_key;
		$tip = str_replace("\n", '
', $LANG['help'][$tip_key]);
?>
<div class="clsHelpText" id="<?php echo $tipfor;?>_Help" style="visibility:hidden"><?php echo $tip;?></div>
<?php
	}

/**
 * check the current page is ajax request
 *
 * @access	public
 * @param
 * @return	boolean
 */
function isAjax()
		{
			return (isset($_REQUEST['ajax_page']) and $_REQUEST['ajax_page']==true) or (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
		    $_SERVER ['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');
		}

/**
 * used to change the format of date
 *
 * @access	public
 * @param	string
 * @return	string
 */
function FMT_DATE($date)
	{
		return $date;
	}

/**
 * used to change the format of amount
 *
 * @access	public
 * @param	string
 * @return	string
 */
function FMT_AMOUNT($amount)
	{
		global $CFG;
		$exponent = pow(10, $CFG['framework']['no_of_decimals']);
		return (floor($amount * $exponent) / $exponent);
	}

/**
 * to display the exposed query
 *
 * @access	public
 * @param	string	error message
 * @param	string	new line character (currently we don't use the argument)
 * @return	static
 */
function ExposeQuery($msg, $newline = '')
	{
		GLOBAL $SQL_QUERIES;
		$SQL_QUERIES .= "\n".$msg."\n";
   	}

/**
 * to display debugging list
 *
 * @access	public
 * @param	string	error name
 * @param	string	error description
 * @return	static
 */
function DEBUG($var_name, $var_desc='')
	{
	    global $CFG, $DEBUG_TRACE;
	    if ($CFG['debug']['is_debug_mode'])
			{
        		$DEBUG_TRACE .= "\n".$var_desc.':';
        		if (!is_array($var_name))
					$var_name = htmlspecialchars($var_name);
        		$DEBUG_TRACE .= print_r($var_name, true);
        		if (is_array($var_name))
					reset($var_name);
        		$DEBUG_TRACE .= "\n";
    		}
	}

/**
 * to redirection
 *
 * @access	public
 * @param	string
 * @return	static
 */
function Redirect2URL($url)
	{
		global $CFG;
		if(isAjaxpage() or $CFG['admin']['session_redirect_light_window_page'])
			{
				if(!isMember())
					{
						unset($_SESSION['url']);
						$param = '';
						if(isAjaxpage() and $CFG['html']['current_script_name'] != 'shareVideo')
							$param = '?ajax_page=true';
						$url = $CFG['auth']['ajax_url'].$param;
					}
			}

		if (!headers_sent())
		    {
			   header('Location: '.URL($url));
			   //if IIS, then send Refresh header too (as a safe solution)...Location header doesn't seems to work in IIS
			   if (stristr($_SERVER['SERVER_SIGNATURE'], 'IIS'))
			   		header('Refresh: 0;url='.$url);
		    }
		else
			{
				trigger_error('Headers already sent', E_USER_NOTICE);
				echo '<meta http-equiv="refresh" content="0; URL='.URL($url).'" />'."\n";
				echo '<p>Please click this <a href="'.URL($url).'">link</a> to continue...</p>'."\n";
			}
		exit(0);
	}

/**
 * to get the advertisement
 *
 * @access	public
 * @param	string	block name
 * @return	string
 */
$______ADVERTISEMENT_ID = array();
function getAdvertisement($block,$not_allowed_page_name=array())
	{
		global $CFG;
		global $db;
		global $______ADVERTISEMENT_ID;
		$block_condition='';
		if(!chkAllowedModule(array('banner')))
			return;
		 $cur_page_name=strtolower(basename($_SERVER['SCRIPT_NAME'], ".php")); /* supposing filetype .php*/

		  if(sizeof($not_allowed_page_name)>0 && in_array($cur_page_name,$not_allowed_page_name))
	 	    {
	 		 return false;
	 		}

	  	$sql = 'SELECT add_id, source FROM '.$CFG['db']['tbl']['advertisement'].' WHERE'.
			' post_from=\'Admin\'AND block=\''.$block.'\''.
			' AND status=\'activate\'';

		if($CFG['admin']['banner']['impressions_date'])
			{
				$sql .= ' AND NOW()>=start_date AND (((allowed_impressions!=\'\' AND allowed_impressions!=0) AND'.
						' (completed_impressions < allowed_impressions)) OR ((allowed_impressions=\'\''.
						' OR allowed_impressions=0) AND (end_date!=\'0000-00-00 00:00:00\''.
						' AND end_date > NOW())))';
			}
		$stmt = $db->Prepare($sql);
		$rs = $db->Execute($stmt, array());
		    if (!$rs)
			    trigger_db_error($db);

		$total_count = $rs->PO_RecordCount();

   		if(!$total_count)
         {
		 $sql = 'SELECT add_id, source FROM '.$CFG['db']['tbl']['advertisement'].' WHERE'.
				' post_from=\'Admin\' AND block LIKE \'%'.$block.'\''.
				' AND status=\'activate\'';

		if($CFG['admin']['banner']['impressions_date'])
			{
				$sql .= ' AND NOW()>=start_date AND (((allowed_impressions!=\'\' AND allowed_impressions!=0) AND'.
						' (completed_impressions < allowed_impressions)) OR ((allowed_impressions=\'\''.
						' OR allowed_impressions=0) AND (end_date!=\'0000-00-00 00:00:00\''.
						' AND end_date > NOW())))';
			}

		$stmt = $db->Prepare($sql);
		$rs = $db->Execute($stmt);
		    if (!$rs)
			    trigger_db_error($db);

		$total_count = $rs->PO_RecordCount();
		}

   		if(!$total_count)
   			return false;

		$add_array = array();

		$need = rand(1, $total_count);
		$i = 1;
		while($row = $rs->FetchRow())
			{
				if($need==$i)
					{
						echo htmlentitydecode($row['source']);
						$______ADVERTISEMENT_ID[$row['add_id']] = $row['add_id'];
						break;
					}

				 $i++;
			}
	}

function htmlentitydecode($text)
	{
		global $CFG;

		$default_charset = strtolower($CFG['site']['charset']);
		$allwable_charsets = array('iso-8859-1', 'iso-8859-15', 'utf-8', 'cp866', 'cp1251',
									'cp1252', 'koi8-r', 'big5', 'gb2312', 'big5-hkscs', 'shift_jis',
									'euc-jp', 'iso8859-1', 'iso8859-15', 'ibm866', '866', 'windows-1251',
									'win-1251', '1251', 'windows-1252', '1252', 'koi8-ru', 'koi8r', '950',
									'936', 'sjis', '932', 'eucjp');

		if(in_array($default_charset, $allwable_charsets))
			{
				$charset = $CFG['site']['charset'];
			}
		else
			{
				$charset = 'ISO-8859-1';
			}

		return @html_entity_decode($text, ENT_QUOTES, $charset);
	}

/**
 * to update the advertisement view count
 *
 * @access	public
 * @param
 * @return	static
 */
function updateAdvertisementCount()
	{
		global $______ADVERTISEMENT_ID;
		global $CFG;
		global $db;

		if(!$CFG['admin']['banner']['impressions_date'])
			return;

		if(sizeof($______ADVERTISEMENT_ID))
			{
				$sql = 'UPDATE '.$CFG['db']['tbl']['advertisement'].' SET'.
						' completed_impressions=completed_impressions+1'.
						' WHERE add_id IN('.implode(',', $______ADVERTISEMENT_ID).')';

				$stmt = $db->Prepare($sql);
				$rs = $db->Execute($stmt);
				    if (!$rs)
					    trigger_db_error($db);

				$______ADVERTISEMENT_ID = array();
			}
	}

function getCleanUrl($url)
	{
		global $CFG;
		if($CFG['feature']['rewrite_mode']=='clean')
			{
				$url = str_replace('&amp;', '/', $url);
				$url = str_replace('?', '/', $url);
				$url = str_replace('&', '/', $url);
				$url = str_replace('=', '/', $url);
			}
		return $url;
	}

function populateGETValue()
	{
		global $CFG;
		if($CFG['feature']['rewrite_mode']=='clean')
			{
				if($CFG['site']['query_string'])
					{
						$query_string = getCleanUrl($CFG['site']['query_string']);
						/*while(strpos($query_string, '//'))
							{
								$query_string = str_replace('//', '/', $query_string);
							}*/
						if(strpos($query_string, '/')===0)
							$query_string = substr($query_string, 1);
						if(strrpos($query_string, '/')==strlen($query_string)-1)
							$query_string = substr($query_string, 0, strlen($query_string)-1);

						$query_string_arr = explode('/', $query_string);
						for($i=0;$i<sizeof($query_string_arr);$i = $i+2)
							{
								$_REQUEST[$query_string_arr[$i]] = $_GET[$query_string_arr[$i]] = isset($query_string_arr[$i+1])?urldecode(str_replace('%25', '%', $query_string_arr[$i+1])):'';
							}
					}
			}
	}
populateGETValue();

/**
 * to get the url based on htaccess setting
 *
 * @access	public
 * @param	string	file_name url
 * @param	string	normal url
 * @param	string	htaccess url
 * @param	boolean	check url need to change or not(it may be current, root, members, nothing)
 * @return	string
 */
function getUrl($file_name, $normal = '', $htaccess = '', $change = '',$module='')
	{
		global $CFG;
		global $folder_names_arr;
		$relativeUrl='';
		if(!$change)
		{
			$change='current';
		}
		$normal = $CFG['page_url'][$file_name]['normal'].$normal;
		$htaccess = $CFG['page_url'][$file_name]['htaccess'].$htaccess;

		if($CFG['feature']['rewrite_mode']=='clean')
			{
				$restricted_pages = array('addbookmark');
				if(!in_array($file_name, $restricted_pages))
					{
						$normal = getCleanUrl($normal);
					}
			}
		if($CFG['feature']['rewrite_mode']=='htaccess')
			{
				if(strrpos($htaccess, '/')==strlen($htaccess)-1 and ($htaccess!=$CFG['site']['url']) and ($htaccess!=$CFG['site']['url'].'/members/') and ($htaccess!=$CFG['site']['url'].'/admin/'))
					{
						$htaccess = substr($htaccess, 0, strrpos($htaccess, '/')).$CFG['feature']['rewrite_mode_endwith'];
					}
				$htaccess = str_replace('/?', '.html?', $htaccess);
				$htaccess = str_replace('/&', '.html&', $htaccess);
			}

		if($module)
		{
			if($CFG['site']['relative_url']==$CFG['site']['url'])
			{
				$relativeUrl=$CFG['site']['url'].$module.'/';

			}
			foreach($folder_names_arr as $folder)
			{
				if($CFG['site']['relative_url']==$CFG['site']['url'].$folder)
				{
					$relativeUrl=$CFG['site']['url'].$module.'/'.$folder;
					break;
				}
			}
			foreach($CFG['site']['modules_arr'] as $mod)
			{

				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/')
				{
					$relativeUrl=$CFG['site']['url'].$module.'/';
					break;
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/members/')
				{
					$relativeUrl=$CFG['site']['url'].$module.'/members/';
					break;
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/rss/')
				{
					$relativeUrl=$CFG['site']['url'].$module.'/rss/';
					break;
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].'admin/'.$mod.'/')
				{
					$relativeUrl=$CFG['site']['url'].'admin/'.$module.'/';
					break;
				}

			}
		$siteUrl=$CFG['site']['url'].$module.'/';

		}
		else
		{
			foreach($CFG['site']['modules_arr'] as $mod)
			{
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/')
				{
					$CFG['site']['relative_url']=$CFG['site']['url'];
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/members/')
				{
					$relativeUrl=$CFG['site']['url'].'members/';
					break;
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/rss/')
				{
					$relativeUrl=$CFG['site']['url'].'rss/';
					break;
				}
				if($CFG['site']['relative_url']==$CFG['site']['url'].$mod.'/admin/')
				{
					$relativeUrl=$CFG['site']['url'].'admin/';
					break;
				}

			}
		$siteUrl=$CFG['site']['url'];
		}
		if(!$relativeUrl)
		{
			$relativeUrl=$CFG['site']['relative_url'];
			$siteUrl=$CFG['site']['url'];
		}
		switch($change)
			{
				case 'current':
						if($CFG['feature']['rewrite_mode']=='htaccess')
							return $relativeUrl.$htaccess;
						else
							return $relativeUrl.$normal;
					break;

				case 'root':
						if($CFG['feature']['rewrite_mode']=='htaccess')
							return $siteUrl.$htaccess;
						else
							return $siteUrl.$normal;
					break;

				case 'members':
						if($CFG['feature']['rewrite_mode']=='htaccess')
							return $siteUrl.'members/'.$htaccess;
						else
							return $siteUrl.'members/'.$normal;
					break;

				case 'admin':
						if($CFG['feature']['rewrite_mode']=='htaccess')
							return $siteUrl.'admin/'.$htaccess;
						else
							return $siteUrl.'admin/'.$normal;
					break;

				case 'nothing':
						if($CFG['feature']['rewrite_mode']=='htaccess')
							return $htaccess;
						else
							return $normal;
					break;
			}
	}

function getCurrentUrl($with_query_string = false)
	{
		global $CFG;
		$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		if(!$with_query_string)
			{
				if(strpos($url, '?'))
					$url = substr($url, 0, strpos($url, '?'));
				if(strpos($url, '.php'))
					$url = substr($url, 0, strpos($url, '.php')+4);
				//$url = $CFG['site']['relative_url'].$CFG['site']['script_name'];
			}
		return $url;
	}

function getQueryString($url)
	{
		if(strpos($url, '?'))
			$url = substr($url, strpos($url, '?'));
		if(strpos($url, '.php'))
			$url = substr($url, strpos($url, '.php')+4);

		return $url;
	}

/**
 * to control the module
 *
 * @access	public
 * @param	array	module list
 * @return	boolean
 */
function chkAllowedModule($module_arr = array())
	{
		global $CFG;
		foreach($module_arr as $key=>$value)
			{
				if(!isset($CFG['admin']['module'][$value]) or
					!$CFG['admin']['module'][$value])
					return false;
			}
		return true;
	}

/**
 * to check member logged in or not
 *
 * @access	public
 * @param
 * @return	boolean
 */
function isMember()
	{
		if(isset($_SESSION['user']['user_id']) and $_SESSION['user']['user_id'])
			return true;
		return false;
	}

function ispaidmember(){
	if(isset($_SESSION['user']['is_paid_member']) and $_SESSION['user']['is_paid_member']=='Yes')
			return true;
		return false;
}

function chkAndUpdatePaidMember(){
	global $db;
	global $CFG;
	$sql = 'SELECT is_paid_member FROM '.$CFG['db']['tbl']['users'].' WHERE user_id ='.$db->Param('user_id');
	$stmt = $db->Prepare($sql);
	$rs = $db->Execute($stmt, array($CFG['user']['user_id']));
	if (!$rs)
		trigger_db_error($db);

	if($row = $rs->FetchRow())
	{
		$_SESSION['user']['is_paid_member']=$row['is_paid_member'];
	}
}

/**
 * to check admin logged in or not
 *
 * @access	public
 * @param
 * @return	boolean
 */
function isAdmin()
	{
		if((isset($_SESSION['user']['user_id']) and $_SESSION['user']['user_id']) and (isset($_SESSION['admin']['is_logged_in']) and $_SESSION['admin']['is_logged_in']))
			return true;
		return false;
	}

/**
 * to check display the block for particular pages
 *
 * @access	public
 * @param	array	pages list
 * @param	boolean	make functionality to reverse
 * @return	boolean
 */
function displayBlock($allowed_pages = array(), $reverse = false)
	{
		global $CFG;
		if($allowed_pages and in_array('index.php', $allowed_pages) and !$reverse)
			$allowed_pages=array_merge($CFG['site']['side_menu_showing_pages'],$allowed_pages);

		$REQUEST_UNAME = (isset($_REQUEST['uname']))?($_REQUEST['uname']):(isset($CFG['user']['user_name'])?$CFG['user']['user_name']:'');
		$script_name = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], '/')+1);

		if(!$reverse)
			{
				if(in_array($script_name, $allowed_pages))
					return true;
				return false;
			}
		else
			{
				if(!in_array($script_name, $allowed_pages))
					return true;
				return false;
			}
	}

/**
 * to change the url and email to clickable from given text
 *
 * @access	public
 * @param	string
 * @return	string
 */
function makeClickableLinks($text)
	{
		$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
		$ret = ' ' . $text;
		$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
		$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"" target=\"_blank\">\\2</a>", $ret);
		$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
		$ret = substr($ret, 1);
		return $ret;
	}

/**
 * to connect the db
 *
 * @access	public
 * @param
 * @return	static
 */
function dbConnect()
	{
		global $db;
		global $CFG;
		$db->Connect($CFG['db']['hostname'], $CFG['db']['username'], $CFG['db']['password'], $CFG['db']['name']);
		if (!$db)
				trigger_error('DB Connection Error', E_USER_ERROR);
	}
/**
 * to disconnect the db
 *
 * @access	public
 * @param
 * @return	static
 */
function dbDisconnect()
	{
		global $db;
		global $CFG;
		$db->Disconnect();
	}

function getUserDisplayName($user_fields_arr)
	{
		global $CFG;
		$user_fields_arr['user_name'] = isset($user_fields_arr['user_name'])?$user_fields_arr['user_name']:'';
		$user_fields_arr['first_name'] = isset($user_fields_arr['first_name'])?$user_fields_arr['first_name']:'';
		$user_fields_arr['middle_name'] = isset($user_fields_arr['middle_name'])?$user_fields_arr['middle_name']:'';
		$user_fields_arr['last_name'] = isset($user_fields_arr['last_name'])?$user_fields_arr['last_name']:'';

		$display_name = $CFG['username']['display_format'];
		$display_name = str_replace('{first_name}', $user_fields_arr['first_name'], $display_name);
		$display_name = str_replace('{middle_name}', $user_fields_arr['middle_name'], $display_name);
		$display_name = str_replace('{last_name}', $user_fields_arr['last_name'], $display_name);
		$display_name = str_replace('{user_name}', $user_fields_arr['user_name'], $display_name);
		return trim($display_name);
	}

function populateRichTextEdit($field_name='', $value='', $useHtmlSpChars = true)
		{
			global $CFG;
			global $LANG;
			$param = 'framework_page';
			$_SESSION[$param] = urlencode($value);
?>
	<script language="JavaScript" type="text/javascript" src="<?php echo $CFG['site']['url'];?>js/lib/richtext/richtext.js"></script>
	<script language="JavaScript" type="text/javascript">
		var palette_url = '<?php echo $CFG['site']['url'].'js/lib/richtext/palette.htm';?>';
		var field_name = '<?php echo $field_name;?>';
		var filenameNew = "<?php echo $CFG['site']['url'];?>richText.php?htmSpChar=<?php echo $useHtmlSpChars?1:0;?>&source=<?php echo $param;?>";
		function submitForm() {
			updateRTE('rte1');
			alert("rte1 = " + document.RTEDemo.rte1.value);
			return false;
		}
		initRTE("<?php echo $CFG['site']['url'];?>js/lib/richtext/icons/", "<?php echo $CFG['site']['url'];?>js/lib/richtext/", "");
	</script>
	<noscript><p><b><?php echo $LANG['javascript_enabled'];?></b></p></noscript>
	<script language="JavaScript" type="text/javascript">
		if(!b.isFirefox())
			{
				writeRichText('rte1', '', 400, 200, true, false);
			}
	</script>
	<?php
		if ($useHtmlSpChars)
		    {
		        $value = htmlspecialchars($value);
		    }
	?>
	<input type="hidden" id="<?php echo $field_name;?>" name="<?php echo $field_name;?>" value="<?php echo ($value);?>" />
	<script language="JavaScript" type="text/javascript">
		if(b.isFirefox())
			{
				writeRichText('rte1', '', 400, 200, true, false);
			}
	</script>
<?php
		}

	function populateWYSIWYGeditor($field_name)
		{
			global $CFG;
			global $LANG;
			if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'opera'))
				return;
?>
	 <script language="JavaScript" type="text/javascript" src="<?php echo $CFG['site']['url'];?>js/lib/wysiwyg/wysiwyg.js"></script>
	  <script language="javascript" type="text/javascript">
	  	generate_wysiwyg('<?php echo $field_name;?>');
	  </script>
<?php
		}


	function populateTinyMceEditor($field_name='', $value='')
		{
				global $CFG;
				global $LANG;
	?>

		<script type="text/javascript" src="<?php echo $CFG['site']['url'];?>js/lib/tinymce/tiny_mce.js"></script>
		<script type="text/javascript">

		tinyMCE.init({
			// General options
			mode : "exact",
			elements: "<?php echo $field_name; ?>",
			theme : "advanced",//"advanced", "simple"
			plugins : "safari,spellchecker,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,ltr,rtl",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,|,visualchars,nonbreaking,blockquote,|,forecolor,backcolor,|,print,|,fullscreen",

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "none",
			width: "100%",
			height : "370",
			theme_advanced_resizing_min_height : 370,
			theme_advanced_resizing_max_height : 500,
			use_native_selects : true,
			convert_urls : false,
   			remove_script_host : false,
			//relative_urls : false,
			//theme_advanced_resizing : true,
			spellchecker_languages : "+English=en",
			tab_focus : ':prev,:next',
			//auto_resize: true
			cleanup_on_startup : true

			// Replace values for the template plugin
			/*template_replace_values : {
				username : "Some User",
				staffid : "991234"
			}*/
		});
		</script>
		<div id="desc_textarea"><textarea name="<?php echo $field_name; ?>"><?php echo $value; ?></textarea></div>
		<noscript><p><b><?php echo $LANG['javascript_enabled'];?></b></p></noscript>

	<?php
		}

	function populateSimpleTinyMceEditor($field_name='', $value='')
		{
				global $CFG;
				global $LANG;
	?>

		<script type="text/javascript" src="<?php echo $CFG['site']['url'];?>js/lib/tinymce/tiny_mce.js"></script>
		<script type="text/javascript">

		tinyMCE.init({
			// General options
			mode : "exact",
			elements: "<?php echo $field_name; ?>",
			theme : "advanced",//"advanced", "simple"
			plugins : "safari,advlink,emotions,inlinepopups,noneditable,xhtmlxtras",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,undo,redo,cleanup,|,styleselect,formatselect,fontselect,fontsizeselect,",
			theme_advanced_buttons2 : "bullist,numlist,|,justifyleft,justifycenter,justifyright,justifyfull,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,|,link,unlink,|,forecolor,|,code",
			theme_advanced_buttons3 : false,
			theme_advanced_buttons4 : false,

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "none",
			width: "100%",
			height : "370",
			theme_advanced_resizing_min_height : 370,
			theme_advanced_resizing_max_height : 500,
			use_native_selects : true,
			convert_urls : false,
   			remove_script_host : false,
			//relative_urls : false,
			//theme_advanced_resizing : true,
			//auto_resize: true
			cleanup_on_startup : true

			// Replace values for the template plugin
			/*template_replace_values : {
				username : "Some User",
				staffid : "991234"
			}*/
		});
		</script>
		<div id="desc_textarea"><textarea name="<?php echo $field_name; ?>"><?php echo $value; ?></textarea></div>
		<noscript><p><b><?php echo $LANG['javascript_enabled'];?></b></p></noscript>

	<?php
		}


	function writeLog($file_name, $data)
		{
			global $CFG;
			if($CFG['feature']['log'])
				{
					chkAndCreateFolder($CFG['site']['project_path'].'files/logs/');
					$path = $CFG['site']['project_path'].'files/logs/'.$file_name;
					$seperator = "\n--------------------------------------------------------------------\n\n";
					$data = date('Y-m-d H:i:s')."\n.....................\n".$data.$seperator;
					write_file($path, $data, 'a+');
				}
		}

	function isMemberShipValid($date)
		{
			global $db, $CFG;

			if(!$CFG['feature']['signup_payment'])
				return true;

			$sql = 'SELECT NOW()<\''.$date.'\' AS date_diff';

			$stmt = $db->Prepare($sql);
			$rs = $db->Execute($stmt);
			    if (!$rs)
				    trigger_db_error($db);

			$row = $rs->FetchRow();
			return $row['date_diff'];
		}

	function to7bit($text)
		{
			global $CFG;

			$text = mb_convert_encoding($text,'HTML-ENTITIES',$CFG['site']['charset']);
			$text = preg_replace( array('/&szlig;/','/&(..)lig;/', '/&([aouAOU])uml;/','/&(.)[^;]*;/'), array('ss',"$1","$1".'e',"$1"), $text);
			return $text;
		}

	function getUrlTitle($text)
		{
			$text = to7bit($text);
			$text = ereg_replace ('[^a-zA-Z0-9]', '_', $text);
			return $text;
		}

	function setMetaKeywords($keywords)
		{
			global $LANG,$CFG;

			$currentPage = strtolower($CFG['html']['current_script_name']);

			if(isset($LANG['header_meta_'.$currentPage.'_keywords']))
				{
					$LANG['header_meta_'.$currentPage.'_keywords'] .= ', '.$keywords ;
					return;
				}
			$LANG['header_meta_'.$currentPage.'_keywords'] = $keywords ;
			return;
		}

	function setMetaDescription($description)
		{
			global $LANG,$CFG;

			$currentPage = strtolower($CFG['html']['current_script_name']);

			if(isset($LANG['header_meta_'.$currentPage.'_description']))
				{
					$LANG['header_meta_'.$currentPage.'_description'] .= ' '.$description ;
					return;
				}
			$LANG['header_meta_'.$currentPage.'_description'] = $description ;
			return;
		}

	function setPageTitle($title)
		{
			global $LANG,$CFG;

			$currentPage = strtolower($CFG['html']['current_script_name']);

			if(isset($LANG['header_meta_'.$currentPage.'_title']))
				{
					$LANG['header_meta_'.$currentPage.'_title'] = $title ;
					return;
				}
			$LANG['header_meta_'.$currentPage.'_title'] = $title ;
			return;
		}

	function regSupportText($text)
		{
			$not_su = array('(', ')', '{', '}', '[', ']', '>', '<', '$', '^');
			foreach($not_su as $value)
				{
					if(strstr($text, $value))
						{
							return false;
						}
				}
			return true;
		}


	function getInitialFilterLink()
		{
			global $CFG;
			global $LANG;

			$url = $CFG['site']['url'].'members/changeContentFilterStatus.php';
			$method_type = 'post';

			$onlink = '<a href="#" onClick="return chnageContentFilter(\''.$url.'\', \'status=On\', \''.$method_type.'\')">'.$LANG['header_off_link'].'</a>';
			$onlink_non_member = '<a href="'.getUrl('profilesettings', '', '', 'members').'">'.$LANG['header_on_link'].'</a>';
			$offlink_non_member = '<a href="'.getUrl('profilesettings', '', '', 'members').'">'.$LANG['header_off_link'].'</a>';
			$offlink = '<a href="#" onClick="return chnageContentFilter(\''.$url.'\', \'status=Off\', \''.$method_type.'\')">'.$LANG['header_on_link'].'</a>';

			if (!chkAllowedModule(array('content_filter')))
				return '';

			if($CFG['admin']['is_logged_in'])
				{
					if($CFG['user']['content_filter'] == 'Off')
						return $onlink;
					else if($CFG['user']['content_filter'] == 'On')
						return $offlink;
					return;
				}

			if(isAdultUser('allow'))
				{
					if(isset($CFG['admin']['videos']['adult_content_view'])
						and $CFG['admin']['videos']['adult_content_view']=='No')
						{
							return $LANG['header_on_link'];
						}
					else
						{
							if($CFG['user']['content_filter'] == 'Off')
								{
									if(isMember())
										return $onlink;
									else
										return $onlink_non_member;
								}
							else if($CFG['user']['content_filter'] == 'On')
								{
									if(isMember())
										return $onlink;
									else
										return $onlink_non_member;
								}
							else if(isset($CFG['admin']['videos']['adult_content_view'])
								and $CFG['admin']['videos']['adult_content_view']!='No')
								{
									if(isMember())
										return $onlink;
									else
										return $onlink_non_member;
								}
						}
				}
			else
				{
					if(isset($CFG['admin']['videos']['adult_content_view'])
						and $CFG['admin']['videos']['adult_content_view']=='No')
						{
							return $LANG['header_on_link'];
						}
					else
						{
							if(isMember())
								{
									return $LANG['header_on_link'];
								}
							else
								{
									return $onlink_non_member;
								}
						}
				}
		}

	function searchJavaScriptCode()
		{
?>
<script type="text/javascript">
function changeAction(){
	var obj = document.formCommonSearch;
	var act_url = '';
	if(obj.tags.value=='')
		return false;
	switch (obj.soption.value){
		case 'videos':
			act_url = '<?php echo getUrl('videolist', '?pg=videonew&tags=', 'videonew/?tags=');?>';
			obj.action = act_url+obj.tags.value;
			return true;
			break;

		case 'members':
			act_url = '<?php echo getUrl('memberslist', '?tags=', '?tags=');?>';
			obj.action = act_url + obj.tags.value;
			return true;

		default:
			return false;
			break;
	}
}
function changeActionSub(){
	var obj = document.formCommonSearchSub;
	var act_url = '';
	if(obj.tagsSub.value=='')
		return false;
	switch (obj.soptionSub.value){
		case 'videos':
			act_url = '<?php echo getUrl('videolist', '?pg=videonew&tags=', 'videonew/?tags=');?>';
			act_url = act_url+obj.tagsSub.value;
			act_url = act_url+'&cid='+obj.catIdSub.value;
			obj.action = act_url;
			return true;
			break;

		case 'members':
			act_url = '<?php echo getUrl('memberslist', '?tags=', '?tags=');?>';
			act_url = act_url + obj.tagsSub.value;
			obj.action = act_url;
			return true;

		default:
			

Dani AI

Generated

This thread shows a huge, mixed PHP/HTML file and a single-line error report (line 3462). As other replies noted ( flagged a missing-brace suspicion; and asked for the actual error and only the relevant snippet), the fastest way to fix this is to get the precise parser message and inspect a small window of source around the reported line. Parse errors are nearly always caused by syntax earlier in the file, not necessarily exactly on the reported line.

Helpful, repeatable diagnosis steps (run on the server/working copy):

php -l filename.php
nl -ba filename.php | sed -n '3455,3475p'    # show ~10 lines around the reported line

Common culprits to look for: a missing semicolon on the preceding line, unbalanced quotes or heredoc/nowdoc blocks, an unterminated string or regex, an extra or missing }/) (order matters even when counts match), a stray ?> followed by PHP code without <?php, or a UTF-8 BOM at the start of the file. If php -l reports "unexpected end of file", there is almost always an unclosed brace or unclosed string earlier.

Quick fixes and safety notes:

  • Temporarily enable full errors for diagnosis (do not leave enabled on production):
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
  • Search included files (parse problems can come from an included file). Use an editor or IDE with PHP parsing or run incremental php -l on parts if necessary.
  • To avoid problems when mixing HTML/PHP, minimize switching between PHP open/close tags and prefer keeping pure-PHP files without a closing ?> at EOF.

Most helpful info when requesting help: the exact php error message text plus ~10 lines before and after the reported line.

Recommended Answers

All 7 Replies

Are you serious?

i am sorry please help me!

I wonder how much database space this thread just wasted?
What exactly is your problem?

LMAO.
Perhaps a mod can replace line 2 .. 3461 with [a lot of irrelevant code that misses one curly bracket] ?
, your code misses a curly bracket :)

Edit: actually, there are equally as many { as } , what error do you get?

Hope that was the issue lol epic code posting holy hell :D

Post error and relevant codes not everything!

Member Avatar for Member #120589

:) This guy takes the biscuit. In fact he takes a whole pallet full of them.

commented: Now i know how you got so many solved threads. lol +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.