Jump to content

awocoupon tracker for prestashop 1.5


Recommended Posts

Hi there 

 

I have created a tracker for awocoupon with recaptcha on prestashop 1.5

I also merged it with the voucher section under (my-account) which could be accessed via http://example.com/discount

 

But my script cover the case when you don't use the default voucher ;-)

 

Unfortunately I can't upload the files here so I post the code within this post

This should really help for awocoupon users since the tracker is only available for Joomla :(

 

/conlroller/DiscountController.php should have

<?php
/*
* 2007-2013 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 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/osl-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 [email protected] 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 <[email protected]>
*  @copyright  2007-2013 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

class DiscountControllerCore extends FrontController
{
	public $auth = true;
	public $php_self = 'discount';
	public $authRedirection = 'discount';
	public $ssl = true;

	/**
	 * Assign template vars related to page content
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();

		$cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, false);
		$nb_cart_rules = count($cart_rules);

		$this->context->smarty->assign(array('nb_cart_rules' => (int)$nb_cart_rules, 'cart_rules' => $cart_rules, 'discount' => $cart_rules, 'nbDiscounts' => (int)$nb_cart_rules));
		
		
		
		
		
/////////////////////////////////////

$amaboxSCSTR="";
$amaboxSCSTR.="<form action=\"\" method=\"post\">
<div ID=\"scResultDiv\">";
// Get a key from https://www.google.com/recaptcha/admin/create
require_once('recaptchalib.php');
$publickey = "6LdZLvASAAAAAJYgZv6JAzH_6QS6Oif8Sfig_Nco";
$privatekey = "6LdZLvASAAAAAESpmctMW96CO80MocG55Q00-c96";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
	$amaboxlink = mysql_connect(_DB_SERVER_, _DB_USER_, _DB_PASSWD_);
	if (!$amaboxlink) {
		die('Not connected : ' . mysql_error());
	}

	// connect to the current prestashop db
	mysql_select_db(_DB_NAME_, $amaboxlink);

	//check for Coupon ID
	$result_scratch_id = mysql_query("SELECT `id`,`coupon_code`,`coupon_value`,`expiration` from `"._DB_PREFIX_."awocoupon` where `coupon_code`= '".$_POST['AmaboxSCText']."'");
	$amabox_num_rows = mysql_num_rows($result_scratch_id);
	if ($amabox_num_rows<>false){
		//list transactions
		list ($sc_id,$sc_coupon_code,$sc_coupon_value,$sc_expiration) = mysql_fetch_row($result_scratch_id);
		mysql_free_result();
		setlocale(LC_MONETARY, 'en_US');
		$amaboxSCSTR.="Coupon Code: ".$sc_coupon_code."<br>\nOriginal Value: ".money_format('%i', $sc_coupon_value)."<br>\nExpiration Date: ".substr($sc_expiration,0,10)."<br>\n";
		$result_scratch_transaction = mysql_query("SELECT `user_email`, `coupon_discount`, `shipping_discount`, `order_id`, `timestamp` from `"._DB_PREFIX_."awocoupon_history` where `coupon_id`= '".$sc_id."'");
		$amabox_scratch_transaction_num_rows = mysql_num_rows($result_scratch_transaction);
		if ($amabox_scratch_transaction_num_rows<>false){
			$sc_ammount_used=0;
			$amaboxSCSTR.="<table ID=\"sc_remain\"><tr class=\"sc_remain_header\"><td>Used by</td><td>Transaction</td><td>Order Reference</td><td>Date</td><tr>";
			for($sc_counter=0;$sc_counter<$amabox_scratch_transaction_num_rows;$sc_counter++){
				list ($sc_user_email, $sc_coupon_discount, $sc_shipping_discount, $sc_order_id, $sc_timestamp)=mysql_fetch_row($result_scratch_transaction);
				$sc_transaction=$sc_shipping_discount+$sc_coupon_discount;
				$sc_ammount_used+=$sc_transaction;
				$sc_order_reference=mysql_result(mysql_query("SELECT `reference` FROM `"._DB_PREFIX_."orders` WHERE `id_order`='$sc_order_id'"),0);
				$amaboxSCSTR.="<tr><td>$sc_user_email</td><td>".money_format('%i', $sc_transaction)."</td><td>$sc_order_reference</td><td>".substr($sc_timestamp,0,10)."</td><tr>";
				$sc_another_check=1;
			}
			$sc_remain=$sc_coupon_value-$sc_ammount_used;
			$amaboxSCSTR.="<tr><td align=right class=\"sc_remain_value\">Remaining Balace:</td><td class=\"sc_remain_value\">".money_format('%i', $sc_remain)."</td><td></td></td><td></tr></table><hr>";
			mysql_free_result();
		}else{
			$amaboxSCSTR.="<p class=\"warning\">Scratch Card Number ".$_POST['AmaboxSCText']." Not Used Yet</p><hr>";
			$sc_another_check=1;
		}

	}else{
		$amaboxSCSTR.= "<p class=\"warning\">Scratch Card Number ".$_POST['AmaboxSCText']." Does Not Exist</p><hr>";
		$sc_another_check=1;
	}
	mysql_close($amaboxlink);

	} else {
		# set the error code so that we can display it
		$error = $resp->error;
	}
}
$amaboxSCSTR.="</div>";
if($sc_another_check==1){
	$amaboxSCSTR.="<input type=\"button\" value=\"Check Another Scratch Card\" onclick=\"scAnotherCheck();\" id=\"scAnotherCheckInput\">
<script>
function scAnotherCheck(){
	document.getElementById(\"scAnotherCheckInput\").style.display=\"none\";
	document.getElementById(\"scResultDiv\").style.display=\"none\";
	document.getElementById(\"scAnotherCheckDiv\").style.display=\"block\";
	
	}
</script>
<div ID=\"scAnotherCheckDiv\" style=\"display:none;\">\n";
}
$amaboxSCSTR.="Enter Scratch Card Number<br/>\n<input type=\"text\" name=\"AmaboxSCText\"/><br>\n";	
$amaboxSCSTR.= recaptcha_get_html($publickey, $error)."<br/>\n<input type=\"submit\" value=\"Submit\" />\n";
$amaboxSCSTR.="</form>";
if($sc_another_check==1){
	$amaboxSCSTR.="</div>";
}
$this->context->smarty->assign("recaptcha", $amaboxSCSTR); 

/////////////////////////////////////
		
		
		
		
		$this->setTemplate(_PS_THEME_DIR_.'discount.tpl');
	}
}

/themes/yourTheme/discount.tpl show be like:

{*
* 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 [email protected] 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 <[email protected]>
*  @copyright  2007-2012 PrestaShop SA
*  @version  Release: $Revision: 6599 $
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*}
{capture name=path}<a href="{$link->getPageLink('my-account.php', true)}">{l s='My account'}</a><span class="navigation-pipe">{$navigationPipe}</span>{l s='My vouchers'}{/capture}
{include file="$tpl_dir./breadcrumb.tpl"}

<h1>{l s='My vouchers'}</h1>

{if isset($cart_rules) && count($cart_rules) && $nb_cart_rules}
<table class="discount std table_block">
	<thead>
		<tr>
			<th class="discount_code first_item">{l s='Code'}</th>
			<th class="discount_description item">{l s='Description'}</th>
			<th class="discount_quantity item">{l s='Quantity'}</th>
			<th class="discount_value item">{l s='Value'}*</th>
			<th class="discount_minimum item">{l s='Minimum'}</th>
			<th class="discount_cumulative item">{l s='Cumulative'}</th>
			<th class="discount_expiration_date last_item">{l s='Expiration date'}</th>
		</tr>
	</thead>
	<tbody>
	{foreach from=$cart_rules item=discountDetail name=myLoop}
		<tr class="{if $smarty.foreach.myLoop.first}first_item{elseif $smarty.foreach.myLoop.last}last_item{else}item{/if} {if $smarty.foreach.myLoop.index % 2}alternate_item{/if}">
			<td class="discount_code">{$discountDetail.code}</td>
			<td class="discount_description">{$discountDetail.name}</td>
			<td class="discount_quantity">{$discountDetail.quantity_for_user}</td>
			<td class="discount_value">
				{if $discountDetail.id_discount_type == 1}
					{$discountDetail.value|escape:'htmlall':'UTF-8'}%
				{elseif $discountDetail.id_discount_type == 2}
					{convertPrice price=$discountDetail.value}
				{elseif $discountDetail.id_discount_type == 3}
					{l s='Free shipping'}
				{else}
					-
				{/if}
			</td>
			<td class="discount_minimum">
				{if $discountDetail.minimal == 0}
					{l s='None'}
				{else}
					{convertPrice price=$discountDetail.minimal}
				{/if}
			</td>
			<td class="discount_cumulative">
				{if $discountDetail.cumulable == 1}
					<img src="{$img_dir}icon/yes.png" alt="{l s='Yes'}" class="icon" /> {l s='Yes'}
				{else}
					<img src="{$img_dir}icon/no.png" alt="{l s='No'}" class="icon" valign="middle" /> {l s='No'}
				{/if}
			</td>
			<td class="discount_expiration_date">{dateFormat date=$discountDetail.date_to}</td>
		</tr>
	{/foreach}
	</tbody>
</table>
<p>
	*{l s='Tax included'}
</p>
{else}
	{$recaptcha}
	
{/if}

<ul class="footer_links">
	<li><a href="{$link->getPageLink('my-account.php', true)}"><img src="{$img_dir}icon/my-account.png" alt="" class="icon" /> {l s='Back to your account'}</a></li>
	<li class="f_right"><a href="{$base_dir}"><img src="{$img_dir}icon/home.png" alt="" class="icon" /> {l s='Home'}</a></li>
</ul>

and /controller/front/recaptcha.php should have the following code:
 

<?php
/*
 * This is a PHP library that handles calling reCAPTCHA.
 *    - Documentation and latest version
 *          http://recaptcha.net/plugins/php/'>http://recaptcha.net/plugins/php/
 *    - Get a reCAPTCHA API Key
 *          https://www.google.com/recaptcha/admin/create
 *    - Discussion group
 *          http://groups.google.com/group/recaptcha
 *
 * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
 * AUTHORS:
 *   Mike Crawford
 *   Ben Maurer
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * The reCAPTCHA server URL's
 */
define("RECAPTCHA_API_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_VERIFY_SERVER", "www.google.com");

/**
 * Encodes the given data into a query string format
 * @param $data - array of string elements to be encoded
 * @return string - encoded request
 */
function _recaptcha_qsencode ($data) {
        $req = "";
        foreach ( $data as $key => $value )
                $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';

        // Cut the last '&'
        $req=substr($req,0,strlen($req)-1);
        return $req;
}



/**
 * Submits an HTTP POST to a reCAPTCHA server
 * @param string $host
 * @param string $path
 * @param array $data
 * @param int port
 * @return array response
 */
function _recaptcha_http_post($host, $path, $data, $port = 80) {

        $req = _recaptcha_qsencode ($data);

        $http_request  = "POST $path HTTP/1.0\r\n";
        $http_request .= "Host: $host\r\n";
        $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
        $http_request .= "Content-Length: " . strlen($req) . "\r\n";
        $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
        $http_request .= "\r\n";
        $http_request .= $req;

        $response = '';
        if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
                die ('Could not open socket');
        }

        fwrite($fs, $http_request);

        while ( !feof($fs) )
                $response .= fgets($fs, 1160); // One TCP-IP packet
        fclose($fs);
        $response = explode("\r\n\r\n", $response, 2);

        return $response;
}



