Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * 2007-2012 PrestaShop
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@prestashop.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
- * versions in the future. If you wish to customize PrestaShop for your
- * needs please refer to http://www.prestashop.com for more information.
- *
- * @author PrestaShop SA <contact@prestashop.com>
- * @copyright 2007-2011 PrestaShop SA
- * @version Release: $Revision: 16479 $
- * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
- * International Registered Trademark & Property of PrestaShop SA
- */
- if (!defined('_PS_VERSION_'))
- exit;
- class GAnalytics extends Module
- {
- function __construct()
- {
- $this->name = 'ganalytics';
- $this->tab = 'analytics_stats';
- $this->version = '1.4.1';
- $this->author = 'PrestaShop';
- $this->displayName = 'Google Analytics';
- $this->module_key = 'fd2aaefea84ac1bb512e6f1878d990b8';
- parent::__construct();
- if ($this->id AND !Configuration::get('GANALYTICS_ID'))
- $this->warning = $this->l('You have not yet set your Google Analytics ID');
- $this->description = $this->l('Integrate Google Analytics script into your shop');
- $this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');
- /** Backward compatibility */
- require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
- }
- function install()
- {
- if (!parent::install() ||
- !$this->registerHook('header') ||
- !$this->registerHook('orderConfirmation'))
- return false;
- return true;
- }
- function uninstall()
- {
- if (!Configuration::deleteByName('GANALYTICS_ID') || !parent::uninstall())
- return false;
- return true;
- }
- public function getContent()
- {
- $output = '<h2>Google Analytics</h2>';
- if (Tools::isSubmit('submitGAnalytics') AND ($gai = Tools::getValue('ganalytics_id')))
- {
- Configuration::updateValue('GANALYTICS_ID', $gai);
- $output .= '
- <div class="conf confirm">
- <img src="../img/admin/ok.gif" alt="" title="" />
- '.$this->l('Settings updated').'
- </div>';
- }
- if (Tools::isSubmit('submitWG') AND ($wgevid = Tools::getValue('wg_event_id'))
- AND ($wgpin = Tools::getValue('wg_pin')) AND ($wgpgmid = Tools::getValue('wg_pgm_id'))
- )
- {
- Configuration::updateValue('WG_EVENT_ID', $wgevid);
- Configuration::updateValue('WG_PGM_ID', $wgpgmid);
- Configuration::updateValue('WG_PIN', $wgpin);
- $output .= '
- <div class="conf confirm">
- <img src="../img/admin/ok.gif" alt="" title="" />
- '.$this->l('Settings updated').'
- </div>';
- }
- if (Tools::isSubmit('removeOrder') AND ($oid = Tools::getValue('order_id'))){
- $message = 'Order Removed from GA : ';
- $order = new Order((int)$oid);
- if (!$order->id_address_delivery){
- $message = 'BAD ORDER NUMBER : ';
- }else{
- $deliveryAddress = new Address(intval($order->id_address_delivery));
- $conversion_rate = 1;
- if ($order->id_currency != Configuration::get('PS_CURRENCY_DEFAULT'))
- {
- $currency = new Currency(intval($order->id_currency));
- $conversion_rate = floatval($currency->conversion_rate);
- }
- // Order general information
- $trans = array(
- 'id' => intval($order->id), // order ID - required
- //'store' => htmlentities(Configuration::get('PS_SHOP_NAME')), // affiliation or store name
- 'store' => preg_replace('/[\'\x00-\x1F\x80-\xFF]/',' ', Configuration::get('PS_SHOP_NAME')),
- 'total' => Tools::ps_round(floatval($order->total_paid) / floatval($conversion_rate), 2), // total - required
- 'tax' => '0', // tax
- 'shipping' => Tools::ps_round(floatval($order->total_shipping) / floatval($conversion_rate), 2), // shipping
- 'city' => addslashes($deliveryAddress->city), // city
- 'state' => '', // state or province
- 'country' => addslashes($deliveryAddress->country) // country
- );
- $products = $order->getProducts();
- foreach ($products AS $product)
- {
- $category = Db::getInstance()->getRow('
- SELECT name FROM `'._DB_PREFIX_.'category_lang` , '._DB_PREFIX_.'product
- WHERE `id_product` = '.intval($product['product_id']).' AND `id_category_default` = `id_category`
- AND `id_lang` = '.intval($parameters['PS_LANG_DEFAULT']));
- $items[] = array(
- 'OrderId' => intval($order->id), // order ID - required
- 'SKU' => addslashes($product['product_id']), // SKU/code - required
- 'Product' => addslashes($product['product_name']), // product name
- 'Category' => addslashes($category['name']), // category or variation
- 'Price' => Tools::ps_round(floatval($product['product_price_wt']) / floatval($conversion_rate), 2), // unit price - required
- 'Quantity' => addslashes(intval($product['product_quantity'])) //quantity - required
- );
- }
- $ganalytics_id = Configuration::get('GANALYTICS_ID');
- /*print_r($trans);
- print_r($products);*/
- $script = '';
- $script .= '
- var _gaq = _gaq || [];
- _gaq.push([\'_setAccount\', \''.$ganalytics_id.'\']);
- // Recommanded value by Google doc and has to before the trackPageView
- _gaq.push([\'_setSiteSpeedSampleRate\', 5]);
- _gaq.push([\'_addTrans\',
- \''.$trans["id"].'\',
- \''.$trans["store"].'\',
- \'-'.$trans["total"].'\',
- \'-'.$trans["tax"].'\',
- \'-'.$trans["shipping"].'\',
- \''.$trans["city"].'\',
- \''.$trans["state"].'\',
- \''.$trans["country"].'\'
- ]);
- ';
- foreach ($items AS $item)
- {
- $script .= '_gaq.push([\'_addItem\',
- \''.$item["OrderId"].'\',
- \''.$item["SKU"].'\',
- \''.$item["Product"].'\',
- \''.$item["Category"].'\',
- \'-'.$item["Price"].'\',
- \'-'.$item["Quantity"].'\'
- ]);';
- }
- $script .= ' _gaq.push([\'_trackTrans\']);';
- $script .= '
- (function() {
- var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;
- ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';
- var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);
- })();
- ';
- }
- $output .= '
- <div class="conf confirm">
- <script type="text/javascript">
- '.$script.'
- </script>
- <img src="../img/admin/ok.gif" alt="" title="" />
- <p>'.$script.'</p>
- <p>'.$message.$oid.'</p>
- </div>';
- }
- return $output.$this->displayForm();
- }
- public function displayForm()
- {
- $output = '
- <form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
- <fieldset class="width2">
- <legend><img src="../img/admin/cog.gif" alt="" class="middle" />'.$this->l('Settings').'</legend>
- <label>'.$this->l('Your username').'</label>
- <div class="margin-form">
- <input type="text" name="ganalytics_id" value="'.Tools::safeOutput(Tools::getValue('ganalytics_id', Configuration::get('GANALYTICS_ID'))).'" />
- <p class="clear">'.$this->l('Example:').' UA-1234567-1</p>
- </div>
- <center><input type="submit" name="submitGAnalytics" value="'.$this->l('Update ID').'" class="button" /></center>
- </fieldset>
- </form>';
- $output .= '
- <p> </p>
- <form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
- <fieldset class="width2">
- <legend><img src="../img/admin/cog.gif" alt="" class="middle" />WEB GAIN</legend>
- <label>WebGain Event Id</label>
- <div class="margin-form">
- <input type="text" name="wg_event_id" value="'.Tools::safeOutput(Tools::getValue('wg_event_id', Configuration::get('WG_EVENT_ID'))).'" />
- </div>
- <label>WebGain Pin</label>
- <div class="margin-form">
- <input type="text" name="wg_pin" value="'.Tools::safeOutput(Tools::getValue('wg_pin', Configuration::get('WG_PIN'))).'" />
- </div>
- <label>WebGain Program Id</label>
- <div class="margin-form">
- <input type="text" name="wg_pgm_id" value="'.Tools::safeOutput(Tools::getValue('wg_pgm_id', Configuration::get('WG_PGM_ID'))).'" />
- </div>
- <center><input type="submit" name="submitWG" value="Update" class="button" /></center>
- </fieldset>
- </form>';
- $output .= '
- <p> </p>
- <form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
- <fieldset class="width2">
- <legend><img src="../img/admin/cog.gif" alt="" class="middle" />Remove Order</legend>
- <label>Order</label>
- <div class="margin-form">
- <input type="text" name="order_id" value="" />
- <p class="clear">'.$this->l('Example:').' 99840971</p>
- </div>
- <center><input type="submit" name="removeOrder" value="Remove Order" class="button" /></center>
- </fieldset>
- </form>';
- $output .= '
- <fieldset class="space">
- <legend><img src="../img/admin/unknown.gif" alt="" class="middle" />'.$this->l('Help').'</legend>
- <h3>'.$this->l('The first step for tracking e-commerce transactions is to enable e-commerce reporting for your website\'s profile.').'</h3>
- '.$this->l('To enable e-Commerce reporting, please follow these steps:').'
- <ol>
- <li>'.$this->l('Log in to your account').'</li>
- <li>'.$this->l('Click Edit next to the profile you would like to enable.').'</li>
- <li>'.$this->l('On the Profile Settings page, click Edit (next to Main Website Profile Information).').'</li>
- <li>'.$this->l('Change the e-Commerce Website radio button from No to Yes').'</li>
- </ol>
- <h3>'.$this->l('To set up your goals, enter Goal Information:').'</h3>
- <ol>
- <li>'.$this->l('Return to Your Account main page').'</li>
- <li>'.$this->l('Find the profile for which you will be creating goals, then click Edit').'</li>
- <li>'.$this->l('Select one of the 4 goal slots available for that profile, then click Edit').'</li>
- <li>'.$this->l('Enter the Goal URL. Reaching this page marks a successful conversion.').'</li>
- <li>'.$this->l('Enter the Goal name as it should appear in your Google Analytics account.').'</li>
- <li>'.$this->l('Turn on Goal.').'</li>
- </ol>
- <h3>'.$this->l('Then, define a funnel by following these steps:').'</h3>
- <ol>
- <li>'.$this->l('Enter the URL of the first page of your conversion funnel. This page should be a common page to all users working their way towards your Goal.').'</li>
- <li>'.$this->l('Enter a Name for this step.').'</li>
- <li>'.$this->l('If this step is a required step in the conversion process, mark the checkbox to the right of the step.').'</li>
- <li>'.$this->l('Continue entering goal steps until your funnel has been completely defined. You may enter up to 10 steps, or only one step.').'</li>
- </ol>
- '.$this->l('Finally, configure Additional settings by following the steps below:').'
- <ol>
- <li>'.$this->l('If the URLs entered above are case sensitive, mark the checkbox.').'</li>
- <li>'.$this->l('Select the appropriate goal Match Type. (').'<a href="http://www.google.com/support/analytics/bin/answer.py?answer=72285">'.$this->l('Learn more').'</a> '.$this->l('about Match Types and how to choose the appropriate goal Match Type for your goal.)').'</li>
- <li>'.$this->l('Enter a Goal value. This is the value used in Google Analytics\' ROI calculations.').'</li>
- <li>'.$this->l('Click Save Changes to create this Goal and funnel, or Cancel to exit without saving.').'</li>
- </ol>
- <h3>'.$this->l('Demonstration: The order process').'</h3>
- <ol>
- <li>'.$this->l('After having enabled your e-commerce reports and selected the respective profile enter \'order-confirmation.php\' as the targeted page URL.').'</li>
- <li>'.$this->l('Name this goal (for example \'Order process\')').'</li>
- <li>'.$this->l('Activate the goal').'</li>
- <li>'.$this->l('Add \'product.php\' as the first page of your conversion funnel').'</li>
- <li>'.$this->l('Give it a name (for example, \'Product page\')').'</li>
- <li>'.$this->l('Do not mark the \'required\' checkbox because the customer could be visiting directly from an \'adding to cart\' button such as in the homefeatured block on the homepage.').'</li>
- <li>'.$this->l('Continue by entering the following URLs as goal steps:').'
- <ul>
- <li>order/step0.html '.$this->l('(required)').'</li>
- <li>authentication.php '.$this->l('(required)').'</li>
- <li>order/step1.html '.$this->l('(required)').'</li>
- <li>order/step2.html '.$this->l('(required)').'</li>
- <li>order/step3.html '.$this->l('(required)').'</li>
- </ul>
- </li>
- <li>'.$this->l('Check the \'Case sensitive\' option').'</li>
- <li>'.$this->l('Save this new goal').'</li>
- </ol>
- </fieldset>';
- return $output;
- }
- function hookHeader($params)
- {
- // Better way to check which file / controller name is loaded
- if (!($file = basename(Tools::getValue('controller'))))
- $file = str_replace(array('.php', '-'), '', basename($_SERVER['SCRIPT_NAME']));
- // Otherwise, create Google Analytics stats
- $ganalytics_id = Configuration::get('GANALYTICS_ID');
- $multilang = method_exists('Language', 'isMultiLanguageActivated') ? Language::isMultiLanguageActivated() : (Language::countActiveLanguages() > 1);
- $defaultMetaOrder = Meta::getMetaByPage('order',$this->context->language->id);
- $order = ($multilang?((string)Tools::getValue('isolang').'/'):'').$defaultMetaOrder['url_rewrite'];
- $pageTrack = preg_match('#(^'.__PS_BASE_URI__.'order.php)|(^'.__PS_BASE_URI__.($multilang ? ((string)Tools::getValue('isolang').'/') : '').$defaultMetaOrder['url_rewrite'].'[^-])#', $_SERVER['REQUEST_URI']) ?
- '/order/step'.(int)Tools::getValue('step').'.html' : $file;
- $this->context->smarty->assign('ganalytics_id', $ganalytics_id);
- $this->context->smarty->assign('pageTrack', $pageTrack);
- $this->context->smarty->assign('isOrder', false);
- return $this->display(__FILE__, 'header.tpl');
- }
- function hookFooter($params)
- {
- // for retrocompatibility
- if (!$this->isRegisteredInHook('header'))
- $this->registerHook('header');
- return ;
- }
- // MODIF QDUBOIS
- function hookConfirmationPage($params) { return $this->hookOrderConfirmation($params); }
- // END OF MODIF QDUBOIS
- function hookOrderConfirmation($params)
- {
- // Setting parameters
- $parameters = Configuration::getMultiple(array('PS_LANG_DEFAULT'));
- //$order = $params['objOrder'];
- // MODIF QDUBOIS
- $id_order = $_GET['id_order'];
- $order = new Order((int)$id_order);
- // END OF MODIF QDUBOIS
- if (Validate::isLoadedObject($order))
- {
- $deliveryAddress = new Address(intval($order->id_address_delivery));
- $conversion_rate = 1;
- if ($order->id_currency != Configuration::get('PS_CURRENCY_DEFAULT'))
- {
- $currency = new Currency(intval($order->id_currency));
- $conversion_rate = floatval($currency->conversion_rate);
- }
- // Order general information
- $trans = array(
- 'id' => intval($order->id), // order ID - required
- //'store' => htmlentities(Configuration::get('PS_SHOP_NAME')), // affiliation or store name
- 'store' => preg_replace('/[\'\x00-\x1F\x80-\xFF]/',' ', Configuration::get('PS_SHOP_NAME')),
- 'total' => Tools::ps_round(floatval($order->total_paid) / floatval($conversion_rate), 2), // total - required
- 'tax' => '0', // tax
- 'shipping' => Tools::ps_round(floatval($order->total_shipping) / floatval($conversion_rate), 2), // shipping
- 'city' => addslashes($deliveryAddress->city), // city
- 'state' => '', // state or province
- 'country' => addslashes($deliveryAddress->country) // country
- );
- // Product information
- $products = $order->getProducts();
- foreach ($products AS $product)
- {
- $category = Db::getInstance()->getRow('
- SELECT name FROM `'._DB_PREFIX_.'category_lang` , '._DB_PREFIX_.'product
- WHERE `id_product` = '.intval($product['product_id']).' AND `id_category_default` = `id_category`
- AND `id_lang` = '.intval($parameters['PS_LANG_DEFAULT']));
- $items[] = array(
- 'OrderId' => intval($order->id), // order ID - required
- 'SKU' => addslashes($product['product_id']), // SKU/code - required
- 'Product' => addslashes($product['product_name']), // product name
- 'Category' => addslashes($category['name']), // category or variation
- 'Price' => Tools::ps_round(floatval($product['product_price_wt']) / floatval($conversion_rate), 2), // unit price - required
- 'Quantity' => addslashes(intval($product['product_quantity'])) //quantity - required
- );
- }
- $ganalytics_id = Configuration::get('GANALYTICS_ID');
- $wgevid = Configuration::get('WG_EVENT_ID');
- $wgpgmid = Configuration::get('WG_PGM_ID');
- $wgpin = Configuration::get('WG_PIN');
- $doWebGain = false;
- //WEBGAIN
- if ($wgevid) {
- $wgOrderValue = $trans['total'];# total order value in the currency your program runs in (please do not include currency symbol)
- $wgOrderReference = rawurlencode($order->id);
- $wgVoucherCode = rawurlencode(''); #string, used to store the voucher code used for transaction
- $wgCurrency = 'EUR'; #only the following are valid: AUD,CAD,CHF,CZK,DKK,EUR,GBP,HKD,HUF,JPY,NOK,NZD,PLN,SEK,SGD,SKK,USD
- $wgEventID=$wgevid; # this identify's the commission type (in account under Program Setup (commission types))
- $wgComment= ''; #optional field
- $wgMultiple=1;
- $wgItems= rawurlencode('');
- /* (optional) should contain pipe separated list of shopping basket items. Fields for each item are seperated by double colon.
- First field is commission type ,
- second field is price of item,
- third field (optional) is name of item, f
- ourth field (optional) is product code/id, f
- ifth field (optional) is voucher code.
- Example for two items; items=1::54.99::Harry%20Potter%20dvd::hpdvd93876|5::2.99::toothbrush::tb287::voucher1 */
- $wgCustomerID= '';# please do not use without contacting us first
- $wgProductID= '';# please do not use without contacting us first
- /* </variables to be assigned values at run time> */
- /* <variables to be assigned values on install> */
- $wgSLang = 'php';# string, used to identify the programming language of your online systems. Needed because url_encoding differs between platforms.
- $wgLang = 'fr_FR';# string, used to identify the human language of the transaction
- $wgPin = $wgpin;# pin number provided by webgains (in account under Program Setup (program settings -> technical setup))
- $wgProgramID = $wgpgmid; # int, used to identify you to webgains systems
- /* </variables to be assigned values on install> */
- /* <not user configurable> */
- $wgVersion = '1.2';
- $wgSubDomain="track";
- $wgCheckString ="wgver=$wgVersion&wgsubdomain=$wgSubDomain&wglang=$wgLang&wgslang=$wgSLang&wgprogramid=$wgProgramID&wgeventid=$wgEventID&wgvalue=$wgOrderValue&wgorderreference=$wgOrderReference&wgcomment=$wgComment&wgmultiple=$wgMultiple&wgitems=$wgItems&wgcustomerid=$wgCustomerID&wgproductid=$wgProductID&wgvouchercode=$wgVoucherCode";
- $wgCheckSum=md5($wgPin.$wgCheckString); # make checksum
- $wgQueryString = $wgCheckString."&wgchecksum=".$wgCheckSum."&wgCurrency=".$wgCurrency;
- $wgUri = '://'.$wgSubDomain.".webgains.com/transaction.html?".$wgQueryString;
- $doWebGain = true;
- }
- //ENDOF WEBGAIN
- $this->context->smarty->assign('items', $items);
- $this->context->smarty->assign('trans', $trans);
- $this->context->smarty->assign('ganalytics_id', $ganalytics_id);
- $this->context->smarty->assign('wgQueryString', $wgQueryString);
- $this->context->smarty->assign('wgUri', $wgUri);
- $this->context->smarty->assign('wgSubDomain', $wgSubDomain);
- $this->context->smarty->assign('doWebGain', $doWebGain);
- $this->context->smarty->assign('isOrder', true);
- return $this->display(__FILE__, 'header.tpl');
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement