<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | File name : Utils.php                                         		  |
// | PHP version >= 5.2                                                   |
// +----------------------------------------------------------------------+
// | Author: ARUN SADASIVAN<arun.s@armiasystems.com>              		  |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ï¿½ 2010                                    |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+

class Utils {
    /*
      Function to set table prefix for a table
     */

    public static function setTablePrefix($tableName) {
        //echo $content;exit;

        return MYSQL_TABLE_PREFIX . $tableName;
    }

    /*
      Function to escape string before db operation
     */

    public static function escapeString($data) {
        return mysql_real_escape_string($data);
    }

    /*
      Function to delete a user session
     * Parameters  : User Session Variables
     */

    public static function logoutUser($objUserSession) {
        $objUserSession = new LibSession();
    }

    /*
      Function to generate randon password
     * Parameters  : Password length
     */

    public static function generateRandomPassword($length = 8) {
        $pass           = 'P'.md5(time());
        if ($length != null) {
            $pass       = substr($pass, 0, $length);
        }
        return $pass;
    }

    /*
      Function to get site settings value
     * Parameters  : filed name
     */

    public static function getSettingsValue($length = 8) {
        $pass           = md5(time());
        if ($length != null) {
            $pass       = substr($pass, 0, $length);
        }
        return $pass;
    }

    /*
     * function to send email to the user
     */
    
    /*
     * function to return sort down arrow
     */
   	public static function sortdownarrow(){
   		return '&nbsp;&nbsp;&nbsp;<img src="'.IMAGE_MAIN_URL.'downarrow.png">';
    	//return '&nbsp;&nbsp;&nbsp;&#9650;';
    } 
	
    /*
     * function to return the sort link
     */
    public static function sortarrow(){
    	return '&nbsp;&nbsp;&nbsp;<img src="'.IMAGE_MAIN_URL.'updown.png">';
    	//return '&nbsp;&nbsp;&nbsp;&#9830;';
    } 
    

    public static function sendUserMail($mailid, $mailTemplateName, $arrReplace) {
        PageContext::includePath('phpmailer');
        $db                 = new Db();
        $mailTemplate       = $db->selectRecord("email_templates", "*", "vtemplate_name='" . $mailTemplateName . "' AND vtemplate_flag ='A'");
        $adfromemail        = $db->selectRow("lookup", "vLookUp_Value", "vLookUp_Name='admin_email'");
        $adfromemailname    = $db->selectRow("lookup", "vLookUp_Value", "vLookUp_Name='admin_name'");
        $footer             = 'Copyright &copy; ' . date('Y') . ' ' . SITENAME . ' All rights reserved';

        if (sizeof($mailTemplate) > 0) {
            $arrSearch      = array('[site_name]');
            $arrParams      = array(SITENAME);
            foreach ($arrReplace as $key => $replace) {
                $arrSearch[] = '[' . $key . ']';
                $arrParams[] = $replace;
            }

            // replace the parameters depends on the mail
            $mailBody       = str_replace($arrSearch, $arrParams, stripslashes($mailTemplate->vemail_body));
            $mainBody       = $db->selectRow("lookup", "vLookUp_Value", "vLookUp_Name='mail_template'");

            // replace the email template details
            $arrMailItems   = array('[DATE]', '[MAILBODY]', '[FOOTER]', '[SITE_URL]');
            $arrMailParams  = array(date('F d, Y'), $mailBody, $footer, BASE_URL);
            $email          = str_replace($arrMailItems, $arrMailParams, stripslashes($mainBody));

            $headers  = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: " . $adfromemailname . "<" . $adfromemail . ">" . "\r\n";
            $headers .= "Reply-To: " . $adfromemailname . "<" . $adfromemail . ">" . "\r\n";

            Logger::info($email);

            $mail           = new PHPMailer();
            $mail->AddReplyTo($adfromemail, $adfromemailname);
            $mail->SetFrom($adfromemail, $adfromemailname);
            $mail->AddAddress($mailid, "");
            $mail->Subject = $mailSubject;
            $mail->AltBody = 'Please refer in ' . SITENAME; // optional, comment out and test
            $mail->MsgHTML($email);
            $mailsent       = $mail->Send();

            return $mailsent;
        }
    }

    /*
     * it generates an activation key for the password reset
     */

