Location: PHPKode > projects > Basic Announce > Basic Announce Version 4.0/inc/functions.inc.php
<?php

/**
 * 	Returns time difference
 * 		@param first_time
 * 		@param last_time
 **/
function time_diff($last_time, $first_time)
{
	// convert to unix timestamps
	$time_diff=strtotime($last_time)-strtotime($first_time);	
	return $time_diff;
}

/**
 * 	Creates a random string with characters 1-10 and a-z
 * 		@param length - the length of the random string 	
 **/
function random_string($length = 10)
{
	$rand_string = "";
	for ($i = 0; $i < $length; $i++) {
		$x = mt_rand(0, 35);
		if ($x > 9) $rand_string .= chr($x + 87);
		else $rand_string .= $x;
	}
	return $rand_string;
}

/**
 * 	Returns IP Address
 */
function get_ip_address()
{
	$ip_address = "";
	if(isset($_SERVER['HTTP_X_FORWARD_FOR'])){
		$ip_address = $_SERVER['HTTP_X_FORWARD_FOR'];
	}else if(isset($_SERVER['REMOTE_ADDR'])){
		$ip_address = $_SERVER['REMOTE_ADDR'];
	}
	return $ip_address;
}

/**
 * Get Site Settings
 */
function get_site_settings()
{
    global $db;
    $site_settings = array("rank_google"=>"", "rank_alexa"=>"", "rank_last_updated"=>"");
    $sql = "SELECT
                ".TABLE_SETTINGS.".*,
                DATE_FORMAT(".TABLE_SETTINGS.".rank_last_updated, '%b %d, %Y') as my_rank_last_updated
            FROM ".TABLE_SETTINGS;        
    $db->Query($sql);        
    if($r__ = $db->FetchAssoc()){
        $site_settings['rank_google'] = $r__['rank_google'];
        $site_settings['rank_alexa'] = $r__['rank_alexa'];
        $site_settings['rank_last_updated'] = $r__['my_rank_last_updated'];
    }
    return $site_settings;
}

/**
 * Set Site Settings
 */
function set_site_settings($fields = array())
{
    global $db;
    $sql = "UPDATE ".TABLE_SETTINGS." SET ";
	$fields_count = 0;
	$total_fields = count($fields);
	foreach($fields as $key => $val){
		$fields_count++;
		$sql .= $key." = '".trim($val)."'";
		if($fields_count < $total_fields) $sql .= ", ";	 		
	}
    if($db->Exec($sql)) return true;
    else return false;    
}

/**
 * Get alexa Rank
 *      @param $domain
 */
function get_alexa_rank($domain)
{
    preg_match('#<POPULARITY URL="(.*?)" TEXT="([0-9]+){1,}"/>#si', file_get_contents('http://data.alexa.com/data?cli=10&dat=s&url='.$domain), $p);
    return (isset($p[2])) ? (int)$p[2] :0;
}

//--------------------------------------------------------------------------
//-- Get Google Rank
//www.lampdeveloper.co.uk/
/*
 * convert a string to a 32-bit integer
 */
function StrToNum($Str, $Check, $Magic)
{
    $Int32Unit = 4294967296;  // 2^32

    $length = strlen($Str);
    for ($i = 0; $i < $length; $i++) {
        $Check *= $Magic; 	
        //If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), 
        //  the result of converting to integer is undefined
        //  refer to http://www.php.net/manual/en/language.types.integer.php
        if ($Check >= $Int32Unit) {
            $Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
            //if the check less than -2^31
            $Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
        }
        $Check += ord($Str{$i}); 
    }
    return $Check;
}

/** 
 * Genearate a hash for a url
 */
function HashURL($String)
{
    $Check1 = StrToNum($String, 0x1505, 0x21);
    $Check2 = StrToNum($String, 0, 0x1003F);

    $Check1 >>= 2; 	
    $Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
    $Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
    $Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);	
    
    $T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
    $T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
    
    return ($T1 | $T2);
}

/**
 * genearate a checksum for the hash string
 */
