24 August 2009

magento-shipping-module

You must have wondered how to add a new Shipping Module in Magento especially if you don’t find your preferred payment module in existing Magento installation with your preferred Shipping Module. Adding a new Magento Shipping Module in not difficult but requires little bit of programming at your end. In this article i am going to elaborate on how to add a new Shipping module to your existing Magento Installation.

Few Notes:

  1. Just Replace all instances of ‘YourCompany’ with your company name.
  2. Replace ‘NewModule’ with the Payment Module name.
  3. Ensure that the path of the PHP include_path is /app/code/local/
  4. Clean your cache after modifying the config xml files.

Now, you are all set to create a new shipping module of your own. Following is a step by step guide to build your own shipping module, just follow them in exact order and make sure that the above requirements are taken care of.

Set The Configuration

You need to create app/code/local/YourCompany/NewModule/etc/config.xml file and write the following lines of code in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0"?>
<config>
  <modules>
<!-- declare module's version information -->
    <YourCompany_NewModule>
<!-- this version number will be used for database upgrades -->
      <version>0.1.0</version>
    </YourCompany_NewModule>
  </modules>
 
  <global>
<!-- declare model group for new module -->
    <models>
<!-- model group alias to be used in Mage::getModel() -->
      <newmodule>
<!-- base class name for the model group -->
        <class>YourCompany_NewModule_Model</class>
      </newmodule>
    </models>
 
<!-- declare resource setup for new module -->
    <resources>
<!-- resource identifier -->
      <newmodule_setup>
<!-- specify that this resource is a setup resource and used for upgrades -->
        <setup>
<!-- which module to look for install/upgrade files in -->
          <module>YourCompany_NewModule</module>
        </setup>
<!-- specify database connection for this resource -->
        <connection>
<!-- do not create new connection, use predefined core setup connection -->
          <use>core_setup</use>
        </connection>
      </newmodule_setup>
    </resources>
  </global>
</config>

Now, edit app/etc/modules/YourCompany_NewModule.xml file

1
2
3
4
5
6
7
8
9
10
11
12
13
<config>
<!-- ... -->
  <modules>
<!-- ... -->
<!-- declare YourCompany_NewModule module -->
    <YourCompany_NewModule>
      <active>true</active>
      <codePool>local</codePool>
    </YourCompany_NewModule>
<!-- ... -->
  </modules>
<!-- ... -->
</config>

Now, the Magento installation is aware that there is a new Module but nothing will happen as there is no Database selected for this.

manage-mysql-databases-magento

Adding Information Into Adapter

Now, create app/code/local/YourCompany/NewModule/Model/Carrier/ShippingMethod.php file and put the following code in it. You can always set the ShippingMethod name of your choice, depending upon for which Payment Gateway you are making a module.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
 
/**
 * Our test shipping method module adapter
 */
class YourCompany_NewModule_Model_Carrier_ShippingMethod extends Mage_Shipping_Model_Carrier_Abstract
{
  /**
   * unique internal shipping method identifier
   * 
   * @var string [a-z0-9_]
   */
  protected $_code = 'newmodule';
 
    /**
     * Collect rates for this shipping method based on information in $request
     *
     * @param Mage_Shipping_Model_Rate_Request $data
     * @return Mage_Shipping_Model_Rate_Result
     */
  public function collectRates(Mage_Shipping_Model_Rate_Request $request)
  {
    // skip if not enabled
    if (!Mage::getStoreConfig('carriers/'.$this->_code.'/active')) {
        return false;
    }
 
    /**
     * here we are retrieving shipping rates from external service
     * or using internal logic to calculate the rate from $request
     * you can see an example in Mage_Usa_Model_Shipping_Carrier_Ups::setRequest()
     */
 
    // get necessary configuration values
    $handling = Mage::getStoreConfig('carriers/'.$this->_code.'/handling');
 
    // this object will be returned as result of this method
    // containing all the shipping rates of this method
    $result = Mage::getModel('shipping/rate_result');
 
    // $response is an array that we have 
    foreach ($response as $rMethod) {
      // create new instance of method rate
      $method = Mage::getModel('shipping/rate_result_method');
 
      // record carrier information
      $method->setCarrier($this->_code);
      $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
 
      // record method information
      $method->setMethod($rMethod['code']);
      $method->setMethodTitle($rMethod['title']);
 
      // rate cost is optional property to record how much it costs to vendor to ship
      $method->setCost($rMethod['amount']);
 
      // in our example handling is fixed amount that is added to cost 
      // to receive price the customer will pay for shipping method.
      // it could be as well percentage: 
      /// $method->setPrice($rMethod['amount']*$handling/100);
      $method->setPrice($rMethod['amount']+$handling);
 
      // add this rate to the result
      $result->append($method);
    }
 
    return $result;
  }
}