    public static function generateResetPasswordActivationKey() {
        Logger::info("Generating reset password activation key :");
        $activationkey      = 're' . uniqid();
        return $activationkey;
    }

    /*
     * function to load the post actions from database
     * TODO: we need to move the function into framework level
     */

    public static function postActionRender($param = '*') {

        $postActionTable        = 'tbl_postactions';
        $url                    = $_SERVER['PATH_INFO'];
        if (!($url[strlen($url) - 1] == '/'))
            $url = $url . "/";
        $db                     = new db();
        if ($db->checkTableExist($postActionTable)) {
            if ($result         = $db->selectResultFrom($postActionTable, "*", "pa_url = '" . $param . "' AND pa_type=1")) {
                Logger::info($result);
                $arrPostActions = $result;
            }

            // TODO: need to add the calculation to find the post actions based on the url
            foreach ($arrPostActions as $postActions) {
                PageContext::registerPostAction($postActions->pa_position, $postActions->pa_function, $postActions->pa_controller, $postActions->pa_module);
            }
        }
    }

    /*
     * function to return the formated date
     */

    public static function getFormatedDate($dateValue, $format = '') {
        $format = 'm/d/y';
        if ($dateValue != '')
            return date($format, strtotime($dateValue));
    }

    /*
     * function to generate the alias for the input text
     */

    public static function generateAlias($table_name, $alias_text, $id_column = "id", $id = "", $alias_column = "alias") {
        //format alias 
        $alias = str_replace("&amp;", "and", $alias_text);
        $alias = htmlspecialchars_decode($alias, ENT_QUOTES);
        $alias = str_replace("-", " ", $alias);
        $alias = preg_replace("/[^a-zA-Z0-9\s]/", "", $alias);
        $alias = preg_replace('/[\r\n\s]+/xms', ' ', trim($alias));
        $alias = strtolower(str_replace(" ", "-", $alias));

        $db    = new db();
        //check for duplicates
        $sql   = "select count(*) as total from $table_name where $alias_column = '" . $alias . "'";
        if ($id)
            $sql .= " and $id_column <> $id";
        $duplicates = $db->fetchSingleRow($sql);

        //if duplicates exist recursively create a new alias and try
        if ($duplicates->total > 0) {
            $rand_str = self::rand_str(4);
            return self::generateAlias($table_name, $alias . "-" . $rand_str, $id_column, $id, $alias_column);
        }
        return strtolower($alias);
    }

    /*
     * function to generate a random string value
     */

    public static function rand_str($length = 32, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890') {
        $chars_length   = (strlen($chars) - 1);
        $string         = $chars{rand(0, $chars_length)};
        for ($i = 1; $i < $length; $i = strlen($string)) {
            $r          = $chars{rand(0, $chars_length)};
            if ($r != $string{$i - 1})
                $string .= $r;
        }
        return $string;
    }

    /*
     * Convert an Object to Array Format
     */

    public static function toArray($obj) {
        if (is_object($obj))
            $obj            = (array) $obj;
        if (is_array($obj)) {
            $new            = array();
            foreach ($obj as $key => $val) {
                $new[$key]  = self::toArray($val);
            }
        } else {
            $new            = $obj;
        }
        return $new;
    }

    /*
     * function to get current session id 
     */

    public static function sessionid() {
        return self::escapeString(session_id());
    }

    /*
     * function to formatText before display
     */

    public static function formatText($string) {

        return $string;
    }

    /*
     * function to create the instance for file uploader
     */

    public function uploadFile($files) {

        $fileHandler        = new Filehandler();
        $upload             = $fileHandler->handleUpload($files);

        return $upload;
    }

    /*
     * function to generate thumbnail
     */

    public function createThumbnail($photoid, $thumbtype, $crop = true) {
        global $imageTypes;
        $db             = new Db();
        $fileDet        = $db->selectRecord("files", "file_orig_name,file_path", "file_id=" . $photoid);
        $sourceFile     = FILE_UPLOAD_DIR . '/' . $fileDet->file_path;
        $newFileName    = $imageTypes[$thumbtype]['width'] . '_' . $imageTypes[$thumbtype]['height'] . '_' . $imageTypes[$thumbtype]['prefix'] . $fileDet->file_path;
        $thumbpath      = $imageTypes[$thumbtype]['thumbpath'];
        $destFile       = FILE_UPLOAD_DIR . '/' . $thumbpath . $newFileName;
        $ih             = new Gdimagehandler($sourceFile);
        $ih->generateThumbnail($destFile, $imageTypes[$thumbtype]['width'], $imageTypes[$thumbtype]['height'], $crop);
    }

