Pingback wasn't successful. Reason: Response body does not match the
expected pattern: OK
Signature base string
uid=currency=type=0ref=369e67e903ca0b2261cd342575b8979e
Signature = MD5(Signature base string)
2aa9f1c847d1492b18cd017cdf78290b
this is model.donate.php
<?php
in_file();
class Mdonate{
protected $registry, $db, $config;
private $vars = array();
protected $hash_item = '';
protected $paypal_ipn_url = 'https://www.paypal.com/cgi-bin/webscr';
protected $paypal_ipn_url_ssl = 'www.paypal.com';
protected $req = 'cmd=_notify-validate';
protected $post = array();
protected $paypal_response;
public $order_details = array();
protected $pw_ip_white_list = array('174.36.92.186', '66.220.10.3', '174.36.92.186', '174.36.96.66', '174.36.92.187', '174.36.92.192', '174.37.14.28');
protected $pw_reason_list = array(0 => 'Invalid Reason',
1 => 'Chargeback',
2 => 'Credit Card fraud',
3 => 'Order fraud',
4 => 'Bad data entry',
5 => 'Fake / proxy user',
6 => 'Rejected by advertiser',
7 => 'Duplicate conversions',
8 => 'Goodwill credit taken back',
9 => 'Cancelled order',
10 => 'Partially reversed transaction');
public function __construct(){
$this->registry = registry::getInstance();
$this->db = $this->registry->db;
$this->config = $this->registry->config;
}
public function __set($key, $val){
$this->vars[$key] = $val;
}
public function __get($name){
return $this->vars[$name];
}
public function __isset($name){
return isset($this->vars[$name]);
}
public function get_paypal_packages(){
return $this->db->query('SELECT id, package, reward, price, currency FROM dmncms_donate_paypal_packages WHERE status = 1 ORDER BY orders ASC')->fetch_all();
}
public function check_package($id){
$count = $this->db->snumrows('SELECT COUNT(id) as count FROM dmncms_donate_paypal_packages WHERE id = '.$this->db->escape($id).' AND status = 1');
return ($count == 1);
}
public function insert_paypal_order($reward, $price, $currency){
$this->hash_item = md5($_SESSION['name'].$price.$currency.uniqid(microtime(),1));
$stmt = $this->db->prepare('INSERT INTO dmncms_donate_paypal_orders (amount, currency, credits, account, hash) VALUES(:amount, :currency, :credits, :account, :hash)');
return $stmt->execute(array(':amount' => $price, ':currency' => $currency, ':credits' => $reward, ':account' => $_SESSION['name'], ':hash' => $this->hash_item));
}
public function get_paypal_data(){
return array('email' => $this->config->load_xml_config('donate|pp_email'), 'item' => $this->hash_item, 'user' => $_SESSION['name']);
}
public function gen_post_fields($data){
$data_array = explode('&', $data);
foreach($data_array as $value){
$value = explode ('=', $value);
if(count($value) == 2)
$this->post[$value[0]] = urldecode($value[1]);
}
foreach($this->post as $key => $value) {
$this->req .= "&".$key."=".urlencode($value);
}
}
public function post_back_paypal_fsock(){
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: ".$this->paypal_ipn_url_ssl."\r\n";
$header .= "Content-Length: " . strlen($this->req) . "\r\n";
$header .= "Connection: close\r\n\r\n";
$fp = fsockopen('ssl://'.$this->paypal_ipn_url_ssl, 443, $errno, $errstr, 30);
if(!$fp){
$this->writelog('PayPal sent fsockopen error no. '.$errno.': '.$errstr.'','Paypal');
return false;
}
else{
fputs($fp, $header.$this->req);
while(!feof($fp)){
$this->paypal_response = fgets($fp, 1024);
}
fclose($fp);
}
return true;
}
public function post_back_paypal_curl(){
$request = curl_init();
curl_setopt_array($request, array(CURLOPT_URL => $this->paypal_ipn_url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $this->req,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('Connection: Close'),
CURLOPT_SSL_VERIFYPEER => TRUE,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FORBID_REUSE => TRUE,
CURLOPT_CAINFO => APP_PATH.DS.'data'.DS.'cacert.pem'));
$this->paypal_response = curl_exec($request);
if(curl_errno($request)){
$this->writelog(curl_error($request), 'Paypal');
return false;
}
curl_close($request);
return true;
}
public function validate_paypal_payment(){
if(stripos($this->paypal_response, "VERIFIED") !== false){
if(!$this->check_email()){
return false;
}
if(!$this->check_order_number()){
return false;
}
switch($this->vars['payment_status']){
case 'Completed':
if($this->vars['tax'] > 0){
$this->vars['mc_gross'] -= $this->vars['tax'];
}
if($this->vars['mc_gross'] == $this->order_details['amount']){
if($this->vars['mc_currency'] == $this->order_details['currency']){
if($this->check_completed_transaction()){
return false;
}
if($this->check_pending_transaction()){
if($this->update_transaction_status()){
return true;
}
}
else{
if($this->insert_transaction_status()){
return true;
}
}
}
}
break;
case 'Pending':
if($this->vars['tax'] > 0){
$this->vars['mc_gross'] -= $this->vars['tax'];
}
if(!$this->check_completed_transaction() && !$this->check_pending_transaction()){
$this->insert_transaction_status();
}
break;
case 'Reversed': case 'Refunded':
$this->decrease_credits($this->order_details['account'], $this->order_details['credits']);
$this->update_transaction_status();
if($this->config->load_xml_config('donate|pp_punish_player') == 1){
$this->block_user($this->order_details['account']);
}
break;
}
}
if(stripos($this->paypal_response, "INVALID") !== false){
$this->writelog('PayPal sent [status: INVALID] [transaction id: '.$this->vars['txn_id'], 'Paypal');
}
}
private function check_email(){
if(strtolower($this->vars['receiver_email']) != strtolower($this->config->load_xml_config('donate|pp_email'))){
$this->writelog('PayPal sent invalid reciever email: '.$this->vars['receiver_email'].'', 'Paypal');
return false;
}
return true;
}
private function check_order_number(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']));
if($count == 1){
$this->order_details = $this->db->query('SELECT amount, currency, account, credits FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']))->fetch();
return true;
}
else{
$this->writelog('PayPal sent invalid order [transaction id: '.$this->vars['txn_id'].']', 'Paypal');
return false;
}
}
private function check_completed_transaction(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Completed\'');
if($count > 0){
return true;
}
return false;
}
private function check_pending_transaction(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Pending\'');
if($count > 0){
return true;
}
return false;
}
private function update_transaction_status(){
$stmt = $this->db->prepare('UPDATE dmncms_donate_paypal_transactions SET status = :status WHERE transaction_id = :trans_id');
return $stmt->execute(array(':status' => $this->vars['payment_status'], ':trans_id' => $this->vars['txn_id']));
}
private function insert_transaction_status(){
$stmt = $this->db1->prepare('INSERT INTO dmncms_donate_paypal_transactions (transaction_id, amount, currency, acc, credits, order_date, status, payer_email) VALUES (:trans_id, :gross, :currency, :account, :credits, :time, :payment_status, :payer_email)');
return $stmt->execute(array(':trans_id' => $this->vars['txn_id'], ':gross' => $this->vars['mc_gross'], ':currency' => $this->vars['mc_currency'], ':account' => $this->order_details['account'], ':credits' => $this->order_details['credits'], ':time' => time(), ':payment_status' => $this->vars['payment_status'], ':payer_email' => $this->vars['payer_email']));
}
public function reward_user($acc, $credits){
$stmt = $this->db->prepare('UPDATE bg_user SET cash = cash + :credits WHERE bg_user = :account');
$stmt->execute(array(':account' => $acc, ':credits' => str_replace('-', '', $credits)));
}
private function decrease_credits($acc, $credits){
$stmt = $this->db1->prepare('UPDATE bg_user SET cash = cash - :credits WHERE bg_user = :account');
$stmt->execute(array(':credits' => str_replace('-', '', $credits), ':account' => $acc));
}
private function block_user($acc){
return;
}
public function validate_ip_list(){
return (in_array($_SERVER['REMOTE_ADDR'], $this->pw_ip_white_list));
}
public function validate_pw_signature(){
return (md5('uid='.$this->vars['uid'].'currency='.$this->vars['currency'].'type='.$this->vars['type'].'ref='.$this->vars['ref'].$this->config->load_xml_config('donate|pw_secretkey')) == $this->vars['sig']);
}
public function validate_pw_payment(){
if(!$this->check_reference()){
if($this->log_pw_transaction()){
return true;
}
}
else{
if($this->vars['type'] == 2){
$this->change_pw_transaction_status();
if($this->vars['reason'] == 2 || $this->vars['reason'] == 3){
$this->block_user($this->vars['uid']);
}
$this->decrease_credits($this->vars['uid'], $this->vars['currency']);
}
}
}
private function check_reference(){
$count = $this->db->snumrows('SELECT COUNT(uid) AS count FROM dmncms_donate_paymentwall WHERE uid = '.$this->db->escape($this->vars['uid']).' AND ref = '.$this->db->escape($this->vars['ref']).'');
if($count > 0){
return true;
}
return false;
}
private function log_pw_transaction(){
$prepare = $this->db->prepare('INSERT INTO dmncms_donate_paymentwall (uid, currency, type, ref, reason, order_date) VALUES (:uid, :currency, :type, :ref, :reason, :time)');
return $prepare->execute(array(':uid' => $this->vars['uid'], ':currency' => $this->vars['currency'], ':type' => $this->vars['type'], ':ref' => $this->vars['ref'], ':reason' => 'Complete', ':time' => time()));
}
private function change_pw_transaction_status(){
$stmt = $this->db->prepare('UPDATE dmncms_donate_paymentwall SET currency = :currency, reason = :reason, order_date = :order_date WHERE uid =:uid AND ref = :ref');
$stmt->execute(array(':currency' => $this->vars['currency'], ':reason' => $this->pw_reason_list[$this->vars['reason']], ':order_date' => time(), ':uid' => $this->vars['uid'], ':ref' => $this->vars['ref']));
}
public function writelog($logentry, $lgname) {
$log = '['.$_SERVER['REMOTE_ADDR'].'] ['.(isset($_SESSION['name']) ? $_SESSION['name'] : 'Unknown').'] '.$logentry.'';
$log_name = APP_PATH.DS.'logs'.DS.$lgname.'_'.date("m-d-y").'.txt';
$logfile = #fopen($log_name, "a+");
if($logfile){
fwrite($logfile, "[".date ("h:iA")."] $log\r\n");
fclose($logfile);
}
}
}
This is view.paymentwall.php / http://domain.com/donate/paymentwall - im using it for pingback adress
<?php
if(load::get('errors') != false){
foreach(load::get('errors') as $errors){
echo '<div class="notification-box notification-box-error">'.$errors.'</div>';
}
}
if(load::get('pw') == false || load::get('pw') == 0){
echo '<div class="notification-box notification-box-error">This donation method is disabled.</div>';
}
else{
echo '<div style="/* border: 1px dotted black; *//* -webkit-border-radius: 5px; */-moz-border-radius: 5px;/* border-radius: 5px; */margin-top: 10px; padding: 10px; height: auto; background: rgba(55, 52, 55, 1); box-shadow: 0 0 4px rgba(0,0,0,.6), 0 1px 1px rgba(0,0,0,.5), inset 0 0 0 1px rgba(255,255,255,.015), inset 0 1px 0 rgba(255,255,255,.05); -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; /* margin-left: -38px; */ z-index: 1;">
<div style="padding: 2px; text-align: center;"><iframe src="http://wallapi.com/api/ps/?key='.load::get('pw_apikey').'&uid='.$_SESSION['name'].'&widget='.load::get('pw_widget').'" width="'.load::get('pw_w_width').'" height="'.load::get('pw_w_height').'" frameborder="0"></iframe></div>
</div>';
}
?>
When Paymentwall sends a Pingback, it expects your server to respond with HTTP Status Code 200 and with response body only containing OK https://www.paymentwall.com/en/documentation/Virtual-Currency-API/711#http_pingback_return_value
It looks like currently your script returns HTML code of the payment page as a response to Paymentwall's Pingback, so the problem is that the response body doesn't only contain OK.
I recommend splitting the payment page and the pingback processing script and move the pingback processing script to something like domain/paymentwall-pingback
On a separate note, to validate Paymentwal pingbacks easier, please feel free to use Paymentwall PHP Library.
With Paymentwall PHP Library, validating the pingback signature, pingback origin and the parameters can be done with just a few lines:
require_once('/path/to/paymentwall-php/lib/paymentwall.php');
Paymentwall_Config::getInstance()->set(array(
'api_type' => Paymentwall_Config::API_VC, //OR API_GOODS or API_CART
'public_key' => 'YOUR_PUBLIC_KEY',
'private_key' => 'YOUR_PRIVATE_KEY'
));
$pingback = new Paymentwall_Pingback($_GET, $_SERVER['REMOTE_ADDR']);
if ($pingback->validate()) {
//product delivery logic
}
It is necessary to use appropriate algorithm and parameters for signature calculation based on version you would like to use :
https://www.paymentwall.com/en/documentation/Signature-Calculation/2313
If the version is 2 or 3 your parameters should be sorted alphabetically.
For pingback you have to return only string "OK" from your server in case of successful pingback/negative pingback.
Related
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
I am up and running my E-Commerce website on a server. I use Paypal IPN notifications to send customers with notifications about payments made by them.
I am currently using Paypal sandbox for testing.
I proceed to checkout => paypal developer account => make payment => i receive message in my paypal account as ipn request is sent but i don't get the values of ipn request in my orders table in the database.
What could be the reason for this ?
I have set my IPN details as in the screenshot below.
and
I also have the screenshot of IPN history of my Paypal developer account.
Can anyone please help me and tell me the reason why the values in my database are not updated ?
Following is my code:
classes/Paypal.php
<?php
class PayPal {
private $_environment = 'sandbox';
private $_url_production = 'https://www.paypal.com/cgi-bin/webscr';
private $_url_sandbox = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
private $_url;
private $_cmd;
private $_products = array();
private $_fields = array();
private $_business = 'xxx-xxx#gmail.com';
private $_page_style = 'null';
private $_return;
private $_cancel_payment;
private $_notify_url;
private $_currency_code = 'GBP';
public $_tax_cart = 0;
public $_tax = 0;
public $_populate = array();
private $_ipn_data = array();
private $_log_file = null;
private $_ipn_result;
public function __construct($cmd = '_cart') {
$this->_url = $this->_environment == 'sandbox' ?
$this->_url_sandbox :
$this->_url_production;
$this->_cmd = $cmd;
$this->_return = SITE_URL."/?page=return";
$this->_cancel_payment = SITE_URL."/?page=cancel";
$this->_notify_url = SITE_URL."/?page=ipn";
$this->_log_file = ROOT_PATH.DS."log".DS."ipn.log";
}
public function addProduct($number, $name, $price = 0, $qty = 1) {
switch($this->_cmd) {
case '_cart':
$id = count($this->_products) + 1;
$this->_products[$id]['item_number_'.$id] = $number;
$this->_products[$id]['item_name_'.$id] = $name;
$this->_products[$id]['amount_'.$id] = $price;
$this->_products[$id]['quantity_'.$id] = $qty;
break;
case '_xclick':
if (empty($this->_products)) {
$this->_products[0]['item_number'] = $number;
$this->_products[0]['item_name'] = $name;
$this->_products[0]['amount'] = $price;
$this->_products[0]['quantity'] = $qty;
}
break;
}
}
private function addField($name = null, $value = null) {
if (!empty($name) && !empty($value)) {
$field = '<input type="hidden" name="'.$name.'" ';
$field .= 'value="'.$value.'" />';
$this->_fields[] = $field;
}
}
private function standardFields() {
$this->addField('cmd', $this->_cmd);
$this->addField('business', $this->_business);
if ($this->_page_style != null) {
$this->addField('page_style', $this->_page_style);
}
$this->addField('return', $this->_return);
$this->addField('notify_url', $this->_notify_url);
$this->addField('cancel_payment', $this->_cancel_payment);
$this->addField('currency_code', $this->_currency_code);
$this->addField('rm', 2);
switch($this->_cmd) {
case '_cart':
if ($this->_tax_cart != 0) {
$this->addField('tax_cart', $this->_tax_cart);
}
$this->addField('upload', 1);
break;
case '_xclick':
if ($this->_tax != 0) {
$this->addField('tax', $this->_tax);
}
break;
}
}
private function prePopulate() {
if (!empty($this->_populate)) {
foreach($this->_populate as $key => $value) {
$this->addField($key, $value);
}
}
}
private function processFields() {
$this->standardFields();
if (!empty($this->_products)) {
foreach($this->_products as $product) {
foreach($product as $key => $value) {
$this->addField($key, $value);
}
}
}
$this->prePopulate();
}
private function getFields() {
$this->processFields();
if (!empty($this->_fields)) {
return implode("", $this->_fields);
}
}
private function render() {
$out = '<form action="'.$this->_url.'" method="post" id="frm_paypal">';
$out .= $this->getFields();
$out .= '<input type="submit" value="Submit" />';
$out .= '</form>';
return $out;
}
public function run($transaction_id = null) {
if (!empty($transaction_id)) {
$this->addField('custom', $transaction_id);
}
return $this->render();
}
private function validateIpn() {
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (!preg_match('/paypal\.com$/', $hostname)) {
return false;
}
$objForm = new Form();
$this->_ipn_data = $objForm->getPostArray();
if (
!empty($this->_ipn_data) &&
array_key_exists('receiver_email', $this->_ipn_data) &&
strtolower($this->_ipn_data['receiver_email']) !=
strtolower($this->_business)
) {
return false;
}
return true;
}
private function getReturnParams() {
$out = array('cmd=_notify-validate');
if (!empty($this->_ipn_data)) {
foreach($this->_ipn_data as $key => $value) {
$value = function_exists('get_magic_quotes_gpc') ?
urlencode(stripslashes($value)) :
urlencode($value);
$out[] = "{$key}={$value}";
}
}
return implode("&", $out);
}
private function sendCurl() {
$response = $this->getReturnParams();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
curl_setopt($ch, T_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: " . strlen($response)
));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$this->_ipn_result = curl_exec($ch);
curl_close($ch);
}
public function ipn() {
if ($this->validateIpn()) {
$this->sendCurl();
if (strcmp($this->_ipn_result, "VERIFIED") == 0) {
$objOrder = new Order();
if (!empty($this->_ipn_data)) {
$objOrder->approve(
$this->_ipn_data,
$this->_ipn_result
);
}
}
}
}
}
mod/paypal.php
<?php
require_once('../inc/autoload.php');
$token2 = Session::getSession('token2');
$objForm = new Form();
$token1 = $objForm->getPost('token');
if ($token2 == Login::string2hash($token1)) {
// create order
$objOrder = new Order();
if ($objOrder->createOrder()) {
// populate order details
$order = $objOrder->getOrder();
$items = $objOrder->getOrderItems();
if (!empty($order) && !empty($items)) {
$objBasket = new Basket();
$objCatalogue = new Catalogue();
$objPayPal = new PayPal();
foreach($items as $item) {
$product = $objCatalogue->getProduct($item['product']);
$objPayPal->addProduct(
$item['product'],
$product['name'],
$item['price'],
$item['qty']
);
}
$objPayPal->_tax_cart = $objBasket->_vat;
// populate client's details
$objUser = new User();
$user = $objUser->getUser($order['client']);
if (!empty($user)) {
$objCountry = new Country();
$country = $objCountry->getCountry($user['country']);
$objPayPal->_populate = array(
'address1' => $user['address_1'],
'address2' => $user['address_2'],
'city' => $user['town'],
'state' => $user['county'],
'zip' => $user['post_code'],
'country' => $country['code'],
'email' => $user['email'],
'first_name' => $user['first_name'],
'last_name' => $user['last_name']
);
// redirect client to PayPal
echo $objPayPal->run($order['id']);
}
}
}
}
IPN settings
IPN Details
Please help me with this .
IPN is not related to your return URL. If you're adding your code that you expect to run when IPNs are triggered to your return URL you will not get the expected result.
To get data to your return URL you would need to use PDT which is very similar to IPN but is intended to be sent to the return URL. IPN goes to your notify URL, which should not match your return URL.
I would like to let the form send a copy to the email address which the visitor entered into 'label' => 'Email'.
3 php files are handling the whole thing and are as fallows:
This is the PHP Form which handles the input of the HTML
<?php
require_once('form_process.php');
$form = array(
'subject' => 'Contact Form',
'heading' => 'Submission',
'success_redirect' => '',
'resources' => array(
'checkbox_checked' => 'Checked',
'checkbox_unchecked' => 'Unchecked',
'submitted_from' => 'Form submitted from website: %s',
'submitted_by' => 'Visitor IP address: %s',
'too_many_submissions' => 'Too many recent submissions from this IP',
'failed_to_send_email' => 'Failed to send email',
'invalid_reCAPTCHA_private_key' => 'Invalid reCAPTCHA private key.',
'invalid_field_type' => 'Unknown field type \'%s\'.',
'invalid_form_config' => 'Field \'%s\' has an invalid configuration.',
'unknown_method' => 'Unknown server request method'
),
'email' => array(
'from' => 'info#myurl.com',
'to' => 'info#myurl.com'
),
'fields' => array(
'custom_U8149' => array(
'order' => 1,
'type' => 'string',
'label' => 'Name',
'required' => true,
'errors' => array(
'required' => 'Field \'Name\' is required.'
)
),
'Email' => array(
'order' => 2,
'type' => 'email',
'label' => 'Email',
'required' => true,
'errors' => array(
'required' => 'Field \'Email\' is required.',
'format' => 'Field \'Email\' has an invalid email.'
)
),
'custom_U8139' => array(
'order' => 3,
'type' => 'string',
'label' => 'Message',
'required' => false,
'errors' => array(
)
)
)
);
process_form($form);
?>
This is the form_process.php
<?php
require_once('form_throttle.php');
function process_form($form) {
if ($_SERVER['REQUEST_METHOD'] != 'POST')
die(get_form_error_response($form['resources']['unknown_method']));
if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
die(get_form_error_response($form['resources']['too_many_submissions']));
// will die() if there are any errors
check_required_fields($form);
// will die() if there is a send email problem
email_form_submission($form);
}
function get_form_error_response($error) {
return get_form_response(false, array('error' => $error));
}
function get_form_response($success, $data) {
if (!is_array($data))
die('data must be array');
$status = array();
$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
return json_serialize($status);
}
function check_required_fields($form) {
$errors = array();
foreach ($form['fields'] as $field => $properties) {
if (!$properties['required'])
continue;
if (!array_key_exists($field, $_REQUEST) || empty($_REQUEST[$field]))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
else if (!check_field_value_format($form, $field, $properties))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
}
if (!empty($errors))
die(get_form_error_response(array('fields' => $errors)));
}
function check_field_value_format($form, $field, $properties) {
$value = get_form_field_value($field, $properties, $form['resources'], false);
switch($properties['type']) {
case 'checkbox':
case 'string':
case 'captcha':
// no format to validate for those fields
return true;
case 'checkboxgroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
// If the value received is not an array, treat it as invalid format
if (!isset($value))
return false;
// Check each option to see if it is a valid value
foreach($value as $checkboxValue) {
if (!in_array($checkboxValue, $properties['optionItems']))
return false;
}
return true;
case 'radiogroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
//check list of real radio values
return in_array($value, $properties['optionItems']);
case 'recaptcha':
if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA_private_key']));
$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
return $resp->is_valid;
case 'email':
return 1 == preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($form['resources']['invalid_field_type'], $properties['type'])));
}
}
function email_form_submission($form) {
if(!defined('PHP_EOL'))
define('PHP_EOL', '\r\n');
$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');
$to = $form['email']['to'];
$subject = $form['subject'];
$message = get_email_body($subject, $form['heading'], $form['fields'], $form['resources']);
$headers = get_email_headers($to, $form_email);
$sent = #mail($to, $subject, $message, $headers);
if(!$sent)
die(get_form_error_response($form['resources']['failed_to_send_email']));
$success_data = array(
'redirect' => $form['success_redirect']
);
echo get_form_response(true, $success_data);
}
function get_email_headers($to_email, $form_email) {
$headers = 'From: ' . $to_email . PHP_EOL;
$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
$headers .= 'X-Mailer: Adobe Muse CC 2015.0.2.310 with PHP' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
return $headers;
}
function get_email_body($subject, $heading, $fields, $resources) {
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">';
$sorted_fields = array();
foreach ($fields as $field => $properties) {
// Skip reCAPTCHA from email submission
if ('recaptcha' == $properties['type'])
continue;
array_push($sorted_fields, array('field' => $field, 'properties' => $properties));
}
// sort fields
usort($sorted_fields, 'field_comparer');
foreach ($sorted_fields as $field_wrapper)
$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($field_wrapper['properties']['label']) . ':</b></td><td>' . get_form_field_value($field_wrapper['field'], $field_wrapper['properties'], $resources, true) . '</td></tr>';
$message .= '</table>';
$message .= '<br/><br/>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_from'], encode_for_form($_SERVER['SERVER_NAME'])) . '</div>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_by'], encode_for_form($_SERVER['REMOTE_ADDR'])) . '</div>';
$message .= '</body></html>';
return cleanup_message($message);
}
function field_comparer($field1, $field2) {
if ($field1['properties']['order'] == $field2['properties']['order'])
return 0;
return (($field1['properties']['order'] < $field2['properties']['order']) ? -1 : 1);
}
function is_assoc_array($arr) {
if (!is_array($arr))
return false;
$keys = array_keys($arr);
foreach (array_keys($arr) as $key)
if (is_string($key)) return true;
return false;
}
function json_serialize($data) {
if (is_assoc_array($data)) {
$json = array();
foreach ($data as $key => $value)
array_push($json, '"' . $key . '": ' . json_serialize($value));
return '{' . implode(', ', $json) . '}';
}
if (is_array($data)) {
$json = array();
foreach ($data as $value)
array_push($json, json_serialize($value));
return '[' . implode(', ', $json) . ']';
}
if (is_int($data) || is_float($data))
return $data;
if (is_bool($data))
return $data ? 'true' : 'false';
return '"' . encode_for_json($data) . '"';
}
function encode_for_json($value) {
return preg_replace(array('/([\'"\\t\\\\])/i', '/\\r/i', '/\\n/i'), array('\\\\$1', '\\r', '\\n'), $value);
}
function encode_for_form($text) {
$text = stripslashes($text);
return htmlentities($text, ENT_QUOTES, 'UTF-8');// need ENT_QUOTES or webpro.js jQuery.parseJSON fails
}
function get_form_field_value($field, $properties, $resources, $forOutput) {
$value = $_REQUEST[$field];
switch($properties['type']) {
case 'checkbox':
return (($value == '1' || $value == 'true') ? $resources['checkbox_checked'] : $resources['checkbox_unchecked']);
case 'checkboxgroup':
if (!is_array($value))
return NULL;
$outputValue = array();
foreach ($value as $checkboxValue)
array_push($outputValue, $forOutput ? encode_for_form($checkboxValue) : stripslashes($checkboxValue));
if ($forOutput)
$outputValue = implode(', ', $outputValue);
return $outputValue;
case 'radiogroup':
return ($forOutput ? encode_for_form($value) : stripslashes($value));
case 'string':
case 'captcha':
case 'recaptcha':
case 'email':
return encode_for_form($value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($resources['invalid_field_type'], $properties['type'])));
}
}
function cleanup_email($email) {
$email = encode_for_form($email);
$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $email);
return $email;
}
function cleanup_message($message) {
$message = wordwrap($message, 70, "\r\n");
return $message;
}
?>
This is the form_throttle.php
<?php
function formthrottle_check()
{
if (!is_writable('.'))
{
return '8';
}
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
if ( file_exists('muse-throttle-db') )
{
unlink('muse-throttle-db');
}
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
if ( file_exists('muse-throttle-db.sqlite3') )
{
unlink('muse-throttle-db.sqlite3');
}
}
}
catch( PDOException $Exception ) {
return '9';
}
$retCode ='5';
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
if($created == 0)
{
$created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))");
}
if ($created != 1)
{
$retCode = '2';
}
}
if($retCode == '5')
{
$res = $db->query("SELECT COUNT(1) FROM Submission_History;");
if ($res && $res->fetchColumn() > 0)
{
$retCode = '0';
}
else
$retCode = '3';
}
// Close file db connection
$db = null;
}
else
$retCode = '4';
return $retCode;
}
function formthrottle_too_many_submissions($ip)
{
$tooManySubmissions = false;
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
}
}
catch( PDOException $Exception ) {
return $tooManySubmissions;
}
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
}
$db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
$stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
$stmt->closeCursor();
$stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
if ($stmt->fetchColumn() > 25)
$tooManySubmissions = true;
// Close file db connection
$db = null;
}
return $tooManySubmissions;
}
?>
i'm writing a script to execute import of a csv using the admin panel: AdminImport.
The script execute a login into the admin panel and post csv with opportune parameters to import the file.
I've founded this class on web:
<?php
class PSRequest {
protected $_eol = "\r\n";
protected $_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
protected $_cookieFileLocation = './cookie.txt';
protected $_referer = "http://www.google.com";
protected $_url;
protected $_followlocation;
protected $_timeout;
protected $_maxRedirects;
protected $_post = false;
protected $_multipart = false;
protected $_file = false;
protected $_postFields;
protected $_postFile;
protected $_session;
protected $_includeHeader;
protected $_noBody;
protected $_status;
protected $_binaryTransfer;
protected $_file_to_upload = null;
protected $_file_to_upload_size = 0;
protected $_file_name = '';
protected $_file_transfer_codebase = false;
protected $_file_content_type = '';
protected $_boundary = 'boundaryAAAbbb';
public $_webpage;
public $authentication = 0;
public $auth_name = '';
public $auth_pass = '';
protected $ch; // curl handler
public function __construct($url = '', $followlocation = true, $timeOut = 30, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = true, $noBody = false)
{
$this->_url = $url;
$this->_followlocation = $followlocation;
$this->_timeout = $timeOut;
$this->_maxRedirects = $maxRedirecs;
$this->_noBody = $noBody;
$this->_includeHeader = $includeHeader;
$this->_binaryTransfer = $binaryTransfer;
$this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';
$this->ch = curl_init();
}
public function __destruct() {
curl_close($this->ch);
}
public function useAuth($use){
$this->authentication = 0;
if($use == true) $this->authentication = 1;
}
public function setEndOfLine($chars) {
$this->_eol = $chars;
}
public function setName($name){
$this->auth_name = $name;
}
public function setPass($pass){
$this->auth_pass = $pass;
}
public function setBoundary($boundary) {
$this->_boundary = $boundary;
}
public function setReferer($referer){
$this->_referer = $referer;
}
public function setCookiFileLocation($path)
{
$this->_cookieFileLocation = $path;
}
public function setFileToUpload($filePath, $filename, $contentType='plain/text')
{
$this->setPostMultipart(array('post'=>'true'));
$this->_file = true;
$this->_file_name = $filename;
$this->_file_content_type = $contentType;
//$this->_file_to_upload = fopen($filePath,'r');
$handle = fopen($filePath, "r");
$this->_file_to_upload_size = filesize($filePath);
$this->_file_to_upload = fread($handle, $this->_file_to_upload_size);
fclose($handle);
}
public function setPostMultipart($postFields)
{
$this->_post = true;
$this->_multipart = true;
if (is_array($postFields)) {
$fields_string = $this->multipart_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setPost($postFields)
{
$this->_post = true;
if (is_array($postFields)) {
$fields_string = http_build_query($postFields);
}
else {
$fields_string = $postFields;
}
$this->_postFields = $fields_string;
}
public function setUserAgent($userAgent)
{
$this->_useragent = $userAgent;
}
public function call($url = null, $header = null)
{
if(is_null($header)) {
if( $this->_multipart == true ) {
$header = array("Content-Type: multipart/form-data; boundary=".$this->_boundary);
} else {
$header = array('Content-Type: application/x-www-form-urlencoded');
}
}
if ($url) {
$this->_url = $url;
}
if (!$url) {
throw new Exception('You should set an URL to call.');
}
curl_setopt($this->ch,CURLOPT_URL,$this->_url);
curl_setopt($this->ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($this->ch,CURLOPT_TIMEOUT,$this->_timeout);
curl_setopt($this->ch,CURLOPT_MAXREDIRS,$this->_maxRedirects);
curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
curl_setopt($this->ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch,CURLOPT_COOKIESESSION, true );
curl_setopt($this->ch,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($this->ch,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if ($this->authentication == 1) {
curl_setopt($this->ch, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
}
if ($this->_multipart) {
curl_setopt($this->ch,CURLOPT_POST,true);
if($this->_file) {
$this->_postFields .= $this->add_multipart_build_file('file',$this->_file_name,$this->_file_content_type);
$this->_postFields .= "--".$this->_eol;
curl_setopt($this->ch, CURLOPT_INFILESIZE, $this->_file_to_upload_size);
curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
}
} else if ($this->_post) {
curl_setopt($this->ch,CURLOPT_POST,true);
}
curl_setopt($this->ch,CURLOPT_POSTFIELDS,$this->_postFields);
if ($this->_includeHeader) {
curl_setopt($this->ch,CURLOPT_HEADER,true);
}
if ($this->_noBody) {
curl_setopt($this->ch,CURLOPT_NOBODY,true);
}
/* if ($this->_file_to_upload_size > 0 && !is_null($this->_file_to_upload)) {
curl_setopt($this->ch, CURLOPT_READFUNCTION, 'uploadFileCall');
} */
curl_setopt($this->ch,CURLOPT_USERAGENT,$this->_useragent);
curl_setopt($this->ch,CURLOPT_REFERER,$this->_referer);
$this->_webpage = curl_exec( $this->ch );
$this->_status = curl_getinfo( $this->ch, CURLINFO_HTTP_CODE );
return $this->_webpage;
}
public function getHttpStatus()
{
return $this->_status;
}
public function __tostring(){
return $this->_webpage;
}
/*function uploadFileCall($ch, $data){
return fread($this->_file_to_upload, $this->_file_to_upload_size);
}*/
function multipart_build_query($fields){
$retval = '';
foreach($fields as $key => $value){
$retval .= "--".$this->_boundary.$this->_eol."Content-Disposition: form-data; name=\"".$key."\"".$this->_eol.$this->_eol.$value.$this->_eol;
}
//$retval .= "--". $this->_boundary ."--".$this->_eol;
$retval .= "--". $this->_boundary .$this->_eol;
return $retval;
}
function add_multipart_build_file($key,$filename='file.csv',$contentType ="application/csv") {
$retval = '';
$retval .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$filename\"".$this->_eol;
$retval .= "Content-Type: $contentType ".$this->_eol.$this->_eol;
if($this->_file_transfer_codebase == true) {
$retval .= 'Content-Transfer-Encoding: base64'.$this->_eol.$this->_eol;
$retval .= chunk_split(base64_encode($this->_file_to_upload));
} else {
$retval .= $this->_file_to_upload;
}
$retval .= "--". $this->_boundary; // ."--".$this->_eol;
return $retval;
}
}
?>
This is the main script:
$request = new PSRequest();
$request->setCookiFileLocation( __DIR__ . '/PScookie.txt' );
debug( "Login..." );
$request->setPost( array( "email" => $adminLoginEmail, "passwd" => $adminLoginPass, "submitLogin" => "Connexion" ) ); // you must be a super admin
$request->call( $adminUrl . "index.php?controller=AdminLogin" );
$response = $request->_webpage;
preg_match( "/&token=([a-z0-9]+)/", $response, $matches );
// $token = Tools::getAdminTokenLite( 'AdminImport' );
$token = $matches[ 1 ];
debug( "Token: ".$token );
$csvname = $upload_dir . 'prestashop_products.csv';
// Send POST datas just like the admin form would do it, those datas depends on what you want to do : check the import admin page.
$request->setPost(array(
"controller" => "AdminImport",
"token" => $token,
"skip" => 1,
"csv" => $csvname,
"convert" => '',
"regenerate" => '',
"entity" => 1, //1 is for products import
"iso_lang" => "it",
"truncate" => 0,
"forceIDs" => 1,
"match_ref" => 1,
"separator" => ";",
"multiple_value_separator" => ",",
"import" => 1,
"type_value" => array( 1 => 'active', 2 => 'reference', 3 => 'name', 4 => 'category', 5 => 'price_tex', 6 => 'supplier', 7 => 'weight', 8 => 'quantity', 9 => 'description' )
)
);
debug( "call AdminImport and POST datas..." );
$request->call( $adminUrl."index.php?controller=AdminImport&token=".$token );
The script initially works: i can get the admin panel and i succesfully get token!!
but when i POST data, the request fails due to 'token invalid'!!
But the token is ok!!
I've tryed to use the function:
Tools::getAdminTokenLite( 'AdminImport' )
the token is different to the token i get from page, but also not work!!
I think problem regardling php sessions but i don't know hot to resolve it!!
someone can help me?