Sage Pay v3.00 Integration - integration

Can anyone help me incorporate the Sagepay v3.00 AES/CBC/PKCS#5 algorithm (encryption) into the following file. I'm really struggling to understand how to include so that customer data is encrypted to the new standard and then decrypted on the way back. Using Sagepay Form with a very old version of cs-cart, though have successfully managed to upgrade from version 2.22 to 2.23, but Sagepay are pulling all support from July.
Not sure how much of this script is relevant to the encryption:
<?php
if ( !defined('IN_CSCART') ) { die('Access denied'); }
if (defined('PAYMENT_NOTIFICATION')) {
// Get the password
$payment_id=db_get_field("SELECT $db_tables[payments].payment_id FROM $db_tables[payments] LEFT JOIN $db_tables[payment_processors] ON $db_tables[payment_processors].processor_id = $db_tables[payments].processor_id WHERE $db_tables[payment_processors].processor_script='protx_form.php'");
$processor_data = fn_get_payment_method_data($payment_id);
$result = "&".simpleXor(base64Decode($_REQUEST['crypt']), $processor_data["params"]["password"])."&";
preg_match("/Status=(.+)&/U", $result, $a);
if(trim($a[1]) == "OK") {
$pp_response['order_status'] = ($processor_data["params"]["transaction_type"] == 'PAYMENT') ? 'P' : 'O';
preg_match("/TxAuthNo=(.+)&/U", $result, $authno);
$pp_response["reason_text"] = "AuthNo: ".$authno[1];
preg_match("/VPSTxID={(.+)}/U", $result, $transaction_id);
$pp_response["transaction_id"] = #$transaction_id[1];
} else {
$pp_response['order_status'] = 'F';
preg_match("/StatusDetail=(.+)&/U", $result, $stat);
$pp_response["reason_text"] = "Status: ".trim($stat[1])." (".trim($a[1]).") ";
}
preg_match("/AVSCV2=(.*)&/U", $result, $avs);
if(!empty($avs[1])) {
$pp_response['descr_avs'] = $avs[1];
}
include $payment_files_dir.'payment_cc_complete.php';
fn_order_placement_routines($order_id);
}
else
{
global $http_location, $b_order, $_total_back;
$post_address = ($processor_data['params']['testmode'] != "N") ? "https://test.sagepay.com/gateway/service/vspform-register.vsp" : "https://live.sagepay.com/gateway/service/vspform-register.vsp";
$post["VPSProtocol"] = "2.23";
$post["TxType"] = $processor_data["params"]["transaction_type"];
$post["Vendor"] = htmlspecialchars($processor_data["params"]["vendor"]);
// Form Cart products
$strings = 0;
if (is_array($cart['products'])) {
$strings += count($cart['products']);
}
if (!empty($cart['products'])) {
foreach ($cart['products'] as $v) {
$_product = db_get_field("SELECT product FROM $db_tables[product_descriptions] WHERE product_id='$v[product_id]' AND lang_code='$cart_language'");
$products_string .= ":".str_replace(":", " ", $_product).":".$v['amount'].":".fn_format_price($v['subtotal']/$v['amount']).":::".fn_format_price($v['subtotal']);
}
}
if (!empty($cart['payment_surcharge'])) {
$products_string .= ":Payment surcharge:---:---:---:---:".fn_format_price($cart['payment_surcharge']);
$strings ++;
}
if (!empty($cart['shipping_cost'])) {
$products_string .= ":Shipping cost:---:---:---:---:".fn_format_price($cart['shipping_cost']);
$strings ++;
}
$post_encrypted .= "Basket=".$strings.$products_string;
$post["Crypt"] = base64_encode(simpleXor($post_encrypted, $processor_data["params"]["password"]));
$post["Crypt"] = htmlspecialchars($post["Crypt"]);
$msg = fn_get_lang_var('text_cc_processor_connection');
$msg = str_replace('[processor]', 'Protx Server', $msg);
echo <<<EOT
<html>
<body onLoad="document.process.submit();">
<form action="{$post_address}" method="POST" name="process">
<INPUT type=hidden name="VPSProtocol" value="{$post['VPSProtocol']}">
<INPUT type=hidden name="Vendor" value="{$post['Vendor']}">
<INPUT type=hidden name="TxType" value="{$post['TxType']}">
<INPUT type=hidden name="Crypt" value="{$post['Crypt']}">
<p>
<div align=center>{$msg}</div>
</p>
</body>
</html>
EOT;
}
exit;
//
// ---------------- Additional functions ------------
//
function simpleXor($InString, $Key) {
$KeyList = array();
$output = "";
for($i = 0; $i < strlen($Key); $i++){
$KeyList[$i] = ord(substr($Key, $i, 1));
}
for($i = 0; $i < strlen($InString); $i++) {
$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
}
return $output;
}
function base64Decode($scrambled) {
// Initialise output variable
$output = "";
// Fix plus to space conversion issue
$scrambled = str_replace(" ","+",$scrambled);
// Do encoding
$output = base64_decode($scrambled);
// Return the result
return $output;
}
?>

