Magento code need precision - php

I'm currently checking a Magento extension and I have a slight doubt about a piece of code. I would like you to explain. I understand all of it but not this one :
$customerID == " "
Is there a case where Magento have a customer id like that ( a space?) ?
Thanks a lot for your reply !
Here the entire function.
public function isAvailable(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$method = $event->getMethodInstance(); //$method return the payment method
$result = $event->getResult(); //$result return true if method is active
$quote = $event->getQuote(); //$quote return var from cart
if($method->getCode() == 'custompayment' ){
//$customerGroup = $quote->getCustomerGroupId();
// $customerGroup="";
// $customerID="";
$login = Mage::getSingleton( 'customer/session' )->isLoggedIn(); //Check if User is Logged In
if($login)
{
$customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId(); //Get Customers Group ID
$customerID = Mage::getSingleton('customer/session')->getCustomerId(); //Get Customers ID
}
$selectedCustomerGroups = Mage::getStoreConfig('payment/custompayment/specificcustomers');
$selectedCustomerGroupsArray = explode(",", $selectedCustomerGroups);
if($selectedCustomerGroups != "" || $customerID == " "){
if(!in_array($customerGroup, $selectedCustomerGroupsArray)) {
$result->isAvailable = false;
}
}
else{
if($result->isAvailable==1){
$result->isAvailable = true;
}
}
}

Answered by adrien54 and JokiRuiz.

Related

Prestashop payment module returning 500 server status

I'm trying to figure out how to give a good response status to my API shot which was made to the prestashop.
That's the code of validation.php:
<?php
class InpayValidationModuleFrontController extends ModuleFrontController
{
/**
* #see FrontController::postProcess()
*/
public function postProcess()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['invoiceCode'] && $_POST['status'] && $_POST['optData']) {
$apiHash = $_SERVER['HTTP_API_HASH'];
$query = http_build_query($_POST);
$hash = hash_hmac("sha512", $query, $this->module->secret_key);
if ($apiHash == $hash) {
PrestaShopLogger::addLog(json_encode(_PS_VERSION_), 1);
parse_str($_POST['optData'], $optData);
$id_cart = intval($optData['cartId']);
$query = "SELECT * from " . _DB_PREFIX_ . "orders where id_cart='" . $id_cart . "'";
//$query = "SELECT * from aps_orders where id_cart='67867'";
$row = Db::getInstance()->getRow($query);
if ($_POST['status'] == 'confirmed' && $row['current_state'] != null) {
$sql = "UPDATE " . _DB_PREFIX_ . "orders SET current_state='2' WHERE id_cart='" . $id_cart . "'";
if(Db::getInstance()->Execute($sql))
Tools::redirect(__FILE__,'payment_confirmation.tpl');
} else {
$cart = new Cart($id_cart);
if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
//die('Cannot create order for this cart.');
Tools::redirect(__FILE__,'payment_cart_error.tpl');
}
$customer = new Customer($cart->id_customer);
if (!Validate::isLoadedObject($customer)) {
//die('No customer for this order.');
Tools::redirect(__FILE__,'payment_customer_error.tpl');
}
$currency = new Currency((int)($cart->id_currency));
$paid_amount = $_POST['amount'];
$order_amount = $cart->getOrderTotal(true, Cart::BOTH);
if ($_POST['status'] == 'confirmed') {
$paymentId = 2;
} elseif ($_POST['status'] == 'received') {
$paymentId = 11;
}
$result = $this->module->validateOrder(
$cart->id,
//Configuration::get('PS_OS_PAYMENT'),
$paymentId,
$order_amount,
$this->module->displayName,
'Invoice Code: ' . $_POST['invoiceCode'],
array(),
intval($currency->id),
false,
$customer->secure_key
);
//die($result);
Tools::redirect(__FILE__,'payment_confirmation.tpl');
}
} else {
return null;
}
}
}
}
While I use the die(); function the server returns 200 response status which is good... but the die isn't a function for production... When using redirect it gives me 302 and additional status of error. I tried doing hacks like:
header("HTTP/1.1 200 OK");
or
return http_response_code(200);
But the status is 500. I would appreciate any tip or help how to do that.
Cheers!
You are trying to redirect directly to the tpl file. You should redirect to a controller or url. For exampl, in the module cheque, in the payment.php there is:
Tools::redirect(Context::getContext()->link->getModuleLink('cheque', 'payment'));
or in validation.php:
Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
Also, Tools::redirect is defined as:
redirect($url, $base_uri = __PS_BASE_URI__, Link $link = null, $headers = null)
On the other hand, you can be trying to use the display function used in modules (for example):
return $this->display(__FILE__, 'file.tpl');
But in this case you should use the assign and setTemplate:
$this->context->smarty->assign(array(/* array of vars to use in tpl*/));
$this->setTemplate('file.tpl');