Soon after you have created a Model, just give admin an option to configure it and let checkout process made aware of this (it will show up in checkout process which your users can choose to pay).

How To Develop Admin Module For Shipping Customizations

Once, you are done with the above steps, you need to inform Magento that there is a new Payment Module which needs to be configured and displayed in admin. In order to do so, you need to create app/code/local/YourCompany/NewModule/etc/system.xml file and put the following lines of code in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
 
<?xml version="1.0"?>
<config>
   <sections>
    <carriers>
        <groups>
            <newmodule translate="label" module="shipping">
                <label>Carrier Name</label>
                <frontend_type>text</frontend_type>
                <sort_order>13</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>1</show_in_store>
                   <fields>
                      <account translate="label">
                            <label>Account number</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>7</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </account>
                        <active translate="label">
                            <label>Enabled</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </active>
                        <contentdesc translate="label">
                            <label>Package Description</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>12</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </contentdesc>
                        <!--
                        If the free_shipping_enable flag enable, the system will check free_shipping_subtotal to give free shipping
                        otherwise will use shopping cart price rule behaviour
                        -->
                        <free_shipping_enable translate="label">
                            <label>Free shipping with minimum order amount</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_enabledisable</source_model>
                            <sort_order>21</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </free_shipping_enable>
                        <free_shipping_subtotal translate="label">
                            <label>Minimum order amount for free shipping</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>22</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </free_shipping_subtotal>
                        <dutiable translate="label">
                            <label>Shipment Dutiable</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>13</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </dutiable>
                        <gateway_url translate="label">
                            <label>Gateway URL</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </gateway_url>
                        <handling_type translate="label">
                            <label>Calculate Handling Fee</label>
                            <frontend_type>select</frontend_type>
                            <source_model>shipping/source_handlingType</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
                        </handling_type>
                        <handling_action translate="label">
                            <label>Handling Applied</label>
                            <frontend_type>select</frontend_type>
                            <source_model>shipping/source_handlingAction</source_model>
                            <sort_order>11</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>0</show_in_store>
                        </handling_action>
                        <handling_fee translate="label">
                            <label>Handling fee</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>12</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </handling_fee>
                        <max_package_weight translate="label">
                            <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>13</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </max_package_weight>
                        <id translate="label">
                            <label>Access ID</label>
                            <frontend_type>text</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>5</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </id>
                        <password translate="label">
                            <label>Password</label>
                            <frontend_type>text</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>6</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </password>
                        <shipping_intlkey translate="label">
                            <label>Shipping key (International)</label>
                            <frontend_type>text</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>8</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </shipping_intlkey>
                        <shipping_key translate="label">
                            <label>Shipping key</label>
                            <frontend_type>text</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>8</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </shipping_key>
                        <sort_order translate="label">
                            <label>Sort order</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>100</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </sort_order>
                        <title translate="label">
                            <label>Title</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </title>
                        <sallowspecific translate="label">
                            <label>Ship to applicable countries</label>
                            <frontend_type>select</frontend_type>
                            <sort_order>90</sort_order>
                            <frontend_class>shipping-applicable-country</frontend_class>
                            <source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </sallowspecific>
                        <specificcountry translate="label">
                            <label>Ship to Specific countries</label>
                            <frontend_type>multiselect</frontend_type>
                            <sort_order>91</sort_order>
                            <source_model>adminhtml/system_config_source_country</source_model>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </specificcountry>
                        <showmethod translate="label">
                            <label>Show method if not applicable</label>
                            <frontend_type>select</frontend_type>
                            <sort_order>92</sort_order>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </showmethod>
                        <specificerrmsg translate="label">
                            <label>Displayed Error Message</label>
                            <frontend_type>textarea</frontend_type>
                            <sort_order>80</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </specificerrmsg>
                    </fields>
                </newmodule>
            </groups>
        </carriers>
    </sections>
</config>

Once this file is saved you will find your new Payment Module under System> Configuration > Shipping Methods. It’s now up to you to add your custom fields in the fields tag, and subsequently make your configuration do something constructive.

Please leave me a comment and let me know if you run into any problems implementing the above code.


18 August 2009

