Location: PHPKode > scripts > PHP Functions Class > php-functions-class/utility.cls.php
<?php

/**
 * This class is to contain all general purpose small utility functions
 *
 * @access public
 * 
 * @version 1.0.0
 * 
 * @author Ashish Mathur <hide@address.com>
 */

class utility
{
    /**
     * Returns the encoded string. 
     * NOTE: This function manipulate submitted string using base64_encode() and str_rot13().
     *
     * @param string the am_encode() to return the encoded string
     *
     * @access public
     *
     * @return string the encoded value
     */
	
    function am_encode($encodeStr="")
    {
        $returnStr = "";
    	if(!empty($encodeStr)) {
    		$enc = base64_encode($encodeStr);
    		$enc = str_replace('=','',$enc);
    		$enc = str_rot13($enc);
			$returnStr = $enc;
		}
		
    	return $returnStr;

    } // end func am_encode

    /**
     * Returns the decoded string. 
     * NOTE: This function manipulate submitted string using base64_decode() and str_rot13().
     *
     * @param string encoded using am_encode() to return the decoded original string
     *
     * @access public
     *
     * @return string the decoded value
     */
	
    function am_decode($encodedStr="")
    {
        $returnStr = "";
    	if(!empty($encodedStr)) {
		    $dec = str_rot13($encodedStr);
		    $dec = base64_decode($dec);
    		$returnStr = $dec;
		}

    	return $returnStr;

    } // end func am_decode
    
    /**
     * Returns the number of words in a string excluding punctuation marks. 
     * NOTE: This function count words from string using eregi_replace() and eregi().
     *
     * @param string to count words from
     *
     * @access public
     *
     * @return integer the number of words
     */
    
