Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Daily Archives: 26/08/2011

jQuery Cookie Plugins


$.cookie('term_condtn', 'accepted', { expires: 1 });
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

PHP Mobile Detection Library


Download this ZIP: click MobileESP_Samples.zip

include("mp/php_redirect_sample/code/mdetect.php");
      $iphoneTierHomePage = 'http://m.xyz.com.au/index.php?page=m';
      $genericMobileDeviceHomePage = 'http://m.xyz.com.au/index.php?page=m';
      $desktopHomePage = 'index.php';
      $uagent_obj = new uagent_info();         
      function AutoRedirectToProperHomePage(){
	      global $uagent_obj, $iphoneTierHomePage, $genericMobileDeviceHomePage, $desktopHomePage; 
	      if ($uagent_obj->isTierIphone == $uagent_obj->true) 
          header ('Location: '.$iphoneTierHomePage);          
	      else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true) 
          header ('Location: '.$genericMobileDeviceHomePage);        
	      else 
          header ('Location: '.$desktopHomePage);
      }  
      AutoRedirectToProperHomePage();

How to user FirePHP


*Install FirePHP FireFox add-ons (get a console like firebug), bottom status console bar in FF
* Copy FirePHP.class.php to the root file location

require("FirePHP.class.php");
$firephp = FirePHP::getInstance(true);
$firephp->log($doc->load($url), 'doc');

how to upgrade cms ms


define('CUSTOMER_FOLDER', '/var/www/vhosts/');
define('WEB_FOLDER', 'httpdocs/websitedesign');
if (PHP_SAPI != "cli") exit;
if ($argc != 2){
    echo 'this command needs 1 argument'."\n";
    exit;
}
if (!file_exists(CUSTOMER_FOLDER.$argv[1].'/'.WEB_FOLDER.'/version.php')){
    echo CUSTOMER_FOLDER.$argv[1].'/'.WEB_FOLDER.'/version.php'."\n";
    echo 'Check the folder name'."\n";
    exit;
}
$sitename = $argv[1];
$path = CUSTOMER_FOLDER.$sitename.'/';
$owner = 'thehost5';
$group = 'psacln';
chdir('/var/www/vhosts/'.$sitename.'/');
if (!file_exists($path.'backup')){
    mkdir($path.'backup');
} else {
    echo 'backup folder exists'."\n";
}
exec('tar cvzf backup/'.WEB_FOLDER.'.tar.gz '.WEB_FOLDER);
include($path.WEB_FOLDER.'/config.php');
exec('mysqldump -u '.$config['db_username'].' -p'.$config['db_password'].' '.$config['db_name'].' > backup/db.sql');
exec('tar cvzf backup/db.tar.gz backup/db.sql');
unlink($path.'backup/db.sql');
chdir(WEB_FOLDER);
exec('tar xvzf /root/CMS.1-9-4-2.tar.gz');
exec('chown -R '.$owner['name'].'.'.$group['name'].' *');
exec('chown -R '.$owner['name'].'.'.$group['name'].' ../backup');
exec('chmod -R 777 tmp config.php');
exec('chmod -R 777 uploads/ modules/');

how to display products group price B2B CreLoaded Store


$products_group_price = getSpecialPrices($product_info['products_id']);
function getSpecialPrices($products_id){
	$m_value = '';
	$sql = "SELECT `customers_group_price` FROM `products_groups` WHERE `products_id` ='".$products_id."'";
	$m_query = tep_db_query($sql);
	while ($m_rows = tep_db_fetch_array($m_query)) {
		$m_value = $m_rows['customers_group_price'];
	}
	return $m_value;
}

show all categories expanded