How to get supplier id when it has just been added in the db?

When I add a supplier in the admin panel (and click the save button) I want to retrieve its ID in the method postProcess() in the controller
prestashop/controllers/admin/AdminSuppliersController.php
in such a way that I can associate to this supplier other custom info in custom tables in the DB. I can't find in code the part when it stores the supplier to the db (I find only the part when it inserts the address relative to the supplier in ps_address table).
Here the default postProcess() method:
public function postProcess()
{
// checks access
if (Tools::isSubmit('submitAdd'.$this->table) && !($this->tabAccess['add'] === '1')) {
$this->errors[] = Tools::displayError('You do not have permission to add suppliers.');
return parent::postProcess();
}
if (Tools::isSubmit('submitAdd'.$this->table)) {
if (Tools::isSubmit('id_supplier') && !($obj = $this->loadObject(true))) {
return;
}
// updates/creates address if it does not exist
if (Tools::isSubmit('id_address') && (int)Tools::getValue('id_address') > 0) {
$address = new Address((int)Tools::getValue('id_address'));
} // updates address
else {
$address = new Address();
} // creates address
$address->alias = Tools::getValue('name', null);
$address->lastname = 'supplier'; // skip problem with numeric characters in supplier name
$address->firstname = 'supplier'; // skip problem with numeric characters in supplier name
$address->address1 = Tools::getValue('address', null);
$address->address2 = Tools::getValue('address2', null);
$address->postcode = Tools::getValue('postcode', null);
$address->phone = Tools::getValue('phone', null);
$address->phone_mobile = Tools::getValue('phone_mobile', null);
$address->id_country = Tools::getValue('id_country', null);
$address->id_state = Tools::getValue('id_state', null);
$address->city = Tools::getValue('city', null);
$validation = $address->validateController();
// checks address validity
if (count($validation) > 0) {
foreach ($validation as $item) {
$this->errors[] = $item;
}
$this->errors[] = Tools::displayError('The address is not correct. Please make sure all of the required fields are completed.');
} else {
if (Tools::isSubmit('id_address') && Tools::getValue('id_address') > 0) {
$address->update();
} else {
$address->save();
// here I want to get the ID of the inserted supplier
$_POST['id_address'] = $address->id;
}
}
return parent::postProcess();
} elseif (Tools::isSubmit('delete'.$this->table)) {
if (!($obj = $this->loadObject(true))) {
return;
} elseif (SupplyOrder::supplierHasPendingOrders($obj->id)) {
$this->errors[] = $this->l('It is not possible to delete a supplier if there are pending supplier orders.');
} else {
//delete all product_supplier linked to this supplier
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'product_supplier` WHERE `id_supplier`='.(int)$obj->id);
$id_address = Address::getAddressIdBySupplierId($obj->id);
$address = new Address($id_address);
if (Validate::isLoadedObject($address)) {
$address->deleted = 1;
$address->save();
}
return parent::postProcess();
}
} else {
return parent::postProcess();
}
}
You could use the hook actionObjectSupplierAddAfter to get the supplier object right after it was added to database using in your module something like:
public function hookActionObjectSupplierAddAfter($params) {
$supplier = $params['object'];
}

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

Secure parameter in Codeigniter PHP controller?