We are proud to announce our FREE Magento theme for our blog readers and rest of the Magento community. Magik Soft Goods  is really a simple yet complicated Free Magento theme with no paid version means its entirely free. Our goal is to design and offer stunning free themes to the Magento community. You will also be able to download the theme from the Magento Connect. This article will give you a brief of what does it have in terms of design elements and few functional aspects. It’s one of our proudest work and I hope you like it.

Screenshots:

Magik soft Goods Category View

Magik soft Goods - Category View


Magik Soft Goods - Product Description Popup

Magik Soft Goods - Product Description Popup

Live Demo

Like what you see?  Be sure to check out the live demo to see Magik Soft Goods.

Download

Although, you can download this free theme from Magento Connect but if you are interested in playing with this theme before going live leave us a tweet @magentomagik. Send us a message in twitter and we will get back to you with the source code. You can also contact us by filling our form.

Cross Browser Compatible

I’ve tried my full efforts to make Magik Soft Goods play nice with all the major browsers.  The following  browsers have been personally verified by us: Internet Explorer 6.0+, Firefox 2+, Opera 9+, Safari 3+ and Chrome 0.2+!

License

This is a free theme.  You may use, alter, tweak, tamper, modify and mangle it to your liking.  But please leave the footer links in tact.  I know it sucks, if you still like to remove the links from footer then please signup with us for one time fee of $25.

Support

This theme is provide as is and we do not provide  free online support. Still, in order to order to obtain support please contact us.

What do you think about this free theme please leave us a comment and let us know.


17 August 2009

magento-lightbox-installation-guide

Have you ever wondered how people are showing larger images for products on mouseover or mouse click using lightbox (very popular JavaScript library). Adding Lightbox to your magento theme is not difficult and by adding very little code to your theme you can get the Lightbox functionality easily. Lightbox will give the ability to highlight your products by showing lager image of the product along with brief description. Our approach will be based on default layout, you can change the theme name based on your selection.

Steps To Add Lightbox To Magento Theme (Prerequisites)

Following are the steps to add Lightbox to your Magento Theme

  1. Download Lightbox from here
  2. Make a directory called /lightbox under /skin/frontend/default/default/js/ and copy the entire lighbox code under that directory. Once done, your directory will look like /skin/frontend/default/default/js/lightbox (all code under this directory)
  3. copy the lightbox.js under /magento/js/lightbox (create a folder under js directory and name it lightbox). If you installation is under root directory then copy it under /root/js/lightbox
  4. Now, you should copy the lightbox.css to /skin/frontend/default/default/css directory.
  5. Create a folder called lightbox under /skin/frontend/default/default/images. Your directories for images will finally look like /skin/frontend/default/default/images/lightbox. Copy all the images from source lightbox directory here.

Changing Lightbox default’s As Per Your Magento Theme

Lightbox is free open source JavaScript library to suit any kind of environment. In order to use Lightbox with Magento we have to change few default settings by assigning your theme’s original path. Following are few changes which you have to make in order to install Lightbox with your Magento theme installation.

How To Change Image Directory Location Of The Lightbox

Soon after you are done with the above pre-requisites change the following code by editing /skin/frontend/default/default/css/lightbox.css

find the following line of code

1
background: transparent url(../images/blank.gif) no-repeat;

and replace it with

1
background: transparent url(../images/lightbox/blank.gif) no-repeat;

Now find the following line of code

1
#prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; }

and replace it with

1
#prevLink:hover, #prevLink:visited:hover { background: url(../images/lightbox/prevlabel.gif) left 15% no-repeat; }

Find the following line of code

1
#nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; }

and replace it with

1
#nextLink:hover, #nextLink:visited:hover { background: url(../images/lightbox/nextlabel.gif) right 15% no-repeat; }

Now, lets make few changes in the lighbox.js file which will be found under /skin/frontend/default/default/js/lightbox/lightbox.js
Edit this JS file with your favorite editor and find the following line of code

1
2
fileLoadingImage: 'images/loading.gif',     
fileBottomNavCloseImage: 'images/closelabel.gif',

and replace these lines with this

1
2
fileLoadingImage: SKIN_URL + 'images/lightbox/loading.gif',     
fileBottomNavCloseImage: SKIN_URL + 'images/lightbox/closelabel.gif',

Now, change the head.phtml file which will be found under /app/design/frontend/default/default/template/page/html/head.phtml
Edit this file using your favorite editor and find the following line of code