function CheckHash($Hashnum)
{
    $CheckByte = 0;
    $Flag = 0;

    $HashStr = sprintf('%u', $Hashnum) ;
    $length = strlen($HashStr);
    
    for ($i = $length - 1;  $i >= 0;  $i --) {
        $Re = $HashStr{$i};
        if (1 === ($Flag % 2)) {              
            $Re += $Re;     
            $Re = (int)($Re / 10) + ($Re % 10);
        }
        $CheckByte += $Re;
        $Flag ++;	
    }

    $CheckByte %= 10;
    if (0 !== $CheckByte) {
        $CheckByte = 10 - $CheckByte;
        if (1 === ($Flag % 2) ) {
            if (1 === ($CheckByte % 2)) {
                $CheckByte += 9;
            }
            $CheckByte >>= 1;
        }
    }

    return '7'.$CheckByte.$HashStr;
}

/**
 * Get Google Rank
 */
function get_google_rank($url)
{
    $pagerank = "-1";
    
    $fp = fsockopen("toolbarqueries.google.com", 80, $errno, $errstr, 30);
    if (!$fp) {
       //echo "$errstr ($errno)<br />\n";
    } else {
        $out = "GET /search?client=navclient-auto&ch=".CheckHash(HashURL($url))."&features=Rank&q=info:".$url."&num=100&filter=0 HTTP/1.1\r\n";
        $out .= "Host: toolbarqueries.google.com\r\n";
        $out .= "User-Agent: Mozilla/4.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)\r\n";
        $out .= "Connection: Close\r\n\r\n";
    
       fwrite($fp, $out);
       
       while (!feof($fp)) {
        $data = fgets($fp, 128);
        $pos = strpos($data, "Rank_");
        if($pos === false){} else{
            $pagerank = substr($data, $pos + 9);
        }
       }
       fclose($fp);           
    }
    return $pagerank;    
}

/**
 * Set brobser definitions
 */
function set_browser_definitions()
{
    $bd = array();
    
    $agent = $_SERVER['HTTP_USER_AGENT'];
    // initialize properties
    $bd['platform'] = "Windows";
    $bd['browser'] = "MSIE";
    $bd['version'] = "6.0";    
      
    // find operating system
    if (preg_match("/win/i", $agent))       $bd['platform'] = "Windows";
    elseif (preg_match("/mac/i", $agent))   $bd['platform'] = "MacIntosh";
    elseif (preg_match("/linux/i", $agent)) $bd['platform'] = "Linux";
    elseif (preg_match("/OS\/2/i", $agent))  $bd['platform'] = "OS/2";
    elseif (preg_match("/BeOS/i", $agent))  $bd['platform'] = "BeOS";
    
    // test for Opera
    if (preg_match("/opera/i",$agent)){
        $val = stristr($agent, "opera");
        if (preg_match("/\//i", $val)){
            $val = explode("/",$val); $bd['browser'] = $val[0]; $val = explode(" ",$val[1]); $bd['version'] = $val[0];
        }else{
            $val = explode(" ",stristr($val,"opera")); $bd['browser'] = $val[0]; $bd['version'] = $val[1];
        }
    // test for MS Internet Explorer version 1
    }elseif(preg_match("/microsoft internet explorer/i", $agent)){
        $bd['browser'] = "MSIE"; $bd['version'] = "1.0"; $var = stristr($agent, "/");
        if (preg_match("/308|425|426|474|0b1/i", $var)) $bd['version'] = "1.5";
    // test for MS Internet Explorer
    }elseif(preg_match("/msie/i",$agent) && !preg_match("/opera/i",$agent)){
        $val = explode(" ",stristr($agent,"msie")); $bd['browser'] = $val[0]; $bd['version'] = $val[1];
    // test for MS Pocket Internet Explorer
    }elseif(preg_match("/mspie/i",$agent) || preg_match("/pocket/i", $agent)){
        $val = explode(" ",stristr($agent,"mspie")); $bd['browser'] = "MSPIE"; $bd['platform'] = "WindowsCE";
        if (preg_match("/mspie/i", $agent))
            $bd['version'] = $val[1];
        else {
            $val = explode("/",$agent);     $bd['version'] = $val[1];
        }
    // test for Firebird
    }elseif(preg_match("/firebird/i", $agent)){
        $bd['browser']="Firebird"; $val = stristr($agent, "Firebird"); $val = explode("/",$val); $bd['version'] = $val[1];
    // test for Firefox
    }elseif(preg_match("/Firefox/i", $agent)){
        $bd['browser']="Firefox"; $val = stristr($agent, "Firefox"); $val = explode("/",$val); $bd['version'] = $val[1];
    // test for Mozilla Alpha/Beta Versions
    }elseif(preg_match("/mozilla/i",$agent) && preg_match("/rv:[0-9].[0-9][a-b]/i",$agent) && !preg_match("/netscape/i",$agent)){
        $bd['browser'] = "Mozilla"; $val = explode(" ",stristr($agent,"rv:")); preg_match("/rv:[0-9].[0-9][a-b]/i",$agent,$val); $bd['version'] = str_replace("rv:","",$val[0]);
    // test for Mozilla Stable Versions
    }elseif(preg_match("/mozilla/i",$agent) && preg_match("/rv:[0-9]\.[0-9]/i",$agent) && !preg_match("/netscape/i",$agent)){
        $bd['browser'] = "Mozilla"; $val = explode(" ",stristr($agent,"rv:")); preg_match("/rv:[0-9]\.[0-9]\.[0-9]/i",$agent,$val); $bd['version'] = str_replace("rv:","",$val[0]);
    // remaining two tests are for Netscape
    }elseif(preg_match("/netscape/i",$agent)){
        $val = explode(" ",stristr($agent,"netscape")); $val = explode("/",$val[0]); $bd['browser'] = $val[0]; $bd['version'] = $val[1];
    }elseif(preg_match("/mozilla/i",$agent) && !preg_match("/rv:[0-9]\.[0-9]\.[0-9]/i",$agent)){
        $val = explode(" ",stristr($agent,"mozilla")); $val = explode("/",$val[0]); $bd['browser'] = "Netscape"; $bd['version'] = $val[1];
    }
    // clean up extraneous garbage that may be in the name
    $bd['browser'] = preg_replace("/[^a-z,A-Z]/", "", $bd['browser']);
    $bd['version'] = preg_replace("/[^0-9,.,a-z,A-Z]/", "", $bd['version']);
    
    return $bd;
}