I'm trying to create callback script for Coinbase bitcoin payments. Here is the below function from my payment controller:
function callback($secret = NULL) {
if ($secret == 'testSECRETkey') {
//If order is "completed", please proceed.
$data = json_decode(file_get_contents('php://input'), TRUE);
$status = $data['order']['status'];
$userid = '507';
if (($status === 'completed')) {
$this->db->query( 'update users set user_money=user_money+15, user_credits=user_credits+5 WHERE users_id=' . $userid );
}
}
How to include special parameter, so when I request the url: www.example.com/payments/callback
to add special key and if it's not valid to reject access to the script. Example:
www.example.com/payments/callback?secret=testSECRETkey
Unfortunately, it doesnt work as I want. It doesnt take effect. Whats wrong on it?
To access the key parameter you will use the Input class' get method https://ellislab.com/codeigniter/user-guide/libraries/input.html
$this->input->get('key');
function callback()
{
$key = $this->input->get('key');
if( ! $this->is_valid_key($key)) {
// do something here and return
return;
}
//If order is "completed", please proceed.
$data = json_decode(file_get_contents('php://input'), TRUE);
$status = $data['order']['status'];
$userid = '507';
if (($status === 'completed')) {
$this->db->query( 'update users set user_money=user_money+15, user_credits=user_credits+5 WHERE users_id=' . $userid );
}
}
Create a new method to validate the key
function is_valid_key($key) {
// logic to check key
$valid = true;
if($valid) {
return true;
}
else {
return false;
}
}

Looking for inputs on my cookie/session authentication class, not sure if i got it correct

Im currently creating my own forum for my website and i have read plenty of topics on cookie/session authentication and i think im aware of the attacks etc that exists. I get that its not 100% secure but im trying to do it as safe as possible.
Im currently storing IP in the cookie and im aware that some might have problems with that but im going to change to check the first 2 blocks of the IP instead. I dont think its going to be a problem since 95% of the people in Sweden got broadband which rarely changes IP.
Something that im really insecure about is the session_start which i do need later for forms etc what is the best practice to implement it? im pretty sure that im doing that thing pretty much wrong.
Any inputs is much appreciated!
Class
class user2
{
private $db = null;
private $cookie_salt = '!!PLonSIMDSAM35324dfg5DAUSHODNASDJ353NMASDSA&%&A/SD&HASNJDdfghAS&DGIHYAUSDNA3535SDFASDF%A3532dfgsdfggsdg53532535SDGIASYDU';
var $user_ip = false;
var $user_id = false;
var $user_username = false;
var $cookie_identifier = false;
var $user_logged_in = false;
function __construct()
{
global $mysql_server;
global $mysql_user;
global $mysql_password;
global $mysql_database_name;
$this->db = new database($mysql_server, $mysql_user, $mysql_password, $mysql_database_name, true);
$this->checkUserAuthentication();
}
public function Login($input_username, $input_user_password)
{
// If empty parameters return false
if (empty($input_username) || empty($input_user_password))
{
return false;
}
$user_login = $this->db->q("SELECT user_id, username FROM `forum_user` WHERE username = ? AND password = ? LIMIT 1", 'ss' , $input_username, $input_user_password);
if ($user_login != false)
{
$this->user_ip = $_SERVER['REMOTE_ADDR'];
$this->user_id = $user_login[0]['user_id'];
$this->user_username = $user_login[0]['username'];
if($this->initiateSessionCookie() == true)
{
$this->user_logged_in = true;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
private function initiateSessionCookie()
{
// Delete old sessions from this user or USE REPLACE instead
$this->db->q("DELETE FROM `forum_session` WHERE userid = ?", 'i' , $this->user_id);
$identifier = md5($this->cookie_salt . md5($this->user_username . $this->user_ip) . $this->cookie_salt);
$token = md5($this->generateToken());
$timeout = time() + 60 * 60 * 24 * 7; // 7 days
$timeout_minutes = 10080; // 7 days
$init_session = $this->db->q("INSERT INTO forum_session SET session = ?
, token = ?
, userid = ?
, sess_start = now()
, last_activity = now()
, sess_expire = DATE_ADD(curdate(),INTERVAL ? MINUTE)
, ip = ?", 'ssiis' , $identifier, $token, $this->user_id, $timeout_minutes, $this->user_ip);
if($init_session != false) {
setcookie('auth', "$identifier:$token", $timeout);
return true;
}
else {
return false;
}
}
private function generateToken()
{
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!#&";
for($i = 1; $i <= 20; $i++)
{
$rand_number = rand(0, 59);
$random_string .= $chars[$rand_number];
}
return $random_string;
}
private function checkUserAuthentication()
{
$this->user_logged_in = false;
list($_cookie_identifier, $_cookie_token) = explode(':', $_COOKIE['auth']);
if(ctype_alnum($_cookie_identifier) && ctype_alnum($_cookie_token))
{
$_cookie_data['identifier'] = $_cookie_identifier;
$_cookie_data['token'] = $_cookie_token;
}
else
{
return false;
}
$auth_user = $this->db->q("SELECT *
FROM forum_session a
LEFT JOIN
forum_user b ON a.userid = b.user_id
WHERE
a.session = ? AND
a.token = ?
LIMIT 1", 'ss' , $_cookie_data['identifier'], $_cookie_data['token']);
if($auth_user != false)
{
if(time() > strtotime($auth_user[0]['sess_expire']))
{
return false;
}
if($_cookie_data['identifier'] == md5($this->cookie_salt . md5($auth_user[0]['username'] . $_SERVER['REMOTE_ADDR']) . $this->cookie_salt))
{
$this->user_logged_in = true;
$this->user_id = $auth_user[0]['user_id'];
$this->user_username = $auth_user[0]['username'];
$this->user_ip = $_SERVER['REMOTE_ADDR'];
return true;
// TODO list
// Renew token every 5 min?
// Renew cookie expire date
// Renew session expire date
}
else
{
return false;
}
}
else
{
return false;
}
}
public function isUserLoggedIn()
{
return $this->user_logged_in;
}
}
The session handler which i include in all pages on the forum.
require_once('classes/user2.class.php');
$user = new User2();
session_start();
Why not start with session_start() in the controller(?).
If not needed always, I'd use a method in the controller so you avoid double session_start:
class controller {
$sStarted = false;
function sStart() {
if (!$this->sStarted) {
session_start();
$this->sStarted = true;
}
regards
/t

Categories