Thursday, 25 April 2013

Create HomePageBanner Module for X cart in Few Steps



Create HomePageBanner Module for X cart in Few Steps
Directory Structure.
Catelog
-admin
  -- home_banners.php (new file)
  --/* save as home_banners.php */
<?php
define('USE_TRUSTED_POST_VARIABLES',1);
$trusted_post_variables = array('add');
require './auth.php';
require $xcart_dir.'/include/security.php';
//if (empty($active_modules['XAffiliate']))
   // func_403(6);
require $xcart_dir . '/include/home_banners.php';
// Assign the section navigation data
$smarty->assign('dialog_tools_data', $dialog_tools_data);
if (
    file_exists($xcart_dir.'/modules/gold_display.php')
    && is_readable($xcart_dir.'/modules/gold_display.php')
) {
    include $xcart_dir.'/modules/gold_display.php';
}
func_display('admin/home.tpl', $smarty);
?>
-include
   -- home_banners.php (new file)
--/* save as home_banners.php */

<?php
if ( !defined('XCART_START') ) { header("Location: ../"); die("Access denied"); }
x_load('image');
x_session_register('file_upload_data');
x_session_register('store_banner_data', array());
$is_partner_area = constant('AREA_TYPE') == 'B';
$location[] = array(func_get_langvar_by_name('lbl_home_banners'), "");
/*** Define data for the navigation within section */
$dialog_tools_data['left'][] = array('link' => "home_banners.php", 'title' => func_get_langvar_by_name('lbl_banners_list'));
if (!$is_partner_area) {  
    $dialog_tools_data['left'][] = array('link'  => 'home_banners.php?banner_type=G','title' => func_get_langvar_by_name('lbl_add_graphic_banner'));
}
if ($mode == 'add' && $add && $banner_type)
{
    // Add/Modify banner
    $error = $err_field = false;
    if (empty($add['banner'])) {
        $error = func_get_langvar_by_name('lbl_banner_has_no_name');
        $err_field = 'banner';
    } elseif ( !empty($add['banner_x']) && (!is_numeric($add['banner_x']) || $add['banner_x'] < 1)) {
        $error = func_get_langvar_by_name('lbl_banner_has_wrong_width');
        $err_field = 'banner_xy';
    } elseif (!empty($add['banner_y']) && (!is_numeric($add['banner_y']) || $add['banner_y'] < 1)) {
        $error = func_get_langvar_by_name('lbl_banner_has_wrong_height');
        $err_field = 'banner_xy';
    }
    if ($error) {
        $store_banner_data = $add;
        $store_banner_data['bannerid'] = $bannerid;
        $top_message = array( 'type' => 'E',  'content' => $error );
        func_header_location('home_banners.php?banner_type=' . $banner_type . '&bannerid=' . $bannerid . '&err_field=' . $err_field);
    }
    $store_banner_data = array();
    $data = array(
        'banner'        => $add['banner'],
        'body'          => $add['body'],
        'avail'         => $add['avail'],
        'is_image'      => $add['is_image'],
        'is_name'       => $add['is_name'],
        'is_descr'      => $add['is_descr'],
        'is_add'        => $add['is_add'],
        'banner_type'   => $banner_type,
        'open_blank'    => $add['open_blank'],
        'legend'        => $add['legend'],
        'alt'           => $add['alt'],
        'direction'     => $add['direction'],
        'banner_x'      => $add['banner_x'],
        'banner_y'      => $add['banner_y']
    );
    $is_new = false;
    if ($bannerid) {
        func_array2update('home_banners', $data, "bannerid = '$bannerid'");
        $top_message = array('content' => func_get_langvar_by_name('lbl_banner_is_updated'));
    } else {     
       $bannerid = func_array2insert('home_banners', $data);
        $top_message = array('content' => func_get_langvar_by_name('lbl_banner_is_created'));
        $is_new = true;
    }
    if ($banner_type == 'G' && $bannerid && func_check_image_posted($file_upload_data, 'H')) {
        func_save_image($file_upload_data, 'H', $bannerid);
    }
    if ($banner_type == 'G' && $bannerid) {
        $has_image = func_query_first_cell("SELECT COUNT(*) FROM $sql_tbl[images_H] WHERE id = '$bannerid'");
        if (!$has_image) {
            func_array2update('home_banners', array('avail' => ''), "bannerid = '$bannerid'");
            $top_message['content'] .='<br>'.func_get_langvar_by_name($is_new ? 'lbl_banner_is_created_without_image':'lbl_banner_is_updated_without_image');
        }
    }
    func_header_location('home_banners.php?bannerid=' . $bannerid);
}
elseif ($mode == 'delete') { // Delete banner element
    if ($bannerid) {
        db_query ("DELETE FROM $sql_tbl[home_banners] WHERE bannerid = '$bannerid'");
        func_delete_image($bannerid, 'H');
        $top_message = array('content' => func_get_langvar_by_name('lbl_banner_is_deleted'));
        func_header_location('home_banners.php');
    }
}