/**
 * Check bad characters
 *      @param $str_words
 */
function check_bad_chars($str_words)
{
    $bad_string = array("select", "drop", ";", "--", "insert","delete", "xp_", "%20union%20", "/*", "*/union/*", "+union+", "load_file", "outfile", "document.cookie", "onmouse", "<script", "<iframe", "<applet", "<meta", "<style", "<form", "<img", "<body", "<link", "_GLOBALS", "_REQUEST", "_GET", "_POST", "include_path", "prefix", "http://", "https://", "ftp://", "smb://", "onmouseover=", "onmouseout=");
    for($i = 0; $i < count($bad_string); $i++){
        if(strstr($bad_string[$i], $str_words)){
            return false;
        }
    }
    return true;
}

/**
 * Remove bad characters
 *      @param $str_words
 *      @param $level
 */
function remove_bad_chars($str_words, $level = "high")
{
    if($level == "high"){
        $bad_string = array("select", "drop", ";", "--", "insert", "delete", "xp_", "%20union%20", "/*", "*/union/*", "+union+", "load_file", "outfile", "document.cookie", "onmouse", "<script", "<iframe", "<applet", "<meta", "<style", "<form", "<img", "<body", "<link", "_GLOBALS", "_REQUEST", "_GET", "_POST", "include_path", "prefix", "http://", "https://", "ftp://", "smb://", "onmouseover=", "onmouseout=");            
    }else if($level = "medium"){
        $bad_string = array("select", "drop", "insert", "delete", "xp_", "%20union%20", "/*", "*/union/*", "+union+", "load_file", "outfile", "document.cookie", "onmouse", "<script", "<iframe", "<applet", "<meta", "<style", "<form", "<img", "<body", "<link", "_GLOBALS", "_REQUEST", "_GET", "_POST", "include_path", "prefix", "http://", "https://", "ftp://", "smb://", "onmouseover=", "onmouseout=");                        
    }else{
        $bad_string = array("<script", "<iframe", "<applet");
    }
    for($i = 0; $i < count($bad_string); $i++){
        $str_words = str_replace($bad_string[$i], "", $str_words);
    }
    return $str_words;            
}

