Spade

Mini Shell

Directory:~$ /home/lmsyaran/public_html/joomla3/plugins/chat/send_by_bale/classes/
Upload File

[Home] [System Details] [Kill Me]
Current File:~$ /home/lmsyaran/public_html/joomla3/plugins/chat/send_by_bale/classes/bale_webhook.php

<?php
define('_JEXEC', 1);
define('JPATH_BASE',
dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/');

include_once JPATH_BASE . 'includes/defines.php';
include_once JPATH_BASE . 'includes/framework.php';
// echo JPATH_BASE . 'includes/defines.php'; die();
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

require_once __DIR__ . '/send.php';

//$filename = __DIR__ . "/log2.txt";
//file_put_contents($filename, "param = " . print_r($_GET,
true)."\n", FILE_APPEND);

class bale_webhook extends send
{
    public static function gregorian_to_jalali($gy, $gm, $gd)
    {
        $g_d_m = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304,
334);
        $gy2 = ($gm > 2)? ($gy + 1) : $gy;
        $days = 355666 + (365 * $gy) + ((int)(($gy2 + 3) / 4)) -
((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) + $gd + $g_d_m[$gm
- 1];
        $jy = -1595 + (33 * ((int)($days / 12053)));
        $days %= 12053;
        $jy += 4 * ((int)($days / 1461));
        $days %= 1461;
        if ($days > 365)
        {
            $jy += (int)(($days - 1) / 365);
            $days = ($days - 1) % 365;
        }
        if ($days < 186)
        {
            $jm = 1 + (int)($days / 31);
            $jd = 1 + ($days % 31);
        }
        else
        {
            $jm = 7 + (int)(($days - 186) / 30);
            $jd = 1 + (($days - 186) % 30);
        }
        return array($jy, $jm, $jd);
    }

    public static function human_readble_datetime($timestamp)
    {
        $date = new DateTime("@".$timestamp);  // will snap to
UTC because of the
        $date->setTimezone(new DateTimeZone('Asia/Tehran'));
        // echo $date->format('Y-m-d H:i:s') .
"<br>";  // Pacific time
        $y = intval($date->format('Y'));
        $m = intval($date->format('m'));
        $d = intval($date->format('d'));
        $t = $date->format('H:i:s');
        list($jy, $jm, $jd) = self::gregorian_to_jalali($y, $m, $d);
        return "$jy/$jm/$jd $t";
    }
    public static function when_receive_webhook()
    {
        $filename = __DIR__ . "/log2.txt";
        $data = [];
        $param = file_get_contents('php://input');

        $param = json_decode($param);
        $password = "3a4V4yK)uaM7";
        $spl = ':*&|';
//		 file_put_contents($filename, "param= " . print_r($param,
true)."\n", FILE_APPEND);

        if($param)
        {
            if (isset($param->callback_query))
            {
                self::callback($param);
                return;
            }

            $first_name = $param->message->from->first_name;
            $chat_id = $param->message->chat->id;
            $message_id = $param->message->message_id;
            $message = $param->message->text;
            $type = $param->message->chat->type;
            // //// file_put_contents($filename, "param = " .
print_r($param, true)."\n", FILE_APPEND);
            $from = $param->message->from;
            $bale_username = isset($from->username) ? $from->username
: '';
            $user_chat_id = $from->id;


            $exp_message= explode(' ', $message, 2);
            if (count($exp_message) > 1)
            {
                $start= $exp_message[0];
                $query_param= $exp_message[1];
            }

            if($start == '/start')
            {
//                $app = JFactory::getApplication('site');
//                include_once(JPATH_ADMINISTRATOR .
'/components/com_comprofiler/plugin.foundation.php');
//
//                $cbUser = &CBuser::getInstance($query_param);
//                $user = $cbUser->getUserData();
//                $user->set('cb_balechatid', $user_chat_id);
//                $r= $user->store();

                $object = new stdClass();
                $object->id = $query_param;
                $object->cb_balechatid = $user_chat_id;
                $r=