You could try dropping the following functions into the script, then swapping out simpleXor for encryptAes. Make sure that you also add an '#' symbol as the first character of the crypt string (and strip it off when decoding the response from Sage Pay).
function addPKCS5Padding($input)
{
$blockSize = 16;
$padd = "";
$length = $blockSize - (strlen($input) % $blockSize);
for ($i = 1; $i <= $length; $i++)
{
$padd .= chr($length);
}
return $input . $padd;
}
function removePKCS5Padding($input)
{
$blockSize = 16;
$padChar = ord($input[strlen($input) - 1]);
$unpadded = substr($input, 0, (-1) * $padChar);
return $unpadded;
}
function encryptAes($string, $key)
{
$string = addPKCS5Padding($string);
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $key);
return strtoupper(bin2hex($crypt));
}
function decryptAes($strIn, $password)
{
$strInitVector = $password;
$strIn = pack('H*', $hex);
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, $strIn, MCRYPT_MODE_CBC,$strInitVector);
return removePKCS5Padding($string);
}

You could try this. I can't test it, so let me know how you get on.
<?php
if ( !defined('IN_CSCART') ) { die('Access denied'); }
if (defined('PAYMENT_NOTIFICATION')) {
// Get the password
$payment_id=db_get_field("SELECT $db_tables[payments].payment_id FROM $db_tables[payments] LEFT JOIN $db_tables[payment_processors] ON $db_tables
[payment_processors].processor_id = $db_tables[payments].processor_id WHERE $db_tables[payment_processors].processor_script='protx_form.php'");
$processor_data = fn_get_payment_method_data($payment_id);
#Rik added:
$result = "&".decryptAes($_REQUEST['crypt'], $processor_data["params"]["password"])."&";
#$result = "&".simpleXor(base64Decode($_REQUEST['crypt']), $processor_data["params"]["password"])."&";
preg_match("/Status=(.+)&/U", $result, $a);
if(trim($a[1]) == "OK") {
$pp_response['order_status'] = ($processor_data["params"]["transaction_type"] == 'PAYMENT') ? 'P' : 'O';
preg_match("/TxAuthNo=(.+)&/U", $result, $authno);
$pp_response["reason_text"] = "AuthNo: ".$authno[1];
preg_match("/VPSTxID={(.+)}/U", $result, $transaction_id);
$pp_response["transaction_id"] = #$transaction_id[1];
} else {
$pp_response['order_status'] = 'F';
preg_match("/StatusDetail=(.+)&/U", $result, $stat);
$pp_response["reason_text"] = "Status: ".trim($stat[1])." (".trim($a[1]).") ";
}
preg_match("/AVSCV2=(.*)&/U", $result, $avs);
if(!empty($avs[1])) {
$pp_response['descr_avs'] = $avs[1];
}
include $payment_files_dir.'payment_cc_complete.php';
fn_order_placement_routines($order_id);
}
else
{
global $http_location, $b_order, $_total_back;
$post_address = ($processor_data['params']['testmode'] != "N") ? "https://test.sagepay.com/gateway/service/vspform-register.vsp" :
"https://live.sagepay.com/gateway/service/vspform-register.vsp";
$post["VPSProtocol"] = "2.23";
$post["TxType"] = $processor_data["params"]["transaction_type"];
$post["Vendor"] = htmlspecialchars($processor_data["params"]["vendor"]);
// Form Cart products
$strings = 0;
if (is_array($cart['products'])) {
$strings += count($cart['products']);
}
if (!empty($cart['products'])) {
foreach ($cart['products'] as $v) {
$_product = db_get_field("SELECT product FROM $db_tables[product_descriptions] WHERE product_id='$v[product_id]' AND lang_code='$cart_language'");
$products_string .= ":".str_replace(":", " ", $_product).":".$v['amount'].":".fn_format_price($v['subtotal']/$v['amount']).":::".fn_format_price($v
['subtotal']);
}
}
if (!empty($cart['payment_surcharge'])) {
$products_string .= ":Payment surcharge:---:---:---:---:".fn_format_price($cart['payment_surcharge']);
$strings ++;
}
if (!empty($cart['shipping_cost'])) {
$products_string .= ":Shipping cost:---:---:---:---:".fn_format_price($cart['shipping_cost']);
$strings ++;
}
$post_encrypted .= "Basket=".$strings.$products_string;
#Rik added:
$post["Crypt"] = "#".encryptAes($post_encrypted, $processor_data["params"]["password"]);
# $post["Crypt"] = base64_encode(simpleXor($post_encrypted, $processor_data["params"]["password"]));
# $post["Crypt"] = htmlspecialchars($post["Crypt"]);
$msg = fn_get_lang_var('text_cc_processor_connection');
$msg = str_replace('[processor]', 'Protx Server', $msg);
echo <<<EOT
<html>
<body onLoad="document.process.submit();">
<form action="{$post_address}" method="POST" name="process">
<INPUT type=hidden name="VPSProtocol" value="{$post['VPSProtocol']}">
<INPUT type=hidden name="Vendor" value="{$post['Vendor']}">
<INPUT type=hidden name="TxType" value="{$post['TxType']}">
<INPUT type=hidden name="Crypt" value="{$post['Crypt']}">
<p>
<div align=center>{$msg}</div>
</p>
</body>
</html>
EOT;
}
exit;
//
// ---------------- Additional functions ------------
//
function simpleXor($InString, $Key) {
$KeyList = array();
$output = "";
for($i = 0; $i < strlen($Key); $i++){
$KeyList[$i] = ord(substr($Key, $i, 1));
}
for($i = 0; $i < strlen($InString); $i++) {
$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
}
return $output;
}
function base64Decode($scrambled) {
// Initialise output variable
$output = "";
// Fix plus to space conversion issue
$scrambled = str_replace(" ","+",$scrambled);
// Do encoding
$output = base64_decode($scrambled);
// Return the result
return $output;
}
#added by Rik
function addPKCS5Padding($input)
{
$blockSize = 16;
$padd = "";
$length = $blockSize - (strlen($input) % $blockSize);
for ($i = 1; $i <= $length; $i++)
{
$padd .= chr($length);
}
return $input . $padd;
}
function removePKCS5Padding($input)
{
$blockSize = 16;
$padChar = ord($input[strlen($input) - 1]);
$unpadded = substr($input, 0, (-1) * $padChar);
return $unpadded;
}
function encryptAes($string, $key)
{
$string = addPKCS5Padding($string);
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $key);
return strtoupper(bin2hex($crypt));
}
function decryptAes($strIn, $password)
{
#Sagepay specific - remove the '#'
$strIn = substr($strIn,1)
$strInitVector = $password;
$strIn = pack('H*', $hex);
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, $strIn, MCRYPT_MODE_CBC,$strInitVector);
return removePKCS5Padding($string);
}
?>