if (!empty($bannerid) && empty($err_field)) {
    $banner = func_query_first("SELECT * FROM $sql_tbl[home_banners] WHERE bannerid = '$bannerid'");
    if (!$banner) {
        func_header_location('home_banners.php');
    }   
    $banner['can_edit'] = true;
    $smarty->assign ('banner', $banner);
    $banner_type = $banner['banner_type'];
    $location[count($location) - 1][1] = 'home_banners.php';
    $location[] = array($banner['banner'], 'home_banners.php?bannerid=' . $bannerid);
} elseif ($store_banner_data) {
    $smarty->assign ('err_field', $err_field);
    $smarty->assign ('banner', $store_banner_data);
}

$banners = func_query("SELECT * FROM $sql_tbl[home_banners]");
if ($banners) {
    foreach ($banners as $k => $v) {
        $banners[$k]['banner_type_text'] = func_get_banner_type_text($v['banner_type']);
        $banners[$k]['can_edit'] = true;
    }
    $smarty->assign('banners', $banners);
}
if (!empty($banner_type)) {
    $smarty->assign('banner_type', $banner_type);
}
$smarty->assign('now',            XC_TIME);
$smarty->assign('main',           'home_banners');
// Assign the current location line
$smarty->assign('location', $location);
?>
-module
  ---HomeBanners
      ---config.php(newfile)
--/* save as config.php */
            <?php
if (!defined('XCART_START') ) { header('Location: ../../'); die('Access denied'); }
$addons['HomeBanners'] = true;
$css_files['HomeBanners'][] = array();
$config['available_images']['H'] = "U";
$sql_tbl['images_H']       = XC_TBL_PREFIX . 'images_H';
$sql_tbl['home_banners']   = XC_TBL_PREFIX . 'home_banners';
if (defined('TOOLS')) {     
    $tbl_keys['images_H.id'] = array(
        'keys' => array('images_H.id' => 'home_banners.bannerid'),
        'where' => "home_banners.banner_type = 'G'",
        'fields' => array('id')
    );
    $tbl_keys['home_banners.imageid'] = array(
        'keys' => array('home_banners.bannerid' => 'images_H.id'),
        'where' => "home_banners.banner_type = 'G'",
        'fields' => array('bannerid')
    );
    $tbl_demo_data['HomeBanners'] = array('home_banners'  => '', );
}
?>
      --- home_banners.php (newfile)
--/* save as home_banners.php */
            <?php
if ( !defined('XCART_START') ) { header("Location: ../"); die("Access denied"); }
$banners = func_query("SELECT * FROM $sql_tbl[home_banners] WHERE avail = 'Y'");
if ($banners) {   
    $smarty->assign('banners', $banners);
    $smarty->assign('customer_home_banners','Y');
}
?>
-images
   --image_H
-skin
   --common_files
      ---admin
          ---newfilesbysr
              --- display_banner.tpl (newfile)
{if $banners ne "" and $banner_type eq ''}
            <a href="home_banners.php?bannerid={$v.bannerid}">
<img src="{$current_location}/image.php?type=H&amp;id={$banner.bannerid}" border="0" alt="{if $banner.alt ne ''}{$banner.alt|escape}{/if}" width="960" height="230px;">
            </a>
{/if}  
              --- edit_image.tpl (newfile)
{if $idtag eq ''}
  {assign var="idtag" value="edit_image"}
{/if}
<img id="{$idtag}" src="{$xcart_web_dir}/image.php?type={$type}&amp;id={$id}&amp;ts={$smarty.now}{if $already_loaded}&amp;tmp=Y{/if}" width="905" height="230" alt="{include file="main/image_property.tpl"}" style="margin-bottom: 10px;" />