    /*
     * function Unset an array variable / session
     */

    public function unsetArray($postArray, $key) {
        unset($postArray[$key]);
        return $postArray;
    }

    /*
     * function get the current date 
     */

    public static function Currentdate() {
        return date('Y-m-d');
    }

    /*
     * function get the current date 
     */

    public static function CurrentdateTime() {
        return date("Y-m-d H:i:s");
    }

    /*
     * function to check the value exist in array
     */

    function in_array($needle, $haystack) {
        if (in_array($needle, $haystack)) {

            return true;
        }
    }

    /*
     * function to check the image exist or not. If exist it will return the desired size image.
     * if not it will create a an image or thumbnail. If the image not exist it will load the placeholder image
     * To use this function : 
     * 
     *   	$image 		= Utils::imageCheck('testimage.jpg','sitelogo','placeholder_logo.jpg');
      echo $image;
     */

    public static function imageCheck($source_file, $destination_prefix, $additional_file = '') {
        global $imageTypes;
        $folderpath         = $imageTypes[$destination_prefix]['folderpath'];
        $finalImage         = '';
        if ($source_file && file_exists(FILE_UPLOAD_DIR . '/' . $folderpath . $source_file)) {
            $imgName        = $imageTypes[$destination_prefix]['prefix'] . $source_file;
            if (file_exists(FILE_UPLOAD_DIR . '/' . $folderpath . $imgName)) {
                $imgUrl     = USER_IMAGE_URL . $folderpath . $imgName;
                $finalImage = $imgName;
            } else {
                $newImage   = Utils::generateImage($source_file, $imgName, $imageTypes[$destination_prefix]['width'], $imageTypes[$destination_prefix]['height'], true, $folderpath);
                $imgUrl     = USER_IMAGE_URL . $newImage;
                $finalImage = $newImage;
            }
        } else if ($additional_file != '') {
            if ($additional_file && file_exists(FILE_UPLOAD_DIR . '/' . $folderpath . $additional_file)) {

                $imgUrl = USER_IMAGE_URL . $folderpath . $additional_file;
                $finalImage     = $additional_file;
                $newThumbImg    = self::generateThumbnail($finalImage, $destination_prefix, true, $folderpath);
                if ($newThumbImg != '')
                    $imgUrl     = USER_IMAGE_URL . $folderpath . $newThumbImg;
            }
        }else {
            $imgUrl             = USER_IMAGE_URL . $imageTypes[$destination_prefix]['default'];
            //$finalImage = $default_file;
        }
        $imagPath               = '<img src="' . $imgUrl . '" width="' . $imageTypes[$destination_prefix]["width"] . '" height="' . $imageTypes[$destination_prefix]["height"] . '"  >';
        return $imagPath;
    }

    /*
     * function to generate the image with desired height and width
     */

    public static function generateImage($sourceimage, $newimagename, $width, $height, $crop = false, $path) {
        $sourceFile         = FILE_UPLOAD_DIR . '/' . $path . $sourceimage;
        $destFile           = FILE_UPLOAD_DIR . '/' . $path . $newimagename;
        $ih                 = new Gdimagehandler($sourceFile);
        $ih->generateThumbnail($destFile, $width, $height, $crop);
        return $newimagename;
    }

    /*
     * generate the thumbnail image from the image url
     */

    public function generateThumbnail($imgUrl, $thumbtype, $crop = true, $path) {
        global $imageTypes;
        $sourceFile     = FILE_UPLOAD_DIR . '/' . $path . $imgUrl;
        $destFile       = FILE_UPLOAD_DIR . '/' . $path . $imageTypes[$thumbtype]['prefix'] . $imgUrl;
        $ih             = new Gdimagehandler($sourceFile);
        $ih->generateThumbnail($destFile, $imageTypes[$thumbtype]['width'], $imageTypes[$thumbtype]['height'], $crop);
        return $imageTypes[$thumbtype]['prefix'] . $imgUrl;
    }

    /*
     * get Logged User Session Name
     */