/**
 * Remove bad characters
 *      @param $str_words
 *      @param $level
 */
function strip_quotes($strWords)
{
    return str_replace("'", "''", $strWords);
}

/**
 * Read directory sub-folders
 *      @param $dir
 */
function read_directory_subfolders($dir = ".")
{
    $folder=dir($dir); 
    $arrFolderEntries = array();
    while($folderEntry=$folder->read()){ 
        if($folderEntry != '.' && $folderEntry != '..' && is_dir($dir.$folderEntry)) 
            $arrFolderEntries[] = $folderEntry; 
    }     
    $folder->close(); 
    return $arrFolderEntries;
}

/**
 *	Draws message
 *      @param $type - message type: normal|error|success
 *  	@param $message - message text
 *      @param $is_draw
 *      @param $width
 *      @param $dir
 *      @param $draw_sign
 */
function draw_message($type="normal", $message, $is_draw=true, $width="100%", $dir="", $draw_sign = true)
{        
    $output = "";        
    if($type == "success"){
        $table_class = "success_message_box";
        $message_sign = "success_sign.gif";
    }else if($type == "error"){
        $table_class = "important_message_box";
        $message_sign = "error_sign.gif";
    }else{
        $table_class = "message_box";
        $message_sign = "attention_sign.gif";
    }
    if (!empty($message)){
        $output .= "<table width='".$width."' align='center' class='".$table_class."' border='0'><tr>";
        if($draw_sign) $output .= "<td class='message_sign'><img align='center' src='".$dir."images/".$message_sign."' alt=''></td>";
        else "<td class='message_sign'></td>";
        $output .= "<td class='message_text'>".$message."</td></tr></table>";
    }
    if(!$is_draw) return $output;
    else echo $output;	
}    

/**
 *	Returns formated dataime by mask
 *      @param $datetime - datetime to be formated
 *  	@param $mask - datetime mask
 */
function my_date_format($datetime, $mask="M d, Y g:i A")
{       
    if($datetime != "" && $datetime != "0000-00-00 00:00:00" && $datetime != "Never"){
        $mktime = mktime(substr($datetime, 11, 2), substr($datetime, 14, 2),
                        substr($datetime, 17, 2), substr($datetime, 5, 2),
                        substr($datetime, 8, 2), substr($datetime, 0, 4));         
        return date($mask, $mktime);
    }else if($datetime == "Never"){
        return "Never";    
    } else {
        return "";    
    }        
}

/**
 *	Returns formated text
 *      @param $text
 */
function my_text_format($text)
{
	$text = nl2br($text);
	return $text;
}

/**
 *	Check if user has access right to certain page
 *      @script_name - script name
 */
function page_access_allowed($script_name = "", $page_id = "")
{
    $page_array = explode('/', $script_name);
    $page = $page_array[count($page_array) - 1]; 
    
    if(isset($_SESSION['adm_status']) && ($_SESSION['adm_status'] == "main admin")) return true;
    if($page != "" && isset($_SESSION['menu_access_list'])){
        if(array_key_exists($page, $_SESSION['menu_access_list'])){
            // check for page IDs (for user and admin)
            $page_ids = explode('-', $_SESSION['menu_access_list'][$page]);
            if($page_id != "" && !in_array($page_id, $page_ids)){
				return false;
			}				
            return true;
        }
    }
    return false;
}

/**
 *	Check if module installed
 *      @script_name - script name
 */
function module_istalled($module_name = "")
{
    global $MODULES;

    if(isset($MODULES[$module_name]) && ($MODULES[$module_name] == "1")) return true;
    else return false;
}

/**
 *	Redirect to another location
 *      @script_name - script name
 */
function redirect_to($script_name = "", $target = "document", $wait = "")
{
    if($script_name != ""){
		if($wait != ""){
			echo "<script type='text/javascript'>setTimeout(\"$target.location.href='$script_name'\", ".(int)$wait.");</script>";	
		}else{
			echo "<script type='text/javascript'>$target.location.href='$script_name';</script>";	
		}		
	}
    exit;
}

/**
 *	Transform header
 *      @header
 */
function transform_header($header = "")
{
    $output = "";
    $header = explode("_", $header);
    foreach($header as $val){
        $output .= (($output != "") ? " " : "").ucfirst($val);
    }
    return $output;
}