1
2
3
<script type="text/javascript">var BLANK_URL = '<?php echo $this->helper('core/js')->getJsUrl('blank.html') ?>';
var BLANK_IMG = '<?php echo $this->helper('core/js')->getJsUrl('spacer.gif') ?>';
</script>

replace this code with the following line of code

1
2
3
<script type="text/javascript">var BLANK_URL = '<?php echo $this->helper('core/js')->getJsUrl('blank.html') ?>';
var BLANK_IMG = '<?php echo $this->helper('core/js')->getJsUrl('spacer.gif') ?>';
var SKIN_URL = '<?php echo $this->helper('core/js')->getJsSkinUrl('') ?>';</script>

Adding Stylesheet & JavaScript To Your Magento Installation

Open page.xml from /app/design/frontend/default/default/layout/page.xml using your favorite editor.

Under the following line of code

1
2
3
<block type="page/html_head" name="head" as="head">
         ....
</block>

Add this

1
2
<action method="addItem"><type>skin_js</type><name>js/lightbox/lightbox.js</name></action>
<action method="addCss"><stylesheet>css/lightbox.css</stylesheet></action>

AFTER the prototype.js. It is recommended to add the two lines where the list of js and css files intersect so it will look something like this:

1
2
3
4
5
6
     ...
<action method="addJs"><script>mage/cookies.js</script></action>
<action method="addItem"><type>skin_js</type><name>js/lightbox/lightbox.js</name></action>
<action method="addCss"><stylesheet>css/lightbox.css</stylesheet></action>
<action method="addCss"><stylesheet>css/reset.css</stylesheet></action
    ...

How To Add Lightbox To Magento Product Detail Page

Edit media.phtml from /app/design/frontend/default/default/template/catalog/product/view/media.phtml using your favorite editor

Find the following line of code

1
2
3
4
5
<?php foreach ($this->getGalleryImages() as $_image): ?>
<li><a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'scrollbars=yes,width=200,height=200,resizable=yes');return false;">
<img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(68,68); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"/></a>
</li>
<?php endforeach; ?>

and replace the above lines with this

1
2
3
4
<?php foreach ($this->getGalleryImages() as $_image): ?>
<li><a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()); ?>" rel="lightbox[rotation]" title="<?php echo $_product->getName();?>"><img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(68, 68); ?>" width="68" height="68" alt=""/></a>
</li>
<?php endforeach; ?>

Now, you are all set. You will see the Lightbox opening up for your product images. Leave me a comment and let me know if you run into any difficulty.


12 August 2009

magento-export-profile

People often find exporting data from Magento difficult. In order to get CSV file downloaded on your PC you have to follow certain steps. Remember you must have admin privileges before indulging yourself in this task.

Here is how you can download the export file from your system.

  1. Log In to Magento Admin panel of your site.
  2. Go to System > Import/Export > Profiles
  3. You will see a list of profiles available for download.
  4. Suppose, you want to download (export) all existing products from the system. Click on “Export All Products” profile. You will be redirected to profile page.
  5. Click on “Run Profile” option from the left menu. Once you hit “Run Profile” it will display a popup box containing profile name which will start soon after you confirm. Product export file generation will start and finish automatically. (This process may take some time depending upon your bandwidth and product count.)
  6. After completion you can see Saved successfully: “export_all_products.csv” message & file is saved in “var/export” directory.
  7. You have two options to get the CSV file on your computer.
    1. Log on to your server using any ftp client and download the CSV file.
    2. Use the code below to set your system to automatically download the entire export directory as and when required.

How To Download Export Directory On Your Desktop

Downloading a CSV (exported) file from your server using ftp client becomes a pain as you need to connect and download the file manually.  In order to overcome this problem we have programmed a code which will download the entire export directory on your desktop without the need of ftp softwares.

Suppose the path of the export file for your Magento installation is “var/export”. It may change depending upon the installation (ask your server guy to help you here). Once you run the profile to export files using the above method your CSV will be generated at this path.

The following code will download the entire export folder in zipped format on your desktop.

Class to zip the entire export folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php
/* Class to dynamically create a zip file (archive) of file(s) and/or directory */
 
class CreateZipFile {
 
	public $compressedData = array();
	public $centralDirectory = array(); // central directory
	public $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
	public $oldOffset = 0;
 