/**
 * Gets the challenge HTML (javascript and non-javascript version).
 * This is called from the browser, and the resulting reCAPTCHA HTML widget
 * is embedded within the HTML form it was called from.
 * @param string $pubkey A public key for reCAPTCHA
 * @param string $error The error given by reCAPTCHA (optional, default is null)
 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)

 * @return string - The HTML to be embedded in the user's form.
 */
function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
{
	if ($pubkey == null || $pubkey == '') {
		die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
	}
	
	if ($use_ssl) {
                $server = RECAPTCHA_API_SECURE_SERVER;
        } else {
                $server = RECAPTCHA_API_SERVER;
        }

        $errorpart = "";
        if ($error) {
           $errorpart = "&error=" . $error;
        }
        return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>

	<noscript>
  		<iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
  		<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  		<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
	</noscript>';
}




/**
 * A ReCaptchaResponse is returned from recaptcha_check_answer()
 */
class ReCaptchaResponse {
        var $is_valid;
        var $error="<p class=\"warning\">Invalid Captcha</p>";
}


/**
  * Calls an HTTP POST function to verify if the user's guess was correct
  * @param string $privkey
  * @param string $remoteip
  * @param string $challenge
  * @param string $response
  * @param array $extra_params an array of extra variables to post to the server
  * @return ReCaptchaResponse
  */