/**
 *  Get base URL 
 */
function get_base_url()
{
    $protocol = "http://";
    $port = "";
    $http_host = $_SERVER['HTTP_HOST'];
    if((isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != "off")) ||
        strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, 5)) == "https"){
        $protocol = "https://";
    }	
    if(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != "80"){
        if(!strpos($_SERVER['HTTP_HOST'], ":")){
            $port = ":".$_SERVER['SERVER_PORT'];
        }
    }	
    $folder = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1);	
    return $protocol.$port.$http_host.$folder;
}

/**
 *  Set time zone by offset
 */
function get_timezone_by_offset($offset) 
{ 
    $testTimestamp = time(); 
    date_default_timezone_set('UTC'); 
    $testLocaltime = localtime($testTimestamp,true); 
    $testHour = $testLocaltime['tm_hour'];        
      
    $abbrarray = timezone_abbreviations_list(); 
    foreach($abbrarray as $abbr){ 
        foreach($abbr as $city){
            if($city['timezone_id'] != ""){
                date_default_timezone_set($city['timezone_id']); 
                $testLocaltime  = localtime($testTimestamp,true); 
                $hour           = $testLocaltime['tm_hour'];        
                $testOffset     =  $hour - $testHour; 
                if($testOffset == $offset){
                    date_default_timezone_set('UTC'); 
                    return $city['timezone_id']; 
                } 
            }
        } 
    }
    return "UTC"; 
}

/**
 *  Return language constant
 *      @param $word
 */
function lang($word, $case_sensitive = true)
{
    global $arrLang;
    $word_temp = ($case_sensitive) ? $word : strtolower($word);
    if(isset($arrLang[$word_temp])){
        $output = $arrLang[$word_temp];
    }else{
        $word_parts = explode("_", $word);
        $output = implode(" ", $word_parts);
    }
    return $output;
}

/**
 *  Prepare input
 *      @param $input
 *      @param $validation_type
 *      @param $possible_values
 *      @param $level
 */
function prepare_input($input, $validation_type = "", $possible_values = "", $level = "medium")
{
    $output = "";
    if($level == "medium"){
        $output = strip_tags($input);
        //$output = str_replace(array("'", '"'), "", $input);
    }
    
    //$possible_values = array('([^0-9px])','([^0-9%])');
    //$with = array('');
    if($validation_type == "custom"){
        $output = preg_replace("/".$possible_values."/", '', $input);
    }
    
    #if(is_array($possible_values) && !empty($possible_values)){
    #    if(in_array($output)) return $output;
    #    else return "";
    #}
    return $output;
}

/**
 *  Returns breadcrumbs for defined page
 *      @param $page
 */
function page_breadcrumbs($page = "", $home = "home.php")
{
    global $db, $SETTINGS;
    $parent_link = $link = $mgid = "";
    
    if(!$SETTINGS['allow_breadcrumbs']) return "";
    
    if($page == ""){
        $file = $_SERVER["SCRIPT_NAME"];
        $break = explode('/', $file);
        $page = $break[count($break) - 1];
    }
    if(isset($db)){
        $sql = "SELECT
                    m1.name,
                    m1.parent_id,
                    m2.name as parent_name
                FROM ".TABLE_MENU." m1
                    LEFT OUTER JOIN ".TABLE_MENU." m2 ON m1.parent_id = m2.id
                WHERE m1.page_name = '".$page."'";
        $db->Query($sql);
        if($row = $db->FetchAssoc()){
            $link = $row['name'];
            $parent_link = $row['parent_name'];
            $mgid = $row['parent_id'];
        }
    }

    $output = "<table id='tblBreadcrumbs' width='100%' border='0' cellspacing='0' cellpadding='0'>
    <tr>
        <td><div class='section_title_".(($SETTINGS['language_dir'] == "rtl") ? "right" : "left")."'></div></td>
        <td width='100%' align='".(($SETTINGS['language_dir'] == "rtl") ? "right" : "left")."' class='breadcrumb'>
            <div class='section_title'><div class='section_title_text'>
                <a href='".$home."' title='".lang("home")."'><img src='../images/home.gif' style='width:12px; height:11px; margin-top:-3px;' /></a>";
				$parent_link_name = lang(str_replace(" ", "_", $parent_link), false);
                if($parent_link) $output .= " &raquo; <a href='menu_options_manager.php?mgid=".$mgid."' title='".$parent_link_name."'>".$parent_link_name."</a>";
                $link_name = lang(str_replace(" ", "_", $link), false);
				if($link) $output .= " &raquo; <a href='".$page."' title='".$link_name."'>".$link_name."</a>";
            $output .= "&nbsp;</div></div>
        </td>  
        <td><div class='section_title_".(($SETTINGS['language_dir'] == "rtl") ? "left" : "right")."'></div></td>
    </tr>
    </table>";
    
    return $output;
}

