TRUNCATE mysql table in the while loop only executes ones - mysql

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 :(

Related

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

Sage Pay v3.00 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 );
}

insert data to the database from csv file

i am trying to insert data from the csv excel file to the database but the code seem not to work,
i don't know where am doing wrong.
here is my code:
public function postUploadS(){
$file = array('file' => Input::file('file'));
$rule = array('file' => 'required');
$mime = array( 'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel'
);
$uploaded_mime = Input::file('file')->getMimeType();
$staff_list=$_FILES['file']['tmp_name'];
$linecount = "";
$cols = 5;
$numx ="";
$mimes = array(
'text/csv',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',);
if(empty($staff_list)){
$_SESSION['error']="<font color='#FF0000'>Please choose the csv file to upload</font>";
}
elseif(!in_array($_FILES['file']['type'], $mimes)) {
$_SESSION['error']="<font color='#FF0000'>Invalid file format, Please choose only csv exel format</font>";
}
else{
$staff_list=$_FILES['file']['tmp_name'];
$handle=fopen($staff_list,"r");
// read the first line and ignore it
fgets($handle);
//count number of lines of uploaded csv file
$fh = fopen($staff_list,'rb') or die("ERROR OPENING DATA");
while (fgets($fh) !== false) $linecount++;
fclose($fh);
var_dump($fh); exit();
while(($fileop=fgetcsv($handle,1000,",")) !==false){
$fullname = $fileop[1];
$staff_id = $fileop[0];
$gender = $fileop[2];
$position= $fileop[3];
$department= $fileop[4];
$numx = count($fileop);
$tfulname = trim($fullname);
$lfulname = strtolower($tfulname);
$name_full = explode(' ', $lfulname);
$firstname = $name_full[0];
$middlename = implode(array_slice($name_full, 1, -1));
$lastname = end($name_full);
$phone = '';
$email = '';
$college = '';
if($gender == 'M'){
$gender == 'Male';
}
elseif ($gender =='F') {
$gender == 'Female';
}
DB::beginTransaction();
try{
$staff = new Staff;
$staff->staff_id = $staff_id;
$staff->firstname = $firstname;
$staff->middlename = $middlename;
$staff->lastname = $lastname;
$staff->gender = $gender;
$staff->position = $position;
$staff->phone = $phone;
$staff->email = $email;
$staff->college = $college;
$staff->department = $department;
$staff->save();
}
catch(Exception $e){
Session::put('key','There is a duplicate row in your data,check the file and try again');
}
$cPass = ucfirst($lastname);
$hashed_pass = Hash::make($cPass);
$user = new User;
$user->username = $staff_id;
$user->password = $hashed_pass;
$user->save();
}
if($numx!=$cols){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,number of columns does not match the defined value,please check your file and try again</font>");
}
elseif(Session::has('key')){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,duplicate entry detected in your file,please check your file and try again</font>");
}
else{
DB::commit();
Session::put("success","<font color='#0099FF'>Staff list has been uploaded successfully</font>");
}
}
}
when i run above code no data is inserted and i don't get any error. help please
$file = Reader::createFromPath('path-to-your-file');
$result = $file->fetchAll();
foreach($result as $data){
// do database add here
}

Enable a mediawiki function to render wikitext

My mediawiki version is 1.16.5. I have a function that selects a random quote from the database and displays it on a wiki page. Italics and bold are rendered when I use html, however, I want to be able to use wikitext, specifically external links format, i.e.
[http://mediawiki.org MediaWiki]
Currently, if using something like the above, it is not rendered and displays literally. There is some reference on what is needed here: http://www.mediawiki.org/wiki/Manual:Tag_extensions#How_do_I_render_wikitext_in_my_extension.3F but I do not know how to implement this.
Here is the code:
function wfGetQuote() {
$randstr = wfRandom();
$row = selectRandomQuoteFromDB( $randstr );
if( !$row )
$row = selectRandomQuoteFromDB( "0" );
if( $row ) {
list( $quote, $attribution ) = explode( "\n", $row->quote_text );
return '<div id="trrandomquote"><div id="trquote">'. $quote .'</div> <span>'. $attribution .'</span></div>';
}
else
return 'Error: No quote found';
}
function selectRandomQuoteFromDB( $randstr ) {
global $wgUser, $site;
$lang = $wgUser->getOption( 'language' );
if( $site == 'wiki' )
$lang = 'en';
$dbr = wfGetDB( DB_SLAVE );
$use_index = $dbr->useIndexClause( 'quote_random' );
$quote = $dbr->tableName( 'quote' );
$sql = "SELECT quote_text
FROM $quote $use_index
WHERE quote_random >= $randstr
AND quote_lang = '$lang'";
$sql = $dbr->limitResult( $sql, 1, 0 );
$fname = 'RandomQuote::selectRandomQuoteFromDB';
$res = $dbr->query( $sql, $fname );
return $dbr->fetchObject( $res );
}
Normally I use the $wgOut->addWikiText( $msg ); function.
I would modify your code to:
function wfGetQuote() {
global $wgOut; // Added line
$randstr = wfRandom();
$row = selectRandomQuoteFromDB( $randstr );
if( !$row )
$row = selectRandomQuoteFromDB( "0" );
if( $row ) {
list( $quote, $attribution ) = explode( "\n", $row->quote_text );
$wgOut->addWikiText( '<div id="trrandomquote"><div id="trquote">'. $quote .'</div> <span>'. $attribution .'</span></div>' );
}
else
return 'Error: No quote found';
}
I haven't tested it, but it may do the job you're looking for.

PHP MySQL script gone wrong

I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message
Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
$array = mysql_fetch_array($result);
mysql_close($con);
$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
if($pre == NULL){
$pre = $row["headc"];
$test[0][0]=$row["headc"];
$test[0][1]=$row["subc"];
}
else
{
if($pre ==$row["headc"]){
$sc++;
$test[$hc][$sc] = $row["subc"];
}
else
{
$hc++;
$sc = 1;
$test[$hc][0]=$row["headc"];
$test[$hc][$sc]=$row["subc"];
$pre = $row["headc"];
}
}
}
foreach( $test as $arrays=>$cat)
{
$first = TRUE;
foreach($cat as $element)
{
if($first == TRUE)
{
$htmlString.= '<h3>'.$element.'</h3>
<div>
<ul>
';
$first = FALSE;
}
else
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$element.'</a></li>';
}
}
$htmlString.= '</ul> </div>';
}
return $htmlString;
}
I'm really stuck, the page just keeps timing out the point where i call the function
Try this:
while ($array = mysql_fetch_array($result)) {}
Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]
I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
// arrays can have strings as keys as well as numbers,
// and setting $some_array[] = 'value'; (note the empty brackets [])
// automatically appends 'value' to the end of $some_array,
// so you don't have to keep track of or increment indexes
while ($row = mysql_fetch_assoc($result))
{
$test[$row["headc"]][] = $row["subc"];
}
// don't close the connection until after we're done reading the rows
mysql_close($con);
// $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
// so we step through each headc, and within that loop, step through each headc's array of subc's.
foreach($test as $headc => $subc_array)
{
$htmlString.= '<h3>'.$headc.'</h3><div><ul>';
foreach($subc_array as $subc)
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$subc.'</a></li>';
}
$htmlString.= '</ul></div>';
}
return $htmlString;
}