    function getAdminUserSession() {

        return $_SESSION['sess_adminname'];
    }

    /*
     * redirect url 
     */

    function redirectUrl($url) {
        header("Location:$url");
        exit;
    }

    function stringtolower($string) {
        return strtolower($string);
    }

    function formatPrice($price) {
        
    }

    /*
     * function to get the admin session name
     */

    public static function getAdminSession($sessionField = '') {
        if ($sessionField != '') {
            return $_SESSION[$sessionField];
        } else {
            $adminArray = array('cms_admin_type' => $_SESSION['cms_admin_type'],
                'cms_admin_logged_in' => $_SESSION['cms_admin_logged_in'],
                'cms_cms_username' => $_SESSION['cms_cms_username']);
            return $adminArray;
        }
    }

    public static function getPage($alias = '') {

        $objResult = new Messages();

        //Select User Record If User id is not null
        if ($alias != '') {
            $db = new Db();
            $tableName = 'content';
            $selectCase = "  content_alias ='" . Utils::escapeString($alias) . "'";
            Logger::info($selectCase);

            $objResultRow = $db->selectRecord($tableName, '*', $selectCase);
            // If user exists then assign user data to result object

            $objResult->data = $objResultRow; // Assign user record  to object
        }

        Logger::info($objResult);
        //echopre($objResult->data);
        return $objResult->data;
    }

    /*
     * Convert Object to array
     */

    public static function objectToArray($obj) {

        $data = array();
        if ($obj) {
            foreach ($obj as $key => $val) {
                $data[$key] = $val;
            }
        }
        return $data;
    }
    
     /*
     * function to return sort up arrow
     */
    public static function sortuparrow(){
    	return '&nbsp;&nbsp;&nbsp;<img src="'.IMAGE_MAIN_URL.'uparrow.png">';
    	//return '&nbsp;&nbsp;&nbsp;&#9660;';
    }
    

    
/*
	 * function to get the sorting order of the field
	 */
	public static function getsortorder($order){ 
		if($order == 'DESC') return Utils::sortuparrow();
        else if($order == 'ASC') return Utils::sortdownarrow();
	}
    /*
     * Convert Array to Object
     */

    public static function arrayToObject($array = array(), $extra = array(), $unset = array()) {
        $data = new stdClass();
        if ($unset) {
            foreach ($unset as $key => $val) {
                unset($array[$val]);
                if ($extra) {
                    unset($extra[$val]);
                }
            }
        }
      
//   unset($array['__utma']) ;   
//    unset($array['__utmz']) ;  
//     unset($array['__utmb']) ;
//      unset($array['__utmc']) ;
//      unset($array['CAKEPHP']) ;
        
        

        if ($array) {
            foreach ($array as $key => $val) {
                $data->$key = addslashes($val);
            }
        }
        if ($extra) {
            foreach ($extra as $key => $val) {
                $data->$key = addslashes($val);
            }
        }

        
        
        //echopre($data);

        return $data;
    }

    /*
     * check whether the user is logined or not
     */

    public static function checkUserLoginStatus($redirect=true) {
        $objSession = new LibSession();
        $values = $objSession->get('user_id', 'default');
        if ($values) {
            return true;
        } else {
            if($redirect){
                Utils::redirecttohome();
            }
            else{
               return false; 
            }
        }
    }

    public function redirecttohome() {
        header("Location:" . BASE_URL);
        exit;
    }

    /*
     * Will Set Session from Object value
     */

    public static function setSessions($objList) {

        $objSession = new LibSession();

        if ($objList) {
            foreach ($objList as $key => $val) {
                $objSession->set($key, $val);
            }
        }

        return true;
    }

    /*
     * To get Session Value
     */

    public static function getAuth($name='') {

        if ($name) {
            $objSession = new LibSession();
            $values = $objSession->get($name, 'default');
            if ($values) {
                return $values;
            } else {
                return '';
            }
        } else {
            return '';
        }
    }
    
    
    /*
     * Will Set Cookies from Object value
     */