/*First build your data. */
$data = 'variableA='.$this->variableA;
$data .= '&variableB='.$this->variableB;
...
$data .= '&variableZ='.$this->variableZ;
/** Encript data */
$dataEncrip = $this->encData($data);
/** function to Encrypt *//
public function encData($data){
$data = $this->pkcs5_pad( $data, 16);
$dataEnc = "#".bin2hex( mcrypt_encrypt( MCRYPT_RIJNDAEL_128,
$this->passwordToEncript,
$data,
MCRYPT_MODE_CBC,
$this->getPasswordToEncrypt()));
return $dataEnc;
}
/** Pkcs5_pad */
public function pkcs5_pad( $data, $blocksize ){
$pad = $blocksize - (strlen( $data ) % $blocksize);
return $data . str_repeat( chr( $pad ), $pad );
}

Related

The code gives a parse error I can't find what the error is

The code gives a parse error I can't find what the error is, the curlys brackets aren't wrong I'm trying to model the equation, v = \sqrt\frac{19.6mass}{Cd1.229*area}
<?php
function terminalVelocity($mass,$cd,$area) {
$velocity = (sqrt(19.6 * $mass / $cd * 1.229 * $area));
return $volume;
}
if ($_POST['enter']) {
$mass = ($_POST['mass']);
$area = ($_POST['area']);
$cd = ($_POST['cd']);
if ($mass > 0 && $front > 0) {
$result = terminalVelocity($mass,$cd,$area);
echo "The terminal velocity of the is: ". round($result,2);
} else {
echo "You must have a value for each input";
}
?>
if ($_POST['enter']) {
$mass = ($_POST['mass']);
$area = ($_POST['area']);
$cd = ($_POST['cd']);
if ($mass > 0 && $front > 0) {
$result = terminalVelocity($mass,$cd,$area);
echo "The terminal velocity of the is: ". round($result,2);
} else {
echo "You must have a value for each input";
}
The number of {s compared with }s doesn't match. Try:
if ($_POST['enter']) {
$mass = ($_POST['mass']);
$area = ($_POST['area']);
$cd = ($_POST['cd']);
if ($mass > 0 && $front > 0) {
$result = terminalVelocity($mass,$cd,$area);
echo "The terminal velocity of the is: ". round($result,2);
}
} else {
echo "You must have a value for each input";
}
Check this
<?php
function terminalVelocity($mass,$cd,$area) {
$velocity = (sqrt(19.6 * $mass / $cd * 1.229 * $area));
return $volume;
}
if ($_POST['enter']) {
$mass = ($_POST['mass']);
$area = ($_POST['area']);
$cd = ($_POST['cd']);
} elseif ($mass > 0 && $front > 0) {
$result = terminalVelocity($mass,$cd,$area);
echo "The terminal velocity of the is: ". round($result,2);
} else {
echo "You must have a value for each input";
}
?>

Can not save data but the message has been save

I have created Cake PHP 3, I want to add data, but when I clik submit button, the data is didn't save but the message show data has been save. I add into two different tables. When I try to add data in one table is fine.
This is my controller
StoreController.php
public function add()
{
$this->loadComponent('General');
$setStatus = 1;
$store = $this->Stores->newEntity();
if ($this->request->is('post')) {
// dd( $this->request->getData());exit;
$connection = ConnectionManager::get('ora');
$connection->begin();
$store = $this->Stores->patchEntity($store, $this->request->getData());;
$merchantTable = TableRegistry::get('MasterFile.Merchants');
$merchant = $merchantTable->find()->where(['MERCHANT_CODE'=>$store->MERCHANT_CODE])->first();
$store->MERCHANT_ID = $merchant->MERCHANT_ID;
$store->CREATED_DATE = date("Y-m-d h:i:s");
$store->LAST_UPDATED_DATE = date("Y-m-d h:i:s");
$store->LAST_APPROVED_DATE = date("Y-m-d h:i:s");
$store->LAST_VERSION_DATE = date("Y-m-d h:i:s");
// $store->store_address->LINE1 = $store->LINE1;
// Start - Controller Code to handle file uploading
if(!empty($this->request->data['STORE_LOGO']['name']))
{
$file = $this->request->data['STORE_LOGO']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
$fileName = $this->request->data['STORE_LOGO']['name'];
$uploadPath = WWW_ROOT.'img/store_logo/';
$uploadFile = $uploadPath.$fileName;
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($this->request->data['STORE_LOGO']['tmp_name'],$uploadFile))
{
$store['STORE_LOGO'] = $uploadFile;
}
}
}
if(!empty($this->request->data['BACKGROUND_PICTURE']['name']))
{
$fileName = $this->request->data['BACKGROUND_PICTURE']['name'];
$uploadPath = WWW_ROOT.'img/background_picture/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['BACKGROUND_PICTURE']['tmp_name'],$uploadFile))
{
$store['BACKGROUND_PICTURE'] = $uploadFile;
}
}
// now do the save
if ($this->Stores->save($store)) {
$setStatus = 1;
$message = 'The store has been saved.';
if($setStatus == 1){
$this->loadComponent('General');
$this->loadModel('MasterFile.Addresss');
$setStatus = 1;
$address = $this->Addresss->newEntity();
//dd($this->request->data);
$this->request->data['Address']['LINE1'] = $this->request->data['LINE1'];
$this->request->data['Address']['LINE2'] = $this->request->data['LINE2'];
$this->request->data['Address']['LINE3'] = $this->request->data['LINE3'];
//dd($this->request->data['Address']);
$connection = ConnectionManager::get('ora');
$connection->begin();
$address = $this->Addresss->patchEntity($address, $this->request->data['Address']);
// dd($address);
// now do the save
if ($this->Addresss->save($address)) {
$setStatus = 1;
$message = 'The store has been saved.';
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
}
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
if($setStatus){
$connection->commit();
return $this->redirect(['action' => 'index']);
}else {
$connection->rollback();
}
}
$this->set(compact('store'));
$this->set('_serialize', ['store']);
}
What should i do?
Thank you for your help!
Try debugging the entity:
if ($this->Stores->save($store)) {
debug($store);
...

Email attachment does not download with imap_fetchstructure function

I am trying to download email attachment through imap_fetchstructure().
but attachment does not download to the server.
code other parts are perfectly working. text message insert to the database as I coded. only problem is attachment part, can you please help me to resolve this problem. bellow is my code
#!/usr/bin/php -q
<?PHP
//echo $output;
$servername = "localhost";
$username = "user";
$password = "pssw";
$dbname = "db_name";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* connect to email */
$hostname = '{example.org:995/pop3/ssl/novalidate-cert}';
$username = 'test#example.org';
$password = '123456';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to SERVER: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'NEW');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
asort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1);
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
/* prefix the email number to the filename in case two emails
* have the attachment with the same file name.
*/
$fp = fopen("./" . $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
//Attachement close
$subject = $overview[0]->subject;
$from = $overview[0]->from;
$received_date = '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '<div class="body">'.$message.'</div>';
}
//INSERT INTO DATABASE
$sql = "INSERT INTO msg_messages (`customer_id`, `msg_title`, `msg_content`, `received`, `handle_by`, `agent_asign`,`dep_id`, `msg_received_date`, `priority_status`, `from_lyca`) VALUES ('".$cus_id."', '".$subject."', '".$remove_customer_mobile_from_message."', '".$cus_mail."', '999999', '999999', 1, '".date("Y-m-d H:i:s")."', 2, 1)";
$result = mysqli_query($conn, $sql);
}
/* close the connection */
imap_close($inbox);
?>

