PHP Script stopping without any error - php

For some reason i do not know why my script is stopping. It runs for about 20mins and then it stops without retrieving all the records. Im sure something is causing it to stop, but i don't know what. if it were out of memory then i suppose that error message would be thrown, but its not. This project is due next week. We are running this script by a cron job. Please help!
<?php
set_time_limit(0);
ini_set('max_execution_time', 0);
ini_set('memory_limit','4G');
$Num = $_GET['Num'];
$Token = $_GET['Token'];
if(strlen($Num) > 0){
$j = $Num;
$j = 1;
}
else{
$j = 0;
}
$e = 0;
$k = 0;
$g = 1;
$x=0;
$json = '';
$EmailIDs = array();
$leads = new bList();
$leads->listId = 2867;
$AllLeads = array();
$AllLeads = $leads->fields;
if(strlen($Token) > 0){
$NextPage = $Token;
$leads->nextPageToken = $NextPage;
}
RUN();
function RUN(){
global $leads;
global $k;
global $json;
global $Next;
if($k == 0){
AreUnsubscribed($leads->getData());
$k = 1;
$Next = $json[nextPageToken];
$NextPage = $Next;
}
else{
AreUnsubscribed($leads->getData());
$Next = $json[nextPageToken];
if($Next != null){
$NextPage = $Next;
unset($Next);
}
else{
$msg = 'Status = no NextPage' ;
$msg = wordwrap($msg,70);
mail("email#domain.com",'Status = no NextPage - Done',$msg);
}
}
unset($leads,$json,$Next);
}
class bList {
private $host = "Some URL";//CHANGE ME
private $clientId = "###############";//CHANGE ME
private $clientSecret = "###############";//CHANGE ME
public $listId;//id of list to retrieve leads from
public $fields = array("Time","SignUp","createdDate", etc....)
public $batchSize; //max 300 default 300
public $NextPage;
public $nextPageToken; //token returned from previous call for paging
public function getData(){
$url = $this->host . "/rest/v1/list/" . $this->listId . "/leads.json?access_token=" . $this->getToken();
if (isset($this->fields)){
$url = $url . "&fields=" . $this::csvString($this->fields);
}
if (isset($this->batchSize)){
$url = $url . "&batchSize=" . $this->batchSize;
}
if (isset($this->nextPageToken)){
$url = $url . "&nextPageToken=" . $this->nextPageToken;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
private static function csvString($fields){
$csvString = "";
$rr= implode(",",$fields);
$FF = str_replace(' ', '', $rr);
$csvString = $FF;
$csvString = rtrim($csvString,',');
return $csvString;
}
}
function AreUnsubscribed($G){
global $k;
global $AllLeads;
global $EmailIDs;
global $j;
global $e;
global $json;
global $Next;
$json = json_decode($G, true);
if($j == 0){
$EmailIDs[0] = $AllLeads;
$j=1;
}
if($e == 0){
for($n = 0; $n<=300; $n++){
$SORTING = $json['result'][$n];
if($SORTING == null){
break;
}
else{
array_push($EmailIDs, jj($SORTING));
}
unset($SORTING);
}
$e = 1;
$k =1;
RUN();
}
if($k == 1){
Part2($json);
}
unset($EmailIDs, $json, $AllLeads);
}
function Part2($json){
global $EmailIDs;
global $g;
for($n = 0; $n<=300; $n++, $g++){ // 300 records
$SORTING = $json['result'][$n];
if($SORTING == null){
break;
} else{
$EmailIDs[$g] = array_merge((array)$EmailIDs[$g], jj($SORTING));// position
}
unset($SORTING);
}
GG($EmailIDs);
unset($EmailIDs, $json);
}
function jj($kk){
$NewArray = array();
global $AllLeads;
global $e;
if($e == 0){
for($b = 0; $b<270; $b++){
if($kk[$AllLeads[$b]] == null){
array_push($NewArray, $kk[$AllLeads[$b]]);
}
else{
array_push($NewArray, '"'.$kk[$AllLeads[$b]].'"');
}
}
$kk = null;
} else{
for($b = 270; $b<540; $b++){
if($kk[$AllLeads[$b]] == null){
array_push($NewArray, $kk[$AllLeads[$b]]);
}else{
array_push($NewArray, '"'.$kk[$AllLeads[$b]].'"');
}
}
$kk = null;
}
unset($EmailIDs, $json, $kk);
return $NewArray;
unset($NewArray);
}
function GG($val){
$datetime = date('Y-m-d');
global $EmailIDs;
global $x;
global $e;
global $g;
global $Next;
global $j;
global $json;
$handle = fopen("New" . "-Export-" . $datetime . ".csv", "a");
foreach($val as $value){
fputcsv($handle, (array)$value);
}
fclose($handle);
unset($val);
//echo '<pre>';
//$vars = get_defined_vars();
//foreach($vars as $name=>$var)
//{
// echo '<strong>' . $name . '</strong>: ' . strlen(serialize($var)) . '<br/>';
//}
$EmailIDs = array();
$Next = $json[nextPageToken];
if($Next != null){
print_r('{"Number":"'. $j . '", "Token":"' . $Next .'"}');
unset($EmailIDs, $json);
unset($GLOBALS['leads']);
exit;
}else{
print_r('Finished');
}
}
?>

Related

Need Help: Trying to get property 'role' of non-object

I am receiving the bellow error, I am newbie in coding and have not much knowladge.
Can you please help me to resolve this issue?
Trying to get property 'role' of non-object (View:
/home/public_html/resources/views/layouts/back-end/partials-seller/_header.blade.php)
Here is screenshot https://snipboard.io/NSMxv7.jpg
Bellow is code:
<?php
namespace App\CPU;
use App\Model\Admin;
use App\Model\BusinessSetting;
use App\Model\Category;
use App\Model\Color;
use App\Model\Coupon;
use App\Model\Currency;
use App\Model\Order;
use App\Model\Review;
use App\Model\Seller;
use App\Model\ShippingMethod;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class Helpers
{
public static function status($id)
{
if ($id == 1) {
$x = 'active';
} elseif ($id == 0) {
$x = 'in-active';
}
return $x;
}
public static function transaction_formatter($transaction)
{
if ($transaction['paid_by'] == 'customer') {
$user = User::find($transaction['payer_id']);
$payer = $user->f_name . ' ' . $user->l_name;
} elseif ($transaction['paid_by'] == 'seller') {
$user = Seller::find($transaction['payer_id']);
$payer = $user->f_name . ' ' . $user->l_name;
} elseif ($transaction['paid_by'] == 'admin') {
$user = Admin::find($transaction['payer_id']);
$payer = $user->name;
}
if ($transaction['paid_to'] == 'customer') {
$user = User::find($transaction['payment_receiver_id']);
$receiver = $user->f_name . ' ' . $user->l_name;
} elseif ($transaction['paid_to'] == 'seller') {
$user = Seller::find($transaction['payment_receiver_id']);
$receiver = $user->f_name . ' ' . $user->l_name;
} elseif ($transaction['paid_to'] == 'admin') {
$user = Admin::find($transaction['payment_receiver_id']);
$receiver = $user->name;
}
$transaction['payer_info'] = $payer;
$transaction['receiver_info'] = $receiver;
return $transaction;
}
public static function get_customer($request = null)
{
$user = null;
if (auth('customer')->check()) {
$user = auth('customer')->user(); // for web
} elseif ($request != null && $request->user() != null) {
$user = $request->user(); //for api
} elseif (session()->has('customer_id')) {
$user = User::find(session('customer_id'));
}
if ($user == null) {
$user = 'offline';
}
return $user;
}
public static function coupon_discount($request)
{
$discount = 0;
$user = Helpers::get_customer($request);
$couponLimit = Order::where('customer_id', $user->id)
->where('coupon_code', $request['coupon_code'])->count();
$coupon = Coupon::where(['code' => $request['coupon_code']])
->where('limit', '>', $couponLimit)
->where('status', '=', 1)
->whereDate('start_date', '<=', Carbon::parse()->toDateString())
->whereDate('expire_date', '>=', Carbon::parse()->toDateString())->first();
if (isset($coupon)) {
$total = 0;
foreach (CartManager::get_cart(CartManager::get_cart_group_ids($request)) as $cart) {
$product_subtotal = $cart['price'] * $cart['quantity'];
$total += $product_subtotal;
}
if ($total >= $coupon['min_purchase']) {
if ($coupon['discount_type'] == 'percentage') {
$discount = (($total / 100) * $coupon['discount']) > $coupon['max_discount'] ? $coupon['max_discount'] : (($total / 100) * $coupon['discount']);
} else {
$discount = $coupon['discount'];
}
}
}
return $discount;
}
public static function default_lang()
{
if (strpos(url()->current(), '/api')) {
$lang = App::getLocale();
} elseif (session()->has('local')) {
$lang = session('local');
} else {
$data = Helpers::get_business_settings('language');
$code = 'en';
$direction = 'ltr';
foreach ($data as $ln) {
if (array_key_exists('default', $ln) && $ln['default']) {
$code = $ln['code'];
if (array_key_exists('direction', $ln)) {
$direction = $ln['direction'];
}
}
}
session()->put('local', $code);
Session::put('direction', $direction);
$lang = $code;
}
return $lang;
}
public static function rating_count($product_id, $rating)
{
return Review::where(['product_id' => $product_id, 'rating' => $rating])->count();
}
public static function get_business_settings($name)
{
$config = null;
$check = ['currency_model', 'currency_symbol_position', 'system_default_currency', 'language', 'company_name', 'decimal_point_settings'];
if (in_array($name, $check) == true && session()->has($name)) {
$config = session($name);
} else {
$data = BusinessSetting::where(['type' => $name])->first();
if (isset($data)) {
$config = json_decode($data['value'], true);
if (is_null($config)) {
$config = $data['value'];
}
}
if (in_array($name, $check) == true) {
session()->put($name, $config);
}
}
return $config;
}
public static function get_settings($object, $type)
{
$config = null;
foreach ($object as $setting) {
if ($setting['type'] == $type) {
$config = $setting;
}
}
return $config;
}
public static function get_shipping_methods($seller_id, $type)
{
if ($type == 'admin') {
return ShippingMethod::where(['status' => 1])->where(['creator_type' => 'admin'])->get();
} else {
return ShippingMethod::where(['status' => 1])->where(['creator_id' => $seller_id, 'creator_type' => $type])->get();
}
}
public static function get_image_path($type)
{
$path = asset('storage/app/public/brand');
return $path;
}
public static function set_data_format($data)
{
try {
$variation = [];
$data['category_ids'] = json_decode($data['category_ids']);
$data['images'] = json_decode($data['images']);
$data['colors'] = Color::whereIn('code', json_decode($data['colors']))->get(['name', 'code']);
$attributes = [];
if (json_decode($data['attributes']) != null) {
foreach (json_decode($data['attributes']) as $attribute) {
$attributes[] = (integer)$attribute;
}
}
$data['attributes'] = $attributes;
$data['choice_options'] = json_decode($data['choice_options']);
foreach (json_decode($data['variation'], true) as $var) {
$variation[] = [
'type' => $var['type'],
'price' => (double)$var['price'],
'sku' => $var['sku'],
'qty' => (integer)$var['qty'],
];
}
$data['variation'] = $variation;
} catch (\Exception $exception) {
info($exception);
}
return $data;
}
public static function product_data_formatting($data, $multi_data = false)
{
$storage = [];
if ($multi_data == true) {
foreach ($data as $item) {
$storage[] = Helpers::set_data_format($item);
}
$data = $storage;
} else {
$data = Helpers::set_data_format($data);;
}
return $data;
}
public static function units()
{
$x = ['kg', 'pc', 'gms', 'ltrs'];
return $x;
}
public static function remove_invalid_charcaters($str)
{
return str_ireplace(['\'', '"', ',', ';', '<', '>', '?'], ' ', $str);
}
public static function saveJSONFile($code, $data)
{
ksort($data);
$jsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents(base_path('resources/lang/en/messages.json'), stripslashes($jsonData));
}
public static function combinations($arrays)
{
$result = [[]];
foreach ($arrays as $property => $property_values) {
$tmp = [];
foreach ($result as $result_item) {
foreach ($property_values as $property_value) {
$tmp[] = array_merge($result_item, [$property => $property_value]);
}
}
$result = $tmp;
}
return $result;
}
public static function error_processor($validator)
{
$err_keeper = [];
foreach ($validator->errors()->getMessages() as $index => $error) {
$err_keeper[] = ['code' => $index, 'message' => $error[0]];
}
return $err_keeper;
}
public static function currency_load()
{
$default = Helpers::get_business_settings('system_default_currency');
$current = \session('system_default_currency_info');
if (session()->has('system_default_currency_info') == false || $default != $current['id']) {
$id = Helpers::get_business_settings('system_default_currency');
$currency = Currency::find($id);
session()->put('system_default_currency_info', $currency);
session()->put('currency_code', $currency->code);
session()->put('currency_symbol', $currency->symbol);
session()->put('currency_exchange_rate', $currency->exchange_rate);
}
}
public static function currency_converter($amount)
{
$currency_model = Helpers::get_business_settings('currency_model');
if ($currency_model == 'multi_currency') {
if (session()->has('usd')) {
$usd = session('usd');
} else {
$usd = Currency::where(['code' => 'USD'])->first()->exchange_rate;
session()->put('usd', $usd);
}
$my_currency = \session('currency_exchange_rate');
$rate = $my_currency / $usd;
} else {
$rate = 1;
}
return Helpers::set_symbol(round($amount * $rate, 2));
}
public static function language_load()
{
if (\session()->has('language_settings')) {
$language = \session('language_settings');
} else {
$language = BusinessSetting::where('type', 'language')->first();
\session()->put('language_settings', $language);
}
return $language;
}
public static function tax_calculation($price, $tax, $tax_type)
{
$amount = ($price / 100) * $tax;
return $amount;
}
public static function get_price_range($product)
{
$lowest_price = $product->unit_price;
$highest_price = $product->unit_price;
foreach (json_decode($product->variation) as $key => $variation) {
if ($lowest_price > $variation->price) {
$lowest_price = round($variation->price, 2);
}
if ($highest_price < $variation->price) {
$highest_price = round($variation->price, 2);
}
}
$lowest_price = Helpers::currency_converter($lowest_price - Helpers::get_product_discount($product, $lowest_price));
$highest_price = Helpers::currency_converter($highest_price - Helpers::get_product_discount($product, $highest_price));
if ($lowest_price == $highest_price) {
return $lowest_price;
}
return $lowest_price . ' - ' . $highest_price;
}
public static function get_product_discount($product, $price)
{
$discount = 0;
if ($product->discount_type == 'percent') {
$discount = ($price * $product->discount) / 100;
} elseif ($product->discount_type == 'flat') {
$discount = $product->discount;
}
return floatval($discount);
}
public static function module_permission_check($mod_name)
{
$user_role = auth('admin')->user()->role;
$permission = $user_role->module_access;
if (isset($permission) && $user_role->status == 1 && in_array($mod_name, (array)json_decode($permission)) == true) {
return true;
}
if (auth('admin')->user()->admin_role_id == 1) {
return true;
}
return false;
}
public static function convert_currency_to_usd($price)
{
$currency_model = Helpers::get_business_settings('currency_model');
if ($currency_model == 'multi_currency') {
Helpers::currency_load();
$code = session('currency_code') == null ? 'USD' : session('currency_code');
$currency = Currency::where('code', $code)->first();
$price = floatval($price) / floatval($currency->exchange_rate);
} else {
$price = floatval($price);
}
return $price;
}
public static function order_status_update_message($status)
{
if ($status == 'pending') {
$data = BusinessSetting::where('type', 'order_pending_message')->first()->value;
} elseif ($status == 'confirmed') {
$data = BusinessSetting::where('type', 'order_confirmation_msg')->first()->value;
} elseif ($status == 'processing') {
$data = BusinessSetting::where('type', 'order_processing_message')->first()->value;
} elseif ($status == 'out_for_delivery') {
$data = BusinessSetting::where('type', 'out_for_delivery_message')->first()->value;
} elseif ($status == 'delivered') {
$data = BusinessSetting::where('type', 'order_delivered_message')->first()->value;
} elseif ($status == 'returned') {
$data = BusinessSetting::where('type', 'order_returned_message')->first()->value;
} elseif ($status == 'failed') {
$data = BusinessSetting::where('type', 'order_failed_message')->first()->value;
} elseif ($status == 'delivery_boy_delivered') {
$data = BusinessSetting::where('type', 'delivery_boy_delivered_message')->first()->value;
} elseif ($status == 'del_assign') {
$data = BusinessSetting::where('type', 'delivery_boy_assign_message')->first()->value;
} elseif ($status == 'ord_start') {
$data = BusinessSetting::where('type', 'delivery_boy_start_message')->first()->value;
} else {
$data = '{"status":"0","message":""}';
}
$res = json_decode($data, true);
if ($res['status'] == 0) {
return 0;
}
return $res['message'];
}
public static function send_push_notif_to_device($fcm_token, $data)
{
$key = BusinessSetting::where(['type' => 'push_notification_key'])->first()->value;
$url = "https://fcm.googleapis.com/fcm/send";
$header = array("authorization: key=" . $key . "",
"content-type: application/json"
);
if (isset($data['order_id']) == false) {
$data['order_id'] = null;
}
$postdata = '{
"to" : "' . $fcm_token . '",
"data" : {
"title" :"' . $data['title'] . '",
"body" : "' . $data['description'] . '",
"image" : "' . $data['image'] . '",
"order_id":"' . $data['order_id'] . '",
"is_read": 0
},
"notification" : {
"title" :"' . $data['title'] . '",
"body" : "' . $data['description'] . '",
"image" : "' . $data['image'] . '",
"order_id":"' . $data['order_id'] . '",
"title_loc_key":"' . $data['order_id'] . '",
"is_read": 0,
"icon" : "new",
"sound" : "default"
}
}';
$ch = curl_init();
$timeout = 120;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Get URL content
$result = curl_exec($ch);
// close handle to release resources
curl_close($ch);
return $result;
}
public static function send_push_notif_to_topic($data)
{
$key = BusinessSetting::where(['type' => 'push_notification_key'])->first()->value;
$url = "https://fcm.googleapis.com/fcm/send";
$header = ["authorization: key=" . $key . "",
"content-type: application/json",
];
$image = asset('storage/app/public/notification') . '/' . $data['image'];
$postdata = '{
"to" : "/topics/sixvalley",
"data" : {
"title":"' . $data->title . '",
"body" : "' . $data->description . '",
"image" : "' . $image . '",
"is_read": 0
},
"notification" : {
"title":"' . $data->title . '",
"body" : "' . $data->description . '",
"image" : "' . $image . '",
"title_loc_key":"' . $data['order_id'] . '",
"is_read": 0,
"icon" : "new",
"sound" : "default"
}
}';
$ch = curl_init();
$timeout = 120;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Get URL content
$result = curl_exec($ch);
// close handle to release resources
curl_close($ch);
return $result;
}
public static function get_seller_by_token($request)
{
$data = '';
$success = 0;
$token = explode(' ', $request->header('authorization'));
if (count($token) > 1 && strlen($token[1]) > 30) {
$seller = Seller::where(['auth_token' => $token['1']])->first();
if (isset($seller)) {
$data = $seller;
$success = 1;
}
}
return [
'success' => $success,
'data' => $data
];
}
public static function remove_dir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir") Helpers::remove_dir($dir . "/" . $object); else unlink($dir . "/" . $object);
}
}
reset($objects);
rmdir($dir);
}
}
public static function currency_code()
{
Helpers::currency_load();
if (session()->has('currency_symbol')) {
$symbol = session('currency_symbol');
$code = Currency::where(['symbol' => $symbol])->first()->code;
} else {
$system_default_currency_info = session('system_default_currency_info');
$code = $system_default_currency_info->code;
}
return $code;
}
public static function get_language_name($key)
{
$values = Helpers::get_business_settings('language');
foreach ($values as $value) {
if ($value['code'] == $key) {
$key = $value['name'];
}
}
return $key;
}
public static function setEnvironmentValue($envKey, $envValue)
{
$envFile = app()->environmentFilePath();
$str = file_get_contents($envFile);
if (is_bool(env($envKey))) {
$oldValue = var_export(env($envKey), true);
} else {
$oldValue = env($envKey);
}
// $oldValue = var_export(env($envKey), true);
if (strpos($str, $envKey) !== false) {
$str = str_replace("{$envKey}={$oldValue}", "{$envKey}={$envValue}", $str);
// dd("{$envKey}={$envValue}");
// dd($str);
} else {
$str .= "{$envKey}={$envValue}\n";
}
$fp = fopen($envFile, 'w');
fwrite($fp, $str);
fclose($fp);
return $envValue;
}
public static function requestSender()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, array(
CURLOPT_URL => route(base64_decode('YWN0aXZhdGlvbi1jaGVjaw==')),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$data = json_decode($response, true);
return $data;
}
public static function sales_commission($order)
{
$order_summery = OrderManager::order_summary($order);
$order_total = $order_summery['subtotal'] - $order_summery['total_discount_on_product'] - $order['discount_amount'];
$commission_amount = 0;
if ($order['seller_is'] == 'seller') {
$seller = Seller::find($order['seller_id']);
if (isset($seller) && $seller['sales_commission_percentage'] !== null) {
$commission = $seller['sales_commission_percentage'];
} else {
$commission = Helpers::get_business_settings('sales_commission');
}
$commission_amount = (($order_total / 100) * $commission);
}
return $commission_amount;
}
public static function categoryName($id)
{
return Category::select('name')->find($id)->name;
}
public static function set_symbol($amount)
{
$decimal_point_settings = Helpers::get_business_settings('decimal_point_settings');
$position = Helpers::get_business_settings('currency_symbol_position');
if (!is_null($position) && $position == 'left') {
$string = currency_symbol() . '' . number_format($amount, $decimal_point_settings);
} else {
$string = number_format($amount, $decimal_point_settings) . '' . currency_symbol();
}
return $string;
}
public static function pagination_limit()
{
$pagination_limit = BusinessSetting::where('type', 'pagination_limit')->first();
if ($pagination_limit != null) {
return $pagination_limit->value;
} else {
return 25;
}
}
public static function gen_mpdf($view, $file_prefix, $file_postfix)
{
$mpdf = new \Mpdf\Mpdf(['default_font' => 'FreeSerif', 'mode' => 'utf-8', 'format' => [190, 250]]);
/* $mpdf->AddPage('XL', '', '', '', '', 10, 10, 10, '10', '270', '');*/
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf_view = $view;
$mpdf_view = $mpdf_view->render();
$mpdf->WriteHTML($mpdf_view);
$mpdf->Output($file_prefix . $file_postfix . '.pdf', 'D');
}
}
if (!function_exists('currency_symbol')) {
function currency_symbol()
{
Helpers::currency_load();
if (\session()->has('currency_symbol')) {
$symbol = \session('currency_symbol');
} else {
$system_default_currency_info = \session('system_default_currency_info');
$symbol = $system_default_currency_info->symbol;
}
return $symbol;
}
}
//formats currency
if (!function_exists('format_price')) {
function format_price($price)
{
return number_format($price, 2) . currency_symbol();
}
}
function translate($key)
{
$local = Helpers::default_lang();
App::setLocale($local);
try {
$lang_array = include(base_path('resources/lang/' . $local . '/messages.php'));
$processed_key = ucfirst(str_replace('_', ' ', Helpers::remove_invalid_charcaters($key)));
if (!array_key_exists($key, $lang_array)) {
$lang_array[$key] = $processed_key;
$str = "<?php return " . var_export($lang_array, true) . ";";
file_put_contents(base_path('resources/lang/' . $local . '/messages.php'), $str);
$result = $processed_key;
} else {
$result = __('messages.' . $key);
}
} catch (\Exception $exception) {
$result = __('messages.' . $key);
}
return $result;
}
Help me please to remove this error
The error is self describing, you are trying to echo out role on NULL, this means that auth('admin')->user() is NULL. Try to dd(auth()->check()) and see if you are logged in.

