Call to undefined function ecrypt() - function

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

Related

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 );
}

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

codeigniter - convert html to pdf

I have a little problem. I have html page and I want to convert to pdf. My index page has a list that will get to the database and click on "Download PDF", I put this list in a PDF file.
My controller:
<?php
class pdf_c extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper(array('url', 'mediatutorialpdf'));
}
function index($download_pdf = ''){
$ret = '';
$ID = 1;
$pdf_filename = 'user_info_'.$ID.'.pdf';
$link_download = ($download_pdf == TRUE)?'':anchor(base_url().'index.php/true', 'Download PDF');
$query = $this->db->query("SELECT * FROM `ci_pdf_user` WHERE `id` = '{$ID}' LIMIT 1");
if($query->num_rows() > 0)
{
$user_info = $query->row_array();
}
$data_header = array(
'title' => 'Convert codeigniter to pdf'
);
$data_userinfo = array(
'user_info' => $user_info,
'link_download' => $link_download
);
$header = $this->load->view('header',$data_header, true);
$user_info = $this->load->view('user_table', $data_userinfo, true);
$footer = $this->load->view('footer','', true);
$output = $header.$user_info.$footer;
if($download_pdf == TRUE)
{
generate_pdf($output, $pdf_filename);
}
else
{
echo $output;
}
}
}
?>
The problem is when I click the button "Download PDF" should redirect me to the function index () and get the $ download_pdf = true. And so called generate_pdf function () that will generate the PDF.
I think the problem is in the variable $ link_download, but can not solve the problem.
Thanks
I think that you could try with:
function index(pdf = 0)...
Then check that optional parameter with:
$pdf = $this->uri->segment(2, 0); //not sure, should be 2? try it...`
And then, if $pdf=='1' (send nummber rather than string 'true') ...etc,etc...

Google API for analytics invalid grant but works sometimes

I've been on this problem now for 2 days and have tried looking under google code and stackoverflow but still can come up with an answer.
My problem is when I try my google analytics api I get "Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'"
But the weird part is that some times it will work. rarely but if I refresh and keep trying it, it will output.
The only thing I could find is that it could be the refresh token limit has been exceeded
Attached is my code if someone could help me out or point me to the right direction.
Thanks!
<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';
$keyFile = 'key.p12';
$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setAccessType('offline');
$client->setUseObjects(true);
$service = new Google_AnalyticsService($client);
try {
$results = $service->data_ga->get(
'ga:44444444',
date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m- d'))))),
date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
'ga:visits,ga:newVisits',
/*array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:visits,ga:keyword',
'filters' => 'ga:medium==organic',
'max-results' => '25'
)*/
array('dimensions' => 'ga:date')
);
} catch (Google_ServiceException $e) {
// echo $e->getMessage();
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
if ($results && count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
Edit - It's not the NTP, when I echoed date('l jS \of F Y h:i:s A'); it matched up.
The following works to generate output - make sure you are running PHP 5.3 or higher.
<?php
require_once './src/Google_Client.php';
require_once './src/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '.p12';
$service_account_email = '7#developer.gserviceaccount.com';
$client_id = '7.apps.googleusercontent.com';
$analytics_profile_id = 'ga:IN URL OF ANALYTICS';
$client = new Google_Client();
$client->setApplicationName("API TEST");
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$service_account_email,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
$client->setClientId($client_id);
$client->setAccessType('offline_access');
$service = new Google_AnalyticsService($client);
$from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
$to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
try {
$data = $service->data_ga->get(
//
$analytics_profile_id,
$from,
$to,
'ga:visits,ga:newVisits',
array('dimensions' => 'ga:date')
);
if($data && $data['totalResults'] > 0) {
foreach($data['rows'] as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
<?php
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

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;
}