Location: PHPKode > projects > Floopo > floopo/lib/lib_functions/functions.php
<?php

//+-----------------------------------------------------+//
//+ Copyright live160
//+
//+ A collection of handy little functions
//+-----------------------------------------------------+//



//___Random Characters Generator______________________________________________________________________________________________________
function RandomCode($size) {
    $chars_array = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,R,S,T,U,W,X,Y,Z,2,3,4,5,6,7,8,9,b,c,d,e,f,g,h,k,m,n,p,r,s,t,w,x,z';
    $exploded = explode(',',$chars_array);
    $i = 0;
    for($i; $i < $size; $i++) {
        $random = rand(0,47);
        $code .= $exploded[$random];
    }
    return $code;
}


//___Sanatizer_______________________________________________________________________________________________________________________
function Sanatize($input) {

    if($input != '') {
        $input = strip_tags($input);
        $input = str_replace('<script>','script',$input);
        $input = str_replace('<SCRIPT>','script',$input);
        $input = str_replace('<br />','',$input);
        $input = preg_replace("%\r\n%",' ',$input);
        $input = preg_replace("%\n%",' ',$input);
        $input = preg_replace("%\r%",' ',$input);
        $input = preg_replace("%\t%",' ',$input);

        return $input;
    }
}


//___Validate a URL_______________________________________________________________________________________________________________________
function ValidateURL($url) {
    return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i',$url);

    /* example use
    if(ValidateURL($url)){
    XYZ
    }

    */
}

//___Snip a string to 140 characters_______________________________________________________________________________________________________________________
function StringSnip($str ='') {
GLOBAL $config;

$maxsize = (is_numeric($config['max_text']))? $config['max_text'] : 140;
$str = substr($str, 0, $maxsize);
return $str;
}


//___SEO__Change text to SEO__________________________________________________________________________________________________________
function text_to_seo($input) {
    // change to lower case
    $output = strtolower(trim($input));

    // Remove odd chrs
    $output = html_entity_decode(preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);/',
        '$1',htmlentities($output,ENT_COMPAT)));

    // remove all non-alphanumeric characters except for spaces and dashes
    $output = preg_replace('/[^a-z0-9- ]/','',$output);

    // Clean leftover dashes
    $output = str_replace(array('---','--',' '),'-',$output);

    return $output;
}


//___Login Check_______________________________________________________________________________________________________________________
function loggedin_check() {

    GLOBAL $lang,$config;

    if(isset($_SESSION["env_user_name"]) && isset($_SESSION["env_slat"])) {
        //NULL
    } else {
        ErrorDisplay1($lang['must_be_logged_in']);
        die();
    }
}

//___Login Check_______________________________________________________________________________________________________________________
function loggedin_check_simple() {

    GLOBAL $lang,$config;

    if(isset($_SESSION["env_user_name"]) && isset($_SESSION["env_slat"])) {
        //NULL
    } else {
        die($lang['must_be_logged_in']);
    }
}

//___CriticalInputCheck________________________________________________________________________________________________________________
function CriticalInputCheck($check_type,$input) {
    GLOBAL $lang,$config;
    //Usage: Can be used to check crictical vars. It will produce an error message and die()


    //not_null check


    //numeric check
    is_numeric($input) ? NULL : ErrorDisplay1($lang['generic_error']);


}




//___Login Check_______________________________________________________________________________________________________________________
function ErrorDisplay1($message) {

    GLOBAL $lang,$config;

    echo '
<div align="center">
	&nbsp;<p>&nbsp;</p>
	<table width="556" id="table1" style="border: 1px solid #FF3300; " cellspacing="0" cellpadding="0" bgcolor="#FFDDDD">
		<tr>
			<td bgcolor="#FFECEC">
			<table border="0" width="100%" id="table2" cellspacing="0" cellpadding="0">
				<tr>
			<td width="30">
			<img border="0" src="'.$config['site_url'].'/themes/'.$config['theme'].
        '/system/icons/info.gif"></td>
					<td height="20">
					<p align="center"><font face="Arial" size="2">'.$message.'</font></td>
				</tr>
			</table>
			</td>
		</tr>
	</table>
</div>';
    die();
}


//_____Determine stream_______________________________________________________________

function GetStream() {
    $stream = $_GET['stream'];
    if($stream == '') {
        $stream = $_POST['stream'];
    }
    if($stream == '') {
        $stream = NULL;
    }
    return $stream;
}



//_____Check User Exists_______________________________________________________________

function MemberExists($member) { //returns true or false

    if($member == '' || strtolower($member) == 'public' || is_numeric($member)) {
        return false;
    } else {

        $sql = "SELECT user_id
                FROM member_profile
                WHERE user_name = '$member'";
        if(mysql_num_rows(mysql_query($sql)) > 0) {
            return true;
        } else {
            return false;
        }
    }
}


//_____Check User Notifications Settings_______________________________________________________________

function NotificationStatus($member) { //returns the email address is notifications enabled for member

    if($member == '' || strtolower($member) == 'public' || is_numeric($member)) {
        return false;
    } else {

        $sql = "SELECT email_address
                FROM member_profile
                WHERE user_name = '$member'
				AND
				notifications ='yes'";
        if(mysql_num_rows(mysql_query($sql)) > 0) {
           $query = mysql_query($sql);
           $result = mysql_fetch_array($query);
            return $result['email_address'];
        }
    }
}