$aa = 0;
    $info_box_contents = array();
   // $info_box_contents[] = array('text'  => '' . BOX_HEADING_CATEGORIES4 . '');
  //  new infoBoxHeading($info_box_contents);
  //  $categories_string4 = '';
    if(!$_SESSION['sppc_customer_group_id']) {
      $customer_group_id = 'G';
    } else {
     $customer_group_id = $sppc_customer_group_id;
    }
    $categories_query = tep_db_query("SELECT c.categories_id, cd.categories_name, c.parent_id 
                                        from " . TABLE_CATEGORIES . " c,
                                             " . TABLE_CATEGORIES_DESCRIPTION . " cd 
                                      WHERE c.parent_id = '0' 
                                        and c.categories_id = cd.categories_id 
                                        and cd.language_id='" . $languages_id ."' 
                                      ORDER BY sort_order, cd.categories_name");					  
 
    while ($categories = tep_db_fetch_array($categories_query))  {
		$foo[$categories['categories_id']] = array('name' => $categories['categories_name'],
                                                 'parent' => $categories['parent_id'],
                                                 'level' => 0,
                                                 'path' => $categories['categories_id'],
                                                 'next_id' => false
                                                );
					 if (isset($prev_id)) {
        $foo[$prev_id]['next_id'] = $categories['categories_id'];
      }
      $prev_id = $categories['categories_id'];
      if (!isset($first_element)) {
        $first_element = $categories['categories_id'];      }
	  
	  $categories_query2 = tep_db_query("select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.parent_id = '" . $categories['categories_id'] . "' and c.categories_id = cd.categories_id and cd.language_id='" . $languages_id ."' order by sort_order, cd.categories_name");	 
        $category_check = tep_db_num_rows($categories_query2);
        if ($category_check > 0) {
          $new_path = $categories['categories_id'];
          while ($row = tep_db_fetch_array($categories_query2)) {
            $foo[$row['categories_id']] = array('name' => $row['categories_name'],
                                                'parent' => $row['parent_id'],
                                                'level' => $key+1,
                                                'path' => $new_path . '_' . $row['categories_id'],
                                                'next_id' => false
                                               );
            if (isset($prev_id)) {
              $foo[$prev_id]['next_id'] = $row['categories_id'];
            }
            $prev_id = $row['categories_id'];
		  }
		}   
	  
    }  	
	
    tep_show_category4($first_element);

oscommerce – 30 minutes cleanup from cart baskets


include_once("includes/configure.php");
$conn = mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD);
mysql_select_db(DB_DATABASE);
$sql = "SELECT `customers_basket_id`,`customers_id`,`products_id`,`customers_basket_quantity`,`final_price`,`customers_basket_date_added`,`auction_product`,`customers_basket_datetime` FROM   `customers_basket` ORDER BY `customers_basket_id` ASC";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
	$products_id = $row["products_id"];
	$customers_id = $row["customers_id"];
	$customers_basket_quantity = $row["customers_basket_quantity"];	
	$total_minutes = 0;
	$customers_basket_datetime = $row["customers_basket_datetime"];
	$total_minutes = date_diff($customers_basket_datetime);
	if ($total_minutes >= 30){			
		$sql = "update products set products_quantity = products_quantity + ".$customers_basket_quantity." where products_id = '" .$products_id. "'";
		mysql_query($sql);
		//echo $sql."
"; $sql = "delete from customers_basket where customers_id = '" .$customers_id. "' AND products_id = '" .$products_id. "'"; mysql_query($sql); //echo $sql."
"; $products_parent_id = 0; $products_parent_id = tep_hasParentID($products_id); //echo 'products_parent_id: '.$products_parent_id."
"; if ($products_parent_id>0) { $sql = "update `products` set `products_quantity` = 0, `products_status` = 1 where `products_id` = '".$products_parent_id."'"; mysql_query($sql); //echo $sql."
"; } //echo "
"; } //echo "
"; } mysql_free_result($result); function tep_hasParentID($products_id) { global $conn; $prod_query = mysql_query("SELECT `products_parent_id` FROM `products` WHERE `products_id`='".$products_id."'"); $prods = mysql_fetch_array($prod_query); return $prods['products_parent_id']; } function date_diff($start, $end="NOW"){ $sdate = strtotime($start); $edate = strtotime($end); $time = $edate - $sdate; $phour = ($edate - $sdate) / 3600; $prehour = explode('.',$phour); $premin = $phour-$prehour[0]; $min = explode('.',$premin*60); $presec = '0.'.$min[1]; $sec = $presec*60; $total_mins = 0; if($prehour[0]>0) $total_mins = ($prehour[0] * 60) + $min[0]; else $total_mins = $min[0]; return $total_mins; }

creloaded 6.2 – osCommerce – shopping cart check/uncheck all – remove items from cart


HTML:
<input type="button" value="CHECK ALL" onclick="checkUncheck(true);" />&nbsp;<input type="button" value="UNCHECK ALL" onclick="checkUncheck(false);" />
JS:

function checkUncheck(flag) {
				  for (var i=0;i<document.forms[0].elements.length;i++) {
					var e = document.forms[0].elements[i];
					if ( (e.name != 'cart_delete') && (e.type=='checkbox') && (!e.disabled) ) {
					  if(flag) document.forms[0].elements[i].checked = true; else document.forms[0].elements[i].checked = false;
					}
				  }
				}

Creloaded 6.2 – osCommerce – Cross sell products


$categories = array();
$sql = "SELECT `categories_id` FROM `products_to_categories` WHERE `products_id` = '".$HTTP_GET_VARS['products_id']."'";
$result = tep_db_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $categories[] = $row["categories_id"];
}