<table  cellpadding="0" cellspacing="0">
  <tr>
    <td>
      <input type="button" value="{$lng.lbl_change_image|strip_tags:false|escape}" onclick='javascript: popup_image_selection("{$type}", "{$id}", "{$idtag}");' />
      {if $id ne '' and not $no_delete and ($delete_url or $delete_js)}
        &nbsp;&nbsp;
        <input id="{$idtag}_delete" type="button" value="{$lng.lbl_delete_image|strip_tags:false|escape}" onclick="javascript: {if $delete_js ne ''}{$delete_js|replace:'"':'\"'}{else}self.location='{$delete_url}';{/if}" />
      {/if}
      <span style="{if not $already_loaded}display: none; {/if}padding-left: 10px;" id="{$idtag}_reset">
        <input type="button" value="{$lng.lbl_reset|strip_tags:false|escape}" onclick="javascript: popup_image_selection_reset('{$type}', '{$id}', '{$idtag}');" />
        <input id="skip_image_{$type}" type="hidden" name="skip_image[{$type}]" value="" />
      </span>
    </td>
  </tr>
  <tr style="display: none;" id="{$idtag}_text">
 {if $button_name eq ''} {assign var="button_name" value=$lng.lbl_submit} {/if}
    <td style="padding-top: 10px;">{$lng.txt_image_note|substitute:"button_name":$button_name}</td>
  </tr>
</table>
              --- home_banners.tpl (newfile)