//_____Check User Exists AND is also Active_______________________________________________________________

function IsMemberActive($member) { //returns true or false

    if($member == '' || strtolower($member) == 'public' || is_numeric($member)) {
        return false;
    } else {

        $sql = "SELECT user_id
                FROM member_profile
                WHERE user_name = '$member'
                AND account_status = 'active'";

        if(mysql_num_rows(mysql_query($sql)) > 0) {
            return true;
        } else {
            return false;
        }
    }
}

//_____Check User Exists AND is also Active_______________________________________________________________

function MembersPrivacyCheck($member) { //returns true or false

GLOBAL $env_user_name;

    if($member == '' || strtolower($member) == 'public' || is_numeric($member)) {
        return false;
    } else {

//(1)___is the view site admin___
if($_SESSION['admin'] == 1){
return true;
}

//(2)___is viewer also the owner___
if($env_user_name == $member){
return true;
}

//___lets get member details___
$sql = "SELECT user_id, privacy
        FROM member_profile
        WHERE user_name = '$member'
        AND account_status = 'active'";

$query = @mysql_query($sql);
if(@mysql_num_rows($query) > 0) {
$result = @mysql_fetch_array($query);
$privacy = $result['privacy'];

//(4)___its public___
if($privacy =='public'){
return true;
}else{


//(4)___private and viewer not logged in____
if($env_user_name == ''){
return false;
}


//(5)___is viewer a follower
$sql = "SELECT indexer 
        FROM following
        WHERE user_name = '$member'
        AND followers_user_name = '$env_user_name'
        AND approved = 'yes'";

        if(mysql_num_rows(mysql_query($sql)) > 0) {
            return true;
        }else{
            return false;         
        }

}
}else {
//(6)___
return false;
}
}
}


//______Sort an Array (asc or desc)_________________________________________________________________________
function array_sort($arr,$my_key,$sort_type) {

//usage: array_sort($results, 'members', 'ASC');

$sort_type = strtolower($sort_type);

    foreach($arr as $key => $row) {
        $arr_tmp[$key] = $row["$my_key"];

    }

    if($sort_type == 'desc')
        @array_multisort($arr_tmp,SORT_DESC,$arr);
    else
        @array_multisort($arr_tmp,SORT_ASC,$arr);

    return $arr;
}


//-----------------------------------------------------------Runtime - Content Formating_------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------
// These functions are used during page rendering 





//________Exectute and PHP function during runtime______________________
function runtime_functions($FieldName,&$CurrVal,&$CurrPrm) {

    $php_function = $CurrPrm['php_function'];

    if (function_exists($php_function))    {
        $CurrVal =htmlspecialchars_decode($CurrVal); echo $CurrVal;
    }else{
        $CurrVal = $CurrVal;
    }
    
// Example Usage
// --------------
// [var.messages;onformat=runtime_functions; php_function=stripslashes]  //this will strip slashes and return the text in the HTML

}



//________General Text formatting (links, replies, escapes etc)______________________
function runtime_format_messages($FieldName,&$CurrVal,&$CurrPrm) {

//strip slashes
$CurrVal = stripslashes($CurrVal);


//convert url to links
$CurrVal = preg_replace('/\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i', '<a href="\0" target="_blank" rel="nofollow">\0</a>', $CurrVal);


//convert @replies to links
//$CurrVal = preg_replace('/@([a-zA-Z0-9]*)/i', '<a href="\1/updates">\0</a>', $CurrVal); //TODO: this must be SEO url
$CurrVal = preg_replace('%@([a-zA-Z0-9]*)%', '<a href="\1/updates">\0</a>', $CurrVal); //TODO: this must be SEO url
}


//________Lang Title displayed in siteadmin______________________
function runtime_format_langs($FieldName,&$CurrVal,&$CurrPrm) {

//upper case to first word
$CurrVal = ucfirst($CurrVal);

//convert url to links
$CurrVal = str_replace('_', ' ', $CurrVal);

}


//________Lang Title displayed in siteadmin______________________
function runtime_format_numcheck($FieldName,&$CurrVal,&$CurrPrm) {

if($CurrVal ==''){
$CurrVal = 0;
}
}

//__________Friendly Time formatting_____________________________
function runtime_format_time($FieldName,&$CurrVal,&$CurrPrm) {

//Credits:
//Function coded by (yasmary at gmail dot com) http://uk2.php.net/time

$date = $CurrVal;

    if(empty($date)) {
        return "--";
    }
   
    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths         = array("60","60","24","7","4.35","12","10");
   
    $now             = time();
    $unix_date         = strtotime($date);
   
       // check validity of date
    if(empty($unix_date)) {   
        return " -- ";
    }

    // is it future date or past date
    if($now > $unix_date) {   
        $difference     = $now - $unix_date;
        $tense         = "ago";
       
    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }
   
    $tracker = $difference;
   
    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }
   
    $difference = round($difference);
   
    if($difference != 1) {
        $periods[$j].= "s";
    }


    // Check differece, if less that 24hrs (display as "nice" format) else default long format     
    $CurrVal = (($tracker < 86400)? "$difference $periods[$j] {$tense}" : $CurrVal);


}




?>
Return current item: Floopo