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

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.

Related

Torrent with Laravel using Laratracker

I am implementing the laratracker , a bittorrent tracker built in laravel, but unable to start the download. Only one peer appears to be seeding, Sometimes it is saying "Connecting to peers" and remains at it is. The code which i am using is :
<?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;
}
}
<?php
Not sure what to add or modify to the code to get it working . Help appreciated for the solution .

Pass $sSymbol an input parameter to a Class

I got this class code from https://github.com/ricardotiago/sec-gov-api, which is used to retrieve and parse quarterly and yearly reports from the U.S Securities Exchange website.I do not understand how to print the results and what sort of parameters it's accepts. Is$sSmbol an input parameter, how do I pass this parameter so that it displays the quarterly and yearly report
<?php
require_once "parallelCurl.php";
class SecGovAPI {
const SEARCH_LINK = "http://www.sec.gov/cgi-bin/browse-edgar";
const BASE_LINK = "http://www.sec.gov/";
const QUARTERLY_REPORT = '10-Q';
const YEARLY_REPORT = '10-K';
const MOST_RECENT_REPORT = 0;
const ALL_REPORTS = 1;
public function __construct($sSymbol) {
$this->oParallelCurl = new ParallelCurl();
$this->sSymbol = $sSymbol;
$this->oDoc = new DOMDocument();
$this->report = array();
}
public function getQuaterlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::QUARTERLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getYearlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::YEARLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getReportData($oXPath, $link, $sEntity, $sSaveAs) {
$oNodelist = $oXPath->query("//xbrli:xbrl/".$sEntity);
for ($i = 0; $i < $oNodelist->length; $i++) {
$this->report[$link][$sSaveAs][$i] = $oNodelist->item($i)->nodeValue;
}
}
protected function search($sType, $iSearchType) {
$aParams = array("company" => "",
"match" => "",
"CIK" => $this->sSymbol,
"filenum" => "",
"State" => "",
"Country" => "",
"SIC" => "",
"count" => "40",
"owner" => "exclude",
"Find" => "Find Companies",
"action" => "getcompany",
"type" => $sType,
"output" => "atom");
$sUrl = SecGovAPI::SEARCH_LINK . "?". http_build_query($aParams);
$this->oDoc->load($sUrl);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("atom", "http://www.w3.org/2005/Atom");
$aLinks = $this->getReportLinks($oXPath, $iSearchType);
$aReportLinks = array();
foreach ($aLinks as $link) {
$this->oParallelCurl->addUrl($link);
}
$aHtmls = $this->oParallelCurl->run();
foreach ($aHtmls as $html) {
$this->oDoc->loadHTML($html);
$oXPath = new DOMXPath($this->oDoc);
$oNodeList = $oXPath->query('//table[#summary="Data Files"]/tr[2]/td[3]/a');
if ($oNodeList->length === 0) continue;
$aReportLinks[] = $oNodeList->item(0)->getAttribute("href");
}
return $aReportLinks;
}
protected function getReportLinks($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:link");
if ($aNodeList->length === 1)
return array($aNodeList->item(0)->getAttribute("href"));
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:link");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aReportLinks[] = $aNodeList->item($i)->getAttribute("href");
}
return $aReportLinks;
}
else return null;
}
protected function getAccessionNumber($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:id");
if ($aNodeList->length === 1) $sRawAccessNumber = $aNodeList->item(0)->nodeValue;
else return null;
return $this->processAccessionNumber($sRawAccessNumber);
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:id");
for ($i = 0; $i < $aNodeList->length; $i++) {
$sRawAccessNumber = $aNodeList->item($i)->nodeValue;
$aAccessionNumber[] = $this->processAccessionNumber($sRawAccessNumber);
}
return $aAccessionNumber;
}
else return null;
}
protected function processAccessionNumber($sRawAccessNumber) {
$aSplitData = preg_split('/accession-number=/', $sRawAccessNumber);
if (!isset($aSplitData[1])) return null;
$sAccessionNumber = str_replace('-','', $aSplitData[1]);
return $sAccessionNumber;
}
protected function getReportDate($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:updated");
if ($aNodeList->length === 1)
return $sUpdated = $aNodeList->item(0)->nodeValue;
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:updated");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aUpdated[] = $aNodeList->item($i)->nodeValue;
}
return $aUpdated;
}
else return null;
}
}
?>
parallelCurl.php
<?php
class ParallelCurl {
protected $aHandlers;
public function __construct() {
$this->aHandlers = array();
$this->rMultiHandler = curl_multi_init();
}
public function addUrl($sUrl) {
$rHandler = curl_init();
curl_setopt($rHandler, CURLOPT_URL, $sUrl);
curl_setopt($rHandler, CURLOPT_HEADER, 0);
curl_setopt($rHandler, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($this->rMultiHandler, $rHandler);
$this->aHandlers[$sUrl] = $rHandler;
}
public function run() {
$blsRunning = null;
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler === CURLM_CALL_MULTI_PERFORM);
while ($blsRunning && $rHandler == CURLM_OK) {
if (curl_multi_select($this->rMultiHandler) != -1) {
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler == CURLM_CALL_MULTI_PERFORM);
}
}
foreach ($this->aHandlers as $url => $handler) {
$data[$url] = curl_multi_getcontent($handler);
curl_multi_remove_handle($this->rMultiHandler, $handler);
}
$this->aHandlers = array();
return $data;
}
public function __destruct() {
curl_multi_close($this->rMultiHandler);
}
}
?>
To create an instance of the SecGovAPI class you can use the new keyword:
$class = new SecGovAPI($sSymbol);
then you can call the methods getQuaterlyReport and getYearlyReport with:
echo $class->getQuaterlyReport();
echo $class->getYearlyReport();
Both these methods has an argument, and by default is SecGovAPI::MOST_RECENT_REPORT. You can also use:
SecGovAPI::QUARTERLY_REPORT
SecGovAPI::YEARLY_REPORT
SecGovAPI::ALL_REPORTS
Example:
echo $class->getQuaterlyReport(SecGovAPI::QUARTERLY_REPORT);

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.

