Spade

Mini Shell

Directory:~$ /home/lmsyaran/public_html/modules/mod_emergencyconsultant/
Upload File

[Home] [System Details] [Kill Me]
Current File:~$ /home/lmsyaran/public_html/modules/mod_emergencyconsultant/helper.php

<?php
/*----------------------------------------------------------------------------------|
 www.vdm.io  |----/
				Vast Development Method 
/-------------------------------------------------------------------------------------------------------/

	@version		2.0.3
	@build			14th September, 2023
	@created		18th October, 2016
	@package		Demo
	@subpackage		helper.php
	@author			Llewellyn van der Merwe <https://www.vdm.io/>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later -
http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____ 
_____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \( 
_  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/
)(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__) 
(_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

class ModEmergencyConsultantHelper
{
	public static function do_step0($input, $cb_user)
	{

		$topic = $input->get('topic', null, 'string');
		if (!$topic)
		{
			jfactory::getapplication()->enqueuemessage('یکی از
موضوعات را انتخاب کنید', 'warning');

			return;
		}

		$emergency_request_time = (int)
$cb_user->get('cb_emergency_request_time', 0);
		$time                   = time();

		$offset = 900;
		if (($emergency_request_time + $offset) >= $time)
		{
			jfactory::getapplication()->enqueuemessage("جهت ثبت
درخواست مجدد باید 15 دقیقه از درخواست قبلی
شما بگذرد", 'warning');

			return;
		}
		else
		{
			$cb_user->set('cb_emergency_request_time', $time);
		}


		$user                  = jfactory::getuser();
		$current_user_id       = $user->get('id', 0,
'int');
		$current_user_name     = $user->get('name');
		$current_user_username = $user->get('username');
		$userIds[]             = intval($current_user_id);
		$sendTo                = $input->get('sendto', 0,
'INT');
		if ($sendTo)
		{
			$userIds[] = $sendTo;
		}
		$userDetails = self::getUserDetails($userIds, ['user_id',
'firstname', 'lastname',
'cb_mobilenumber']);

		$current_user_phone_number = $current_user_id != 0 ?
$userDetails[$current_user_id]->cb_mobilenumber : '';

		$groups    = $user->get('groups');
		$errorfake = "";
		if (in_array("10", $groups))
		{
			$errorfake = "*این درخواست از سمت یک مشاور
جهت آزمایش سامانه بوده است. لطفا بخش
اورژانس سامانه را آزمایش نکنید.فیلم
آموزشی موجود است به آن مراجعه کنید، نیازی
به زدن دکمه پذیرفتن نیست.*";
		}
		// dump($groups,"groups");
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('title')
			->from('#__usergroups')
			->where('id IN (' . implode(', ', $groups) .
')');
		$db->setQuery($query);
		$usergroups = implode(' ', $db->loadColumn());

//       $usergroupnames="نقش واقعی فرد:
".$usergroups;
//        $timezone = (array)jFactory::getUser()->getTimezone();
//        date_default_timezone_set($timezone['timezone']);
//        $time = date('H:i:s');

//        $emergency_start_time=
$cb_user->get('cb_emergency_start_time',
'00:00:00')== '00:00:00' ? '00:00:00':
$cb_user->get('cb_emergency_start_time');
//        $emergency_end_time=
$cb_user->get('cb_emergency_end_time', '00:00:00')==
'00:00:00' ? '23:59:59':
$cb_user->get('cb_emergency_start_time');


		$params         =
JComponentHelper::getParams('com_reservation');
		$category_rules = $params->get('category_rule');
		foreach ($category_rules as $category_rule)
		{
			if ($category_rule->cat_rule == 'eplanrule')
			{
				$emergency_catid = $category_rule->catid;
			}
		}


		//        $db = JFactory::getDbo();
		//        $query = $db->getQuery(true);
		//
		//        $query->select('c.id as cbid, cb_queue_consultants,
cb_balechatid, cb_emergency_start_time, cb_emergency_end_time');
		//        $query->from($db->quoteName('#__comprofiler',
'c'));
		//        $query->join('INNER',
$db->quoteName('#__reservation_consultant', 'rc') .
' ON ' . $db->quoteName('rc.userid') . ' =
' . $db->quoteName('c.id'));
		//        $query->join('INNER',
$db->quoteName('#__reservation_plan', 'p') . '
ON ' . $db->quoteName('rc.id') . ' = ' .
$db->quoteName('p.consultantid'));
		//       
$query->where($db->quoteName('c.cb_is_emergency') . '=
1');
		//        $query->where($db->quoteName('p.catid') .
'='. $emergency_catid);
		//       
$query->where('TIME_FORMAT('.$db->quoteName('c.cb_emergency_start_time').',
\'%H:%i:%s\')' . '<=\''.
$time.'\'');
		//       
$query->where('TIME_FORMAT('.$db->quoteName('c.cb_emergency_end_time').',
\'%H:%i:%s\')' . '>=\''.
$time.'\'');
		//        $query->where($db->quoteName('c.cb_balechatid')
. 'is not null');
		//        $query->where($db->quoteName('p.published') .
'= 1');
		//
		//        $db->setQuery($query);
		//        $results = $db->loadObjectList('cbid');

		// sent to specefic user
		$sendto = $input->get('sendto', 0);
		$sendto = $sendto ? "&sendto=" . $sendto : "";
//        $sendto= "&sendto=941";
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL            =>
'https://erammoshaver.ir/index.php?option=com_comprofiler&view=pluginclass&plugin=cbautoactions&action=action&actions=125&Itemid=147'
. $sendto,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => '',
			CURLOPT_MAXREDIRS      => 10,
			CURLOPT_TIMEOUT        => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST  => 'GET'
		));

		$results = json_decode(curl_exec($curl));
		curl_close($curl);
		// $file_name = __DIR__ . '/files_log.txt';
		// file_put_contents($file_name, "var = " . print_r($results,
true) . "\n", FILE_APPEND);
//	    echo '<br><pre style="direction:
ltr;">';
//	    var_dump($results);
//	   
var_dump('https://erammoshaver.ir/index.php?option=com_comprofiler&view=pluginclass&plugin=cbautoactions&action=action&actions=125&Itemid=147'.$sendto);
//	    echo '</pre><br>';
//	    exit();
		$text = '';
		//custom text for out of que bale message
		if ($sendto)
		{
			$text .= " {$errorfake}درخواست اختصاصی مشاوره
اورژانسی فقط برای شما به صورت *{$topic}* توسط
*{$current_user_name}* ارسال شده است.
          چنانچه امکان پاسخگویی دارید تایید
لازم را بدهید و پس از تایید شما، کاربر
مربوطه باید فرآیند پرداخت را انجام بدهد.
در صورتی که فرآیند پرداخت موفق بود برای
شما پیام ارسال می شود که فرآیند مشاوره را
آغاز کنید. ";
		}
		else
		{
			$text .= " {$errorfake} مشاوره اورژانسی با
موضوع {$topic} توسط {$current_user_name} درخواست شده
است.
          ترتیب پیشنهاد مشاور به مراجعه کننده
بر اساس  ترتیب پذیرفتن این مراجعه کننده
است. 15 دقیقه برای پذیرفتن این مراجعه
کننده وقت است.";
		}


		if (!empty($results))
		{
			$data = [];

			foreach ($results as $result)
			{
				$consultant_user_id = $result->id;
				$data[]             = [
					"chat_id"      => $result->cb_balechatid,
					// "chat_id" => '2048243497',
					// "text" =>
$text.'-'.$result->cb_balechatid,
					"text"         => $text,
					"reply_markup" => [
						"inline_keyboard" => [
							[['text' => "پذیرفتن",
"callback_data" =>
"emergency_accept|{$current_user_id}|{$consultant_user_id}"]]
						]
					]
				];
			}

			$text = <<<EOD
					درخواست اورژانسی جدید
					موضوع: {$topic}
					نام: {$current_user_name}
					شناسه کاربر: {$current_user_id}
					نقش واقعی کاربر: {$usergroups}
					شماره موبایل: {$current_user_phone_number}
					نام کاربری: {$current_user_username}
					EOD;

			if ($sendTo)
			{
				$consultant    = $userDetails[$sendTo];
				$consultantStr = "{$consultant->firstname}
{$consultant->lastname} ({$consultant->cb_mobilenumber})";
				$text          .= "\nمشاور: $consultantStr";
			}

			$data[]   = [
				"chat_id" => '@emergencyreq',
//                "text" => "کاربر با شناسه
{$current_user_id} و نام {$current_user_name} درخواست
اورژانسی ارسال کرد *{$usergroupnames}* نام کاربری
مخاطب: *{$current_user_username}*"
				"text"    => $text
			];
			$filename = __DIR__ . '/log.txt';
			// file_put_contents($filename, "count = " .
print_r(count($data), true) . "\n", FILE_APPEND);
			// file_put_contents($filename, "data = " . print_r($data,
true) . "\n", FILE_APPEND);
//            echo '<pre>';
//            var_dump($data);
//            echo '</pre>';
//            exit();
			$bale_response = self::send_bale_message($data);


			$time = time();

			$cb_user->set('cb_emergency_step', 1);
			$cb_user->set('cb_emergency_topic', $topic);

			return $cb_user->store();
		}

		jfactory::getapplication()->enqueuemessage("در حال حاضر
مشاوری آماده پذیرش درخواست مشاوره در
زمینه <b>{$topic}</b> نیست. لطفا مدتی بعد
تلاش کنید.", 'warning');

	}

	public static function
notifyOtherConsultantsClientChooseSomeoneElse($cb_user,
$selectedConsultant) {
//		$cb_user->set('cb_queue_consultants',
serialize(array('3324', '941', '947'))); //
for test and debug

		$otherConsultants =
unserialize($cb_user->get('cb_queue_consultants',
''));
		$selectedConsKey  = array_search($selectedConsultant,
$otherConsultants);
		if ($selectedConsKey !== false)
		{
			unset($otherConsultants[$selectedConsKey]);
		}

		if ($otherConsultants)
		{
			$message           = <<<EOD
							این مراجعه کننده پلن مشاوره اورژانس
را از یکی از مشاورین دیگر خریداری کرد. شما
می توانید از حالت آمادگی جهت مشاوره خارج
شوید.
							EOD;
			$otherConsultants  = array_map('intval', $otherConsultants);
			$otherConsultantsDetail = self::getUserDetails($otherConsultants,
['user_id', 'cb_balechatid']);
			$data        = array();

			foreach ($otherConsultantsDetail as $key => $consultant)
			{
//				for test and debug
//					$message           = <<<EOD
//							consUserId: {$consultant->user_id}
//							{$cb_user->name}، مشاور دیگه ای رو برای
گرفتن مشاوره انتخاب کردن.
//				            این مراجعه کننده پلن مشاوره
اورژانس را از یکی از مشاورین دیگر خریداری
کرد. شما می توانید از حالت آمادگی جهت
مشاوره خارج شوید.
//							EOD;
				$data[] = [
					"chat_id" => $consultant->cb_balechatid,
					"text"    => $message
				];
			}
			self::send_bale_message($data);
		}
	}
	
	public static function do_step2($do, $cb_user, $selectedConsultant)
	{

		if ($do == 'start')
		{
			self::notifyOtherConsultantsClientChooseSomeoneElse($cb_user,
$selectedConsultant);
			$cb_user->set('cb_emergency_step', 0);
			$cb_user->set('cb_queue_consultants', '');
			$cb_user->set('cb_emergency_topic', '');
			$cb_user->store();

			$start_url =
jfactory::getApplication()->input->get('start_url',
'', 'string');
			header("Location: {$start_url}");
			exit();
		}
		elseif ($do == 'find_next')
		{
			$emergency_consultants =
unserialize($cb_user->get('cb_queue_consultants'));
			array_push($emergency_consultants,
array_shift($emergency_consultants));

			$cb_user->set('cb_queue_consultants',
serialize($emergency_consultants));

			return $cb_user->store();
		}
		else
		{
			$cb_user->set('cb_emergency_step', 0);
			$cb_user->set('cb_queue_consultants', '');
			$cb_user->set('cb_emergency_topic', '');

			return $cb_user->store();
		}
	}

	public static function emergency_consultant($cb_user,
$get_emergency_consultant_from_cbuser_object = null)
	{

		$params         =
JComponentHelper::getParams('com_reservation');
		$category_rules = $params->get('category_rule');
		foreach ($category_rules as $category_rule)
		{
			if ($category_rule->cat_rule == 'eplanrule')
			{
				$emergency_catid = $category_rule->catid;
			}
		}

		if (!$get_emergency_consultant_from_cbuser_object)
		{
			$emergency_consultant_id =
unserialize($cb_user->get('cb_queue_consultants'))[0];
		}
		else
		{
			$emergency_consultant_id = $cb_user->get('id');
		}

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

		$query->select('p.*');
		$query->from($db->quoteName('#__reservation_consultant',
'c'));
		$query->join('INNER',
$db->quoteName('#__reservation_plan', 'p') . '
ON ' . $db->quoteName('c.id') . ' = ' .
$db->quoteName('p.consultantid'));
		$query->where($db->quoteName('c.userid') . '='
. $db->quote($emergency_consultant_id));
		$query->where($db->quoteName('p.catid') . '=' .
$db->quote($emergency_catid));
		$query->where($db->quoteName('p.published') . '=
1');

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

		return [$emergency_consultant_id, $emergency_consultant_plan];
	}

	public static function calc_step($cb_user)
	{
		$emergency_step = $cb_user->get('cb_emergency_step', 0);

		return (int) $emergency_step;
	}

	public static function get_topics($cb_user)
	{
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);

		$query->select('fieldlabel');
		$query->from($db->quoteName('#__comprofiler_fields',
'f'));
		$query->join('INNER',
$db->quoteName('#__comprofiler_field_values', 'fv')
. ' ON ' . $db->quoteName('f.fieldid') . ' =
' . $db->quoteName('fv.fieldid'));
		$query->where($db->quoteName('f.name') . '=' .
$db->quote('cb_userexpertisearea'));

		$db->setQuery($query);
		$results = $db->loadObjectList();

		return $results;
	}

	public static function send_bale_message($data = [])
	{
		$params = json_decode(jpluginhelper::getPlugin('chat',
'send_by_bale')->params);

		$bot_token       = $params->bot_token;
		$getupdates_url  = "https://tapi.bale.ai/bot" . $bot_token .
"/getupdates";
		$sendmessage_url = "https://tapi.bale.ai/bot" . $bot_token .
"/sendMessage";

		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $sendmessage_url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:
application/json'));
		$responses = [];
		foreach ($data as $item)
		{
			curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($item));
			$response = curl_exec($curl);
//          $err = curl_error($curl);
			$responses[] = json_decode($response);
		}

		curl_close($curl);
		return $responses;
	}

	public static function is_time_over_reset_it($cb_user)
	{

//        $emergency_request_time =
(int)$cb_user->get('cb_emergency_request_time', 0);
//        $time = time();
//
//        $offset = 900;
//        if (($emergency_request_time + $offset) >= $time)
//        {
//            $cb_user->set('cb_emergency_step', 0);
//            $cb_user->set('cb_queue_consultants',
'');
//            $cb_user->set('cb_emergency_topic',
'');
//            jfactory::getapplication()->enqueuemessage("جهت
ثبت درخواست مجدد باید 15 دقیقه از درخواست
قبلی شما بگذرد", 'warning');
//            return;
//        }
//        else
//        {
//            $cb_user->set('cb_emergency_request_time',
$time);
//        }
//
//        return $cb_user->store();

		$time                   = time();
		$emergency_request_time =
$cb_user->get('cb_emergency_request_time', time());


		$offset = 900;
		if (($emergency_request_time + $offset) < $time)
		{
			$cb_user->set('cb_emergency_step', 0);
			$cb_user->set('cb_queue_consultants', '');
			$cb_user->set('cb_emergency_topic', '');
			$cb_user->store();

			return true;
		}

		return false;
	}

	public static function getAjax()
	{
		include_once(JPATH_ADMINISTRATOR .
'/components/com_comprofiler/plugin.foundation.php');

		$user            = jfactory::getuser();
		$current_user_id = $user->get('id', 0, 'int');

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

		$emergency_step = $cb_user->get('cb_emergency_step', null);

		if ($emergency_step == 2)
			return true;

		return false;

//        $queue_consultants=
$cb_user->get('cb_queue_consultants', null);
//
//        if (empty($queue_consultants))
//            return false;
//
//        return true;
	}


	public static function consultantsInQueueAjax()
	{
		$app         = jfactory::getapplication();
		$return_data = [];
		include_once(JPATH_ADMINISTRATOR .
'/components/com_comprofiler/plugin.foundation.php');
		$user            = jfactory::getuser();
		$current_user_id = $user->get('id', 0, 'int');

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


		$queue_consultants =
unserialize($cb_user->get('cb_queue_consultants'));


		$consultant_ids = $app->input->get('consultant_ids');
		$to             = $app->input->get('to');
		$from           = $app->input->get('from');
		$direction      = $app->input->get('direction');

		$new_consultant_ids = array_filter($queue_consultants, function ($item)
use ($consultant_ids) {

			if (!in_array($item, $consultant_ids)) return true;

		});
		if (!empty($new_consultant_ids))
		{
			if ($direction == 'right') $to = $from + 1;
			else $to = count($queue_consultants) - 1;

			$new_consultants = [];
			foreach ($queue_consultants as $queue_consultant)
			{

				$cbUserIns       = &CBuser::getInstance((int) $queue_consultant);
				$consultant_user = $cbUserIns->getUserData();

				$res = self::emergency_consultant($consultant_user, true);

				$new_consultants[] = [
					'cb_user'                 => $consultant_user,
					'emergency_plan'          => $res[1],
					'emergency_consultant_id' => $queue_consultant,
				];
			}

			ob_start();
			include(JPATH_SITE .
'/modules/mod_emergencyconsultant/tmpl/carousel.php');
			$carousel = ob_get_contents();
			ob_end_clean();


			$return_data['status']   = true;
			$return_data['carousel'] = $carousel;

			return $return_data;
		}

		$return_data['status'] = false;

		return $return_data;

	}

	public static function getUserDetails(array $userIds, array $colList)
	{
		if (!in_array('user_id', $colList))
		{
			$colList[] = 'user_id';
		}
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select(implode(', ', $colList))
			->from('#__comprofiler')
			->where('user_id IN (' . implode(', ', $userIds)
. ')');
		$db->setQuery($query);
		return $db->loadObjectList('user_id');
	}


}