{include file="page_title.tpl" title=$lng.lbl_home_banners_management}
<script type="text/javascript" src="{$SkinDir}/js/popup_image_selection.js"></script>
This section is used to create, modify and delete the home page banners.
<br /><br />
{if $banners ne "" and $banner_type eq ''}
  {capture name=dialog}
    {foreach from=$banners item=v}
      <div class="xaff-banner-item{cycle values=", xaff-banner-item-odd"}">
        {if $v.can_edit}
          <a href="home_banners.php?bannerid={$v.bannerid}" class="modify" >{$lng.lbl_modify}</a>
          &nbsp;&nbsp;&nbsp;
          <a href="home_banners.php?bannerid={$v.bannerid}&amp;mode=delete" class="delete">{$lng.lbl_delete}</a>
        {/if}
        <br />
        <table cellspacing="1" cellpadding="0" class="banner-box">
          <tr>
            <td class="banner-box">
                        {include file="admin/newfilesbysr/display_banner.tpl" assign="ban" banner=$v}
                        {$ban|amp}
                </td>
          </tr>
        </table>
      </div>
    {/foreach}
  {/capture}
  {include file="dialog.tpl" content=$smarty.capture.dialog title=$lng.lbl_available_banners extra='width="100%"'}
{elseif $banner_type ne ''}
  {if not $get and (not $banner.banner_type or $banner.can_edit)}
    {capture name=dialog}
    <script type="text/javascript">
    //<![CDATA[
    var requiredFields = [
      ['banner', "{$lng.lbl_banner_name|strip_tags|wm_remove|escape:javascript}", false], ]
    //]]>
    </script>
    {include file="check_required_fields_js.tpl"}
    <form action="home_banners.php" method="post" enctype="multipart/form-data" name="edit_banner" onsubmit="javascript: return checkRequired(requiredFields)">
      <input type="hidden" name="mode" value="add" />
      <input type="hidden" name="mode2" value="" />
      <input type="hidden" name="banner_type" value="{$banner_type}" />
      <input type="hidden" name="bannerid" value="{$banner.bannerid}" />
      <table cellpadding="0" cellspacing="3" width="100%">
        <tr{cycle values=", class='TableSubHead'"}>
          <td><label for="banner">{$lng.lbl_banner_name}:</label></td>
          <td><input type="text" maxlength="128" size="40" id="banner" name="add[banner]" value="{$banner.banner|escape}" />{if $err_field eq 'banner'}<font class="Star">&lt;&lt;</font>{/if}</td>
        </tr>
        <tr{cycle values=", class='TableSubHead'"} style="display:none;">
          <td><label>Banner size (width x height):</label></td>
          <td>
            <input type="text" size="5" id="banner_x" value="{$banner.banner_x|default:960}" name="add[banner_x]" />
            &nbsp;x&nbsp;
            <input type="text" size="5" id="banner_y" value="{$banner.banner_y|default:230}" name="add[banner_y]" />{if $err_field eq 'banner_xy'}<font class="Star">&lt;&lt;</font>{/if}
          </td>
        </tr>
             <tr{cycle values=", class='TableSubHead'"} class='TableSubHead' >
            <td><label for="alt">{$lng.lbl_alt_tag}</label> ({$lng.lbl_optional}):</td>
            <td><textarea cols="50" rows="3" id="alt" name="add[alt]">{$banner.alt}</textarea></td>
          </tr>
        <tr>
          <td><label for="avail">{$lng.lbl_availability}:</label></td>
          <td><input type="checkbox" value="Y" id="avail" name="add[avail]"{if $banner.avail eq 'Y' or ($banner.bannerid eq '' and $err_field eq '')} checked="checked"{/if} /></td>
        </tr>
        <tr{cycle values=", class='TableSubHead'"}  style="display:none;">
          <td><label for="open_blank">{$lng.lbl_open_in_new_window}:</label></td>
          <td><input type="checkbox" value="N" id="open_blank" name="add[open_blank]"{if $banner.open_blank eq 'Y' or ($banner.bannerid eq '' and $err_field eq '')} checked="checked"{/if} /></td>
        </tr>      
          <tr{cycle values=", class='TableSubHead'"} style="display:none;">
            <td><label for="legend">{$lng.lbl_text}</label> ({$lng.lbl_optional}):</td>
            <td><textarea cols="50" rows="3" id="legend" name="add[legend]">{$banner.legend}</textarea></td>
          </tr>
          
          <tr{cycle values=", class='TableSubHead'"} style="display:none;">
            <td><label for="direction">{$lng.lbl_text_location}:</label></td>
            <td>
              <select id="direction" name="add[direction]">
                <option value="U"{if $banner.direction eq 'U' or $banner.direction eq ''} selected="selected"{/if}>{$lng.lbl_above}</option>
                <option value="L"{if $banner.direction eq 'L'} selected="selected"{/if}>{$lng.lbl_left}</option>
                <option value="R"{if $banner.direction eq 'R'} selected="selected"{/if}>{$lng.lbl_right}</option>
                <option value="D"{if $banner.direction eq 'D'} selected="selected"{/if}>{$lng.lbl_below}</option>
              </select>
            </td>
          </tr> 
          <tr{cycle values=", class='TableSubHead'"} class='TableSubHead'>
            <td>{$lng.lbl_image}:</td>
            <td>
              {include file="admin/newfilesbysr/edit_image.tpl" type="H" id=$banner.bannerid button_name=$lng.lbl_save_banner}
            </td>
          </tr> 
         <tr>
          <td>&nbsp;</td>
          <td class="SubmitBox"><input type="submit" value="{$lng.lbl_save_banner|strip_tags:false|escape}" /></td>
        </tr>
      </table>
    </form>  
  {/capture}
  {if $banner.banner_type ne ''}
    {assign var="title" value=$lng.lbl_modify_banner}
  {else}
    {assign var="title" value=$lng.lbl_add_banner}
  {/if}
  {include file="dialog.tpl" content=$smarty.capture.dialog title=$title extra='width="100%"'}
  {/if}
{/if}