JFactory::getDbo()->updateObject('#__comprofiler', $object,
'id', true);

                $text = "شما با موفقیت به ربات بله
متصل شدید";
//				$url = JURI::root() . 'bale_webhook.php';


//				$msg2send =
"$password$spl$user_chat_id$spl$message_id$spl$password";
//				$encrypted_chat_id = openssl_encrypt($msg2send,
"AES-128-ECB", $password);
//                $encrypted_chat_id = base64_encode($encrypted_chat_id);
                // str_replace(''

//				$url .= "?code=$encrypted_chat_id";

                $data[] = [
                    "chat_id" => $user_chat_id,
                    "text" => $text
                ];
            }
            elseif(count($exp_message) == 1 && $exp_message[0] ==
'/mycoupon')
            {

                $data[] = [
                    "chat_id" => $user_chat_id,
                    "text" => 'لطفا چند دقیقه
صبر کنید و از زدن درخواست مجدد خودداری
کنید ...'
                ];
                self::send_bale_message($data);

                $data = array();
                $coupon_q = "SELECT DISTINCT u.id, u.firstname, hd.*
FROM #__hikashop_product_category AS hpc
				INNER JOIN #__hikashop_product AS hp ON hp.product_id = hpc.product_id
				INNER JOIN #__reservation_plan as rp ON CONCAT('reserve',
rp.id) = hp.product_code
				INNER JOIN #__reservation_consultant AS rc ON rc.id = rp.consultantid
				INNER JOIN #__comprofiler AS u ON u.id = rc.userid
				INNER JOIN #__hikashop_user AS hu ON hu.user_cms_id = u.id
				INNER JOIN #__hikamarket_vendor AS hv ON hv.vendor_admin_id =
hu.user_id
				INNER JOIN #__hikashop_category AS hc ON hc.category_namekey =
CONCAT('vendor_', hv.vendor_id)
				INNER JOIN #__hikashop_discount AS hd ON hd.discount_category_id =