    public static function setCookies($objList,$expires) {

        $objCookie = new LibCookie();

        if ($objList) {
            foreach ($objList as $key => $val) {
                $objCookie->setcookie($key, $val, $expires);
            }
        }

        return true;
    }
     /*
     * Will Get Cookies Values
     */
     public static function getCookies($name) {

        if ($name) {

            $objCookie = new LibCookie();
            $values = $objCookie->get($name, 'default');
         
            if ($values) {
                return $values;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }
    public static function getStatesByCountry($countryCode) {
    	$db 			= new Db();
    	$stateData 		= $db->selectResult('state S INNER JOIN '.MYSQL_TABLE_PREFIX.'country C ON S.tc_id=C.tc_id ', 'S.*', " S.ts_status='A' AND C.tc_code='".$countryCode."'");
    	return $stateData;
    }
    
    public static function unsetArrayElements($elementsArray=array(),$originalArray){
        if(count($elementsArray) > 0){
           foreach($elementsArray AS $element){
               unset($originalArray[$element]);
           } 
        }
        return $originalArray;
    }
    
    
    
    public static function boxResize($path, $sourceFileName, $destFileName,$destination_path, $img_width, $img_height,$method,$bgcolor='FFFFFF') {


        PageContext::includePath('imagehandle');
        $ObjImagehandle                         = new ImagehandleComponent();
        $ObjImagehandle->source_path            = $path.$sourceFileName;
        $ObjImagehandle->preserve_aspect_ratio  = true;
        $ObjImagehandle->enlarge_smaller_images = true;
        $ObjImagehandle->preserve_time          = true;

        $ObjImagehandle->target_path = $destination_path.'/'.$destFileName;
       // echopre($ObjImagehandle);
        $ObjImagehandle =$ObjImagehandle->resize($img_width, $img_height,$method,$bgcolor);

    }
    
    
  public static function  allResize($filPath = '',$folderName,$width,$height)
  {
  //	echopre($width);echopre($height);
       Utils::boxResize(FILE_UPLOAD_DIR,$filPath,$filPath,FILE_UPLOAD_DIR.$folderName, $width, $height,"ZEBRA_IMAGE_BOXED");
   }

   public static function getSettings()
   {
   		$table = 'lookup';
   		$db = new Db();
   		$fileds = "settingfield, value";
   		$values = "'sitelogo','perpage','vadmin_email','metatagKey','metatagDes','sitename','vsite_url',
   				'CloudSpongekey','metaTitle','SSLEnabled','SMTPHost','SMTPUsername','SMTPPassword','SMTPPort',
   				'ADMIN_APPROVE_CLASSIFIEDS_AUTO','auto_approval','ADMIN_APPROVE_BIZCOM_AUTO','ADMIN_APPROVE_USER_AUTO',
                                'bbf_charges','bbf_transaction_charge','bbf_charge_0_50','bbf_charge_50_100','bbf_charge_100plus','bbf_charge_1000plus',
                                'Paypal_api_username','PayPal_api_password','PayPal_api_signature','PayPall_test_mode','currency_code','max_threshold_value','enable_fb','fb_app_id','organization_display','group_display','friend_display','relation_ship','theme','innerlogo','galleryForUsers','pageGroupRelation','chat_display','sitelabel','sitedescription'";
   		$where = " settingfield IN (".$values.")";
   		$result = $db->selectResult($table, $fileds, $where);
   		return $result;
   }
   
   public static function  getBanners()
   {
   	$table = 'banners';
   	$db = new Db();
   	$fileds = "banner_title, banner_description, banner_link, banner_link_text, banner_image_name";
   	
   	$where = " banner_status = 'A' ";
   	$result = $db->selectResult($table, $fileds, $where);
   	return $result;
   }
   public static function getAdminMail(){
       $db = new Db();
       return $adfromemail = $db->selectRow("lookup", "value", "settingfield='vadmin_email'");
   }
   
    public static function setUserfeed($data){
        $db                         = new Db();
        $data_array                 = array(
                                        'feed_type'                         => $data['feed_type'],
                                        'feed_date'                         => date('Y-m-d h:i:s'),
                                        'feed_user_id'                      => $data['feed_user_id'],
                                        'from_user_id'                      => $data['from_user_id'],
                                        'to_user_id'                        => $data['to_user_id'],
                                        'community_id'                      => $data['community_id'],
                                        'table_name'                        => $data['table_name'],
                                        'table_key_id'                      => $data['table_key_id']
                                    );
        $tableName                = Utils::setTablePrefix('feeds');
        $feedId                   = $db->insert($tableName, $data_array);
    }
    
}

?>