n      custommodules.tpl (newfile)
n      <li>
n              <a href='{$catalogs.provider}/testimonials.php'>Custom Modules</a>
n              <div>
n                          <a href="{$catalogs.admin}/home_banners.php">Home Page Banners</a>
n              </div>
n      </li>
      ---customer
         ---newfilesbysr
              --- home_banners.tpl (newfile)
{literal}
<style type="text/css">
div#slideshow {width: 965px; overflow: scroll; position: relative; z-index: 5; margin-bottom:20px;}
div#slideshow ul#nav {display: none;list-style: none;position: relative; top: 75px; z-index: 15;}
div#slideshow ul#nav li#prev {float: left; margin: 0 0 0 10px;}
div#slideshow ul#nav li#next {float: right; margin: 0 50px 0 0;}
div#slideshow ul#nav li a {display: block; width: 80px; height: 80px; text-indent: -9999px;}
div#slideshow ul#nav li#prev a {background: url("../AddYourDirName/skin/common_files/images/prev.png");}
div#slideshow ul#nav li#next a {background: url("../AddYourDirName/skin/common_files/images/next.png");}
div#slideshow ul#slides {list-style: none; padding-left:0px;}
div#slideshow ul#slides li {margin: 0 0 20px 0;}
a {outline: none!important; }
</style>
<script type="text/javascript" src="../AddYourDirName/skin/common_files/js/newfilesbysr/jquery.cycle.all.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
            $("#slideshow").css("overflow", "hidden");   
            $("ul#slides").cycle({
                        fx: 'fade',
                        pause: 1,
                        prev: '#prev',
                        next: '#next'
            });       
            $("#slideshow").hover(function() { $("ul#nav").fadeIn(); },
            function() { $("ul#nav").fadeOut(); });
});
</script>
{/literal}
<div id="slideshow">
{if $banners|@count gt 1} <ul id="nav" style="display: none;"> <li id="prev"><a href="#">Previous</a></li><li id="next"><a href="#">Next</a></li> </ul> {/if}
<ul id="slides">
    {foreach from=$banners item=v}
            <li>
<img src="{$current_location}/image.php?type=H&amp;id={$v.bannerid}" border="0" alt="{if $v.alt ne ''}{$v.alt|escape}{/if}" width="{$v.banner_x}" height="{$v.banner_y}" >
</li>
    {/foreach}
</ul>
</div>
      ---images
          next.png,prev.png(80X80)
      ---js
         ---newfilesbysr
                ----jquery.cycle.all.min.js (new files) à http://code.google.com/p/rgbm/downloads/detail?name=jquery.cycle.all.min.js&can=2&q=
                        or
                ----jquery.wgslider.js (new files) à http://wegraphics.net/downloads/free-simple-jquery-slider/

MODIFY Following EXSITING FILES
home.php
/*** HOME PAGE BANNER MODULE CODE ***/
if (!empty($active_modules['HomeBanners'])) {
    include $xcart_dir . '/modules/HomeBanners/home_banners.php';
}
/** END */

INSTALLATION INSTRUCTION
1. place all the file on proper laoction.
2. run the following patch
     2.a) Create Table for store banner Image
           CREATE TABLE IF NOT EXISTS `xcart_images_H` (
             `imageid` int(11) NOT NULL AUTO_INCREMENT,
             `id` int(11) NOT NULL DEFAULT '0',
             `image` mediumblob NOT NULL,
             `image_path` varchar(255) NOT NULL DEFAULT '',
             `image_type` varchar(64) NOT NULL DEFAULT 'image/jpeg',
             `image_x` int(11) NOT NULL DEFAULT '0',
             `image_y` int(11) NOT NULL DEFAULT '0',
             `image_size` int(11) NOT NULL DEFAULT '0',
             `filename` varchar(255) NOT NULL DEFAULT '',
             `date` int(11) NOT NULL DEFAULT '0',
             `alt` varchar(255) NOT NULL DEFAULT '',
             `avail` char(1) NOT NULL DEFAULT 'Y',
             `orderby` int(11) NOT NULL DEFAULT '0',
             `md5` char(32) NOT NULL DEFAULT '',
             PRIMARY KEY (`imageid`),
             UNIQUE KEY `id` (`id`),
             KEY `image_path` (`image_path`)
           ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

     2.b) Create Table for store banner Image Info.
           CREATE TABLE IF NOT EXISTS `xcart_home_banners` (
             `bannerid` int(11) NOT NULL AUTO_INCREMENT,
             `banner` varchar(128) NOT NULL DEFAULT '',
             `body` mediumblob NOT NULL,
             `avail` char(1) NOT NULL DEFAULT 'Y',
             `is_image` char(1) NOT NULL DEFAULT 'Y',
             `is_name` char(1) NOT NULL DEFAULT 'Y',
             `is_descr` char(1) NOT NULL DEFAULT 'Y',
             `is_add` char(1) NOT NULL DEFAULT 'Y',
             `banner_type` char(1) NOT NULL DEFAULT 'T',
             `open_blank` char(1) NOT NULL DEFAULT 'Y',
             `legend` text NOT NULL,
             `alt` text NOT NULL,
             `direction` char(1) NOT NULL DEFAULT 'D',
             `banner_x` int(11) NOT NULL DEFAULT '0',
             `banner_y` int(11) NOT NULL DEFAULT '0',
             `userid` int(11) NOT NULL DEFAULT '0',
             PRIMARY KEY (`bannerid`),
             KEY `userid` (`userid`)
           ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

     2.c) Patch for home page banner Labels and text
           REPLACE INTO xcart_languages SET code='en', name='lbl_home_banners', value='Home page banners', topic='Labels';
           REPLACE INTO xcart_languages SET code='en', name='lbl_home_banners_management', value='Home page banners management', topic='Labels';
     2.d) patch for insert new module entry in database
           INSERT INTO `xcart_modules` (`moduleid`, `module_name`, `module_descr`, `active`, `init_orderby`, `author`, `module_url`) VALUES
           ('', 'HomeBanners', 'This module enables the Home Page Banners', 'Y', 0, 'qualiteam', '');