    function am_countWords($string)
    {
		$word_count = 0;
		$string = eregi_replace(" +", " ", $string);
		$string = eregi_replace("\n+", " ", $string);
		$string = eregi_replace(" +", " ", $string);
		$string = explode(" ", $string);
	
		while (list(, $word) = each ($string)) {
			if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $word)) {
				$word_count++;
			}
		}
		
		return $word_count;
		
	} // end func am_countWords
	
	/**
     * Returns the formatted string with highlighted search keywords. 
     * NOTE: This function formats string using preg_replace().
     *
     * @param search string, subject string and formatting to be applied for highlighting search keywords 
     *
     * @access public
     *
     * @return formatted string with highlighted search keywords.
     */
	
	function am_highlightSearchString($searchString, $subjectString, $caseSensitive=true, $highlightedBgColor='', $highlightedFontColor='', $applyBold=true, $applyItalic=false, $applyUnderline=false)
	{ 
		if(!empty($searchString) && !empty($subjectString)){
			$style = '';
			
			if(!empty($highlightedFontColor)) {
				$style = "color : $highlightedFontColor; ";
			}
			if(!empty($highlightedBgColor)) {
				$style .= "background-color : $highlightedBgColor; ";
			}
			if($applyBold) {
				$style .= "font-weight : bold; ";
			}
			if($applyItalic) {
				$style .= "font-style : italic; ";
			}
			if($applyUnderline) {
				$style .= "text-decoration : underline; ";
			}
						
			$formattedString = preg_replace("/($searchString)/".($caseSensitive==true?'i':''),"<font style=\"$style\">$1</font>",$subjectString,-1);		
		}else{
			$formattedString = $subjectString;			
		}
		
		return $formattedString;
		
	} // end func am_highlightSearchString
	
	/**
     * Returns true if .htaccess and .htpasswd files generated. 
     * NOTE: This function generates .htaccess and .htpasswd files to protect files or complete folder.
     * using fopen, fwrite(), crypt()
     *
     * @param $folderPathForSecureFiles; path relative to root for secure files like "mysite/secureddata", 
     * 		$folderPathForPasswordFile; path relative to root where .htpasswd file will be stored like "mysite",
     * 		$secureFileNamesCommaSeperated; files to be secured use comma to seperate multiple files, leave blank if want to secure complete folder,
     * 		$username; username used to login into secured area,
     * 		$password; password used to login into secured area 
     *
     * @access public
     *
     * @return creates .htaccess and .htpasswd file and if successfully created returns true
     */
    
    function am_generateHtaccessHtpasswdFile($folderPathForSecureFiles='', $folderPathForPasswordFile='', $secureFileNamesCommaSeperated='', $username, $password)
    {
		if($folderPathForSecureFiles!='') {
			$folderPathForSecureFiles = ereg_replace('[/]$', '', ereg_replace('^[/]', '', $folderPathForSecureFiles));
			$folderPathForSecureFiles .= '/';
		}
    	$htaccessFile = $_SERVER['DOCUMENT_ROOT'] . '/' . $folderPathForSecureFiles . '.htaccess';
    	
    	if($folderPathForPasswordFile!='') {
			$folderPathForPasswordFile = ereg_replace('[/]$', '', ereg_replace('^[/]', '', $folderPathForPasswordFile));
			$folderPathForPasswordFile .= '/';
		}
    	$authUserFile = $_SERVER['DOCUMENT_ROOT'] . '/' . $folderPathForPasswordFile . '.htpasswd';
    	$htpasswdFile = $authUserFile;
    	
		// Generating .htaccess file
    	$fh_acc = fopen($htaccessFile, 'w+') or die("can't open file");
		fwrite($fh_acc,'AuthName "Restricted Area"\r\n');
		fwrite($fh_acc,'AuthType Basic\r\n');
		fwrite($fh_acc,"AuthUserFile $htpasswdFile\r\n");
		fwrite($fh_acc,'AuthGroupFile /dev/null\r\n');
		if($secureFileNamesCommaSeperated!='') {
			$filesArr = split(",",$secureFileNamesCommaSeperated);
			foreach ($filesArr As $val) {
				fwrite($fh_acc,"<Files $val>\r\n");	
				fwrite($fh_acc,'require valid-user\r\n');	
				fwrite($fh_acc,'</Files>\r\n');	
			}
		} else {
			fwrite($fh_acc,'require valid-user\r\n');	
		}
		fclose($fh_acc);
    	// Generating .htaccess file ends
    	
		// Generating .htpasswd file
		$fh_pwd = fopen($htpasswdFile, 'w+') or die("can't open file");
    	$encPassword = crypt($password);		
		fwrite($fh_pwd, "$username:$encPassword\r\n");
		fclose($fh_pwd);
		// Generating .htpasswd file ends
		
		return true;
		
	} // end func am_generateHtaccessHtpasswdFile

	/*********** DATABASE QUERY RELATED FUNCTIONS *******************
	****************************************************************/
	
	/**
     * Returns the INSERT query string. 
     * NOTE: This function creates insert query from tablename and data array 
     * using mysql_real_escape_string(), get_magic_quotes_gpc(), implode(),
     * array_values() and array_keys().
     *
     * @param tblname string and dataArray array
     *
     * @access public
     *
     * @return insert query string
     */
    
    function am_createInsertQuery($tblName, $dataArray)
    {
		$sqlQuery = "";
		if(!empty($tblName) && !empty($dataArray) && is_array($dataArray)) {
	    	if (get_magic_quotes_gpc()) {
		        foreach ($dataArray as $key => $val) {
		    		if (!is_numeric($val)) {
				        $val = stripslashes($val);
		    			$val = mysql_real_escape_string($val);
		    			$dataArray[$key] = $val;
				    }    	
		        }
		    } else {
		    	foreach ($dataArray as $key => $val) {
		    		if (!is_numeric($val)) {
				        $val = mysql_real_escape_string($val);
		    			$dataArray[$key] = $val;
				    }    	
		        }
		    }
		    			
			$sqlQuery = "INSERT INTO $tblName ";
			$sqlQuery .= "(`". implode("`, `",array_keys($dataArray)) . '`)';
			$sqlQuery .= " VALUES ('". implode("', '",array_values($dataArray)) . "')";
		}
		
		return $sqlQuery;
		
	} // end func am_createInsertQuery
	
	/**
     * Returns the UPDATE query string. 
     * NOTE: This function creates update query from tablename and data array 
     * using mysql_real_escape_string(), get_magic_quotes_gpc()
     *
     * @param tblname string, whereCondition string and dataArray array
     *
     * @access public
     *
     * @return update query string
     */
    
    function am_createUpdateQuery($tblName, $dataArray, $whereCondition)
    {
		$sqlQuery = "";
		if(!empty($tblName) && !empty($dataArray) && is_array($dataArray) && !empty($whereCondition)) {
	    	$sqlQuery = "UPDATE $tblName SET";
	    	
			if (get_magic_quotes_gpc()) {
		        foreach ($dataArray as $key => $val) {
		    		if (!is_numeric($val)) {
				        $val = stripslashes($val);
		    			$val = mysql_real_escape_string($val);
		    		}
				    $sqlQuery .= " `" . $key . "` = '". $val . "',";    	
		        }
		    } else {
		    	foreach ($dataArray as $key => $val) {
		    		if (!is_numeric($val)) {
				        $val = mysql_real_escape_string($val);
		    		}
				    $sqlQuery .= " `" . $key . "` = '". $val . "',";    	
		        }
		    }
		    
		    $sqlQuery = substr($sqlQuery,0,-1); // to remove last comma
		    $sqlQuery .= " WHERE " . $whereCondition;
		}
		
		return $sqlQuery;
		
	} // end func am_createUpdateQuery
	
} // end class utility

?>
Return current item: PHP Functions Class