$categories_str = '';
if (sizeof($categories)){
	$categories_str = implode("','", $categories);
}

$products = array();
$sql = "SELECT `products_id` FROM `products_to_categories` WHERE `categories_id` IN ('".$categories_str."')";
$result = tep_db_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $products[] = $row["products_id"];
}
$products_str = '';
if (sizeof($products)){
	$products_str = implode("','", $products);
}

//echo "'".$products_str."'
"; /*SELECT * FROM `products` w ORDER BY RAND() LIMIT 0 , 6;*/ $sql = "select distinct p.products_id, p.products_image, p.products_price, p.manufacturers_id, pd.products_name, p.products_tax_class_id, p.products_date_added, p.products_image , xp.xsell_id products_price from (" . TABLE_PRODUCTS . " p left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id), " . TABLE_PRODUCTS_XSELL . " xp, " . TABLE_PRODUCTS_DESCRIPTION . " pd where xp.products_id = '" . $HTTP_GET_VARS['products_id'] . "' and p.products_id = xp.xsell_id and pd.products_id = xp.xsell_id and pd.language_id = '" . $languages_id . "' and p.products_status = '1' order by rand(), xp.products_id asc limit " . 6; //echo $sql.'
'; $sql = "SELECT * FROM `products` where products_id IN ('".$products_str."') AND `products_price` 0 ORDER BY RAND() LIMIT 0 , 6";

Magento Easy Lightbox

Magento – How to create multiple store?

Magento – Creating a Configurable Product

Magento – How to get a product attribute value?


I have created an extra attribute ‘enquiry_only’ in the back-end, this is how I can retrieve the attribute value in the product info template page:
\public_html\app\design\frontend\base\default\template\catalog\product\

$enquiry_only = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('enquiry_only');

Alternatively we can use like:

$prod = Mage::getModel('catalog/product')->load($_product->getEntityId());
					$prod = $prod->getData(); 								
					$enquiry_only = 'No';		
					$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'enquiry_only');
					foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
						if ($option['value'] == $prod['enquiry_only'])
							$enquiry_only = $option['label'];
					}	

osCommerce – Vouchers or coupons when assigned to specific products


Filename: includes/modules/order_total/ot_coupon.php

$c_restrict_to_products 		= $coupon_result['restrict_to_products'];
$logs .= 'c_restrict_to_products: '.$c_restrict_to_products;	   
$c_restrict_to_categories 	= $coupon_result['restrict_to_categories'];
$logs .= 'c_restrict_to_categories: '.$c_restrict_to_categories;