3.) Create images_H folder under images folder at root level with 777 permision

4.) Modify following files.
     4.1) Admin section TPL
           a.) open /skin/common_files/single/menu_box.tpl
                insert <a href="{$catalogs.admin}/home_banners.php">Home Page Banners</a>
                after <a href="{$catalogs.admin}/images_location.php">{$lng.lbl_images_location}</a>
           b.) open /skin/common_files/single/home.tpl
                insert
                     {elseif $main eq "home_banners"}
                     {include file="admin/newfilesbysr/home_banners.tpl"}
                after
                     {elseif $main eq "configuration"}
                           {include file="admin/main/configuration.tpl"}
     4.2) FRONT END SECTION TPL
           a.) open /skin/common_files/customer/home_main.tpl
                insert
                      {if $customer_home_banners eq "Y"} 
                         {include file="customer/newfilesbysr/home_banners.tpl"}
                      {/if}
                after
                     {elseif $main eq "catalog" and $current_category.category eq ""}
           b.) open /home.php
                insert
                     if (!empty($active_modules['HomeBanners'])) {
                          include $xcart_dir . '/modules/HomeBanners/home_banners.php';
                     }
                before
                     $smarty->assign('main',     'catalog');
    

For Customize slider option check this link
http://wegraphics.net/downloads/free-simple-jquery-slider/
http://basic-slider.com/

Create dynamic tab menu based on display alphabatic range

 /* Create dynamic tab menu based on display alphabatic range Save below code as dynamictabmanu.php and put it along with images*/

 <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
 <script type="text/javascript">
        $(document).ready(function()
        {        
             $("ul#brandstab li:first").addClass("activebox");
             $("div#divcontentbox div:first").css("display","block");
              $('ul#brandstab li a').click(function()
            {           
                      $("ul#brandstab li").removeClass("activebox");
                      $(this).parent().addClass("activebox");
                $(".abi_htab_content").css("display","none");
                 var divid =   $(this).attr("rel");
                $(divid).css("display","block");
              });         
        });
        </script>
        <style type="text/css">
        #divcontentbox .abi_htab_content{display:none;}       
        #brandstab{height: 46px; margin: 0; padding: 0;}
        #brandstab li.activebox, #brandstab li:hover  {background: none repeat scroll 0 0 #F0F0F0;  bottom: -1px;    position: relative;}
        #brandstab li{border-radius: 6px 6px 0 0;  cursor: pointer;  float: left; list-style: none outside none;  margin-right: 1px;  padding: 0 10px;}
        #brandstab li a{color: #CCCCCC;   display: block;    line-height: 9px;    text-decoration: none;}
        #brandstab li.activebox a h3, #brandstab li a h3:hover {color:#000;}
        #divcontentbox { background: none repeat scroll 0 0 #F0F0F0;padding: 10px;}
        div.datablock{float:left; margin:15px;}
        </style>
