CS-Cart Customization: Product Downloads Counter

Notice: This post is aimed at experienced users. It applies to CS-Cart v.3.0.x.

I have already written posts about the CS-Cart shopping cart, here is a new one!

Here is a scenario:

You sell downloadable digital products in your CS-Cart store.

You want to know how many times a user downloaded a file.

You need to keep records of when the customer first and last downloaded the product.

CS-Cart lets you sell digital and downloadable products very easily. It keeps also track of how many times a user “clicked” on the download link (but does not tell you if the file was correctly sent to the user, which might cause an issue if you want to fully refund not-downloaded orders)

Make these modifications to put things in the right way:

1- Edit: <CS-CART_ROOT>/controllers/customer/orders.php

and replace the ‘get_file’ mode block (lignes 403 to 435, may vary upon versions) with the following block:

} elseif ($mode == 'get_file') {

	$field = empty($_REQUEST['preview']) ? 'file_path' : 'preview_path';

	if (($field == 'file_path' && !empty($_REQUEST['ekey']) || $field == 'preview_path')) {

		if (!empty($_REQUEST['ekey'])) {

			$ekey_info = fn_get_product_edp_info($_REQUEST['product_id'], $_REQUEST['ekey']);

			if (empty($ekey_info) || $ekey_info['file_id'] != @$_REQUEST['file_id']) {
				return array(CONTROLLER_STATUS_DENIED);
			}

			// Increase downloads for this file
			$max_downloads = db_get_field("SELECT max_downloads FROM ?:product_files WHERE file_id = ?i", $_REQUEST['file_id']);
			$file_downloads = db_get_field("SELECT downloads FROM ?:product_file_ekeys WHERE ekey = ?s AND file_id = ?i", $_REQUEST['ekey'], $_REQUEST['file_id']);

			if (!empty($max_downloads)) {
				if ($file_downloads >= $max_downloads) {
					return array(CONTROLLER_STATUS_DENIED);
				}
			}

		}

		$file = db_get_row("SELECT $field, file_name, product_id FROM ?:product_files LEFT JOIN ?:product_file_descriptions ON ?:product_file_descriptions.file_id = ?:product_files.file_id AND ?:product_file_descriptions.lang_code = ?s WHERE ?:product_files.file_id = ?i", CART_LANGUAGE, $_REQUEST['file_id']);

		if (!empty($file)) {
			if(fn_get_file(DIR_DOWNLOADS . $file['product_id'] . '/' . $file[$field]) != false)
			{
				db_query('UPDATE ?:product_file_ekeys SET ?u WHERE file_id = ?i AND product_id = ?i AND order_id = ?i', array('downloads' => $file_downloads + 1), $_REQUEST['file_id'], $ekey_info['product_id'], $ekey_info['order_id']);

			}
		}
	}

	return array(CONTROLLER_STATUS_DENIED);

2- Edit <CS-CART_ROOT>/core/fs.fs.php and change the line 332 (where the fn_get_file function calls the “exit;”) to the following:

			return false;

These modifications, make sure the file is sent to the user before increasing the download counter.

Now, lets make the download counter visible in your administration panel.

1- Edit <CS-CART_ROOT>/skins/<ACTIVE_ADMIN_SKIN>/admin/views/orders/details.tpl

After line 343, inside the TR tag, add the column header:

<th>{$lang.downloads_count}</th>

Now, after line 354, add the download counter value:

<td>{$file.downloads}</td>

Save your file and refresh your CS-Cart cache by opening your store’s administration panel and then adding &cc to the end of the page url (if you are on the admin index, also add a “?”)

example: https://www.examplestore.com/administration.php?&cc

Now, go to a confirmed/processed order and on the downloads tab you will have:

CS-Cart download counter in administration panel

In the next post, I will write about how to keep track of first and last download times to let you know more about your customers.

 

Optimize your CS-Cart store

Speed up CS-Cart

Faster websites get better SEO scores and get better indexes in search engines, a Google employee once said “Website should be fast”, your visitors will agree, trust me.

 

CS-Cart more salesFaster and optimized eCommerce websites do sell +40% more than slower ones, just because they are faster. You “will” agree once you see the money come 😉  trust me.

 

In the continuity of my “Website optimization” posts, this time we will see how to optimize CS-Cart, but hints and methods written here are useful for all other platforms, just you will need to adapt, easily.

E-Commerce Optimization

I assume you already know about the ROCK SOLID eCommerce software “CS-Cart”, if not, you are missing BIG!

odience.net|works sponsored this post and asked me to optimize their online marketplace which is based on CS-Cart.

The outcome? A faster CS-Cart store which loads in less than 5 seconds and gets a performance grade of 94/100 and on some pages 99/100 (check for yourself at Pingdom), this literally “ROCKS”.

UPDATE: Based on my work 😉 , odience.net|works made a package that CS-Cart users can use to speed-up their stores. Will be available soon!

Now we will see in this post, how you can optimize your site load times and speed.

A little bit more than “few” technical knowledge is required if you want to read on, but you never know, maybe you will learn on the way 😉

I will expose different steps and aspects of optimization which are also applicable with other websites as we saw in my previous posts.

 

Time Matters

From an optimization point of view, even 0.1 second in load time matters so let’s get started.

 

Optimize Cache, Server side:

CS-Cart integrates a built-in cache, but that needs lots of modifications to be “robust” and “reliable”.

Here are some issues with CS-Cart’s cache:

  • It “kind of” compresses the JavaScript files but doesn’t combine them! So you find your self serving multiple files which is BAD for load time.
  • It does not cache external JS files you include with the {script} tag. OK, this might be “over doing” but it might be interesting as for serving “hosted” Google Analytics JS on CS-Cart…
  • It “combines” the CSS files but does not compress them, so you will be sending the user a quite BIG file; and that is BAD for page speed too.
  • It does not compress nor clean the HTML output, and again, BAD for speed.
  • It does not serve files with the right expires header so no one know when to refresh the content! How a browser is supposed to know what and when to cache?

Well, what to do, is to optimize this caching to the maximum and make the page generation faster and faster.

So for example the same time CS-Cart “combines” CSS files, let’s tell it to “compress” the output CSS file. When it compresses JavaScript files “independently” let’s ask for a combined and compressed output file, in the mean while, cache external JS files to limit multi-domain requests for the user.

Backup AlertThese steps are quite complex, and need core modification, so you must be careful when updating/upgrading your CS-Cart installation to keep a backup of your MODs.

SMARTY

smarty logoIf you don’t know it already, CS-Cart runs Smarty for its template engine. Smarty is basically great from an ease of use point of view, but unfortunately, Smarty v2 is not optimized for speed. Well, Smarty did great on its Smarty v3 on speed optimization, and included multiple cache handlers like eAccelerator, APC and others.

APC

Alternative PHP Cache LogoI have to mention that APC caching improves A LOT your site performance, but, Smarty v2 does not contain an APC cache handler, so I made an APC cache handler for Smarty v2, and thus for CS-Cart 3, which makes your content load directly from “RAM” instead of Hard Drive. This means “very fast”.

CS-Cart Core Optimizers

You can download these “Optimizers” from my Downloads page  odience Market, instructions included.

 

Optimize Cache, Client side:

To tell the browser which files to cache and which ones to not, your server must send correct “Expires headers”.

Unfortunately CS-Cart does not set theme correctly. This causes your client’s browser NOT to cache and ask for every page element at each request. Seriously, you DO NOT WANT THIS, because, wait for it…. BAD for speed!

You will need to edit your HTACCESS file(s) to send correct “cache” headers to the user directly from your server.

CS-Cart Optimized HTACCESS

You can download a sample of the “CS-Cart Optimized HTACCESS” from my Downloads page and for the full version, check odience Market, instructions included.

 

Combine JavaScript files:

Merge JS and CSS files

As I wrote before, CS-Cart just “compresses” JavaScript files and it does NOT combine the files. You need to combine the compressed JavaScript files to use less bandwidth and send the file FASTER to the user, because JavaScript files are “VERY DANGEROUS” for page speed.

A JavaScript file  literally blocks all other elements from loading until itself gets fully loaded, so you want it to be “alone” and to finish loading, wait for it …. …. …. FAST!

CS-Cart JS Optimizer

Get the “JavaScript Combine&Compress Smarty output filter”; that I wrote; from odience Market, instructions included.

 

Compress CSS files:

Compress content

There are lots of great Open Source projects (ex. Minify) which allow great CSS optimization, combination and compression. I don’t know why CS-Cart does not integrate one such library?

Well, all that said, you need to compress CSS files, and more precisely, Minify them to let users receive just what they need to “style”, nothing more nothing less.

Use less files, Use more SPRITES:

CSS Sprites example

CS-Cart uses a lot of small icons for its base skin.

If your current skin is using more than 20 different icons (not product images, just icons, ex. account icon, cart icon, live help icon, menu drop down arrows,…) you should think about combining them into a single file to decrease the number of requests a visitor’s browser makes to your server. This combination reduces significantly your page load time and speeds up your CS-Cart store. So, go ahead  and combine your small icons into one or two bigger image sprites to reduce file requests as these requests are BAD for speed.

There are some free tools which help you automate and simplify sprites generation:

CS-Cart Sprites based Basic skin

Still not finished, but I am working on creating a sprites based “Basic” skin for CS-Cart, help is much appreciated.

 

Use a CDN for your static contents:

CDN77.com Europe Pops

CDN, CDN, CDN! (It stands for Content Delivery Network if your are new :D)

If you got the $$$ to run with the big guys, go with AKAMAI, Amazon and other big Content Delivery Networks.

But! You can set your FREE CDN too! just serve your static content from a different sub-domain (or domain), for exemple:

Serve images from

https://staticimg.yourdomain.com/images/

while serving your mains website from

https://www.yourdomain.com/

This allows “parallel” downloads which will increase significantly page speed.

Well, serving JavaScript and CSS files from a CDN is something to think twice about, because CS-Cart generates your CSS and JS files every time you refresh the cache so if you are on a CDN, that would happen slower than you expect.

To make CS-Cart “CDN-compatible” you will need to make few changes to your skin’s files. If you focus on moving only your images to the CDN, it would be quite easy, though you should also think about the Addons and their images.

Basically, by overriding the $images_dir SMARTY variable at the right moment, you can tell CS-Cart to go get the images from a CDN, though some minor modifications should be done on core smarty plugin files to let CSS files compile correctly.

Another great idea to setup a CDN for CS-Cart is to mount your CDN space as a partition (mount point) on your server and symlink your static directories (images, css, js, cache) to the mount point, this reduces all synchronisation lags, and saves you from changing core files.

CDN CS-CartBut, a better idea, is to use a “Mirror CDN” like CDN77.com!

 

I already tested CDN77.com and the service is great. They offer a 14 days free trial, which lets you know if you are ready for CDN.

I really recommend them because of the number of pops (servers worldwide) and their affordable price ($4.90 /100GB of data, THIS IS VERY LOW!). So, if you need a CDN, sign up for CDN77.com and make your CS-Cart s

ite faster!

Let me explain on how to use a mirror CDN for your CS-Cart ecommerce software:

  1. Open an account on CDN77.com
  2. Create a new CDN
  3. If you need SSL (I recommend it if you have a secure store)
  4. Choose Free SSL (shared)
  5. or choose a custom SSL (ex.: “https://cdn1.gibni.com/” for 39$/month)
  6. Let 4 minutes pass by, for the CDN to be setup of course!
  7. Modify your CS-Cart store to serve images (you can do it even for CSS and JS, but not really needed, as you would have less than 5 JS and CSS files; it’s up to you!)
  8. Enjoy your Free CDN! (Yes, as simple as that, weird huh?)

 

Use a cookie-less domain for static components:

CS-Cart Cookie

Sites setting cookies will send/set the cookie file (0.8 – 1.5 KB) for each requested component (even for static images and css/js files).

These static contents do not require a cookie file, so by using a subdomain, or another domain (like a CDN), you will be able to get this point fixed and make your static components “cookie-less”, i.e. about 1K size reduction per element, so again, read the previous section about CDN to setup one for your images (at least).

 

Optimize your server with HTACCESS and PHP.INI tweaks:

Php.ini and Htaccess optimization for CS-Cart

To oil the gears of your server, you might need to have a look at your .htaccess and php.ini (php5.ini) files.

 

Some stuff you could do:

  • Set Expires headers based on file types,
  • Tell the browser to cache CSS and JS files,
  • Unset ETags,
  • Set Gzip/Deflate compression for your HTML/PHP files,
  • Secure access to your server and store,
  • Secure file requests and prevent file request attacks
  • Make sure downloadable files are downloadable! weird, huh?!
  • Add the “missing” trailing slash in your URLs,
  • Rewrite requests to WWW,
  • Force secure connections through HTTPS
  • Install a Virtualized Software Firewall through HTACCESS to protect yourself from hackers
  • Protect  your server and store from unauthorized queries and requests
  • Speed up the server with the PageSpeed Apache module
  • and so on…

Specially with PHP.INI (PHP5.INI) you could:

  • Set a default FROM address directly on the server to get your emails “delivered”
  • Increase execution times and upload file sizes to optimize performance and ease file uploads
  • Activate ZEND extensions to boost your server
  • and so on…

CS-Cart optimized PHP.INI & HTACCESS

Check the optimized PHP5.INI file (created and tested on Godaddy.com’s Shared hosting) and a tweaked (basic) HTACCESS for CS-Cart at my Downloads page.

 

Conclusions

There is a lot to do for a better web, by optimizing your websites and e-shops, you use less bandwidth and energy. Apart from making better sales and getting better SEO scores, you make a greener world. Do not hesitate about optimization.

APC caching for CS-Cart 3 and Smarty 2

Today I got and email from Godaddy saying that Godaddy.com is implementing APC cache from 1st October 2012. APC cache helps your pages load a lot faster, but it is not always easy to implement it into your software. Smarty, the template engine, implements the APC cache from its version 3, but the older versions of Smarty, are a bit trickier to master.

Finding a good way of implementing APC cache to your Smarty 2 is a challenge, but don’t worry, I am here :D.

Here is a method to implement APC cache to your CS-Cart eCommerce software, which is using Smarty 2 as its templating engine:

You need to:

  1. Create a SMARTY cache handler for handling APC cache. Be careful that your APC cache handler must be compatible with SMARTY 2, as of CS-Cart 3 is concerned.Here is the APC cache handler code for Smarty 2:

    Save this code as “cache.apc.php” and place it in your Smarty’s “plugins_dir” folder. (for CS-Cart, save it in:

    <CS-Cart ROOT>/core/smarty_plugins/

    Download APC Cache handler for Smarty 2, useful for CS-Cart 3 from my Downloads page

  2. Modify the CS-Cart core files to initialize APC caching (careful with this step as it requires core modifications)For instructions about the CS-Cart modifications, please contact me.
  3. Enjoy faster loading CS-Cart store!

 

Set cookie domain for CS-Cart

If your are using CS-Cart eCommerce software, you might need to configure CS-Cart to set its cookies to a specific domain or subdomain.
To do this, you need to modify a bit the “CORE” of CS-Cart.

  1. Edit the file :
<CS-CART_ROOT>/core/fn.common.php
  1. Around lines 2035 to 2044, you will find the fn_set_cookie() function,
  2. Modify the last line of this function from:
 return setcookie($var, $value, $expiry, $current_path);


to

 $current_domain = (defined('HTTPS')) ? Registry::get('config.https_path') : Registry::get('config.http_path');
 if ($current_domain != ''){
    return setcookie($var, $value, $expiry, $current_path, $current_domain);
 }else{
    return setcookie($var, $value, $expiry, $current_path);
 }

Happy creating!