function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
{
	if ($privkey == null || $privkey == '') {
		die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
	}

	if ($remoteip == null || $remoteip == '') {
		die ("For security reasons, you must pass the remote ip to reCAPTCHA");
	}

	
	
        //discard spam submissions
        if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
                $recaptcha_response = new ReCaptchaResponse();
                $recaptcha_response->is_valid = false;
                $recaptcha_response->error = 'incorrect-captcha-sol';
                return $recaptcha_response;
        }

        $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
                                          array (
                                                 'privatekey' => $privkey,
                                                 'remoteip' => $remoteip,
                                                 'challenge' => $challenge,
                                                 'response' => $response
                                                 ) + $extra_params
                                          );

        $answers = explode ("\n", $response [1]);
        $recaptcha_response = new ReCaptchaResponse();

        if (trim ($answers [0]) == 'true') {
                $recaptcha_response->is_valid = true;
        }
        else {
                $recaptcha_response->is_valid = false;
                $recaptcha_response->error = $answers [1];
        }
        return $recaptcha_response;

}

/**
 * gets a URL where the user can sign up for reCAPTCHA. If your application
 * has a configuration page where you enter a key, you should provide a link
 * using this function.
 * @param string $domain The domain where the page is hosted
 * @param string $appname The name of your application
 */