	/**
	 * Function to create the directory where the file(s) will be unzipped
	 *
	 * @param string $directoryName
	 * @access public
	 * @return void
	 */	
	public function addDirectory($directoryName) {
		$directoryName = str_replace("\\", "/", $directoryName);
		$feedArrayRow = "\x50\x4b\x03\x04";
		$feedArrayRow .= "\x0a\x00";
		$feedArrayRow .= "\x00\x00";
		$feedArrayRow .= "\x00\x00";
		$feedArrayRow .= "\x00\x00\x00\x00";
		$feedArrayRow .= pack("V",0);
		$feedArrayRow .= pack("V",0);
		$feedArrayRow .= pack("V",0);
		$feedArrayRow .= pack("v", strlen($directoryName) );
		$feedArrayRow .= pack("v", 0 );
		$feedArrayRow .= $directoryName;
		$feedArrayRow .= pack("V",0);
		$feedArrayRow .= pack("V",0);
		$feedArrayRow .= pack("V",0);
		$this->compressedData[] = $feedArrayRow;
		$newOffset = strlen(implode("", $this->compressedData));
		$addCentralRecord = "\x50\x4b\x01\x02";
		$addCentralRecord .="\x00\x00";
		$addCentralRecord .="\x0a\x00";
		$addCentralRecord .="\x00\x00";
		$addCentralRecord .="\x00\x00";
		$addCentralRecord .="\x00\x00\x00\x00";
		$addCentralRecord .= pack("V",0);
		$addCentralRecord .= pack("V",0);
		$addCentralRecord .= pack("V",0);
		$addCentralRecord .= pack("v", strlen($directoryName) );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("V", 16 );
		$addCentralRecord .= pack("V", $this->oldOffset );
		$this->oldOffset = $newOffset;
		$addCentralRecord .= $directoryName;
		$this->centralDirectory[] = $addCentralRecord;
	}
 
	/**
	 * Function to add file(s) to the specified directory in the archive 
	 *
	 * @param string $directoryName
	 * @param string $data
	 * @return void
	 * @access public
	 */	
	public function addFile($data, $directoryName)   {
		$directoryName = str_replace("\\", "/", $directoryName);
		$feedArrayRow = "\x50\x4b\x03\x04";
		$feedArrayRow .= "\x14\x00";
		$feedArrayRow .= "\x00\x00";
		$feedArrayRow .= "\x08\x00";
		$feedArrayRow .= "\x00\x00\x00\x00";
		$uncompressedLength = strlen($data);
		$compression = crc32($data);
		$gzCompressedData = gzcompress($data);
		$gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2);
		$compressedLength = strlen($gzCompressedData);
		$feedArrayRow .= pack("V",$compression);
		$feedArrayRow .= pack("V",$compressedLength);
		$feedArrayRow .= pack("V",$uncompressedLength);
		$feedArrayRow .= pack("v", strlen($directoryName) );
		$feedArrayRow .= pack("v", 0 );
		$feedArrayRow .= $directoryName;
		$feedArrayRow .= $gzCompressedData;
		$feedArrayRow .= pack("V",$compression);
		$feedArrayRow .= pack("V",$compressedLength);
		$feedArrayRow .= pack("V",$uncompressedLength);
		$this->compressedData[] = $feedArrayRow;
		$newOffset = strlen(implode("", $this->compressedData));
		$addCentralRecord = "\x50\x4b\x01\x02";
		$addCentralRecord .="\x00\x00";
		$addCentralRecord .="\x14\x00";
		$addCentralRecord .="\x00\x00";
		$addCentralRecord .="\x08\x00";
		$addCentralRecord .="\x00\x00\x00\x00";
		$addCentralRecord .= pack("V",$compression);
		$addCentralRecord .= pack("V",$compressedLength);
		$addCentralRecord .= pack("V",$uncompressedLength);
		$addCentralRecord .= pack("v", strlen($directoryName) );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("V", 32 );
		$addCentralRecord .= pack("V", $this->oldOffset );
		$this->oldOffset = $newOffset;
		$addCentralRecord .= $directoryName;
		$this->centralDirectory[] = $addCentralRecord;
	}
 
	/**
	 * Function to return the zip file
	 *
	 * @return zipfile (archive)
	 * @access public
	 * @return void
	 */
	public function getZippedfile() {
		$data = implode("", $this->compressedData);
		$controlDirectory = implode("", $this->centralDirectory);
		return
		$data.
		$controlDirectory.
		$this->endOfCentralDirectory.
		pack("v", sizeof($this->centralDirectory)).
		pack("v", sizeof($this->centralDirectory)).
		pack("V", strlen($controlDirectory)).
		pack("V", strlen($data)).
		"\x00\x00";
	}
 
	/**
	 *
	 * Function to force the download of the archive as soon as it is created
	 *
	 * @param archiveName string - name of the created archive file
	 * @access public
	 * @return ZipFile via Header
	 */
	public function forceDownload($archiveName) {
		if(ini_get('zlib.output_compression')) {
			ini_set('zlib.output_compression', 'Off');
		}
 
		// Security checks
		if( $archiveName == "" ) {
			echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> The download file was NOT SPECIFIED.</body></html>";
			exit;
		}
		elseif ( ! file_exists( $archiveName ) ) {
			echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> File not found.</body></html>";
			exit;
		}
 
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false);
		header("Content-Type: application/zip");
		header("Content-Disposition: attachment; filename=".basename($archiveName).";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($archiveName));
		readfile("$archiveName");
	}
 
	/**
	  * Function to parse a directory to return all its files and sub directories as array
	  *
	  * @param string $dir
	  * @access private
	  * @return array
	  */
	private function parseDirectory($rootPath, $seperator="/"){
		$fileArray=array();
		$handle = opendir($rootPath);
		while( ($file = @readdir($handle))!==false) {
			if($file !='.' && $file !='..'){
				if (is_dir($rootPath.$seperator.$file)){
					$array=$this->parseDirectory($rootPath.$seperator.$file);
					$fileArray=array_merge($array,$fileArray);
				}
				else {
					$fileArray[]=$rootPath.$seperator.$file;
				}
			}
		}		
		return $fileArray;
	}
 
	/**
	 * Function to Zip entire directory with all its files and subdirectories 
	 *
	 * @param string $dirName
	 * @access public
	 * @return void
	 */
	public function zipDirectory($dirName, $outputDir) {
		if (!is_dir($dirName)){
			trigger_error("CreateZipFile FATAL ERROR: Could not locate the specified directory $dirName", E_USER_ERROR);
		}
		$tmp=$this->parseDirectory($dirName);
		$count=count($tmp);
		$this->addDirectory($outputDir);
		for ($i=0;$i<$count;$i++){
			$fileToZip=trim($tmp[$i]);
			$newOutputDir=substr($fileToZip,0,(strrpos($fileToZip,'/')+1));
			$outputDir=$outputDir.$newOutputDir;
			$fileContents=file_get_contents($fileToZip);
			$this->addFile($fileContents,$fileToZip);
		}
	}
}
?>