hc.category_id WHERE u.cb_balechatid = '$user_chat_id' AND
hd.discount_code LIKE 'fatherday%';";
                $db = JFactory::getDbo();
                $db->setQuery($coupon_q);
                $result = $db->loadAssoc();
                if($result)
                {
                    $code = $result['discount_code'];
                    $amount =
intval($result['discount_flat_amount']);
                    $from =
self::human_readble_datetime($result['discount_start']);
                    $to =
self::human_readble_datetime($result['discount_end']);
                    $num = intval($result['discount_quota']) -
intval($result['discount_used_times']);
                    $det = print_r($result, true);
                    $details = "```[جزییات فنی
بیشتر]$det```";
                    $text = "کوپن اختصاصی شما :
*$code*\nمبلغ تخفیف: *$amount* تومان\nتاریخ اعتبار
از *$from* تا *$to*\nتعداد باقیمانده : *$num*
عدد\n$details";
                }
                else
                {
                    $text = 'کوپن تخفیفی برای شما
یافت نشد!';
                }
                $data[] = [
                    "chat_id" => $user_chat_id,
                    "text" => $text
                ];
            }
        }
        else
        {
            $app = JFactory::getApplication('site');
            $input = $app->input;
            // $code = $input->get('code', '');
            $code =
base64_decode($input->getArray()['code']);

            //// file_put_contents($filename, "all= " .
print_r($all, true)."\n", FILE_APPEND);
            // $chat_id =
HelperApi::decryptMessage('[get_code]');
            // // file_put_contents($filename, "Get = " .
print_r($_GET, true)."\n", FILE_APPEND);
            // // file_put_contents($filename, "code = " .
print_r($code, true)."\n", FILE_APPEND);
            if($code)
            {
                $rcv = openssl_decrypt($code, "AES-128-ECB",
$password);
                // // file_put_contents($filename, "rcv = " .
print_r($rcv, true)."\n", FILE_APPEND);
                list($chat_id, $msg_id) = self::validate($rcv, $password,
$spl);
                // // file_put_contents($filename, "chat_id = " .
print_r($chat_id, true)."\n", FILE_APPEND);
                // // file_put_contents($filename, "msg_id = " .
print_r($msg_id, true)."\n", FILE_APPEND);
                $user = JFactory::getUser();
                // // file_put_contents($filename, "user = " .
print_r($user, true)."\n", FILE_APPEND);
                if($user->id)
                {
                    // // file_put_contents($filename, "userid =
" . print_r($user->id, true)."\n", FILE_APPEND);
                    if($chat_id)
                    {
                        // // file_put_contents($filename, "chat_id =
" . print_r($chat_id, true)."\n", FILE_APPEND);

                        if ((!file_exists(JPATH_SITE .
'/libraries/CBLib/CBLib/Core/CBLib.php')) ||
(!file_exists(JPATH_ADMINISTRATOR .
'/components/com_comprofiler/plugin.foundation.php'))) {
                            echo 'CB not installed(bale_webhook.php
file of send_by_bale plugin)';
                            return false;
                        }

                        $db = JFactory::getDbo();
                        $query = $db->getQuery(true);
                       
$query->select($db->quoteName(array('cb_mobilenumber')));
                       
$query->from($db->quoteName('#__comprofiler'));
                       
$query->where($db->quoteName('user_id') . ' = ' .
$db->quote($user->id));
                        $db->setQuery($query);
                        $message = $db->loadResult();

                       
$query->from($db->quoteName('#__send_by_bale',
's'));
                       
$query->where($db->quoteName('s.bale_id').'='.$db->quote($chat_id));
                       
$query->where($db->quoteName('s.mobile').'='.$db->quote($message));

                        $db->setQuery($query);
                        $result = $db->loadObject();

                        if (!empty($result))
                        {
                            $text = "اتصال بله به
سامانه ارم مشاور برای شما از قبل برقرار
گردیده.";
                        }
                        else
                        {
                            $query = $db->getQuery(true);
                            $columns = array('mobile',
'bale_id');
                            $values = array($db->quote($message),
$db->quote($chat_id));

                            $query
                                ->insert('#__send_by_bale')
                                ->columns($columns)
                                ->values(implode(',',
$values));

                            $db->setQuery($query);
                            $db->execute();


                            $text = "اتصال ربات بله به
سامانه ارم مشاور برای شما برقرار گردید.
حتما در گروه بله مربوط به آموزش های فنی
ارم مشاور هم عضو بشوید.

لینک عضویت:

ble.ir/join/CBzWA5ZZ8m";
                        }

                        $object = new stdClass();
                        $object->id = $user->id;
                        $object->cb_balechatid = $chat_id;
                        $result =
JFactory::getDbo()->updateObject('#__comprofiler', $object,
'id', true);
                        // $deldata = [[
                        // 'chat_id' => $chat_id,
                        // 'message_id' => $msg_id
                        // ]];
                        //// file_put_contents($filename, "deldata =
" . print_r($deldata, true)."\n", FILE_APPEND);
                        // self::send_bale_message($deldata,
'delete');

                        $data[] = [
                            'chat_id' => $chat_id,
                            'text' => $text
                        ];

                        //// file_put_contents($filename, "data =
" . print_r($data, true)."\n", FILE_APPEND);

                        self::send_bale_message($data);

                        $app = JFactory::getApplication();

                        $uri = JURI::getInstance();
                        $baseUrl =
$uri->toString(array('scheme', 'host'));
                        // //// file_put_contents($filename, "baseUrl
= " . print_r($baseUrl, true)."\n", FILE_APPEND);
                        $app->enqueueMessage($text,
'success');
                        $app->redirect(JRoute::_($baseUrl .
'/profile-edit'));
                    }
                }
                else
                {
                    $text = "ابتدا باید در سایت
erammoshaver.ir لاگین کنید سپس این  مراحل را
دوباره امتحان کنید. برای ورود می توانید
از لینک https://erammoshaver.ir/cb-login استفاده
کنید.";
                    $data[] = [
                        'chat_id' => $chat_id,
                        'text' => $text
                    ];
                    self::send_bale_message($data);

                    $uri = JURI::getInstance();
                    $baseUrl = $uri->toString(array('scheme',
'host'));
                    // //// file_put_contents($filename, "baseUrl =
" . print_r($baseUrl, true)."\n", FILE_APPEND);
                    $app->enqueueMessage($text, 'success');
                    $app->redirect(JRoute::_($baseUrl .
'/profile-edit'));
                }






            }
        }


        if(!empty($data))
        {
            self::send_bale_message($data);
        }

    }

    public static function validate($message, $password, $spl)
    {
        $filename = __DIR__ . "/log.txt";
        $expl = explode($spl, $message);
        // // file_put_contents($filename, "message = " .
print_r($message, true)."\n", FILE_APPEND);
        // // file_put_contents($filename, "spl = " .
print_r($spl, true)."\n", FILE_APPEND);
        // // file_put_contents($filename, "expl = " .
print_r($expl, true)."\n", FILE_APPEND);
        if(count($expl) != 4)
            return array();
        if(current($expl) != $password || end($expl) != $password)
            return array();
        //// file_put_contents($filename, "test = " .
print_r($expl, true)."\n", FILE_APPEND);
        $pattern = '/^[1-9][0-9]*$/';
        preg_match($pattern, $expl[1], $chtid);
        preg_match($pattern, $expl[2], $msgid);
        if (empty($chtid) || empty($msgid))
            return array();
        return array($chtid[0], $msgid[0]);
    }

    public static function callback($param)
    {
        $app = JFactory::getApplication('site');
        $datar = explode('|',
$param->callback_query->data);


        if ($datar[0]== 'emergency_accept')
        {
            $current_user_id= $datar[1];
            $consultant_user_id= $datar[2];

            include_once(JPATH_ADMINISTRATOR .
'/components/com_comprofiler/plugin.foundation.php');

            $bale_id= $param->callback_query->from->id;
            $message_id=
$param->callback_query->message->message_id;
            $message= $param->callback_query->message->text;

            $cbUser = &CBuser::getInstance($current_user_id);
            $user = $cbUser->getUserData();

            $step= (int)$user->get('cb_emergency_step');

            if ($step== 0)
            {
                $data = [[
                    'chat_id' => $bale_id,
                    'text' => 'این درخواست در
حال حاضر بسته شده است و امکان ثبت درخواست
برای آن وجود ندارد',
                    'message_id'=> $message_id
                ]];
                self::send_bale_message($data, 'edit');
                return true;
            }

            $queue_consultants=
unserialize(!empty($user->get('cb_queue_consultants'))?
$user->get('cb_queue_consultants'): 'a:0:{}');

            if (in_array($consultant_user_id, $queue_consultants))
            {
                return ;
            }

            if (empty($queue_consultants))
            {
                $user->set('cb_emergency_step', 2);
            }


            $time= time();
            // مدت زمان انتظار جهت لغو درخواست
مشاور
            $offset= 900;
            $emergency_request_time=
$user->get('cb_emergency_request_time', time());
            if (($emergency_request_time+ $offset) < $time)
            {
                $data = [[
                    'chat_id' => $bale_id,
                    'text' => $message,
                    'message_id'=> $message_id,
                    "reply_markup"=> [
                        "inline_keyboard"=>[
                            [['text'=> "مدت زمان
پذیرش درخواست به پایان رسید",
"callback_data"=> ""]]
                        ]
                    ]
                ]];
                $data2 = [[
                    'chat_id' => $bale_id,
                    'text' => "مدت زمان پذیرش
این مراجعه کننده به پایان رسیده است."

                ]];
            }
            else
            {
                $queue_consultants[]= $consultant_user_id;
                $user->set('cb_queue_consultants',
serialize($queue_consultants));

                $data = [[
                    'chat_id' => $bale_id,
                    'text' => $message,
                    'message_id'=> $message_id,
                    "reply_markup"=> [
                        "inline_keyboard"=>[
                            [['text'=> "درخواست
شما ثبت شد", "callback_data"=> ""]]
                        ]
                    ]
                ]];
                $data2 = [[
                    'chat_id' => $bale_id,
                    'text' => "درخواست شما
ثبت شد و تا 15 دقیقه آینده کاربر مراجعه
کننده فرصت دارد که فرآیند انتخاب مشاور و
پرداخت را طی کند . اگر تا 15 دقیقه آینده
پیامی در همینجا برای شما مبنی بر خرید پلن
مشاوره شما ارسال نشد، به این معنی است که
کاربر فرآیند لازم را انجام نداده است."

                ]];

                $main_channel_chat_message_id= explode(':',
$datar[3]);
                $main_channel_chat_id= $main_channel_chat_message_id[0];
                $main_channel_message_id=
$main_channel_chat_message_id[1];

                $db = JFactory::getDbo();
                $query = $db->getQuery(true);

                $query->select('text');
               
$query->from($db->quoteName('#__bale_message',
'bm'));
               
$query->where($db->quoteName('chat_id').'='.$db->quote($main_channel_chat_id));
               
$query->where($db->quoteName('message_id').'='.$db->quote($main_channel_message_id));

                $db->setQuery($query);
                $bale_message = $db->loadObject();
                $bale_message_text= $bale_message->text;

                if ($bale_message)
                {
                    $consultantUser =
&CBuser::getInstance($consultant_user_id);
                    $consultant= $consultantUser->getUserData();
                    $consultant_name=
$consultant->get('name');
                    $consultant_mobilenumber=
$consultant->get('cb_mobilenumber');


                    $bale_message_text .=
"\n👨‍⚕{$consultant_name}($consultant_mobilenumber)";
                    $responses=
self::send_bale_message([['chat_id' => $main_channel_chat_id,
'message_id'=> $main_channel_message_id, 'text'=>
$bale_message_text ]], 'edit');

                    $query = $db->getQuery(true);

                    $fields = array(
                        $db->quoteName('text') . ' =
' . $db->quote($bale_message_text),
                    );

                    $conditions = array(
                        $db->quoteName('chat_id') . '
='. $main_channel_chat_id,
                        $db->quoteName('message_id') . '
= '. $main_channel_message_id
                    );

                   
$query->update($db->quoteName('#__bale_message'))->set($fields)->where($conditions);
                    $db->setQuery($query);
                    $result = $db->execute();

//                    $filename = __DIR__ . "/log.txt";
//                    file_put_contents($filename, "bale_message_text
= " . print_r($bale_message_text, true)."\n", FILE_APPEND);
//                    file_put_contents($filename, "responses = "
. print_r($responses, true)."\n", FILE_APPEND);
//                    echo '<pre>';
//                    var_dump(77);
//                    echo '</pre>';
//                    exit();
                }

            }
            $r= $user->store();


            self::send_bale_message($data, 'edit');
            self::send_bale_message($data2);

//            send message to referred
//            self::sendmessage($user->get('cb_mobilenumber'),
$user->get('name'));



            return true;
        }
        elseif ($datar[0]== 'makePrivateCall')
        {
            $bale_id= $param->callback_query->from->id;


            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
           
$query->select($db->quoteName(array('cb_mobilenumber')));
           
$query->from($db->quoteName('#__comprofiler'));
            $query->where($db->quoteName('user_id') .
' = ' . $db->quote($datar[1]));
            $db->setQuery($query);
            $userphone1 = $db->loadResult();

            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
           
$query->select($db->quoteName(array('cb_mobilenumber')));
           
$query->from($db->quoteName('#__comprofiler'));
            $query->where($db->quoteName('user_id') .
' = ' . $db->quote($datar[2]));
            $db->setQuery($query);
            $userphone2 = $db->loadResult();




            $call_data = array(
                // /*'by'			=> 'hash',*/
                'by'			=> 'num',
                'endpoint1'		=> $userphone1,
                'endpoint2'		=> $userphone2,
                'endpoint1_id'  => $datar[1],
                'endpoint2_id'  => $datar[2],
                'session_id'	=> $datar[3],
                'timeout_sec'	=> (int)$datar[4] * 60,
                'bale_id'		=> $bale_id,
                'token'			=> 'lmskaran',
                'status'		=> 0
            );

            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
            $query->select($db->quoteName(array('id')));
            $query->from($db->quoteName('call'));

            $query->where($db->quoteName('endpoint1') .
' = ' . $db->quote($datar[1]));
            $query->where($db->quoteName('endpoint2') .
' = ' . $db->quote($datar[2]));
            $query->where($db->quoteName('session_id') .
' = ' . $db->quote($datar[3]));
            $query->where($db->quoteName('status') . '
= 0');
            $db->setQuery($query);
            $qcall = $db->loadResult();



            $filename = __DIR__ . "/log.txt";
            // file_put_contents($filename, "qcall = " .
print_r($qcall, true)."\n", FILE_APPEND);
            if(!$qcall)
            {
                $call_data['id'] = $qcall;
                $obj = (object)$call_data;
                JFactory::getDbo()->insertObject('call',
$obj);
                $baledata = [[
                    'chat_id' => $bale_id,
                    'text' => 'درحال برقراری
تماس ... لطفا دو دقیقه منتظر باشید',
                ]];
                self::send_bale_message($baledata);
                // file_put_contents($filename, "baledata = " .
print_r($baledata, true)."\n", FILE_APPEND);
                // $endpoint1_id    = JUserHelper::getUserId($datar[1]);
                // $endpoint2_id    = JUserHelper::getUserId($datar[2]);



                /*
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL =>
'https://reclist.lmskaran.com/makePrivateCallBy',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $call_data,
                    CURLOPT_TIMEOUT_MS => 1000,
                    CURLOPT_CONNECTTIMEOUT_MS => 2000,
                ));
                $response = curl_exec($curl);
                curl_close($curl);
                */
                // // file_put_contents($filename, "call_data = "
. print_r($call_data, true)."\n", FILE_APPEND);



                /* // file_put_contents($filename, "response = "
. print_r($response, true)."\n", FILE_APPEND);
                echo $response; */
            }
        }

    }

    public static function sendmessage($phoneNumber, $consultantName)
    {
        $smsService_input_data = array(
            "consultant" => $consultantName
        );
        $smsService_pattern_code = '8bbj7qq33h91ink';
        $smsService_username =  '09122880783';
        $smsService_password =  'fs80170508';

        if ($smsService_username && $smsService_password)
        {
            $res = self::send_sms($phoneNumber, $smsService_input_data,
$smsService_pattern_code, $smsService_username, $smsService_password);
        }

    }

    public static function send_sms($mobilenumber, $smsService_input_data,
$smsService_pattern_code, $smsService_username, $smsService_password)
    {

        $SoapClient = new
SoapClient("http://panel.smsema.com/class/sms/wsdlservice/server.php?wsdl");
        $smsService_from = "+983000505";

        for($i=0; $i< 3; $i++)
        {
            $result= $SoapClient->sendPatternSms($smsService_from,
(array)$mobilenumber, $smsService_username, $smsService_password,
$smsService_pattern_code, $smsService_input_data);
            if ($result)
                return $result;
        }

    }

}


bale_webhook::when_receive_webhook();