/**
 *  Send email 
 *      @param $type
 *      @param $rid
 */
function send_email($mail_to, $mail_from, $subject, $body, &$error_message = "")
{
	//error_reporting(E_ALL);
	//error_reporting(E_STRICT);
	global $SETTINGS;

	$mail = new PHPMailer();
	
    if($SETTINGS['mailer'] == "smtpmail"){
		
		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
												   // 1 = errors and messages
												   // 2 = messages only
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->Host       = $SETTINGS['smtp_address'];  // sets GMAIL as the SMTP server
		$mail->Port       = $SETTINGS['smtp_port'];     // set the SMTP port for the GMAIL server
		$mail->Username   = $SETTINGS['smtp_username']; // GMAIL username
		$mail->Password   = $SETTINGS['smtp_password']; // GMAIL password
		
		$mail->SetFrom($mail_from);                // $mail->SetFrom($mail_from, 'First Last');
		$mail->AddReplyTo($mail_to);               // $mail->AddReplyTo($mail_to, "First Last");
		$mail->AddAddress($mail_to);               // $mail->AddAddress($mail_to, "John Doe"); 

		$mail->Subject    = $subject;
		$mail->AltBody    = strip_tags($body);

		$body = str_replace("\\n", "", nl2br($body));
		$mail->MsgHTML($body);
		
	}else{
		
		$mail->SetFrom($mail_from);                // $mail->SetFrom($mail_from, 'First Last');
		$mail->AddReplyTo($mail_to);               // $mail->AddReplyTo($mail_to, "First Last");
		$mail->AddAddress($mail_to);               // $mail->AddAddress($mail_to, "John Doe"); 
		
		$mail->Subject    = $subject;
		$mail->AltBody    = strip_tags($body);
		
		$body = str_replace("\\n", "", nl2br($body));
		$mail->MsgHTML($body);
		
	}
	
	//$mail->AddAttachment("images/phpmailer.gif");      // attachment
	//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
	
	if(!$mail->Send()){
		$error_message = $mail->ErrorInfo;
		return false;
	}else{
		return true;
	}
}

  
/**
 *  Send email on account created
 *      @param $type
 *      @param $rid
 */
function send_email_on_account_created($type = "", $rid = "0", $password = "")
{
	global $db, $SETTINGS;
	
	if($type == "admins") $type = TABLE_ADMINS;
	else if($type == "users") $type = TABLE_USERS;
	else return false;
	
	$sql = "SELECT username, email, last_name, first_name FROM ".$type." WHERE id = ".(int)$rid;
	$db->Query($sql);
	if($row = $db->FetchArray()){		
		/////////////////////////////////////////////////////////////////
		$sql_template = "SELECT * FROM ".TABLE_EMAIL_TEMPLATES." WHERE template_name = 'account_created'";
		$db->Query($sql_template);
		if($row1 = @$db->FetchAssoc()){				  	
			$msg_title = $row1['template_subject'];
			$message = $row1['template_content'];
			$message = str_replace("%FIRST NAME%", $row['first_name'], $message);
			$message = str_replace("%LAST NAME%", $row['last_name'], $message);
			$message = str_replace("%USER NAME%", $row['username'], $message);
			$message = str_replace("%USER PASSWORD%", $password, $message);
			$message = str_replace("%WEB SITE%", $SETTINGS['site_address'], $message);
		
			$result = send_email($row['email'], $SETTINGS['admin_email'], $msg_title, $message);
		}
		/////////////////////////////////////////////////////////////////
	}
	return true;
}