BitTorrent: Download not starting

I am trying to implement a bittorrent tracker in Laravel. However, I am stuck at the moment as the download won't start. There is one peer which it appears to be seeding and I am 100% sure that it is connectable. But, when I run a second client on a different machine, the download won't start. It is stuck at "Connecting to peers" (uTorrent).
From the tracker I am sending the following response when the client makes an announce:
d8:intervali1000e12:min intervali300e5:peers18:�ؤ�i�ؑ�XÚJU�6e
In the downloading client I have the following data:
Here's my announce code:
<?php
namespace App\Http\Controllers\Announce;
use App\Helpers\BencodeHelper;
use App\Models\Peer;
use App\Models\PeerTorrent;
use App\Models\Torrent;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
class AnnounceController extends Controller
{
const __INTERVAL = 1000;
const __TIMEOUT = 120;
const __INTERVAL_MIN = 60;
const __MAX_PPR = 20;
public function announce(Request $request)
{
Log::info($request->fullUrl());
$status = 200;
$content = "";
$passkey = Input::get('passkey');
$peer_id = Input::get('peer_id');
$port = Input::get('port');
$info_hash = Input::get('info_hash');
$downloaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$uploaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0;
$left = Input::get('left') ? intval(Input::get('left')) : 0;
$compact = Input::get('compact') ? intval(Input::get('compact')) : 0;
$no_peer_id = Input::get('no_peer_id') ? intval(Input::get('no_peer_id')) : 0;
$ipAddress = '';
// Check for X-Forwarded-For headers and use those if found
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) {
$ipAddress = (trim($_SERVER['HTTP_X_FORWARDED_FOR']));
} else {
if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) {
$ipAddress = (trim($_SERVER['REMOTE_ADDR']));
}
}
$port = $_SERVER['REMOTE_PORT'];
/*if(!$port || !ctype_digit($port) || intval($port) < 1 || intval($port) > 65535)
{
$content = BencodeHelper::track("Invalid client port.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
if ($port == 999 && substr($peer_id, 0, 10) == '-TO0001-XX') {
die("d8:completei0e10:incompletei0e8:intervali600e12:min intervali60e5:peersld2:ip12:72.14.194.184:port3:999ed2:ip11:72.14.194.14:port3:999ed2:ip12:72.14.194.654:port3:999eee");
}*/
if (!$passkey) {
$content = BencodeHelper::track("Missing passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$torrent = Torrent::getByInfoHash(sha1($info_hash));
if (!$torrent || $torrent == null) {
$content = "Torrent not registered with this tracker.";
$status = 404;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$user = User::has('passkeys', '=', $passkey)->get();
if ($user == null) {
$content = BencodeHelper::track("Invalid passkey.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer = Peer::getByHashAndPasskey(bin2hex($peer_id), $passkey);
if ($peer == null) {
$peer = Peer::create([
'hash' => bin2hex($peer_id),
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'ip_address' => $ipAddress,
'passkey' => $passkey,
'port' => $port
]);
}
if (!$info_hash || strlen($info_hash) != 20) {
$content = BencodeHelper::track("Invalid info_hash.");
$status = 401;
return (new Response(AnnounceController::track($content), $status))
->header('Content-Type', $value);
}
$peer_torrent = PeerTorrent::getByPeerAndTorrent($peer, $torrent);
if ($peer_torrent == null) {
$peer_torrent = PeerTorrent::create([
'peer_id' => $peer->id,
'torrent_id' => $torrent->id,
'uploaded' => $uploaded,
'downloaded' => $downloaded,
'left' => $left,
'stopped' => false
]);
} else {
$peer_torrent->uploaded = $uploaded;
$peer_torrent->downloaded = $downloaded;
$peer_torrent->left = $left;
$peer_torrent->save();
}
$seeders = $torrent->getSeedersCount();
$leechers = $torrent->getLeechersCount();
$resp = "";
if ($compact != 1) {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("peers") . "l";
} else {
$resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("min interval") . "i" . 300 . "e5:" . "peers";
}
$peer = array();
$peer_num = 0;
foreach ($torrent->getPeersArray() as $row) {
if ($compact != 1) {
if ($row["peer_id"] === $peer->hash) {
continue;
}
$resp .= "d" . $this->benc_str("ip") . $this->benc_str($row['ip']);
if ($no_peer_id == 0) {
$resp .= $this->benc_str("peer id") . $this->benc_str($row["peer_id"]);
}
$resp .= $this->benc_str("port") . "i" . $row["port"] . "e" . "e";
} else {
$peer_ip = explode('.', $row["ip"]);
$peer_ip = pack("C*", $peer_ip[0], $peer_ip[1], $peer_ip[2], $peer_ip[3]);
$peer_port = pack("n*", (int)$row["port"]);
$time = intval((time() % 7680) / 60);
if ($left == 0) {
$time += 128;
}
$time = pack("C", $time);
$peer[] = $time . $peer_ip . $peer_port;
$peer_num++;
}
}
if ($compact != 1) {
$resp .= "ee";
} else {
$o = "";
for ($i = 0; $i < $peer_num; $i++) {
$o .= substr($peer[$i], 1, 6);
}
$resp .= strlen($o) . ':' . $o . 'e';
}
$this->benc_resp_raw($resp);
}
public function benc_resp($d)
{
return $this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d)));
}
public function benc_resp_raw($x)
{
header("Content-Type: text/plain");
header("Pragma: no-cache");
if ($_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip') {
header("Content-Encoding: gzip");
echo gzencode($x, 9, FORCE_GZIP);
} else {
echo $x;
}
}
function benc($obj)
{
if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"]))
return;
$c = $obj["value"];
switch ($obj["type"]) {
case "string":
return $this->benc_str($c);
case "integer":
return $this->benc_int($c);
case "list":
return $this->benc_list($c);
case "dictionary":
return $this->benc_dict($c);
default:
return;
}
}
public function benc_str($s)
{
return strlen($s) . ":$s";
}
public function benc_int($i)
{
return "i" . $i . "e";
}
public function benc_list($a)
{
$s = "l";
foreach ($a as $e) {
$s .= $this->benc($e);
}
$s .= "e";
return $s;
}
public function benc_dict($d)
{
$s = "d";
$keys = array_keys($d);
sort($keys);
foreach ($keys as $k) {
$v = $d[$k];
$s .= $this->benc_str($k);
$s .= $this->benc($v);
}
$s .= "e";
return $s;
}
public function hex2bin($hex)
{
$r = '';
for ($i = 0; $i < strlen($hex); $i += 2) {
$r .= chr(hexdec($hex{$i} . $hex{($i + 1)}));
}
return $r;
}
}
I am not quite sure what am I missing here.
Maybe it's because you constantly set
->header('Content-Type', $value);
without ever setting $value? So the "Announce-Response" is malformed?
$port = $_SERVER['REMOTE_PORT'];
I think the problem is that the tracker instead of register the port that the connecting peer sends in the announce string, the tracker register the remote port that the peer is connecting from.
That is almost certainly the wrong port to use.