function recaptcha_get_signup_url ($domain = null, $appname = null) {
	return "https://www.google.com/recaptcha/admin/create?" .  _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
}

function _recaptcha_aes_pad($val) {
	$block_size = 16;
	$numpad = $block_size - (strlen ($val) % $block_size);
	return str_pad($val, strlen ($val) + $numpad, chr($numpad));
}

/* Mailhide related code */

function _recaptcha_aes_encrypt($val,$ky) {
	if (! function_exists ("mcrypt_encrypt")) {
		die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
	}
	$mode=MCRYPT_MODE_CBC;   
	$enc=MCRYPT_RIJNDAEL_128;
	$val=_recaptcha_aes_pad($val);
	return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}


function _recaptcha_mailhide_urlbase64 ($x) {
	return strtr(base64_encode ($x), '+/', '-_');
}

/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($pubkey, $privkey, $email) {
	if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
		die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
		     "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>'>http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
	}
	

	$ky = pack('H*', $privkey);
	$cryptmail = _recaptcha_aes_encrypt ($email, $ky);
	
	return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
}

/**
 * gets the parts of the email to expose to the user.
 * eg, given johndoe@example,com return ["john", "example.com"].
 * the email is then displayed as [email protected]
 */
function _recaptcha_mailhide_email_parts ($email) {
	$arr = preg_split("/@/", $email );

	if (strlen ($arr[0]) <= 4) {
		$arr[0] = substr ($arr[0], 0, 1);
	} else if (strlen ($arr[0]) <= 6) {
		$arr[0] = substr ($arr[0], 0, 3);
	} else {
		$arr[0] = substr ($arr[0], 0, 4);
	}
	return $arr;
}

/**
 * Gets html to display an email address given a public an private key.
 * to get a key, go to:
 *
 * http://www.google.com/recaptcha/mailhide/apikey
 */
function recaptcha_mailhide_html($pubkey, $privkey, $email) {
	$emailparts = _recaptcha_mailhide_email_parts ($email);
	$url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
	
	return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
		"' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]);

}


?>

For recaptcha.php, you need to change the following

define("RECAPTCHA_API_SERVER", "https://www.google.com/recaptcha/api"); // for https connection

define("RECAPTCHA_API_SERVER", "https://www.google.com/recaptcha/api"); // for http connection

 

Also you need to add the css for result table (feel free to change the CSS value so it will match your theme look and feel)

table#sc_remain td{padding:2px 10px 2px 10px !important; color:#555;}
table#sc_remain tr.sc_remain_header td{font-weight:bold !important; color:#f48b47;}
table#sc_remain td.sc_remain_value{font-weight:bold !important; color:#000000;}
 
 
Hope this post will help some awocoupon users ;-)
 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...