· 7 years ago · Sep 12, 2018, 04:02 PM
1 //==============================================================================
2 // submit()
3 //==============================================================================
4 public function submit() {
5 $this->load->model((version_compare(VERSION, '3.0', '<') ? 'extension' : 'setting') . '/module');
6 $form = $this->{'model_' . (version_compare(VERSION, '3.0', '<') ? 'extension' : 'setting') . '_module'}->getModule($this->request->get['module_id']);
7 // AOE Summit Code
8 $customerType = '';
9 $refererType = '';
10 $deliveryMethod = '';
11 $message = '0';
12 $modelCode='0';
13 $gtmData = '';
14 $str = '';
15 $jsonResponse = array();
16 $formResponse = array();
17 $form_response_id = 0;
18 if(isset($_REQUEST['model'])) {
19 $modelCode = $_REQUEST['model'];
20 }
21 // AOE Summit Code End
22 if (!$form['status']) return;
23
24 $language = (isset($this->session->data['language'])) ? $this->session->data['language'] : $this->config->get('config_language');
25 $store_name = $this->config->get('config_name');
26 if (is_array($store_name)) $store_name = array_shift($store_name);
27 // Build jsonRespone for opportunity
28 $jsonResponse['form_id'] = $form['module_id'];
29 $jsonResponse['form_name'] = $form['name'];
30 $jsonResponse['form_title'] = $form['heading_'.$language];
31 $jsonResponse['store'] = $store_name;
32 $jsonResponse['form_customer_email'] = (isset($form['customer_email']) ? $form['customer_email']:'');
33 $jsonResponse['created_at'] = date("Y-m-d H:i:s");
34 $jsonResponse['customer_id'] = $this->customer->getId();
35
36 // Check captcha
37
38 foreach ($form['fields'] as $field) {
39 if(!isset($field['type'])) continue;
40
41 // AOE Summit Code
42 if($field['type'] == 'submit' ) {
43 $message = $form['success_message_'.$language];
44 }
45 if($field['type'] == 'modelselector') {
46 $modelCode = $_REQUEST[$field['key']];
47 }
48 // AOE Summit Code End
49
50 if ($field['type'] == 'captcha') {
51 if (!empty($form['recaptcha_secret_key'])) {
52 $secret_key = $form['recaptcha_secret_key'];
53 } elseif (version_compare(VERSION, '2.1', '<')) {
54 $secret_key = $this->config->get('config_google_captcha_secret');
55 } elseif (version_compare(VERSION, '3.0', '<')) {
56 $secret_key = $this->config->get('google_captcha_secret');
57 } else {
58 $secret_key = $this->config->get('captcha_google_secret');
59 }
60
61 $recaptcha = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret_key) . '&response=' . $this->request->get['captcha'] . '&remoteip=' . $this->request->server['REMOTE_ADDR']), true);
62
63 if (!$recaptcha['success']) {
64 echo $form['error_captcha_' . $language];
65 return;
66 }
67 }
68 }
69
70 // Set up e-mail
71 if (version_compare(VERSION, '2.0.2', '<')) {
72 $mail = new Mail($this->config->get('config_mail'));
73 } else {
74 if (version_compare(VERSION, '3.0', '<')) {
75 $mail = new Mail();
76 $mail->protocol = $this->config->get('config_mail_protocol');
77 $protocol_engine = $this->config->get('config_mail_protocol');
78 } else {
79 $mail = new Mail($this->config->get('config_mail_engine'));
80 $protocol_engine = $this->config->get('config_mail_engine');
81 }
82 $mail->parameter = $this->config->get('config_mail_parameter');
83 $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
84 $mail->smtp_username = $this->config->get('config_mail_smtp_username');
85 $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
86 $mail->smtp_port = $this->config->get('config_mail_smtp_port');
87 $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
88 }
89
90 // Format responses
91 $responses = array();
92 $customer_emails = array();
93 $files = array();
94 $admin_response_list = '';
95 $customer_response_list = '';
96
97 /* sort fields by Key
98 $sort_field = array();
99 foreach ($form['fields'] as $key => $value) $sort_field[$key] = $value['key'];
100 array_multisort($sort_field, SORT_ASC, $form['fields']);
101 */
102
103 $replace = array();
104 $with = array();
105
106 foreach ($form['fields'] as $field) {
107
108 if(!isset($field['type'])) continue;
109
110 if (in_array($field['type'], array('captcha', 'html', 'submit'))) continue;
111
112 $response = (isset($_REQUEST[$field['key']])) ? $_REQUEST[$field['key']] : '';
113 $responses[$field['key']] = ($field['type'] == 'file') ? array() : $response;
114
115 if ($field['type'] == 'email' && !empty($response)) {
116 $customer_emails[] = trim($response);
117 $jsonResponse["form_customer_email"] = trim($response);
118 // MailChimp Integration connection
119 $prefix = (version_compare(VERSION, '3.0', '<')) ? '' : 'module_';
120 if ($field['key'] == 'mailchimp' && $this->config->get($prefix . 'mailchimp_integration_status')) {
121 if (version_compare(VERSION, '2.1', '<')) $this->load->library('mailchimp_integration');
122 $mailchimp_integration = new MailChimp_Integration($this->config, $this->db, $this->session, $this->url);
123 $mailchimp_integration->send(array('email' => $response, 'newsletter' => 1));
124 }
125 } elseif ($field['type'] == 'file' && !empty($response)) {
126 $filename_array = array();
127 foreach ($response as $encrypted_file) {
128 if (version_compare(VERSION, '2.1', '<')) $this->load->library('encryption');
129 $encryption = new Encryption($this->config->get('config_encryption'));
130 $decrypted_file = $encryption->decrypt($encrypted_file);
131
132 $filename = str_replace(strrchr(basename($decrypted_file), '.'), '', basename($decrypted_file));
133
134 $i = 1;
135 while (file_exists(DIR_CACHE . $filename)) {
136 $filename = $i . '-' . $filename;
137 $i++;
138 }
139
140 $filename_array[] = $filename;
141 $responses[$field['key']][] = $decrypted_file;
142
143 if (file_exists(DIR_DOWNLOAD . $decrypted_file)) {
144 copy(DIR_DOWNLOAD . $decrypted_file, DIR_CACHE . $filename);
145 if (!$form['record_responses']) {
146 unlink(DIR_DOWNLOAD . $decrypted_file);
147 }
148
149 $mail->addAttachment(DIR_CACHE . $filename);
150 $files[] = DIR_CACHE . $filename;
151 }
152 }
153 $response = $filename_array;
154 } else if ($field['type'] == 'modelselector') {
155
156 $modelCode = $response;
157 if($modelCode == '-1') {
158 $response = 'None Selected';
159 }
160 }
161
162 $response_string = (is_array($response)) ? nl2br(implode(', ', $response)) : nl2br($response);
163 $formResponse[$field['key']] = $response_string;
164 $replace[] = '[' . $field['key'] . ']';
165 $with[] = $response_string;
166
167 $field_title = strip_tags(html_entity_decode($field['title_' . $language], ENT_QUOTES, 'UTF-8'));
168 $response_list_line = '<tr><td style="white-space: nowrap"><strong>' . $field_title . (strpos($field_title, ':') === false ? ':' : '') . '</strong></td> <td>' . $response_string . '</td></tr>' . "\n";
169 $admin_response_list .= $response_list_line;
170 if ($field['type'] != 'hidden' || !empty($field['email'])) {
171 $customer_response_list .= $response_list_line;
172 }
173 }
174
175 // Put together cart contents
176 $products = $this->cart->getProducts();
177 if (strpos($form['admin_message_' . $language], '[cart_contents]') && !empty($products)) {
178 $cart_contents = '<table><tr><td style="white-space: nowrap"><strong>Cart Contents:</strong></td> <td>';
179 $responses['CartContents'] = '';
180
181 foreach ($products as $product) {
182 $options_text = '';
183 if (!empty($product['option'])) {
184 $options = array();
185 foreach ($product['option'] as $option) {
186 $options[] = $option['name'] . ': ' . $option['value'];
187 }
188 $options_text = '(' . implode(', ', $options) . ')';
189 }
190
191 $product_text = '- ' . $product['name'] . $options_text . ' x ' . $product['quantity'] . ': ' . $this->currency->format($product['total'], $this->session->data['currency']) . '<br />' . "\n";
192 $cart_contents .= $product_text;
193 $responses['CartContents'] .= $product_text;
194 }
195
196 if ($this->cart->countProducts() > 1) {
197 $cart_contents .= '<b>Total: ' . $this->currency->format($this->cart->getSubTotal(), $this->session->data['currency']) . '</b>';
198 }
199 $cart_contents .= '</td></tr></table>' . "\n";
200
201 $replace[] = '[cart_contents]';
202 $with[] = $cart_contents;
203 }
204
205 foreach($_REQUEST as $name => $value) {
206 $splitString = explode("_", $name);
207 if(count($splitString) > 1) {
208 $dateField = $splitString[0]."_".$splitString[1];
209 if ($dateField == "form".$form['module_id']."_d") {
210 $responses[$splitString[2]] = $_REQUEST[$name];
211 $formResponse[$splitString[2]] = $_REQUEST[$name];
212 }
213 if ($dateField == "form".$form['module_id']."_t") {
214 $responses[$splitString[2].'_slot'] = $_REQUEST[$name];
215 $formResponse[$splitString[2].'_slot'] = $_REQUEST[$name];
216 }
217 }
218 }
219
220 // Record response into database
221 if ($form['record_responses']) {
222 $this->db->query("
223 INSERT INTO " . DB_PREFIX . "form_builder_response SET
224 module_id = " . (int)$this->request->get['module_id'] . ",
225 customer_id = " . (int)$this->customer->getId() . ",
226 date_added = NOW(),
227 ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "',
228 response = '" . $this->db->escape(serialize($responses)) . "',
229 readable_response = '" . $this->db->escape(strip_tags($admin_response_list)) . "'
230 ");
231 // Call Opportunity API to submit for response
232 $form_response_id = $this->db->getLastId();
233 $jsonResponse['form_builder_response_id'] = $form_response_id;
234 if (isset($form['form_type'])) {
235 $jsonResponse["form_type"] = $form['form_type'];
236 }
237 if(isset($_SERVER["HTTP_REFERER"])) {
238 if(strpos($_SERVER["HTTP_REFERER"],'dealer') !== false) {
239 $refererType = 'dealer';
240 } else {
241 $refererType = 'national';
242 }
243 }
244 if(isset($_REQUEST['customerType'])) {
245 $customerType = $_REQUEST['customerType'];
246 }
247 if(isset($_REQUEST['deliverymethod'])) {
248 $deliveryMethod = $_REQUEST['deliverymethod'];
249 }
250 if(isset($_COOKIE['_ga'])) {
251 $jsonResponse['ga_cookie'] = $_COOKIE['_ga'];
252 }
253 $jsonResponse["campaign_code"] = $this->getCampaignCode($refererType,$customerType,$deliveryMethod,$form['module_id']);
254 $jsonResponse['response'] = $formResponse;
255 $record_id = $this->sendOpportunity($form_response_id,json_encode($jsonResponse));
256
257 if($record_id){
258 $this->db->query("
259 UPDATE " . DB_PREFIX . "form_builder_response SET
260 exported = NOW(),
261 opportunity_reference = '" . $this->db->escape($record_id) . "'
262 WHERE form_builder_response_id =".$form_response_id);
263 }
264
265 }
266
267 // Send out e-mails
268
269 // only send emails to admins if its enabled
270 if(isset($form['enable_admin_emails']) && $form['enable_admin_emails']) {
271
272 $admin_emails = array_map('trim', explode(',', $form['admin_email']));
273 $first_admin = '';
274
275 $html = html_entity_decode($form['admin_message_' . $language], ENT_QUOTES, 'UTF-8');
276 $html = str_replace($replace, $with, $html);
277 $html = str_replace('[form_responses]', '<table>' . $admin_response_list . '</table>', $html);
278
279 $html = $this->replaceShortcodesByModel($html, $modelCode);
280 $html = $this->replaceShortcodes($html, $form);
281
282
283 $mail->setSender(!empty($customer_emails) ? $customer_emails[0] : str_replace(array(',', '&'), array('', 'and'), html_entity_decode($store_name, ENT_QUOTES, 'UTF-8')));
284 $mail->setSubject($this->replaceShortcodes(str_replace($replace, $with, $form['admin_subject_' . $language]), $form));
285 $mail->setHtml($html);
286 $mail->setText(strip_tags($html));
287
288 foreach ($admin_emails as $email) {
289 if (strpos($email, ':')) {
290 $if_then = array_map('trim', explode('=', $email));
291 $key_value = array_map('trim', explode(':', $if_then[0]));
292 if (empty($responses[$key_value[0]]) || $responses[$key_value[0]] != $key_value[1]) {
293 continue;
294 }
295 $email = $if_then[1];
296 }
297
298 if ($protocol_engine == 'smtp') {
299 $mail->setFrom($this->config->get('config_email'));
300 } else {
301 $mail->setFrom($email);
302 }
303
304 $mail->setReplyTo(!empty($customer_emails) ? $customer_emails[0] : $email);
305 $mail->setTo($email);
306 $mail->send();
307
308 if (empty($first_admin)) {
309 $first_admin = $email;
310 }
311 }
312 }
313
314 if (!empty($customer_emails) && $form['customer_email']) {
315 $html = html_entity_decode($form['customer_message_' . $language], ENT_QUOTES, 'UTF-8');
316 // Code for IF condition
317 $blocks = $this->mappingConditions($html);
318
319 foreach($blocks as $block){
320 if(isset($_REQUEST[$block['fieldKey']])) {
321 if($_REQUEST[$block['fieldKey']] == $block['fieldVal']) {
322 $html = str_replace($block['mainBlock'],$block['showBlock'],$html);
323 } else if (is_array($_REQUEST[$block['fieldKey']])) {
324 foreach($_REQUEST[$block['fieldKey']] as $fieldKey) {
325 if($fieldKey == $block['fieldVal']) {
326 $html = str_replace($block['mainBlock'],$block['showBlock'],$html);
327 }
328 }
329
330 } else {
331 $html = str_replace($block['mainBlock'],'',$html);
332 }
333 }
334 else
335 {
336 $html = str_replace($block['mainBlock'],'',$html);
337 }
338 }
339 // End of code for IF condition
340 $html = str_replace($replace, $with, $html);
341 $html = str_replace('[form_responses]', '<table>' . $customer_response_list . '</table>', $html);
342 $html = $this->replaceShortcodesByModel($html, $modelCode);
343 $html = $this->replaceShortcodes($html, $form);
344
345 if ($protocol_engine == 'smtp') {
346 $mail->setFrom($form['admin_from']);
347 } else {
348 $mail->setFrom($form['admin_from']);
349 }
350
351 $mail->setSender($form['admin_sender']);
352 $mail->setSubject($this->replaceShortcodes(str_replace($replace, $with, $form['customer_subject_' . $language]), $form));
353 $mail->setHtml($html);
354 $mail->setText(strip_tags($html));
355
356 foreach ($customer_emails as $email) {
357 $mail->setTo($email);
358 $mail->send();
359 }
360 }
361 // AOE Code for GTM Data Layer Object
362
363 $modelData = array();
364 $pageNamePrefix = "-1";
365 $virtualPageSuccess = "-1";
366
367 if($modelCode != '-1') {
368 $this->load->model('extension/summit/vehicle_model_selector');
369
370 $modelData = $this->model_extension_summit_vehicle_model_selector->getVehicleByModel($modelCode);
371
372 }
373 $str = "";
374 if(!empty($form['datalayer_success_page_'.$language]) )
375 {
376 $originalStr = $form['datalayer_success_page_'.$language];
377 $arrStr = explode("\n", $originalStr);
378 $countVal = 0;
379 foreach($arrStr as $val)
380 {
381 $valArr = explode(":", $val);
382 if($countVal > 0)
383 {
384 $str .= ",";
385 }
386 $str .= '"'.$valArr[0].'":"'.$valArr[1].'"';
387 $countVal = 1;
388
389 }
390 if($form['virtual_page'] == "0" || $form['virtual_page'] == "2" )
391 {
392 $virtualPageSuccess = $form["virtual_page_success"];
393
394 }
395 if(isset($form['page_name']) && ($form['page_name'] == "0" || $form['page_name'] == "2"))
396 {
397 $pageNamePrefix = isset($form['page_name_prefix']) ? $form['page_name_prefix'] : '';
398 $pageNamePrefix .= isset($form['success_page_name_prefix']) ? $form['success_page_name_prefix'] : '';
399 }
400 if($form['vehicle_model_style'] == "0" || $form['vehicle_model_style'] == "2" )
401 {
402 if(isset($modelData['model_lcdv']))
403 {
404 $str .= ',"vehicleModelBodystyle":"'.$modelData['model_lcdv'].'"';
405 }
406
407 }
408 if($form['forms_lead_type'] == "0" || $form['forms_lead_type'] == "2" )
409 {
410 $str .= ',"formleadType":"'.$form['forms_lead_type_success'].'"';
411
412 }
413 if($form['page_category'] == "0" || $form['page_category'] == "2")
414 {
415 $str .= ',"pageCategory":"'.$form['page_category_success'].'"';
416
417 }
418
419 if($form['vehicle_model_style_label'] == "0" || $form['vehicle_model_style_label'] == "2")
420 {
421 if($modelCode != '-1' && $modelCode != '0')
422 {
423 $str .= ',"vehicleModelBodystyleLabel":"'.$modelCode.'"';
424 }
425
426 }
427 $gtmData = $str;
428 }
429
430 // End Code for GTM Data Layer
431 // AOE IF Condition Mapping
432 $blocks = $this->mappingConditions($message);
433
434 foreach($blocks as $block){
435 if(isset($_REQUEST[$block['fieldKey']])) {
436 if($_REQUEST[$block['fieldKey']] == $block['fieldVal']) {
437 $message = str_replace($block['mainBlock'],$block['showBlock'],$message);
438 } else if (is_array($_REQUEST[$block['fieldKey']])) {
439 foreach($_REQUEST[$block['fieldKey']] as $fieldKey) {
440 if($fieldKey == $block['fieldVal']) {
441 $message = str_replace($block['mainBlock'],$block['showBlock'],$message);
442 }
443 }
444
445 } else {
446 $message = str_replace($block['mainBlock'],'',$message);
447 }
448 }
449 else
450 {
451 $message = str_replace($block['mainBlock'],'',$message);
452 }
453 }
454 // End If Condition Mapping
455 // Destroy files
456 foreach ($files as $file) {
457 if (file_exists($file)) unlink($file);
458 }
459
460
461 $message = $this->replaceShortcodesByModel($message,$modelCode);
462 $message = $this->replaceShortcodes($message, $form);
463
464 $message = $message;
465
466 $json = array();
467 $json['success'] = 'success';
468 $json['pageNamePrefix'] = $pageNamePrefix;
469 $json['virtualPageSuccess'] = $virtualPageSuccess;
470 $json['message'] = html_entity_decode(trim($message), ENT_QUOTES, 'UTF-8');
471 $json['gtmData'] ='{'.$gtmData.'}';
472 $json['form_response_id'] = $form_response_id;
473 $json['form_id'] =$form['module_id'];
474 $json['formresponse'] = json_encode($formResponse);
475
476 $callback = $this->validateRequest($this->request->get['callback']);
477 if($callback) {
478 $this->response->setOutput($callback."(".json_encode($json).")");
479 } else {
480 $this->response->setOutput('Invalid request!');
481 }
482 }