Amazon Scraper Script works on XAMPP Windows but not PHP5 Cli on Linux

I'm trying to scrape Amazon ASIN codes using the below code:
<?php
class Scraper {
const BASE_URL = "http://www.amazon.com";
private $categoryFile = "";
private $outputFile = "";
private $catArray;
private $currentPage = NULL;
private $asin = array();
private $categoriesMatched = 0;
private $categoryProducts = array();
private $pagesMatched = 0;
private $totalPagesMatched = 0;
private $productsMatched = 0;
public function __construct($categoryFile, $outputFile) {
$this->categoryFile = $categoryFile;
$this->outputFile = $outputFile;
}
public function run() {
$this->readCategories($this->categoryFile);
$this->setupASINArray($this->asin);
$x = 1;
foreach ($this->catArray as $cat) {
$this->categoryProducts["$x"] = 0;
if ($this->currentPage == NULL) {
$this->currentPage = $cat;
$this->scrapeASIN($this->currentPage, $x);
$this->pagesMatched++;
}
if ($this->getNextPageLink($this->currentPage)) {
do {
// next page found
$this->pagesMatched++;
$this->scrapeASIN($this->currentPage, $x);
} while ($this->getNextPageLink($this->currentPage));
}
echo "Category complete: $this->pagesMatched Pages" . "\n";
$this->totalPagesMatched += $this->pagesMatched;
$this->pagesMatched = 0;
$this->writeASIN($this->outputFile, $x);
$x++;
$this->currentPage = NULL;
$this->categoriesMatched++;
}
$this->returnStats();
}
private function readCategories($categoryFile) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
}
private function setupASINArray($asinArray) {
$x = 0;
foreach ($this->catArray as $cat) {
$asinArray["$x"][0] = "$cat";
$x++;
}
$this->asin = $asinArray;
}
private function getNextPageLink($currentPage) {
$document = new DOMDocument();
$html = file_get_contents($currentPage);
#$document->loadHTML($html);
$xpath = new DOMXPath($document);
$element = $xpath->query("//a[#id='pagnNextLink']/#href");
if ($element->length != 0) {
$this->currentPage = self::BASE_URL . $element->item(0)->value;
return true;
} else {
return false;
}
}
private function scrapeASIN($currentPage, $catNo) {
$html = file_get_contents($currentPage);
$regex = '~(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?~isx';
preg_match_all($regex, $html, $asin);
foreach ($asin[1] as $match) {
$this->asin[$catNo-1][] = $match;
}
}
private function writeASIN($outputFile, $catNo) {
$fh = fopen($outputFile, "a+");
$this->fixDupes($catNo);
$this->productsMatched += (count($this->asin[$catNo-1]) - 1);
$this->categoryProducts["$catNo"] = (count($this->asin[$catNo-1]) - 1);
flock($fh, LOCK_EX);
$x = 0;
foreach ($this->asin[$catNo-1] as $asin) {
fwrite($fh, "$asin" . "\n");
$x++;
}
flock($fh, LOCK_UN);
fclose($fh);
$x -= 1;
echo "$x ASIN codes written to file" . "\n";
}
private function fixDupes($catNo) {
$this->asin[$catNo-1] = array_unique($this->asin[$catNo-1], SORT_STRING);
}
public function returnStats() {
echo "Categories matched: " . $this->categoriesMatched . "\n";
echo "Pages parsed: " . $this->totalPagesMatched . "\n";
echo "Products parsed: " . $this->productsMatched . "\n";
echo "Category breakdown:" . "\n";
$x = 1;
foreach ($this->categoryProducts as $catProds) {
echo "Category $x had $catProds products" . "\n";
$x++;
}
}
}
$scraper = new Scraper($argv[1], $argv[2]);
$scraper->run();
?>
But it works fine on XAMPP on Windows but not on Linux. Any ideas as to why this may be? Sometimes it scrapes 0 ASIN's to file, sometimes it only scrapes 1 page in a category of 400+ pages. But the output/functionality is totally fine in Windows/XAMPP.
Any thoughts would be greatly appreciated!
Cheers
- Bryce
So try to change this way, just to avoid the error messages:
private function readCategories($categoryFile) {
if (file_exists($categoryFile)) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
} else {
echo "File ".$categoryFile.' not exists!';
$this->catArray = array();
}
}