<?php
$display_range = 'A-H,I-Z'; // change this as per need for example create three tab set range like this 'A-H,I-P,Q-Z'
$resexplode = explode(',',$display_range);
$mainarray = array(
                        "0"=>array("id"=>1,"title"=>"AR","img"=>"ar.jpg","w"=>100,"h"=>100),
                        "1"=>array("id"=>10,"title"=>"CR","img"=>"cr.jpg","w"=>100,"h"=>100),
                        "2"=>array("id"=>20,"title"=>"HR","img"=>"hr.jpg","w"=>100,"h"=>100),
                        "3"=>array("id"=>25,"title"=>"HK","img"=>"hk.jpg","w"=>100,"h"=>100),
                        "4"=>array("id"=>30,"title"=>"KP","img"=>"kp.jpg","w"=>100,"h"=>100),
                        "5"=>array("id"=>40,"title"=>"SR","img"=>"sr.jpg","w"=>100,"h"=>100),
                        "6"=>array("id"=>50,"title"=>"SK","img"=>"sk.jpg","w"=>100,"h"=>100),
                        "7"=>array("id"=>55,"title"=>"VJ","img"=>"vj.jpg","w"=>100,"h"=>100),
                        "8"=>array("id"=>58,"title"=>"ZQ","img"=>"zq.jpg","w"=>100,"h"=>100),
                  );
                 
        $recAH =  array();
      $brandcollection =  array();
      $data = array();     
      for($k=0;$k<count($resexplode);$k++)
      { 
          $charsetLetter  =  explode('-',$resexplode[$k]);
          if(count($charsetLetter) == 2)
          {
              $datastr =  $charsetLetter[0]."2".$charsetLetter[1];
              $recAH = range($charsetLetter[0], $charsetLetter[1]);
              for($i=0;$i<count($mainarray);$i++)
              { 
                    $brandname = trim($mainarray[$i]['title']);
                    $char = ucfirst(substr($brandname, 0,1));
                    if(in_array($char,$recAH)){
                      $mainarray[$i]['class'] = $charsetLetter[0]."2".$charsetLetter[1];
                      $data[] =   $mainarray[$i];          
                    }
              }
              array_filter($data);        
              $brandcollection[$k]= $data;
              unset($data); 
          }
      }  
          echo '<ul class="abi_htabs" id="brandstab">';
         for($k=0;$k<count($resexplode);$k++){ echo '<li><a rel="#'.$resexplode[$k].'"><h3>'.$resexplode[$k].'</h3></a></li>';}
          echo '</ul>';
         echo '<div class="abi_htab_container" id="divcontentbox">';
         for($k=0;$k<count($resexplode);$k++)
        {
            echo '<div id="'.$resexplode[$k].'" class="abi_htab_content">';
            for($i=0;$i<count($brandcollection[$k]);$i++)
            {
                echo '<div class="datablock"><div class="title">'.$brandcollection[$k][$i]['title'].'</div>';
                echo '<div class="img"><img src="'.$brandcollection[$k][$i]['img'].'" width="'.$brandcollection[$k][$i]['w'].'" height="'.$brandcollection[$k][$i]['h'].'"></div>';
                echo '</div>';   
            }
            echo '<br style="clear:both;">';
            echo '</div>';
        }
         echo '</div>';
?>

Dispaly Image in Ratio

<?php
/*save below code as demo.php. */
/* Dispaly Image in ratio */
$inputwidth=$_GET['w']; //new user define width for image
$inputheight=$_GET['h']; //new user define Height for image
$imgsrc=$_GET['src']; // imagepath from where image need to be load.
//get image details
list($width, $height, $type, $attr) = getimagesize($imgsrc);
//Generate new height and width based on original image size in ratio
if (($width/$height) > ($inputwidth/$inputheight))
{
    $outputwidth = $inputwidth;
    $outputheight = ($inputwidth * $height)/ $width;
}// And if the image is taller rather than wider, then set the height and figure out the width
elseif (($width/$height) < ($inputwidth/$inputheight)) {
                $outputwidth = ($inputheight * $width)/ $height;
                  $outputheight = $inputheight;
}    // And because it is entirely possible that the image could be the exact same size/aspect ratio of the desired area,
elseif (($width/$height) == ($inputwidth/$inputheight))
{
    $outputwidth = $inputwidth;
    $outputheight = $inputheight;
}             
echo '<img src="'.$imgsrc.'" width="'.$outputwidth.'" height="" alt="'.$outputheight.'">';
?>

Wednesday, 24 April 2013

Smarty plugin FOR X CART

<?php
/*
* Smarty plugin BY happylifetruelife
* ————————————————————-
* File:     function.recurse_array.php
* Type:     function
* Name:     recurse_array
* Purpose:  prints out elements of an array recursively
* Author:   happylifetruelife
* ————————————————————-
*/