$valid_coupon_product_id_exists = 'false';
if($c_restrict_to_products !=''){		    	  
  $db_product_ids = split("[,]", $c_restrict_to_products);		   
  for ($i=0; $i products); $i++) { 
	$logs .= 'products_id: '.$order->products[$i]['id'];
	if (in_array($order->products[$i]['id'], $db_product_ids)) {
		 $valid_coupon_product_id_exists = 'true';
	}
  }		  			  
}else if($c_restrict_to_categories !=''){
  $db_category_ids = split("[,]", $c_restrict_to_categories);
  for ($i=0; $i products); $i++) { 			
	$category_id = $this->getProductsCategoryID($order->products[$i]['id']);
	$logs .= 'products_id: '.$order->products[$i]['id'];
	$logs .= 'category_id: '.$category_id;
	if (in_array($category_id, $db_category_ids)) {
		 $valid_coupon_product_id_exists = 'true';
	}
  }  		 	  
}
$logs .= 'valid_coupon_product_id_exists: '.$valid_coupon_product_id_exists;
if ($valid_coupon_product_id_exists == 'false') {		    
  tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=ot_coupon&error=' . urlencode('This coupon is not valid for the product(s) you are purchasing.' ), 'SSL'));
}

function getProductsCategoryID($products_id){
$category_id 		= 0;
$p_parent_query		=	tep_db_query("select `products_parent_id` from `products` where products_id = '".$products_id."'");
$p_parent_result	=	tep_db_fetch_array($p_parent_query);
$products_parent_id = 	$p_parent_result['products_parent_id'];

if($products_parent_id == 0){
	$sql = "SELECT `categories_id` FROM `products_to_categories` where products_id = '".$products_id."'";
	$p_parent_queryX = tep_db_query($sql);
	$category_id = $p_parent_queryX['categories_id'];
}else{
	$sql = "SELECT `categories_id` FROM `products_to_categories` where products_id = '".$products_parent_id."'";
	$p_parent_queryY = tep_db_query($sql);	
	$category_id = $p_parent_queryY['categories_id'];
}
return $category_id;
}

Magento – Terms & Condition Popup for Category Page Link


jQuery Library include:
CSS:
css/ui-lightness/jquery-ui-1.8.16.custom.css

JS:
js/jquery-1.6.2.min.js
js/jquery-ui-1.8.16.custom.min.js

Javascript code:

$(document).ready(function(){		
	
	TERMS_CONDT_CNT = 0;
	
	$('.category-box a').click(function() {					
		//$( "#dialog:ui-dialog" ).dialog( "destroy" );	
		console.log(this);
		vlink = this.href;
		console.log(vlink);
		if (TERMS_CONDT_CNT == 0){		
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:500,
			width:500,
			modal: true,
			buttons: {
				"Accept": function() {
					TERMS_CONDT_CNT++;
					debugger;
					$( this ).dialog( "close" );
					document.location = vlink;
				},
				"Decline": function() {
					$( this ).dialog( "close" );
					TERMS_CONDT_CNT = 0;
					return false;
				}
			}
		});
		}//if TERMS_CONDT_CNT
		console.log(TERMS_CONDT_CNT);
		if (TERMS_CONDT_CNT == 0) return false; else return true;
		
	});
	});

HTML Code:
<!– popup –>
<div id="dialog-confirm" title="Accept Terms and Conditions: " style="display:none;">
<p style="overflow:auto;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
</div>
<!– popup –>
<!– front-end link page –>
<div id="categories">
<div class="col_full">
<div class="listing">

<div class="category-box">
<a href="#trucks.html"><div class="category-image-box">
<img height="97" border="0" src="media/catalog/category/cat-image_1.jpg">
</div>
<div class="category-name">
<p>Trucks</p>
</div></a>
</div>

<div class="category-box">
<div class="category-image-box">
<a href="#/workmate.html"><img height="97" border="0" src="/media/catalog/category/cat-image_25.jpg"></a>
</div>
<div class="category-name">
<p><a href="#/workmate.html"> Workmate</a></p>
</div>
</div>
</div>
<!– front-end link page –>