Change php script with variables from working in http to working in shell

I use a script from here to generate my sitemaps.
I can call it with the browser with http://www.example.com/sitemap.php?update=pages and its working fine.
I need to call it as shell script so that I can automate it with the windows task scheduler. But the script needs to be changed to get the variables ?update=pages. But I don't manage to change it correctly.
Could anybody help me so that I can execute the script from command line with
...\php C:\path\to\script\sitemap.php update=pages. It would also be fine for me to hardcode the variables into the script since I wont change them anyway.
define("BASE_URL", "http://www.example.com/");
define ('BASE_URI', $_SERVER['DOCUMENT_ROOT'] . '/');
class Sitemap {
private $compress;
private $page = 'index';
private $index = 1;
private $count = 1;
private $urls = array();
public function __construct ($compress=true) {
ini_set('memory_limit', '75M'); // 50M required per tests
$this->compress = ($compress) ? '.gz' : '';
}
public function page ($name) {
$this->save();
$this->page = $name;
$this->index = 1;
}
public function url ($url, $lastmod='', $changefreq='', $priority='') {
$url = htmlspecialchars(BASE_URL . 'xx' . $url);
$lastmod = (!empty($lastmod)) ? date('Y-m-d', strtotime($lastmod)) : false;
$changefreq = (!empty($changefreq) && in_array(strtolower($changefreq), array('always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never'))) ? strtolower($changefreq) : false;
$priority = (!empty($priority) && is_numeric($priority) && abs($priority) <= 1) ? round(abs($priority), 1) : false;
if (!$lastmod && !$changefreq && !$priority) {
$this->urls[] = $url;
} else {
$url = array('loc'=>$url);
if ($lastmod !== false) $url['lastmod'] = $lastmod;
if ($changefreq !== false) $url['changefreq'] = $changefreq;
if ($priority !== false) $url['priority'] = ($priority < 1) ? $priority : '1.0';
$this->urls[] = $url;
}
if ($this->count == 50000) {
$this->save();
} else {
$this->count++;
}
}
public function close() {
$this->save();
}
private function save () {
if (empty($this->urls)) return;
$file = "sitemaps/xx-sitemap-{$this->page}-{$this->index}.xml{$this->compress}";
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($this->urls as $url) {
$xml .= ' <url>' . "\n";
if (is_array($url)) {
foreach ($url as $key => $value) $xml .= " <{$key}>{$value}</{$key}>\n";
} else {
$xml .= " <loc>{$url}</loc>\n";
}
$xml .= ' </url>' . "\n";
}
$xml .= '</urlset>' . "\n";
$this->urls = array();
if (!empty($this->compress)) $xml = gzencode($xml, 9);
$fp = fopen(BASE_URI . $file, 'wb');
fwrite($fp, $xml);
fclose($fp);
$this->index++;
$this->count = 1;
$num = $this->index; // should have already been incremented
while (file_exists(BASE_URI . "xxb-sitemap-{$this->page}-{$num}.xml{$this->compress}")) {
unlink(BASE_URI . "xxc-sitemap-{$this->page}-{$num}.xml{$this->compress}");
$num++;
}
$this->index($file);
}
private function index ($file) {
$sitemaps = array();
$index = "sitemaps/xx-sitemap-index.xml{$this->compress}";
if (file_exists(BASE_URI . $index)) {
$xml = (!empty($this->compress)) ? gzfile(BASE_URI . $index) : file(BASE_URI . $index);
$tags = $this->xml_tag(implode('', $xml), array('sitemap'));
foreach ($tags as $xml) {
$loc = str_replace(BASE_URL, '', $this->xml_tag($xml, 'loc'));
$lastmod = $this->xml_tag($xml, 'lastmod');
$lastmod = ($lastmod) ? date('Y-m-d', strtotime($lastmod)) : date('Y-m-d');
if (file_exists(BASE_URI . $loc)) $sitemaps[$loc] = $lastmod;
}
}
$sitemaps[$file] = date('Y-m-d');
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($sitemaps as $loc => $lastmod) {
$xml .= ' <sitemap>' . "\n";
$xml .= ' <loc>' . BASE_URL . $loc . '</loc>' . "\n";
$xml .= ' <lastmod>' . $lastmod . '</lastmod>' . "\n";
$xml .= ' </sitemap>' . "\n";
}
$xml .= '</sitemapindex>' . "\n";
if (!empty($this->compress)) $xml = gzencode($xml, 9);
$fp = fopen(BASE_URI . $index, 'wb');
fwrite($fp, $xml);
fclose($fp);
}
private function xml_tag ($xml, $tag, &$end='') {
if (is_array($tag)) {
$tags = array();
while ($value = $this->xml_tag($xml, $tag[0], $end)) {
$tags[] = $value;
$xml = substr($xml, $end);
}
return $tags;
}
$pos = strpos($xml, "<{$tag}>");
if ($pos === false) return false;
$start = strpos($xml, '>', $pos) + 1;
$length = strpos($xml, "</{$tag}>", $start) - $start;
$end = strpos($xml, '>', $start + $length) + 1;
return ($end !== false) ? substr($xml, $start, $length) : false;
}
public function __destruct () {
$this->save();
}
}
// start part 2
$sitemap = new Sitemap;
if (get('pages')) {
$sitemap->page('pages');
$result = mysql_query("SELECT uri FROM app_uri");
while (list($url, $created) = mysql_fetch_row($result)) {
$sitemap->url($url, $created, 'monthly');
}
}
$sitemap->close();
unset ($sitemap);
function get ($name) {
return (isset($_GET['update']) && strpos($_GET['update'], $name) !== false) ? true : false;
}
?>
I could install wget (it's available for windows as well) and then call the url via localhost in the task scheduler script:
wget.exe "http://localhost/path/to/script.php?pages=test"
This way you wouldn't have to rewrite the php script.
Otherwise, if the script is meant for shell usage only, then pass variables via command line:
php yourscript.php variable1 variable2 ...
In the php script you can than access those variables using the $argv variable:
$variable1 = $argv[1];
$variable2 = $argv[2];
have a look on:
How to pass GET variables to php file with Shell?
which already answered the same question :).