/**
 *  Send email on changed password 
 *      @param $type
 *      @param $rid
 *      @param $old_password
 */
function send_email_on_password_changed($type = "", $rid = "0", $old_password = "")
{
	global $db, $SETTINGS;
	
	if($old_password == "") return false;
	if($type == "admins") $type = TABLE_ADMINS;
	else if($type == "users") $type = TABLE_USERS;
	else return false;	
	
	// check if password was changed old password
	if($SETTINGS['passwords_encryption']){
		if($SETTINGS['passwords_encryption_type'] == "AES"){
			$password = "AES_DECRYPT(password, '".$SETTINGS['passwords_encrypt_key']."') as decoded_password";				
		}else{
			$pswd_prefix = ((strtolower($SETTINGS['passwords_encryption_type']) == "md5") ? "sp" : "rp");
			$password_new = isset($_POST[$pswd_prefix.'ypassword']) ? $_POST[$pswd_prefix.'ypassword'] : "";
			$password = "'".$password_new."' as decoded_password";
		}
	}else{
		$password = "password as decoded_password";
	}				
	$sql = "SELECT username, email, last_name, first_name, password, ".$password." FROM ".$type." WHERE id = ".(int)$rid;
	$db->Query($sql);
	if($row = $db->FetchArray()){
		if($old_password != $row['password']){
			/////////////////////////////////////////////////////////////////
			$sql_template = "SELECT * FROM ".TABLE_EMAIL_TEMPLATES." WHERE template_name = 'password_changed'";
			$db->Query($sql_template);
			if($row1 = @$db->FetchAssoc()){				  	
				$msg_title = $row1['template_subject'];
				$message = $row1['template_content'];
				$message = str_replace("%FIRST NAME%", $row['first_name'], $message);
				$message = str_replace("%LAST NAME%", $row['last_name'], $message);
				$message = str_replace("%USER NAME%", $row['username'], $message);
				$message = str_replace("%USER PASSWORD%", $row['decoded_password'], $message);
				$message = str_replace("%WEB SITE%", $SETTINGS['site_address'], $message);
				
				$result = send_email($row['email'], $SETTINGS['admin_email'], $msg_title, $message);				
			}
			/////////////////////////////////////////////////////////////////
		}
	}
	return true;
}

/**
 *  Get language abbraviation for jsafv
 *  	@param $filename
 */
function get_lang_abbr_for_jsafv($lang)
{
	$return_abbrv = "en";
	switch($lang){
		case "de":
			$return_abbrv = "de"; break;
		case "es":
			$return_abbrv = "es"; break;
		case "fr":
			$return_abbrv = "fr"; break;
		case "it": 
			$return_abbrv = "it"; break;
		case "ja_utf8":
			$return_abbrv = "ja"; break;
		case "en":
		default:
			$return_abbrv = "en"; break;
	}
	return $return_abbrv;
}

/**
 *  Get include file content
 *  	@param $filename
 */
function get_include_contents($filename)
{
    //if(is_file($filename)){
	if($filename != ""){
        ob_start();
        include $filename;
        return ob_get_clean();
    }
    return false;
}

/**
 *	Get encoded text
 *		@param $string
 **/
function encode_text($string = "")
{
	$search	 = array("\\","\0","\n","\r","\x1a","'",'"',"\'",'\"');
	$replace = array("\\\\","\\0","\\n","\\r","\Z","\'",'\"',"\\'",'\\"');
	return str_replace($search, $replace, $string);
}

/**
 *	Get decoded text
 *		@param $string
 **/
function decode_text($string = "", $code_quotes = true, $quotes_type = "")
{
	$single_quote = "'";
	$double_quote = '"';		
	if($code_quotes){
		if(!$quotes_type){
			$single_quote = "&#039;";
			$double_quote = "&#034;";
		}else if($quotes_type == "single"){
			$single_quote = "&#039;";
		}else if($quotes_type == "double"){
			$double_quote = "&#034;";
		}
	}
	
	$search  = array("\\\\","\\0","\\n","\\r","\Z","\\'",'\\"','"',"'");
	$replace = array("\\","\0","\n","\r","\x1a","\'",'\"',$double_quote,$single_quote);
	return str_replace($search, $replace, $string);
}

?>
Return current item: Basic Announce