· 8 years ago · Jul 26, 2018, 04:56 PM
1<?php
2/*
3Addon Name: Bot Inboxer
4Unique Name: messenger_bot
5Module ID: 200
6Project ID: 3
7Addon URI: http://getfbinboxer.com
8Author: Xerone IT
9Author URI: http://xeroneit.net
10Version: 2.4.4
11Description: Facebook messenger chat bot.
12*/
13require_once("application/controllers/Home.php"); // loading home controller
14class Messenger_bot extends Home
15{
16 public $addon_data=array();
17 public function __construct()
18 {
19 parent::__construct();
20 $this->load->config('messenger_bot_config');// config
21 // getting addon information in array and storing to public variable
22 // addon_name,unique_name,module_id,addon_uri,author,author_uri,version,description,controller_name,installed
23 //------------------------------------------------------------------------------------------
24 $addon_path=APPPATH."modules/".strtolower($this->router->fetch_class())."/controllers/".ucfirst($this->router->fetch_class()).".php"; // path of addon controller
25 $addondata=$this->get_addon_data($addon_path);
26 $this->addon_data=$addondata;
27 $this->user_id=$this->session->userdata('user_id'); // user_id of logged in user, we may need it
28 $function_name=$this->uri->segment(2);
29 if($function_name!="webhook_callback" && $function_name!="send_reply_curl_call" && $function_name!="download_profile_pic")
30 {
31 // all addon must be login protected
32 //------------------------------------------------------------------------------------------
33 if ($this->session->userdata('logged_in')!= 1) redirect('home/login', 'location');
34 // if you want the addon to be accessed by admin and member who has permission to this addon
35 //-------------------------------------------------------------------------------------------
36 if(isset($addondata['module_id']) && is_numeric($addondata['module_id']) && $addondata['module_id']>0)
37 {
38 if($this->session->userdata('user_type') != 'Admin' && !in_array($addondata['module_id'],$this->module_access))
39 {
40 redirect('home/login_page', 'location');
41 exit();
42 }
43 }
44 }
45 }
46 public function create_subscriber($sender_id='', $page_id='')
47 {
48 $table = "messenger_bot_subscriber";
49 $where = array('messenger_bot_subscriber.subscribe_id' => $sender_id);
50 $is_exist = $this->basic->is_exist($table,$where);
51
52 $response=array();
53 $response['is_new']=FALSE;
54
55 if(!$is_exist){
56
57 $response['is_new']=TRUE;
58 $table = "messenger_bot_page_info";
59 $where['where'] = array('page_id' => $page_id);
60 $page_access_token_array = $this->basic->get_data($table,$where,"page_access_token,user_id");
61 $page_access_token = $page_access_token_array[0]['page_access_token'];
62 $user_id = $page_access_token_array[0]['user_id'];
63 $user_data = $this->subscriber_info($page_access_token,$sender_id);
64 $data = array(
65 'user_id' => $user_id,
66 'page_id' => $page_id,
67 'subscribe_id' => $sender_id,
68 'first_name' => $user_data['first_name'],
69 'last_name' => $user_data['last_name'],
70 'profile_pic' => $user_data['profile_pic'],
71 'locale' => $user_data['locale'],
72 'timezone' => $user_data['timezone'],
73 'gender' => $user_data['gender'],
74 'subscribed_at' => date('Y-m-d H:i:s')
75 );
76 if($this->basic->insert_data('messenger_bot_subscriber',$data)){
77 return $response;
78 }else{
79 return $response;
80 }
81 }
82
83 return $response;
84 }
85 public function send_reply($access_token='',$reply='')
86 {
87 $url="https://graph.facebook.com/v2.6/me/messages?access_token=$access_token";
88 $ch = curl_init();
89 $headers = array("Content-type: application/json");
90 curl_setopt($ch, CURLOPT_URL, $url);
91 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
92
93 curl_setopt($ch,CURLOPT_POST,1);
94 curl_setopt($ch,CURLOPT_POSTFIELDS,$reply);
95
96 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
97 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
98 curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
99 curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');
100 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
101 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
102 $st=curl_exec($ch);
103
104 $result=json_decode($st,TRUE);
105 return $result;
106 }
107 public function send_reply_curl_call(){
108 ignore_user_abort(TRUE);
109 $access_token=$_POST['access_token'];
110 $reply=$_POST['reply'];
111
112 $url="https://graph.facebook.com/v2.6/me/messages?access_token=$access_token";
113 $ch = curl_init();
114 $headers = array("Content-type: application/json");
115 curl_setopt($ch, CURLOPT_URL, $url);
116 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
117
118 curl_setopt($ch,CURLOPT_POST,1);
119 curl_setopt($ch,CURLOPT_POSTFIELDS,$reply);
120
121 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
122 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
123 curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
124 curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');
125 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
126 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"); $st=curl_exec($ch);
127
128 $result=json_decode($st,TRUE);
129 return $result;
130 }
131
132 /**Sender action added 19.03.2018 by Konok**/
133
134 public function sender_action($sender_id,$action_type,$post_access_token='')
135 {
136
137 $url = "https://graph.facebook.com/v2.6/me/messages?access_token={$post_access_token}";
138
139 $post_data_array['recipient']['id']=$sender_id;
140 $post_data_array['sender_action']=$action_type;
141 $post_data=json_encode($post_data_array);
142 $ch = curl_init();
143 $headers = array("Content-type: application/json");
144 curl_setopt($ch, CURLOPT_URL, $url);
145 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
146 curl_setopt($ch,CURLOPT_POST,1);
147 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
148 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
149 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
150 curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
151 curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');
152 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
153 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
154 $st=curl_exec($ch);
155 $result=json_decode($st,TRUE);
156 return $result;
157 }
158 public function is_email($email)
159 {
160 $email=trim($email);
161 $is_valid=0;
162 /***Validation check***/
163 $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
164 if (preg_match($pattern, $email) === 1) {
165 $is_valid=1;
166 }
167 return $is_valid;
168 }
169 public function is_phone_number($phone)
170 {
171 $is_valid=0;
172 if(preg_match("#\+\d{7}#",$phone)===1)
173 $is_valid=1;
174
175 return $is_valid;
176
177 }
178
179 public function webhook_callback()
180 {
181 $challenge = $this->input->get_post('hub_challenge');
182 $verify_token =$this->input->get_post('hub_verify_token');
183 if($verify_token === $this->config->item("webhook_verify_token"))
184 {
185 echo $challenge;
186 die();
187 }
188 $currenTime=date("Y-m-d H:i:s");
189 $response_raw=file_get_contents("php://input");
190
191 /*file_put_contents("fb.txt",$response_raw, FILE_APPEND | LOCK_EX);
192 exit();*/
193
194 $response = json_decode($response_raw,TRUE);
195 if(isset($response['entry']['0']['messaging'][0]['delivery'])) exit();
196
197 // for package expired users bot will not work section
198 $page_id = $response['entry']['0']['messaging'][0]['recipient']['id'];
199 $table_name = "messenger_bot_page_info";
200 $where['where'] = array('messenger_bot_page_info.page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1');
201 $join = array('users'=>"users.id=messenger_bot_page_info.user_id,left");
202 $users_expiry_info = $this->basic->get_data($table_name,$where,array("users.expired_date","users.user_type","users.deleted","users.status"),$join);
203 if($users_expiry_info[0]['user_type'] != 'Admin')
204 {
205 $user_status = $users_expiry_info[0]['status'];
206 $user_deleted = $users_expiry_info[0]['deleted'];
207 if($user_deleted == '1' || $user_status == '0') exit();
208
209 $expire_date = strtotime($users_expiry_info[0]['expired_date']);
210 $current_date = strtotime(date("Y-m-d"));
211 if ($expire_date < $current_date)
212 exit();
213 }
214 // end of for package expired users bot will not work section
215
216 if(isset($response['entry']['0']['messaging'][0]['read']))
217 {
218 $receipent_id_read=isset($response['entry']['0']['messaging'][0]['sender']['id'])?$response['entry']['0']['messaging'][0]['sender']['id']:"";
219 $where_array=array("subscribe_id"=>$receipent_id_read,"opened"=>"0","processed"=>'1',"error_message"=>"");
220 $campaign_info=$this->basic->get_data("messenger_bot_broadcast_serial_send",array("where"=>$where_array));
221 $campaign_id_read=array();
222 foreach($campaign_info as $read_info)
223 {
224 $campaign_id_read[]= $read_info['campaign_id'];
225 }
226 if(!empty($campaign_id_read))
227 {
228 $campaign_info_multiple=$this->basic->get_data("messenger_bot_broadcast_serial",array("where_in"=>array("id"=>$campaign_id_read)));
229 foreach ($campaign_info_multiple as $key => $value)
230 {
231 $cam_id=$value["id"];
232 $successfully_opened=$value["successfully_opened"];
233 $report_temp=json_decode($value["report"],true);
234 $report_temp[$receipent_id_read]["opened"]="1";
235 $report_temp[$receipent_id_read]["open_time"]=$currenTime;
236 $report_json=json_encode($report_temp);
237 $successfully_opened++;
238 $this->basic->update_data("messenger_bot_broadcast_serial",array("id"=>$cam_id),array("report"=>$report_json,"successfully_opened"=>$successfully_opened));
239 }
240 $update_data_read= array("opened"=>"1","open_time"=>$currenTime);
241 $this->basic->update_data('messenger_bot_broadcast_serial_send',$where_array,$update_data_read);
242 }
243 exit();
244 }
245
246
247 //if it's optin from checkbox plugin, then tese action is not needed. As not information can be found for that.
248
249 $page_id = $response['entry']['0']['messaging'][0]['recipient']['id'];
250
251 if(!isset($response['entry'][0]['messaging'][0]['optin']['user_ref']))
252 {
253 $sender_id= $response['entry']['0']['messaging'][0]['sender']['id'];
254
255 //subscriber status
256 $subscriber_new_old_info= $this->create_subscriber($sender_id, $page_id);
257 $subscriber_where['where'] = array('subscribe_id' => $sender_id);
258 $subscriber_info = $this->basic->get_data("messenger_bot_subscriber",$subscriber_where,'',"","1");
259
260 }
261
262 /*** Check if it coming from after subscribing by checkbox plugin ***/
263
264 if($this->db->table_exists('messenger_bot_engagement_2way_chat_plugin'))
265 {
266 if(isset($response['entry'][0]['messaging'][0]['prior_message']['source']) && $response['entry'][0]['messaging'][0]['prior_message']['source']=="checkbox_plugin")
267 {
268
269 $user_identifier= isset($response['entry'][0]['messaging'][0]['prior_message']['identifier']) ? $response['entry'][0]['messaging'][0]['prior_message']['identifier']:"";
270
271 if($user_identifier!="")
272 {
273 //Get check_box plugin id searching with user_identifier.
274 $check_box_plugin_info= $this->basic->get_data("messenger_bot_engagement_checkbox_reply",array("where"=>array("user_ref"=>$user_identifier)));
275
276 $check_box_plugin_id=isset($check_box_plugin_info[0]['checkbox_plugin_id']) ? $check_box_plugin_info[0]['checkbox_plugin_id']:"";
277 $check_box_plugin_reference=isset($check_box_plugin_info[0]['reference']) ? $check_box_plugin_info[0]['reference']:"";
278
279 if($check_box_plugin_id!="")
280 {
281 // Update subscriber if new, then source is from checkbox plugin & also reffernce updated.
282 if($subscriber_new_old_info['is_new'])
283 {
284 $plugin_name=$response['entry'][0]['messaging'][0]['prior_message']['source'];
285 $subscriber_id_update=$subscriber_info[0]['id'];
286 $update_data=array("refferer_id"=>$check_box_plugin_reference,"refferer_source"=>$plugin_name,"refferer_uri"=>"N/A");
287 $this->basic->update_data("messenger_bot_subscriber",array("id"=>$subscriber_id_update),$update_data);
288 }
289
290 $engagementer_info= $this->basic->get_data("messenger_bot_engagement_checkbox",array("where"=>array("id"=>$check_box_plugin_id)));
291
292 $label_ids=isset($engagementer_info[0]['label_ids']) ? $engagementer_info[0]['label_ids']:"";
293
294 if($label_ids!="" )
295 {
296 $post_data_label_assign=array("psid"=>$sender_id,"fb_page_id"=>$page_id,"label_auto_ids"=>$label_ids);
297 $url=base_url()."messenger_broadcaster/assign_label_webhook_call";
298 $ch = curl_init();
299 curl_setopt($ch, CURLOPT_URL, $url);
300 curl_setopt($ch,CURLOPT_POST,1);
301 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data_label_assign);
302 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
303 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
304 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
305 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
306 $reply_response=curl_exec($ch);
307 }
308
309 }
310
311 }
312
313
314 }
315 }
316
317
318
319
320 if(isset($response['entry'][0]['messaging'][0]['message']['text'])
321 && !isset($response['entry'][0]['messaging'][0]['message']['quick_reply'])
322 && !isset($response['entry'][0]['messaging'][0]['postback'])
323 && !isset($response['entry'][0]['messaging'][0]['optin'])) //message for all
324 {
325 $messages = $response['entry']['0']['messaging'][0]['message']['text'];
326 $table_name = "messenger_bot";
327 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1');
328 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
329 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
330
331 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
332 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
333 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
334 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
335
336
337 if($enable_mark_seen)
338 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
339 foreach ($messenger_bot_info as $key => $value) {
340 $cam_keywords_str = $value['keywords'];
341 $cam_keywords_array = explode(",", $cam_keywords_str);
342 foreach ($cam_keywords_array as $cam_keywords) {
343 if(function_exists('iconv') && function_exists('mb_detect_encoding')){
344 $encoded_word = mb_detect_encoding($cam_keywords);
345 if(isset($encoded_word)){
346 $cam_keywords = iconv( $encoded_word, "UTF-8//TRANSLIT", $cam_keywords );
347 }
348 }
349 $pos= stripos($messages,trim($cam_keywords));
350 if($pos!==FALSE){
351 $message_str = $value['message'];
352 $message_array = json_decode($message_str,true);
353 // if(!isset($message_array[1])) $message_array[1]=$message_array;
354 if(!isset($message_array[1])){
355 $message_array_org=$message_array;
356 $message_array=array();
357 $message_array[1]=$message_array_org;
358 }
359 foreach($message_array as $msg)
360 {
361 $template_type_file_track=$msg['message']['template_type'];
362 unset($msg['message']['template_type']);
363 $msg['messaging_type'] = "RESPONSE";
364 $reply = json_encode($msg);
365 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
366 if(isset($subscriber_info[0]['first_name']))
367 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
368 if(isset($subscriber_info[0]['last_name']))
369 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
370 $access_token = $value['page_access_token'];
371 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1")
372 {
373 if($enable_typing_on){
374 $this->sender_action($sender_id,"typing_on",$access_token);
375 sleep($typing_on_delay_time);
376 }
377
378 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio')
379 {
380 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
381 $url=base_url()."messenger_bot/send_reply_curl_call";
382 $ch = curl_init();
383 curl_setopt($ch, CURLOPT_URL, $url);
384 curl_setopt($ch,CURLOPT_POST,1);
385 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
386 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
387 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
388 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
389 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
390 $reply_response=curl_exec($ch);
391 }
392 else
393 $reply_response= $this->send_reply($access_token,$reply);
394
395 /*****Insert into database messenger_bot_reply_error_log if get error****/
396 if(isset($reply_response['error']['message'])){
397 $bot_settings_id= $value['id'];
398 $reply_error_message= $reply_response['error']['message'];
399 $error_time= date("Y-m-d H:i:s");
400 $page_table_id=$value['page_id'];
401 $user_id=$value['user_id'];
402
403 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
404 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
405 "error_time"=>$error_time);
406 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
407
408 }
409
410
411 }
412
413
414 }
415 die();
416 }
417 }
418 }
419 $table_name = "messenger_bot";
420 $where['where'] = array('messenger_bot.fb_page_id' => $page_id, 'messenger_bot.keyword_type' => 'no match','messenger_bot_page_info.bot_enabled' => '1');
421 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
422 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'1','','messenger_bot.id asc');
423
424 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
425 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
426 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
427 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
428
429 if(isset($messenger_bot_info[0]) && !empty($messenger_bot_info)){
430 $message_str = $messenger_bot_info[0]['message'];
431 $message_array = json_decode($message_str,true);
432 // if(!isset($message_array[1])) $message_array[1]=$message_array;
433 if(!isset($message_array[1])){
434 $message_array_org=$message_array;
435 $message_array=array();
436 $message_array[1]=$message_array_org;
437 }
438 foreach($message_array as $msg)
439 {
440 $template_type_file_track=$msg['message']['template_type'];
441 unset($msg['message']['template_type']);
442 $msg['messaging_type'] = "RESPONSE";
443 $reply = json_encode($msg);
444 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
445 if(isset($subscriber_info[0]['first_name']))
446 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
447 if(isset($subscriber_info[0]['last_name']))
448 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
449 $access_token = $messenger_bot_info[0]['page_access_token'];
450 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1")
451 {
452 if($enable_typing_on){
453 $this->sender_action($sender_id,"typing_on",$access_token);
454 sleep($typing_on_delay_time);
455 }
456
457 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio')
458 {
459 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
460 $url=base_url()."messenger_bot/send_reply_curl_call";
461 $ch = curl_init();
462 curl_setopt($ch, CURLOPT_URL, $url);
463 curl_setopt($ch,CURLOPT_POST,1);
464 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
465 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
466 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
467 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
468 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
469 $reply_response=curl_exec($ch);
470
471 }
472 else
473 $reply_response=$this->send_reply($access_token,$reply);
474 /*****Insert into database messenger_bot_reply_error_log if get error****/
475 if(isset($reply_response['error']['message'])){
476 $bot_settings_id= $value['id'];
477 $reply_error_message= $reply_response['error']['message'];
478 $error_time= date("Y-m-d H:i:s");
479 $page_table_id=$value['page_id'];
480 $user_id=$value['user_id'];
481
482 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
483 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
484 "error_time"=>$error_time);
485 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
486
487 }
488 }
489 }
490 die();
491 }
492 }
493
494 elseif(isset($response['entry'][0]['messaging'][0]['optin'])) //Optins from Send to messengers
495 {
496
497 if($this->db->table_exists('messenger_bot_engagement_2way_chat_plugin')){
498
499 $reference_id = isset($response['entry'][0]['messaging'][0]['optin']['ref'])?$response['entry'][0]['messaging'][0]['optin']['ref']:"";
500 $user_reference_id = isset($response['entry'][0]['messaging'][0]['optin']['user_ref'])?$response['entry'][0]['messaging'][0]['optin']['user_ref']:"";
501
502 if($user_reference_id!="")
503 $table_name="messenger_bot_engagement_checkbox";
504
505 else
506 {
507
508 $table_name="messenger_bot_engagement_send_to_msg";
509
510 if($subscriber_new_old_info['is_new'])
511 {
512
513 $plugin_name="SEND-TO-MESSENGER-PLUGIN";
514 $subscriber_id_update=$subscriber_info[0]['id'];
515
516 $update_data=array("refferer_id"=>$reference_id,"refferer_source"=>$plugin_name,"refferer_uri"=>"N/A");
517 $this->basic->update_data("messenger_bot_subscriber",array("id"=>$subscriber_id_update),$update_data);
518 }
519
520 }
521
522
523 $engagementer_info= $this->basic->get_data($table_name,array("where"=>array("reference"=>$reference_id)));
524
525 $label_ids=isset($engagementer_info[0]['label_ids']) ? $engagementer_info[0]['label_ids']:"";
526
527 $template_id=isset($engagementer_info[0]['template_id']) ? $engagementer_info[0]['template_id']:"";
528
529 $plugin_auto_id=isset($engagementer_info[0]['id']) ? $engagementer_info[0]['id']:"";
530
531
532 /** Insert into messenger_bot_engagement_checkbox_reply if it comes from checkbox plugin ***/
533 if($user_reference_id!="")
534 {
535 $reference_data_checkbox['user_ref']=$user_reference_id;
536 $reference_data_checkbox['checkbox_plugin_id']=$plugin_auto_id;
537 $reference_data_checkbox['reference']=$reference_id;
538 $reference_data_checkbox['optin_time']=date("Y-m-d H:i:s");
539 $this->basic->insert_data("messenger_bot_engagement_checkbox_reply",$reference_data_checkbox);
540
541 }
542
543
544
545 if($label_ids!="" && $user_reference_id==""){ // Update Label if only send-to-messenger. Don't for checkbox for first time. As we can't infromation
546
547 $post_data_label_assign=array("psid"=>$sender_id,"fb_page_id"=>$page_id,"label_auto_ids"=>$label_ids);
548 $url=base_url()."messenger_broadcaster/assign_label_webhook_call";
549 $ch = curl_init();
550 curl_setopt($ch, CURLOPT_URL, $url);
551 curl_setopt($ch,CURLOPT_POST,1);
552 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data_label_assign);
553 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
554 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
555 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
556 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
557 $reply_response=curl_exec($ch);
558
559 }
560
561 if($template_id!=""){
562
563 $postback_id_info= $this->basic->get_data("messenger_bot_postback",array("where"=>array("id"=>$template_id)));
564 $postback_id= isset($postback_id_info[0]['postback_id']) ? $postback_id_info[0]['postback_id'] :"";
565 }
566
567 $table_name = "messenger_bot";
568
569 if($template_id=="")
570
571 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'keyword_type'=>'get-started','messenger_bot_page_info.bot_enabled' => '1');
572
573 else
574
575 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1',"postback_id"=>$postback_id);
576
577 }
578
579 else
580
581 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'keyword_type'=>'get-started','messenger_bot_page_info.bot_enabled' => '1');
582
583
584 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
585 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
586
587 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
588 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
589 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
590 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
591
592
593 if($enable_mark_seen && $user_reference_id=="")
594 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
595
596
597 foreach ($messenger_bot_info as $key => $value) {
598 $message_str = $value['message'];
599 $message_array = json_decode($message_str,true);
600 // if(!isset($message_array[1])) $message_array[1]=$message_array;
601 if(!isset($message_array[1])){
602 $message_array_org=$message_array;
603 $message_array=array();
604 $message_array[1]=$message_array_org;
605 }
606 foreach($message_array as $msg)
607 {
608 $template_type_file_track=$msg['message']['template_type'];
609 unset($msg['message']['template_type']);
610 $msg['messaging_type'] = "RESPONSE";
611 $reply = json_encode($msg);
612
613 if($user_reference_id=="") // if comes from send-to-messenger rather than checkbox plugin
614 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
615
616 else // if comes from checkbox plugin, then it's different message structure.
617 $reply=str_replace('{"id":"replace_id"}', '{"user_ref":"'.$user_reference_id.'"}', $reply);
618
619 if(isset($subscriber_info[0]['first_name']))
620 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
621 if(isset($subscriber_info[0]['last_name']))
622 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
623 $access_token = $value['page_access_token'];
624
625 if((isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1") || $user_reference_id!=""){
626
627 if($enable_typing_on && $user_reference_id==""){
628 $this->sender_action($sender_id,"typing_on",$access_token);
629 sleep($typing_on_delay_time);
630 }
631
632 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio'){
633 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
634 $url=base_url()."messenger_bot/send_reply_curl_call";
635 $ch = curl_init();
636 curl_setopt($ch, CURLOPT_URL, $url);
637 curl_setopt($ch,CURLOPT_POST,1);
638 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
639 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
640 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
641 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
642 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
643 $reply_response=curl_exec($ch);
644
645 }
646 else
647 $reply_response=$this->send_reply($access_token,$reply);
648
649 /*****Insert into database messenger_bot_reply_error_log if get error****/
650 if(isset($reply_response['error']['message'])){
651 $bot_settings_id= $value['id'];
652 $reply_error_message= $reply_response['error']['message'];
653 $error_time= date("Y-m-d H:i:s");
654 $page_table_id=$value['page_id'];
655 $user_id=$value['user_id'];
656
657 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
658 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
659 "error_time"=>$error_time);
660 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
661
662 }
663 }
664 }
665 die();
666 }
667 }
668
669
670 elseif((isset($response['entry'][0]['messaging'][0]['postback']['referral']['type']) && $response['entry'][0]['messaging'][0]['postback']['referral']['type']=="OPEN_THREAD") ||
671
672 (isset($response['entry'][0]['messaging'][0]['postback']['payload']) && $response['entry'][0]['messaging'][0]['postback']['payload']=="GET_STARTED_PAYLOAD" ))
673
674 //When not any conversation and get started button is added
675 {
676
677 /**Check If the Engagement add-on is installed or not. Check a table of this addon is exist or not**/
678
679 if($this->db->table_exists('messenger_bot_engagement_2way_chat_plugin')){
680
681
682 $reference_id = isset($response['entry'][0]['messaging'][0]['postback']['referral']['ref'])?$response['entry'][0]['messaging'][0]['postback']['referral']['ref']:"";
683
684 $reference_source=isset($response['entry'][0]['messaging'][0]['postback']['referral']['source'])?$response['entry'][0]['messaging'][0]['postback']['referral']['source']:"";
685
686
687 if($reference_source=="CUSTOMER_CHAT_PLUGIN"){ // If from Custom CHat
688 $table_name="messenger_bot_engagement_2way_chat_plugin";
689 $plugin_name=$reference_source;
690 $refferer_uri=isset($response['entry'][0]['messaging'][0]['postback']['referral']['referer_uri'])?$response['entry'][0]['messaging'][0]['postback']['referral']['referer_uri']:"";
691 }
692
693 else if($reference_source=="SHORTLINK"){ // If from custom link
694
695 $table_name="messenger_bot_engagement_mme";
696 $plugin_name=$reference_source;
697 $refferer_uri="N/A";
698
699 }
700 else if($reference_source=="MESSENGER_CODE"){ //if messenger codes
701
702 $table_name="messenger_bot_engagement_messenger_codes";
703 $plugin_name=$reference_source;
704 $refferer_uri="N/A";
705
706 }
707 else{ // If come from page directly
708 $table_name="";
709 $plugin_name="FB PAGE";
710 $refferer_uri="N/A";
711 }
712
713 if($subscriber_new_old_info['is_new']){
714 $subscriber_id_update=$subscriber_info[0]['id'];
715 $update_data=array("refferer_id"=>$reference_id,"refferer_source"=>$plugin_name,"refferer_uri"=>$refferer_uri);
716 $this->basic->update_data("messenger_bot_subscriber",array("id"=>$subscriber_id_update),$update_data);
717 }
718
719
720 $postback_id="";
721
722 if($table_name!=""){
723
724 $engagementer_info= $this->basic->get_data($table_name,array("where"=>array("reference"=>$reference_id)));
725 $label_ids=isset($engagementer_info[0]['label_ids']) ? $engagementer_info[0]['label_ids']:"";
726 $template_id=isset($engagementer_info[0]['template_id']) ? $engagementer_info[0]['template_id']:"";
727 if(!empty($label_ids)){
728
729 $post_data_label_assign=array("psid"=>$sender_id,"fb_page_id"=>$page_id,"label_auto_ids"=>$label_ids);
730 $url=base_url()."messenger_broadcaster/assign_label_webhook_call";
731 $ch = curl_init();
732 curl_setopt($ch, CURLOPT_URL, $url);
733 curl_setopt($ch,CURLOPT_POST,1);
734 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data_label_assign);
735 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
736 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
737 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
738 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
739 $reply_response=curl_exec($ch);
740
741 }
742
743 if($template_id!=""){
744 $postback_id_info= $this->basic->get_data("messenger_bot_postback",array("where"=>array("id"=>$template_id)));
745 $postback_id= isset($postback_id_info[0]['postback_id']) ? $postback_id_info[0]['postback_id'] :"";
746
747 }
748
749 }
750
751
752 if($postback_id=="")
753
754 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'keyword_type'=>'get-started','messenger_bot_page_info.bot_enabled' => '1');
755
756 else
757 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1',"postback_id"=>$postback_id);
758
759 }
760
761 else // if engagement add-on not installed, then default query for get started.
762
763 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'keyword_type'=>'get-started','messenger_bot_page_info.bot_enabled' => '1');
764
765
766
767 $messages = $response['entry'][0]['messaging'][0]['message']['text'];
768 $table_name = "messenger_bot";
769
770 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
771 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
772
773 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
774 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
775 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
776 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
777
778
779 if($enable_mark_seen) // mark ass seen action
780 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
781
782 foreach ($messenger_bot_info as $key => $value) {
783 $message_str = $value['message'];
784 $message_array = json_decode($message_str,true);
785 // if(!isset($message_array[1])) $message_array[1]=$message_array;
786 if(!isset($message_array[1])){
787 $message_array_org=$message_array;
788 $message_array=array();
789 $message_array[1]=$message_array_org;
790 }
791 foreach($message_array as $msg)
792 {
793 $template_type_file_track=$msg['message']['template_type'];
794 unset($msg['message']['template_type']);
795 $msg['messaging_type'] = "RESPONSE";
796 $reply = json_encode($msg);
797 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
798 if(isset($subscriber_info[0]['first_name']))
799 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
800 if(isset($subscriber_info[0]['last_name']))
801 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
802 $access_token = $value['page_access_token'];
803 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1"){
804
805 if($enable_typing_on){
806 $this->sender_action($sender_id,"typing_on",$access_token);
807 sleep($typing_on_delay_time);
808 }
809 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio'){
810 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
811 $url=base_url()."messenger_bot/send_reply_curl_call";
812 $ch = curl_init();
813 curl_setopt($ch, CURLOPT_URL, $url);
814 curl_setopt($ch,CURLOPT_POST,1);
815 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
816 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
817 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
818 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
819 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
820 $reply_response=curl_exec($ch);
821
822 }
823 else
824 $reply_response=$this->send_reply($access_token,$reply);
825 /*****Insert into database messenger_bot_reply_error_log if get error****/
826 if(isset($reply_response['error']['message'])){
827 $bot_settings_id= $value['id'];
828 $reply_error_message= $reply_response['error']['message'];
829 $error_time= date("Y-m-d H:i:s");
830 $page_table_id=$value['page_id'];
831 $user_id=$value['user_id'];
832
833 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
834 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
835 "error_time"=>$error_time);
836 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
837
838 }
839 }
840 }
841
842 die();
843 }
844 }
845 elseif (isset($response['entry'][0]['messaging'][0]['message']['quick_reply'])) //quick_reply
846 {
847 //catch payload_id from response
848 $payload_id = $response['entry'][0]['messaging'][0]['message']['quick_reply']['payload'];
849 $messages = $response['entry'][0]['messaging'][0]['message']['text'];
850 $table_name = "messenger_bot";
851 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1');
852 $this->db->where("FIND_IN_SET('$payload_id',messenger_bot.postback_id) !=", 0);
853 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
854 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
855
856 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
857 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
858 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
859 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
860
861 /*** Insert email into database if it's email from quick reply ***/
862
863 if($this->is_email($payload_id)){
864
865 $fb_page_id=$subscriber_info[0]['page_id'];
866 $user_id=$subscriber_info[0]['user_id'];
867 $fb_user_id=$subscriber_info[0]['subscribe_id'];
868 $fb_user_first_name=$subscriber_info[0]['first_name'];
869 $fb_user_last_name=$subscriber_info[0]['last_name'];
870 $profile_pic=$subscriber_info[0]['profile_pic'];
871 $update_time=date("Y-m-d H:i:s");
872 $email=$payload_id;
873
874 $sql="INSERT INTO messenger_bot_quick_reply_email (fb_page_id,user_id,fb_user_id,fb_user_first_name,fb_user_last_name,
875 profile_pic,email,entry_time,last_update_time) VALUES ('$fb_page_id','$user_id','$fb_user_id','$fb_user_first_name',
876 '$fb_user_last_name','$profile_pic','$email','$update_time','$update_time')
877 ON DUPLICATE KEY UPDATE last_update_time='$update_time';
878 ";
879 $this->basic->execute_complex_query($sql);
880 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1',"keyword_type"=>"email-quick-reply");
881 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
882 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
883 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
884 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
885
886 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
887 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
888 }
889 elseif($this->is_phone_number($payload_id)){
890
891 $fb_page_id=$subscriber_info[0]['page_id'];
892 $user_id=$subscriber_info[0]['user_id'];
893 $fb_user_id=$subscriber_info[0]['subscribe_id'];
894 $fb_user_first_name=$subscriber_info[0]['first_name'];
895 $fb_user_last_name=$subscriber_info[0]['last_name'];
896 $profile_pic=$subscriber_info[0]['profile_pic'];
897 $update_time=date("Y-m-d H:i:s");
898 $phone_number=$payload_id;
899
900 $sql="INSERT INTO messenger_bot_quick_reply_email (fb_page_id,user_id,fb_user_id,fb_user_first_name,fb_user_last_name,
901 profile_pic,phone_number,phone_number_entry_time,phone_number_last_update)
902 VALUES ('$fb_page_id','$user_id','$fb_user_id','$fb_user_first_name',
903 '$fb_user_last_name','$profile_pic','$phone_number','$update_time','$update_time')
904 ON DUPLICATE KEY UPDATE phone_number_last_update='$update_time',phone_number='$phone_number';";
905
906
907 $this->basic->execute_complex_query($sql);
908 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1',"keyword_type"=>"phone-quick-reply");
909 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
910 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
911
912 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
913 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
914 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
915 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
916 }
917
918
919
920 if($enable_mark_seen)
921 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
922 foreach ($messenger_bot_info as $key => $value) {
923 $message_str = $value['message'];
924 $message_array = json_decode($message_str,true);
925 // if(!isset($message_array[1])) $message_array[1]=$message_array;
926 if(!isset($message_array[1])){
927 $message_array_org=$message_array;
928 $message_array=array();
929 $message_array[1]=$message_array_org;
930 }
931 foreach($message_array as $msg)
932 {
933 $template_type_file_track=$msg['message']['template_type'];
934 unset($msg['message']['template_type']);
935 $msg['messaging_type'] = "RESPONSE";
936 $reply = json_encode($msg);
937 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
938 if(isset($subscriber_info[0]['first_name']))
939 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
940 if(isset($subscriber_info[0]['last_name']))
941 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
942 $access_token = $value['page_access_token'];
943 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1"){
944
945 if($enable_typing_on){
946 $this->sender_action($sender_id,"typing_on",$access_token);
947 sleep($typing_on_delay_time);
948 }
949 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio'){
950 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
951 $url=base_url()."messenger_bot/send_reply_curl_call";
952 $ch = curl_init();
953 curl_setopt($ch, CURLOPT_URL, $url);
954 curl_setopt($ch,CURLOPT_POST,1);
955 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
956 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
957 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
958 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
959 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
960 $reply_response=curl_exec($ch);
961
962 }
963 else
964 $reply_response=$this->send_reply($access_token,$reply);
965 /*****Insert into database messenger_bot_reply_error_log if get error****/
966 if(isset($reply_response['error']['message'])){
967 $bot_settings_id= $value['id'];
968 $reply_error_message= $reply_response['error']['message'];
969 $error_time= date("Y-m-d H:i:s");
970 $page_table_id=$value['page_id'];
971 $user_id=$value['user_id'];
972
973 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
974 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
975 "error_time"=>$error_time);
976 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
977
978 }
979 }
980 }
981 die();
982 }
983 }
984 elseif(isset($response['entry'][0]['messaging'][0]['postback']))//Clicking on Payload Button like Start Chatting
985 {
986 $payload_id = $response['entry'][0]['messaging'][0]['postback']['payload'];
987 $messages = $response['entry'][0]['messaging'][0]['message']['text'];
988 $table_name = "messenger_bot";
989 $where['where'] = array('messenger_bot.fb_page_id' => $page_id,'messenger_bot_page_info.bot_enabled' => '1');
990 $this->db->where("FIND_IN_SET('$payload_id',messenger_bot.postback_id) !=", 0);
991 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
992 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'','','messenger_bot.id asc');
993
994 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
995 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
996 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
997 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
998
999
1000 if($enable_mark_seen)
1001 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
1002
1003 if($payload_id=="UNSUBSCRIBE_QUICK_BOXER")
1004 {
1005 $post_data_unsubscribe=array("psid"=>$sender_id,"fb_page_id"=>$page_id);
1006 $url=base_url()."messenger_broadcaster/unsubscribe_webhook_call";
1007 $ch = curl_init();
1008 curl_setopt($ch, CURLOPT_URL, $url);
1009 curl_setopt($ch,CURLOPT_POST,1);
1010 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data_unsubscribe);
1011 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
1012 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1013 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1014 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1015 $reply_response=curl_exec($ch);
1016 }
1017 elseif($payload_id=="RESUBSCRIBE_QUICK_BOXER")
1018 {
1019 $post_data_unsubscribe=array("psid"=>$sender_id,"fb_page_id"=>$page_id);
1020 $url=base_url()."messenger_broadcaster/resubscribe_webhook_call";
1021 $ch = curl_init();
1022 curl_setopt($ch, CURLOPT_URL, $url);
1023 curl_setopt($ch,CURLOPT_POST,1);
1024 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data_unsubscribe);
1025 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
1026 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1027 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1028 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1029 $reply_response=curl_exec($ch);
1030 }
1031
1032 foreach ($messenger_bot_info as $key => $value) {
1033
1034 $message_str = $value['message'];
1035 $message_array = json_decode($message_str,true);
1036 // if(!isset($message_array[1])) $message_array[1]=$message_array;
1037 if(!isset($message_array[1])){
1038 $message_array_org=$message_array;
1039 $message_array=array();
1040 $message_array[1]=$message_array_org;
1041 }
1042 foreach($message_array as $msg)
1043 {
1044 $template_type_file_track=$msg['message']['template_type'];
1045 unset($msg['message']['template_type']);
1046 $msg['messaging_type'] = "RESPONSE";
1047 $reply = json_encode($msg);
1048 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
1049 if(isset($subscriber_info[0]['first_name']))
1050 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
1051 if(isset($subscriber_info[0]['last_name']))
1052 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
1053 $access_token = $value['page_access_token'];
1054 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1"){
1055
1056 if($enable_typing_on){
1057 $this->sender_action($sender_id,"typing_on",$access_token);
1058 sleep($typing_on_delay_time);
1059 }
1060
1061
1062 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio'){
1063 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
1064 $url=base_url()."messenger_bot/send_reply_curl_call";
1065 $ch = curl_init();
1066 curl_setopt($ch, CURLOPT_URL, $url);
1067 curl_setopt($ch,CURLOPT_POST,1);
1068 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
1069 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
1070 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1071 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1072 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1073 $reply_response=curl_exec($ch);
1074
1075 }
1076 else
1077 $reply_response=$this->send_reply($access_token,$reply);
1078 /*****Insert into database messenger_bot_reply_error_log if get error****/
1079 if(isset($reply_response['error']['message'])){
1080 $bot_settings_id= $value['id'];
1081 $reply_error_message= $reply_response['error']['message'];
1082 $error_time= date("Y-m-d H:i:s");
1083 $page_table_id=$value['page_id'];
1084 $user_id=$value['user_id'];
1085
1086 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
1087 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
1088 "error_time"=>$error_time);
1089 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
1090
1091 }
1092 }
1093 }
1094 die();
1095 }
1096 }
1097 else
1098 {
1099 $table_name = "messenger_bot";
1100 $where['where'] = array('messenger_bot.fb_page_id' => $page_id, 'messenger_bot.keyword_type' => 'no match','messenger_bot_page_info.bot_enabled' => '1');
1101 $join = array('messenger_bot_page_info'=>"messenger_bot_page_info.page_id=messenger_bot.fb_page_id,left");
1102 $messenger_bot_info = $this->basic->get_data($table_name,$where,array("messenger_bot.*","messenger_bot_page_info.page_access_token as page_access_token","messenger_bot_page_info.enable_mark_seen as enable_mark_seen","messenger_bot_page_info.enbale_type_on as enbale_type_on","messenger_bot_page_info.reply_delay_time as reply_delay_time"),$join,'1','','messenger_bot.id asc');
1103
1104 $enable_mark_seen=$messenger_bot_info[0]['enable_mark_seen'];
1105 $enable_typing_on=$messenger_bot_info[0]['enbale_type_on'];
1106 $typing_on_delay_time = $messenger_bot_info[0]['reply_delay_time'];
1107 if($typing_on_delay_time=="0") $typing_on_delay_time=1;
1108
1109
1110 if($enable_mark_seen)
1111 $this->sender_action($sender_id,"mark_seen",$messenger_bot_info[0]['page_access_token']);
1112 if(isset($messenger_bot_info[0]) && !empty($messenger_bot_info)){
1113 $message_str = $messenger_bot_info[0]['message'];
1114 $message_array = json_decode($message_str,true);
1115 // if(!isset($message_array[1])) $message_array[1]=$message_array;
1116 if(!isset($message_array[1])){
1117 $message_array_org=$message_array;
1118 $message_array=array();
1119 $message_array[1]=$message_array_org;
1120 }
1121 foreach($message_array as $msg)
1122 {
1123 $template_type_file_track=$msg['message']['template_type'];
1124 unset($msg['message']['template_type']);
1125 $msg['messaging_type'] = "RESPONSE";
1126 $reply = json_encode($msg);
1127 $reply=str_replace('{"id":"replace_id"}', '{"id":"'.$sender_id.'"}', $reply);
1128 if(isset($subscriber_info[0]['first_name']))
1129 $reply=str_replace('#LEAD_USER_FIRST_NAME#', $subscriber_info[0]['first_name'], $reply);
1130 if(isset($subscriber_info[0]['last_name']))
1131 $reply=str_replace('#LEAD_USER_LAST_NAME#', $subscriber_info[0]['last_name'], $reply);
1132 $access_token = $messenger_bot_info[0]['page_access_token'];
1133 if(isset($subscriber_info[0]['status']) && $subscriber_info[0]['status']=="1"){
1134
1135 if($enable_typing_on){
1136 $this->sender_action($sender_id,"typing_on",$access_token);
1137 sleep($typing_on_delay_time);
1138 }
1139 if($template_type_file_track=='video' || $template_type_file_track=='file' || $template_type_file_track=='audio'){
1140 $post_data=array("access_token"=>$access_token,"reply"=>$reply);
1141 $url=base_url()."messenger_bot/send_reply_curl_call";
1142 $ch = curl_init();
1143 curl_setopt($ch, CURLOPT_URL, $url);
1144 curl_setopt($ch,CURLOPT_POST,1);
1145 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
1146 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
1147 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1148 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1149 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1150 $reply_response=curl_exec($ch);
1151
1152 }
1153 else
1154 $reply_response=$this->send_reply($access_token,$reply);
1155 /*****Insert into database messenger_bot_reply_error_log if get error****/
1156 if(isset($reply_response['error']['message'])){
1157 $bot_settings_id= $value['id'];
1158 $reply_error_message= $reply_response['error']['message'];
1159 $error_time= date("Y-m-d H:i:s");
1160 $page_table_id=$value['page_id'];
1161 $user_id=$value['user_id'];
1162
1163 $error_insert_data=array("page_id"=>$page_table_id,"fb_page_id"=>$page_id,"user_id"=>$user_id,
1164 "error_message"=>$reply_error_message,"bot_settings_id"=>$bot_settings_id,
1165 "error_time"=>$error_time);
1166 $this->basic->insert_data('messenger_bot_reply_error_log',$error_insert_data);
1167
1168 }
1169 }
1170 }
1171
1172 die();
1173 }
1174 }
1175 }
1176
1177
1178 public function subscriber_info($access_token='',$sender_id='')
1179 {
1180 $url = "https://graph.facebook.com/v2.6/$sender_id?access_token=$access_token";
1181 $ch = curl_init();
1182 $headers = array("Content-type: application/json");
1183 curl_setopt($ch, CURLOPT_URL, $url);
1184 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
1185 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1186 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1187 curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
1188 curl_setopt($ch, CURLOPT_COOKIEFILE,'cookie.txt');
1189 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1190 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
1191 $st=curl_exec($ch);
1192 $result=json_decode($st,TRUE);
1193 return $result;
1194 }
1195
1196 public function index()
1197 {
1198 $total_enabled_bot = $this->basic->get_data('messenger_bot_page_info',['where'=>['user_id'=>$this->user_id,'bot_enabled'=>'1']],['count(id) as total_enabled_bot']);
1199 $total_errors_in_bot = $this->basic->get_data('messenger_bot_reply_error_log',['where'=>['user_id'=>$this->user_id]],['count(id) as total_errors_in_bot']);
1200 $total_enabled_persistent_menu = $this->basic->get_data('messenger_bot_page_info',['where'=>['user_id'=>$this->user_id,'persistent_enabled'=>'1']],['count(id) as total_enabled_persistent_menu']);
1201 $total_subscribers = $this->basic->get_data('messenger_bot_subscriber',['where'=>['user_id'=>$this->user_id]],['count(id) as total_subscribers']);
1202 $total_male_subscribers = $this->basic->get_data('messenger_bot_subscriber',['where'=>['user_id'=>$this->user_id,'gender'=>'male']],['count(id) as total_subscribers']);
1203 $total_female_subscribers = $this->basic->get_data('messenger_bot_subscriber',['where'=>['user_id'=>$this->user_id,'gender'=>'female']],['count(id) as total_subscribers']);
1204 $gender_type_data = array(
1205 0 => array(
1206 "value" => $total_male_subscribers[0]['total_subscribers'],
1207 "color" => '#FFCF75',
1208 "highlight" => '#FFCF75',
1209 "label" => $this->lang->line('Male subscriber')
1210 ),
1211 1 => array(
1212 "value" => $total_female_subscribers[0]['total_subscribers'],
1213 "color" => '#FF8000',
1214 "highlight" => '#FF8000',
1215 "label" => $this->lang->line('Female subscriber')
1216 )
1217 );
1218 $data['gender_type_data'] = $gender_type_data;
1219 $data['total_male_subscribers'] = $total_male_subscribers[0]['total_subscribers'];
1220 $data['total_female_subscribers'] = $total_female_subscribers[0]['total_subscribers'];
1221
1222 $data['total_enabled_bot'] = $total_enabled_bot[0]['total_enabled_bot'];
1223 $data['total_errors_in_bot'] = $total_errors_in_bot[0]['total_errors_in_bot'];
1224 $data['total_enabled_persistent_menu'] = $total_enabled_persistent_menu[0]['total_enabled_persistent_menu'];
1225 $data['total_subscribers'] = $total_subscribers[0]['total_subscribers'];
1226 $curdate=date("Y-m-d");
1227 $from_date=date('Y-m-d', strtotime($curdate. " - 30 days"));
1228 $from_date = $from_date." 00:00:00";
1229 $to_date = $curdate." 23:59:59";
1230 $where = array();
1231 $where['where'] = array(
1232 "subscribed_at >=" => $from_date,
1233 "subscribed_at <=" => $to_date,
1234 "gender" => 'male',
1235 "user_id" => $this->user_id
1236 );
1237 $select = array(
1238 "date_format(subscribed_at,'%Y-%m-%d') as date",
1239 "count(id) as number_of_subscriber"
1240 );
1241 $day_wise_male_subscribers = $this->basic->get_data('messenger_bot_subscriber',$where,$select,$join='',$limit='',$start='',$order_by='',$group_by="date");
1242 $male_subscribers = array();
1243 foreach($day_wise_male_subscribers as $value)
1244 {
1245 $male_subscribers[$value['date']] = $value['number_of_subscriber'];
1246 }
1247 $where = array();
1248 $where['where'] = array(
1249 "subscribed_at >=" => $from_date,
1250 "subscribed_at <=" => $to_date,
1251 "gender" => 'female',
1252 "user_id" => $this->user_id
1253 );
1254 $select = array(
1255 "date_format(subscribed_at,'%Y-%m-%d') as date",
1256 "count(id) as number_of_subscriber"
1257 );
1258 $day_wise_female_subscribers = $this->basic->get_data('messenger_bot_subscriber',$where,$select,$join='',$limit='',$start='',$order_by='',$group_by="date");
1259 $female_subscribers = array();
1260 foreach($day_wise_female_subscribers as $value)
1261 {
1262 $female_subscribers[$value['date']] = $value['number_of_subscriber'];
1263 }
1264 $subscribers_comparison_data = array();
1265 $total_subscribers_data = array();
1266 $dDiff = strtotime($to_date) - strtotime($from_date);
1267 $no_of_days = floor($dDiff/(60*60*24));
1268
1269 for($i=0;$i<=$no_of_days;$i++){
1270 $day_count = date('Y-m-d', strtotime($from_date. " + $i days"));
1271 if(isset($male_subscribers[$day_count]))
1272 {
1273 $daily_male_subscribers = $male_subscribers[$day_count];
1274 $subscribers_comparison_data[$i]['date'] = $day_count;
1275 $subscribers_comparison_data[$i]['male'] = $daily_male_subscribers;
1276 }
1277 else
1278 {
1279 $daily_male_subscribers = 0;
1280 $subscribers_comparison_data[$i]['date'] = $day_count;
1281 $subscribers_comparison_data[$i]['male'] = $daily_male_subscribers;
1282 }
1283 if(isset($female_subscribers[$day_count]))
1284 {
1285 $daily_female_subscribers = $female_subscribers[$day_count];
1286 $subscribers_comparison_data[$i]['date'] = $day_count;
1287 $subscribers_comparison_data[$i]['female'] = $daily_female_subscribers;
1288 }
1289 else
1290 {
1291 $daily_female_subscribers = 0;
1292 $subscribers_comparison_data[$i]['date'] = $day_count;
1293 $subscribers_comparison_data[$i]['female'] = $daily_female_subscribers;
1294 }
1295 $total_subscribers_data[$i]['date'] = $day_count;
1296 $total_subscribers_data[$i]['subscribers'] = $daily_male_subscribers + $daily_female_subscribers;
1297 }
1298 $data['subscribers_comparison_data'] = $subscribers_comparison_data;
1299 $data['total_subscribers_data'] = $total_subscribers_data;
1300 $where = array();
1301 $where['where'] = array(
1302 "last_update_time >=" => $from_date,
1303 "last_update_time <=" => $to_date,
1304 "user_id" => $this->user_id
1305 );
1306 $select = array(
1307 "date_format(last_update_time,'%Y-%m-%d') as date",
1308 "count(id) as number_of_emails"
1309 );
1310 $day_wise_email_gain = $this->basic->get_data('messenger_bot_quick_reply_email',$where,$select,$join='',$limit='',$start='',$order_by='',$group_by="date");
1311 $email_gain = array();
1312 foreach($day_wise_email_gain as $value)
1313 {
1314 $email_gain[$value['date']] = $value['number_of_emails'];
1315 }
1316 $day_wise_total_email = array();
1317 for($i=0;$i<=$no_of_days;$i++){
1318 $day_count = date('Y-m-d', strtotime($from_date. " + $i days"));
1319 if(isset($email_gain[$day_count]))
1320 {
1321 $total_emails = $email_gain[$day_count];
1322 $day_wise_total_email[$i]['date'] = $day_count;
1323 $day_wise_total_email[$i]['emails'] = $total_emails;
1324 }
1325 else
1326 {
1327 $total_emails = 0;
1328 $day_wise_total_email[$i]['date'] = $day_count;
1329 $day_wise_total_email[$i]['emails'] = $total_emails;
1330 }
1331 }
1332 $total_emails_gain = $this->basic->get_data('messenger_bot_quick_reply_email',['where'=>['user_id'=>$this->user_id]],['count(id) as number_of_emails']);
1333 $data['total_emails'] = $total_emails_gain[0]['number_of_emails'];
1334 $data['day_wise_total_email'] = $day_wise_total_email;
1335 $data['body'] = 'dashboard';
1336 $this->_viewcontroller($data);
1337 }
1338 public function activate()
1339 {
1340 if(!$_POST) exit();
1341 if(!isset($_SERVER['HTTPS']))
1342 {
1343 echo json_encode(array('status'=>'0','message'=>$this->lang->line('This add-on requires HTTPS.')));
1344 exit();
1345 }
1346 $is_free_addon=false;
1347 $addon_controller_name=ucfirst($this->router->fetch_class()); // here addon_controller_name name is Comment [origianl file is Comment.php, put except .php]
1348 $purchase_code=$this->input->post('purchase_code');
1349 if(!$is_free_addon)
1350 {
1351 $this->addon_credential_check($purchase_code,strtolower($addon_controller_name)); // retuns json status,message if error
1352 }
1353 $verify_token=$this->_random_number_generator(15);
1354 $app_package_config_data = "<?php ";
1355 $app_package_config_data.= "\n\$config['webhook_verify_token'] = '$verify_token';\n";
1356 $app_package_config_data.= "\n\$config['bot_backup_mode'] = '0';";
1357 @file_put_contents(APPPATH.'modules/'.strtolower($this->router->fetch_class()).'/config/messenger_bot_config.php', $app_package_config_data, LOCK_EX);
1358
1359 //this addon system support 2-level sidebar entry, to make sidebar entry you must provide 2D array like below
1360 $sidebar=array
1361 (
1362 0 =>array
1363 (
1364 'name' => 'Messenger Bot',
1365 'icon' => 'fa fa-comments',
1366 'url' => '#',
1367 'is_external' => '0',
1368 'child_info' => array
1369 (
1370 'have_child'=>'1', // parent has child menus, 0 means no child
1371 'child'=>array // if status = 1 then you must add child array, other wise not need to set this index
1372 (
1373 0 => array
1374 (
1375 'name'=>'Dashboard',
1376 'icon'=>'fa fa-dashboard',
1377 'url' => 'messenger_bot/index',
1378 'is_external' => '0'
1379 ),
1380 1 => array
1381 (
1382 'name'=>'General Settings',
1383 'icon'=>'fa fa-cog',
1384 'url' => 'messenger_bot/configuration',
1385 'is_external' => '0'
1386 ),
1387 2 => array
1388 (
1389 'name'=>'Facebook API Settings',
1390 'icon'=>'fa fa-facebook-official',
1391 'url' => 'messenger_bot/facebook_config',
1392 'is_external' => '0'
1393 ),
1394 3 => array
1395 (
1396 'name'=>'Import Account',
1397 'icon'=>'fa fa-cloud-download',
1398 'url' => 'messenger_bot/account_import',
1399 'is_external' => '0'
1400 ),
1401 4 => array
1402 (
1403 'name'=>'Domain Whitelist',
1404 'icon'=>'fa fa-list-ol',
1405 'url' => 'messenger_bot/domain_whitelist',
1406 'is_external' => '0'
1407 ),
1408 5 => array
1409 (
1410 'name'=>'Bot Settings',
1411 'icon'=>'fa fa-plus',
1412 'url' => 'messenger_bot/bot_list',
1413 'is_external' => '0'
1414 ),
1415 6 => array
1416 (
1417 'name'=>'Template Manager',
1418 'icon'=>'fa fa-th-large',
1419 'url' => 'messenger_bot/template_manager',
1420 'is_external' => '0'
1421 ),
1422 7 => array
1423 (
1424 'name'=>'Cron Job',
1425 'icon'=>'fa fa-clock-o',
1426 'url' => 'messenger_bot/cron_job',
1427 'is_external' => '0'
1428 )
1429
1430 )
1431 ),
1432 'only_admin' => '0' ,
1433 'only_member' => '0'
1434 )
1435 );
1436 // mysql raw query needed to run, it's an array, put each query in a seperate index, create table query must should IF NOT EXISTS
1437 $sql=array
1438 (
1439 0 =>"CREATE TABLE IF NOT EXISTS `messenger_bot` (
1440 `id` int(11) NOT NULL AUTO_INCREMENT,
1441 `user_id` int(11) NOT NULL,
1442 `page_id` int(11) NOT NULL,
1443 `fb_page_id` varchar(200) NOT NULL,
1444 `template_type` enum('text','image','audio','video','file','quick reply','text with buttons','generic template','carousel') NOT NULL DEFAULT 'text',
1445 `bot_type` enum('generic','keyword') NOT NULL DEFAULT 'generic',
1446 `keyword_type` enum('reply','post-back','no match','get-started') NOT NULL DEFAULT 'reply',
1447 `keywords` text NOT NULL,
1448 `message` text NOT NULL,
1449 `buttons` longtext NOT NULL,
1450 `images` longtext NOT NULL,
1451 `audio` varchar(255) NOT NULL,
1452 `video` varchar(255) NOT NULL,
1453 `file` varchar(255) NOT NULL,
1454 `status` enum('0','1') NOT NULL DEFAULT '1',
1455 `bot_name` varchar(200) NOT NULL,
1456 `postback_id` varchar(255) NOT NULL,
1457 `last_replied_at` datetime NOT NULL,
1458 PRIMARY KEY (`id`),
1459 KEY `user_id` (`user_id`,`page_id`)
1460 ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;",
1461 1=>"CREATE TABLE IF NOT EXISTS `messenger_bot_config` (
1462 `id` int(11) NOT NULL AUTO_INCREMENT,
1463 `app_name` varchar(100) DEFAULT NULL,
1464 `api_id` varchar(250) DEFAULT NULL,
1465 `api_secret` varchar(250) DEFAULT NULL,
1466 `numeric_id` varchar(250) NOT NULL,
1467 `user_access_token` varchar(500) DEFAULT NULL,
1468 `status` enum('0','1') NOT NULL DEFAULT '1',
1469 `deleted` enum('0','1') NOT NULL DEFAULT '0',
1470 `user_id` int(11) NOT NULL,
1471 `use_by` enum('only_me','everyone') NOT NULL DEFAULT 'only_me',
1472 PRIMARY KEY (`id`)
1473 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;",
1474 2=>"CREATE TABLE IF NOT EXISTS `messenger_bot_domain_whitelist` (
1475 `id` int(11) NOT NULL AUTO_INCREMENT,
1476 `user_id` int(11) NOT NULL,
1477 `messenger_bot_user_info_id` int(11) NOT NULL,
1478 `page_id` int(11) NOT NULL,
1479 `domain` tinytext NOT NULL,
1480 `created_at` datetime NOT NULL,
1481 PRIMARY KEY (`id`),
1482 KEY `user_id` (`user_id`,`page_id`)
1483 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;",
1484 3=>"CREATE TABLE IF NOT EXISTS `messenger_bot_page_info` (
1485 `id` int(11) NOT NULL AUTO_INCREMENT,
1486 `user_id` int(11) NOT NULL,
1487 `messenger_bot_user_info_id` int(11) NOT NULL,
1488 `page_id` varchar(200) NOT NULL,
1489 `page_cover` text,
1490 `page_profile` text,
1491 `page_name` varchar(200) DEFAULT NULL,
1492 `username` varchar(255) NOT NULL,
1493 `page_access_token` text NOT NULL,
1494 `page_email` varchar(200) DEFAULT NULL,
1495 `add_date` date NOT NULL,
1496 `deleted` enum('0','1') NOT NULL DEFAULT '0',
1497 `bot_enabled` enum('0','1') NOT NULL DEFAULT '0',
1498 `started_button_enabled` enum('0','1') NOT NULL DEFAULT '0',
1499 PRIMARY KEY (`id`),
1500 KEY `page_id` (`page_id`),
1501 KEY `user_id` (`user_id`,`page_id`)
1502 ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;",
1503 4=>"CREATE TABLE IF NOT EXISTS `messenger_bot_postback` (
1504 `id` int(11) NOT NULL AUTO_INCREMENT,
1505 `user_id` int(11) NOT NULL,
1506 `postback_id` varchar(255) NOT NULL,
1507 `page_id` int(11) NOT NULL,
1508 `use_status` enum('0','1') NOT NULL DEFAULT '0',
1509 `status` enum('0','1') NOT NULL DEFAULT '1',
1510 `messenger_bot_table_id` int(11) NOT NULL,
1511 `bot_name` varchar(255) NOT NULL,
1512 PRIMARY KEY (`id`),
1513 KEY `user_id` (`user_id`,`postback_id`,`page_id`)
1514 ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;",
1515 5=>"CREATE TABLE IF NOT EXISTS `messenger_bot_subscriber` (
1516 `id` int(11) NOT NULL AUTO_INCREMENT,
1517 `user_id` int(11) NOT NULL,
1518 `page_id` varchar(200) NOT NULL,
1519 `subscribe_id` varchar(255) NOT NULL,
1520 `first_name` varchar(255) NOT NULL,
1521 `last_name` varchar(255) NOT NULL,
1522 `profile_pic` varchar(255) NOT NULL,
1523 `gender` varchar(255) NOT NULL,
1524 `locale` varchar(255) NOT NULL,
1525 `timezone` varchar(255) NOT NULL,
1526 `subscribed_at` datetime NOT NULL,
1527 `status` enum('0','1') NOT NULL DEFAULT '1',
1528 PRIMARY KEY (`id`),
1529 KEY `user_id` (`user_id`,`page_id`,`subscribe_id`)
1530 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;",
1531 6=>"CREATE TABLE IF NOT EXISTS `messenger_bot_user_info` (
1532 `id` int(11) NOT NULL AUTO_INCREMENT,
1533 `messenger_bot_config_id` int(11) NOT NULL,
1534 `user_id` int(11) NOT NULL,
1535 `access_token` text NOT NULL,
1536 `name` varchar(200) DEFAULT NULL,
1537 `email` varchar(200) DEFAULT NULL,
1538 `fb_id` varchar(200) NOT NULL,
1539 `add_date` date NOT NULL,
1540 `deleted` enum('0','1') NOT NULL,
1541 `need_to_delete` enum('0','1') NOT NULL,
1542 PRIMARY KEY (`id`)
1543 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;",
1544 // extra module, this module aslo deleted manaually
1545 7=>"INSERT INTO `modules` (`id`, `module_name`, `add_ons_id`, `deleted`) VALUES ('199', 'Messenger Bot - Account Import', '0', '0');",
1546 8=>"ALTER TABLE `messenger_bot_page_info` ADD `persistent_enabled` ENUM('0','1') NOT NULL DEFAULT '0' AFTER `started_button_enabled`;",
1547 9=> "INSERT INTO `modules` (`id`, `module_name`, `add_ons_id`, `deleted`) VALUES ('197', 'Messenger Bot - Persistent Menu', '0', '0');",
1548 10=>"INSERT INTO `modules` (`id`, `module_name`, `add_ons_id`, `deleted`) VALUES ('198', 'Messenger Bot - Persistent Menu Copyright', '0', '0');",
1549 11=>"UPDATE `modules` SET `extra_text` = '' WHERE `modules`.`id` = 197",
1550 12=>"UPDATE `modules` SET `extra_text` = '' WHERE `modules`.`id` = 198;",
1551 13=>"UPDATE `modules` SET `extra_text` = '' WHERE `modules`.`id` = 199;",
1552 14=>"UPDATE `modules` SET `extra_text` = '' WHERE `modules`.`id` = 200;",
1553 15=>"UPDATE `modules` SET `limit_enabled` = '0' WHERE `modules`.`id` = 198;",
1554 16=>"UPDATE menu_child_1 SET only_admin='1' WHERE module_access=200 AND serial=1;",
1555 17=> "CREATE TABLE IF NOT EXISTS `messenger_bot_persistent_menu` (
1556 `id` int(11) NOT NULL AUTO_INCREMENT,
1557 `user_id` int(11) NOT NULL,
1558 `page_id` varchar(100) NOT NULL,
1559 `locale` varchar(20) NOT NULL DEFAULT 'default',
1560 `item_json` longtext NOT NULL,
1561 `composer_input_disabled` enum('0','1') NOT NULL DEFAULT '0',
1562 `poskback_id_json` text NOT NULL,
1563 PRIMARY KEY (`id`),
1564 UNIQUE KEY `page_id` (`page_id`,`locale`)
1565 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
1566 18=>"ALTER TABLE `messenger_bot_postback` DROP INDEX `user_id`, ADD UNIQUE `user_id` (`user_id`, `postback_id`, `page_id`) USING BTREE;",
1567 19 => "ALTER TABLE `messenger_bot_page_info` ADD `enable_mark_seen` ENUM( '0', '1' ) NOT NULL DEFAULT '0',
1568 ADD `enbale_type_on` ENUM( '0', '1' ) NOT NULL DEFAULT '0';",
1569 20 => "CREATE TABLE IF NOT EXISTS `messenger_bot_reply_error_log` (
1570 `id` int(11) NOT NULL AUTO_INCREMENT,
1571 `page_id` int(11) NOT NULL,
1572 `fb_page_id` varchar(200) NOT NULL,
1573 `user_id` int(11) NOT NULL,
1574 `error_message` varchar(250) NOT NULL,
1575 `bot_settings_id` int(11) NOT NULL,
1576 `error_time` datetime NOT NULL,
1577 PRIMARY KEY (`id`)
1578 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;",
1579 21 => "CREATE TABLE IF NOT EXISTS `messenger_bot_quick_reply_email` (
1580 `id` int(11) NOT NULL AUTO_INCREMENT,
1581 `fb_page_id` varchar(50) NOT NULL,
1582 `user_id` int(11) NOT NULL,
1583 `fb_user_id` varchar(50) NOT NULL,
1584 `fb_user_first_name` varchar(100) CHARACTER SET utf8 NOT NULL,
1585 `fb_user_last_name` varchar(100) CHARACTER SET utf8 NOT NULL,
1586 `profile_pic` text NOT NULL,
1587 `email` varchar(200) NOT NULL,
1588 `entry_time` datetime NOT NULL,
1589 `last_update_time` datetime NOT NULL,
1590 PRIMARY KEY (`id`),
1591 UNIQUE KEY `fb_page_id` (`fb_page_id`,`fb_user_id`,`email`,`user_id`)
1592 ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;",
1593 22 => "ALTER TABLE `messenger_bot_quick_reply_email` ADD `phone_number` VARCHAR(20) NOT NULL AFTER `last_update_time`, ADD `phone_number_entry_time` DATETIME NOT NULL AFTER `phone_number`, ADD `phone_number_last_update` DATETIME NOT NULL AFTER `phone_number_entry_time`;",
1594 23 => "ALTER TABLE `messenger_bot_quick_reply_email` DROP INDEX `fb_page_id`, ADD UNIQUE `fb_page_id` (`fb_page_id`, `fb_user_id`, `user_id`) USING BTREE;",
1595
1596 24 => "ALTER TABLE `messenger_bot_postback` ADD `is_template` ENUM('0','1') NOT NULL AFTER `bot_name`, ADD `template_jsoncode` LONGTEXT NOT NULL AFTER `is_template`;",
1597 25 => "ALTER TABLE `messenger_bot` ADD `is_template` ENUM('0','1') NOT NULL AFTER `last_replied_at`;",
1598 26 => "ALTER TABLE `messenger_bot_postback` ADD `template_name` VARCHAR(255) NOT NULL AFTER `template_jsoncode`;",
1599 27 => "ALTER TABLE `messenger_bot_postback` ADD `template_for` ENUM('reply_message','unsubscribe','resubscribe') NOT NULL AFTER `template_name`;",
1600 28 => "ALTER TABLE `messenger_bot_subscriber` ADD `is_image_download` ENUM('0','1') NOT NULL DEFAULT '0' AFTER `subscribed_at`, ADD `image_path` VARCHAR(250) NOT NULL AFTER `is_image_download`;",
1601 29 => "ALTER TABLE `messenger_bot` CHANGE `keyword_type` `keyword_type` ENUM('reply','post-back','no match','get-started','email-quick-reply','phone-quick-reply') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'reply';",
1602 30 => "ALTER TABLE `messenger_bot_postback` CHANGE `template_for` `template_for` ENUM('reply_message','unsubscribe','resubscribe','email-quick-reply','phone-quick-reply') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;",
1603 31 => "ALTER TABLE `messenger_bot_page_info` ADD `reply_delay_time` INT NOT NULL AFTER `enbale_type_on`;",
1604 32 => "ALTER TABLE `messenger_bot_postback` ADD `template_id` INT(11) NOT NULL AFTER `template_for`;",
1605 33 => "ALTER TABLE `messenger_bot_postback` ADD `inherit_from_template` ENUM('0','1') NOT NULL AFTER `template_id`;",
1606 34 => "UPDATE `menu_child_1` SET `only_admin` = '0' WHERE `menu_child_1`.`url` = 'messenger_bot/index';"
1607
1608 );
1609 //send blank array if you does not need sidebar entry,send a blank array if your addon does not need any sql to run
1610 $this->register_addon($addon_controller_name,$sidebar,$sql,$purchase_code);
1611 }
1612
1613 public function deactivate()
1614 {
1615 $addon_controller_name=ucfirst($this->router->fetch_class()); // here addon_controller_name name is Comment [origianl file is Comment.php, put except .php]
1616 $this->db->query("DELETE FROM `modules` WHERE `modules`.`id` = 197");
1617 $this->db->query("DELETE FROM `modules` WHERE `modules`.`id` = 198");
1618 $this->db->query("DELETE FROM `modules` WHERE `modules`.`id` = 199");
1619 // only deletes add_ons,modules and menu, menu_child1 table entires and put install.txt back, it does not delete any files or custom sql
1620 $this->unregister_addon($addon_controller_name);
1621 }
1622 public function delete()
1623 {
1624 $addon_controller_name=ucfirst($this->router->fetch_class()); // here addon_controller_name name is Comment [origianl file is Comment.php, put except .php]
1625 // mysql raw query needed to run, it's an array, put each query in a seperate index, drop table/column query should have IF EXISTS
1626 $sql=array
1627 (
1628 0=>"DROP TABLE IF EXISTS `messenger_bot`;",
1629 1=>"DROP TABLE IF EXISTS `messenger_bot_config`;",
1630 2=>"DROP TABLE IF EXISTS `messenger_bot_domain_whitelist`;",
1631 3=>"DROP TABLE IF EXISTS `messenger_bot_page_info`;",
1632 4=>"DROP TABLE IF EXISTS `messenger_bot_postback`;",
1633 5=>"DROP TABLE IF EXISTS `messenger_bot_subscriber`;",
1634 6=>"DROP TABLE IF EXISTS `messenger_bot_user_info`;",
1635 7=>"DROP TABLE IF EXISTS `messenger_bot_persistent_menu`;",
1636 8=>"DELETE FROM `modules` WHERE `modules`.`id` = 199",
1637 9=>"DELETE FROM `modules` WHERE `modules`.`id` = 198",
1638 10=>"DELETE FROM `modules` WHERE `modules`.`id` = 197",
1639 11 => "DROP TABLE IF EXISTS `messenger_bot_reply_error_log`;",
1640 12 => "DROP TABLE IF EXISTS `messenger_bot_quick_reply_email`;"
1641 );
1642
1643 // deletes add_ons,modules and menu, menu_child1 table ,custom sql as well as module folder, no need to send sql or send blank array if you does not need any sql to run on delete
1644 $this->delete_addon($addon_controller_name,$sql);
1645 }
1646 //=================================BOT SETTINGS===============================
1647 public function bot_list()
1648 {
1649 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
1650 redirect('home/login_page', 'location');
1651 $data['body'] = 'bot_list';
1652 $data['page_title'] = $this->lang->line('Bot Settings');
1653 $table_name = "messenger_bot_page_info";
1654 $where['where'] = array('bot_enabled' => "1",'messenger_bot_page_info.user_id'=> $this->user_id);
1655 $join = array('messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left");
1656 $page_info = $this->basic->get_data($table_name,$where,array("messenger_bot_page_info.*","messenger_bot_user_info.name as account_name","messenger_bot_user_info.fb_id"),$join,'','','page_name asc');
1657 $error_record = $this->basic->get_data('messenger_bot_reply_error_log',array('where'=>array('user_id'=>$this->user_id)),$select=array('page_id','count(id) as total_error'),$join='',$limit='',$start=NULL,$order_by='',$group_by='page_id');
1658 $error_record_array = array();
1659 foreach($error_record as $value)
1660 {
1661 $error_record_array[$value['page_id']] = $value['total_error'];
1662 }
1663 $data['error_record'] = $error_record_array;
1664 $len_page_info = count($page_info);
1665 $data['page_info'] = $page_info;
1666 $this->_viewcontroller($data);
1667 }
1668 public function view_bot($bot_id= '0')
1669 {
1670 if($this->session->userdata('user_type') != 'Admin' && !in_array(200, $this->module_access))
1671 redirect ('home/login_page','location');
1672 if($bot_id == 0)
1673 die();
1674 $table_name = "messenger_bot";
1675 $where_bot['where'] = array('id' => $bot_id, 'status' => '1');
1676 $bot_info = $this->basic->get_data($table_name, $where_bot);
1677 if(!isset($bot_info[0]))
1678 redirect('messenger_bot/bot_list', 'location');
1679 $table_name = "messenger_bot_page_info";
1680 $where['where'] = array('bot_enabled' => "1", "messenger_bot_page_info.id"=>$bot_info[0]["page_id"]);
1681 $join = array('messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left");
1682 $page_info = $this->basic->get_data($table_name,$where, array("messenger_bot_page_info.*","messenger_bot_user_info.name as account_name","messenger_bot_user_info.fb_id"),$join);
1683 if(!isset($page_info[0]))
1684 redirect('messenger_bot/bot_list','location');
1685 $data["templates"]=$this->basic->get_enum_values("messenger_bot","template_type");
1686 $data["keyword_types"]=$this->basic->get_enum_values("messenger_bot","keyword_type");
1687 $data['body'] = 'view_bot_settings';
1688 $data['page_title'] = $this->lang->line('View Bot Settings');
1689 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
1690 $data['bot_info'] = isset($bot_info[0]) ? $bot_info[0] : array();
1691 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$bot_info[0]["page_id"])));
1692 // $postback_id_array = array();
1693 // foreach ($postback_id_list as $value) {
1694 // $postback_id_array[$value['postback_id']] = $value['postback_id']." (".$value['bot_name'].")";
1695 // }
1696 $data['postback_ids'] = $postback_id_list;
1697 $this->_viewcontroller($data);
1698 }
1699 public function edit_bot($bot_id='0')
1700 {
1701 if($this->session->userdata('user_type') != 'Admin' && !in_array(200, $this->module_access))
1702 redirect ('home/login_page','location');
1703 if($bot_id == 0)
1704 die();
1705 $table_name = "messenger_bot";
1706 $where_bot['where'] = array('id' => $bot_id, 'status' => '1');
1707 $bot_info = $this->basic->get_data($table_name, $where_bot);
1708 if(!isset($bot_info[0]))
1709 redirect('messenger_bot/bot_list', 'location');
1710 $table_name = "messenger_bot_page_info";
1711 $where['where'] = array('bot_enabled' => "1", "messenger_bot_page_info.id"=>$bot_info[0]["page_id"]);
1712 $join = array('messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left");
1713 $page_info = $this->basic->get_data($table_name,$where, array("messenger_bot_page_info.*","messenger_bot_user_info.name as account_name","messenger_bot_user_info.fb_id"),$join);
1714 if(!isset($page_info[0]))
1715 redirect('messenger_bot/bot_list','location');
1716 $data["templates"]=$this->basic->get_enum_values("messenger_bot","template_type");
1717 $data["keyword_types"]=$this->basic->get_enum_values("messenger_bot","keyword_type");
1718 $data['body'] = 'edit_bot_settings';
1719 $data['page_title'] = $this->lang->line('Edit Bot Settings');
1720 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
1721 $data['bot_info'] = isset($bot_info[0]) ? $bot_info[0] : array();
1722 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$bot_info[0]["page_id"])));
1723 $current_postbacks = array();
1724 foreach ($postback_id_list as $value) {
1725 if($value['messenger_bot_table_id'] == $bot_id)
1726 $current_postbacks[] = $value['postback_id'];
1727 }
1728 $data['postback_ids'] = $postback_id_list;
1729 $data['current_postbacks'] = $current_postbacks;
1730 $page_id=$page_info[0]['id'];// database id
1731 $postback_data=$this->basic->get_data("messenger_bot_postback",array("where"=>array("page_id"=>$page_id,"is_template"=>"1"),"or_where"=>array("messenger_bot_table_id"=>$bot_id)),'','','',$start=NULL,$order_by='template_name ASC');
1732
1733 $poption=array();
1734 foreach ($postback_data as $key => $value)
1735 {
1736 if($value["template_for"]=="unsubscribe" || $value["template_for"]=="resubscribe" || $value["template_for"]=="email-quick-reply" || $value["template_for"]=="phone-quick-reply") continue;
1737 $poption[$value["postback_id"]]=$value['template_name'].' ['.$value['postback_id'].']';
1738 }
1739 $data['poption']=$poption;
1740
1741 if($this->basic->is_exist("add_ons",array("project_id"=>16)))
1742 $data['has_broadcaster_addon'] = 1;
1743 else
1744 $data['has_broadcaster_addon'] = 0;
1745
1746 $this->_viewcontroller($data);
1747 }
1748 public function bot_settings($page_auto_id='0')
1749 {
1750 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
1751 redirect('home/login_page', 'location');
1752 if($page_auto_id==0) exit();
1753 $table_name = "messenger_bot_page_info";
1754 $where['where'] = array('bot_enabled' => "1","messenger_bot_page_info.id"=>$page_auto_id);
1755 $join = array('messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left");
1756 $page_info = $this->basic->get_data($table_name,$where,array("messenger_bot_page_info.*","messenger_bot_user_info.name as account_name","messenger_bot_user_info.fb_id"),$join);
1757 if(!isset($page_info[0]))
1758 redirect('messenger_bot/bot_list', 'location');
1759 $bot_settings=$this->basic->get_data("messenger_bot",array("where"=>array("page_id"=>$page_auto_id,"is_template"=>"0")),'','','','','bot_name asc');
1760 $data["templates"]=$this->basic->get_enum_values("messenger_bot","template_type");
1761 $data["keyword_types"]=$this->basic->get_enum_values("messenger_bot","keyword_type");
1762 $data['body'] = 'bot_settings';
1763 $data['page_title'] = $this->lang->line('Bot Settings');
1764 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
1765 $data['bot_settings'] = $bot_settings;
1766
1767 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$page_auto_id)));
1768 $data['postback_ids'] = $postback_id_list;
1769
1770 if($this->basic->is_exist("add_ons",array("project_id"=>16)))
1771 $data['has_broadcaster_addon'] = 1;
1772 else
1773 $data['has_broadcaster_addon'] = 0;
1774 $this->_viewcontroller($data);
1775 }
1776 public function get_postback()
1777 {
1778 if(!$_POST) exit();
1779 $page_id=$this->input->post('page_id');// database id
1780 $order_by=$this->input->post('order_by');
1781 if($order_by=="") $order_by="id DESC";
1782 else $order_by=$order_by." ASC";
1783 $postback_data=$this->basic->get_data("messenger_bot_postback",array("where"=>array("page_id"=>$page_id,"is_template"=>"1")),'','','',$start=NULL,$order_by);
1784 $push_postback="";
1785 foreach ($postback_data as $key => $value)
1786 {
1787 if($value["template_for"]=="unsubscribe" || $value["template_for"]=="resubscribe" || $value["template_for"]=="email-quick-reply" || $value["template_for"]=="phone-quick-reply") continue;
1788 $push_postback.="<option value='".$value['postback_id']."'>".$value['template_name'].' ['.$value['postback_id'].']'."</option>";
1789 }
1790 echo $push_postback;
1791 }
1792 //=================================BOT SETTINGS===============================
1793 public function edit_generate_messenger_bot()
1794 {
1795 $post=$_POST;
1796 foreach ($post as $key => $value)
1797 {
1798 $$key=$value;
1799 }
1800 // $template_type = trim($template_type);
1801 $insert_data = array();
1802 $insert_data['bot_name'] = $bot_name;
1803 $insert_data['fb_page_id'] = $page_id;
1804 $insert_data['keywords'] = trim($keywords_list);
1805 $insert_data['page_id'] = $page_table_id;
1806 // $insert_data['template_type'] = $template_type;
1807 $insert_data['keyword_type'] = $keyword_type;
1808 if($keyword_type == 'post-back')
1809 $insert_data['postback_id'] = implode(',', $keywordtype_postback_id);
1810
1811 // $template_type = str_replace(' ', '_', $template_type);
1812 // domain white list section
1813 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token"));
1814 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
1815 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
1816 $white_listed_domain = $this->basic->get_data("messenger_bot_domain_whitelist",array("where"=>array("user_id"=>$this->user_id,"messenger_bot_user_info_id"=>$messenger_bot_user_info_id,"page_id"=>$page_table_id)),"domain");
1817 $white_listed_domain_array = array();
1818 foreach ($white_listed_domain as $value) {
1819 $white_listed_domain_array[] = $value['domain'];
1820 }
1821 $need_to_whitelist_array = array();
1822 // domain white list section
1823
1824 $postback_insert_data = array();
1825 $reply_bot = array();
1826 $bot_message = array();
1827 for ($k=1; $k <=3 ; $k++)
1828 {
1829 $template_type = 'template_type_'.$k;
1830 $template_type = $$template_type;
1831 $template_type = str_replace(' ', '_', $template_type);
1832 if($template_type == 'text')
1833 {
1834 $text_reply = 'text_reply_'.$k;
1835 $text_reply = $$text_reply;
1836 if($text_reply != '')
1837 {
1838 $reply_bot[$k]['template_type'] = $template_type;
1839 $reply_bot[$k]['text'] = $text_reply;
1840
1841 }
1842 }
1843 if($template_type == 'image')
1844 {
1845 $image_reply_field = 'image_reply_field_'.$k;
1846 $image_reply_field = $$image_reply_field;
1847 if($image_reply_field != '')
1848 {
1849 $reply_bot[$k]['template_type'] = $template_type;
1850 $reply_bot[$k]['attachment']['type'] = 'image';
1851 $reply_bot[$k]['attachment']['payload']['url'] = $image_reply_field;
1852 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
1853 }
1854 }
1855 if($template_type == 'audio')
1856 {
1857 $audio_reply_field = 'audio_reply_field_'.$k;
1858 $audio_reply_field = $$audio_reply_field;
1859 if($audio_reply_field != '')
1860 {
1861 $reply_bot[$k]['template_type'] = $template_type;
1862 $reply_bot[$k]['attachment']['type'] = 'audio';
1863 $reply_bot[$k]['attachment']['payload']['url'] = $audio_reply_field;
1864 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
1865 }
1866
1867 }
1868 if($template_type == 'video')
1869 {
1870 $video_reply_field = 'video_reply_field_'.$k;
1871 $video_reply_field = $$video_reply_field;
1872 if($video_reply_field != '')
1873 {
1874 $reply_bot[$k]['template_type'] = $template_type;
1875 $reply_bot[$k]['attachment']['type'] = 'video';
1876 $reply_bot[$k]['attachment']['payload']['url'] = $video_reply_field;
1877 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
1878 }
1879 }
1880 if($template_type == 'file')
1881 {
1882 $file_reply_field = 'file_reply_field_'.$k;
1883 $file_reply_field = $$file_reply_field;
1884 if($file_reply_field != '')
1885 {
1886 $reply_bot[$k]['template_type'] = $template_type;
1887 $reply_bot[$k]['attachment']['type'] = 'file';
1888 $reply_bot[$k]['attachment']['payload']['url'] = $file_reply_field;
1889 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
1890 }
1891 }
1892 if($template_type == 'text_with_buttons')
1893 {
1894 $text_with_buttons_input = 'text_with_buttons_input_'.$k;
1895 $text_with_buttons_input = $$text_with_buttons_input;
1896 $reply_bot[$k]['template_type'] = $template_type;
1897 $reply_bot[$k]['attachment']['type'] = 'template';
1898 $reply_bot[$k]['attachment']['payload']['template_type'] = 'button';
1899 $reply_bot[$k]['attachment']['payload']['text'] = $text_with_buttons_input;
1900 for ($i=1; $i <= 3 ; $i++)
1901 {
1902 $button_text = 'text_with_buttons_text_'.$i.'_'.$k;
1903 $button_text = $$button_text;
1904 $button_type = 'text_with_button_type_'.$i.'_'.$k;
1905 $button_type = $$button_type;
1906 $button_postback_id = 'text_with_button_post_id_'.$i.'_'.$k;
1907 $button_postback_id = $$button_postback_id;
1908 $button_web_url = 'text_with_button_web_url_'.$i.'_'.$k;
1909 $button_web_url = $$button_web_url;
1910 $button_call_us = 'text_with_button_call_us_'.$i.'_'.$k;
1911 $button_call_us = $$button_call_us;
1912 if($button_type == 'post_back')
1913 {
1914 if($button_text != '' && $button_type != '' && $button_postback_id != '')
1915 {
1916 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'postback';
1917 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_postback_id;
1918 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
1919 $single_postback_insert_data = array();
1920 $single_postback_insert_data['user_id'] = $this->user_id;
1921 $single_postback_insert_data['postback_id'] = $button_postback_id;
1922 $single_postback_insert_data['page_id'] = $page_table_id;
1923 $single_postback_insert_data['bot_name'] = $bot_name;
1924 $postback_insert_data[] = $single_postback_insert_data;
1925 }
1926 }
1927 if($button_type == 'web_url')
1928 {
1929 if($button_text != '' && $button_type != '' && $button_web_url != '')
1930 {
1931 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'web_url';
1932 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['url'] = $button_web_url;
1933 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
1934 if(!in_array($button_web_url, $white_listed_domain_array))
1935 {
1936 $need_to_whitelist_array[] = $button_web_url;
1937 }
1938 }
1939 }
1940 if($button_type == 'phone_number')
1941 {
1942 if($button_text != '' && $button_type != '' && $button_call_us != '')
1943 {
1944 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'phone_number';
1945 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_call_us;
1946 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
1947 }
1948 }
1949 }
1950 }
1951
1952 if($template_type == 'quick_reply')
1953 {
1954 $quick_reply_text = 'quick_reply_text_'.$k;
1955 $quick_reply_text = $$quick_reply_text;
1956 $reply_bot[$k]['template_type'] = $template_type;
1957 $reply_bot[$k]['text'] = $quick_reply_text;
1958 for ($i=1; $i <= 3 ; $i++)
1959 {
1960 $button_text = 'quick_reply_button_text_'.$i.'_'.$k;
1961 $button_text = $$button_text;
1962 $button_postback_id = 'quick_reply_post_id_'.$i.'_'.$k;
1963 $button_postback_id = $$button_postback_id;
1964 $button_type = 'quick_reply_button_type_'.$i.'_'.$k;
1965 $button_type = $$button_type;
1966 if($button_type=='post_back')
1967 {
1968 if($button_text != '' && $button_postback_id != '')
1969 {
1970 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'text';
1971 $reply_bot[$k]['quick_replies'][$i-1]['payload'] = $button_postback_id;
1972 $reply_bot[$k]['quick_replies'][$i-1]['title'] = $button_text;
1973 $single_postback_insert_data = array();
1974 $single_postback_insert_data['user_id'] = $this->user_id;
1975 $single_postback_insert_data['postback_id'] = $button_postback_id;
1976 $single_postback_insert_data['page_id'] = $page_table_id;
1977 $single_postback_insert_data['bot_name'] = $bot_name;
1978 $postback_insert_data[] = $single_postback_insert_data;
1979 }
1980 }
1981 if($button_type=='phone_number')
1982 {
1983 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_phone_number';
1984 }
1985 if($button_type=='user_email')
1986 {
1987 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_email';
1988 }
1989 if($button_type=='location')
1990 {
1991 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'location';
1992 }
1993
1994 }
1995 }
1996 if($template_type == 'generic_template')
1997 {
1998 $generic_template_title = 'generic_template_title_'.$k;
1999 $generic_template_title = $$generic_template_title;
2000 $generic_template_image = 'generic_template_image_'.$k;
2001 $generic_template_image = $$generic_template_image;
2002 $generic_template_subtitle = 'generic_template_subtitle_'.$k;
2003 $generic_template_subtitle = $$generic_template_subtitle;
2004 $generic_template_image_destination_link = 'generic_template_image_destination_link_'.$k;
2005 $generic_template_image_destination_link = $$generic_template_image_destination_link;
2006 $reply_bot[$k]['template_type'] = $template_type;
2007 $reply_bot[$k]['attachment']['type'] = 'template';
2008 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
2009 $reply_bot[$k]['attachment']['payload']['elements'][0]['title'] = $generic_template_title;
2010 $reply_bot[$k]['attachment']['payload']['elements'][0]['image_url'] = $generic_template_image;
2011 $reply_bot[$k]['attachment']['payload']['elements'][0]['subtitle'] = $generic_template_subtitle;
2012 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['type'] = 'web_url';
2013 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['url'] = $generic_template_image_destination_link;
2014
2015 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['messenger_extensions'] = true;
2016 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['webview_height_ratio'] = 'tall';
2017 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['fallback_url'] = $generic_template_image_destination_link;
2018
2019 for ($i=1; $i <= 3 ; $i++)
2020 {
2021 $button_text = 'generic_template_button_text_'.$i.'_'.$k;
2022 $button_text = $$button_text;
2023 $button_type = 'generic_template_button_type_'.$i.'_'.$k;
2024 $button_type = $$button_type;
2025 $button_postback_id = 'generic_template_button_post_id_'.$i.'_'.$k;
2026 $button_postback_id = $$button_postback_id;
2027 $button_web_url = 'generic_template_button_web_url_'.$i.'_'.$k;
2028 $button_web_url = $$button_web_url;
2029 $button_call_us = 'generic_template_button_call_us_'.$i.'_'.$k;
2030 $button_call_us = $$button_call_us;
2031 if($button_type == 'post_back')
2032 {
2033 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2034 {
2035 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'postback';
2036 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_postback_id;
2037 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2038 $single_postback_insert_data = array();
2039 $single_postback_insert_data['user_id'] = $this->user_id;
2040 $single_postback_insert_data['postback_id'] = $button_postback_id;
2041 $single_postback_insert_data['page_id'] = $page_table_id;
2042 $single_postback_insert_data['bot_name'] = $bot_name;
2043 $postback_insert_data[] = $single_postback_insert_data;
2044 }
2045 }
2046 if($button_type == 'web_url')
2047 {
2048 if($button_text != '' && $button_type != '' && $button_web_url != '')
2049 {
2050 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'web_url';
2051 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['url'] = $button_web_url;
2052 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2053 if(!in_array($button_web_url, $white_listed_domain_array))
2054 {
2055 $need_to_whitelist_array[] = $button_web_url;
2056 }
2057 }
2058 }
2059 if($button_type == 'phone_number')
2060 {
2061 if($button_text != '' && $button_type != '' && $button_call_us != '')
2062 {
2063 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'phone_number';
2064 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_call_us;
2065 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2066 }
2067 }
2068 }
2069 }
2070 if($template_type == 'carousel')
2071 {
2072 $reply_bot[$k]['template_type'] = $template_type;
2073 $reply_bot[$k]['attachment']['type'] = 'template';
2074 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
2075 for ($j=1; $j <=5 ; $j++)
2076 {
2077 $carousel_image = 'carousel_image_'.$j.'_'.$k;
2078 if($$carousel_image == '') continue;
2079 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['image_url'] = $$carousel_image;
2080 $carousel_title = 'carousel_title_'.$j.'_'.$k;
2081 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['title'] = $$carousel_title;
2082 $carousel_subtitle = 'carousel_subtitle_'.$j.'_'.$k;
2083 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['subtitle'] = $$carousel_subtitle;
2084 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['type'] = 'web_url';
2085 $carousel_image_destination_link = 'carousel_image_destination_link_'.$j.'_'.$k;
2086 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['url'] = $$carousel_image_destination_link;
2087 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['messenger_extensions'] = true;
2088 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['webview_height_ratio'] = 'tall';
2089 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['fallback_url'] = $$carousel_image_destination_link;
2090
2091 for ($i=1; $i <= 3 ; $i++)
2092 {
2093 $button_text = 'carousel_button_text_'.$j."_".$i.'_'.$k;
2094 $button_text = $$button_text;
2095 $button_type = 'carousel_button_type_'.$j."_".$i.'_'.$k;
2096 $button_type = $$button_type;
2097 $button_postback_id = 'carousel_button_post_id_'.$j."_".$i.'_'.$k;
2098 $button_postback_id = $$button_postback_id;
2099 $button_web_url = 'carousel_button_web_url_'.$j."_".$i.'_'.$k;
2100 $button_web_url = $$button_web_url;
2101 $button_call_us = 'carousel_button_call_us_'.$j."_".$i.'_'.$k;
2102 $button_call_us = $$button_call_us;
2103 if($button_type == 'post_back')
2104 {
2105 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2106 {
2107 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'postback';
2108 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_postback_id;
2109 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2110 $single_postback_insert_data = array();
2111 $single_postback_insert_data['user_id'] = $this->user_id;
2112 $single_postback_insert_data['postback_id'] = $button_postback_id;
2113 $single_postback_insert_data['page_id'] = $page_table_id;
2114 $single_postback_insert_data['bot_name'] = $bot_name;
2115 $postback_insert_data[] = $single_postback_insert_data;
2116 }
2117 }
2118 if($button_type == 'web_url')
2119 {
2120 if($button_text != '' && $button_type != '' && $button_web_url != '')
2121 {
2122 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'web_url';
2123 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['url'] = $button_web_url;
2124 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2125 if(!in_array($button_web_url, $white_listed_domain_array))
2126 {
2127 $need_to_whitelist_array[] = $button_web_url;
2128 }
2129 }
2130 }
2131 if($button_type == 'phone_number')
2132 {
2133 if($button_text != '' && $button_type != '' && $button_call_us != '')
2134 {
2135 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'phone_number';
2136 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_call_us;
2137 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2138 }
2139 }
2140 }
2141 }
2142 }
2143 if(isset($reply_bot[$k]))
2144 {
2145 $bot_message[$k]['recipient'] = array('id'=>'replace_id');
2146 $bot_message[$k]['message'] = $reply_bot[$k];
2147 }
2148 }
2149
2150 $reply_bot_filtered = array();
2151 $m=0;
2152 foreach ($bot_message as $value) {
2153 $m++;
2154 $reply_bot_filtered[$m] = $value;
2155 }
2156
2157 // domain white list section start
2158 $this->load->library("messenger_bot_login");
2159 $domain_whitelist_insert_data = array();
2160 foreach($need_to_whitelist_array as $value)
2161 {
2162 $response=$this->messenger_bot_login->domain_whitelist($page_access_token,$value);
2163 if($response['status'] != '0')
2164 {
2165 $temp_data = array();
2166 $temp_data['user_id'] = $this->user_id;
2167 $temp_data['messenger_bot_user_info_id'] = $messenger_bot_user_info_id;
2168 $temp_data['page_id'] = $page_table_id;
2169 $temp_data['domain'] = $value;
2170 $temp_data['created_at'] = date("Y-m-d H:i:s");
2171 $domain_whitelist_insert_data[] = $temp_data;
2172 }
2173 }
2174 if(!empty($domain_whitelist_insert_data))
2175 $this->db->insert_batch('messenger_bot_domain_whitelist',$domain_whitelist_insert_data);
2176 // domain white list section end
2177
2178 $insert_data['message'] = json_encode($reply_bot_filtered,true);
2179 $insert_data['user_id'] = $this->user_id;
2180 $this->basic->update_data('messenger_bot',array("id" => $id),$insert_data);
2181 // $this->basic->delete_data('messenger_bot_postback',array('messenger_bot_table_id'=> $id));
2182 $messenger_bot_table_id = $id;
2183
2184 $existing_postback_ids_array = array();
2185 $existing_postback_ids = $this->basic->get_data('messenger_bot_postback',array('where'=>array('messenger_bot_table_id'=>$messenger_bot_table_id)),array('postback_id'));
2186 if(!empty($existing_postback_ids))
2187 {
2188 foreach($existing_postback_ids as $value)
2189 {
2190 array_push($existing_postback_ids_array, strtoupper($value['postback_id']));
2191 }
2192 }
2193
2194 $postback_insert_data_modified = array();
2195 $m=0;
2196 foreach($postback_insert_data as $value)
2197 {
2198 if(in_array(strtoupper($value['postback_id']), $existing_postback_ids_array)) continue;
2199 $postback_insert_data_modified[$m]['user_id'] = $value['user_id'];
2200 $postback_insert_data_modified[$m]['postback_id'] = $value['postback_id'];
2201 $postback_insert_data_modified[$m]['page_id'] = $value['page_id'];
2202 $postback_insert_data_modified[$m]['bot_name'] = $value['bot_name'];
2203 $postback_insert_data_modified[$m]['messenger_bot_table_id'] = $messenger_bot_table_id;
2204 $m++;
2205 }
2206
2207 if($keyword_type == 'post-back' && !empty($keywordtype_postback_id))
2208 {
2209 $this->db->where_in("postback_id", $keywordtype_postback_id);
2210 $this->db->update('messenger_bot_postback', array('use_status' => '1'));
2211 }
2212
2213 // if(!empty($postback_insert_data_modified))
2214 // $this->db->insert_batch('messenger_bot_postback',$postback_insert_data_modified);
2215
2216 $this->session->set_flashdata('bot_update_success',1);
2217 echo json_encode(array("status" => "1", "message" =>$this->lang->line("bot settings has been updated successfully.")));
2218
2219 }
2220 public function ajax_generate_messenger_bot()
2221 {
2222 $post=$_POST;
2223 foreach ($post as $key => $value)
2224 {
2225 $$key=$value;
2226 }
2227 // $template_type = trim($template_type);
2228 $insert_data = array();
2229 $insert_data['bot_name'] = $bot_name;
2230 $insert_data['fb_page_id'] = $page_id;
2231 $insert_data['keywords'] = trim($keywords_list);
2232 $insert_data['page_id'] = $page_table_id;
2233 // $insert_data['template_type'] = $template_type;
2234 $insert_data['keyword_type'] = $keyword_type;
2235 if($keyword_type == 'post-back')
2236 $insert_data['postback_id'] = implode(',', $keywordtype_postback_id);
2237
2238 // $template_type = str_replace(' ', '_', $template_type);
2239 // domain white list section
2240 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token"));
2241 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
2242 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
2243 $white_listed_domain = $this->basic->get_data("messenger_bot_domain_whitelist",array("where"=>array("user_id"=>$this->user_id,"messenger_bot_user_info_id"=>$messenger_bot_user_info_id,"page_id"=>$page_table_id)),"domain");
2244 $white_listed_domain_array = array();
2245 foreach ($white_listed_domain as $value) {
2246 $white_listed_domain_array[] = $value['domain'];
2247 }
2248 $need_to_whitelist_array = array();
2249 // domain white list section
2250
2251 $postback_insert_data = array();
2252 $reply_bot = array();
2253 $bot_message = array();
2254 for ($k=1; $k <=3 ; $k++)
2255 {
2256 $template_type = 'template_type_'.$k;
2257 $template_type = $$template_type;
2258 // $insert_data['template_type'] = $template_type;
2259 $template_type = str_replace(' ', '_', $template_type);
2260
2261 if($template_type == 'text')
2262 {
2263 $text_reply = 'text_reply_'.$k;
2264 $text_reply = $$text_reply;
2265 if($text_reply != '')
2266 {
2267 $reply_bot[$k]['template_type'] = $template_type;
2268 $reply_bot[$k]['text'] = $text_reply;
2269
2270 }
2271 }
2272 if($template_type == 'image')
2273 {
2274 $image_reply_field = 'image_reply_field_'.$k;
2275 $image_reply_field = $$image_reply_field;
2276 if($image_reply_field != '')
2277 {
2278 $reply_bot[$k]['template_type'] = $template_type;
2279 $reply_bot[$k]['attachment']['type'] = 'image';
2280 $reply_bot[$k]['attachment']['payload']['url'] = $image_reply_field;
2281 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2282 }
2283 }
2284 if($template_type == 'audio')
2285 {
2286 $audio_reply_field = 'audio_reply_field_'.$k;
2287 $audio_reply_field = $$audio_reply_field;
2288 if($audio_reply_field != '')
2289 {
2290 $reply_bot[$k]['template_type'] = $template_type;
2291 $reply_bot[$k]['attachment']['type'] = 'audio';
2292 $reply_bot[$k]['attachment']['payload']['url'] = $audio_reply_field;
2293 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2294 }
2295
2296 }
2297 if($template_type == 'video')
2298 {
2299 $video_reply_field = 'video_reply_field_'.$k;
2300 $video_reply_field = $$video_reply_field;
2301 if($video_reply_field != '')
2302 {
2303 $reply_bot[$k]['template_type'] = $template_type;
2304 $reply_bot[$k]['attachment']['type'] = 'video';
2305 $reply_bot[$k]['attachment']['payload']['url'] = $video_reply_field;
2306 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2307 }
2308 }
2309 if($template_type == 'file')
2310 {
2311 $file_reply_field = 'file_reply_field_'.$k;
2312 $file_reply_field = $$file_reply_field;
2313 if($file_reply_field != '')
2314 {
2315 $reply_bot[$k]['template_type'] = $template_type;
2316 $reply_bot[$k]['attachment']['type'] = 'file';
2317 $reply_bot[$k]['attachment']['payload']['url'] = $file_reply_field;
2318 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2319 }
2320 }
2321 if($template_type == 'text_with_buttons')
2322 {
2323 $text_with_buttons_input = 'text_with_buttons_input_'.$k;
2324 $text_with_buttons_input = $$text_with_buttons_input;
2325 $reply_bot[$k]['template_type'] = $template_type;
2326 $reply_bot[$k]['attachment']['type'] = 'template';
2327 $reply_bot[$k]['attachment']['payload']['template_type'] = 'button';
2328 $reply_bot[$k]['attachment']['payload']['text'] = $text_with_buttons_input;
2329 for ($i=1; $i <= 3 ; $i++)
2330 {
2331 $button_text = 'text_with_buttons_text_'.$i.'_'.$k;
2332 $button_text = $$button_text;
2333 $button_type = 'text_with_button_type_'.$i.'_'.$k;
2334 $button_type = $$button_type;
2335 $button_postback_id = 'text_with_button_post_id_'.$i.'_'.$k;
2336 $button_postback_id = $$button_postback_id;
2337 $button_web_url = 'text_with_button_web_url_'.$i.'_'.$k;
2338 $button_web_url = $$button_web_url;
2339 $button_call_us = 'text_with_button_call_us_'.$i.'_'.$k;
2340 $button_call_us = $$button_call_us;
2341 if($button_type == 'post_back')
2342 {
2343 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2344 {
2345 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'postback';
2346 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_postback_id;
2347 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2348 $single_postback_insert_data = array();
2349 $single_postback_insert_data['user_id'] = $this->user_id;
2350 $single_postback_insert_data['postback_id'] = $button_postback_id;
2351 $single_postback_insert_data['page_id'] = $page_table_id;
2352 $single_postback_insert_data['bot_name'] = $bot_name;
2353 $postback_insert_data[] = $single_postback_insert_data;
2354 }
2355 }
2356 if($button_type == 'web_url')
2357 {
2358 if($button_text != '' && $button_type != '' && $button_web_url != '')
2359 {
2360 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'web_url';
2361 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['url'] = $button_web_url;
2362 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2363 if(!in_array($button_web_url, $white_listed_domain_array))
2364 {
2365 $need_to_whitelist_array[] = $button_web_url;
2366 }
2367 }
2368 }
2369 if($button_type == 'phone_number')
2370 {
2371 if($button_text != '' && $button_type != '' && $button_call_us != '')
2372 {
2373 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'phone_number';
2374 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_call_us;
2375 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2376 }
2377 }
2378 }
2379 }
2380 if($template_type == 'quick_reply')
2381 {
2382 $quick_reply_text = 'quick_reply_text_'.$k;
2383 $quick_reply_text = $$quick_reply_text;
2384 $reply_bot[$k]['template_type'] = $template_type;
2385 $reply_bot[$k]['text'] = $quick_reply_text;
2386 for ($i=1; $i <= 3 ; $i++)
2387 {
2388 $button_text = 'quick_reply_button_text_'.$i.'_'.$k;
2389 $button_text = $$button_text;
2390 $button_postback_id = 'quick_reply_post_id_'.$i.'_'.$k;
2391 $button_postback_id = $$button_postback_id;
2392 $button_type = 'quick_reply_button_type_'.$i.'_'.$k;
2393 $button_type = $$button_type;
2394 if($button_type=='post_back')
2395 {
2396 if($button_text != '' && $button_postback_id != '')
2397 {
2398 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'text';
2399 $reply_bot[$k]['quick_replies'][$i-1]['payload'] = $button_postback_id;
2400 $reply_bot[$k]['quick_replies'][$i-1]['title'] = $button_text;
2401 $single_postback_insert_data = array();
2402 $single_postback_insert_data['user_id'] = $this->user_id;
2403 $single_postback_insert_data['postback_id'] = $button_postback_id;
2404 $single_postback_insert_data['page_id'] = $page_table_id;
2405 $single_postback_insert_data['bot_name'] = $bot_name;
2406 $postback_insert_data[] = $single_postback_insert_data;
2407 }
2408 }
2409 if($button_type=='phone_number')
2410 {
2411 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_phone_number';
2412 }
2413 if($button_type=='user_email')
2414 {
2415 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_email';
2416 }
2417 if($button_type=='location')
2418 {
2419 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'location';
2420 }
2421
2422 }
2423 }
2424
2425 if($template_type == 'generic_template')
2426 {
2427 $generic_template_title = 'generic_template_title_'.$k;
2428 $generic_template_title = $$generic_template_title;
2429 $generic_template_image = 'generic_template_image_'.$k;
2430 $generic_template_image = $$generic_template_image;
2431 $generic_template_subtitle = 'generic_template_subtitle_'.$k;
2432 $generic_template_subtitle = $$generic_template_subtitle;
2433 $generic_template_image_destination_link = 'generic_template_image_destination_link_'.$k;
2434 $generic_template_image_destination_link = $$generic_template_image_destination_link;
2435 $reply_bot[$k]['template_type'] = $template_type;
2436 $reply_bot[$k]['attachment']['type'] = 'template';
2437 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
2438 $reply_bot[$k]['attachment']['payload']['elements'][0]['title'] = $generic_template_title;
2439 $reply_bot[$k]['attachment']['payload']['elements'][0]['image_url'] = $generic_template_image;
2440 $reply_bot[$k]['attachment']['payload']['elements'][0]['subtitle'] = $generic_template_subtitle;
2441 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['type'] = 'web_url';
2442 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['url'] = $generic_template_image_destination_link;
2443
2444 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['messenger_extensions'] = true;
2445 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['webview_height_ratio'] = 'tall';
2446 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['fallback_url'] = $generic_template_image_destination_link;
2447
2448 for ($i=1; $i <= 3 ; $i++)
2449 {
2450 $button_text = 'generic_template_button_text_'.$i.'_'.$k;
2451 $button_text = $$button_text;
2452 $button_type = 'generic_template_button_type_'.$i.'_'.$k;
2453 $button_type = $$button_type;
2454 $button_postback_id = 'generic_template_button_post_id_'.$i.'_'.$k;
2455 $button_postback_id = $$button_postback_id;
2456 $button_web_url = 'generic_template_button_web_url_'.$i.'_'.$k;
2457 $button_web_url = $$button_web_url;
2458 $button_call_us = 'generic_template_button_call_us_'.$i.'_'.$k;
2459 $button_call_us = $$button_call_us;
2460 if($button_type == 'post_back')
2461 {
2462 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2463 {
2464 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'postback';
2465 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_postback_id;
2466 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2467 $single_postback_insert_data = array();
2468 $single_postback_insert_data['user_id'] = $this->user_id;
2469 $single_postback_insert_data['postback_id'] = $button_postback_id;
2470 $single_postback_insert_data['page_id'] = $page_table_id;
2471 $single_postback_insert_data['bot_name'] = $bot_name;
2472 $postback_insert_data[] = $single_postback_insert_data;
2473 }
2474 }
2475 if($button_type == 'web_url')
2476 {
2477 if($button_text != '' && $button_type != '' && $button_web_url != '')
2478 {
2479 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'web_url';
2480 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['url'] = $button_web_url;
2481 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2482 if(!in_array($button_web_url, $white_listed_domain_array))
2483 {
2484 $need_to_whitelist_array[] = $button_web_url;
2485 }
2486 }
2487 }
2488 if($button_type == 'phone_number')
2489 {
2490 if($button_text != '' && $button_type != '' && $button_call_us != '')
2491 {
2492 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'phone_number';
2493 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_call_us;
2494 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2495 }
2496 }
2497 }
2498 }
2499
2500 if($template_type == 'carousel')
2501 {
2502 $reply_bot[$k]['template_type'] = $template_type;
2503 $reply_bot[$k]['attachment']['type'] = 'template';
2504 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
2505 for ($j=1; $j <=5 ; $j++)
2506 {
2507 $carousel_image = 'carousel_image_'.$j.'_'.$k;
2508 if($$carousel_image == '') continue;
2509 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['image_url'] = $$carousel_image;
2510 $carousel_title = 'carousel_title_'.$j.'_'.$k;
2511 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['title'] = $$carousel_title;
2512 $carousel_subtitle = 'carousel_subtitle_'.$j.'_'.$k;
2513 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['subtitle'] = $$carousel_subtitle;
2514 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['type'] = 'web_url';
2515 $carousel_image_destination_link = 'carousel_image_destination_link_'.$j.'_'.$k;
2516 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['url'] = $$carousel_image_destination_link;
2517 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['messenger_extensions'] = true;
2518 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['webview_height_ratio'] = 'tall';
2519 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['fallback_url'] = $$carousel_image_destination_link;
2520
2521 for ($i=1; $i <= 3 ; $i++)
2522 {
2523 $button_text = 'carousel_button_text_'.$j."_".$i.'_'.$k;
2524 $button_text = $$button_text;
2525 $button_type = 'carousel_button_type_'.$j."_".$i.'_'.$k;
2526 $button_type = $$button_type;
2527 $button_postback_id = 'carousel_button_post_id_'.$j."_".$i.'_'.$k;
2528 $button_postback_id = $$button_postback_id;
2529 $button_web_url = 'carousel_button_web_url_'.$j."_".$i.'_'.$k;
2530 $button_web_url = $$button_web_url;
2531 $button_call_us = 'carousel_button_call_us_'.$j."_".$i.'_'.$k;
2532 $button_call_us = $$button_call_us;
2533 if($button_type == 'post_back')
2534 {
2535 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2536 {
2537 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'postback';
2538 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_postback_id;
2539 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2540 $single_postback_insert_data = array();
2541 $single_postback_insert_data['user_id'] = $this->user_id;
2542 $single_postback_insert_data['postback_id'] = $button_postback_id;
2543 $single_postback_insert_data['page_id'] = $page_table_id;
2544 $single_postback_insert_data['bot_name'] = $bot_name;
2545 $postback_insert_data[] = $single_postback_insert_data;
2546 }
2547 }
2548 if($button_type == 'web_url')
2549 {
2550 if($button_text != '' && $button_type != '' && $button_web_url != '')
2551 {
2552 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'web_url';
2553 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['url'] = $button_web_url;
2554 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2555 if(!in_array($button_web_url, $white_listed_domain_array))
2556 {
2557 $need_to_whitelist_array[] = $button_web_url;
2558 }
2559 }
2560 }
2561 if($button_type == 'phone_number')
2562 {
2563 if($button_text != '' && $button_type != '' && $button_call_us != '')
2564 {
2565 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'phone_number';
2566 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_call_us;
2567 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
2568 }
2569 }
2570 }
2571 }
2572 }
2573 if(isset($reply_bot[$k]))
2574 {
2575 $bot_message[$k]['recipient'] = array('id'=>'replace_id');
2576 $bot_message[$k]['message'] = $reply_bot[$k];
2577 }
2578
2579 }
2580
2581 $reply_bot_filtered = array();
2582 $m=0;
2583 foreach ($bot_message as $value) {
2584 $m++;
2585 $reply_bot_filtered[$m] = $value;
2586 }
2587
2588 // domain white list section start
2589 $this->load->library("messenger_bot_login");
2590 $domain_whitelist_insert_data = array();
2591 foreach($need_to_whitelist_array as $value)
2592 {
2593 $response=$this->messenger_bot_login->domain_whitelist($page_access_token,$value);
2594 if($response['status'] != '0')
2595 {
2596 $temp_data = array();
2597 $temp_data['user_id'] = $this->user_id;
2598 $temp_data['messenger_bot_user_info_id'] = $messenger_bot_user_info_id;
2599 $temp_data['page_id'] = $page_table_id;
2600 $temp_data['domain'] = $value;
2601 $temp_data['created_at'] = date("Y-m-d H:i:s");
2602 $domain_whitelist_insert_data[] = $temp_data;
2603 }
2604 }
2605 if(!empty($domain_whitelist_insert_data))
2606 $this->db->insert_batch('messenger_bot_domain_whitelist',$domain_whitelist_insert_data);
2607 // domain white list section end
2608
2609 $insert_data['message'] = json_encode($reply_bot_filtered,true);
2610 $insert_data['user_id'] = $this->user_id;
2611 $this->basic->insert_data('messenger_bot',$insert_data);
2612 $messenger_bot_table_id = $this->db->insert_id();
2613 $postback_insert_data_modified = array();
2614 $m=0;
2615 foreach($postback_insert_data as $value)
2616 {
2617 $postback_insert_data_modified[$m]['user_id'] = $value['user_id'];
2618 $postback_insert_data_modified[$m]['postback_id'] = $value['postback_id'];
2619 $postback_insert_data_modified[$m]['page_id'] = $value['page_id'];
2620 $postback_insert_data_modified[$m]['bot_name'] = $value['bot_name'];
2621 $postback_insert_data_modified[$m]['messenger_bot_table_id'] = $messenger_bot_table_id;
2622 $m++;
2623 }
2624
2625 if($keyword_type == 'post-back' && !empty($keywordtype_postback_id))
2626 {
2627 $this->db->where_in("postback_id", $keywordtype_postback_id);
2628 $this->db->update('messenger_bot_postback', array('use_status' => '1'));
2629 }
2630
2631 // if(!empty($postback_insert_data_modified))
2632 // $this->db->insert_batch('messenger_bot_postback',$postback_insert_data_modified);
2633 $this->session->set_flashdata('bot_success',1);
2634 echo json_encode(array("status" => "1", "message" =>$this->lang->line("new bot settings has been stored successfully.")));
2635
2636 }
2637 public function template_manager()
2638 {
2639 $data['body'] = 'template_manager';
2640 $data['page_title'] = $this->lang->line('Template Manager');
2641 $this->_viewcontroller($data);
2642 }
2643 public function template_manager_data()
2644 {
2645 $page = isset($_POST['page']) ? intval($_POST['page']) : 15;
2646 $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 5;
2647 $sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'messenger_bot_postback.id';
2648 $order = isset($_POST['order']) ? strval($_POST['order']) : 'DESC';
2649
2650 $page_name = trim($this->input->post("page_name", true));
2651 $postback = trim($this->input->post("postback", true));
2652 $is_searched = $this->input->post('is_searched', true);
2653 if($is_searched)
2654 {
2655 $this->session->set_userdata('template_manager_search_page_name', $page_name);
2656 $this->session->set_userdata('template_manager_search_postback', $postback);
2657 }
2658 $search_page_names = $this->session->userdata('template_manager_search_page_name');
2659 $search_postback = $this->session->userdata('template_manager_search_postback');
2660
2661 $where_simple=array();
2662 if ($search_page_names) $where_simple['page_name like '] = "%".$search_page_names."%";
2663 if ($search_postback) $where_simple['postback_id like '] = "%".$search_postback."%";
2664 $where_simple['messenger_bot_postback.user_id'] = $this->user_id;
2665 $where_simple['messenger_bot_postback.is_template'] = '1';
2666 $where_simple['messenger_bot_postback.template_for'] = 'reply_message';
2667
2668 $where = array('where'=>$where_simple);
2669 $order_by_str=$sort." ".$order;
2670 $offset = ($page-1)*$rows;
2671 $result = array();
2672 $table = "messenger_bot_postback";
2673 $join = array('messenger_bot_page_info'=>'messenger_bot_postback.page_id=messenger_bot_page_info.id,left');
2674 $select = array('messenger_bot_postback.*','page_name');
2675
2676 $info = $this->basic->get_data($table, $where, $select, $join, $limit=$rows, $start=$offset, $order_by=$order_by_str, $group_by='');
2677 $total_rows_array = $this->basic->count_row($table, $where, $count="messenger_bot_postback.id", $join);
2678 $total_result = $total_rows_array[0]['total_rows'];
2679
2680 $information = array();
2681 for($i=0;$i<count($info);$i++)
2682 {
2683 $id = $info[$i]['id'];
2684 $information[$i]['template_name'] = $info[$i]['template_name'];
2685 $information[$i]['page_name'] = $info[$i]['page_name'];
2686 $information[$i]['postback_id'] = $info[$i]['postback_id'];
2687 $information[$i]['action'] = "<a class='text-center' title='Edit this template' href='".base_url("messenger_bot/edit_template/$id")."'> <i class='fa fa-2x fa-edit'></i></a>";
2688 }
2689 echo convert_to_grid_data($information, $total_result);
2690
2691 }
2692 public function create_new_template($is_iframe="0",$default_page="")
2693 {
2694 $data['body'] = 'add_new_template';
2695 $data['page_title'] = $this->lang->line('Create new template');
2696 $data["templates"]=$this->basic->get_enum_values("messenger_bot","template_type");
2697 $data["keyword_types"]=$this->basic->get_enum_values("messenger_bot","keyword_type");
2698 $join = array('messenger_bot_user_info'=>'messenger_bot_page_info.messenger_bot_user_info_id=messenger_bot_user_info.id,left');
2699 $page_info = $this->basic->get_data('messenger_bot_page_info',array('where'=>array('messenger_bot_page_info.user_id'=>$this->user_id,'bot_enabled'=>'1')),array('messenger_bot_page_info.id','page_name','name'),$join);
2700 $page_list = array();
2701 foreach($page_info as $value)
2702 {
2703 $page_list[$value['id']] = $value['page_name']." [".$value['name']."]";
2704 }
2705 $data['page_list'] = $page_list;
2706 $data['is_iframe'] = $is_iframe;
2707 $data['default_page'] = $default_page;
2708 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id)));
2709 $data['postback_ids'] = $postback_id_list;
2710 $this->_viewcontroller($data);
2711 }
2712 public function create_template_action()
2713 {
2714 $post=$_POST;
2715 foreach ($post as $key => $value)
2716 {
2717 $$key=$value;
2718 }
2719 // $template_type = trim($template_type);
2720 $insert_data = array();
2721 $insert_data_to_bot = array();
2722 $insert_data['bot_name'] = $bot_name;
2723 $insert_data_to_bot['bot_name'] = $bot_name;
2724 $insert_data['template_name'] = $bot_name;
2725 $insert_data['postback_id'] = $template_postback_id;
2726 $insert_data_to_bot['postback_id'] = $template_postback_id;
2727 $insert_data['page_id'] = $page_table_id;
2728 $insert_data_to_bot['page_id'] = $page_table_id;
2729 $insert_data['is_template'] = '1';
2730 $insert_data_to_bot['is_template'] = '1';
2731 $insert_data['use_status'] = '1';
2732
2733 // $insert_data['template_type'] = $template_type;
2734 // $insert_data['keyword_type'] = $keyword_type;
2735 // if($keyword_type == 'post-back')
2736 // $insert_data['postback_id'] = implode(',', $keywordtype_postback_id);
2737
2738 // $template_type = str_replace(' ', '_', $template_type);
2739 // domain white list section
2740 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token","page_id"));
2741 $insert_data_to_bot['fb_page_id'] = $messenger_bot_user_info_id[0]['page_id'];
2742
2743 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
2744 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
2745 $white_listed_domain = $this->basic->get_data("messenger_bot_domain_whitelist",array("where"=>array("user_id"=>$this->user_id,"messenger_bot_user_info_id"=>$messenger_bot_user_info_id,"page_id"=>$page_table_id)),"domain");
2746
2747 $white_listed_domain_array = array();
2748 foreach ($white_listed_domain as $value) {
2749 $white_listed_domain_array[] = $value['domain'];
2750 }
2751 $need_to_whitelist_array = array();
2752 // domain white list section
2753
2754 $postback_insert_data = array();
2755 $reply_bot = array();
2756 $bot_message = array();
2757 for ($k=1; $k <=3 ; $k++)
2758 {
2759 $template_type = 'template_type_'.$k;
2760 $template_type = $$template_type;
2761 // $insert_data['template_type'] = $template_type;
2762 $template_type = str_replace(' ', '_', $template_type);
2763
2764 if($template_type == 'text')
2765 {
2766 $text_reply = 'text_reply_'.$k;
2767 $text_reply = $$text_reply;
2768 if($text_reply != '')
2769 {
2770 $reply_bot[$k]['template_type'] = $template_type;
2771 $reply_bot[$k]['text'] = $text_reply;
2772
2773 }
2774 }
2775 if($template_type == 'image')
2776 {
2777 $image_reply_field = 'image_reply_field_'.$k;
2778 $image_reply_field = $$image_reply_field;
2779 if($image_reply_field != '')
2780 {
2781 $reply_bot[$k]['template_type'] = $template_type;
2782 $reply_bot[$k]['attachment']['type'] = 'image';
2783 $reply_bot[$k]['attachment']['payload']['url'] = $image_reply_field;
2784 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2785 }
2786 }
2787 if($template_type == 'audio')
2788 {
2789 $audio_reply_field = 'audio_reply_field_'.$k;
2790 $audio_reply_field = $$audio_reply_field;
2791 if($audio_reply_field != '')
2792 {
2793 $reply_bot[$k]['template_type'] = $template_type;
2794 $reply_bot[$k]['attachment']['type'] = 'audio';
2795 $reply_bot[$k]['attachment']['payload']['url'] = $audio_reply_field;
2796 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2797 }
2798
2799 }
2800 if($template_type == 'video')
2801 {
2802 $video_reply_field = 'video_reply_field_'.$k;
2803 $video_reply_field = $$video_reply_field;
2804 if($video_reply_field != '')
2805 {
2806 $reply_bot[$k]['template_type'] = $template_type;
2807 $reply_bot[$k]['attachment']['type'] = 'video';
2808 $reply_bot[$k]['attachment']['payload']['url'] = $video_reply_field;
2809 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2810 }
2811 }
2812 if($template_type == 'file')
2813 {
2814 $file_reply_field = 'file_reply_field_'.$k;
2815 $file_reply_field = $$file_reply_field;
2816 if($file_reply_field != '')
2817 {
2818 $reply_bot[$k]['template_type'] = $template_type;
2819 $reply_bot[$k]['attachment']['type'] = 'file';
2820 $reply_bot[$k]['attachment']['payload']['url'] = $file_reply_field;
2821 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
2822 }
2823 }
2824 if($template_type == 'text_with_buttons')
2825 {
2826 $text_with_buttons_input = 'text_with_buttons_input_'.$k;
2827 $text_with_buttons_input = $$text_with_buttons_input;
2828 $reply_bot[$k]['template_type'] = $template_type;
2829 $reply_bot[$k]['attachment']['type'] = 'template';
2830 $reply_bot[$k]['attachment']['payload']['template_type'] = 'button';
2831 $reply_bot[$k]['attachment']['payload']['text'] = $text_with_buttons_input;
2832 for ($i=1; $i <= 3 ; $i++)
2833 {
2834 $button_text = 'text_with_buttons_text_'.$i.'_'.$k;
2835 $button_text = $$button_text;
2836 $button_type = 'text_with_button_type_'.$i.'_'.$k;
2837 $button_type = $$button_type;
2838 $button_postback_id = 'text_with_button_post_id_'.$i.'_'.$k;
2839 $button_postback_id = $$button_postback_id;
2840 $button_web_url = 'text_with_button_web_url_'.$i.'_'.$k;
2841 $button_web_url = $$button_web_url;
2842 $button_call_us = 'text_with_button_call_us_'.$i.'_'.$k;
2843 $button_call_us = $$button_call_us;
2844 if($button_type == 'post_back')
2845 {
2846 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2847 {
2848 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'postback';
2849 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_postback_id;
2850 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2851 $single_postback_insert_data = array();
2852 $single_postback_insert_data['user_id'] = $this->user_id;
2853 $single_postback_insert_data['postback_id'] = $button_postback_id;
2854 $single_postback_insert_data['page_id'] = $page_table_id;
2855 $single_postback_insert_data['bot_name'] = $bot_name;
2856 $postback_insert_data[] = $single_postback_insert_data;
2857 }
2858 }
2859 if($button_type == 'web_url')
2860 {
2861 if($button_text != '' && $button_type != '' && $button_web_url != '')
2862 {
2863 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'web_url';
2864 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['url'] = $button_web_url;
2865 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2866 if(!in_array($button_web_url, $white_listed_domain_array))
2867 {
2868 $need_to_whitelist_array[] = $button_web_url;
2869 }
2870 }
2871 }
2872 if($button_type == 'phone_number')
2873 {
2874 if($button_text != '' && $button_type != '' && $button_call_us != '')
2875 {
2876 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'phone_number';
2877 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_call_us;
2878 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
2879 }
2880 }
2881 }
2882 }
2883 if($template_type == 'quick_reply')
2884 {
2885 $quick_reply_text = 'quick_reply_text_'.$k;
2886 $quick_reply_text = $$quick_reply_text;
2887 $reply_bot[$k]['template_type'] = $template_type;
2888 $reply_bot[$k]['text'] = $quick_reply_text;
2889 for ($i=1; $i <= 3 ; $i++)
2890 {
2891 $button_text = 'quick_reply_button_text_'.$i.'_'.$k;
2892 $button_text = $$button_text;
2893 $button_postback_id = 'quick_reply_post_id_'.$i.'_'.$k;
2894 $button_postback_id = $$button_postback_id;
2895 $button_type = 'quick_reply_button_type_'.$i.'_'.$k;
2896 $button_type = $$button_type;
2897 if($button_type=='post_back')
2898 {
2899 if($button_text != '' && $button_postback_id != '')
2900 {
2901 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'text';
2902 $reply_bot[$k]['quick_replies'][$i-1]['payload'] = $button_postback_id;
2903 $reply_bot[$k]['quick_replies'][$i-1]['title'] = $button_text;
2904 $single_postback_insert_data = array();
2905 $single_postback_insert_data['user_id'] = $this->user_id;
2906 $single_postback_insert_data['postback_id'] = $button_postback_id;
2907 $single_postback_insert_data['page_id'] = $page_table_id;
2908 $single_postback_insert_data['bot_name'] = $bot_name;
2909 $postback_insert_data[] = $single_postback_insert_data;
2910 }
2911 }
2912 if($button_type=='phone_number')
2913 {
2914 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_phone_number';
2915 }
2916 if($button_type=='user_email')
2917 {
2918 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_email';
2919 }
2920 if($button_type=='location')
2921 {
2922 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'location';
2923 }
2924
2925 }
2926 }
2927
2928 if($template_type == 'generic_template')
2929 {
2930 $generic_template_title = 'generic_template_title_'.$k;
2931 $generic_template_title = $$generic_template_title;
2932 $generic_template_image = 'generic_template_image_'.$k;
2933 $generic_template_image = $$generic_template_image;
2934 $generic_template_subtitle = 'generic_template_subtitle_'.$k;
2935 $generic_template_subtitle = $$generic_template_subtitle;
2936 $generic_template_image_destination_link = 'generic_template_image_destination_link_'.$k;
2937 $generic_template_image_destination_link = $$generic_template_image_destination_link;
2938 $reply_bot[$k]['template_type'] = $template_type;
2939 $reply_bot[$k]['attachment']['type'] = 'template';
2940 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
2941 $reply_bot[$k]['attachment']['payload']['elements'][0]['title'] = $generic_template_title;
2942 $reply_bot[$k]['attachment']['payload']['elements'][0]['image_url'] = $generic_template_image;
2943 $reply_bot[$k]['attachment']['payload']['elements'][0]['subtitle'] = $generic_template_subtitle;
2944 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['type'] = 'web_url';
2945 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['url'] = $generic_template_image_destination_link;
2946
2947 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['messenger_extensions'] = true;
2948 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['webview_height_ratio'] = 'tall';
2949 // $reply_bot['attachment']['payload']['elements'][0]['default_action']['fallback_url'] = $generic_template_image_destination_link;
2950
2951 for ($i=1; $i <= 3 ; $i++)
2952 {
2953 $button_text = 'generic_template_button_text_'.$i.'_'.$k;
2954 $button_text = $$button_text;
2955 $button_type = 'generic_template_button_type_'.$i.'_'.$k;
2956 $button_type = $$button_type;
2957 $button_postback_id = 'generic_template_button_post_id_'.$i.'_'.$k;
2958 $button_postback_id = $$button_postback_id;
2959 $button_web_url = 'generic_template_button_web_url_'.$i.'_'.$k;
2960 $button_web_url = $$button_web_url;
2961 $button_call_us = 'generic_template_button_call_us_'.$i.'_'.$k;
2962 $button_call_us = $$button_call_us;
2963 if($button_type == 'post_back')
2964 {
2965 if($button_text != '' && $button_type != '' && $button_postback_id != '')
2966 {
2967 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'postback';
2968 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_postback_id;
2969 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2970 $single_postback_insert_data = array();
2971 $single_postback_insert_data['user_id'] = $this->user_id;
2972 $single_postback_insert_data['postback_id'] = $button_postback_id;
2973 $single_postback_insert_data['page_id'] = $page_table_id;
2974 $single_postback_insert_data['bot_name'] = $bot_name;
2975 $postback_insert_data[] = $single_postback_insert_data;
2976 }
2977 }
2978 if($button_type == 'web_url')
2979 {
2980 if($button_text != '' && $button_type != '' && $button_web_url != '')
2981 {
2982 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'web_url';
2983 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['url'] = $button_web_url;
2984 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2985 if(!in_array($button_web_url, $white_listed_domain_array))
2986 {
2987 $need_to_whitelist_array[] = $button_web_url;
2988 }
2989 }
2990 }
2991 if($button_type == 'phone_number')
2992 {
2993 if($button_text != '' && $button_type != '' && $button_call_us != '')
2994 {
2995 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'phone_number';
2996 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_call_us;
2997 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
2998 }
2999 }
3000 }
3001 }
3002
3003 if($template_type == 'carousel')
3004 {
3005 $reply_bot[$k]['template_type'] = $template_type;
3006 $reply_bot[$k]['attachment']['type'] = 'template';
3007 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
3008 for ($j=1; $j <=5 ; $j++)
3009 {
3010 $carousel_image = 'carousel_image_'.$j.'_'.$k;
3011 if($$carousel_image == '') continue;
3012 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['image_url'] = $$carousel_image;
3013 $carousel_title = 'carousel_title_'.$j.'_'.$k;
3014 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['title'] = $$carousel_title;
3015 $carousel_subtitle = 'carousel_subtitle_'.$j.'_'.$k;
3016 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['subtitle'] = $$carousel_subtitle;
3017 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['type'] = 'web_url';
3018 $carousel_image_destination_link = 'carousel_image_destination_link_'.$j.'_'.$k;
3019 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['url'] = $$carousel_image_destination_link;
3020 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['messenger_extensions'] = true;
3021 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['webview_height_ratio'] = 'tall';
3022 // $reply_bot['attachment']['payload']['elements'][$j-1]['default_action']['fallback_url'] = $$carousel_image_destination_link;
3023
3024 for ($i=1; $i <= 3 ; $i++)
3025 {
3026 $button_text = 'carousel_button_text_'.$j."_".$i.'_'.$k;
3027 $button_text = $$button_text;
3028 $button_type = 'carousel_button_type_'.$j."_".$i.'_'.$k;
3029 $button_type = $$button_type;
3030 $button_postback_id = 'carousel_button_post_id_'.$j."_".$i.'_'.$k;
3031 $button_postback_id = $$button_postback_id;
3032 $button_web_url = 'carousel_button_web_url_'.$j."_".$i.'_'.$k;
3033 $button_web_url = $$button_web_url;
3034 $button_call_us = 'carousel_button_call_us_'.$j."_".$i.'_'.$k;
3035 $button_call_us = $$button_call_us;
3036 if($button_type == 'post_back')
3037 {
3038 if($button_text != '' && $button_type != '' && $button_postback_id != '')
3039 {
3040 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'postback';
3041 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_postback_id;
3042 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3043 $single_postback_insert_data = array();
3044 $single_postback_insert_data['user_id'] = $this->user_id;
3045 $single_postback_insert_data['postback_id'] = $button_postback_id;
3046 $single_postback_insert_data['page_id'] = $page_table_id;
3047 $single_postback_insert_data['bot_name'] = $bot_name;
3048 $postback_insert_data[] = $single_postback_insert_data;
3049 }
3050 }
3051 if($button_type == 'web_url')
3052 {
3053 if($button_text != '' && $button_type != '' && $button_web_url != '')
3054 {
3055 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'web_url';
3056 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['url'] = $button_web_url;
3057 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3058 if(!in_array($button_web_url, $white_listed_domain_array))
3059 {
3060 $need_to_whitelist_array[] = $button_web_url;
3061 }
3062 }
3063 }
3064 if($button_type == 'phone_number')
3065 {
3066 if($button_text != '' && $button_type != '' && $button_call_us != '')
3067 {
3068 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'phone_number';
3069 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_call_us;
3070 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3071 }
3072 }
3073 }
3074 }
3075 }
3076 if(isset($reply_bot[$k]))
3077 {
3078 $bot_message[$k]['recipient'] = array('id'=>'replace_id');
3079 $bot_message[$k]['message'] = $reply_bot[$k];
3080 }
3081
3082 }
3083
3084 $reply_bot_filtered = array();
3085 $m=0;
3086 foreach ($bot_message as $value) {
3087 $m++;
3088 $reply_bot_filtered[$m] = $value;
3089 }
3090
3091 // domain white list section start
3092 $this->load->library("messenger_bot_login");
3093 $domain_whitelist_insert_data = array();
3094 foreach($need_to_whitelist_array as $value)
3095 {
3096 $response=$this->messenger_bot_login->domain_whitelist($page_access_token,$value);
3097 if($response['status'] != '0')
3098 {
3099 $temp_data = array();
3100 $temp_data['user_id'] = $this->user_id;
3101 $temp_data['messenger_bot_user_info_id'] = $messenger_bot_user_info_id;
3102 $temp_data['page_id'] = $page_table_id;
3103 $temp_data['domain'] = $value;
3104 $temp_data['created_at'] = date("Y-m-d H:i:s");
3105 $domain_whitelist_insert_data[] = $temp_data;
3106 }
3107 }
3108 if(!empty($domain_whitelist_insert_data))
3109 $this->db->insert_batch('messenger_bot_domain_whitelist',$domain_whitelist_insert_data);
3110 // domain white list section end
3111
3112 $insert_data['template_jsoncode'] = json_encode($reply_bot_filtered,true);
3113 $insert_data_to_bot['message'] = json_encode($reply_bot_filtered,true);
3114 $insert_data['user_id'] = $this->user_id;
3115 $insert_data_to_bot['user_id'] = $this->user_id;
3116 $this->basic->insert_data('messenger_bot',$insert_data_to_bot);
3117 $messenger_bot_table_id = $this->db->insert_id();
3118 $insert_data['messenger_bot_table_id'] = $messenger_bot_table_id;
3119 $this->basic->insert_data('messenger_bot_postback',$insert_data);
3120 $template_id = $this->db->insert_id();
3121 $postback_insert_data_modified = array();
3122 $m=0;
3123 foreach($postback_insert_data as $value)
3124 {
3125 $postback_insert_data_modified[$m]['user_id'] = $value['user_id'];
3126 $postback_insert_data_modified[$m]['postback_id'] = $value['postback_id'];
3127 $postback_insert_data_modified[$m]['page_id'] = $value['page_id'];
3128 $postback_insert_data_modified[$m]['bot_name'] = $value['bot_name'];
3129 $postback_insert_data_modified[$m]['template_id'] = $template_id;
3130 $postback_insert_data_modified[$m]['inherit_from_template'] = '1';
3131 $m++;
3132 }
3133
3134 // if($keyword_type == 'post-back' && !empty($keywordtype_postback_id))
3135 // {
3136 // $this->db->where_in("postback_id", $keywordtype_postback_id);
3137 // $this->db->update('messenger_bot_postback', array('use_status' => '1'));
3138 // }
3139
3140 if(!empty($postback_insert_data_modified))
3141 $this->db->insert_batch('messenger_bot_postback',$postback_insert_data_modified);
3142 $this->session->set_flashdata('bot_success',1);
3143 echo json_encode(array("status" => "1", "message" =>$this->lang->line("New template has been stored successfully.")));
3144
3145 }
3146 public function edit_template($postback_table_id=0)
3147 {
3148 if($postback_table_id == 0) exit();
3149 $table_name = "messenger_bot_postback";
3150 $where_bot['where'] = array('id' => $postback_table_id, 'status' => '1');
3151 $bot_info = $this->basic->get_data($table_name, $where_bot);
3152 $data['body'] = 'edit_template';
3153 $data['page_title'] = $this->lang->line('Edit template');
3154 $data["templates"]=$this->basic->get_enum_values("messenger_bot","template_type");
3155 $data["keyword_types"]=$this->basic->get_enum_values("messenger_bot","keyword_type");
3156 $join = array('messenger_bot_user_info'=>'messenger_bot_page_info.messenger_bot_user_info_id=messenger_bot_user_info.id,left');
3157 $page_info = $this->basic->get_data('messenger_bot_page_info',array('where'=>array('messenger_bot_page_info.user_id'=>$this->user_id,'bot_enabled'=>'1')),array('messenger_bot_page_info.id','page_name','name'),$join);
3158 $page_list = array();
3159 foreach($page_info as $value)
3160 {
3161 $page_list[$value['id']] = $value['page_name']." [".$value['name']."]";
3162 }
3163 $data['page_list'] = $page_list;
3164 $data['bot_info'] = isset($bot_info[0]) ? $bot_info[0] : array();
3165 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$bot_info[0]["page_id"]),'where_not_in'=>array('UNSUBSCRIBE_QUICK_BOXER','RESUBSCRIBE_QUICK_BOXER')));
3166 $current_postbacks = array();
3167 foreach ($postback_id_list as $value) {
3168 if($value['template_id'] == $postback_table_id || $value['id'] == $postback_table_id)
3169 $current_postbacks[] = $value['postback_id'];
3170 }
3171 $data['postback_ids'] = $postback_id_list;
3172 $data['current_postbacks'] = $current_postbacks;
3173 $this->_viewcontroller($data);
3174 }
3175
3176 public function edit_template_action()
3177 {
3178 $post=$_POST;
3179 foreach ($post as $key => $value)
3180 {
3181 $$key=$value;
3182 }
3183 // $template_type = trim($template_type);
3184 $insert_data = array();
3185 $insert_data['bot_name'] = $bot_name;
3186 $insert_data['template_name'] = $bot_name;
3187 $insert_data['postback_id'] = $template_postback_id;
3188 $insert_data['page_id'] = $page_table_id;
3189 $insert_data['is_template'] = '1';
3190 // domain white list section
3191 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token"));
3192 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
3193 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
3194 $white_listed_domain = $this->basic->get_data("messenger_bot_domain_whitelist",array("where"=>array("user_id"=>$this->user_id,"messenger_bot_user_info_id"=>$messenger_bot_user_info_id,"page_id"=>$page_table_id)),"domain");
3195 $white_listed_domain_array = array();
3196 foreach ($white_listed_domain as $value) {
3197 $white_listed_domain_array[] = $value['domain'];
3198 }
3199 $need_to_whitelist_array = array();
3200 // domain white list section
3201
3202 $postback_insert_data = array();
3203 $reply_bot = array();
3204 $bot_message = array();
3205 for ($k=1; $k <=3 ; $k++)
3206 {
3207 $template_type = 'template_type_'.$k;
3208 $template_type = $$template_type;
3209 $template_type = str_replace(' ', '_', $template_type);
3210 if($template_type == 'text')
3211 {
3212 $text_reply = 'text_reply_'.$k;
3213 $text_reply = $$text_reply;
3214 if($text_reply != '')
3215 {
3216 $reply_bot[$k]['template_type'] = $template_type;
3217 $reply_bot[$k]['text'] = $text_reply;
3218
3219 }
3220 }
3221 if($template_type == 'image')
3222 {
3223 $image_reply_field = 'image_reply_field_'.$k;
3224 $image_reply_field = $$image_reply_field;
3225 if($image_reply_field != '')
3226 {
3227 $reply_bot[$k]['template_type'] = $template_type;
3228 $reply_bot[$k]['attachment']['type'] = 'image';
3229 $reply_bot[$k]['attachment']['payload']['url'] = $image_reply_field;
3230 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
3231 }
3232 }
3233 if($template_type == 'audio')
3234 {
3235 $audio_reply_field = 'audio_reply_field_'.$k;
3236 $audio_reply_field = $$audio_reply_field;
3237 if($audio_reply_field != '')
3238 {
3239 $reply_bot[$k]['template_type'] = $template_type;
3240 $reply_bot[$k]['attachment']['type'] = 'audio';
3241 $reply_bot[$k]['attachment']['payload']['url'] = $audio_reply_field;
3242 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
3243 }
3244
3245 }
3246 if($template_type == 'video')
3247 {
3248 $video_reply_field = 'video_reply_field_'.$k;
3249 $video_reply_field = $$video_reply_field;
3250 if($video_reply_field != '')
3251 {
3252 $reply_bot[$k]['template_type'] = $template_type;
3253 $reply_bot[$k]['attachment']['type'] = 'video';
3254 $reply_bot[$k]['attachment']['payload']['url'] = $video_reply_field;
3255 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
3256 }
3257 }
3258 if($template_type == 'file')
3259 {
3260 $file_reply_field = 'file_reply_field_'.$k;
3261 $file_reply_field = $$file_reply_field;
3262 if($file_reply_field != '')
3263 {
3264 $reply_bot[$k]['template_type'] = $template_type;
3265 $reply_bot[$k]['attachment']['type'] = 'file';
3266 $reply_bot[$k]['attachment']['payload']['url'] = $file_reply_field;
3267 $reply_bot[$k]['attachment']['payload']['is_reusable'] = true;
3268 }
3269 }
3270 if($template_type == 'text_with_buttons')
3271 {
3272 $text_with_buttons_input = 'text_with_buttons_input_'.$k;
3273 $text_with_buttons_input = $$text_with_buttons_input;
3274 $reply_bot[$k]['template_type'] = $template_type;
3275 $reply_bot[$k]['attachment']['type'] = 'template';
3276 $reply_bot[$k]['attachment']['payload']['template_type'] = 'button';
3277 $reply_bot[$k]['attachment']['payload']['text'] = $text_with_buttons_input;
3278 for ($i=1; $i <= 3 ; $i++)
3279 {
3280 $button_text = 'text_with_buttons_text_'.$i.'_'.$k;
3281 $button_text = $$button_text;
3282 $button_type = 'text_with_button_type_'.$i.'_'.$k;
3283 $button_type = $$button_type;
3284 $button_postback_id = 'text_with_button_post_id_'.$i.'_'.$k;
3285 $button_postback_id = $$button_postback_id;
3286 $button_web_url = 'text_with_button_web_url_'.$i.'_'.$k;
3287 $button_web_url = $$button_web_url;
3288 $button_call_us = 'text_with_button_call_us_'.$i.'_'.$k;
3289 $button_call_us = $$button_call_us;
3290 if($button_type == 'post_back')
3291 {
3292 if($button_text != '' && $button_type != '' && $button_postback_id != '')
3293 {
3294 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'postback';
3295 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_postback_id;
3296 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
3297 $single_postback_insert_data = array();
3298 $single_postback_insert_data['user_id'] = $this->user_id;
3299 $single_postback_insert_data['postback_id'] = $button_postback_id;
3300 $single_postback_insert_data['page_id'] = $page_table_id;
3301 $single_postback_insert_data['bot_name'] = $bot_name;
3302 $postback_insert_data[] = $single_postback_insert_data;
3303 }
3304 }
3305 if($button_type == 'web_url')
3306 {
3307 if($button_text != '' && $button_type != '' && $button_web_url != '')
3308 {
3309 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'web_url';
3310 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['url'] = $button_web_url;
3311 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
3312 if(!in_array($button_web_url, $white_listed_domain_array))
3313 {
3314 $need_to_whitelist_array[] = $button_web_url;
3315 }
3316 }
3317 }
3318 if($button_type == 'phone_number')
3319 {
3320 if($button_text != '' && $button_type != '' && $button_call_us != '')
3321 {
3322 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['type'] = 'phone_number';
3323 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['payload'] = $button_call_us;
3324 $reply_bot[$k]['attachment']['payload']['buttons'][$i-1]['title'] = $button_text;
3325 }
3326 }
3327 }
3328 }
3329
3330 if($template_type == 'quick_reply')
3331 {
3332 $quick_reply_text = 'quick_reply_text_'.$k;
3333 $quick_reply_text = $$quick_reply_text;
3334 $reply_bot[$k]['template_type'] = $template_type;
3335 $reply_bot[$k]['text'] = $quick_reply_text;
3336 for ($i=1; $i <= 3 ; $i++)
3337 {
3338 $button_text = 'quick_reply_button_text_'.$i.'_'.$k;
3339 $button_text = $$button_text;
3340 $button_postback_id = 'quick_reply_post_id_'.$i.'_'.$k;
3341 $button_postback_id = $$button_postback_id;
3342 $button_type = 'quick_reply_button_type_'.$i.'_'.$k;
3343 $button_type = $$button_type;
3344 if($button_type=='post_back')
3345 {
3346 if($button_text != '' && $button_postback_id != '')
3347 {
3348 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'text';
3349 $reply_bot[$k]['quick_replies'][$i-1]['payload'] = $button_postback_id;
3350 $reply_bot[$k]['quick_replies'][$i-1]['title'] = $button_text;
3351 $single_postback_insert_data = array();
3352 $single_postback_insert_data['user_id'] = $this->user_id;
3353 $single_postback_insert_data['postback_id'] = $button_postback_id;
3354 $single_postback_insert_data['page_id'] = $page_table_id;
3355 $single_postback_insert_data['bot_name'] = $bot_name;
3356 $postback_insert_data[] = $single_postback_insert_data;
3357 }
3358 }
3359 if($button_type=='phone_number')
3360 {
3361 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_phone_number';
3362 }
3363 if($button_type=='user_email')
3364 {
3365 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'user_email';
3366 }
3367 if($button_type=='location')
3368 {
3369 $reply_bot[$k]['quick_replies'][$i-1]['content_type'] = 'location';
3370 }
3371
3372 }
3373 }
3374 if($template_type == 'generic_template')
3375 {
3376 $generic_template_title = 'generic_template_title_'.$k;
3377 $generic_template_title = $$generic_template_title;
3378 $generic_template_image = 'generic_template_image_'.$k;
3379 $generic_template_image = $$generic_template_image;
3380 $generic_template_subtitle = 'generic_template_subtitle_'.$k;
3381 $generic_template_subtitle = $$generic_template_subtitle;
3382 $generic_template_image_destination_link = 'generic_template_image_destination_link_'.$k;
3383 $generic_template_image_destination_link = $$generic_template_image_destination_link;
3384 $reply_bot[$k]['template_type'] = $template_type;
3385 $reply_bot[$k]['attachment']['type'] = 'template';
3386 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
3387 $reply_bot[$k]['attachment']['payload']['elements'][0]['title'] = $generic_template_title;
3388 $reply_bot[$k]['attachment']['payload']['elements'][0]['image_url'] = $generic_template_image;
3389 $reply_bot[$k]['attachment']['payload']['elements'][0]['subtitle'] = $generic_template_subtitle;
3390 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['type'] = 'web_url';
3391 $reply_bot[$k]['attachment']['payload']['elements'][0]['default_action']['url'] = $generic_template_image_destination_link;
3392
3393 for ($i=1; $i <= 3 ; $i++)
3394 {
3395 $button_text = 'generic_template_button_text_'.$i.'_'.$k;
3396 $button_text = $$button_text;
3397 $button_type = 'generic_template_button_type_'.$i.'_'.$k;
3398 $button_type = $$button_type;
3399 $button_postback_id = 'generic_template_button_post_id_'.$i.'_'.$k;
3400 $button_postback_id = $$button_postback_id;
3401 $button_web_url = 'generic_template_button_web_url_'.$i.'_'.$k;
3402 $button_web_url = $$button_web_url;
3403 $button_call_us = 'generic_template_button_call_us_'.$i.'_'.$k;
3404 $button_call_us = $$button_call_us;
3405 if($button_type == 'post_back')
3406 {
3407 if($button_text != '' && $button_type != '' && $button_postback_id != '')
3408 {
3409 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'postback';
3410 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_postback_id;
3411 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
3412 $single_postback_insert_data = array();
3413 $single_postback_insert_data['user_id'] = $this->user_id;
3414 $single_postback_insert_data['postback_id'] = $button_postback_id;
3415 $single_postback_insert_data['page_id'] = $page_table_id;
3416 $single_postback_insert_data['bot_name'] = $bot_name;
3417 $postback_insert_data[] = $single_postback_insert_data;
3418 }
3419 }
3420 if($button_type == 'web_url')
3421 {
3422 if($button_text != '' && $button_type != '' && $button_web_url != '')
3423 {
3424 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'web_url';
3425 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['url'] = $button_web_url;
3426 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
3427 if(!in_array($button_web_url, $white_listed_domain_array))
3428 {
3429 $need_to_whitelist_array[] = $button_web_url;
3430 }
3431 }
3432 }
3433 if($button_type == 'phone_number')
3434 {
3435 if($button_text != '' && $button_type != '' && $button_call_us != '')
3436 {
3437 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['type'] = 'phone_number';
3438 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['payload'] = $button_call_us;
3439 $reply_bot[$k]['attachment']['payload']['elements'][0]['buttons'][$i-1]['title'] = $button_text;
3440 }
3441 }
3442 }
3443 }
3444 if($template_type == 'carousel')
3445 {
3446 $reply_bot[$k]['template_type'] = $template_type;
3447 $reply_bot[$k]['attachment']['type'] = 'template';
3448 $reply_bot[$k]['attachment']['payload']['template_type'] = 'generic';
3449 for ($j=1; $j <=5 ; $j++)
3450 {
3451 $carousel_image = 'carousel_image_'.$j.'_'.$k;
3452 if($$carousel_image == '') continue;
3453 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['image_url'] = $$carousel_image;
3454 $carousel_title = 'carousel_title_'.$j.'_'.$k;
3455 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['title'] = $$carousel_title;
3456 $carousel_subtitle = 'carousel_subtitle_'.$j.'_'.$k;
3457 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['subtitle'] = $$carousel_subtitle;
3458 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['type'] = 'web_url';
3459 $carousel_image_destination_link = 'carousel_image_destination_link_'.$j.'_'.$k;
3460 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['default_action']['url'] = $$carousel_image_destination_link;
3461
3462 for ($i=1; $i <= 3 ; $i++)
3463 {
3464 $button_text = 'carousel_button_text_'.$j."_".$i.'_'.$k;
3465 $button_text = $$button_text;
3466 $button_type = 'carousel_button_type_'.$j."_".$i.'_'.$k;
3467 $button_type = $$button_type;
3468 $button_postback_id = 'carousel_button_post_id_'.$j."_".$i.'_'.$k;
3469 $button_postback_id = $$button_postback_id;
3470 $button_web_url = 'carousel_button_web_url_'.$j."_".$i.'_'.$k;
3471 $button_web_url = $$button_web_url;
3472 $button_call_us = 'carousel_button_call_us_'.$j."_".$i.'_'.$k;
3473 $button_call_us = $$button_call_us;
3474 if($button_type == 'post_back')
3475 {
3476 if($button_text != '' && $button_type != '' && $button_postback_id != '')
3477 {
3478 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'postback';
3479 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_postback_id;
3480 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3481 $single_postback_insert_data = array();
3482 $single_postback_insert_data['user_id'] = $this->user_id;
3483 $single_postback_insert_data['postback_id'] = $button_postback_id;
3484 $single_postback_insert_data['page_id'] = $page_table_id;
3485 $single_postback_insert_data['bot_name'] = $bot_name;
3486 $postback_insert_data[] = $single_postback_insert_data;
3487 }
3488 }
3489 if($button_type == 'web_url')
3490 {
3491 if($button_text != '' && $button_type != '' && $button_web_url != '')
3492 {
3493 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'web_url';
3494 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['url'] = $button_web_url;
3495 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3496 if(!in_array($button_web_url, $white_listed_domain_array))
3497 {
3498 $need_to_whitelist_array[] = $button_web_url;
3499 }
3500 }
3501 }
3502 if($button_type == 'phone_number')
3503 {
3504 if($button_text != '' && $button_type != '' && $button_call_us != '')
3505 {
3506 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['type'] = 'phone_number';
3507 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['payload'] = $button_call_us;
3508 $reply_bot[$k]['attachment']['payload']['elements'][$j-1]['buttons'][$i-1]['title'] = $button_text;
3509 }
3510 }
3511 }
3512 }
3513 }
3514 if(isset($reply_bot[$k]))
3515 {
3516 $bot_message[$k]['recipient'] = array('id'=>'replace_id');
3517 $bot_message[$k]['message'] = $reply_bot[$k];
3518 }
3519 }
3520
3521 $reply_bot_filtered = array();
3522 $m=0;
3523 foreach ($bot_message as $value) {
3524 $m++;
3525 $reply_bot_filtered[$m] = $value;
3526 }
3527
3528 // domain white list section start
3529 $this->load->library("messenger_bot_login");
3530 $domain_whitelist_insert_data = array();
3531 foreach($need_to_whitelist_array as $value)
3532 {
3533 $response=$this->messenger_bot_login->domain_whitelist($page_access_token,$value);
3534 if($response['status'] != '0')
3535 {
3536 $temp_data = array();
3537 $temp_data['user_id'] = $this->user_id;
3538 $temp_data['messenger_bot_user_info_id'] = $messenger_bot_user_info_id;
3539 $temp_data['page_id'] = $page_table_id;
3540 $temp_data['domain'] = $value;
3541 $temp_data['created_at'] = date("Y-m-d H:i:s");
3542 $domain_whitelist_insert_data[] = $temp_data;
3543 }
3544 }
3545 if(!empty($domain_whitelist_insert_data))
3546 $this->db->insert_batch('messenger_bot_domain_whitelist',$domain_whitelist_insert_data);
3547 // domain white list section end
3548
3549 $insert_data['template_jsoncode'] = json_encode($reply_bot_filtered,true);
3550 $insert_data['user_id'] = $this->user_id;
3551 $this->basic->update_data('messenger_bot_postback',array("id" => $id),$insert_data);
3552
3553 $existing_data = $this->basic->get_data('messenger_bot_postback',array('where'=>array('id'=>$id)));
3554 $this->basic->update_data('messenger_bot',array('id'=>$existing_data[0]['messenger_bot_table_id']),array('message'=>$existing_data[0]['template_jsoncode']));
3555
3556 $messenger_bot_table_id = $existing_data[0]['messenger_bot_table_id'];
3557
3558 // $existing_postback_ids_array = array();
3559 // $existing_postback_ids = $this->basic->get_data('messenger_bot_postback',array('where'=>array('page_id'=>$page_table_id)),array('postback_id'));
3560 $this->basic->delete_data('messenger_bot_postback',array('page_id'=>$page_table_id,'template_id'=>$id,'use_status'=>'0','inherit_from_template'=>'1'));
3561 // if(!empty($existing_postback_ids))
3562 // {
3563 // foreach($existing_postback_ids as $value)
3564 // {
3565 // array_push($existing_postback_ids_array, strtoupper($value['postback_id']));
3566 // }
3567 // }
3568
3569 $postback_insert_data_modified = array();
3570 $m=0;
3571 foreach($postback_insert_data as $value)
3572 {
3573 // if(in_array(strtoupper($value['postback_id']), $existing_postback_ids_array)) continue;
3574 if($value['postback_id'] == 'UNSUBSCRIBE_QUICK_BOXER' || $value['postback_id'] == 'RESUBSCRIBE_QUICK_BOXER') continue;
3575 $postback_insert_data_modified[$m]['user_id'] = $value['user_id'];
3576 $postback_insert_data_modified[$m]['postback_id'] = $value['postback_id'];
3577 $postback_insert_data_modified[$m]['page_id'] = $value['page_id'];
3578 $postback_insert_data_modified[$m]['bot_name'] = $value['bot_name'];
3579 $postback_insert_data_modified[$m]['messenger_bot_table_id'] = $messenger_bot_table_id;
3580 $postback_insert_data_modified[$m]['inherit_from_template'] = '1';
3581 $postback_insert_data_modified[$m]['template_id'] = $id;
3582 $m++;
3583 }
3584
3585 // if($keyword_type == 'post-back' && !empty($keywordtype_postback_id))
3586 // {
3587 // $this->db->where_in("postback_id", $keywordtype_postback_id);
3588 // $this->db->update('messenger_bot_postback', array('use_status' => '1'));
3589 // }
3590
3591 if(!empty($postback_insert_data_modified))
3592 $this->db->insert_batch('messenger_bot_postback',$postback_insert_data_modified);
3593
3594 $this->session->set_flashdata('bot_update_success',1);
3595 echo json_encode(array("status" => "1", "message" =>$this->lang->line("Template been updated successfully.")));
3596
3597 }
3598
3599 public function upload_image_only()
3600 {
3601 if ($_SERVER['REQUEST_METHOD'] === 'GET') exit();
3602 $ret=array();
3603 $folder_path = FCPATH."upload/image";
3604 if (!file_exists($folder_path)) {
3605 mkdir($folder_path, 0777, true);
3606 }
3607 $output_dir = FCPATH."upload/image/".$this->user_id;
3608 if (!file_exists($output_dir)) {
3609 mkdir($output_dir, 0777, true);
3610 }
3611 if (isset($_FILES["myfile"])) {
3612 $error =$_FILES["myfile"]["error"];
3613 $post_fileName =$_FILES["myfile"]["name"];
3614 $post_fileName_array=explode(".", $post_fileName);
3615 $ext=array_pop($post_fileName_array);
3616 $filename=implode('.', $post_fileName_array);
3617 $filename="image_".$this->user_id."_".time().substr(uniqid(mt_rand(), true), 0, 6).".".$ext;
3618 $allow=".jpg,.jpeg,.png,.gif";
3619 $allow=str_replace('.', '', $allow);
3620 $allow=explode(',', $allow);
3621 if(!in_array(strtolower($ext), $allow))
3622 {
3623 echo json_encode("Are you kidding???");
3624 exit();
3625 }
3626
3627 move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir.'/'.$filename);
3628 $ret[]= $filename;
3629 echo json_encode($filename);
3630 }
3631 }
3632
3633 public function delete_uploaded_file() // deletes the uploaded video to upload another one
3634 {
3635 if(!$_POST) exit();
3636 $output_dir = FCPATH."upload/image/".$this->user_id."/";
3637 if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
3638 {
3639 $fileName =$_POST['name'];
3640 $fileName=str_replace("..",".",$fileName); //required. if somebody is trying parent folder files
3641 $filePath = $output_dir. $fileName;
3642 if (file_exists($filePath))
3643 {
3644 unlink($filePath);
3645 }
3646 }
3647 }
3648 public function upload_live_video()
3649 {
3650 if ($_SERVER['REQUEST_METHOD'] === 'GET') exit();
3651 $ret=array();
3652 $output_dir = FCPATH."upload/video";
3653 $folder_path = FCPATH."upload/video";
3654 if (!file_exists($folder_path)) {
3655 mkdir($folder_path, 0777, true);
3656 }
3657 if (isset($_FILES["myfile"])) {
3658 $error =$_FILES["myfile"]["error"];
3659 $post_fileName =$_FILES["myfile"]["name"];
3660 $post_fileName_array=explode(".", $post_fileName);
3661 $ext=array_pop($post_fileName_array);
3662 $filename=implode('.', $post_fileName_array);
3663 $filename="video_".$this->user_id."_".time().substr(uniqid(mt_rand(), true), 0, 6).".".$ext;
3664 $allow=".mov,.mpeg4,.mp4,.avi,.wmv,.mpegps,.flv,.3gpp,.webm";
3665 $allow=str_replace('.', '', $allow);
3666 $allow=explode(',', $allow);
3667 if(!in_array(strtolower($ext), $allow))
3668 {
3669 echo json_encode("Are you kidding???");
3670 exit();
3671 }
3672 move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir.'/'.$filename);
3673 $ret[]= $filename;
3674 $this->session->set_userdata("go_live_video_file_path_name", $output_dir.'/'.$filename);
3675 $this->session->set_userdata("go_live_video_filename", $filename);
3676 echo json_encode($filename);
3677 }
3678 }
3679
3680 public function delete_uploaded_live_file() // deletes the uploaded video to upload another one
3681 {
3682 if(!$_POST) exit();
3683 $output_dir = FCPATH."upload/video/";
3684 if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
3685 {
3686 $fileName =$_POST['name'];
3687 $fileName=str_replace("..",".",$fileName); //required. if somebody is trying parent folder files
3688 $filePath = $output_dir. $fileName;
3689 if (file_exists($filePath))
3690 {
3691 unlink($filePath);
3692 }
3693 }
3694 }
3695 // audio/pdf/doc file upload section
3696 public function upload_audio_file()
3697 {
3698 if ($_SERVER['REQUEST_METHOD'] === 'GET') exit();
3699 $ret=array();
3700 $output_dir = FCPATH."upload/audio";
3701 $folder_path = FCPATH."upload/audio";
3702 if (!file_exists($folder_path)) {
3703 mkdir($folder_path, 0777, true);
3704 }
3705 if (isset($_FILES["myfile"])) {
3706 $error =$_FILES["myfile"]["error"];
3707 $post_fileName =$_FILES["myfile"]["name"];
3708 $post_fileName_array=explode(".", $post_fileName);
3709 $ext=array_pop($post_fileName_array);
3710 $filename=implode('.', $post_fileName_array);
3711 $filename="audio_".$this->user_id."_".time().substr(uniqid(mt_rand(), true), 0, 6).".".$ext;
3712 $allow=".amr,.mp3,.wav,.WAV,.MP3,.AMR";
3713 $allow=str_replace('.', '', $allow);
3714 $allow=explode(',', $allow);
3715 if(!in_array(strtolower($ext), $allow))
3716 {
3717 echo json_encode("Are you kidding???");
3718 exit();
3719 }
3720 move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir.'/'.$filename);
3721 $ret[]= $filename;
3722 $this->session->set_userdata("go_live_video_file_path_name", $output_dir.'/'.$filename);
3723 $this->session->set_userdata("go_live_video_filename", $filename);
3724 echo json_encode($filename);
3725 }
3726 }
3727
3728 public function delete_audio_file() // deletes the uploaded video to upload another one
3729 {
3730 if(!$_POST) exit();
3731 $output_dir = FCPATH."upload/audio/";
3732 if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
3733 {
3734 $fileName =$_POST['name'];
3735 $fileName=str_replace("..",".",$fileName); //required. if somebody is trying parent folder files
3736 $filePath = $output_dir. $fileName;
3737 if (file_exists($filePath))
3738 {
3739 unlink($filePath);
3740 }
3741 }
3742 }
3743
3744 public function upload_general_file()
3745 {
3746 if ($_SERVER['REQUEST_METHOD'] === 'GET') exit();
3747 $ret=array();
3748 $output_dir = FCPATH."upload/file";
3749 $folder_path = FCPATH."upload/file";
3750 if (!file_exists($folder_path)) {
3751 mkdir($folder_path, 0777, true);
3752 }
3753 if (isset($_FILES["myfile"])) {
3754 $error =$_FILES["myfile"]["error"];
3755 $post_fileName =$_FILES["myfile"]["name"];
3756 $post_fileName_array=explode(".", $post_fileName);
3757 $ext=array_pop($post_fileName_array);
3758 $filename=implode('.', $post_fileName_array);
3759 $filename="file_".$this->user_id."_".time().substr(uniqid(mt_rand(), true), 0, 6).".".$ext;
3760 $allow=".doc,.docx,.pdf,.txt,.ppt,.pptx,.xls,.xlsx";
3761 $allow=str_replace('.', '', $allow);
3762 $allow=explode(',', $allow);
3763 if(!in_array(strtolower($ext), $allow))
3764 {
3765 echo json_encode("Are you kidding???");
3766 exit();
3767 }
3768 move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir.'/'.$filename);
3769 $ret[]= $filename;
3770 $this->session->set_userdata("go_live_video_file_path_name", $output_dir.'/'.$filename);
3771 $this->session->set_userdata("go_live_video_filename", $filename);
3772 echo json_encode($filename);
3773 }
3774 }
3775
3776 public function delete_general_file() // deletes the uploaded video to upload another one
3777 {
3778 if(!$_POST) exit();
3779 $output_dir = FCPATH."upload/file/";
3780 if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
3781 {
3782 $fileName =$_POST['name'];
3783 $fileName=str_replace("..",".",$fileName); //required. if somebody is trying parent folder files
3784 $filePath = $output_dir. $fileName;
3785 if (file_exists($filePath))
3786 {
3787 unlink($filePath);
3788 }
3789 }
3790 }
3791 //===========================ENABLE DISABLE STARTED Button====================
3792 public function enable_disable_started_button()
3793 {
3794 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
3795 exit();
3796 if(!$_POST) exit();
3797 $page_id=$this->input->post('page_id');
3798 $enable_disable=$this->input->post('enable_disable');
3799 $this->load->library("messenger_bot_login");
3800 $page_data=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_id)));
3801 $page_access_token=isset($page_data[0]["page_access_token"]) ? $page_data[0]["page_access_token"] : "";
3802 if($enable_disable=='enable')
3803 {
3804 $response=$this->messenger_bot_login->add_get_started_button($page_access_token);
3805 if(!isset($response['error']))
3806 $this->basic->update_data("messenger_bot_page_info",array("id"=>$page_id),array("started_button_enabled"=>"1"));
3807 //$response=array('success'=>1,'status'=>'Disable your started Button');
3808 }
3809 else
3810 {
3811 $response=$this->messenger_bot_login->delete_get_started_button($page_access_token);
3812 if(!isset($response['error']))
3813 $this->basic->update_data("messenger_bot_page_info",array("id"=>$page_id),array("started_button_enabled"=>"0"));
3814
3815 //$response=array('success'=>1,'status'=>'Enable your started Button');
3816 }
3817 echo json_encode($response);
3818 }
3819 public function enable_disable_mark_seen()
3820 {
3821 if(!$_POST) exit();
3822 $table_id=$this->input->post('table_id');
3823 $enable_disable=$this->input->post('enable_disable');
3824 $this->basic->update_data('messenger_bot_page_info',array('id'=>$table_id),array('enable_mark_seen'=>$enable_disable));
3825 echo "success";
3826 }
3827 public function typing_on_settings()
3828 {
3829 if(!$_POST) exit();
3830 $table_id=$this->input->post('table_id');
3831 $reply_delay_time=$this->input->post('reply_delay_time');
3832 $enbale_type_on=$this->input->post('enbale_type_on');
3833 if($enbale_type_on=="0") $reply_delay_time=0;
3834 $this->basic->update_data('messenger_bot_page_info',array('id'=>$table_id),array('enbale_type_on'=>$enbale_type_on,'reply_delay_time'=>$reply_delay_time));
3835 }
3836
3837 public function email_list_display()
3838 {
3839 if(empty($_POST['table_id'])) {
3840 die();
3841 }
3842 $table_id = $this->input->post('table_id');
3843 $page_info = $this->basic->get_data('messenger_bot_page_info',array('where'=>array('id'=>$table_id)),array('page_id'));
3844 $email_list_info = $this->basic->get_data('messenger_bot_quick_reply_email',['where'=>['user_id'=>$this->user_id,'fb_page_id'=>$page_info[0]['page_id']]]);
3845 if(!empty($email_list_info))
3846 {
3847 $email_link=base_url("messenger_bot/edit_quick_email_reply/".$table_id.'/'.$page_info[0]['page_id']);
3848 $phone_link=base_url("messenger_bot/edit_quick_phone_reply/".$table_id.'/'.$page_info[0]['page_id']);
3849 $str = '<script>
3850 $j(document).ready(function() {
3851 $("#email_list_table").DataTable();
3852 });
3853 </script>
3854 <div class="text-center" style="margin-top: -20px !important;">
3855 <button class="btn-sm btn btn-info download_email" table_id="'.$table_id.'"><i class="fa fa-cloud-download"></i> '.$this->lang->line("Download email & phone list").'</button>
3856 <a class="btn-sm btn btn-primary" target="_BLANK" href="'.$email_link.'"><i class="fa fa-envelope"></i> '.$this->lang->line("Set Email Subscription Reply").'</a>
3857 <a class="btn-sm btn btn-info" target="_BLANK" href="'.$phone_link.'"><i class="fa fa-phone"></i> '.$this->lang->line("Set Phone Subscription Reply").'</a>
3858 </div><br>
3859 <table id="email_list_table">
3860 <thead>
3861 <tr>
3862 <th>'.$this->lang->line("First Name").'</th>
3863 <th>'.$this->lang->line("Last Name").'</th>
3864 <th>'.$this->lang->line("Email").'</th>
3865 <th>'.$this->lang->line("Phone Number").'</th>
3866 <th>'.$this->lang->line("Email Upate").'</th>
3867 <th>'.$this->lang->line("Phone Number Update").'</th>
3868 </tr>
3869 </thead>
3870 <tbody>';
3871
3872
3873 foreach($email_list_info as $value)
3874 {
3875 $email_update_time=($value['last_update_time']!="0000-00-00 00:00:00")?date("Y-m-d H:i",strtotime($value['last_update_time'])):"0000-00-00 00:00";
3876 $phone_number_update_time=($value['phone_number_last_update']!="0000-00-00 00:00:00")?date("Y-m-d H:i",strtotime($value['phone_number_last_update'])):"0000-00-00 00:00";
3877
3878 $str .= '<tr>
3879 <td>'.$value['fb_user_first_name'].'</td>
3880 <td>'.$value['fb_user_last_name'].'</td>
3881 <td>'.$value['email'].'</td>
3882 <td>'.$value['phone_number'].'</td>
3883 <td>'.$email_update_time.'</td>
3884 <td>'.$phone_number_update_time.'</td>
3885 </tr>';
3886 }
3887 $str .= '</tbody>
3888 </table>';
3889 }
3890 else
3891 {
3892 $str = "<div class='alert alert-danger text-center'>{$this->lang->line("No data to show")}</div>";
3893 }
3894 echo $str;
3895 }
3896 public function email_list_download()
3897 {
3898 if(empty($_POST['table_id'])) {
3899 die();
3900 }
3901 $table_id = $this->input->post('table_id');
3902 $page_info = $this->basic->get_data('messenger_bot_page_info',array('where'=>array('id'=>$table_id)),array('page_id','page_name'));
3903 $email_list_info = $this->basic->get_data('messenger_bot_quick_reply_email',['where'=>['user_id'=>$this->user_id,'fb_page_id'=>$page_info[0]['page_id']]]);
3904 if(empty($email_list_info))
3905 {
3906 $str = "<div class='alert alert-danger text-center'>".$this->lang->line("No data to download")."</div>";
3907 }
3908 else
3909 {
3910 $download_path=fopen("download/email_download_{$this->user_id}.csv", "w");
3911 // make output csv file unicode compatible
3912 fprintf($download_path, chr(0xEF).chr(0xBB).chr(0xBF));
3913 /**Write header in csv file***/
3914 $write_data[]="First Name";
3915 $write_data[]="Last Name";
3916 $write_data[]="Email";
3917 $write_data[]="Phone Number";
3918 $write_data[]="Page ID";
3919 $write_data[]="Paage Name";
3920 fputcsv($download_path, $write_data);
3921 foreach($email_list_info as $value)
3922 {
3923 $write_data=array();
3924 $write_data[]=$value['fb_user_first_name'];
3925 $write_data[]=$value['fb_user_last_name'];
3926 $write_data[]=$value['email'];
3927 $write_data[]=$value['phone_number'];
3928 $write_data[]=$page_info[0]['page_id'];
3929 $write_data[]=$page_info[0]['page_name'];
3930 fputcsv($download_path, $write_data);
3931 }
3932 $str = "<div class='download_box'><h2>".$this->lang->line('Your file is ready to download')."</h2>";
3933 $str .= '<i class="fa fa-2x fa-thumbs-o-up"style="color:black"></i><br><br>';
3934 $str .= "<a href='".base_url()."download/email_download_".$this->user_id.".csv"."'". "title='Download' class='btn btn-warning btn-lg' style='width:200px;'><i class='fa fa-cloud-download' style='color:white'></i> ".$this->lang->line('Download')."</a></div>";
3935 }
3936 echo $str;
3937 }
3938
3939 //=============================ENABLE DISBALE BOT==============================
3940 public function enable_disable_bot()
3941 {
3942 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
3943 exit();
3944 if(!$_POST) exit();
3945 $page_id=$this->input->post('page_id');
3946 $enable_disable=$this->input->post('enable_disable');
3947 $this->load->library("messenger_bot_login");
3948
3949 $page_data=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_id)));
3950 $fb_page_id=isset($page_data[0]["page_id"]) ? $page_data[0]["page_id"] : "";
3951 $page_access_token=isset($page_data[0]["page_access_token"]) ? $page_data[0]["page_access_token"] : "";
3952 $persistent_enabled=isset($page_data[0]["persistent_enabled"]) ? $page_data[0]["persistent_enabled"] : "0";
3953 $fb_user_id = $page_data[0]["messenger_bot_user_info_id"];
3954 $fb_user_info = $this->basic->get_data('messenger_bot_user_info',array('where'=>array('id'=>$fb_user_id)));
3955 $this->messenger_bot_login->app_initialize($fb_user_info[0]['messenger_bot_config_id']);
3956 if($enable_disable=='enable')
3957 {
3958 $already_enabled = $this->basic->get_data('messenger_bot_page_info',array('where'=>array('page_id'=>$fb_page_id,'bot_enabled'=>'1')));
3959 if(!empty($already_enabled))
3960 {
3961 echo json_encode(array('success'=>0,'error'=>$this->lang->line("This page is already enabled by other Admin.")));
3962 exit();
3963 }
3964 //************************************************//
3965 $status=$this->_check_usage($module_id=200,$request=1);
3966 if($status=="2")
3967 {
3968 echo json_encode(array('success'=>0,'error'=>$this->lang->line("Module limit is over.")));
3969 exit();
3970 }
3971 else if($status=="3")
3972 {
3973 echo json_encode(array('success'=>0,'error'=>$this->lang->line("Module limit is over.")));
3974 exit();
3975 }
3976 //************************************************//
3977
3978 $response=$this->messenger_bot_login->enable_bot($fb_page_id,$page_access_token);
3979 $output = $response;
3980 if($output['error'] == '')
3981 {
3982 $this->basic->update_data("messenger_bot_page_info",array("id"=>$page_id),array("bot_enabled"=>"1"));
3983 $this->_insert_usage_log($module_id=200,$request=1);
3984 }
3985 echo json_encode($response);
3986 }
3987 else
3988 {
3989 $updateData=array("bot_enabled"=>"0");
3990 if($persistent_enabled=='1')
3991 {
3992 $updateData['persistent_enabled']='0';
3993 $updateData['started_button_enabled']='0';
3994 $this->messenger_bot_login->delete_persistent_menu($page_access_token); // delete persistent menu
3995 $this->messenger_bot_login->delete_get_started_button($page_access_token); // delete get started button
3996 $this->basic->delete_data("messenger_bot_persistent_menu",array("page_id"=>$page_id,"user_id"=>$this->user_id));
3997 $this->_delete_usage_log($module_id=197,$request=1);
3998 }
3999 $response=$this->messenger_bot_login->disable_bot($fb_page_id,$page_access_token);
4000 $output = $response;
4001 if($output['error'] == '')
4002 {
4003 $this->basic->update_data("messenger_bot_page_info",array("id"=>$page_id),$updateData);
4004 $this->_delete_usage_log($module_id=200,$request=1);
4005 }
4006 echo json_encode($response);
4007 }
4008 }
4009 //=============================ENABLE DISBALE BOT==============================
4010
4011 //=============================DOMAIN WHITELIST================================
4012 public function domain_whitelist()
4013 {
4014 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
4015 redirect('home/login_page', 'location');
4016 $table = "messenger_bot_page_info";
4017 $where_simple['messenger_bot_page_info.user_id'] = $this->user_id;
4018 $where_simple['messenger_bot_page_info.bot_enabled'] = '1';
4019 $where = array('where'=>$where_simple);
4020 $join = array('messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left");
4021 $page_info = $this->basic->get_data($table, $where, $select=array("messenger_bot_page_info.*","messenger_bot_user_info.name as account_name"),$join,'','','page_name asc');
4022 $pagelist=array();
4023 $i=0;
4024 foreach($page_info as $key => $value)
4025 {
4026 // $pagelist[$value["id"]]["account_name"]=$value['account_name'];
4027 // $pagelist[$value["id"]]["page_name"]=$value['page_name'];
4028 $pagelist[$value["messenger_bot_user_info_id"]]["account_name"]=$value['account_name'];
4029 $pagelist[$value["messenger_bot_user_info_id"]]["page_data"][$i]["page_name"]=$value['page_name'];
4030 $pagelist[$value["messenger_bot_user_info_id"]]["page_data"][$i]["page_id"]=$value['id'];
4031 $i++;
4032 }
4033 $data['page_title'] = $this->lang->line("Whitelisted Domains");
4034 $data['pagelist'] = $pagelist;
4035 $data['body'] = 'domain_list';
4036 $this->_viewcontroller($data);
4037 }
4038
4039 public function domain_whitelist_data()
4040 {
4041 // setting variables for pagination
4042 $page = isset($_POST['page']) ? intval($_POST['page']) : 100;
4043 $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 5;
4044 $sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'page_name';
4045 $order = isset($_POST['order']) ? strval($_POST['order']) : 'ASC';
4046 $order_by_str=$sort." ".$order;
4047
4048 // setting properties for search
4049 $search_domain = trim($this->input->post('search_domain', true));
4050 $search_page = $this->input->post('search_page', true);
4051 $is_searched = $this->input->post('is_searched', true);
4052
4053 if ($is_searched)
4054 {
4055 $this->session->set_userdata('messenger_bot_whitelist_domain',$search_domain);
4056 $this->session->set_userdata('messenger_bot_whitelist_page',$search_page);
4057 }
4058 $search_domain = $this->session->userdata('messenger_bot_whitelist_domain');
4059 $search_pasearch_domainge = $this->session->userdata('messenger_bot_whitelist_page');
4060 $where_simple=array();
4061 if ($search_domain!="")
4062 {
4063 $where_simple['domain like '] = "%".$search_domain."%";
4064 }
4065 if ($search_page!="")
4066 {
4067 $where_simple['page_name like '] = "%".$search_page."%";
4068 }
4069
4070 $where_simple['messenger_bot_domain_whitelist.user_id'] = $this->user_id;
4071 $where_simple['messenger_bot_page_info.user_id'] = $this->user_id;
4072 $where_simple['messenger_bot_page_info.deleted'] = '0';
4073 $where_simple['messenger_bot_page_info.bot_enabled'] = '1';
4074 $where = array('where'=>$where_simple);
4075 $offset = ($page-1)*$rows;
4076 $result = array();
4077 $table = "messenger_bot_domain_whitelist";
4078 $join = array
4079 (
4080 'messenger_bot_page_info'=>"messenger_bot_page_info.id=messenger_bot_domain_whitelist.page_id,left",
4081 'messenger_bot_user_info'=>"messenger_bot_user_info.id=messenger_bot_page_info.messenger_bot_user_info_id,left"
4082 );
4083 $group_by = "messenger_bot_domain_whitelist.page_id";
4084 $info = $this->basic->get_data($table, $where, $select=array("messenger_bot_domain_whitelist.*","messenger_bot_page_info.page_name", "messenger_bot_user_info.name as account_name","count(messenger_bot_domain_whitelist.id) as count"), $join, $limit=$rows, $start=$offset, $order_by=$order_by_str,$group_by);
4085 // echo $this->db->last_query();
4086 $total_rows_array = $this->basic->count_row($table, $where, $count="messenger_bot_domain_whitelist.id",$join,$group_by);
4087 $total_result = $total_rows_array[0]['total_rows'];
4088 echo convert_to_grid_data($info, $total_result);
4089 }
4090 public function domain_details()
4091 {
4092 if (empty($_POST['page_id']))
4093 {
4094 die();
4095 }
4096 $page_id = $this->input->post("page_id");
4097 $page_name = $this->input->post("page_name");
4098 $account_name = $this->input->post("account_name");
4099 $table_name = "messenger_bot_domain_whitelist";
4100 $where['where'] = array('user_id' => $this->user_id, 'page_id' => $page_id);
4101 $domain_data = $this->basic->get_data($table_name,$where);
4102 $html = '<script>
4103 $j(document).ready(function() {
4104 $("#domain_data_table").DataTable();
4105 });
4106 </script>';
4107 $html .= "<h3 class='text-center'>".$this->lang->line('page')." : ".$page_name." (".$account_name.")</h3>
4108 <table id='domain_data_table' class='table table-striped table-bordered nowrap' cellspacing='0' width='100%''>
4109 <thead>
4110 <tr>
4111 <th>".$this->lang->line("domain")."</th>
4112 <th>".$this->lang->line("whitlisted at")."</th>
4113 <th>".$this->lang->line("delete")."</th>
4114 </tr>
4115 </thead>
4116 <tbody>";
4117 foreach ($domain_data as $one_user)
4118 {
4119 $btn_id=$one_user['id'];
4120 $delete_btn= "<a class='btn btn-sm btn-danger delete_domain' id='domain-".$btn_id."' data-id='".$btn_id."'><i class='fa fa-remove'></i> ".$this->lang->line("delete")."</a>";
4121 $html .= "<tr>
4122 <td><a target='_BLANK' href='".$one_user['domain']."'>".$one_user['domain']."</a></td>
4123 <td>".date("jS M, y H:i:s",strtotime($one_user['created_at']))."</td>";
4124 $html .= "
4125 <td>".$delete_btn."</td>
4126 </tr>";
4127 }
4128
4129 $html .= "</tbody>
4130 </table>";
4131
4132 echo $html;
4133 }
4134 public function delete_domain()
4135 {
4136 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
4137 exit();
4138
4139 if(!$_POST['domain_id']) exit();
4140 $domain_id=$this->input->post('domain_id');
4141 if($this->basic->delete_data('messenger_bot_domain_whitelist',array('id'=>$domain_id,'user_id'=>$this->user_id))) echo "1";
4142 else echo "0";
4143 }
4144 public function delete_bot()
4145 {
4146 if(!$_POST) exit();
4147 $id=$this->input->post("id");
4148 $bot_posback_ids = $this->basic->get_data('messenger_bot',array('where'=>array('id'=>$id)));
4149 $postback_id = array();
4150 if($bot_posback_ids[0]['keyword_type'] == 'post-back')
4151 {
4152 $postback_id = explode(',', $bot_posback_ids[0]['postback_id']);
4153 }
4154 $this->db->trans_start();
4155 $this->basic->delete_data("messenger_bot",array("id"=>$id,"user_id"=>$this->user_id));
4156
4157 if(!empty($postback_id))
4158 {
4159 $this->db->where_in("postback_id", $postback_id);
4160 $this->db->update('messenger_bot_postback', array('use_status' => '0'));
4161 }
4162 $this->db->trans_complete();
4163 if($this->db->trans_status() === false)
4164 echo '0';
4165 else
4166 echo '1';
4167 }
4168 public function add_domain()
4169 {
4170 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
4171 exit();
4172 if(!$_POST['page_id']) exit();
4173 $page_id=$this->input->post('page_id');
4174 $domain_name=$this->input->post('domain_name');
4175 $userdata=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_id)));
4176 $messenger_bot_user_info_id=isset($userdata[0]['messenger_bot_user_info_id']) ? $userdata[0]['messenger_bot_user_info_id'] : "";
4177 $page_access_token=isset($userdata[0]['page_access_token']) ? $userdata[0]['page_access_token'] : "";
4178 if(!$this->basic->is_exist('messenger_bot_domain_whitelist',array('page_id'=>$page_id,'domain'=>$domain_name)))
4179 {
4180 $this->basic->insert_data('messenger_bot_domain_whitelist',array('page_id'=>$page_id,'domain'=>$domain_name,"created_at"=>date("Y-m-d H:i:s"),"messenger_bot_user_info_id"=>$messenger_bot_user_info_id,"user_id"=>$this->user_id));
4181 $this->load->library("messenger_bot_login");
4182 $response=array();
4183 $response=$this->messenger_bot_login->domain_whitelist($page_access_token,$domain_name);
4184 }
4185 else $response=array('status'=>'1','result'=>$this->lang->line("Successfully updated whitelisted domains"));
4186 echo json_encode($response);
4187
4188 }
4189 //=============================DOMAIN WHITELIST================================
4190
4191
4192 //==============================ACCOUNT IMPORT================================
4193 public function account_import()
4194 {
4195 if($this->session->userdata('user_type') != 'Admin' && !in_array(199,$this->module_access))
4196 redirect('home/login_page', 'location');
4197 if($this->session->userdata("messenger_bot_user_info")==0 && $this->config->item("bot_backup_mode")==1)
4198 redirect('messenger_bot/facebook_config','refresh');
4199 $this->load->library("messenger_bot_login");
4200 $data['body'] = 'account_import';
4201 $data['page_title'] = $this->lang->line('Facebook Account Import');
4202 $redirect_url = base_url()."messenger_bot/refresh_login_callback";
4203 $fb_login_button = $this->messenger_bot_login->login_for_user_access_token($redirect_url);
4204 $data['fb_login_button'] = $fb_login_button;
4205 $where['where'] = array('user_id'=>$this->user_id);
4206 $existing_accounts = $this->basic->get_data('messenger_bot_user_info',$where);
4207 $show_import_account_box = 1;
4208 $data['show_import_account_box'] = 1;
4209 if(!empty($existing_accounts))
4210 {
4211 $i=0;
4212 foreach($existing_accounts as $value)
4213 {
4214 $existing_account_info[$i]['need_to_delete'] = $value['need_to_delete'];
4215 if($value['need_to_delete'] == '1')
4216 {
4217 $show_import_account_box = 0;
4218 $data['show_import_account_box'] = $show_import_account_box;
4219 }
4220 $existing_account_info[$i]['fb_id'] = $value['fb_id'];
4221 $existing_account_info[$i]['userinfo_table_id'] = $value['id'];
4222 $existing_account_info[$i]['name'] = $value['name'];
4223 $existing_account_info[$i]['email'] = $value['email'];
4224 $existing_account_info[$i]['user_access_token'] = $value['access_token'];
4225 $valid_or_invalid = $this->messenger_bot_login->access_token_validity_check_for_user($value['access_token']);
4226 if($valid_or_invalid)
4227 {
4228 $existing_account_info[$i]['validity'] = 'yes';
4229 }
4230 else
4231 {
4232 $existing_account_info[$i]['validity'] = 'no';
4233 }
4234
4235 $where = array();
4236 $where['where'] = array('messenger_bot_user_info_id'=>$value['id']);
4237 $page_count = $this->basic->get_data('messenger_bot_page_info',$where);
4238 $existing_account_info[$i]['page_list'] = $page_count;
4239 if(!empty($page_count))
4240 {
4241 $existing_account_info[$i]['total_pages'] = count($page_count);
4242 }
4243 else $existing_account_info[$i]['total_pages'] = 0;
4244 $i++;
4245 }
4246 $data['existing_accounts'] = $existing_account_info;
4247 }
4248 else $data['existing_accounts'] = '0';
4249
4250 $this->_viewcontroller($data);
4251 }
4252
4253 public function ajax_delete_account_action()
4254 {
4255 if($this->session->userdata('user_type') != 'Admin' && !in_array(199,$this->module_access))
4256 exit();
4257 if($this->session->userdata("messenger_bot_user_info")==0 && $this->config->item("bot_backup_mode")==1)
4258 exit();
4259 $table_id = $this->input->post("user_table_id");
4260 $this->db->trans_start();
4261 $this->basic->delete_data('messenger_bot_user_info',array('id'=>$table_id,"user_id"=>$this->user_id));
4262 $this->_delete_usage_log($module_id=199,$request=1); // messenger account import module
4263 $bot_page_list=$this->basic->get_data("messenger_bot_page_info",array("where"=>array('messenger_bot_user_info_id'=>$table_id))); // all pages of that account
4264 $page_id_array=array();
4265 $menu_page_id_array=array();
4266 $no_enabled_pages=0;
4267 $no_menu_enabled_pages=0;
4268 $this->load->library("messenger_bot_login");
4269 foreach($bot_page_list as $value)
4270 {
4271 array_push($page_id_array, $value['id']);
4272 if($value['bot_enabled']=='1')
4273 {
4274 $no_enabled_pages++;
4275 $fb_page_id=isset($value['page_id']) ? $value['page_id'] : "";
4276 $page_access_token=isset($value['page_access_token']) ? $value['page_access_token'] : "";
4277 if($value['persistent_enabled']=='1')
4278 {
4279 $no_menu_enabled_pages++;
4280 array_push($menu_page_id_array, $value['id']);
4281 $this->messenger_bot_login->delete_persistent_menu($page_access_token); // delete persistent menu
4282 $this->messenger_bot_login->delete_get_started_button($page_access_token); // delete get started button
4283 }
4284 $this->messenger_bot_login->disable_bot($fb_page_id,$page_access_token);
4285 }
4286 }
4287 if(!empty($page_id_array))
4288 {
4289 $this->db->where_in('page_id', $page_id_array);
4290 $this->db->delete("messenger_bot"); //delete all bot settings of pages of deleted account
4291 $this->db->where_in('page_id', $page_id_array);
4292 $this->db->delete("messenger_bot_postback"); //delete all bot payload/postback settings of pages of deleted account
4293 }
4294 if(!empty($menu_page_id_array))
4295 {
4296 $this->db->where_in('page_id', $menu_page_id_array);
4297 $this->db->delete("messenger_bot_persistent_menu"); //delete all persistent menu of pages of deleted account
4298 }
4299 if($no_enabled_pages>0)
4300 $this->_delete_usage_log($module_id=200,$request=$no_enabled_pages); // messenger bot module
4301 if($no_menu_enabled_pages>0)
4302 $this->_delete_usage_log($module_id=197,$request=$no_menu_enabled_pages); // persistent menu module
4303 $this->basic->delete_data('messenger_bot_page_info',array('messenger_bot_user_info_id'=>$table_id,"user_id"=>$this->user_id)); // delete all page of that account
4304 $this->basic->delete_data('messenger_bot_domain_whitelist',array('messenger_bot_user_info_id'=>$table_id,"user_id"=>$this->user_id)); // delete all whitlisted domain of that account
4305
4306 $this->db->where_in('page_id', $page_id_array);
4307 $this->db->delete("messenger_bot_postback"); //delete all bot payload/postback settings of pages of deleted account
4308 $this->db->trans_complete();
4309 if($this->db->trans_status() === false)
4310 {
4311 echo "<div class='alert alert-danger text-center'>'".$this->lang->line("something went wrong, please try again.")."'</div>";
4312 }
4313 else
4314 {
4315 echo "success";
4316 }
4317 }
4318
4319 public function send_user_roll_access()
4320 {
4321 if($this->session->userdata('user_type') != 'Admin' && !in_array(199,$this->module_access))
4322 exit();
4323 if($this->session->userdata("messenger_bot_user_info")==0 && $this->config->item("bot_backup_mode")==1)
4324 exit();
4325 $this->load->library("messenger_bot_login");
4326 if($_POST)
4327 {
4328 $fb_numeric_id= $this->input->post("fb_numeric_id");
4329 $database_id = $this->session->userdata('messenger_bot_login_database_id');
4330 $facebook_config=$this->basic->get_data("messenger_bot_config",array("where"=>array("id"=>$database_id)));
4331 if(isset($facebook_config[0]))
4332 {
4333 $app_id=$facebook_config[0]["api_id"];
4334 $app_secret=$facebook_config[0]["api_secret"];
4335 $user_access_token=$facebook_config[0]["user_access_token"];
4336 }
4337 $response=$this->messenger_bot_login->send_user_roll_access($app_id,$fb_numeric_id,$user_access_token);
4338
4339 if(isset($response['success']) && $response['success'] == 1)
4340 echo "<br/>
4341 <div class='well'><h4 class='text-center red'>'".$this->lang->line("please log in & check your facebook profile page notifications, to accept our invitation")."'</h4></div>
4342 <div class='alert alert-danger text-center'>
4343 <h4 style='line-height:25px'>'".$this->lang->line("a request has been sent to your facebook account. please login to your facebook account, confirm the app request and click below button.")."'<br/><br/>'".$this->lang->line("do not click this until confirmed")."'</h4>
4344 <br/>
4345 <button class='btn btn-default btn-lg' id='fb_confirm'><b>'".$this->lang->line("i've confirmed app request in facebook")."'</b></button>
4346 </div>";
4347 else if (isset($response["error"]["error_user_msg"]))
4348 echo "<br/><div class='alert alert-danger text-center'>
4349 <p><i class='fa fa-remove'></i> ".$response["error"]["error_user_msg"]."</p>
4350 </div>";
4351 else
4352 {
4353 echo "<br/><div class='alert alert-danger text-center'>
4354 <p><i class='fa fa-remove'></i> ".$this->lang->line("something went wrong, please try with correct information.")."<br>";
4355 if(isset($response['error']['message']))
4356 echo "<br>".$response['error']['message'];
4357 if(isset($response['error']['message']) && $response['error']['message']=='(#100) 372747716260046 does not resolve to a valid user ID');
4358 echo "<br> Please make sure this is the numeric ID of your profile not any of your page.";
4359 echo "</p>
4360 </div>";
4361 }
4362 }
4363 }
4364
4365 public function ajax_get_login_button()
4366 {
4367 if($this->session->userdata('user_type') != 'Admin' && !in_array(199,$this->module_access))
4368 exit();
4369 if($this->session->userdata("messenger_bot_user_info")==0 && $this->config->item("bot_backup_mode")==1)
4370 exit();
4371 $this->load->library("messenger_bot_login");
4372 $redirect_url = base_url()."messenger_bot/user_login_callback";
4373 $fb_login_button = $this->messenger_bot_login->login_for_user_access_token($redirect_url);
4374 if(isset($fb_login_button))
4375 {
4376 echo '<br/><div class="alert alert-danger text-center">
4377 <h3 class="">'.$fb_login_button.'<h3>
4378 </div>';
4379 }
4380 else
4381 echo "<br/><div class='alert alert-danger text-center'><p>".$this->lang->line("something went wrong, please try again with proper information")."</p></div>";
4382 }
4383
4384 public function user_login_callback()
4385 {
4386 $id = $this->session->userdata('messenger_bot_login_database_id');
4387 $this->load->library("messenger_bot_login");
4388 $redirect_url = base_url()."messenger_bot/user_login_callback";
4389 $user_info = $this->messenger_bot_login->login_callback($redirect_url);
4390
4391 if( isset($user_info['status']) && $user_info['status'] == '0')
4392 {
4393 $data['error'] = 1;
4394 $data['message'] = "'".$this->lang->line("something went wrong,please")."' <a href='".base_url("messenger_bot/account_import")."'>'".$this->lang->line("try again")."'</a>";
4395 $data['body'] = "user_login";
4396 $this->_viewcontroller($data);
4397 }
4398 else
4399 {
4400 //************************************************//
4401 $status=$this->_check_usage($module_id=199,$request=1);
4402 if($status=="2")
4403 {
4404 $this->session->set_userdata('limit_cross', $this->lang->line("Module limit is over."));
4405 redirect('messenger_bot/account_import','location');
4406 exit();
4407 }
4408 else if($status=="3")
4409 {
4410 $this->session->set_userdata('limit_cross', $this->lang->line("Module limit is over."));
4411 redirect('messenger_bot/account_import','location');
4412 exit();
4413 }
4414 //************************************************//
4415 $access_token=$user_info['access_token_set'];
4416 //checking permission given by the users
4417 $permission = $this->messenger_bot_login->debug_access_token($access_token);
4418 $given_permission = array();
4419 if(isset($permission['data']['scopes']))
4420 {
4421 $permission_checking = array();
4422 $needed_permission = array('manage_pages','publish_pages','pages_messaging');
4423 $given_permission = $permission['data']['scopes'];
4424 $permission_checking = array_intersect($needed_permission,$given_permission);
4425 if(empty($permission_checking))
4426 {
4427 // $documentation_link = base_url('documentation/#!/sm_import_account');
4428 $text = "'".$this->lang->line("sorry, you didn't confirm the request yet. please login to your fb account and accept the request. for more");
4429 $this->session->set_userdata('limit_cross', $text);
4430 redirect('messenger_bot/account_import','location');
4431 exit();
4432 }
4433 }
4434
4435 if(isset($access_token))
4436 {
4437 $data = array(
4438 'user_id' => $this->user_id,
4439 'messenger_bot_config_id' => $id,
4440 'access_token' => $access_token,
4441 'name' => $user_info['name'],
4442 'email' => isset($user_info['email']) ? $user_info['email'] : "",
4443 'fb_id' => $user_info['id'],
4444 'add_date' => date('Y-m-d'),
4445 'deleted' => '0'
4446 );
4447 $where=array();
4448 $where['where'] = array('user_id'=>$this->user_id,'fb_id'=>$user_info['id']);
4449 $exist_or_not = array();
4450 $exist_or_not = $this->basic->get_data('messenger_bot_user_info',$where,$select='',$join='',$limit='',$start=NULL,$order_by='',$group_by='',$num_rows=0,$csv='',$delete_overwrite=1);
4451 if(empty($exist_or_not))
4452 {
4453 $this->basic->insert_data('messenger_bot_user_info',$data);
4454 $facebook_table_id = $this->db->insert_id();
4455 }
4456 else
4457 {
4458 $facebook_table_id = $exist_or_not[0]['id'];
4459 $where = array('user_id'=>$this->user_id,'id'=>$facebook_table_id);
4460 $this->basic->update_data('messenger_bot_user_info',$where,$data);
4461 }
4462 $this->session->set_userdata("messenger_bot_user_info",$facebook_table_id);
4463 $page_list = array();
4464 $page_list = $this->messenger_bot_login->get_page_list($access_token);
4465 if(!empty($page_list))
4466 {
4467 foreach($page_list as $page)
4468 {
4469 $user_id = $this->user_id;
4470 $page_id = $page['id'];
4471 $page_cover = '';
4472 if(isset($page['cover']['source'])) $page_cover = $page['cover']['source'];
4473 $page_profile = '';
4474 if(isset($page['picture']['url'])) $page_profile = $page['picture']['url'];
4475 $page_name = '';
4476 if(isset($page['name'])) $page_name = $page['name'];
4477 $page_access_token = '';
4478 if(isset($page['access_token'])) $page_access_token = $page['access_token'];
4479 $page_email = '';
4480 if(isset($page['emails'][0])) $page_email = $page['emails'][0];
4481 $page_username = '';
4482 if(isset($page['username'])) $page_username = $page['username'];
4483 $data = array(
4484 'user_id' => $user_id,
4485 'messenger_bot_user_info_id' => $facebook_table_id,
4486 'page_id' => $page_id,
4487 'page_cover' => $page_cover,
4488 'page_profile' => $page_profile,
4489 'page_name' => $page_name,
4490 'page_access_token' => $page_access_token,
4491 'page_email' => $page_email,
4492 'username' => $page_username,
4493 'add_date' => date('Y-m-d'),
4494 'deleted' => '0'
4495 );
4496 $where=array();
4497 $where['where'] = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4498 $exist_or_not = array();
4499 $exist_or_not = $this->basic->get_data('messenger_bot_page_info',$where,$select='',$join='',$limit='',$start=NULL,$order_by='',$group_by='',$num_rows=0,$csv='',$delete_overwrite=1);
4500 if(empty($exist_or_not))
4501 {
4502 $this->basic->insert_data('messenger_bot_page_info',$data);
4503 }
4504 else
4505 {
4506 $where = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4507 $this->basic->update_data('messenger_bot_page_info',$where,$data);
4508 }
4509 }
4510 }
4511
4512 //insert data to useges log table
4513 $this->_insert_usage_log($module_id=199,$request=1);
4514 $this->session->set_userdata('success_message', 'success');
4515 redirect('messenger_bot/account_import','location');
4516 exit();
4517 }
4518 else
4519 {
4520 $data['error'] = 1;
4521 $data['message'] = "'".$this->lang->line("something went wrong,please")."' <a href='".base_url("messenger_bot/account_import")."'>'".$this->lang->line("try again")."'</a>";
4522 $data['body'] = "user_login";
4523 $this->_viewcontroller($data);
4524 }
4525 }
4526 }
4527
4528 public function refresh_login_callback()
4529 {
4530 $id = $this->session->userdata('messenger_bot_login_database_id');
4531 $this->load->library("messenger_bot_login");
4532 $redirect_url = base_url()."messenger_bot/refresh_login_callback";
4533 $user_info = array();
4534 $user_info = $this->messenger_bot_login->login_callback($redirect_url);
4535
4536 if( isset($user_info['status']) && $user_info['status'] == '0')
4537 {
4538 $data['error'] = 1;
4539 $data['message'] = "'".$this->lang->line("something went wrong,please")."' <a href='".base_url("messenger_bot/account_import")."'>'".$this->lang->line("try again")."'</a>";
4540 $data['body'] = "user_login";
4541 $this->_viewcontroller($data);
4542 }
4543 else
4544 {
4545 $access_token=$user_info['access_token_set'];
4546 //checking permission given by the users
4547 $permission = $this->messenger_bot_login->debug_access_token($access_token);
4548 $given_permission = array();
4549 if(isset($permission['data']['scopes']))
4550 {
4551 $permission_checking = array();
4552 $needed_permission = array('manage_pages','publish_pages','pages_messaging');
4553 $given_permission = $permission['data']['scopes'];
4554 $permission_checking = array_intersect($needed_permission,$given_permission);
4555 if(empty($permission_checking))
4556 {
4557 // $documentation_link = base_url('documentation/#!/sm_import_account');
4558 $text = "'".$this->lang->line("sorry, you didn't confirm the request yet. please login to your fb account and accept the request. for more");
4559 $this->session->set_userdata('limit_cross', $text);
4560 redirect('messenger_bot/account_import','location');
4561 exit();
4562 }
4563 }
4564
4565 if(isset($access_token))
4566 {
4567 $data = array(
4568 'user_id' => $this->user_id,
4569 'messenger_bot_config_id' => $id,
4570 'access_token' => $access_token,
4571 'name' => $user_info['name'],
4572 'email' => isset($user_info['email']) ? $user_info['email'] : "",
4573 'fb_id' => $user_info['id'],
4574 'add_date' => date('Y-m-d'),
4575 'deleted' => '0'
4576 );
4577 $where=array();
4578 $where['where'] = array('user_id'=>$this->user_id,'fb_id'=>$user_info['id']);
4579 $exist_or_not = array();
4580 $exist_or_not = $this->basic->get_data('messenger_bot_user_info',$where,$select='',$join='',$limit='',$start=NULL,$order_by='',$group_by='',$num_rows=0,$csv='',$delete_overwrite=1);
4581 if(empty($exist_or_not))
4582 {
4583 //************************************************//
4584 $status=$this->_check_usage($module_id=199,$request=1);
4585 if($status=="2")
4586 {
4587 $this->session->set_userdata('limit_cross', $this->lang->line("Module limit is over."));
4588 redirect('messenger_bot/account_import','location');
4589 exit();
4590 }
4591 else if($status=="3")
4592 {
4593 $this->session->set_userdata('limit_cross', $this->lang->line("Module limit is over."));
4594 redirect('messenger_bot/account_import','location');
4595 exit();
4596 }
4597 //************************************************//
4598 $this->basic->insert_data('messenger_bot_user_info',$data);
4599 $facebook_table_id = $this->db->insert_id();
4600 //insert data to useges log table
4601 $this->_insert_usage_log($module_id=199,$request=1);
4602 }
4603 else
4604 {
4605 $facebook_table_id = $exist_or_not[0]['id'];
4606 $where = array('user_id'=>$this->user_id,'id'=>$facebook_table_id);
4607 $this->basic->update_data('messenger_bot_user_info',$where,$data);
4608 }
4609 $page_list = array();
4610 $page_list = $this->messenger_bot_login->get_page_list($access_token);
4611 if(!empty($page_list))
4612 {
4613 foreach($page_list as $page)
4614 {
4615 $user_id = $this->user_id;
4616 $page_id = $page['id'];
4617 $page_cover = '';
4618 if(isset($page['cover']['source'])) $page_cover = $page['cover']['source'];
4619 $page_profile = '';
4620 if(isset($page['picture']['url'])) $page_profile = $page['picture']['url'];
4621 $page_name = '';
4622 if(isset($page['name'])) $page_name = $page['name'];
4623 $page_access_token = '';
4624 if(isset($page['access_token'])) $page_access_token = $page['access_token'];
4625 $page_email = '';
4626 if(isset($page['emails'][0])) $page_email = $page['emails'][0];
4627 $page_username = '';
4628 if(isset($page['username'])) $page_username = $page['username'];
4629 $data = array(
4630 'user_id' => $user_id,
4631 'messenger_bot_user_info_id' => $facebook_table_id,
4632 'page_id' => $page_id,
4633 'page_cover' => $page_cover,
4634 'page_profile' => $page_profile,
4635 'page_name' => $page_name,
4636 'username' => $page_username,
4637 'page_access_token' => $page_access_token,
4638 'page_email' => $page_email,
4639 'add_date' => date('Y-m-d'),
4640 'deleted' => '0'
4641 );
4642 $where=array();
4643 $where['where'] = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4644 $exist_or_not = array();
4645 $exist_or_not = $this->basic->get_data('messenger_bot_page_info',$where,$select='',$join='',$limit='',$start=NULL,$order_by='',$group_by='',$num_rows=0,$csv='',$delete_overwrite=1);
4646 if(empty($exist_or_not))
4647 {
4648 $this->basic->insert_data('messenger_bot_page_info',$data);
4649 }
4650 else
4651 {
4652 $where = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4653 $this->basic->update_data('messenger_bot_page_info',$where,$data);
4654 }
4655 }
4656 }
4657 $this->session->set_userdata('success_message', 'success');
4658 redirect('messenger_bot/account_import','location');
4659 exit();
4660 }
4661 else
4662 {
4663 $data['error'] = 1;
4664 $data['message'] = "'".$this->lang->line("something went wrong,please")."' <a href='".base_url("messenger_bot/account_import")."'>'".$this->lang->line("try again")."'</a>";
4665 $data['body'] = "user_login";
4666 $this->_viewcontroller($data);
4667 }
4668 }
4669 }
4670 //==============================ACCOUNT IMPORT================================
4671
4672
4673
4674 // ======================FACEBOOK APP CONFIG==================================
4675 public function facebook_config()
4676 {
4677 if($this->session->userdata('user_type') != 'Admin' && !in_array(200,$this->module_access))
4678 redirect('home/login_page', 'location');
4679
4680 if ($this->session->userdata('user_type')== "Member" && $this->config->item("bot_backup_mode")==0) {
4681 redirect('home/login', 'location');
4682 }
4683 $this->load->database();
4684 $this->load->library('grocery_CRUD');
4685 $crud = new grocery_CRUD();
4686 $crud->set_theme('flexigrid');
4687 $crud->set_table('messenger_bot_config');
4688 $crud->order_by('app_name');
4689 $crud->set_subject($this->lang->line("facebook API settings"));
4690 $crud->required_fields('api_id', 'api_secret','status');
4691 $crud->columns('app_name','api_id', 'api_secret','status','validity');
4692 $crud->fields('app_name','api_id', 'api_secret','status');
4693 $crud->where('user_id',$this->session->userdata('user_id'));
4694 $crud->callback_field('status', array($this, 'status_field_crud'));
4695 $crud->callback_column('status', array($this, 'status_display_crud'));
4696 $crud->callback_column('validity', array($this, 'validity_display_crud'));
4697 $crud->callback_after_insert(array($this, 'make_up_fb_setting'));
4698 $crud->unset_export();
4699 $crud->unset_print();
4700 $crud->unset_read();
4701 $crud->unset_delete();
4702 $total_rows_array = $this->basic->count_row("messenger_bot_config",array("where"=>array('user_id'=>$this->session->userdata('user_id'))), $count="id");
4703 $total_result = $total_rows_array[0]['total_rows'];
4704 if($this->session->userdata("user_type")=="Member" && $total_result>0)
4705 $crud->unset_add();
4706 $crud->display_as('validity', $this->lang->line('Token Validity'));
4707 $crud->display_as('app_name', $this->lang->line('facebook app Name'));
4708 $crud->display_as('api_id', $this->lang->line('facebook App ID'));
4709 $crud->display_as('api_secret', $this->lang->line('facebook App secret'));
4710 $crud->display_as('status', $this->lang->line('status'));
4711
4712 $images_url = base_url("plugins/grocery_crud/themes/flexigrid/css/images/login.png");
4713 $crud->add_action('Login', $images_url, 'messenger_bot/fb_login');
4714 $output = $crud->render();
4715 $data['output'] = $output;
4716 $data['crud'] = 1;
4717 $data['page_title'] = $this->lang->line("facebook API settings");
4718 $this->_viewcontroller($data);
4719 }
4720 public function make_up_fb_setting($post_array, $primary_key)
4721 {
4722 if($this->session->userdata("user_type")=="Admin") $use_by = "everyone";
4723 else $use_by = "only_me";
4724 $this->basic->update_data("messenger_bot_config",array('id'=> $primary_key),array("user_id"=>$this->session->userdata("user_id"),'use_by'=>$use_by));
4725 return true;
4726 }
4727
4728 public function fb_login($id)
4729 {
4730 $this->session->set_userdata("messenger_bot_login_database_id",$id);
4731 $this->load->library("messenger_bot_login");
4732
4733 $redirect_url = base_url()."messenger_bot/login_callback";
4734 $data['fb_login_button'] = $this->messenger_bot_login->login_for_user_access_token($redirect_url);
4735 $data['body'] = 'admin_login';
4736 $data['page_title'] = $this->lang->line("admin login");
4737 $data['expired_or_not'] = $this->messenger_bot_login->access_token_validity_check();
4738 $this->_viewcontroller($data);
4739 }
4740
4741 public function status_field_crud($value, $row)
4742 {
4743 if ($value == '') {
4744 $value = 1;
4745 }
4746 return form_dropdown('status', array(0 => $this->lang->line('inactive'), 1 => $this->lang->line('active')), $value, 'class="form-control" id="field-status"');
4747 }
4748 public function status_display_crud($value, $row)
4749 {
4750 if ($value == 1) {
4751 return "<span class='label label-success' title='Access Token : ".$row->user_access_token."'>".$this->lang->line('active')."</sapn>";
4752 } else {
4753 return "<span class='label label-warning' title='Access Token : ".$row->user_access_token."'>".$this->lang->line('inactive')."</sapn>";
4754 }
4755 }
4756 function validity_display_crud($value, $row)
4757 {
4758 $input_token = $row->user_access_token;
4759 if($input_token=="")
4760 return "<span class='label label-warning' style='font-weight:normal'>Invalid</sapn>";
4761 $this->load->library("messenger_bot_login");
4762 $url="https://graph.facebook.com/debug_token?input_token={$input_token}&access_token={$input_token}";
4763 $result= $this->messenger_bot_login->run_curl_for_fb($url);
4764 $result = json_decode($result,true);
4765 if(isset($result["data"]["is_valid"]) && $result["data"]["is_valid"])
4766 {
4767 return "<span class='label label-success' style='font-weight:normal'>".$this->lang->line('Valid')."</sapn>";
4768 }
4769 else
4770 {
4771 return "<span class='label label-warning' style='font-weight:normal'>".$this->lang->line('Expired')."</sapn>";
4772 }
4773 }
4774 public function login_callback()
4775 {
4776
4777 if ($this->session->userdata('logged_in')!= 1) exit();
4778 $id=$this->session->userdata("messenger_bot_login_database_id");
4779 $redirect_url = base_url()."messenger_bot/login_callback/";
4780 $this->load->library('messenger_bot_login');
4781 $user_info = $this->messenger_bot_login->login_callback($redirect_url);
4782 if(isset($user_info['status']) && $user_info['status'] == '0')
4783 {
4784 $data['error'] = 1;
4785 $data['message'] = "<a href='".base_url("messenger_bot/facebook_config/")."'>".$this->lang->line("something went wrong, please try again.")."</a>";
4786 $data['body'] = "admin_login";
4787 $this->_viewcontroller($data);
4788 }
4789 else
4790 {
4791 $access_token=$user_info['access_token_set'];
4792 $where = array('id'=>$id);
4793 $update_data = array('user_access_token'=>$access_token);
4794 if($this->basic->update_data('messenger_bot_config',$where,$update_data))
4795 {
4796 $data = array(
4797 'user_id' => $this->user_id,
4798 'messenger_bot_config_id' => $id,
4799 'access_token' => $access_token,
4800 'name' => $user_info['name'],
4801 'email' => isset($user_info['email']) ? $user_info['email'] : "",
4802 'fb_id' => $user_info['id'],
4803 'add_date' => date('Y-m-d')
4804 );
4805 $where=array();
4806 $where['where'] = array('user_id'=>$this->user_id,'fb_id'=>$user_info['id']);
4807 $exist_or_not = $this->basic->get_data('messenger_bot_user_info',$where);
4808 if(empty($exist_or_not))
4809 {
4810 $this->basic->insert_data('messenger_bot_user_info',$data);
4811 $facebook_table_id = $this->db->insert_id();
4812 }
4813 else
4814 {
4815 $facebook_table_id = $exist_or_not[0]['id'];
4816 $where = array('user_id'=>$this->user_id,'fb_id'=>$user_info['id']);
4817 $this->basic->update_data('messenger_bot_user_info',$where,$data);
4818 }
4819 $this->session->set_userdata("messenger_bot_user_info",$facebook_table_id);
4820 $page_list = $this->messenger_bot_login->get_page_list($access_token);
4821 if(!empty($page_list))
4822 {
4823 foreach($page_list as $page)
4824 {
4825 $user_id = $this->user_id;
4826 $page_id = $page['id'];
4827 $page_cover = '';
4828 if(isset($page['cover']['source'])) $page_cover = $page['cover']['source'];
4829 $page_profile = '';
4830 if(isset($page['picture']['url'])) $page_profile = $page['picture']['url'];
4831 $page_name = '';
4832 if(isset($page['name'])) $page_name = $page['name'];
4833 $page_username = '';
4834 if(isset($page['username'])) $page_username = $page['username'];
4835 $page_access_token = '';
4836 if(isset($page['access_token'])) $page_access_token = $page['access_token'];
4837 $page_email = '';
4838 if(isset($page['emails'][0])) $page_email = $page['emails'][0];
4839 $data = array(
4840 'user_id' => $user_id,
4841 'messenger_bot_user_info_id' => $facebook_table_id,
4842 'page_id' => $page_id,
4843 'page_cover' => $page_cover,
4844 'page_profile' => $page_profile,
4845 'page_name' => $page_name,
4846 'username' => $page_username,
4847 'page_access_token' => $page_access_token,
4848 'page_email' => $page_email,
4849 'add_date' => date('Y-m-d')
4850 );
4851 $where=array();
4852 $where['where'] = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4853 $exist_or_not = $this->basic->get_data('messenger_bot_page_info',$where);
4854 if(empty($exist_or_not))
4855 {
4856 $this->basic->insert_data('messenger_bot_page_info',$data);
4857 }
4858 else
4859 {
4860 $where = array('messenger_bot_user_info_id'=>$facebook_table_id,'page_id'=>$page['id']);
4861 $this->basic->update_data('messenger_bot_page_info',$where,$data);
4862 }
4863 }
4864 }
4865 $this->session->set_flashdata('success_message', 1);
4866 redirect('messenger_bot/facebook_config','location');
4867 exit();
4868 }
4869 else
4870 {
4871 $data['error'] = 1;
4872 $data['message'] = "<a href='".base_url("messenger_bot/facebook_config/")."'>".$this->lang->line("something went wrong, please try again.")."</a>";
4873 $data['body'] = "admin_login";
4874 $this->_viewcontroller($data);
4875 }
4876 }
4877 }
4878 // ======================FACEBOOK APP CONFIG==================================
4879 public function user_details_modal_bot()
4880 {
4881 if (empty($_POST['user_id_page_id'])) {
4882 die();
4883 }
4884
4885 $user_id_and_page_id = explode("-",$_POST['user_id_page_id']);
4886 $user_id = $user_id_and_page_id[0];
4887 $page_id = $user_id_and_page_id[1];
4888
4889 $table_name = "messenger_bot_subscriber";
4890 $where['where'] = array('user_id' => $user_id, 'page_id' => $page_id);
4891 $one_page_user_details = $this->basic->get_data($table_name,$where);
4892
4893 $html = '<script>
4894 $j(document).ready(function() {
4895 $("#user_data_for_inbox").DataTable();
4896 });
4897 </script>';
4898 $html .= "
4899 <div class='text-center' style='margin-top: -20px !important;'>
4900 <button class='btn btn-info download_subscriber' page_id='".$page_id."'><i class='fa fa-cloud-download'></i> ".$this->lang->line("Download subscriber list")."</button>
4901 </div>
4902 <table id='user_data_for_inbox' class='table table-striped table-bordered nowrap' cellspacing='0' width='100%''>
4903 <thead>
4904 <tr>
4905 <th class='text-center'>".$this->lang->line("picture")."</th>
4906 <th>".$this->lang->line("user name")."</th>
4907 <th class='text-center'>".$this->lang->line("gender")."</th>
4908 <th class='text-center'>".$this->lang->line("Subscribed at")."</th>
4909 <th class='text-center'>".$this->lang->line("status")."</th>
4910 </tr>
4911 </thead>
4912 <tbody>";
4913
4914 foreach ($one_page_user_details as $one_user)
4915 {
4916 $btn_id=$one_user['id'];
4917 $img_src=($one_user["image_path"]!="")?base_url($one_user["image_path"]):base_url("assets/images/avatar.png");
4918 $img="<img src='".$img_src."' class='img-circle' style='height:40px;width:40px;'>";
4919
4920 $html .= "<tr>
4921 <td class='text-center'>".$img."</td>
4922 <td style='vertical-align:middle !important'>".$one_user['first_name']." ".$one_user['last_name']."</td>
4923 <td class='text-center' style='vertical-align:middle !important'>".$one_user['gender']."</td>
4924 <td class='text-center' style='vertical-align:middle !important'>".date("jS M, y H:i:s",strtotime($one_user['subscribed_at']))."</td><td class='text-center'>";
4925 if($one_user['status'] == '1')
4926 {
4927 $html .= "<button id ='".$one_user['id']."-".$one_user['status']."' type='button' class='client_thread_subscribe_unsubscribe btn btn-danger btn-sm'>".$this->lang->line("Stop Bot")."</button>";//$one_user['permission'];
4928 }
4929 elseif ($one_user['status'] == '0')
4930 {
4931 $html .= "<button id ='".$one_user['id']."-".$one_user['status']."' type='button' class='client_thread_subscribe_unsubscribe btn btn-success btn-sm'>".$this->lang->line("Start Bot")."</button>";
4932 }
4933 $html .= "</td>
4934 </tr>";
4935 }
4936
4937 $html .= "</tbody>
4938 </table>
4939 ";
4940
4941 echo $html;
4942 }
4943 public function subscriber_list_download()
4944 {
4945 if(empty($_POST['page_id'])) {
4946 die();
4947 }
4948 $table_name = "messenger_bot_subscriber";
4949 $user_id = $this->user_id;
4950 $page_id = $this->input->post('page_id');
4951 $where['where'] = array('user_id' => $user_id, 'page_id' => $page_id);
4952 $one_page_user_details = $this->basic->get_data($table_name,$where);
4953
4954 if(empty($one_page_user_details))
4955 {
4956 $str = "<div class='alert alert-danger text-center'>".$this->lang->line("No data to download")."</div>";
4957 }
4958 else
4959 {
4960 $download_path=fopen("download/subscriber_download_{$this->user_id}.csv", "w");
4961 // make output csv file unicode compatible
4962 fprintf($download_path, chr(0xEF).chr(0xBB).chr(0xBF));
4963 /**Write header in csv file***/
4964 $write_data[]="User ID";
4965 $write_data[]="Page ID";
4966 $write_data[]="subscribe ID";
4967 // $write_data[]="Contact Group ID";
4968 $write_data[]="Locale";
4969 $write_data[]="First Name";
4970 $write_data[]="Last Name";
4971 $write_data[]="Gender";
4972 $write_data[]="Subscribed at";
4973 $write_data[]="Status";
4974 // $write_data[]="Paage Name";
4975 fputcsv($download_path, $write_data);
4976 foreach($one_page_user_details as $value)
4977 {
4978 $write_data=array();
4979 $write_data[]=$value['user_id'];
4980 $write_data[]=$value['page_id'];
4981 $write_data[]=$value['subscribe_id'];
4982 // $write_data[]=$value['contact_group_id'];
4983 $write_data[]=$value['locale'];
4984 $write_data[]=$value['first_name'];
4985 $write_data[]=$value['last_name'];
4986 $write_data[]=$value['gender'];
4987 $write_data[]=$value['subscribed_at'];
4988 $write_data[]=$value['status'];
4989 // $write_data[]=$page_info[0]['page_name'];
4990 fputcsv($download_path, $write_data);
4991 }
4992 $str = "<div class='download_box'><h2>".$this->lang->line('Your file is ready to download')."</h2>";
4993 $str .= '<i class="fa fa-2x fa-thumbs-o-up"style="color:black"></i><br><br>';
4994 $str .= "<a href='".base_url()."download/subscriber_download_".$this->user_id.".csv"."'". "title='Download' class='btn btn-warning btn-lg' style='width:200px;'><i class='fa fa-cloud-download' style='color:white'></i> ".$this->lang->line('Download')."</a></div>";
4995 }
4996 echo $str;
4997 }
4998
4999 public function delete_error_log($id=0)
5000 {
5001 if($id == 0) exit();
5002 $this->basic->delete_data("messenger_bot_reply_error_log",array("id"=>$id));
5003 redirect(base_url('messenger_bot/bot_list'),'location');
5004 }
5005 public function error_log_report()
5006 {
5007 if(empty($_POST['table_id'])) {
5008 die();
5009 }
5010 $user_id = $this->user_id;
5011 $page_table_id = $this->input->post('table_id');
5012 $table_name = "messenger_bot_reply_error_log";
5013 $select=array("messenger_bot_reply_error_log.*","bot_name");
5014 $join = array('messenger_bot'=>"messenger_bot_reply_error_log.bot_settings_id=messenger_bot.id,left");
5015 $where['where'] = array('messenger_bot_reply_error_log.user_id' => $user_id, 'messenger_bot_reply_error_log.page_id' => $page_table_id);
5016 $error_log_report_info = $this->basic->get_data($table_name,$where,$select,$join);
5017 $html = '<script>
5018 $j(document).ready(function() {
5019 $("#user_data_for_inbox").DataTable();
5020 });
5021 </script>';
5022 $html .= "
5023 <table id='user_data_for_inbox' class='table table-striped table-bordered' cellspacing='0' width='100%''>
5024 <thead>
5025 <tr>
5026 <th>".$this->lang->line("Bot Name")."</th>
5027 <th>".$this->lang->line("Error Message")."</th>
5028 <th>".$this->lang->line("Error Time")."</th>
5029 <th>".$this->lang->line("Actions")."</th>
5030 </tr>
5031 </thead>
5032 <tbody>";
5033 foreach ($error_log_report_info as $error_info)
5034 {
5035 $html .= "<tr>
5036 <td>".$error_info['bot_name']."</td>
5037 <td>".$error_info['error_message']."</td>
5038 <td>".date("jS M, y H:i:s",strtotime($error_info['error_time']))."</td>
5039 <td class='text-center'>
5040 <a title='Edit This Bot' class='orange' style='font-size:18px;;' href=".base_url('messenger_bot/edit_bot/').$error_info['bot_settings_id']."> <i class='fa fa-pencil'></i></a>
5041 <a title='Clear Error Log' href=".base_url('messenger_bot/delete_error_log/').$error_info['id']." class='red' style='font-size:18px;;'> <i class='fa fa-trash'></i></a>
5042
5043 </td>
5044 <td>";
5045 $html .= "</td>
5046 </tr>";
5047 }
5048 $html .= "</tbody>
5049 </table>
5050 ";
5051 echo $html;
5052 }
5053 public function client_subscribe_unsubscribe_status_change()
5054 {
5055 if (empty($_POST['client_subscribe_unsubscribe_status'])) {
5056 die();
5057 }
5058 $client_subscribe_unsubscribe = array();
5059 $post_val=$this->input->post('client_subscribe_unsubscribe_status');
5060 $client_subscribe_unsubscribe = explode("-",$post_val);
5061 $id = isset($client_subscribe_unsubscribe[0]) ? $client_subscribe_unsubscribe[0]: 0;
5062 $current_status = isset($client_subscribe_unsubscribe[1]) ? $client_subscribe_unsubscribe[1]: 0;
5063
5064 if($current_status=="1") $permission="0";
5065 else $permission="1";
5066
5067 $where = array
5068 (
5069 'id' => $id,
5070 'user_id' => $this->user_id
5071 );
5072 $data = array('status' => $permission);
5073
5074
5075 if($permission=="0")
5076 {
5077 $response = "<button id ='".$id."-".$permission."' type='button' class='client_thread_subscribe_unsubscribe btn btn-success'>Start Bot</button>";
5078 $this->basic->update_data("messenger_bot_subscriber",$where, $data);
5079 }
5080 else
5081 {
5082 $response = "<button id ='".$id."-".$permission."' type='button' class='client_thread_subscribe_unsubscribe btn btn-danger'>Stop Bot</button>";
5083 $this->basic->update_data("messenger_bot_subscriber",$where, $data);
5084 }
5085 echo $response;
5086 }
5087 public function edit_quick_email_reply($auto_id="",$page_id="")
5088 {
5089 if(!$this->basic->is_exist("messenger_bot",array("postback_id"=>"QUICK_REPLY_EMAIL_REPLY_BOT","page_id"=>$auto_id)))
5090 {
5091 $user_id=$this->user_id;
5092 $sql='INSERT INTO `messenger_bot` ( `user_id`, `page_id`, `fb_page_id`, `template_type`, `bot_type`, `keyword_type`, `keywords`, `message`, `buttons`, `images`, `audio`, `video`, `file`, `status`, `bot_name`, `postback_id`, `last_replied_at`, `is_template`) VALUES
5093 ("'.$user_id.'", "'.$auto_id.'", "'.$page_id.'", "text", "generic", "email-quick-reply","", \'{"1":{"recipient":{"id":"replace_id"},"message":{"template_type":"text","text":"Thanks, we have received your email. We will keep you updated. Thank you for being with us."}}}\', "", "", "", "", "", "1", "QUICK REPLY EMAIL REPLY", "QUICK_REPLY_EMAIL_REPLY_BOT", "0000-00-00 00:00:00", "0");';
5094 $this->db->query($sql);
5095 $insert_id=$this->db->insert_id();
5096 $sql='INSERT INTO messenger_bot_postback(user_id,postback_id,page_id,use_status,status,messenger_bot_table_id,bot_name,is_template,template_jsoncode,template_name,template_for) VALUES
5097 ("'.$user_id.'","QUICK_REPLY_EMAIL_REPLY_BOT","'.$auto_id.'","0","1","'.$insert_id.'","QUICK REPLY EMAIL REPLY","1",\'{"1":{"recipient":{"id":"replace_id"},"message":{"template_type":"text","text":"Thanks, we have received your email. We will keep you updated. Thank you for being with us."}}}\',"QUICK REPLY EMAIL REPLY","email-quick-reply")';
5098 $this->db->query($sql);
5099 }
5100 $postback_info = $this->basic->get_data("messenger_bot_postback",array("where"=>array("template_for"=>"email-quick-reply","user_id"=>$this->user_id)));
5101 $postback_id=isset($postback_info[0]['id'])?$postback_info[0]['id']:0;
5102 redirect(base_url('messenger_bot/edit_template/').$postback_id,'location');
5103 }
5104 public function edit_quick_phone_reply($auto_id="",$page_id="")
5105 {
5106 if(!$this->basic->is_exist("messenger_bot",array("postback_id"=>"QUICK_REPLY_PHONE_REPLY_BOT","page_id"=>$auto_id)))
5107 {
5108 $user_id=$this->user_id;
5109 $sql='INSERT INTO `messenger_bot` ( `user_id`, `page_id`, `fb_page_id`, `template_type`, `bot_type`, `keyword_type`, `keywords`, `message`, `buttons`, `images`, `audio`, `video`, `file`, `status`, `bot_name`, `postback_id`, `last_replied_at`, `is_template`) VALUES
5110 ("'.$user_id.'", "'.$auto_id.'", "'.$page_id.'", "text", "generic", "phone-quick-reply","", \'{"1":{"recipient":{"id":"replace_id"},"message":{"template_type":"text","text":"Thanks, we have received your phone. Thank you for being with us."}}}\', "", "", "", "", "", "1", "QUICK REPLY PHONE REPLY", "QUICK_REPLY_PHONE_REPLY_BOT", "0000-00-00 00:00:00", "0");';
5111 $this->db->query($sql);
5112 $insert_id=$this->db->insert_id();
5113 $sql='INSERT INTO messenger_bot_postback(user_id,postback_id,page_id,use_status,status,messenger_bot_table_id,bot_name,is_template,template_jsoncode,template_name,template_for) VALUES
5114 ("'.$user_id.'","QUICK_REPLY_PHONE_REPLY_BOT","'.$auto_id.'","0","1","'.$insert_id.'","QUICK REPLY PHONE REPLY","1",\'{"1":{"recipient":{"id":"replace_id"},"message":{"template_type":"text","text":"Thanks, we have received your phone. Thank you for being with us."}}}\',"QUICK REPLY PHONE REPLY","phone-quick-reply")';
5115 $this->db->query($sql);
5116 }
5117 $postback_info = $this->basic->get_data("messenger_bot_postback",array("where"=>array("template_for"=>"phone-quick-reply","user_id"=>$this->user_id)));
5118 $postback_id=isset($postback_info[0]['id'])?$postback_info[0]['id']:0;
5119 redirect(base_url('messenger_bot/edit_template/').$postback_id,'location');
5120 }
5121
5122 protected function sdk_locale()
5123 {
5124 $config = array(
5125 'default'=> 'Default',
5126 'af_ZA' => 'Afrikaans',
5127 'ar_AR' => 'Arabic',
5128 'az_AZ' => 'Azerbaijani',
5129 'be_BY' => 'Belarusian',
5130 'bg_BG' => 'Bulgarian',
5131 'bn_IN' => 'Bengali',
5132 'bs_BA' => 'Bosnian',
5133 'ca_ES' => 'Catalan',
5134 'cs_CZ' => 'Czech',
5135 'cy_GB' => 'Welsh',
5136 'da_DK' => 'Danish',
5137 'de_DE' => 'German',
5138 'el_GR' => 'Greek',
5139 'en_GB' => 'English (UK)',
5140 'en_PI' => 'English (Pirate)',
5141 'en_UD' => 'English (Upside Down)',
5142 'en_US' => 'English (US)',
5143 'eo_EO' => 'Esperanto',
5144 'es_ES' => 'Spanish (Spain)',
5145 'es_LA' => 'Spanish',
5146 'et_EE' => 'Estonian',
5147 'eu_ES' => 'Basque',
5148 'fa_IR' => 'Persian',
5149 'fb_LT' => 'Leet Speak',
5150 'fi_FI' => 'Finnish',
5151 'fo_FO' => 'Faroese',
5152 'fr_CA' => 'French (Canada)',
5153 'fr_FR' => 'French (France)',
5154 'fy_NL' => 'Frisian',
5155 'ga_IE' => 'Irish',
5156 'gl_ES' => 'Galician',
5157 'he_IL' => 'Hebrew',
5158 'hi_IN' => 'Hindi',
5159 'hr_HR' => 'Croatian',
5160 'hu_HU' => 'Hungarian',
5161 'hy_AM' => 'Armenian',
5162 'id_ID' => 'Indonesian',
5163 'is_IS' => 'Icelandic',
5164 'it_IT' => 'Italian',
5165 'ja_JP' => 'Japanese',
5166 'ka_GE' => 'Georgian',
5167 'km_KH' => 'Khmer',
5168 'ko_KR' => 'Korean',
5169 'ku_TR' => 'Kurdish',
5170 'la_VA' => 'Latin',
5171 'lt_LT' => 'Lithuanian',
5172 'lv_LV' => 'Latvian',
5173 'mk_MK' => 'Macedonian',
5174 'ml_IN' => 'Malayalam',
5175 'ms_MY' => 'Malay',
5176 'nb_NO' => 'Norwegian (bokmal)',
5177 'ne_NP' => 'Nepali',
5178 'nl_NL' => 'Dutch',
5179 'nn_NO' => 'Norwegian (nynorsk)',
5180 'pa_IN' => 'Punjabi',
5181 'pl_PL' => 'Polish',
5182 'ps_AF' => 'Pashto',
5183 'pt_BR' => 'Portuguese (Brazil)',
5184 'pt_PT' => 'Portuguese (Portugal)',
5185 'ro_RO' => 'Romanian',
5186 'ru_RU' => 'Russian',
5187 'sk_SK' => 'Slovak',
5188 'sl_SI' => 'Slovenian',
5189 'sq_AL' => 'Albanian',
5190 'sr_RS' => 'Serbian',
5191 'sv_SE' => 'Swedish',
5192 'sw_KE' => 'Swahili',
5193 'ta_IN' => 'Tamil',
5194 'te_IN' => 'Telugu',
5195 'th_TH' => 'Thai',
5196 'tl_PH' => 'Filipino',
5197 'tr_TR' => 'Turkish',
5198 'uk_UA' => 'Ukrainian',
5199 'vi_VN' => 'Vietnamese',
5200 'zh_CN' => 'Chinese (China)',
5201 'zh_HK' => 'Chinese (Hong Kong)',
5202 'zh_TW' => 'Chinese (Taiwan)',
5203 );
5204 asort($config);
5205 return $config;
5206 }
5207
5208 public function remove_persistent_menu_locale($auto_id=0,$page_auto_id=0)
5209 {
5210 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5211 redirect('home/login_page', 'location');
5212 $this->basic->delete_data("messenger_bot_persistent_menu",array("id"=>$auto_id,"user_id"=>$this->user_id));
5213 $this->session->set_flashdata('remove_persistent_menu_locale',1);
5214 redirect(base_url('messenger_bot/persistent_menu_list/'.$page_auto_id),'location');
5215 }
5216 public function remove_persistent_menu($page_auto_id=0)
5217 {
5218 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5219 redirect('home/login_page', 'location');
5220
5221 $this->load->library("messenger_bot_login");
5222 $page_info=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_auto_id,'user_id'=>$this->user_id)));
5223 if(!isset($page_info[0])) exit();
5224 $page_access_token=$page_info[0]['page_access_token'];
5225 $response=$this->messenger_bot_login->delete_persistent_menu($page_access_token);
5226 if(!isset($response['error']))
5227 {
5228 $this->basic->update_data('messenger_bot_page_info',array("id"=>$page_auto_id,'user_id'=>$this->user_id),array("persistent_enabled"=>'0'));
5229 $this->basic->delete_data('messenger_bot_persistent_menu',array("page_id"=>$page_auto_id,'user_id'=>$this->user_id));
5230 $this->session->set_flashdata('perrem_success',1);
5231 $this->_delete_usage_log($module_id=197,$request=1);
5232 }
5233 else
5234 {
5235 $err_message=isset($response['error']['message'])?$response['error']['message']:$this->lang->line("something went wrong, please try again.");
5236
5237 $this->session->set_flashdata('perrem_success',0);
5238 $this->session->set_flashdata('perrem_message',$err_message);
5239 }
5240 redirect(base_url('messenger_bot/bot_list'),'location');
5241 }
5242 public function publish_persistent_menu($page_auto_id=0)
5243 {
5244 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5245 redirect('home/login_page', 'location');
5246 $page_info=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_auto_id,'user_id'=>$this->user_id)));
5247 if(!isset($page_info[0])) exit();
5248 $page_access_token=$page_info[0]['page_access_token'];
5249 $is_already_persistent_enabled=$page_info[0]['persistent_enabled'];
5250 if($is_already_persistent_enabled=='0') // no need to check if it was already published and user is just editing menu
5251 {
5252 $status=$this->_check_usage($module_id=197,$request=1);
5253 if($status=="3")
5254 {
5255 $this->session->set_flashdata('per_success',0);
5256 $this->session->set_flashdata('per_message',$this->lang->line("You are not allowed to publish new persistent menu. Module limit has been exceeded."));
5257 $this->_insert_usage_log($module_id=197,$request=1);
5258 redirect(base_url('messenger_bot/persistent_menu_list/'.$page_auto_id),'location');
5259 }
5260 }
5261 $this->load->library("messenger_bot_login");
5262 $json_array=array();
5263 $menu_data=$this->basic->get_data("messenger_bot_persistent_menu",array("where"=>array("page_id"=>$page_auto_id,"user_id"=>$this->user_id)));
5264 foreach ($menu_data as $key => $value)
5265 {
5266 $temp=json_decode($value["item_json"],true);
5267 $temp2=isset($temp['call_to_actions'])?$temp['call_to_actions']:array();
5268
5269 if($this->session->userdata('user_type') == 'Member' && in_array(198,$this->module_access) && count($temp2)<3)
5270 {
5271 end($temp2);
5272 $key2 = key($temp2);
5273 $key2++;
5274 $copyright_text=$this->config->item("persistent_menu_copyright_text");
5275 if($copyright_text=="") $copyright_text=$this->config->item("product_name");
5276 $copyright_url=$this->config->item("persistent_menu_copyright_url");
5277 if($copyright_url=="") $copyright_url=base_url();
5278 $temp["call_to_actions"][$key2]["title"]=$copyright_text;
5279 $temp["call_to_actions"][$key2]["type"]="web_url";
5280 $temp["call_to_actions"][$key2]["url"]=$copyright_url;
5281 }
5282 $json_array["persistent_menu"][]=$temp;
5283 }
5284
5285 $json=json_encode($json_array);
5286
5287 $response=$this->messenger_bot_login->add_persistent_menu($page_access_token,$json);
5288
5289 if(!isset($response['error']))
5290 {
5291 if(!empty($postback_insert_data))
5292 $this->db->insert_batch('messenger_bot_postback',$postback_insert_data);
5293 $this->basic->update_data('messenger_bot_page_info',array("id"=>$page_auto_id,'user_id'=>$this->user_id),array("persistent_enabled"=>'1'));
5294 $this->session->set_flashdata('menu_success',1);
5295 if($is_already_persistent_enabled=='0') // no need to check if it was already published and user is just editing menu
5296 $this->_insert_usage_log($module_id=197,$request=1);
5297 redirect(base_url('messenger_bot/bot_list'),'location');
5298 }
5299 else
5300 {
5301 $err_message=isset($response['error']['message'])?$response['error']['message']:$this->lang->line("something went wrong, please try again.");
5302 $this->session->set_flashdata('per_success',0);
5303 $this->session->set_flashdata('per_message',$err_message);
5304 redirect(base_url('messenger_bot/persistent_menu_list/'.$page_auto_id),'location');
5305 }
5306 }
5307
5308 public function persistent_menu_list($page_auto_id=0)
5309 {
5310 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5311 redirect('home/login_page', 'location');
5312
5313 $data['body'] = 'persistent_menu_list';
5314 $data['page_title'] = $this->lang->line('Persistent Menu List');
5315 $page_info=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_auto_id,'user_id'=>$this->user_id)));
5316 if(!isset($page_info[0])) exit();
5317
5318 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
5319 $data["menu_info"]=$this->basic->get_data("messenger_bot_persistent_menu",array("where"=>array("page_id"=>$page_auto_id,"user_id"=>$this->user_id)));
5320 $this->_viewcontroller($data);
5321 }
5322
5323 public function create_persistent_menu($page_auto_id=0)
5324 {
5325 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5326 redirect('home/login_page', 'location');
5327
5328 $data['body'] = 'persistent_menu';
5329 $data['page_title'] = $this->lang->line('Persistent Menu');
5330 $page_info=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_auto_id,'user_id'=>$this->user_id)));
5331 if(!isset($page_info[0])) exit();
5332
5333 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
5334 $started_button_enabled = isset($page_info[0]["started_button_enabled"])?$page_info[0]["started_button_enabled"]:"0";
5335 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$page_auto_id)));
5336 $data['postback_ids'] = $postback_id_list;
5337 $data['page_auto_id'] = $page_auto_id;
5338 $data['started_button_enabled'] = $started_button_enabled;
5339 $data['locale']=$this->sdk_locale();
5340 $this->_viewcontroller($data);
5341 }
5342 public function create_persistent_menu_action()
5343 {
5344 if(!$_POST) exit();
5345 $post=$_POST;
5346 foreach ($post as $key => $value)
5347 {
5348 $$key=$value;
5349 }
5350 if($this->basic->is_exist("messenger_bot_persistent_menu",array("page_id"=>$page_table_id,"locale"=>$locale)))
5351 {
5352 echo json_encode(array('status'=>'0','message'=>$this->lang->line("persistent menu is already exists for this locale.")));
5353 exit();
5354 }
5355 $menu=array();
5356 $postback_insert_data=array();
5357 $only_postback=array();
5358 for($i=1;$i<=$level1_limit;$i++)
5359 {
5360 $level_title_temp="text_with_buttons_text_".$i;
5361 $level_type_temp="text_with_button_type_".$i;
5362 if($$level_title_temp=="") continue; // form gets everything but we need only filled data
5363 if($$level_type_temp=="post_back") $$level_type_temp="postback";
5364 $menu[$i]=array
5365 (
5366 "title"=>$$level_title_temp,
5367 "type"=> $$level_type_temp
5368 );
5369 if($$level_type_temp=="postback")
5370 {
5371 $level_postback_temp="text_with_button_post_id_".$i;
5372 // $$level_postback_temp=strtoupper($$level_postback_temp);
5373 $menu[$i]["payload"]=$$level_postback_temp;
5374 $single_postback_insert_data = array();
5375 $single_postback_insert_data['user_id'] = $this->user_id;
5376 $single_postback_insert_data['postback_id'] = $$level_postback_temp;
5377 $single_postback_insert_data['page_id'] = $page_table_id;
5378 $single_postback_insert_data['bot_name'] = '';
5379 $postback_insert_data[] = $single_postback_insert_data;
5380 $only_postback[]=$$level_postback_temp;
5381 }
5382 else if($$level_type_temp=="web_url")
5383 {
5384 $level_web_url_temp="text_with_button_web_url_".$i;
5385 $menu[$i]["url"]=$$level_web_url_temp;
5386 }
5387 else
5388 {
5389 for($j=1;$j<=$level2_limit;$j++)
5390 {
5391 $level2_title_temp="text_with_buttons_text_".$i."_".$j;
5392 $level2_type_temp="text_with_button_type_".$i."_".$j;
5393 if($$level2_title_temp=="") continue; // form gets everything but we need only filled data
5394 if($$level2_type_temp=="post_back") $$level2_type_temp="postback";
5395 $menu[$i]["call_to_actions"][$j]["title"]=$$level2_title_temp;
5396 $menu[$i]["call_to_actions"][$j]["type"]=$$level2_type_temp;
5397 if($$level2_type_temp=="postback")
5398 {
5399 $level2_postback_temp="text_with_button_post_id_".$i."_".$j;
5400 // $$level2_postback_temp=strtoupper($$level2_postback_temp);
5401 $menu[$i]["call_to_actions"][$j]["payload"]=$$level2_postback_temp;
5402 $single_postback_insert_data = array();
5403 $single_postback_insert_data['user_id'] = $this->user_id;
5404 $single_postback_insert_data['postback_id'] = $$level2_postback_temp;
5405 $single_postback_insert_data['page_id'] = $page_table_id;
5406 $single_postback_insert_data['bot_name'] = '';
5407 $postback_insert_data[] = $single_postback_insert_data;
5408 $only_postback[]=$$level2_postback_temp;
5409 }
5410 else if($$level2_type_temp=="web_url")
5411 {
5412 $level2_web_url_temp="text_with_button_web_url_".$i."_".$j;
5413 $menu[$i]["call_to_actions"][$j]["url"]=$$level2_web_url_temp;
5414 }
5415 else
5416 {
5417 for($k=1;$k<=$level3_limit;$k++)
5418 {
5419 $level3_title_temp="text_with_buttons_text_".$i."_".$j."_".$k;
5420 $level3_type_temp="text_with_button_type_".$i."_".$j."_".$k;
5421 if($$level3_title_temp=="") continue; // form gets everything but we need only filled data
5422 if($$level3_type_temp=="post_back") $$level3_type_temp="postback";
5423 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["title"]=$$level3_title_temp;
5424 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["type"]=$$level3_type_temp;
5425 if($$level3_type_temp=="postback")
5426 {
5427 $level3_postback_temp="text_with_button_post_id_".$i."_".$j."_".$k;
5428 // $$level3_postback_temp=strtoupper($$level3_postback_temp);
5429 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["payload"]=$$level3_postback_temp;
5430 $single_postback_insert_data = array();
5431 $single_postback_insert_data['user_id'] = $this->user_id;
5432 $single_postback_insert_data['postback_id'] = $$level3_postback_temp;
5433 $single_postback_insert_data['page_id'] = $page_table_id;
5434 $single_postback_insert_data['bot_name'] = '';
5435 $postback_insert_data[] = $single_postback_insert_data;
5436 $only_postback[]=$$level3_postback_temp;
5437 }
5438 else if($$level3_type_temp=="web_url")
5439 {
5440 $level3_web_url_temp="text_with_button_web_url_".$i."_".$j."_".$k;
5441 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["url"]=$$level3_web_url_temp;
5442 }
5443 }
5444 }
5445 }
5446 }
5447 }
5448 $menu_json_array=array();
5449 $menu_json_array["locale"]=$locale;
5450 $composer_input_disabled2='false';
5451 if($composer_input_disabled==='1') $composer_input_disabled2='true';
5452 $menu_json_array["composer_input_disabled"]=$composer_input_disabled2;
5453 $index=1;
5454 foreach ($menu as $key => $value)
5455 {
5456 $menu_json_array["call_to_actions"][$index]=$value;
5457 $index++;
5458 }
5459 $menu_json=json_encode($menu_json_array);
5460 $insert_data = array();
5461 $insert_data['page_id'] = $page_table_id;
5462 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token"));
5463 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
5464 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
5465 $this->db->trans_start();
5466 if(!empty($postback_insert_data)) $this->db->insert_batch('messenger_bot_postback',$postback_insert_data);
5467 $this->basic->insert_data("messenger_bot_persistent_menu",array("user_id"=>$this->user_id,"page_id"=>$page_table_id,"locale"=>$locale,"item_json"=>$menu_json,"composer_input_disabled"=>$composer_input_disabled,'poskback_id_json'=>json_encode($only_postback)));
5468 $this->db->trans_complete();
5469 if ($this->db->trans_status() === FALSE)
5470 echo json_encode(array('status'=>'0','message'=>$this->lang->line("something went wrong, please try again.")));
5471 else
5472 {
5473 $this->session->set_flashdata('per_success',1);
5474 echo json_encode(array('status'=>'1','message'=>$this->lang->line("persistent menu has been created successfully.")));
5475 }
5476 }
5477 public function edit_persistent_menu($id=0)
5478 {
5479 if($this->session->userdata('user_type') != 'Admin' && !in_array(197,$this->module_access))
5480 redirect('home/login_page', 'location');
5481
5482 $data['body'] = 'persistent_menu_edit';
5483 $data['page_title'] = $this->lang->line('Edit Persistent Menu');
5484 $xdata=$this->basic->get_data("messenger_bot_persistent_menu",array("where"=>array("id"=>$id,"user_id"=>$this->user_id)));
5485 if(!isset($xdata[0])) exit();
5486 $data['xdata']=$xdata[0];
5487 $page_auto_id=$xdata[0]["page_id"];
5488 $page_info=$this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_auto_id,'user_id'=>$this->user_id)));
5489 if(!isset($page_info[0])) exit();
5490
5491 $data['page_info'] = isset($page_info[0]) ? $page_info[0] : array();
5492 $started_button_enabled = isset($page_info[0]["started_button_enabled"])?$page_info[0]["started_button_enabled"]:"0";
5493 $postback_id_list = $this->basic->get_data('messenger_bot_postback',array('where'=>array('user_id'=>$this->user_id,'page_id'=>$page_auto_id)));
5494 $data['postback_ids'] = $postback_id_list;
5495 $data['page_auto_id'] = $page_auto_id;
5496 $data['started_button_enabled'] = $started_button_enabled;
5497 $data['locale']=$this->sdk_locale();
5498 $this->_viewcontroller($data);
5499 }
5500 public function edit_persistent_menu_action()
5501 {
5502 if(!$_POST) exit();
5503 $post=$_POST;
5504 foreach ($post as $key => $value)
5505 {
5506 $$key=$value;
5507 }
5508 if($this->basic->is_exist("messenger_bot_persistent_menu",array("page_id"=>$page_table_id,"locale"=>$locale,"id!="=>$auto_id)))
5509 {
5510 echo json_encode(array('status'=>'0','message'=>$this->lang->line("persistent menu is already exists for this locale.")));
5511 exit();
5512 }
5513 $menu=array();
5514 $postback_insert_data=array();
5515 $only_postback=array();
5516 $current_postbacks=json_decode($current_postbacks,true);
5517 $current_postbacks=array_map('strtoupper', $current_postbacks);
5518 for($i=1;$i<=$level1_limit;$i++)
5519 {
5520 $level_title_temp="text_with_buttons_text_".$i;
5521 $level_type_temp="text_with_button_type_".$i;
5522 if($$level_title_temp=="") continue; // form gets everything but we need only filled data
5523 if($$level_type_temp=="post_back") $$level_type_temp="postback";
5524 $menu[$i]=array
5525 (
5526 "title"=>$$level_title_temp,
5527 "type"=> $$level_type_temp
5528 );
5529 if($$level_type_temp=="postback")
5530 {
5531 $level_postback_temp="text_with_button_post_id_".$i;
5532 // $$level_postback_temp=strtoupper($$level_postback_temp);
5533 $menu[$i]["payload"]=$$level_postback_temp;
5534 $single_postback_insert_data = array();
5535 $single_postback_insert_data['user_id'] = $this->user_id;
5536 $single_postback_insert_data['postback_id'] = $$level_postback_temp;
5537 $single_postback_insert_data['page_id'] = $page_table_id;
5538 $single_postback_insert_data['bot_name'] = '';
5539 if(!in_array(strtoupper($$level_postback_temp), $current_postbacks))
5540 $postback_insert_data[] = $single_postback_insert_data;
5541 $only_postback[]=$$level_postback_temp;
5542 }
5543 else if($$level_type_temp=="web_url")
5544 {
5545 $level_web_url_temp="text_with_button_web_url_".$i;
5546 $menu[$i]["url"]=$$level_web_url_temp;
5547 }
5548 else
5549 {
5550 for($j=1;$j<=$level2_limit;$j++)
5551 {
5552 $level2_title_temp="text_with_buttons_text_".$i."_".$j;
5553 $level2_type_temp="text_with_button_type_".$i."_".$j;
5554 if($$level2_title_temp=="") continue; // form gets everything but we need only filled data
5555 if($$level2_type_temp=="post_back") $$level2_type_temp="postback";
5556 $menu[$i]["call_to_actions"][$j]["title"]=$$level2_title_temp;
5557 $menu[$i]["call_to_actions"][$j]["type"]=$$level2_type_temp;
5558 if($$level2_type_temp=="postback")
5559 {
5560 $level2_postback_temp="text_with_button_post_id_".$i."_".$j;
5561 // $$level2_postback_temp=strtoupper($$level2_postback_temp);
5562 $menu[$i]["call_to_actions"][$j]["payload"]=$$level2_postback_temp;
5563 $single_postback_insert_data = array();
5564 $single_postback_insert_data['user_id'] = $this->user_id;
5565 $single_postback_insert_data['postback_id'] = $$level2_postback_temp;
5566 $single_postback_insert_data['page_id'] = $page_table_id;
5567 $single_postback_insert_data['bot_name'] = '';
5568 if(!in_array(strtoupper($$level2_postback_temp), $current_postbacks))
5569 $postback_insert_data[] = $single_postback_insert_data;
5570 $only_postback[]=$$level2_postback_temp;
5571 }
5572 else if($$level2_type_temp=="web_url")
5573 {
5574 $level2_web_url_temp="text_with_button_web_url_".$i."_".$j;
5575 $menu[$i]["call_to_actions"][$j]["url"]=$$level2_web_url_temp;
5576 }
5577 else
5578 {
5579 for($k=1;$k<=$level3_limit;$k++)
5580 {
5581 $level3_title_temp="text_with_buttons_text_".$i."_".$j."_".$k;
5582 $level3_type_temp="text_with_button_type_".$i."_".$j."_".$k;
5583 if($$level3_title_temp=="") continue; // form gets everything but we need only filled data
5584 if($$level3_type_temp=="post_back") $$level3_type_temp="postback";
5585 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["title"]=$$level3_title_temp;
5586 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["type"]=$$level3_type_temp;
5587 if($$level3_type_temp=="postback")
5588 {
5589 $level3_postback_temp="text_with_button_post_id_".$i."_".$j."_".$k;
5590 // $$level3_postback_temp=strtoupper($$level3_postback_temp);
5591 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["payload"]=$$level3_postback_temp;
5592 $single_postback_insert_data = array();
5593 $single_postback_insert_data['user_id'] = $this->user_id;
5594 $single_postback_insert_data['postback_id'] = $$level3_postback_temp;
5595 $single_postback_insert_data['page_id'] = $page_table_id;
5596 $single_postback_insert_data['bot_name'] = '';
5597 if(!in_array(strtoupper($$level3_postback_temp), $current_postbacks))
5598 $postback_insert_data[] = $single_postback_insert_data;
5599 $only_postback[]=$$level3_postback_temp;
5600 }
5601 else if($$level3_type_temp=="web_url")
5602 {
5603 $level3_web_url_temp="text_with_button_web_url_".$i."_".$j."_".$k;
5604 $menu[$i]["call_to_actions"][$j]["call_to_actions"][$k]["url"]=$$level3_web_url_temp;
5605 }
5606 }
5607 }
5608 }
5609 }
5610 }
5611 $menu_json_array=array();
5612 $menu_json_array["locale"]=$locale;
5613 $composer_input_disabled2='false';
5614 if($composer_input_disabled==='1') $composer_input_disabled2='true';
5615 $menu_json_array["composer_input_disabled"]=$composer_input_disabled2;
5616 $index=1;
5617 foreach ($menu as $key => $value)
5618 {
5619 $menu_json_array["call_to_actions"][$index]=$value;
5620 $index++;
5621 }
5622 $menu_json=json_encode($menu_json_array);
5623 $insert_data = array();
5624 $insert_data['page_id'] = $page_table_id;
5625 $messenger_bot_user_info_id = $this->basic->get_data("messenger_bot_page_info",array("where"=>array("id"=>$page_table_id)),array("messenger_bot_user_info_id","page_access_token"));
5626 $page_access_token = $messenger_bot_user_info_id[0]['page_access_token'];
5627 $messenger_bot_user_info_id = $messenger_bot_user_info_id[0]["messenger_bot_user_info_id"];
5628
5629 $this->db->trans_start();
5630 if(!empty($postback_insert_data)) $this->db->insert_batch('messenger_bot_postback',$postback_insert_data);
5631 $this->basic->update_data("messenger_bot_persistent_menu",array("id"=>$auto_id,"user_id"=>$this->user_id),array("locale"=>$locale,"item_json"=>$menu_json,"composer_input_disabled"=>$composer_input_disabled,'poskback_id_json'=>json_encode($only_postback)));
5632 $this->db->trans_complete();
5633 if ($this->db->trans_status() === FALSE)
5634 echo json_encode(array('status'=>'0','message'=>$this->lang->line("something went wrong, please try again.")));
5635 else
5636 {
5637 $this->session->set_flashdata('per_update_success',1);
5638 echo json_encode(array('status'=>'1','message'=>$this->lang->line("persistent menu has been updated successfully.")));
5639 }
5640 }
5641
5642 public function configuration()
5643 {
5644 if ($this->session->userdata('logged_in') == 1 && $this->session->userdata('user_type') != 'Admin') {
5645 redirect('home/login_page', 'location');
5646 }
5647
5648 $data['body'] = "edit_config";
5649 $data['page_title'] = $this->lang->line('general settings')." : ".$this->lang->line('messenger bot');
5650 $this->_viewcontroller($data);
5651 }
5652
5653 public function edit_config()
5654 {
5655 if ($_SERVER['REQUEST_METHOD'] === 'GET') {
5656 redirect('home/access_forbidden', 'location');
5657 }
5658 if ($_POST)
5659 {
5660 $this->form_validation->set_rules('backup_mode', '<b>'.$this->lang->line("Backup Mode").'</b>','trim');
5661 $this->form_validation->set_rules('persistent_menu_copyright_text', '<b>'.$this->lang->line("persistent menu copyright text").'</b>','trim');
5662 $this->form_validation->set_rules('persistent_menu_copyright_url', '<b>'.$this->lang->line("persistent menu copyright URL").'</b>','trim');
5663 $this->form_validation->set_rules('has_manage_page_approval', '<b>'.$this->lang->line("User login type").'</b>','trim');
5664 // go to config form page if validation wrong
5665 if ($this->form_validation->run() == false)
5666 {
5667 return $this->configuration();
5668 }
5669 else
5670 {
5671 $backup_mode=addslashes(strip_tags($this->input->post('backup_mode', true)));
5672 $persistent_menu_copyright_text=addslashes(strip_tags($this->input->post('persistent_menu_copyright_text', true)));
5673 $persistent_menu_copyright_url=addslashes(strip_tags($this->input->post('persistent_menu_copyright_url', true)));
5674 $has_manage_page_approval=addslashes(strip_tags($this->input->post('has_manage_page_approval', true)));
5675 // writing application/config/my_config
5676 $app_my_config_data = "<?php ";
5677 $app_my_config_data.= "\n\$config['webhook_verify_token'] = '".$this->config->item('webhook_verify_token')."';\n";
5678 if($backup_mode == 'yes') $mode_to_write = 1;
5679 else $mode_to_write = 0;
5680 $app_my_config_data.= "\$config['bot_backup_mode'] = '$mode_to_write';\n";
5681
5682 if($persistent_menu_copyright_text!="")
5683 $app_my_config_data.= "\$config['persistent_menu_copyright_text'] = '$persistent_menu_copyright_text';\n";
5684 if($persistent_menu_copyright_url!="")
5685 $app_my_config_data.= "\$config['persistent_menu_copyright_url'] = '$persistent_menu_copyright_url';\n";
5686 $app_my_config_data.= "\$config['has_manage_page_approval'] = '$has_manage_page_approval';";
5687 file_put_contents(APPPATH.'modules/'.strtolower($this->router->fetch_class()).'/config/messenger_bot_config.php', $app_my_config_data, LOCK_EX);
5688
5689 $admin_info = $this->basic->get_data("users",array("where"=>array('user_type'=>'Admin')),array('id'));
5690 $admin_ids = array();
5691 foreach($admin_info as $value)
5692 {
5693 array_push($admin_ids, $value['id']);
5694 }
5695
5696 // Messenger Bot
5697 if($this->basic->is_exist("modules",$where=array('id'=>200)))
5698 {
5699 $admin_app_info = $this->basic->get_data("messenger_bot_config",array("where_in"=>array("user_id"=>$admin_ids)),array("id"));
5700 $admin_app_ids = array();
5701 foreach($admin_app_info as $apps)
5702 {
5703 array_push($admin_app_ids, $apps['id']);
5704 }
5705 if($mode_to_write == 1)
5706 {
5707 if(!empty($admin_app_ids))
5708 {
5709 $this->db->where_in('messenger_bot_config_id', $admin_app_ids);
5710 $this->db->where_not_in('user_id', $admin_ids);
5711 $this->db->update("messenger_bot_user_info",array("need_to_delete"=>"1"));
5712 }
5713 }
5714 else
5715 {
5716 if(!empty($admin_app_ids))
5717 {
5718 $this->db->where_in('messenger_bot_config_id', $admin_app_ids);
5719 $this->db->where_not_in('user_id', $admin_ids);
5720 $this->db->update("messenger_bot_user_info",array("need_to_delete"=>"0"));
5721 }
5722 }
5723 }
5724 // Messenger Bot
5725
5726 $this->session->set_flashdata('success_message', 1);
5727 redirect('messenger_bot/configuration', 'location');
5728 }
5729 }
5730 }
5731 public function cron_job()
5732 {
5733 if($this->session->userdata('user_type') != 'Admin')
5734 redirect('home/login_page', 'location');
5735
5736 $data['body'] = "cron_job";
5737 $data['page_title'] = 'cron job';
5738 $api_data=$this->basic->get_data("native_api",array("where"=>array("user_id"=>$this->session->userdata("user_id"))));
5739 $data["api_key"]="";
5740 if(count($api_data)>0) $data["api_key"]=$api_data[0]["api_key"];
5741 $this->_viewcontroller($data);
5742 }
5743 function download_profile_pic($api_key){
5744
5745 $this->api_key_check($api_key);
5746 $subscriber_info = $this->basic->get_data('messenger_bot_subscriber',array('where'=>array('is_image_download'=>'0')),$select='',$join='',$limit=10);
5747
5748 foreach($subscriber_info as $info){
5749
5750 $profile_pic_url=$info['profile_pic'];
5751 $subscribe_id=$info['subscribe_id'];
5752 $subscribe_auto_id=$info['id'];
5753
5754 $upload_path="upload/subscriber_pic";
5755
5756 if(!file_exists($upload_path))
5757 mkdir($upload_path,0755);
5758
5759 $user_pic_name=$upload_path."/".$subscribe_id.".png";
5760
5761
5762 $content= @file_get_contents($profile_pic_url);
5763
5764 if($content===FALSE){
5765
5766 $this->basic->update_data("messenger_bot_subscriber",array("id"=>$subscribe_auto_id),array("is_image_download"=>"1"));
5767
5768 }
5769 else{
5770 file_put_contents($user_pic_name,$content);
5771 $this->basic->update_data("messenger_bot_subscriber",array("id"=>$subscribe_auto_id),array("is_image_download"=>"1","image_path"=>$user_pic_name));
5772 }
5773 }
5774
5775 }
5776 private function api_key_check($api_key="")
5777 {
5778 $user_id="";
5779 if($api_key!="")
5780 {
5781 $explde_api_key=explode('-',$api_key);
5782 $user_id="";
5783 if(array_key_exists(0, $explde_api_key))
5784 $user_id=$explde_api_key[0];
5785 }
5786 if($api_key=="")
5787 {
5788 echo "API Key is required.";
5789 exit();
5790 }
5791 if(!$this->basic->is_exist("native_api",array("api_key"=>$api_key,"user_id"=>$user_id)))
5792 {
5793 echo "API Key does not match with any user.";
5794 exit();
5795 }
5796 if(!$this->basic->is_exist("users",array("id"=>$user_id,"status"=>"1","deleted"=>"0","user_type"=>"Admin")))
5797 {
5798 echo "API Key does not match with any authentic user.";
5799 exit();
5800 }
5801 }
5802
5803
5804}