<?php
class generalMethods {

    public static function getCategorydetailNavigationURL($categoryID,$page = NULL, $pagegroup = NULL) {
        global $tableprefix;
        $navigationURL = $bindCategory = NULL;

        if(!empty($categoryID)) {
            $resCat = DbHelper::execute("SELECT category_name FROM ".$tableprefix."categories WHERE category_id =".$categoryID);
            $data = DbHelper::fetchOne($resCat);
            $bindCategory = generalMethods::doTrimSeoNames(strtolower(stripslashes($data)));
            $navigationURL = SITE_URL."/".$bindCategory."/".$categoryID;
            if(!empty($page)) {
                $navigationURL .="/".$page;
            }

            if(!empty($pagegroup)) {
                $navigationURL .="/".$pagegroup;
            }
        }
        return $navigationURL;
    }

    // Function to get Facebook Meta Tag Property
 
    function GetMetaProperty($productid='') {
        global $tableprefix;

        if($productid!='')  {
       
            $productSql = "SELECT
                    p.product_id,p.product_name,p.product_description,
                    po.image_small,po.image_big,
                    (SELECT pm.vimage_name FROM ".$tableprefix."product_view_images pm where pm.nimage_productid=p.product_id LIMIT 0,1)AS smallimage
                    FROM " . $tableprefix . "products p
                    INNER JOIN " . $tableprefix . "product_options po ON po.product_id = p.product_id AND po.default_option = 'YES'
                    INNER JOIN  " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id
                    INNER JOIN  " . $tableprefix . "categories  c ON c.category_id = p.product_category
                    WHERE p.product_id = '" . addslashes($productid) . "' ";
            $resultSql =mysql_query($productSql) or die(mysql_error());
     
            $seo_meta_product_page = mysql_fetch_array($resultSql);
               

                $page_title 		= 		$seo_meta_product_page['product_name'];

                $page_description	= 		$seo_meta_product_page['product_description'];
                
                $product_image = '';
                
                $prodimagedir = SITE_URL."/products/";
                
                if($seo_meta_product_page["image_big"] != "" && !strstr($product_image, "http://")) {
                    $product_image = $prodimagedir.$seo_meta_product_page["image_big"];
                }else if($seo_meta_product_page["image_big"] != "" && strstr($product_image, "http://")) {
                        $imageurl = $product_image;
                }else if($seo_meta_product_page["image_small"] != "" && !strstr($product_image, "http://")){
                    $product_image = $prodimagedir.'fb-share/'.$seo_meta_product_page["image_small"];
                }else if($seo_meta_product_page["image_small"] != "" && strstr($product_image, "http://")){
                    $product_image = $product_image;
                }else if($seo_meta_product_page["smallimage"] != "" && strstr($product_image, "http://")){
                    $product_image = $seo_meta_product_page["smallimage"];
                }else{
                    $product_image = $prodimagedir.$seo_meta_product_page["smallimage"];
                }

                if($product_image=="") {
                    $imageurl = $prodimagedir."noimage.jpg";
                }
                else {
                   
                        $imageurl = $product_image;
                   
                }

               
        $page_meta_tags= array("fbmeta_title"=>$page_title,
                "fbmeta_image"=>$imageurl,
                "fbmeta_description"=>$page_description);

        return $page_meta_tags;
        
        }     



    }


    public static function getProductdetailNavigationURL($productID,$page = NULL, $pagegroup = NULL) {
        global $tableprefix;
        $navigationURL = $bindName = NULL;

        if(!empty($productID)) {
            $resSet = DbHelper::execute("SELECT product_name,product_category,alias FROM ".$tableprefix."products WHERE product_id =".$productID);
            $data = DbHelper::fetchRow($resSet);            
            //$bindName = generalMethods::doTrimSeoNames(strtolower(stripslashes($data)));
            //$navigationURL = SITE_URL."/product/".$bindName."/".$productID;
            // Get SEO friendly URL
            $navigationURL = getOptimisedLink(SITE_URL, $data->product_category, $data->alias);
            
            if(!empty($page)) {
                $navigationURL .="/".$page;
            }

            if(!empty($pagegroup)) {
                $navigationURL .="/".$pagegroup;
            }
        }
        return $navigationURL;
    } // End

     public static function getSellerNavigationURL($artistID,$storename, $artistname,$enable_seller_friendly) {
             
            if($enable_seller_friendly == "Y")
            {

                $sellerLink = (!empty($storename)) ? SITE_URL . "/stores/" . $storename : SITE_URL . "/store/" . $artistname;
                //$sellerLink = SITE_URL . "/store/" . $row['artist_name'];
            }
            else
            {
                $sellerLink = (!empty($storename)) ? SITE_URL."/showportfolio.php?storename=" . $storename : SITE_URL."/showportfolio.php?artistid=" . $artistID;
            }

       
        return $sellerLink;
    } // End
    
