Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.34 KB | None | 0 0
  1. <?php
  2. /**
  3. * API VK
  4. * @author k011E (Александр Каплин)
  5. */
  6. class API
  7. {
  8.     public $tocken;
  9.     public $secret_code;
  10.     public $confirmation_code;
  11.     public $data;
  12.     public $tocken_app = '089d42df638b4966278e37cae6d0fd0a30009ff9ec1e90bd4cb993f682d25163c1bd1144e7214038ab332';
  13.     public $group_id;
  14.  
  15.     function defaultGenarateQuest(){
  16.             global $db;
  17.             $num = $db->query("SELECT * FROM `quests`")->num_rows;
  18.             $rnd = rand(1, $num);
  19.             $quest = $db->query("SELECT * FROM `quests` WHERE `id`='".$rnd."'")->fetch_assoc();
  20.  
  21.             // Кнопки
  22.             $button1 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '1')), 'label' => '1'), 'color' => 'positive');
  23.             $button2 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '2')), 'label' => '2'), 'color' => 'positive');
  24.             $button3 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '3')), 'label' => '3'), 'color' => 'positive');
  25.             $button4 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '4')), 'label' => '4'), 'color' => 'positive');
  26.             $button2_1 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => 'start_exam')), 'label' => "Начать экзамен"), 'color' => 'primary');
  27.            
  28.             // Клавиатуры
  29.             $array = array($button1, $button2, $button3, $button4);
  30.             $array2 = array($button2_1);
  31.  
  32.             $generate_message = 'Вопрос: '.$quest['name'].'
  33.  
  34.             Варианты ответов:
  35.             1. '.$quest['answer1'].'
  36.             2. '.$quest['answer2'];
  37.             if(!empty($quest['answer3'])){
  38.                 $generate_message .= '
  39.                 3. '.$quest['answer3'];
  40.             }
  41.             if(!empty($quest['answer4'])){
  42.                 $generate_message .= '
  43.                 4. '.$quest['answer4'];
  44.             }
  45.            
  46.             $this->sendKeyboard($generate_message, $array, $array2, $this->attachImage($quest['img']));
  47.             $this->updateUser($quest['id']);
  48.     }
  49.  
  50.     function __construct($tocken, $secret_code, $confirmation_code, $group_id, $data)
  51.     {
  52.         $this->tocken = $tocken;
  53.         $this->secret_code = $secret_code;
  54.         $this->confirmation_code = $confirmation_code;
  55.         $this->data = $data;
  56.         $this->group_id = $group_id;
  57.     }
  58.  
  59.     function getType(){
  60.         return $this->data->type;
  61.     }
  62.  
  63.     function getPayload(){
  64.         $string = json_decode($this->data->object->payload, true);
  65.         return $string["button"];
  66.     }
  67.  
  68.     // Проверка paylaod на начало экзамена
  69.     function isStartExam(){
  70.         if($this->getPayload() == "start_exam"){
  71.             return true;
  72.         }else{
  73.             return false;
  74.         }
  75.     }
  76.  
  77.     function isStopExam(){
  78.         if($this->getPayload() == "stop_exam"){
  79.             return true;
  80.         }else{
  81.             return false;
  82.         }
  83.     }
  84.  
  85.     // Функция иницилизирующая старт экзамена
  86.     function startExam(){
  87.         global $db;
  88.         $ticket = $db->query("SELECT * FROM `ticket` ORDER BY RAND() LIMIT 1")->fetch_assoc();
  89.         $db->query("INSERT INTO `session_exams` SET `id_user`='".$this->data->object->user_id."', `time_start`='".time()."', `time_end`='".(time() + 1200)."', `ticket`='".$ticket['id']."', `step`='1'");
  90.         $this->sendMessage("Экзамен начат!");
  91.     }
  92.  
  93.     function stopExam(){
  94.         global $db;
  95.         $session = $this->getSessionUser();
  96.         $this->sendMessage("Вы отменили экзамен. Отвечено на ".$session['step']." вопросов. Ошибок: ".$session['errors']);
  97.         $db->query("DELETE FROM `session_exams` WHERE `id`='".$session['id']."'");
  98.     }
  99.  
  100.  
  101.     // Функция проверки существует ли начатый экзамен
  102.     function isHaveStartedExam(){
  103.         global $db;
  104.         if($db->query("SELECT `id` FROM `session_exams` WHERE `id_user`='".$this->data->object->user_id."'")->num_rows!=0){
  105.             return true;
  106.         }else{
  107.             return false;
  108.         }
  109.     }
  110.  
  111.     // Функция генерации вопроса
  112.     function generateQuest(){
  113.         global $db;
  114.  
  115.         $session = $this->getSessionUser();
  116.         $quest = $db->query("SELECT * FROM `quests` WHERE `ticket`='".$session['ticket']."' AND `number`='".$session['step']."'")->fetch_assoc();
  117.         $generate_message = 'Времени осталось: '.$this->getTime(time(), $session['time_end']).'
  118.  
  119.         Вопрос: '.$quest['name'].'
  120.  
  121.             Варианты ответов:
  122.             1. '.$quest['answer1'].'
  123.             2. '.$quest['answer2'];
  124.             if(!empty($quest['answer3'])){
  125.                 $generate_message .= '
  126.                 3. '.$quest['answer3'];
  127.             }
  128.             if(!empty($quest['answer4'])){
  129.                 $generate_message .= '
  130.                 4. '.$quest['answer4'];
  131.             }
  132.         return $generate_message;
  133.     }
  134.  
  135.     function sendQuest(){
  136.         global $db;
  137.  
  138.         $button1 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '1')), 'label' => '1'), 'color' => 'positive');
  139.         $button2 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '2')), 'label' => '2'), 'color' => 'positive');
  140.         $button3 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '3')), 'label' => '3'), 'color' => 'positive');
  141.         $button4 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => '4')), 'label' => '4'), 'color' => 'positive');
  142.         $button2_1 = array('action' => array('type' => 'text', 'payload' => json_encode(array('button' => 'stop_exam')), 'label' => "Закончить экзамен"), 'color' => 'negative');
  143.            
  144.         // Клавиатуры
  145.         $array = array($button1, $button2, $button3, $button4);
  146.         $array2 = array($button2_1);
  147.         $session = $this->getSessionUser();
  148.         $quest = $db->query("SELECT * FROM `quests` WHERE `ticket`='".$session['ticket']."' AND `number`='".$session['step']."'")->fetch_assoc();
  149.         $this->sendKeyboard($this->generateQuest(), $array, $array2, $this->attachImage($quest['img']));
  150.     }
  151.  
  152.     function checkEndExam(){
  153.         global $db;
  154.  
  155.         $session = $this->getSessionUser();
  156.  
  157.         if($session['time_end'] <= time()){
  158.             $this->sendMessage("Время вышло. Количество ошибок: ".$session['errors']);
  159.             $db->query("DELETE FROM `session_exams` WHERE `id`='".$session['id']."'");
  160.             if($session['errors'] > 2 AND $session['step'] < 20){
  161.                 $this->sendMessage("Вы не сдали экзамен. Попробуйте ещё раз.");
  162.             }else{
  163.                 $this->sendMessage("Вы успешно сдали экзамен!");
  164.             }
  165.         }
  166.        
  167.  
  168.     }
  169.  
  170.     function checkAnswerExam(){
  171.         global $db;
  172.  
  173.         $session = $this->getSessionUser();
  174.         $quest = $db->query("SELECT * FROM `quests` WHERE `ticket`='".$session['ticket']."' AND `number`='".$session['step']."'")->fetch_assoc();
  175.         if($this->data->object->body == $quest['correct']){
  176.            
  177.         }else{
  178.             $this->sendMessage('Вы ответили неправильно!
  179.                 Комментарий:
  180.                 '.$quest['explanation']);
  181.             $db->query("UPDATE `session_exams` SET `errors`=`errors`+1 WHERE `id`='".$session['id']."'");
  182.         }
  183.         $db->query("UPDATE `session_exams` SET `step`=`step`+1 WHERE `id`='".$session['id']."'");
  184.     }
  185.  
  186.     function getTime($start, $end){
  187.         $time = $end - $start;
  188.         $m = intval($time / 60);
  189.         $s = $time - $m * 60;
  190.         return $m.":".$s;
  191.     }
  192.  
  193.     function attachImage($image){
  194.         $uploadServer = $this->getMessagesUploadServer();
  195.         $link = $uploadServer->response->upload_url;
  196.         $img_path  = dirname(__FILE__).'/image/'.$image.'.jpg';
  197.         $cfile = curl_file_create($img_path,'image/jpeg',$image.'.jpg');
  198.         $curl=curl_init();
  199.         curl_setopt_array($curl, array(
  200.             CURLOPT_POST => true,
  201.             CURLOPT_RETURNTRANSFER => TRUE,
  202.             CURLOPT_URL => $link,
  203.             CURLOPT_POSTFIELDS => array("photo" => $cfile)
  204.         ));
  205.         $resul_arr = json_decode(curl_exec($curl));
  206.         curl_close($curl);
  207.         $resul_photo = stripslashes($resul_arr->photo);
  208.         $ph = $this->saveMessagesPhoto($resul_photo, $resul_arr->server, $resul_arr->hash);
  209.         if(isset($ph->error)){
  210.             //$VK->sendMessage($ph->error->error_msg.'///'.$resul_arr->server);
  211.         }
  212.         return 'photo'.$ph->response[0]->owner_id.'_'.$ph->response[0]->id;
  213.     }
  214.  
  215.     function getSessionUser(){
  216.         global $db;
  217.  
  218.         return $db->query("SELECT * FROM `session_exams` WHERE `id_user`='".$this->data->object->user_id."'")->fetch_assoc();
  219.     }
  220.  
  221.     function getConfirmationCode(){
  222.         return $this->confirmation_code;
  223.     }
  224.  
  225.     function checkSubscribe(){
  226.         $sub = json_decode(file_get_contents("https://api.vk.com/method/groups.isMember?group_id=".$this->group_id."&user_id=".$this->data->object->user_id."&v=5.0&extended=1&access_token=".$this->tocken));
  227.         if($sub->response->member == 0){
  228.             return false;
  229.         }else{
  230.             return true;
  231.         }
  232.     }
  233.  
  234.     function sendMessage($text, $attachment = NULL, $keyboard = NULL){
  235.         $request_params = array(
  236.           'message' => $text,
  237.           'user_id' => $this->data->object->user_id,
  238.           'access_token' => $this->tocken,
  239.           'v' => '5.0',
  240.           'attachment' => $attachment,
  241.           'keyboard' => $keyboard
  242.         );
  243.         $get_params = http_build_query($request_params);
  244.         file_get_contents('https://api.vk.com/method/messages.send?'. $get_params);
  245.     }
  246.  
  247.     function sendKeyboard($message, $buttons, $buttons2 = NULL, $attachment = NULL){
  248.         $key = $this->generateKeyboard($buttons, $buttons2);
  249.         $request_params = array(
  250.           'message' => $message,
  251.           'user_id' => $this->data->object->user_id,
  252.           'access_token' => $this->tocken,
  253.           'v' => '5.80',
  254.           'keyboard' => $key,
  255.           'attachment' => $attachment
  256.         );
  257.         $get_params = http_build_query($request_params);
  258.         file_get_contents('https://api.vk.com/method/messages.send?'. $get_params);
  259.     }
  260.  
  261.     function generateKeyboard($buttons, $buttons2 = NULL){
  262.         $array = array('one_time' => false, 'buttons' => array($buttons, $buttons2));
  263.         return json_encode($array, JSON_UNESCAPED_UNICODE);
  264.     }
  265.  
  266.     function getMessagesUploadServer(){
  267.         $get = json_decode(file_get_contents('https://api.vk.com/method/photos.getMessagesUploadServer?access_token='.$this->tocken.'&v=5.69'));
  268.         return $get;
  269.     }
  270.  
  271.     function saveMessagesPhoto($photo, $server, $hash){
  272.         $params = array('photo' => $photo,
  273.             'server' => $server,
  274.             'hash' => $hash,
  275.             'access_token' => $this->tocken,
  276.             'v' => '5.67');
  277.         $get_params = http_build_query($params);
  278.         $photo = json_decode(file_get_contents('https://api.vk.com/method/photos.saveMessagesPhoto?'.$get_params));
  279.         return $photo;
  280.     }
  281.  
  282.     function getBody(){
  283.         return $this->data->object->body;
  284.     }
  285.  
  286.     function isAttachement(){
  287.         if(isset($this->data->object->attachments[0]->type)){
  288.             return true;
  289.         }else{
  290.             return false;
  291.         }
  292.     }
  293.  
  294.     function updateUser($quest){
  295.         global $db;
  296.         if(!$this->isUser()){
  297.             $db->query("INSERT INTO `users` SET `id_user`='".$this->data->object->user_id."', `id_quest`='".$quest."'");
  298.         }else{
  299.             $db->query("UPDATE `users` SET `id_quest`='".$quest."' WHERE `id_user`='".$this->data->object->user_id."'");
  300.         }
  301.     }
  302.  
  303.     function isUser(){
  304.         global $db;
  305.         if($db->query("SELECT `id` FROM `users` WHERE `id_user`='".$this->data->object->user_id."'")->num_rows!=0){
  306.             return true;
  307.         }else{
  308.             return false;
  309.         }
  310.     }
  311.  
  312.     function checkAnswer(){
  313.         global $db;
  314.         $user = $db->query("SELECT * FROM `users` WHERE `id_user`='".$this->data->object->user_id."'")->fetch_assoc();
  315.         $quest = $db->query("SELECT * FROM `quests` WHERE `id`='".$user['id_quest']."'")->fetch_assoc();
  316.         if($this->data->object->body == $quest['correct']){
  317.             $this->sendMessage('Вы ответили правильно!');
  318.         }else{
  319.             $this->sendMessage('Вы ответили неправильно!
  320.                 Комментарий:
  321.                 '.$quest['explanation']);
  322.         }
  323.     }
  324.  
  325.  
  326. }
  327. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement