| Current Path : /var/www/html/dosm_backup/frontend/controllers/ |
| Current File : /var/www/html/dosm_backup/frontend/controllers/ChatController.php.backup |
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Request;
use yii\db\conditions\BetweenColumnsCondition;
use yii\web\Session;
use yii\filters\VerbFilter;
use frontend\models\chat\ChatGreeting;
use frontend\models\chat\ChatCommonWord;
use frontend\models\chat\ChatCommonQuestion;
use frontend\models\chat\ChatQuestion;
use frontend\models\chat\ChatQuestionTag;
use frontend\models\chat\ChatAnswer;
use frontend\models\chat\ChatAnswerBot;
use frontend\models\chat\ChatUser;
use frontend\models\chat\ChatLive;
use frontend\models\chat\ChatConfig;
use frontend\models\chat\ChatSuggestion;
class ChatController extends \yii\web\Controller {
public function behaviors() {
$this->enableCsrfValidation = false;
$session = Yii::$app->session;
if (empty($session->id)) {
if (Yii::$app->request->post('sessionid'))
$session->setId(Yii::$app->request->post('sessionid'));
if (Yii::$app->request->get('sessionid'))
$session->setId(Yii::$app->request->get('sessionid'));
}
// if session is not open, open session
if (!$session->isActive) {
$session->open();
}
return [
'contentNegotiator' => [
'class' => \yii\filters\ContentNegotiator::className(),
'formatParam' => '_format',
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
//Respond API
public function responseChat($data, $type, $status = true) {
$response = array(
'data' => $data,
'type' => $type,
'status' => $status,
'response_date_time' => date('Y-m-d H:i:s')
);
return $response;
}
//Remove common question
public function removeCommonQuestion($str) {
//Remove common question
$commonQuestion = ChatCommonQuestion::find()->all();
$commonQuestionArr = [];
foreach ($commonQuestion as $word) {
$commonQuestionArr[] = $word->common_question_description;
}
$str = preg_replace('/\b(' . implode('|', $commonQuestionArr) . ')\b/', '', $str);
$str = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));
return $str;
}
//Remove common words
public function removeCommonWords($str) {
//Remove common words
$commonWords = ChatCommonWord::find()->all();
$commonWordsArr = [];
foreach ($commonWords as $word) {
$commonWordsArr[] = $word->common_word_description;
}
$str = preg_replace('/\b(' . implode('|', $commonWordsArr) . ')\b/', '', $str);
return $str;
}
//Remove common words & question
public function cleanupWords($str) {
$str = $this->removeCommonWords($str);
$str = $this->removeCommonQuestion($str);
return $str;
}
//Return question when user ask new question
public function getUserQuestion($str) {
$strArr = explode(' ', $str);
$result = "";
$found = false;
foreach ($strArr as $word) {
$commonQuestion = ChatCommonQuestion::find()
->where(['=', 'common_question_description', $word])
->one();
if ($commonQuestion) {
$result = $word;
$found = true;
break;
}
}
return $result;
}
public function getGreeting() {
date_default_timezone_set('Asia/Kuala_Lumpur');
$b = time();
$hour = date("H", $b);
$greetings = ChatGreeting::find()
->where(new BetweenColumnsCondition($hour, 'BETWEEN', 'greeting_time_start', 'greeting_time_end'))
->one();
return $greetings->greeting_description;
}
//Check question or not
public function checkQuestionType($str) {
$sentenceType = "non";
if (strpos($str, "?") > -1)
return "question";
$str = $this->removeCommonWords($str);
$str = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));
$strArr = explode(" ", $str);
foreach ($strArr as $word) {
$checkQuestion = ChatCommonQuestion::find()
->where(['=', 'common_question_description', $word])
->one();
if ($checkQuestion) {
$sentenceType = "question";
break;
}
}
return $sentenceType;
}
//User terminate chat
public function actionUserBye() {
$session = Yii::$app->session;
$chatUser = ChatUser::find()
->where(['=', 'user_id', $session->get('user_id')])
->one();
$chatUser->user_live_active = 0;
$chatUser->update();
if (!isset($_SESSION['user'])) {
return $this->actionGreeting();
}
$finalAnswer = "Terima kasih " . $_SESSION['user'] . " Jumpa lagi...";
//Remove session
$session->remove('user');
$session->remove('user_id');
$session->remove('last_question_id');
$session->remove('update_record');
// close a session
$session->close();
// destroys all data registered to a session.
$session->destroy();
return $this->responseChat($finalAnswer, 'user-bye');
}
//User answer question not in database.
public function actionUserAnswer() {
$checkUserAnswer = ChatAnswer::find()
->where(['=', 'question_tag_id', Yii::$app->request->post('question_tag_id')])
->andWhere(['=', 'user_id', $_SESSION['user_id']])
->one();
if (!$checkUserAnswer) {
$userDetail = new ChatAnswer();
$userDetail->answer_description = Yii::$app->request->post('answer');
$userDetail->user_id = $_SESSION['user_id'];
$userDetail->question_tag_id = Yii::$app->request->post('question_tag_id');
$userDetail->save();
}
$msg = "Terima kasih diatas jawapan anda.";
$finalAnswer = [
'message' => $msg,
'question_tag_id' => 0
];
return $this->responseChat($finalAnswer, 'user-answer');
}
//Start talk to user
public function askUser($str) {
$language = strtoupper(Yii::$app->request->post('language') ? Yii::$app->request->post('language') : 'MY');
if ($language == 'EN') {
$wrongAnswer = ['wrong', 'not correct', 'no'];
$correctAnswer = ['wrong', 'yes', 'greate'];
} else {
$wrongAnswer = ['salah', 'tidak tepat', 'tak', 'tak betul'];
$correctAnswer = ['betul', 'tepat', 'ya'];
}
$found = false;
$correct = false;
foreach ($wrongAnswer as $word) {
if (strpos($str, $word) !== false) {
$found = true;
}
}
//Wrong answered on last question
if ($found) {
//errorMsgBotWrongAnswer
$msg = $this->getErrorMsg('MsgBotWrongAnswer');
$_SESSION['update_record'] = true;
} else {
foreach ($correctAnswer as $word) {
if (strpos($str, $word) !== false) {
$correct = true;
}
}
//User response good!!
if ($correct) {
$msg = "Terima kasih. Ada apa yang boleh saya bantu?";
}
//User might need to update details or just create user conversation
else {
//Update the correct answer
//if($_SESSION['update_record']){
if (Yii::$app->request->post('question_tag_id')) {
$chatAnswer = ChatAnswer::find()
->where(['=', 'question_tag_id', Yii::$app->request->post('question_tag_id')])
->andWhere(['=', 'user_id', $_SESSION['user_id']])
->one();
if (!$chatAnswer) {
$chatAnswer = new ChatAnswer();
$chatAnswer->question_tag_id = Yii::$app->request->post('question_tag_id');
$chatAnswer->user_id = $_SESSION['user_id'];
}
$chatAnswer->answer_description = Yii::$app->request->post('question');
$chatAnswer->save();
//errorMsgUpdateUserDetails
$msg = $this->getErrorMsg('MsgUpdateUserDetails');
$_SESSION['update_record'] = false;
}
//Just create user conversation
else {
//errorMsgBotNoIdea
$msg = $this->getErrorMsg('MsgBotNoIdea');
}
}
}
$finalAnswer = [
'message' => $msg,
'question_tag_id' => 0
];
return $this->responseChat($finalAnswer, 'ask-user-answer');
}
public function getCombinations(&$set, &$results) {
for ($i = 0; $i < count($set); $i++) {
$results[] = $set[$i];
$tempset = $set;
array_splice($tempset, $i, 1);
$tempresults = array();
$this->getCombinations($tempset, $tempresults);
foreach ($tempresults as $res) {
$results[] = trim($set[$i] . " " . $res);
}
}
}
public function getStringCombination($str) {
$words = explode(" ", $str);
$wordsArr = [];
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
for ($j = $i; $j < $num_words; $j++) {
for ($k = $i; $k <= $j; $k++) {
$wordsArr[] = $words[$k] . " ";
}
}
}
return $wordsArr;
}
public function getSuggestion() {
$suggestion = ChatSuggestion::find()
->where(['=', 'suggestion_status', 'A'])->all();
$suggestionArr = [];
foreach ($suggestion as $r) {
$suggestionArr[] = array(
'id' => $r->suggestion_id,
'description' => $r->suggestion_description,
);
}
return $suggestionArr;
}
//User start questioning
public function actionQuestion() {
$status = true;
$self = false;
$sentenceType = 'non';
$answerFound = false;
$language = strtoupper(Yii::$app->request->post('language') ? Yii::$app->request->post('language') : 'MY');
if (!isset($_SESSION['user'])) {
return $this->actionGreeting();
}
if (Yii::$app->request->post('question') == "") {
$finalAnswer = "Maaf, saya tidak menerima sebarang pertanyaan dari anda. Sila cuba lagi";
return $this->responseChat($finalAnswer, 'answer', false);
}
$question = Yii::$app->request->post('question');
//Check sentence is question or not
//$sentenceType = $this->checkQuestionType($question);
//if($sentenceType == 'non'){
if (Yii::$app->request->post('question_tag_id')) {
return $this->askUser($question);
}
//$question = preg_replace('/[^\p{L}\p{N}\s]/u', '', $question);
//$question = $this->cleanupWords($question);
//$questionAbc = explode(" ", $question);
$questionWordArr = str_word_count($question, 2);
$questionArr = [];
foreach ($questionWordArr as $f) {
$questionArr[] = $f;
}
$found = false;
//Check user ask name
if (count($questionArr) == 1) {
if ($language == 'EN')
$userSelf = ['am', 'i', 'name'];
else
$userSelf = ['kenal', 'nama', 'siapa', ''];
foreach ($questionArr as $q) {
if (in_array($q, $userSelf)) {
$found = true;
$self = true;
break;
}
}
$questionTagId = 0;
}
//Check question about user details
$questionSelf = Yii::$app->request->post('question');
$questionSelfArr = str_word_count($questionSelf, 2);
/*
if($language == 'EN')
$selfArr = ['my', 'me', $_SESSION['user']];
else
$selfArr = ['saya', 'aku', $_SESSION['user']];
foreach($selfArr as $word){
if (in_array($word, $questionSelfArr)) {
$self = true;
}
}
*/
//Find Other Question Tag
if ($found == false) {
$this->getCombinations($questionArr, $testCombination);
$questionTag = ChatQuestionTag::find()
->join('INNER JOIN', 'chat_answer_bot', 'chat_answer_bot.question_tag_id = chat_question_tag.question_tag_id');
foreach ($testCombination as $q) {
$questionTag = $questionTag->orWhere(['=', 'question_tag_name', $q]);
}
if ($self) {
$questionTag = $questionTag->orWhere(['=', 'question_tag_name', implode(' ', $questionArr) . " saya"]);
} else {
$questionTag = $questionTag->orWhere(['=', 'question_tag_name', implode(' ', $questionArr)]);
}
//$questionTag->andWhere(['=', 'question_tag_language', $language]);
$questionTag->orderBy('question_tag_name DESC');
$questionTag = $questionTag->one();
if ($questionTag) {
$questionTagId = $questionTag->question_tag_id;
$found = true;
}
}
if ($found) {
$checkAnswerBot = ChatAnswerBot::find()
->where(['=', 'question_tag_id', $questionTag->question_tag_id])
->one();
$answerFound = true;
}
//Question found in database
if ($found && $answerFound) {
//Find Answer
$answer = ChatAnswer::find()
->where(['=', 'question_tag_id', $questionTagId])
->andWhere(['=', 'user_id', $_SESSION['user_id']])
->one();
//Return Answer
switch ($questionTagId) {
case 0:
//errorMsgKnowYou
$msg = $this->getErrorMsg('MsgKnowYou', $_SESSION['user']);
$finalAnswer = array(
'message' => $msg,
'question_tag_id' => 0
);
break;
default:
if ($answer) {
//errorMsgAnswerKnowYou
$msg = $this->getErrorMsg('MsgAnswerKnowYou', $answer->answer_description);
$finalAnswer = array(
'message' => $msg,
'question_tag_id' => 0
);
} else {
//Refer Bot Answer
if (!$self) {
$checkAnswerBot = ChatAnswerBot::find()
->where(['=', 'question_tag_id', $questionTag->question_tag_id])
->one();
if ($checkAnswerBot) {
$suggestion_status = false;
if ($checkAnswerBot->answer_bot_suggestion_description != "" && $checkAnswerBot->answer_bot_suggestion_description != null) {
$suggestion = array(
'suggestion_id' => 0,
'suggestion_description' => $checkAnswerBot->answer_bot_suggestion_description
);
} else {
$suggestion = $this->getSuggestion();
}
if ($suggestion) {
$suggestion_status = true;
}
$finalAnswer = array(
'message' => $checkAnswerBot->answer_bot_description,
'suggestion_status' => $suggestion_status,
'suggestion' => $suggestion,
'question_tag_id' => 0
);
} else {
//errorMsgNewQuestion
$msg = $this->getErrorMsg('MsgNoAnswer');
$questionTagId = 0;
$finalAnswer = array(
'message' => $msg,
'question_tag_id' => 0
);
}
}
//Ask User Back
else {
$userQuestion = $this->getUserQuestion(Yii::$app->request->post('question'));
$param = [
'userQuestion' => $userQuestion,
'questionTag' => $questionTag
];
//errorMsgAnswerKnowYou
$msg = $this->getErrorMsg('MsgQuestionUser', $param);
$finalAnswer = array(
'message' => $msg,
'question_tag_id' => $questionTag->question_tag_id
);
}
}
break;
}
$_SESSION['last_question_id'] = $questionTagId;
$_SESSION['update_record'] = false;
}
//New question
else {
//errorMsgNewQuestion
$msg = $this->getErrorMsg('MsgNewQuestion');
$questionTagId = 0;
//Check Question
$checkQuestion = ChatQuestion::find()
->where(['=', 'question_description', Yii::$app->request->post('question')])
->one();
//Question not exists
if (!$checkQuestion) {
//Add Question
$chatQuestion = new ChatQuestion();
$chatQuestion->question_description = Yii::$app->request->post('question');
$chatQuestion->user_id = $_SESSION['user_id'];
$chatQuestion->question_language = $language;
$chatQuestion->save();
}
//Add Question Tag
if ($self) {
/*
$chatQuestionTag = new ChatQuestionTag();
$chatQuestionTag->question_tag_name = implode(' ', $questionArr) . " saya";
$chatQuestionTag->question_tag_language = $language;
$chatQuestionTag->save(false);
$questionTagId = $chatQuestionTag->question_tag_id;
*/
}
$finalAnswer = array(
'message' => $msg,
'question_tag_id' => $questionTagId
);
$status = false;
}
return $this->responseChat($finalAnswer, 'answer', $status);
}
public function getErrorMsg($error, $param = null) {
$language = strtoupper(Yii::$app->request->post('language') ? Yii::$app->request->post('language') : 'MY');
switch ($error) {
case 'MsgNoAnswer':
if ($language == 'EN') {
$msg = "Sorry, I don't have answer for your question. We will answer your question in future. Thank you.";
} else {
$msg = "Maaf, tiada jawapan untuk soalan anda. Kami akan berusaha mendapatkan jawapan untuk anda. Anda boleh cuba bertanya soalan yang sama pada masa yang akan datang.";
}
break;
case 'MsgNewQuestion':
if ($language == 'EN') {
$msg = "Sorry, I don't have answer for your question. Your question has been log into our record. We will answer your question in future. Thank you.";
} else {
//$msg = "Maaf, tiada jawapan untuk soalan anda. Soalan anda telahpun dilog ke dalam pengkalan data. Kami akan berusaha mendapatkan jawapan untuk anda. Anda boleh cuba bertanya soalan yang sama pada masa yang akan datang.";
$msg = "Maaf, saya tidak begitu memahami pertanyaan anda. Sila susun semula ayat yang digunakan. Hubungi meja bantuan di talian +603-8000 8000 untuk bantuan lanjut";
}
break;
case 'MsgKnowYou':
if ($language == 'EN') {
$msg = "You " . $param . ". Is there anything that I can help you?";
} else {
$msg = "Awak " . $param . ".Ada apa yang boleh saya bantu?";
}
break;
case 'MsgAnswerKnowYou':
if ($language == 'EN') {
$msg = "Hmmm..... " . $param . ". Is there anything that I can help you?";
} else {
$msg = "Hmmm..... " . $param . ".Ada apa yang boleh saya bantu?";
}
break;
case 'MsgQuestionUser':
if ($language == 'EN') {
$msg = 'Sorry, ' . $param['userQuestion'] . ' ' . str_replace("my", "is your", $param['questionTag']->question_tag_name) . '? Please let me know.';
} else {
$msg = 'Maaf, ' . $param['userQuestion'] . ' ' . str_replace("saya", "anda", $param['questionTag']->question_tag_name) . '? Sila masukkan jawapan.';
}
break;
case 'MsgUpdateUserDetails':
if ($language == 'EN') {
$msg = "Thank you. Is there anything that I can help you?";
} else {
$msg = "Maklumat berjaya dikemaskini. Ada apa yang boleh saya bantu?";
}
break;
case 'MsgBotNoIdea':
if ($language == 'EN')
$msg = "Sorry, I don't understand your question. Please try again.";
else
$msg = "Maaf, saya tidak memahami soalan anda. Sila masukkan soalan yang tepat dan cuba sekali lagi";
break;
case 'MsgBotWrongAnswer':
if ($language == 'EN')
$msg = "Sorry for giving wrong info, please update me the correct details.";
else
$msg = "Maaf kerana memberi maklumat yang tidak tepat, sila masukkan jawapan yang tepat untuk dikemaskini?";
break;
}
return $msg;
}
public function insertLiveChat() {
$chat = new ChatLive();
$chat->live_message = Yii::$app->request->post("chat");
if (Yii::$app->request->post("live_session")) {
$chat->live_session = Yii::$app->request->post("live_session");
$chat->admin_id = Yii::$app->request->post("admin_id");
$chat->user_id = 0;
} else {
$chat->live_session = $_SESSION['live_session'];
$chat->user_id = $_SESSION['user_id'];
}
$chat->save();
$user = ChatUser::find()
->where(['=', 'user_id', $chat->user_id])
->one();
$user->live_message_last = Yii::$app->request->post("chat");
$user->save();
return $chat->live_id;
}
public function checkChatLive() {
$model = ChatConfig::find()->one();
$status = true;
$message = "";
if ($model->config_status == 0) {
$status = false;
$message = $model->config_message;
} else {
date_default_timezone_set('Asia/Kuala_Lumpur');
$b = time();
$hour = date("H:m:s", $b);
$checkTime = ChatConfig::find()
->where(new BetweenColumnsCondition($hour, 'BETWEEN', 'config_start_time', 'config_end_time'))
->one();
if (!$checkTime) {
$message = "Live chat beroperasi dari " . $model->config_start_time . " hingga " . $model->config_end_time . " . Harap maaaf";
$status = false;
}
}
$response = [
'status' => $status,
'message' => $message
];
return $response;
}
public function actionLiveChatInit() {
$checking = $this->checkChatLive();
if ($checking['status'] == false) {
return $this->responseChat($checking['message'], 'live-chat-init', $checking['status']);
}
$_SESSION['last_live_id'] = 0;
$chatUser = ChatUser::find()
->where(['=', 'user_id', $_SESSION['user_id']])
->one();
$chatUser->user_live_active = 1;
$chatUser->update();
return $this->responseChat('Live chat init..', 'live-chat-init');
}
public function actionLiveChat() {
$checking = $this->checkChatLive();
if ($checking['status'] == false) {
return $this->responseChat($checking['message'], 'live-chat', $checking['status']);
}
if (!isset($_SESSION['last_live_id']) && !Yii::$app->request->post("live_session")) {
return $this->actionGreeting();
}
if (!isset($_SESSION['last_live_id'])) {
$_SESSION['last_live_id'] = 0;
}
$lastId = $_SESSION['last_live_id'];
$excludeLiveId = 0;
$liveSession = "";
//Operator
if (Yii::$app->request->post("live_session")) {
$liveSession = Yii::$app->request->post("live_session");
$condition = ['and',
['=', 'live_session', $liveSession]
];
ChatLive::updateAll(['live_read_status' => 1], $condition);
}
//Normal User
else {
$liveSession = $_SESSION['live_session'];
}
if (Yii::$app->request->post("chat") && Yii::$app->request->post("chat") != null) {
$excludeLiveId = $this->insertLiveChat();
}
$rows = (new \yii\db\Query())
->select(['chat_live.live_id', 'chat_live.live_message', 'chat_live.create_dttm', 'IF(chat_live.admin_id <> 0, dmg_user_info.staff_name, chat_user.user_name) as user_name', 'chat_live.admin_id', 'chat_live.admin_id as icon'])
->from('chat_live')
->join('INNER JOIN', 'chat_user', 'chat_user.user_id = chat_live.user_id')
->join('LEFT JOIN', 'dmg_user_info', 'dmg_user_info.userid = chat_live.admin_id')
->where(['live_session' => $liveSession])
->andWhere(['>', 'live_id', $lastId]);
if ($excludeLiveId != 0) {
$rows = $rows->andWhere(['<>', 'live_id', $excludeLiveId]);
}
$rows = $rows->orderBy([
'create_dttm' => SORT_ASC
])->all();
if ($rows) {
foreach ($rows as &$r) {
if (file_exists("/www/admin/images/profile_pic/" . $r['admin_id'] . '.jpg'))
$img = "/www/admin/images/profile_pic/" . $r['admin_id'] . '.jpg';
else
$img = "/www/admin/images/user_icon.png";
$r['icon'] = $img;
$lastId = $r['live_id'];
}
} else {
$rows = [];
}
if ($excludeLiveId != 0)
$_SESSION['last_live_id'] = $excludeLiveId;
else
$_SESSION['last_live_id'] = $lastId;
return $this->responseChat($rows, 'live-chat');
}
//Init session
public function actionGreetingName() {
$session = Yii::$app->session;
$chatUser = ChatUser::find()
->where(['=', 'user_phone', Yii::$app->request->post("userphone")])
->andWhere(['=', 'user_email', Yii::$app->request->post("useremail")])
->one();
if (!$chatUser) {
$chatUser = new ChatUser();
$chatUser->user_name = Yii::$app->request->post("username");
$chatUser->user_phone = Yii::$app->request->post("userphone");
$chatUser->user_email = Yii::$app->request->post("useremail");
$chatUser->save();
}
if (!$session->has('user')) {
$_SESSION['user'] = Yii::$app->request->post("username");
$_SESSION['user_id'] = $chatUser->user_id;
$_SESSION['last_question_id'] = 0;
$_SESSION['update_record'] = false;
$_SESSION['live_session'] = Yii::$app->session->getId();
}
$msg = $this->getGreeting();
$msg .= " " . $_SESSION['user'] . " .Boleh saya bantu?";
$data = [
'message' => $msg,
'sessionid' => $_SESSION['live_session']
];
return $this->responseChat($data, 'greeting-name');
}
//Init greetings
public function actionGreeting() {
$greeting_description = $this->getGreeting();
return $this->responseChat($greeting_description, 'greeting');
}
public function actionIndex() {
}
}