Call to undefined function ecrypt()

ERROR:Fatal error: Call to undefined function ecrypt()
code all works fine without the ecrypt function call in the anchor. I want to secure it from code injection. why am i getting the above error?
view:
<?php
echo anchor("resetPasswordController/delete_news/".ecrypt($content1['id']),
'<i class="fa fa-trash-o fa-fw"></i>Delete','id="actions"', array
('onClick' => "return confirm('Are you sure you want to delete?')"));?>
controller:
function delete_news() {
$this->load->library('encrypt');
$this->load->model('users_model');
//var_dump($product_id);die();
$ls_id= $this->decrypt($this->uri->segment(3));
$result = $this->users_model->get_id($ls_id);
$this->users_model->delete($ls_id);
$this->db->trans_complete();
$message2 = "News has been deleted successfully";
echo "<script type='text/javascript'>alert('$message2'); </script>";
$this->manage_news();
}
// Encryption function starts
function ecrypt($str)
{
$result ="";
$key = "snowtogsbydigitechsoftwaresolutionsabcxyzdfvdfd";
for($i=0; $i<strlen($str); $i++)
{
$char = substr($str, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return base64_encode($result);
}
// Encryption function end
// This code use for id decrypt
function decrypt($str)
{
$str = base64_decode($str);
$result = '';
$key = "snowtogsbydigitechsoftwaresolutionsabcxyzdfvdfd";
for($i=0;$i<strlen($str); $i++)
{
$char = substr($str, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}
// decryption function end
model:
function delete($id){
$this->db->where('id', $id);
$this->db->delete('news');
}
function get_id($id){
$this->db->where('id',$id);
$query = $this->db->get('news');
return $query->result_array();
}
In your views:
<?php
$CI = & get_instance();
echo anchor("resetPasswordController/delete_news/".$CI->ecrypt($content1['id']),
'<i class="fa fa-trash-o fa-fw"></i>Delete','id="actions"', array
('onClick' => "return confirm('Are you sure you want to delete?')"));?>
Update solution:
Base64 return a string that have = at the last, this may cause problem so you can replace it
function ecrypt($str)
{
$result ="";
$key = "snowtogsbydigitechsoftwaresolutionsabcxyzdfvdfd";
for($i=0; $i<strlen($str); $i++)
{
$char = substr($str, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
$data = base64_encode($result);
$data = str_replace(array('='),array('.'),$data);
return $data
}
Similarly replace '.' with = in decrypt function

TRUNCATE mysql table in the while loop only executes ones

I have a bunch of websites stored as strings in 3 mysql tables. My script puts them into arrays, empties the table, parse the strings, extracts all the links and sort them into 2 tables. Its broken in 3 identical modules which do the sorting. The above mentioned 3 mysql tables gets populate with new data every few seconds from external source (other php script).
The whole thing is looped with while to perform its operations every 90 seconds.
For some reason only on the first go of the loop the TRUNCATE part gets executed, on every next go it doesn't empty the table.
Before I get to my code, I apologize for depreciated mysql, this script will be only to used on local machine and I will update it when the time is right.
Here is my code:
$i=1;
$domain1 = 'example1.com';
$domain2 = 'example2.com';
$domain3 = 'example3.com';
$robots1 = array("url1",
"url2",
"url3");
$robots2 = array("url1",
"url2",
"url3");
$robots3 = array("url1",
"url2",
"url3");
require_once 'Normalizer.php';
$conn = mysql_connect('localhost:3306','user', 'pass', true );
mysql_select_db( 't1000', $conn );
do {
$query = 'SELECT * FROM dump1';
$result1=mysql_query( $query, $conn );
$strings1=array();
while ($row = mysql_fetch_assoc($result1)) {
array_push($strings1, $row["link"]);
}
$query = 'TRUNCATE TABLE dump1';
$delete=mysql_query( $query, $conn );
$query = 'SELECT * FROM dump2';
$result1=mysql_query( $query, $conn );
$strings2=array();
while ($row = mysql_fetch_assoc($result1)) {
array_push($strings2, $row["link"]);
}
$query = 'TRUNCATE TABLE dump2';
$delete=mysql_query( $query, $conn );
$query = 'SELECT * FROM dump3';
$result1=mysql_query( $query, $conn );
$strings3=array();
while ($row = mysql_fetch_assoc($result1)) {
array_push($strings3, $row["link"]);
}
$query = 'TRUNCATE TABLE dump3';
$delete=mysql_query( $query, $conn );
// Module 1 start
$ii=0;
$links = array();
$edofollow = array();
$enofollow = array();
$internal = array();
foreach ($strings1 as $value)
{
$input=$strings1[$ii];
$htm=stripcslashes($input);
$doc = new DOMDocument();
#$doc->loadHTML($htm);
$arr = $doc->getElementsByTagName("a"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
$href = $item->getAttribute("href");
$rel = $item->getAttribute("rel");
$text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
$links[] = array(
'href' => $href,
'rel' => $rel,
'text' => $text
);
if (strpos($href, '://')!==false AND strpos($href, $domain1)==false AND $rel!=='nofollow')
{
$un = new URL\Normalizer();
$un->setUrl( $href );
$href= parse_url($un->normalize(), PHP_URL_HOST);
array_push($edofollow, $href);
}
else if (strpos($href, '://')!==false AND strpos($href, $domain1)==false AND $rel=='nofollow')
{
$un1 = new URL\Normalizer();
$un1->setUrl( $href );
array_push($enofollow, $un1->normalize());
}
else if (strpos($href,'://')==false or strpos($href,$domain1)!==false)
{
$un2 = new URL\Normalizer();
$un2->setUrl( $href );
$href1=$un2->normalize();
if (strpos($href1, 'TRANSCRIPTS')==false AND strpos($href1, '(')==false AND strpos($href1, ')')==false AND strpos($href1, '#')==false AND strpos($href1, 'javascript')==false AND strpos($href1, '?')==false AND strpos($href1, 'void')==false)
{
if($href1=='' or $href1=='/')
{}
else{
if (strpos($href1, '://')==false)
{$href1='http://'.$domain1.$href1;}
if (in_array($href1, $robots1)) { }
else {
array_push($internal, $href1);
}
}
}
}
}
$uedofollow = array_values(array_unique($edofollow));
foreach ($uedofollow as $value) {
$query=mysql_query("select * from dofollow where link='".$value."' ");
$duplicate=0;
if($query){
$duplicate=mysql_num_rows($query);
}
if($duplicate==0)
{
$sql='INSERT INTO dofollow (link) VALUES ("'.$value.'")';
mysql_query( $sql, $conn );
}
}
$uinternal = array_values(array_unique($internal));
foreach ($uinternal as $value2) {
$query=mysql_query("select * from joblist1 where link='".$value2."' ");
if ($query) {
$duplicate=0;
$duplicate=mysql_num_rows($query);
if($duplicate==0)
{
$sql='INSERT INTO joblist1 (link) VALUES ("'.$value2.'")';
mysql_query( $sql, $conn );
}
}
}
$ii=$ii+1;
}
// Module 1 ends
// Module 2 start
$links = array();
$edofollow = array();
$enofollow = array();
$internal = array();
$ii=0;
foreach ($strings2 as $value)
{
$input=$strings2[$ii];
$htm=stripcslashes($input);
$doc = new DOMDocument();
#$doc->loadHTML($htm);
$arr = $doc->getElementsByTagName("a"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
$href = $item->getAttribute("href");
$rel = $item->getAttribute("rel");
$text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
$links[] = array(
'href' => $href,
'rel' => $rel,
'text' => $text
);
if (strpos($href, '://')!==false AND strpos($href, $domain2)==false AND $rel!=='nofollow')
{
$un = new URL\Normalizer();
$un->setUrl( $href );
$href= parse_url($un->normalize(), PHP_URL_HOST);
array_push($edofollow, $href);
}
else if (strpos($href, '://')!==false AND strpos($href, $domain2)==false AND $rel=='nofollow')
{
$un1 = new URL\Normalizer();
$un1->setUrl( $href );
array_push($enofollow, $un1->normalize());
}
else if (strpos($href,'://')==false or strpos($href,$domain2)!==false)
{
$un2 = new URL\Normalizer();
$un2->setUrl( $href );
$href1=$un2->normalize();
if (strpos($href1, 'TRANSCRIPTS')==false AND strpos($href1, '(')==false AND strpos($href1, ')')==false AND strpos($href1, '#')==false AND strpos($href1, 'javascript')==false AND strpos($href1, '?')==false AND strpos($href1, 'void')==false)
{
if($href1=='' or $href1=='/')
{}
else{
if (strpos($href1, '://')==false)
{$href1='http://'.$domain2.$href1;}
if (in_array($href1, $robots2)) { }
else {
array_push($internal, $href1);
}
}
}
}
}
$uedofollow = array_values(array_unique($edofollow));
foreach ($uedofollow as $value) {
$query=mysql_query("select * from dofollow where link='".$value."' ");
$duplicate=0;
if($query){
$duplicate=mysql_num_rows($query);
}
if($duplicate==0)
{
$sql='INSERT INTO dofollow (link) VALUES ("'.$value.'")';
mysql_query( $sql, $conn );
}
}
$uinternal = array_values(array_unique($internal));
foreach ($uinternal as $value2) {
$query=mysql_query("select * from joblist2 where link='".$value2."' ");
if ($query) {
$duplicate=0;
$duplicate=mysql_num_rows($query);
if($duplicate==0)
{
$sql='INSERT INTO joblist2 (link) VALUES ("'.$value2.'")';
mysql_query( $sql, $conn );
}
}
}
$ii=$ii+1;
}
// Module 2 Ends
// Module 3 start
$links = array();
$edofollow = array();
$enofollow = array();
$internal = array();
$ii=0;
foreach ($strings3 as $value)
{
$input=$strings3[$ii];
$htm=stripcslashes($input);
$doc = new DOMDocument();
#$doc->loadHTML($htm);
$arr = $doc->getElementsByTagName("a"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
$href = $item->getAttribute("href");
$rel = $item->getAttribute("rel");
$text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
$links[] = array(
'href' => $href,
'rel' => $rel,
'text' => $text
);
if (strpos($href, '://')!==false AND strpos($href, $domain3)==false AND $rel!=='nofollow')
{
$un = new URL\Normalizer();
$un->setUrl( $href );
$href= parse_url($un->normalize(), PHP_URL_HOST);
array_push($edofollow, $href);
}
else if (strpos($href, '://')!==false AND strpos($href, $domain3)==false AND $rel=='nofollow')
{
$un1 = new URL\Normalizer();
$un1->setUrl( $href );
array_push($enofollow, $un1->normalize());
}
else if (strpos($href,'://')==false or strpos($href,$domain3)!==false)
{
$un2 = new URL\Normalizer();
$un2->setUrl( $href );
$href1=$un2->normalize();
if (strpos($href1, 'TRANSCRIPTS')==false AND strpos($href1, '(')==false AND strpos($href1, ')')==false AND strpos($href1, '#')==false AND strpos($href1, 'javascript')==false AND strpos($href1, '?')==false AND strpos($href1, 'void')==false)
{
if($href1=='' or $href1=='/')
{}
else{
if (strpos($href1, '://')==false)
{$href1='http://'.$domain3.$href1;}
if (in_array($href1, $robots3)) { }
else {
array_push($internal, $href1);
}
}
}
}
}
$uedofollow = array_values(array_unique($edofollow));
foreach ($uedofollow as $value) {
$query=mysql_query("select * from dofollow where link='".$value."' ");
$duplicate=0;
if($query){
$duplicate=mysql_num_rows($query);
}
if($duplicate==0)
{
$sql='INSERT INTO dofollow (link) VALUES ("'.$value.'")';
mysql_query( $sql, $conn );
}
}
$uinternal = array_values(array_unique($internal));
foreach ($uinternal as $value2) {
$query=mysql_query("select * from joblist3 where link='".$value2."' ");
if ($query) {
$duplicate=0;
$duplicate=mysql_num_rows($query);
if($duplicate==0)
{
$sql='INSERT INTO joblist3 (link) VALUES ("'.$value2.'")';
mysql_query( $sql, $conn );
}
}
}
$ii=$ii+1;
}
// Module 3 ends
sleep(90);
$i=$i++;
} while($i<=50000);
I was trying to troubleshoot it for days now, mixing things around but no luck...
How do I get it to empty the table each time?
I was also thinking to get rid of the loop and just run the script with cron, but I think this approach is counter productive :(