function smarty_function_recurse_array($params, &$smarty)
{
    if (is_array($params['array']) && count($params['array']) > 0)
    {
           $markup = '';
        $markup .= '<ul>';
        foreach ($params['array'] as $element)
        {
                  $markup .= '<li>';$arrow = '';
            if (isset($element['children']) && $element['parent'] > 0){
                $arrow = 'sub-link-2';
            }
             $productcount = '';
            if (array_key_exists('products_count', $element) && $element['parent'] > 0) {
                $productcount = ' ('.$element['products_count'].')';
            }

            $markup .='<a id="tabSr'.$element['id'].'" class="main-tabs '.$arrow.'" href="'.$element['link'].'">'.$element['title'].$productcount.'</a>';
            if (isset($element['children'])) {
                $markup .= smarty_function_recurse_array(array('array' => $element['children']), $smarty);
                  }
            $markup .= '</li>';
           }
           $markup.= '</ul>';
           return $markup;
    }
    else {
       return '';
    }
}

POST FORM DATA USING AJAX PROCESS

// POST FORM DATA USING AJAX PROCESS
<script type="text/javascript">
    $(document).ready(function()
    {
        $('#bunttonid').click(function()
        {
               var data = $('form#formid').serialize();
               $.post( 'processajaxdatafile.php', data,function(data){
                if(data == 'Y'){
                    // add code for return "Y" with success
                }
                else if(data == 'N'){
        // add code for return "N"  with failled
                }
                return false;} );
              return false;
        });
    });

Regualer expression for validation form field

//Regular expression for validate eamil
var email_reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
var email = "sanjay@demo.com";
if (!email_reg.test(email))
{
    alert('Invalid email.');$("#email").focus();    return false;
}else{
alert('valid email.');
}



//Regular expression for validate date filed with dd-mm-YY
var date_reg = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
var date ='22-05-2013';
if (!date_reg.test(date))
{
    alert('Invalid date.');$("#date").focus();    return false;
}else{
alert('valid date.');
}

//Regular expression for validate password with aplhanumeric charachter with min length 6 
 
var re = /^(?=.*[A-Za-z])(?=.*[0-9])(?!.*[^A-Za-z0-9])(?!.*\s).{5,12}$/;
if ( !re.test(password) )
{
alert('wrong password');
}else{
error = false;
alert('correctpassword');
}
Function for DELETE ALL CHILDREN OF A PARENT CATEGORIES
function deleteChildren($parentId) {
      $lochid = new Location();
      $children = $lochid->where("parent_id", $parentId)->get();
      if (!empty($children)) {
            foreach ($children as $child) {
                $this->deleteChildren($child->id);
                $this->db->delete('countries_locations', array('id' =>$child->id));
            }
        }
    }


Function for update ALL CHILDREN VALUE WHEN PARENT IS UPDATED OF A PARENT CATEGORIES
function updateChildren($parentId) {

      $sql = "SELECT * from  xcart_categories WHERE parentid='$parentId'";
      $children = func_query($sql);
      if (!empty($children)) {
            foreach ($children as $key=>$val) {
                $childcatid = $val['categoryid'];
                $child_data = array('to_show_top_nav' =>'Y');
                func_array2update('categories', $child_data, "categoryid='".intval($childcatid)."'");
                updateChildren($childcatid);
           }
        }
    }


/* Function for create parent and child from an array */
$speed_bar = array();
$speed_bar = buildTree($speed_bar);
function buildTree(array $elements, $parentId = '')
{
        $branch = array();
        foreach ($elements as $element)
    {
            if ($element['parent'] == $parentId)
        {
            $children = buildTree($elements, $element['id']);
            if ($children) {
            $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }
    return $branch;
}    


/* Code FOR GET Number of days between TWO TIME STAMP


$lastapplytime=$lastdatetimestemp;
$todaytime = time();
$diff = abs($todaytime - $lastapplytime);
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$diff2 =  $days+($months*30);

OR

$numDays = floor(abs($lastapplytime - $todaytime)/60/60/24);

List OF BANK PAN Numbers

List OF BANK PAN Numbers Bank/Home Loan Providers PAN Number Allahabad Bank AACCA8464F Andhra Bank AABCA7375C Axis Bank...