« An Error occurred during authorization » using Linkedin API

I'm trying to use the Linkedin API in order to publish some content on my company page but I'm facing a very weird error. Here is what I did up to now.
First of all, I registered an application with the following parameters :
OAuth 2.0 Redirect URLs / OAuth 1.0a Accept/Cancel Redirect URL : https://mywebsite.com/linkedin/demo.php
Default Scope : all checked parameters
Then I put in my linkedin folder the following files :
auth.php
<?php
session_start();
$config['base_url'] = 'http://mywebsite.com/linkedin/auth.php';
$config['callback_url'] = 'http://mywebsite.com/linkedin/demo.php';
$config['linkedin_access'] = '************';
$config['linkedin_secret'] = '************';
include_once "linkedin.php";
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
header("Location: " . $linkedin->generateAuthorizeUrl());;
?>
demo.php
<?php
session_start();
$config['base_url'] = 'http://mywebsite.com/linkedin/auth.php';
$config['callback_url'] = 'http://mywebsite.com/linkedin/demo.php';
$config['linkedin_access'] = '************';
$config['linkedin_secret'] = '************';
include_once "linkedin.php";
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;
} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
echo '<pre>';
echo 'My Profile Info';
echo $xml_response;
echo '<br />';
echo '</pre>';
$search_response = $linkedin->search("?company-name=facebook&count=10");
echo $search_response;
$xml = simplexml_load_string($search_response);
echo '<pre>';
echo 'Look people who worked in facebook';
print_r($xml);
echo '</pre>';
?>
I also put the linkedin.php and the OAuth.php files that I easily found online :
Linkedin.php
<?php
require_once("OAuth.php");
class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
public $debug = false;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL) {
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken() {
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl() {
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier) {
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
if($debug) {
echo $response . "\n";
}
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~") {
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
if ($debug) {
echo $auth_header;
}
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status) {
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
if ($debug) {
echo $auth_header . "\n";
}
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function search($parameters) {
$search_url = $this->base_url . "/v1/people/" . $parameters;
echo "Performing search for: " . $parameters . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
if ($debug) {
echo $request->get_signature_base_string() . "\n";
echo $auth_header . "\n";
}
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL) {
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
if ($this->debug) {
echo $data . "\n";
}
curl_close($curl);
return $data;
}
}
OAuth.php
<?php
class OAuthConsumer {
public $key;
public $secret;
function __construct($key, $secret, $callback_url=NULL) {
$this->key = $key;
$this->secret = $secret;
$this->callback_url = $callback_url;
}
function __toString() {
return "OAuthConsumer[key=$this->key,secret=$this->secret]";
}
}
class OAuthToken {
public $key;
public $secret;
function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
}
function to_string() {
return "oauth_token=" .
OAuthUtil::urlencode_rfc3986($this->key) .
"&oauth_token_secret=" .
OAuthUtil::urlencode_rfc3986($this->secret);
}
function __toString() {
return $this->to_string();
}
}
abstract class OAuthSignatureMethod {
abstract public function get_name();
abstract public function build_signature($request, $consumer, $token);
public function check_signature($request, $consumer, $token, $signature) {
$built = $this->build_signature($request, $consumer, $token);
return $built == $signature;
}
}
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
function get_name() {
return "HMAC-SHA1";
}
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
}
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
public function get_name() {
return "PLAINTEXT";
}
public function build_signature($request, $consumer, $token) {
$key_parts = array($consumer->secret,($token) ? $token->secret : "");
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$request->base_string = $key;
return $key;
}
}
abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
public function get_name() { return "RSA-SHA1";}
protected abstract function fetch_public_cert(&$request);
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
$cert = $this->fetch_private_cert($request);
$privatekeyid = openssl_get_privatekey($cert);
$ok = openssl_sign($base_string, $signature, $privatekeyid);
openssl_free_key($privatekeyid);
return base64_encode($signature);
}
public function check_signature($request, $consumer, $token, $signature) {
$decoded_sig = base64_decode($signature);
$base_string = $request->get_signature_base_string();
$cert = $this->fetch_public_cert($request);
$publickeyid = openssl_get_publickey($cert);
$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
openssl_free_key($publickeyid);
return $ok == 1;
}
}
class OAuthRequest {
private $parameters;
private $http_method;
private $http_url;
// for debug purposes
public $base_string;
public static $version = '1.0';
public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) {
#$parameters or $parameters = array();
$parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
$this->parameters = $parameters;
$this->http_method = $http_method;
$this->http_url = $http_url;
}
public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
#$http_url or $http_url = $scheme .
'://' . $_SERVER['HTTP_HOST'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
#$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
if (!$parameters) {
$request_headers = OAuthUtil::get_headers();
$parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
if ($http_method == "POST"
&& #strstr($request_headers["Content-Type"],
"application/x-www-form-urlencoded")
) {
$post_data = OAuthUtil::parse_parameters(
file_get_contents(self::$POST_INPUT)
);
$parameters = array_merge($parameters, $post_data);
}
if (#substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
$header_parameters = OAuthUtil::split_header(
$request_headers['Authorization']
);
$parameters = array_merge($parameters, $header_parameters);
}
}
return new OAuthRequest($http_method, $http_url, $parameters);
}
public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
#$parameters or $parameters = array();
$defaults = array("oauth_version" => OAuthRequest::$version,
//"oauth_nonce" => OAuthRequest::generate_nonce(),
"oauth_timestamp" => OAuthRequest::generate_timestamp(),
"oauth_consumer_key" => $consumer->key);
if ($token)
$defaults['oauth_token'] = $token->key;
$parameters = array_merge($defaults, $parameters);
return new OAuthRequest($http_method, $http_url, $parameters);
}
public function set_parameter($name, $value, $allow_duplicates = true) {
if ($allow_duplicates && isset($this->parameters[$name])) {
if (is_scalar($this->parameters[$name])) {
$this->parameters[$name] = array($this->parameters[$name]);
}
$this->parameters[$name][] = $value;
} else {
$this->parameters[$name] = $value;
}
}
public function get_parameter($name) {
return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
}
public function get_parameters() {
return $this->parameters;
}
public function unset_parameter($name) {
unset($this->parameters[$name]);
}
public function get_signable_parameters() {
$params = $this->parameters;
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
return OAuthUtil::build_http_query($params);
}
public function get_signature_base_string() {
$parts = array(
$this->get_normalized_http_method(),
$this->get_normalized_http_url(),
$this->get_signable_parameters()
);
$parts = OAuthUtil::urlencode_rfc3986($parts);
return implode('&', $parts);
}
public function get_normalized_http_method() {
return strtoupper($this->http_method);
}
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$port = #$parts['port'];
$scheme = $parts['scheme'];
$host = $parts['host'];
$path = #$parts['path'];
$port or $port = ($scheme == 'https') ? '443' : '80';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
public function to_url() {
$post_data = $this->to_postdata();
$out = $this->get_normalized_http_url();
if ($post_data) {
$out .= '?'.$post_data;
}
return $out;
}
public function to_postdata() {
return OAuthUtil::build_http_query($this->parameters);
}
public function to_header($realm=null) {
if($realm)
$out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
else
$out = 'Authorization: OAuth';
$total = array();
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) {
throw new OAuthException('Arrays not supported in headers');
}
$out .= ',' .
OAuthUtil::urlencode_rfc3986($k) .
'="' .
OAuthUtil::urlencode_rfc3986($v) .
'"';
}
return $out;
}
public function __toString() {
return $this->to_url();
}
public function sign_request($signature_method, $consumer, $token) {
$this->set_parameter(
"oauth_signature_method",
$signature_method->get_name(),
false
);
$signature = $this->build_signature($signature_method, $consumer, $token);
$this->set_parameter("oauth_signature", $signature, false);
}
public function build_signature($signature_method, $consumer, $token) {
$signature = $signature_method->build_signature($this, $consumer, $token);
return $signature;
}
private static function generate_timestamp() {
return time();
}
private static function generate_nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand); // md5s look nicer than numbers
}
}
class OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
protected $signature_methods = array();
protected $data_store;
function __construct($data_store) {
$this->data_store = $data_store;
}
public function add_signature_method($signature_method) {
$this->signature_methods[$signature_method->get_name()] =
$signature_method;
}
public function fetch_request_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = NULL;
$this->check_signature($request, $consumer, $token);
$callback = $request->get_parameter('oauth_callback');
$new_token = $this->data_store->new_request_token($consumer, $callback);
return $new_token;
}
public function fetch_access_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// requires authorized request token
$token = $this->get_token($request, $consumer, "request");
$this->check_signature($request, $consumer, $token);
// Rev A change
$verifier = $request->get_parameter('oauth_verifier');
$new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
return $new_token;
}
public function verify_request(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = $this->get_token($request, $consumer, "access");
$this->check_signature($request, $consumer, $token);
return array($consumer, $token);
}
private function get_version(&$request) {
$version = $request->get_parameter("oauth_version");
if (!$version) {
// Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
// Chapter 7.0 ("Accessing Protected Ressources")
$version = '1.0';
}
if ($version !== $this->version) {
throw new OAuthException("OAuth version '$version' not supported");
}
return $version;
}
private function get_signature_method(&$request) {
$signature_method =
#$request->get_parameter("oauth_signature_method");
if (!$signature_method) {
// According to chapter 7 ("Accessing Protected Ressources") the signature-method
// parameter is required, and we can't just fallback to PLAINTEXT
throw new OAuthException('No signature method parameter. This parameter is required');
}
if (!in_array($signature_method,
array_keys($this->signature_methods))) {
throw new OAuthException(
"Signature method '$signature_method' not supported " .
"try one of the following: " .
implode(", ", array_keys($this->signature_methods))
);
}
return $this->signature_methods[$signature_method];
}
private function get_consumer(&$request) {
$consumer_key = #$request->get_parameter("oauth_consumer_key");
if (!$consumer_key) {
throw new OAuthException("Invalid consumer key");
}
$consumer = $this->data_store->lookup_consumer($consumer_key);
if (!$consumer) {
throw new OAuthException("Invalid consumer");
}
return $consumer;
}
private function get_token(&$request, $consumer, $token_type="access") {
$token_field = #$request->get_parameter('oauth_token');
$token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field
);
if (!$token) {
throw new OAuthException("Invalid $token_type token: $token_field");
}
return $token;
}
private function check_signature(&$request, $consumer, $token) {
$timestamp = #$request->get_parameter('oauth_timestamp');
$nonce = #$request->get_parameter('oauth_nonce');
$this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp);
$signature_method = $this->get_signature_method($request);
$signature = $request->get_parameter('oauth_signature');
$valid_sig = $signature_method->check_signature(
$request,
$consumer,
$token,
$signature
);
if (!$valid_sig) {
throw new OAuthException("Invalid signature");
}
}
private function check_timestamp($timestamp) {
if( ! $timestamp )
throw new OAuthException(
'Missing timestamp parameter. The parameter is required'
);
// verify that timestamp is recentish
$now = time();
if (abs($now - $timestamp) > $this->timestamp_threshold) {
throw new OAuthException(
"Expired timestamp, yours $timestamp, ours $now"
);
}
}
private function check_nonce($consumer, $token, $nonce, $timestamp) {
if( ! $nonce )
throw new OAuthException(
'Missing nonce parameter. The parameter is required'
);
// verify that the nonce is uniqueish
$found = $this->data_store->lookup_nonce(
$consumer,
$token,
$nonce,
$timestamp
);
if ($found) {
throw new OAuthException("Nonce already used: $nonce");
}
}
}
class OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
}
}
class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
return str_replace(
'+',
' ',
str_replace('%7E', '~', rawurlencode($input))
);
} else {
return '';
}
}
public static function urldecode_rfc3986($string) {
return urldecode($string);
}
public static function split_header($header, $only_allow_oauth_parameters = true) {
$pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
$offset = 0;
$params = array();
while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
$match = $matches[0];
$header_name = $matches[2][0];
$header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
$params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
}
$offset = $match[1] + strlen($match[0]);
}
if (isset($params['realm'])) {
unset($params['realm']);
}
return $params;
}
public static function get_headers() {
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
$out = array();
foreach( $headers AS $key => $value ) {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("-", " ", $key)))
);
$out[$key] = $value;
}
} else {
$out = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
);
$out[$key] = $value;
}
}
}
return $out;
}
public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();
$pairs = explode('&', $input);
$parsed_parameters = array();
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = OAuthUtil::urldecode_rfc3986($split[0]);
$value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
if (isset($parsed_parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to the list
// of parameters with this name
if (is_scalar($parsed_parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into an array
// so we can add the duplicates
$parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
return $parsed_parameters;
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
natsort($value);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}
?>
But when I tried to get the auth.php page, I get this error :
An Error occurred during authorization, please try again later.
And I end up on this page : https://www.linkedin.com/uas/oauth/authorize?oauth_token=
So, is it a problem on my side or on their side ?
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
Use this line in your function httpRequest in linkedin.php
Note:
Download https://github.com/Thamaraiselvam/Linkedin-Api
I have cleared all errors

I'm using text file as db # php,but sometimes it fails to save

Hi I am using serialize & unserialize functions and fwrite & fopen for text based db
<?php
ini_set('display_errors', 'on');
header('Content-Type: text/html; charset=utf-8');
$debugged = (bool) isset($_GET['debug']);
error_reporting($debugged ? E_ALL : 0);
$data_filename = "database.txt";
$admins = array(
"admin" => "admin",
"admin2" => "admin2"
);
$superadmin = "admin";
$order = "asc";
include_once "functions.php";
?>
<?php
function clean($d) {
return str_replace(array(
"\t",
"\n",
"\s",
"\r"
), "", $d);
}
function add($email, $age_id, $gender_id, $city, $prof_id, $model, $token, $os_version, $udid, $admin) {
global $data_filename;
$datax['email'] = $email;
$datax['age_id'] = $age_id;
$datax['gender_id'] = $gender_id;
$datax['city'] = $city;
$datax['prof_id'] = $prof_id;
$datax['model'] = $model;
$datax['token'] = $token;
$datax['os_version'] = $os_version;
$datax['udid'] = $udid;
$datax['admin'] = $admin;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
$entrie = serialize($datax);
$data[] = $entrie;
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function get_file_content($filename) {
if (!file_exists($filename))
fclose(fopen($filename, "w"));
if (!file_exists($filename))
die("sie.");
$content = (filesize($filename) > 0) ? #fread(fopen($filename, "r+"), filesize($filename)) : NULL;
if ($content === false)
die("aq");
return $content;
}
if (!$data_filename) {
die("sie-31");
}
$datasey = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$datasey = #unserialize($data_content);
function put_file_content($filename, $content) {
if (file_put_contents($filename, $content, LOCK_EX)) {
return true;
} else {
usleep(250000);
put_file_content($filename, $content, LOCK_EX);
}
}
function reverse_data($data) {
$data = array_reverse($data);
foreach ($data as $key => $entrie)
$key = $entries_num - $key - 1;
return $data;
}
function del_admin_contents($who) {
global $admin, $superadmin, $data_filename;
;
$array = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$array = unserialize($data_content);
foreach ($array as $key => $value) {
$bok = unserialize($value);
if ($bok["admin"] == $who) {
unset($array[$key]);
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
$data_content = serialize($array);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_entries($select, $udid) {
global $data_filename;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$data = unserialize($data_content);
$data = del_id($data, $select, $udid);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_id($array, $id_array, $udid) {
global $admin, $superadmin;
foreach ($id_array as $id)
if (isset($array[$id])) {
$bok = unserialize($array[$id]);
if ($bok["admin"] == $admin || $admin == $superadmin) {
if ($bok["udid"] == $udid) {
unset($array[$id]);
}
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
return $temp;
}
function up_id($array, $new_array, $id) {
global $admin, $superadmin;
if (isset($array[$id])) {
$array[$id] = serialize($new_array);
}
return $array;
}
function update_id($data, $id, $new_array) {
global $data_filename;
$data = up_id($data, $new_array, $id);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function emailupdate($udid, $email) {
global $data_filename;
$data = array();
$ret = false;
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return false;
$data = unserialize($data_content);
$id = 0;
foreach ($data as $d) {
$new_array = unserialize($d);
if ($new_array["udid"] == $udid) {
$new_array["email"] = $email;
update_id($data, $id, $new_array);
$ret = true;
}
$id++;
}
return $ret;
}
function alldata() {
global $datasey;
$benimdata = array();
if (count($datasey) > 0) {
foreach ($datasey as $key => $entrie) {
$gec = unserialize($entrie);
$benimdata[] = $gec;
}
return $benimdata;
} else {
return false;
}
}
function cleaner() {
global $data_filename, $max_entries;
if ($max_entries == 0)
return;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
while (count($data) >= $max_entries)
$data = clear_id($data, array(
0
));
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function logincheck($user, $pass) {
global $admins;
if (array_key_exists($user, $admins)) {
if ($admins[$user] == $pass) {
return true;
} else {
return false;
}
} else {
return false;
}
}
$backup = "./backup/" . date("Ymd-H:i") . ".dat";
if (!file_exists($backup)) {
$backup_data_content = get_file_content($data_filename);
file_put_contents($backup, $backup_data_content, LOCK_EX);
}
?>
As here is an example of how I add new value(s):
$data_content=add($_POST["email"],$_POST["age_id"],$_POST["gender_id"],$_POST["city_id"],$_POST["prof_id"],$_POST["model"],"N/A",$_POST["os_version"],$randomudid,$admin);
for delete :
$data_content=del_entries(array($_GET["del"]),$_GET["delete"]);
My question is when 2 admins try to enter a value at the same time it writes to database only the last value sent and deletes the old values, how can I resolve this issue?

Categories