facebook integration suddenly failed using this php class

Facebook integration has been working perfectly on my site for some time, then overnight something happened at facebook because it's now failing.
Can someone have a look at the code I use all over my site and advise what I should do to get this working again as soon as possible, without having to remodel the whole implementation?
<?php
// http://developers.facebook.com/docs/reference/fql/user
class Facebook_class
{
var $cookie;
function Facebook_class() {
$this->cookie = $this->get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
}
function getUserid() {
$cookie = $this->getCookie();
$fb_userid = $cookie['uid'];
return $fb_userid;
}
function getProfilePicture() {
$url = 'https://graph.facebook.com/'.$this->getUserid().'/picture?type=large';
//$url = 'api.facebook.com/method/fql.query?query=SELECT pic_big FROM user WHERE uid = '.$this->getUserid();
$url = $this->get_redirect_url($url);
return $url;
}
function getUserData() {
if($this->getCookie()) {
$url = 'https://graph.facebook.com/me?access_token='.$this->getAccessToken();
$userData = json_decode(file_get_contents($url));
return $userData;
}
}
function getCookie() {
return $this->cookie;
}
function getAccessToken() {
return $this->cookie['access_token'];
}
function loadJsSDK($path_to_library='') {
echo '<script type="text/javascript">
//<![CDATA[ ';
?>
function logoutFacebookUser(){FB.logout(function(response){window.location.reload();});}
function fbActionConnect(){FB.login(function(response){if (response.session){window.location = "http://www.mysite.com/signin/fbconnect";if(response.perms){}else{}}else{}}, {perms:'publish_stream,email'});}
function fbAppActionConnect(){FB.login(function(response){if (response.session){window.location = "http://www.mysite.com/signin/fbappconnect";if(response.perms){}else{}}else{}}, {perms:'publish_stream,email'});}
function fbLinkActionConnect(){FB.login(function(response){if (response.session){window.location = "http://www.mysite.com/index.php?name=signin&file=MyServices&op=linkacc";if(response.perms){}else {}}else{}},{perms:'publish_stream,email'});}
function fbActionCartConnect(id, sport) {FB.login(function(response){if(response.session){window.location = "//index.php?name=signin&file=cart&id=" + id + "&sport=" + sport + "&op=fbsignup";if (response.perms){}else{}}else{}},{perms:'publish_stream,email'});}
window.fbAsyncInit = function() {FB.init({appId: xxxxxxxxxxxxxxxxx, channelUrl:'http://www.mysite.com/channel.html', status: true, cookie: true, xfbml: true});};(function() {var e = document.createElement('script'); e.async = true;e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';document.getElementById('fb-root').appendChild(e);}());//]]></script>
<?php
}
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
function get_redirect_url($url) {
$redirect_url = null;
$url_parts = #parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function getFacebookFriends($criteria='') {
$name = $criteria['name'];
if($name=='') $name = 'me';
$url = 'https://graph.facebook.com/'.$name.'/friends?access_token='.$this->getAccessToken();
$content = #file_get_contents($url,0,null,null);
$content = json_decode($content,true);
$users = $this->formatFacebookUsers($content);
return $users;
}
function formatFacebookUsers($content) {
for($i=0; $i<count($content['data']); $i++) {
$id = $content['data'][$i]['id'];
$name = $content['data'][$i]['name'];
$picture = 'https://graph.facebook.com/'.$id.'/picture?type=square'; //square, small, large
$url = 'http://www.facebook.com/profile.php?id='.$id;
$users[$i]['id'] = $id;
$users[$i]['name'] = $name;
$users[$i]['picture'] = $picture;
$users[$i]['url'] = $url;
}
return $users;
}
function getFacebookAccounts() {
$url = 'https://graph.facebook.com/me/accounts?access_token='.$this->getAccessToken();
$content = #file_get_contents($url,0,null,null);
$content = json_decode($content,true);
return $content;
}
function displayUsersIcons($criteria) {
$users = $criteria['users'];
$nb_display = $criteria['nb_display'];
$width = $criteria['width'];
if($width=='') $width="30";
if($nb_display>count($users) || $nb_display=='') $nb_display=count($users); //display value never bigger than nb users
$display = '';
for($i=0;$i<$nb_display;$i++) {
$name = $users[$i]['name'];
$picture = $users[$i]['picture'];
$url = $users[$i]['url'];
$display .= '<a href="'.$url.'" target="_blank" title="'.$name.'">';
$display .= '<img src="'.$picture.'" width="'.$width.'" style="padding:2px;">';
$display .= '</a>';
}
return $display;
}
function getFacebookFeeds() {
$url = 'https://graph.facebook.com/me/posts?access_token='.$this->getAccessToken();
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data,true);
$dataList = $this->formatFacebookPosts($data);
return $dataList;
}
function formatFacebookPosts($data) {
$i=0;
foreach($data['data'] as $value) {
$id = $value['id'];
$from_id = $value['from']['id'];
$from_name = $value['from']['name'];
$type = $value['type']; //video, link, status, picture, swf
$message = $value['message'];
$picture = $value['picture'];
$link = $value['link'];
$source = $value['source']; //for videos
$name = $value['name']; //for videos or links
$caption = $value['caption']; //for videos (domain name url) or links
$description = $value['description']; //for videos
$icon = $value['icon'];
$created = $value['created_time'];
$likes_nb = $value['likes'];
$comments = $value['comments']['data']; //(message, created_time)
$comments_nb = $value['comments']['count'];
$action_comment = $value['actions'][0]['link'];
$picture_url = 'https://graph.facebook.com/'.$from_id.'/picture';
$profile_url = 'http://www.facebook.com/profile.php?id='.$from_id;
$attribution = $value['attribution'];
if($type=='status') {
$dataList[$i]['id'] = $id;
$dataList[$i]['from_id'] = $from_id;
$dataList[$i]['from_name'] = $from_name;
$dataList[$i]['type'] = $type;
$dataList[$i]['message'] = $message;
$dataList[$i]['picture'] = $picture;
$dataList[$i]['link'] = $link;
$dataList[$i]['source'] = $source;
$dataList[$i]['name'] = $name;
$dataList[$i]['caption'] = $caption;
$dataList[$i]['description'] = $description;
$dataList[$i]['icon'] = $icon;
$dataList[$i]['created'] = $created;
$dataList[$i]['attribution'] = $attribution;
$dataList[$i]['likes_nb'] = $likes_nb;
$dataList[$i]['comments'] = $comments;
$dataList[$i]['comments_nb'] = $comments_nb;
$dataList[$i]['action_comment'] = $action_comment;
$dataList[$i]['picture_url'] = $picture_url;
$dataList[$i]['profile_url'] = $profile_url;
$i++;
}
}
return $dataList;
}
function updateFacebookStatus($status) {
$postParms = "access_token=".$this->getAccessToken()."&message=".$status;
$ch = curl_init('https://graph.facebook.com/me/feed');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParms);
$results = curl_exec($ch);
curl_close($ch);
}
function postmsg() {
$FILE_PATH = $_SERVER["DOCUMENT_ROOT"]."images/default/webedition1.jpg";
$token=$this->getAccessToken();
if (file_exists($FILE_PATH)) {
$args = array('message' => 'From the coaches locker');
$args['image'] = '#' . realpath($FILE_PATH);
$arr_attachment = array('image' => '#'.realpath($FILE_PATH),
'message' => 'Test caption'
);
$_curl = curl_init();
curl_setopt($_curl, CURLOPT_URL, "https://graph.facebook.com/me/photos?access_token=".$token);
curl_setopt($_curl, CURLOPT_HEADER, false);
curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($_curl, CURLOPT_POST, true);
curl_setopt($_curl, CURLOPT_POSTFIELDS, $arr_attachment);
curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, 0);
$_photo = curl_exec($_curl);
echo($_photo);
} else {
echo "cannot find file:".$FILE_PATH;
}
}
}
?>
Thanks.
Facebook introduced some breaking changes for OAuth2 authentication to the JavaScript SDK yesterday: http://developers.facebook.com/blog/post/614/
More details: http://developers.facebook.com/blog/post/525/
Basically some changes I've seen were:
FB.getSession() now changed to FB.getAuthResponse()
FB.init() now has the 'oath' value as always 'true'.
'perms' is now changed to 'scope' in the login button html
Possibly FB.Event.subscribe('auth.sessionChange'..) is now FB.Event.subscribe('auth.authResponseChange'..)
Hope that helps.

Categories