    public static function getHelpdetailNavigationURL($helpID) {
        global $tableprefix;
        $navigationURL = $bindName = NULL;

        if(!empty($productID)) {
            $resSet = DbHelper::execute("SELECT htitle FROM ".$tableprefix."help WHERE hid =".$helpID);
            $data = DbHelper::fetchOne($resSet);
            $bindName = generalMethods::doTrimSeoNames(strtolower(stripslashes($data)));
            $navigationURL = SITE_URL."/help/".$bindName."/".$helpID;

        }
        return $navigationURL;
    } // End

    public static function getBreadCrumbs($urlArr = array()) {
        $content = NULL;
        $content .= '<div class="brdcrumb_container">';
        $content .= '<a class="nobg" href="'.SITE_URL.'"> Home </a>';
        if(!empty($urlArr)) {
            foreach($urlArr as $item) {
                $navigationURL = (empty($item['url'])) ? 'javascript:void(0);' : SITE_URL.'/'.$item['url'];
                $content .= '<a href="'.$navigationURL.'"> '.$item['name'].' </a>';
            } // End foreach
        }
        $content .= '</div>';

        return $content;
    } // End

    public static function doTrimSeoNames($string) {
        $content = NULL;
        $search = array('/[^a-z0-9]+/', '/[^a-z0-9]$/');
        $replace = array('-', '');
        $content = preg_replace($search, $replace, strtolower($string));
        $content = rtrim($content, '-');
        $content = ltrim($content, '-');
        return $content;
    } // End Function

    public static function redirect($url){
        header("location:".$url);
        exit;
    }
    
    public static function faceBookShareCode($pageURL,$width=626,$height=436)
    {
        $fbShareCode ="<script>
        function fbs_click()         
        {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><a href='http://www.facebook.com/share.php?v=1&u=<".$pageURL.">' onclick='return fbs_click()' target='_blank'><img src='".SITE_URL."/social_media/f_share.jpg' alt='Share on Facebook' /></a>";
        return $fbShareCode;
    }

// Function for getting all subcategories a particular category
     public static function getsubCategoryIds($categoryId) {
        global $tableprefix;
      
        if(!empty($categoryId)) {
            $resSet = DbHelper::execute("SELECT category_id from ".$tableprefix."categories cat where cat.route REGEXP '^".$categoryId.",|,^".$categoryId."|,".$categoryId.",|,".$categoryId."$|^".$categoryId."$' ");
            $data = DbHelper::fetchAll($resSet);

            if(count($data)>0)
                {

                foreach($data as $data_value)
                    $category_array[] =$data_value->category_id;
                     $categoryString = implode("','",$category_array);
                }

                  
            
        }
        return $categoryString;
    } // End

    
           /*
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 get the current session id 
      public static function sessionid() {
               return self::escapeString(session_id());
    }


     //Function to display number formated numeric value
        public static function numberFormat($num)
        {
            if($num>0) {
                return number_format($num, 2, ".", "");
            }
            else {
                return '0.00';
            }
        }
        
        
        //Function to display special character escaped string
        public static function html_entity($txtString)
        {
            if($txtString)
                return htmlentities(stripslashes($txtString));
        }


        // function to check an image / file exist in mentioned location
        public static function file_exists($url)
        {
             // Initialize the handle
                $ch = curl_init();
                // Set the URL to be executed
                curl_setopt($ch, CURLOPT_URL, $url);
                // Set the curl option to include the header in the output
                curl_setopt($ch, CURLOPT_HEADER, true);
                // Set the curl option NOT to output the body content
                curl_setopt($ch, CURLOPT_NOBODY, true);
                /* Set to TRUE to return the transfer
                    as a string of the return value of curl_exec(),
                    instead of outputting it out directly */
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                // Execute it
                $data = curl_exec($ch);
                // Finally close the handle
                curl_close($ch);
                /* In this case, weÃ¢â‚¬â„¢re interested in
                    only the HTTP status code returned, therefore we
                    use preg_match to extract it, so in the second element
                    of the returned array is the status code */
                preg_match("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);

                print_r($matches);

                if($matches[1]!='200') {
                    return false;
                }else
                    return true;
           }



           // get the brosed user location and ip addredd

   public static function get_location($ip=NULL) {
            if (empty($ip)) {
                if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }
                elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
                else { $ip = $_SERVER['REMOTE_ADDR']; }
            }
            if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
                $ip = '8.8.8.8';
            }
            if($ip=='')
            {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
           //$details =  file_get_contents('http://freegeoip.net/json/'.$ip);
           $details = json_decode(file_get_contents('http://freegeoip.net/json/'.$ip));
           return $details;
            
    }
    
    public static function formatText($txtString)
        {
            if($txtString)
               $newString =  strip_tags(html_entity_decode(stripslashes(nl2br($txtString)),ENT_NOQUOTES,"Utf-8"));
            return $newString;
        }
        
        // Add Http to Url if not exists 
  public static   function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

    
} // End Class

?>