Code to download export directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
include_once("CreateZipFile.inc.php");
$createZipFile=new CreateZipFile;
 
$directoryToZip="var/export"; // This will zip all the file(s) in this present working directory. Change this to your export directory
 
$outputDir="/"; //Replace "/" with the name of the desired output directory.
$zipName="export.zip";
 
//Code toZip a directory and all its files/subdirectories
$createZipFile->zipDirectory($directoryToZip,$outputDir);
 
$rand=time();
$zipName=$rand."_".$zipName;
$fd=fopen($zipName, "wb");
$out=fwrite($fd,$createZipFile->getZippedfile());
fclose($fd);
$createZipFile->forceDownload($zipName);
@unlink($zipName);
 
?>

Make sure you verify the the path of the export directory “var/export” in our case. Now upload these two PHP files on the same server where Magento is installed.

How it works?

PHP code will find the path of the export directory, it will result in error if the path is not found. Once the path is found and verified it will zip the entire export folder and initiate the download. Once these two files are added to the Magento root directory you can run it like this – http://yoursite.com/exportdata.php (considering you have uploaded exportdata.php on your root).

Leave us a comment and let me know if you run into any Magento export related problems.


10 August 2009

magnento-ecommerce-store

If you are an existing store owner then you must have heard about Mangento for sure. Magento is an Open Source ecommerce web application built on Zend Framework created by Varien.Varien initially started working on osCommerce and wanted to built their own product but later decided to create their own E-Commerce application on Zend Framework. They launched their public beta in 2007 and since then they have released significant updates.

Now, Magento is very popular amongst online store owners and due to its strong backend (Zend Framework) it is giving good results. This success gave boost to the Magento  and now there are two versions available in the market.

1. Community Edition (No Community Support, available for FREE)
2. Enterprise Edition (Starting with $8,900 USD/yr)

Magento Connect

Magento supports installation of modules through a web based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.
There are three categories of modules hosted on Magento Connect:

  • Core Modules
  • Community Modules
  • Commercial Modules

Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

If you are using any other Ecommerce open source application then give Magento a try and you won’t regret for sure. Leave us a comment and share your experiences of Magento ecommerce application with us.