PluginProbe
Connector for Gravity Forms and Google Sheets / 1.2.5
Connector for Gravity Forms and Google Sheets v1.2.5
1.3.0 trunk 1.0.2 1.0.3 1.0.4 1.0.7 1.1.1 1.2.0 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9
wp-gravity-forms-spreadsheets / wp-gravity-forms-spreadsheets.php

wp-gravity-forms-spreadsheets.php in Connector for Gravity Forms and Google Sheets 1.2.5, at wp-gravity-forms-spreadsheets.php

1,851 lines 64.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: Connector for Gravity Forms and Google Sheets
4 * Description: Integrates Gravity Forms with Google Sheets allowing form submissions to be automatically sent to your Google Sheets.
5 * Version: 1.2.5
6 * Requires at least: 3.8
7 * Author URI: https://www.crmperks.com
8 * Plugin URI: https://www.crmperks.com/plugins/gravity-forms-plugins/gravity-forms-google-sheets-plugin/
9 * Author: CRM Perks.
10 * Text Domain: gravity-forms-googlesheets-crm
11 * Domain Path: /languages/
12 */
13 // Exit if accessed directly
14 if( !defined( 'ABSPATH' ) ) exit;
15
16
17 if( !class_exists( 'vxg_googlesheets' ) ):
18
19 class vxg_googlesheets {
20
21
22 public $url = 'https://www.crmperks.com';
23
24 public $crm_name = 'googlesheets';
25 public $id = 'vxg_googlesheets';
26 public $domain = 'vxg-gsheets';
27 public $version = "1.2.5";
28 public $update_id = '30021';
29 public $min_gravityforms_version = '1.3.9';
30 public $type = 'vxg_googlesheets_pro';
31 public $fields = null;
32 public $data = null;
33
34 private $filter_condition;
35 private $plugin_dir= '';
36 private $temp= '';
37 private $crm_arr= false;
38 private $entry;
39 private $form;
40 public $notice_js= false;
41 public static $title='Gravity Forms Google Sheets Plugin';
42 public static $path = '';
43 public static $slug = '';
44 public static $debug_html = '';
45 public static $save_key='';
46 public static $lic_msg = '';
47 public static $db_version='';
48 public static $vx_plugins;
49 public static $note;
50 public static $feeds_res;
51 public static $gf_status='';
52 public static $plugin='';
53 public static $gf_status_msg='';
54 public static $is_pr=true;
55 public static $api_timeout;
56
57 public function instance(){
58 self::$path=$this->get_base_path();
59 add_action( 'plugins_loaded', array( $this, 'setup_main' ) );
60 register_deactivation_hook(__FILE__,array($this,'deactivate'));
61 register_activation_hook(__FILE__,(array($this,'activate')));
62
63
64 }
65
66 /**
67 * Plugin starting point. Will load appropriate files
68 *
69 */
70 public function init(){
71
72 self::$gf_status= $this->gravity_forms_status();
73 if(self::$gf_status !== 1){
74 add_action( 'admin_notices', array( $this, 'install_gf_notice' ) );
75 $slug=$this->get_slug();
76 add_action( 'after_plugin_row_'.$slug, array( $this, 'install_gf_notice_plugin_row' ) );
77 return;
78 }
79
80 $pro_file=self::$path . 'wp/crmperks-notices.php';
81 if(file_exists($pro_file)){
82 include_once($pro_file);
83 self::$is_pr=false;
84 }else{
85 $this->plugin_api(true);
86 self::$is_pr=true;
87 $pro_file=self::$path . 'pro/add-ons.php';
88 if(file_exists($pro_file)){
89 include_once($pro_file);
90 } }
91
92 require_once(self::$path . "includes/crmperks-gf.php");
93 require_once(self::$path . "includes/plugin-pages.php");
94
95 }
96
97
98 /**
99 * install plugin
100 *
101 */
102 public function setup_main(){
103
104
105
106 // include_once(self::$path. "includes/edit-form.php");
107 //handling post submission. gform_after_submission runs after gform_replace_merge_tags
108 add_action('gform_entry_created', array($this, 'gf_entry_created_before'), 99, 2);
109 //added via GF API
110 add_action("gform_post_add_entry", array($this, 'gf_entry_created_before'), 40, 2);
111 //trash , restore entry
112 add_action('gform_update_status', array($this, 'entry_status'),10,3);
113 //update entry
114 add_action('gform_after_update_entry', array($this, 'update_entry'),10,2);
115 //updated via GF API
116 add_action('gform_post_update_entry', array($this, 'update_entry_api'),10,2);
117
118
119
120 if(self::$is_pr){
121 // add_action("gform_post_payment_status", array($this, 'gf_entry_paid'), 10, 2); //$feed,$entry
122 add_action("gform_post_payment_completed", array($this, 'gf_entry_paid_normal'), 10, 2); //$entry,$pay_info
123
124 add_action('gform_after_submission', array($this, 'gf_entry_created_after'), 99, 2);
125 add_action("gform_post_add_subscription_payment", array($this, 'gf_entry_paid_subscription'), 10, 2); //$entry,$pay_info
126 }
127
128 add_filter("gform_confirmation", array($this, 'confirmation_error'));
129
130 if(is_admin()){
131 add_action('init', array($this,'init'));
132 //loading translations
133 load_plugin_textdomain('gravity-forms-googlesheets-crm', FALSE, $this->plugin_dir_name(). '/languages/' );
134
135 self::$db_version=get_option($this->type."_version");
136 if(self::$db_version != $this->version && current_user_can( 'manage_options' )){
137 $data=$this->get_data_object();
138 $data->update_table();
139 update_option($this->type."_version", $this->version);
140 //add post permissions
141 require_once(self::$path . "includes/install.php");
142 $install=new vxg_install_googlesheets();
143 $install->create_roles();
144 $log_str="Installing ".self::$title." version=".$this->version;
145 $this->log_msg($log_str);
146 }
147
148 }
149 }
150
151 public function plugin_api($start_instance=false){
152 if(empty(self::$path)){ self::$path=$this->get_base_path(); }
153 $file=self::$path . "pro/plugin-api.php";
154 if(!class_exists('vxcf_plugin_api') && file_exists($file)){
155 require_once($file);
156 }
157 if(class_exists('vxcf_plugin_api')){
158 $slug=$this->get_slug();
159 $settings_link=$this->link_to_settings();
160 $is_plugin_page=$this->is_crm_page();
161 self::$plugin=new vxcf_plugin_api($this->id,$this->version,$this->type,$this->domain,$this->update_id,self::$title,$slug,self::$path,$settings_link,$is_plugin_page);
162 if($start_instance){
163 self::$plugin->instance();
164 }
165 } }
166 public function install_gf_notice(){
167 $message=self::$gf_status_msg;
168 if(!empty($message)){
169 $this->display_msg('admin',$message,'gravity');
170 $this->notice_js=true;
171
172 }
173 }
174 /**
175 * Install Gravity Forms Notice (plugin row)
176 *
177 */
178 public function install_gf_notice_plugin_row(){
179 $message=self::$gf_status_msg;
180 if(!empty($message)){
181 $this->display_msg('',$message,'gravity');
182 }
183 }
184 /**
185 * display admin notice
186 *
187 * @param mixed $type
188 * @param mixed $message
189 * @param mixed $id
190 */
191 public function display_msg($type,$message,$id=""){
192 //exp
193 global $wp_version;
194 $ver=floatval($wp_version);
195 if($type == "admin"){
196 if($ver<4.2){
197 ?>
198 <div class="error vx_notice notice" data-id="<?php echo esc_html($id) ?>"><p style="display: table"><span style="display: table-cell; width: 98%"><span class="dashicons dashicons-megaphone"></span> <b><?php esc_html_e('Gravity Forms Google Sheets Plugin','gravity-forms-googlesheets-crm') ?>. </b><?php echo wp_kses_post($message);?> </span>
199 <span style="display: table-cell; padding-left: 10px; vertical-align: middle;"><a href="#" class="notice-dismiss" title="<?php esc_html_e('Dismiss Notice','gravity-forms-googlesheets-crm') ?>">dismiss</a></span> </p></div>
200 <?php
201 }else{
202 ?>
203 <div class="error vx_notice notice is-dismissible" data-id="<?php echo esc_html($id) ?>"><p><span class="dashicons dashicons-megaphone"></span> <b><?php esc_html_e('Gravity Forms Google Sheets Plugin','gravity-forms-googlesheets-crm') ?>. </b> <?php echo wp_kses_post($message);?> </p>
204 </div>
205 <?php
206 }
207 }else{
208 ?>
209 <tr class="plugin-update-tr"><td colspan="5" class="plugin-update">
210 <style type="text/css"> .vx_msg a{color: #fff; text-decoration: underline;} .vx_msg a:hover{color: #eee} </style>
211 <div style="background-color: rgba(224, 224, 224, 0.5); padding: 9px; margin: 0px 10px 10px 28px "><div style="background-color: #d54d21; padding: 5px 10px; color: #fff" class="vx_msg"> <span class="dashicons dashicons-info"></span> <?php echo wp_kses_post($message) ?>
212 </div></div></td></tr>
213 <?php
214 }
215 }
216 /**
217 * admin_screen_message function.
218 *
219 * @param mixed $message
220 * @param mixed $level
221 */
222 public function screen_msg( $message, $level = 'updated') {
223 echo '<div class="'. esc_attr( $level ) .' notice is-dismissible"><p>';
224 echo wp_kses_post($message);
225 echo '</p></div>';
226 }
227
228
229
230 /**
231 * Gravity forms status
232 *
233 */
234 public function gravity_forms_status() {
235
236 $installed = 0;
237 if(!class_exists('RGForms')) {
238 if(file_exists(WP_PLUGIN_DIR.'/gravityforms/gravityforms.php')) {
239 $installed=2;
240 }
241 }else{
242 $installed=1;
243 if(!$this->is_gravityforms_supported()){
244 $installed=3;
245 }
246 }
247 if($installed !=1){
248 if($installed === 0){ // not found
249 $message = sprintf(__("%sGravity Forms%s is required. %sPurchase it today!%s", 'gravity-forms-googlesheets-crm'), "<a href='http://www.gravityforms.com/'>", "</a>", "<a href='http://www.gravityforms.com/'>", "</a>");
250 }else if($installed === 2){ // not active
251 $message = sprintf(__('Gravity Forms is installed but not active. %sActivate Gravity Forms%s to use the Gravity Forms Google Sheets Plugin','gravity-forms-googlesheets-crm'), '<strong><a href="'.wp_nonce_url(admin_url('plugins.php?action=activate&plugin=gravityforms/gravityforms.php'), 'activate-plugin_gravityforms/gravityforms.php').'">', '</a></strong>');
252 } else if($installed === 3){ // not supported
253 $message = sprintf(__("A higher version of %sGravity Forms%s is required. %sPurchase it today!%s", 'gravity-forms-googlesheets-crm'), "<a href='http://www.gravityforms.com/'>", "</a>", "<a href='http://www.gravityforms.com/'>", "</a>");
254 }
255 self::$gf_status_msg=$message;
256 }
257 return $installed;
258 }
259 /**
260 * display error to admin only in form front
261 *
262 * @param mixed $confirmation
263 * @param mixed $form
264 * @param mixed $lead
265 * @param mixed $ajax
266 */
267 public function confirmation_error($confirmation, $form = '', $lead = '', $ajax ='' ) {
268 if(current_user_can('administrator') && !empty($_REQUEST['VXGGoogle SheetsError'])) { ///
269 $confirmation .= sprintf(__('%sThe entry was not added to Google Sheets because: %s. %sYou are only being shown this because you are an administrator. Other users will not see this message.%s', 'gravity-forms-googlesheets-crm'), '<div class="error" style="text-align:center; color:#790000; font-size:14px; line-height:1.5em; margin-bottom:16px;background-color:#FFDFDF; margin-bottom:6px!important; padding:6px 6px 4px 6px!important; border:1px dotted #C89797">','<strong>'.esc_html($_REQUEST['VXGGoogle SheetsError']). '</strong>', '<br /><em>', '</em></div>');
270 }
271 return $confirmation;
272 }
273
274 /**
275 * Returns true if the current page is an Feed pages. Returns false if not
276 *
277 * @param mixed $page
278 */
279 public function is_crm_page($page=""){
280 if(empty($page)) {
281 $page = $this->post("page");
282 }
283 if(isset($_GET['subview'])){
284 $page = $this->post("subview");
285 }
286 return $page == $this->id;
287 }
288 /**
289 * Called when entry is manually updated in the Single Entry view of Gravity Forms.
290 *
291 * @param mixed $form
292 * @param mixed $entry_id
293 */
294 public function manual_export( $form, $entry_id = NULL ) {
295
296 global $plugin_page;
297
298 // Is this the Gravity Forms entries page?
299 if(false === ($this->is_gravity_page('gf_entries') && rgget("view") == 'entry' && (rgget('lid') || !rgblank(rgget('pos'))))) {
300 return;
301 }
302 $entry=array();
303 // Both admin_init and gforms_after_update_entry will have this set
304 if( empty( $_POST['gforms_save_entry'] ) || empty( $_POST['action'] ) ) { return; }
305
306 // Different checks since admin_init runs in both cases but we need to wait for entry update
307 $current_hook = current_filter();
308
309 if( $current_hook == 'admin_init' && empty( $_POST[$this->id.'_send'] ) ) { return; }
310 if( $current_hook == 'gform_after_update_entry' && empty( $_POST[$this->id.'_update'] ) ) { return; }
311
312 // Verify authenticity of request
313 check_admin_referer('gforms_save_entry', 'gforms_save_entry');
314
315 // For admin_init hook, get the entry ID from the URL
316 if(empty($entry_id)) {
317 $entry_id = rgget('lid');
318 $form_id = rgget('id');
319
320 // fetch alternative entry id: look for gf list details when using pagination
321 if(empty($entry_id)) {
322 $entry_id=$this->get_entry_id($form_id);
323 }
324 $form = RGFormsModel::get_form_meta($form_id);
325 }
326 $entry=$this->get_gf_entry($entry_id);
327 if(!current_user_can($this->id."_send_to_crm")){
328 return;
329 }
330 // Export the entry
331 $push=$this->push($entry, $form,"",true);
332 if(!empty($push['msg'])){
333 $this->screen_msg($push['msg'],$push['class']);
334 }
335 // Don't send twice.
336 unset($_POST[$this->id.'_update']);
337 unset($_POST[$this->id.'_send']);
338 }
339 /**
340 * get entry id
341 *
342 * @param mixed $form_id
343 */
344 public function get_entry_id($form_id){
345 $entry_id='';
346 $position = rgget('pos');
347 $paging = array('offset' => $position, 'page_size' => 1);
348
349 $entries = GFAPI::get_entries($form_id, array(), null, $paging);
350
351 if(!empty($entries)) {
352 // pluck first entry to use id from, should always only be one
353 $entry = array_shift($entries);
354 $entry_id = $entry['id'];
355 }
356
357 return $entry_id;
358 }
359
360
361 /**
362 * settings link
363 *
364 * @param mixed $escaped
365 */
366 public function link_to_settings( $escaped = true ) {
367
368 $url = admin_url('admin.php?page=gf_settings&subview='.$this->id);
369
370 return $url;
371 }
372
373 /**
374 * Get CRM info
375 *
376 */
377 public function get_info($id){
378 $data=$this->get_data_object();
379 $info=$data->get_account($id);
380 $info_arr=$data=array(); $meta=array();
381 if(is_array($info)){
382 if(!empty($info['data'])){
383
384 $info['data']=trim($info['data']);
385 if(strpos($info['data'],'{') !== 0){
386 $info['data']=$this->de_crypt($info['data']);
387 }
388 $info_arr=json_decode($info['data'],true);
389
390 if(!is_array($info_arr)){
391 $info_arr=array();
392 }
393 }
394
395 //$info_arr['time']=$info['time'];
396 $info_arr['id']=$info['id'];
397 $info['data']=$info_arr;
398 if(!empty($info['meta'])){
399 $meta=json_decode($info['meta'],true);
400 }
401 $info['meta']=is_array($meta) ? $meta : array();
402
403 if(!empty($info['time'])){
404 $info['time']=strtotime($info['time']);
405 }
406 }
407
408 return $info;
409 }
410 /**
411 * update account
412 *
413 * @param mixed $data
414 * @param mixed $id
415 */
416 public function update_info($data,$id) {
417
418 if(empty($id)){
419 return;
420 }
421
422 $time = current_time( 'mysql' ,1);
423
424 $sql=array('updated'=>$time);
425 if(is_array($data)){
426
427
428 if(isset($data['meta'])){
429 $sql['meta']= json_encode($data['meta']);
430 }
431 if( isset($data['data']) && is_array($data['data'])){
432 $_data=$this->get_data_object();
433 $acount=$_data->get_account($id);
434 if(empty($acount['time'])){
435 $sql['time']= $time;
436 }
437 $sql['status']='2';
438 if(isset($data['data']['class'])){
439 $sql['status']= $data['data']['class'] == 'updated' ? '1' : '2';
440 }
441 if(isset($data['data']['meta'])){
442 unset($data['data']['meta']);
443 }
444 if(isset($data['data']['status'])){
445 unset($data['data']['status']);
446 }
447 if(isset($data['data']['name'])){
448 $sql['name']=$data['data']['name'];
449 // unset($data['data']['name']);
450 }else if(isset($_GET['id'])){
451 $sql['name']="Account #".$this->post('id');
452 }
453
454 $enc_str=json_encode($data['data']);
455 // $enc_str=$this->en_crypt($enc_str);
456 $sql['data']=$enc_str;
457 }
458 }
459
460
461 $data=$this->get_data_object();
462 $result = $data->update_account($sql,$id);
463
464 return $result;
465 }
466
467 /**
468 * gravity forms field values, modify check boxes etc
469 *
470 * @param mixed $entry
471 * @param mixed $form
472 * @param mixed $gf_field_id
473 * @param mixed $crm_field_id
474 * @param mixed $custom
475 */
476 public function verify_field_val($entry,$form,$gf_field_id,$crm_field_id="",$custom=""){
477
478 $value=false;
479 /* if(empty($field)){
480 return $value;
481 }*/
482
483 if(isset($entry[$gf_field_id])){
484 $value=$entry[$gf_field_id];
485 if(in_array($gf_field_id,array('date_created','payment_date'))){
486 $date_format=trim(get_option( 'date_format' ).' '.get_option( 'time_format' ));
487 if(empty($date_format)){
488 $date_format='Y/m/d H:i:s';
489 }
490 $value=GFCommon::format_date( $value, false, $date_format , false );
491
492 }
493 if(is_numeric($gf_field_id)){
494 $field = RGFormsModel::get_field($form, $gf_field_id);
495 //$value=GFCommon::get_lead_field_display( $field, $value,'',false,'text' );
496 //$value=$field->get_value_entry_detail($value,'',false,'text');
497 if(isset($field->type) && in_array($field->type,array('list')) ){
498 $value=maybe_unserialize($value);
499 }
500 if(isset($field->type) && in_array($field->type,array('option','product')) ){
501 $found=strpos($value,'|');
502 if($found){
503 if(!empty($custom)){ //it is empty with process_tags function
504 $value=substr($value,$found+1);
505 }else{
506 $value=substr($value,0,$found);
507 }
508 }
509 }
510 if( (isset($field->storageType) && $field->storageType == 'json') || $field->type == 'fileupload' ){
511 $value=$field->get_value_entry_detail($value,'',false,'text');//convert direct url to gravity download hash
512 /* $value_temp=json_decode($value,1); if(!empty($value_temp)){ $value=$value_temp; }
513 if(is_array($value)){
514 $value=implode("\n",$value);
515 }*/
516 }
517 if( in_array($field->type, array('survey','quiz')) && !empty($field->choices)){
518 $val_temp=explode(':',$value);
519 if(count($val_temp) > 1){ $value=$val_temp[1]; }
520 foreach($field->choices as $v){
521 if($v['value'] == $value){
522 $value=!empty($v['score']) ? $v['score'] : $v['text'];
523 $value=!empty($v['gquizWeight']) ? $v['gquizWeight'] : $v['text'];
524 break;
525 }
526 }
527 }
528 if($field->type == 'consent'){
529 $value= !empty($value) ? 'Yes' : 'No';
530 }
531
532 if($field->type == 'date' && !empty($value) ){
533 $formats=array('mdy'=>'m/d/Y','dmy'=>'d/m/Y','dmy_dash'=>'d-m-Y','dmy_dot'=>'d.m.Y','ymd_slash'=>'Y/m/d','ymd_dash'=>'Y-m-d','ymd_dot'=>'Y.m.d');
534 if( !empty($field->dateFormat) && isset($formats[$field->dateFormat])){
535 $value=date($formats[$field->dateFormat],strtotime($value));
536 }
537 }else if($field->type == "post_image"){
538 $value=rtrim($value,'|:|');
539 }else if($field->type == 'list' && is_array($value)){
540 $v_temp=array();
541 foreach($value as $v){
542 if(is_array($v)){
543 $v=trim(implode(', ',array_values($v)));
544 }
545 $v_temp[]=$v;
546 }
547 $value=trim(implode(" - \n",$v_temp));
548 }else if($field->type == 'number'){
549 $value=$field->get_value_entry_detail($value);
550 }
551 }
552 $val=true;
553 }else{ //check if full address
554 if($gf_field_id=='entry_url'){
555 $value=add_query_arg(array('page'=>'gf_entries','view'=>'entry','lid'=>$entry['id'],'id'=>$entry['form_id']), admin_url('admin.php'));
556 $val=true;
557 }else if($gf_field_id=="form_title"){
558 $value=$form['title'];
559 $val=true;
560 }else{
561 $field = RGFormsModel::get_field($form, $gf_field_id);
562
563 if(!empty($field)){
564 if($field->type == "address"){
565 $address_type="";
566 if($crm_field_id!=""){
567 $address_type=isset($custom[$crm_field_id]['type']) && $custom[$crm_field_id]['type'] == "address" ? "json" : "";
568 }
569 $value=$this->get_address($entry,$gf_field_id,$address_type);
570 $val=true;
571 }else if(is_numeric($gf_field_id)){
572 // This is for checkboxes
573 $elements = array();
574 foreach($entry as $key => $val_e) {
575 if(is_numeric($key) && floor($key) == floor($gf_field_id) && !empty($val_e)) {
576 $elements[] = htmlspecialchars($val_e);
577 }}
578 if(count($elements)>0){
579 $value=$elements; $val=true;
580 } }
581 }else if(isset($_REQUEST[$gf_field_id])){
582 $value=$this->post($gf_field_id);
583 }
584 }
585 }
586 if($value && is_array($value)){
587 // $value=implode(", ",$value);
588 }
589
590 return $value;
591 }
592 /**
593 * filter enteries
594 *
595 * @param mixed $feed
596 * @param mixed $entry
597 * @param mixed $form
598 */
599 public function check_filter($feed,$entry,$form){
600 $filters=$this->post('filters',$feed);
601 $final=$this->filter_condition=null;
602 if(is_array($filters)){
603 $time=current_time('timestamp');
604 foreach($filters as $filter_s){
605 $check=null; $and=null; $and_c=array();
606 if(is_array($filter_s)){
607 foreach($filter_s as $filter){
608 $field=$filter['field'];
609 $fval=$filter['value'];
610 $val=$this->verify_field_val($entry,$form,$field);
611 if(is_array($val)){ $val=implode(' ',$val); }
612
613 switch($filter['op']){
614 case"is": $check=$fval == $val; break;
615 case"is_not": $check=$fval != $val; break;
616 case"contains": $check=preg_match('/'.$fval.'/i', $val) > 0; break;
617 case"not_contains": $check=preg_match('/'.$fval.'/i', $val) === 0; break;
618 case"is_in": $check=strpos($fval,$val) !==false; break;
619 case"not_in": $check=strpos($fval,$val) ===false; break;
620 case"starts": $check=strpos($val,$fval) === 0; break;
621 case"not_starts": $check=strpos($val,$fval) !== 0; break;
622 case"ends": $check=(strrpos($val,$fval)+strlen($fval)) == strlen($val); break;
623 case"not_ends": $check=(strrpos($val,$fval)+strlen($fval)) != strlen($val); break;
624 case"less": $check=(float)$val<(float)$fval; break;
625 case"greater": $check=(float)$val>(float)$fval; break;
626 case"less_date": $check=strtotime($val,$time) < strtotime($fval,$time); break;
627 case"greater_date": $check=strtotime($val,$time) > strtotime($fval,$time); break;
628 case"equal_date": $check=strtotime($val,$time) == strtotime($fval,$time); break;
629 case"empty": $check=$val == ""; break;
630 case"not_empty": $check=$val != ""; break;
631 }
632 $and_c[]=array("check"=>$check,"field_val"=>$fval,"input"=>$val,"field"=>$field,"op"=>$filter['op']);
633 if($check !== null){
634 if($and !== null){
635 $and=$and && $check;
636 }else{
637 $and=$check;
638 }
639 }
640 } //end and loop filter
641 }
642 if($and !== null){
643 if($final !== null){
644 $final=$final || $and;
645 }else{
646 $final=$and;
647 }
648 }
649 $this->filter_condition[]=$and_c;
650 } // end or loop
651 }
652 // var_dump($final); die();
653 return $final === null ? true : $final;
654 }
655
656 /**
657 * get address components
658 *
659 * @param mixed $entry
660 * @param mixed $field_id
661 * @param mixed $type
662 */
663 private function get_address($entry, $field_id,$type=""){
664 $street_value = str_replace(" ", " ", trim($entry[$field_id . ".1"]));
665 $street2_value = str_replace(" ", " ", trim($entry[$field_id . ".2"]));
666 $city_value = str_replace(" ", " ", trim($entry[$field_id . ".3"]));
667 $state_value = str_replace(" ", " ", trim($entry[$field_id . ".4"]));
668 $zip_value = trim($entry[$field_id . ".5"]);
669 if(method_exists('GF_Field_Address','get_country_code')){
670 $field_c=new GF_Field_Address();
671 $country_value=$field_c->get_country_code(trim($entry[$field_id . ".6"]));
672 }else{
673 $country_value = GFCommon::get_country_code(trim($entry[$field_id . ".6"]));
674 }
675 $country =trim($entry[$field_id . ".6"]);
676 $address = $street_value;
677 $address .= !empty($address) && !empty($street2_value) ? " $street2_value" : $street2_value;
678 if($type =="json"){
679 $arr=array("street"=>$address,"city"=>$city_value,"state"=>$state_value,"zip"=>$zip_value,"country"=>$country);
680 return json_encode($arr);
681 }
682 $address .= !empty($address) && (!empty($city_value) || !empty($state_value)) ? " $city_value" : $city_value;
683 $address .= !empty($address) && !empty($city_value) && !empty($state_value) ? " $state_value" : $state_value;
684 $address .= !empty($address) && !empty($zip_value) ? " $zip_value" : $zip_value;
685 $address .= !empty($address) && !empty($country_value) ? " $country_value" : $country_value;
686
687 return $address;
688 }
689 /**
690 * if gravity forms page
691 *
692 * @param mixed $page
693 */
694 public function is_gravity_page($page = array()){
695 if(!class_exists('RGForms')) { return false; }
696 $current_page = trim(strtolower(RGForms::get("page")));
697 if(empty($page)) {
698 $gf_pages = array("gf_edit_forms","gf_new_form","gf_entries","gf_settings","gf_export","gf_help");
699 } else {
700 $gf_pages = is_array($page) ? $page : array($page);
701 }
702
703 return in_array($current_page, $gf_pages);
704 }
705 /**
706 * Add checkbox to entry info - option to send entry to crm
707 *
708 * @param mixed $form_id
709 * @param mixed $lead
710 */
711 public function entry_info_send_checkbox( $form_id, $lead ) {
712
713 // If this entry's form isn't connected to crm, don't show the checkbox
714 if(!$this->show_send_to_crm_button() ) { return; }
715
716 // If this is not the Edit screen, get outta here.
717 if(empty($_POST["screen_mode"]) || $_POST["screen_mode"] === 'view') { return; }
718
719 if(!current_user_can($this->id."_send_to_crm")){return; }
720
721 if( apply_filters( $this->id.'_show_manual_export_button', true ) ) {
722 printf('<input type="checkbox" name="'.$this->id.'_update" id="'.$this->id.'_update" value="1" /><label for="'.$this->id.'_update" title="%s">%s</label><br /><br />', esc_html__('Create or update this entry in Google Sheets. The fields will be mapped according to the form feed settings.', 'gravity-forms-googlesheets-crm'), esc_html__('Send to Google Sheets', 'gravity-forms-googlesheets-crm'));
723 } else {
724 echo '<input type="hidden" name="'.$this->id.'_update" id="'.$this->id.'_update" value="1" />';
725 }
726 }
727 /**
728 * Add button to entry info - option to send entry to crm
729 *
730 * @param mixed $button
731 */
732 public function entry_info_send_button( $button = '' ) {
733 // If this entry's form isn't connected to crm, don't show the button
734 if(!$this->show_send_to_crm_button()) { return $button; }
735 if(!current_user_can($this->id."_send_to_crm")){return; }
736 // Is this the view or the edit screen?
737 $mode = empty($_POST["screen_mode"]) ? "view" : $this->post("screen_mode");
738 if($mode === 'view') {
739 $margin="";
740 if(defined("vx_btn")){
741 $margin="margin-top: 5px;";
742 }else{define('vx_btn','true');}
743 $button.= '<input type="submit" class="button button-large button-secondary alignright" name="'.$this->id.'_send" style="margin-left:5px; '.$margin.'" title="'.__('Create or update this entry in Google Sheets. The fields will be mapped according to the form feed settings.','gravity-forms-googlesheets-crm').'" value="'.__('Send to Google Sheets', 'gravity-forms-googlesheets-crm').'" onclick="jQuery(\'#action\').val(\'send_to_crm\')" />';
744 //logs button
745
746 $entry_id=$this->post('lid');
747 $form_id = rgget('id');
748 if(empty($entry_id)){
749 $entry_id=$this->get_entry_id($form_id);
750 }
751 $log_url=admin_url( 'admin.php?page=gf_edit_forms&view=settings&subview='.$this->id.'&tab=log&id='.$form_id.'&entry_id='.$entry_id);
752 $button.= '<a class="button button-large button-secondary alignright" style="margin-left:5px; margin-top:5px; " title="'.__('Go to Google Sheets Logs','gravity-forms-googlesheets-crm').'" href="'.$log_url.'">'.__('Google Sheets Logs','gravity-forms-googlesheets-crm').'</a>';
753
754 }
755 return $button;
756 }
757 /**
758 * Whether to show the Entry "Send to CRM" button or not
759 *
760 * If the entry's form has been mapped to CRM feed, show the Send to CRM button. Otherwise, don't.
761 *
762 * @return boolean True: Show the button; False: don't show the button.
763 */
764 public function show_send_to_crm_button() {
765
766 $form_id = rgget('id');
767
768 return $this->has_feed($form_id);
769 }
770 /**
771 * Does the current form have a feed assigned to it?
772 * @param INT $form_id Form ID
773 * @return boolean
774 */
775 function has_feed($form_id) {
776 $data=$this->get_data_object();
777 $feeds = $data->get_feed_by_form( $form_id , true);
778
779 return !empty($feeds);
780 }
781
782 /**
783 * Add note to GF Entry
784 * @param int $id Entry ID
785 * @param string $note Note text
786 */
787 private function add_note($id, $note) {
788
789 RGFormsModel::add_note($id, 0, esc_html__('Gravity Forms Google Sheets Plugin','gravity-forms-googlesheets-crm'), $note);
790 }
791
792 /**
793 * if gravity forms installed and supported
794 *
795 */
796 private function is_gravityforms_supported(){
797 if(class_exists("GFCommon")){
798 $is_correct_version = version_compare(GFCommon::$version, $this->min_gravityforms_version, ">=");
799 return $is_correct_version;
800 }
801 else{
802 return false;
803 }
804 }
805 /**
806 * uninstall plugin
807 *
808 */
809 public function uninstall(){
810 //droping all tables
811 require_once(self::$path . "includes/install.php");
812 $install=new vxg_install_googlesheets();
813 do_action('uninstall_vx_plugin_'.$install->id);
814 $install->remove_data();
815 }
816 /**
817 * email validation
818 *
819 * @param mixed $email
820 */
821 public function is_valid_email($email){
822 if(function_exists('filter_var')){
823 if(filter_var($email, FILTER_VALIDATE_EMAIL)){
824 return true;
825 }
826 }else{
827 if(strpos($email,"@")>1){
828 return true;
829 }
830 }
831 return false;
832 }
833 /**
834 * deactivate
835 *
836 * @param mixed $action
837 */
838 public function deactivate($action="deactivate"){
839 do_action('plugin_status_'.$this->type,$action);
840 }
841 /**
842 * activate plugin
843 *
844 */
845 public function activate(){
846 $this->plugin_api(true);
847 do_action('plugin_status_'.$this->type,'activate');
848 }
849 /**
850 * Send CURL Request
851 *
852 * @param mixed $body
853 * @param mixed $path
854 * @param mixed $method
855 */
856 public function request($path="",$method='POST',$body="",$head=array()) {
857
858 $args = array(
859 'body' => $body,
860 'headers'=> $head,
861 'method' => strtoupper($method), // GET, POST, PUT, DELETE, etc.
862 'sslverify' => false,
863 'timeout' => 20,
864 );
865
866 $response = wp_remote_request($path, $args);
867
868 if(is_wp_error($response)) {
869 $this->error_msg= $response->get_error_message();
870 return false;
871 } else if(isset($response['response']['code']) && $response['response']['code'] != 200 && $response['response']['code'] != 404) {
872 $this->error_msg = strip_tags($response['body']);
873 return false;
874 } else if(!$response) {
875 return false;
876 }
877 $result=wp_remote_retrieve_body($response);
878 return $result;
879 }
880
881 /**
882 * Adds feed tooltips to the list of tooltips
883 *
884 * @param mixed $tooltips
885 */
886 public function tooltips($tooltips){
887 $crm_tooltips = array(
888 'vx_feed_name' => '<h6>' . esc_html__('Feed Name', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Enter feed name of your choice.', 'gravity-forms-googlesheets-crm'),
889 'vx_sel_object' => '<h6>' .__('Google Sheets Object', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Select the Object to Create when a Form is Submitted.', 'gravity-forms-googlesheets-crm'),
890 'vx_sel_account' => '<h6>' .__('Google Sheets Account', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Select the Google Sheets account you would like to export entries to.', 'gravity-forms-googlesheets-crm'),
891 'vx_sel_form' => '<h6>' . esc_html__('Gravity Form', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Select the Gravity Form you would like to integrate with Google Sheets. Contacts generated by this form will be automatically added to your Google Sheets account.', 'gravity-forms-googlesheets-crm'),
892
893 'vx_map_fields' => '<h6>' . esc_html__('Map Standard Fields', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Associate your Google Sheets fields to the appropriate Gravity Form fields.', 'gravity-forms-googlesheets-crm'),
894
895 'vx_optin_condition' => '<h6>' . esc_html__('Opt-In Condition', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('When the opt-in condition is enabled, form submissions will only be exported to Google Sheets when the condition is met. When disabled all form submissions will be exported.', 'gravity-forms-googlesheets-crm'),
896
897 'vx_manual_export' => '<h6>' . esc_html__('Manual Export', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('If you do not want all entries sent to Google Sheets, but only specific, approved entries, check this box. To manually send an entry to Google Sheets, go to Entries, choose the entry you would like to send to Google Sheets, and then click the "Send to Google Sheets" button.', 'gravity-forms-googlesheets-crm'),
898
899 'vx_entry_notes' => '<h6>' . esc_html__('Entry Notes', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Enable this option if you want to synchronize Gravity Forms entry notes to Google Sheets Object notes. For example , when you add a note to a Gravity Forms entry, it will be added to the Google Sheets Object selected in the feed.', 'gravity-forms-googlesheets-crm'),
900
901 'vx_primary_key' => '<h6>' . esc_html__('Primary Key', 'gravity-forms-googlesheets-crm') . '</h6>' . esc_html__('Which field should be used to update existing objects?', 'gravity-forms-googlesheets-crm'),
902
903
904 'vx_web' => '<h6>' . esc_html__('Web to Lead', 'gravity-forms-googlesheets-crm') . '</h6>' . sprintf(__('Web-to-Lead is available for all Google Sheets Editions. If you are not sure if your Google Sheets Edition supports the API, you should use Web-to-Lead. Editions that do not support the Google Sheets API: %s 1: Personal Edition %s 2: Group Edition %s 3: Professional Edition %s Note: You can purchase API access for a Professional Edition', 'gravity-forms-googlesheets-crm'),'<br/>','<br/>','<br/>','<br/>'),
905
906 'vx_api' => '<h6>' . esc_html__('Google Sheets API', 'gravity-forms-googlesheets-crm') . '</h6>' .sprintf(__('The API features are more powerful than Web-to-Lead. You can create different object types, as well as other advanced features. If you have any of the following Google Sheets Editions, you can use the included API Add-on: %s 1: Enterprise Edition %s 2: Unlimited Edition %s 3: Developer Edition %s 4: Professional Edition - Requires API Upgrade', 'gravity-forms-googlesheets-crm'),'<br/>','<br/>','<br/>','<br/>','<br/>'),
907
908
909 'vx_custom_app'=>'<h6>' . esc_html__('Custom App', 'gravity-forms-googlesheets-crm') . '</h6>' .__('This option is for advanced users who want to override default Google Sheets App.','gravity-forms-googlesheets-crm'),
910
911
912 'vx_camps'=>'<h6>' . esc_html__('Google Sheets Campaigns', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Get Campaigns and Status list from googlesheets.','gravity-forms-googlesheets-crm'),
913
914 'vx_sel_price_book'=>__('Which Pricebook should be searched for product','gravity-forms-googlesheets-crm'),
915
916 'vx_sel_camp'=>'<h6>' . esc_html__('Select Campaign', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Which Campaign should be assigned to this object.','gravity-forms-googlesheets-crm'),
917
918 'vx_sel_status'=>'<h6>' . esc_html__('Campaign Status', 'gravity-forms-googlesheets-crm') . '</h6>' .__('What should be Member Status.','gravity-forms-googlesheets-crm'),
919
920 'vx_pro_desc'=>'<h6>' . esc_html__('Price Book', 'gravity-forms-googlesheets-crm') . '</h6>' .__('A new product will be created in selected Pricebook. You can add a description for new products created by this plugin.','gravity-forms-googlesheets-crm'),
921
922 'vx_assign_account'=>'<h6>' . esc_html__('Google Sheets Account', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Enable this option if you want to assign an account this object.','gravity-forms-googlesheets-crm'),
923
924 'vx_sel_account'=>'<h6>' . esc_html__('Select Account', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Object created by this feed will be assigned to the selected Account.','gravity-forms-googlesheets-crm'),
925
926 'vx_assign_contract'=>'<h6>' . esc_html__('Assign Contract', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Enable this option , if you want to assign a Contract to this object','gravity-forms-googlesheets-crm'),
927
928 'vx_sel_contract'=>'<h6>' . esc_html__('Select Contact', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Select Contract feed. Contract created by this feed will be assigned to this object','gravity-forms-googlesheets-crm'),
929
930 'vx_camp_check'=>'<h6>' . esc_html__('Add to Campaign', 'gravity-forms-googlesheets-crm') . '</h6>' .__('If enabled, Lead/Contact will be added to selected Campaign','gravity-forms-googlesheets-crm'),
931 'vx_owner_check'=>'<h6>' . esc_html__('Assign Owner', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Enable this option if you want to assign another object owner.','gravity-forms-googlesheets-crm'),
932
933 'vx_owners'=>'<h6>' . esc_html__('Google Sheets Users', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Get Users list from Google Sheets','gravity-forms-googlesheets-crm'),
934
935 'vx_order_notes'=>'<h6>' . esc_html__('Entry Notes', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Enable this option if you want to synchronize Entry notes to Google Sheets Object notes. For example, when you add a note to a Entry, it will be added to the Google Sheets Object selected in the feed.','gravity-forms-googlesheets-crm'),
936
937 'vx_sel_owner'=>'<h6>' . esc_html__('Select Owner', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Select a user as a owner of this object','gravity-forms-googlesheets-crm'),
938
939 'vx_entry_note'=>'<h6>' . esc_html__('Entry Note', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Check this option if you want to send more data as CRM entry note.', 'gravity-forms-googlesheets-crm'),
940 'vx_note_fields'=>'<h6>' . esc_html__('Note Fields', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Select fields which you want to send as a note', 'gravity-forms-googlesheets-crm'),
941 'vx_disable_note'=>'<h6>' . esc_html__('Note Fields', 'gravity-forms-googlesheets-crm') . '</h6>' .__('Enable this option if you want to add note only for new CRM entry', 'gravity-forms-googlesheets-crm')
942
943 );
944 return array_merge($tooltips,$crm_tooltips);
945 }
946
947 /**
948 * Formates User Informations and submitted form to string
949 * This string is sent to email and googlesheets
950 * @param array $info User informations
951 * @param bool $is_html If HTML needed or not
952 * @return string formated string
953 */
954 public function format_user_info($info,$is_html=false){
955 $str=""; $file="";
956 if($is_html){
957 if(file_exists(self::$path."templates/email.php")){
958 ob_start();
959 include_once(self::$path."templates/email.php");
960 $file= ob_get_contents(); // data is now in here
961 ob_end_clean();
962 }
963 if(trim($file) == "")
964 $is_html=false;
965 }
966 if(isset($info['info']) && is_array($info['info'])){
967 if($is_html){
968 if(isset($info['info_title'])){
969 $str.='<tr><td style="font-family: Helvetica, Arial, sans-serif;background-color: #C35050; height: 36px; color: #fff; font-size: 24px; padding: 0px 10px">'.$info['info_title'].'</td></tr>'."\n";
970 }
971 if(is_array($info['info']) && count($info['info'])>0){
972 $str.='<tr><td style="padding: 10px;"><table border="0" cellpadding="0" cellspacing="0" width="100%;"><tbody>';
973 foreach($info['info'] as $f_k=>$f_val){
974 $str.='<tr><td style="padding-top: 10px;color: #303030;font-family: Helvetica;font-size: 13px;line-height: 150%;text-align: right; font-weight: bold; width: 28%; padding-right: 10px;">'.$f_k.'</td><td style="padding-top: 10px;color: #303030;font-family: Helvetica;font-size: 13px;line-height: 150%;text-align: left; word-break:break-all;">'.$f_val.'</td></tr>'."\n";
975 }
976 $str.="</table></td></tr>";
977 }
978 }else{
979 if(isset($info['title']))
980 $str.="\n".$info['title']."\n";
981 foreach($info['info'] as $f_k=>$f_val){
982 $str.=$f_k." : ".$f_val."\n";
983 }
984 }
985 }
986 if($is_html){
987 $str=str_replace(array("{title}","{msg}","{sf_contents}"),array($info['title'],$info['msg'],$str),$file);
988 }
989 return $str;
990 }
991
992
993 /**
994 * if plugin user is valid
995 *
996 * @param mixed $update
997 */
998
999 public function is_valid_user($update){
1000 return is_array($update) && isset($update['user']['user']) && $update['user']['user']!=""&& isset($update['user']['expires']);
1001 }
1002 /**
1003 * Get variable from array
1004 *
1005 * @param mixed $key
1006 * @param mixed $arr
1007 */
1008 public function post($key, $arr="") {
1009 if(is_array($arr)){
1010 return isset($arr[$key]) ? $arr[$key] : "";
1011 }
1012 //clean when getting extrenals
1013 return isset($_REQUEST[$key]) ? $this->clean($_REQUEST[$key],$key) : "";
1014 }
1015 public function clean($var,$key=''){
1016 if ( is_array( $var ) ) {
1017 $a=array();
1018 foreach($var as $k=>$v){
1019 $a[$k]=$this->clean($v,$k);
1020 }
1021 return $a;
1022 }else {
1023 $var=wp_unslash($var);
1024 if(in_array($key,array('note_val','value'))){
1025 $var=sanitize_textarea_field($var);
1026 }else{
1027 $var=sanitize_text_field($var);
1028 }
1029 return $var;
1030 }
1031 }
1032
1033 /**
1034 * Get WP Encryption key
1035 * @return string Encryption key
1036 */
1037 public static function get_key(){
1038 $k='Wezj%+l-x.4fNzx%hJ]FORKT5Ay1w,iczS=DZrp~H+ve2@1YnS;;g?_VTTWX~-|t';
1039 if(defined('AUTH_KEY')){
1040 $k=AUTH_KEY;
1041 }
1042 return substr($k,0,30);
1043 }
1044 /**
1045 * check if other version of this plugin exists
1046 *
1047 */
1048 public function other_plugin_version(){
1049
1050 $status=0;
1051 if(class_exists('vxg_googlesheets_wp')){
1052 $status=1;
1053 }else if( file_exists(WP_PLUGIN_DIR.'/gravity-forms-googlesheets-crm/gravity-forms-googlesheets-crm.php')) {
1054 $status=2;
1055 }
1056 return $status;
1057 }
1058 /**
1059 * Get time Offset
1060 *
1061 */
1062 public function time_offset(){
1063 $offset = (int) get_option('gmt_offset');
1064 return $offset*3600;
1065 }
1066 /**
1067 * Decrypts Values
1068 * @param array $info Google Sheets encrypted API info
1069 * @return array API settings
1070 */
1071 public static function de_crypt($info){
1072 $info=trim($info);
1073 if($info == "")
1074 return '';
1075 $str=base64_decode($info);
1076 $key=self::get_key();
1077 $decrypted_string='';
1078 if(function_exists("openssl_encrypt") && strpos($str,':')!==false ) {
1079 $method='AES-256-CBC';
1080 $arr = explode(':', $str);
1081 if(isset($arr[1]) && $arr[1]!=""){
1082 $decrypted_string=openssl_decrypt($arr[0],$method,$key,false, base64_decode($arr[1]));
1083 }
1084 }else{
1085 $decrypted_string=$str;
1086 }
1087 return $decrypted_string;
1088 }
1089 /**
1090 * Encrypts Values
1091 * @param string $str
1092 * @return string Encrypted Value
1093 */
1094 public static function en_crypt($str){
1095 $str=trim($str);
1096 if($str == "")
1097 return '';
1098 $key=self::get_key();
1099 if(function_exists("openssl_encrypt")) {
1100 $method='AES-256-CBC';
1101 $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
1102 $enc_str=openssl_encrypt($str,$method, $key,false,$iv);
1103 $enc_str.=":".base64_encode($iv);
1104 }else{
1105 $enc_str=$str;
1106 }
1107 $enc_str=base64_encode($enc_str);
1108 return $enc_str;
1109 }
1110
1111 /**
1112 * Get variable from array
1113 *
1114 * @param mixed $key
1115 * @param mixed $key2
1116 * @param mixed $arr
1117 */
1118 public function post2($key,$key2, $arr="") {
1119 if(is_array($arr) && isset($arr[$key]) && is_array($arr[$key])){
1120 return isset($arr[$key][$key2]) ? $arr[$key][$key2] : "";
1121 }
1122 return isset($_REQUEST[$key][$key2]) && is_array($_REQUEST[$key]) ? $this->clean($_REQUEST[$key][$key2]) : "";
1123 }
1124 /**
1125 * Get variable from array
1126 *
1127 * @param mixed $key
1128 * @param mixed $key2
1129 * @param mixed $arr
1130 */
1131 public function post3($key,$key2,$key3, $arr="") {
1132 if(is_array($arr)){
1133 return isset($arr[$key][$key2][$key3]) ? $arr[$key][$key2][$key3] : "";
1134 }
1135 return isset($_REQUEST[$key][$key2][$key3]) ? $this->clean($_REQUEST[$key][$key2][$key3]) : "";
1136 }
1137 /**
1138 * get base url
1139 *
1140 */
1141 public function get_base_url(){
1142 return plugin_dir_url(__FILE__);
1143 }
1144 /**
1145 * get plugin direcotry name
1146 *
1147 */
1148 public function plugin_dir_name(){
1149 if(!empty($this->plugin_dir)){
1150 return $this->plugin_dir;
1151 }
1152 if(empty(self::$path)){
1153 self::$path=$this->get_base_path();
1154 }
1155 $this->plugin_dir=basename(self::$path);
1156 return $this->plugin_dir;
1157 }
1158 /**
1159 * get plugin slug
1160 *
1161 */
1162 public function get_slug(){
1163 return plugin_basename(__FILE__);
1164 }
1165 public function do_actions(){
1166 if(!is_object(self::$plugin) ){ $this->plugin_api(); }
1167 if(is_object(self::$plugin) && method_exists(self::$plugin,'valid_addons')){
1168 return self::$plugin->valid_addons();
1169 }
1170
1171 return false;
1172 }
1173 /**
1174 * Returns the physical path of the plugin's root folder
1175 *
1176 */
1177 public function get_base_path(){
1178 return plugin_dir_path(__FILE__);
1179 }
1180 /**
1181 * Writes an error message to the Gravity Forms log.
1182 *
1183 */
1184 public function log_msg($message,$type=""){
1185 if (class_exists("GFLogging")) {
1186 GFLogging::include_logger();
1187 $slug=$this->plugin_dir_name();
1188 $log_type=KLogger::DEBUG;
1189 if($type == "error"){
1190 $log_type=KLogger::ERROR;
1191 }
1192 GFLogging::log_message($slug, $message,$log_type);
1193 }
1194 }
1195 /**
1196 * get api object
1197 *
1198 * @param mixed $settings
1199 * @return vxg_api_zoho
1200 */
1201 public function get_api($crm=""){
1202 $api = false;
1203 if(!class_exists("vxg_googlesheets_api"))
1204 require_once($this->get_base_path()."api/api.php");
1205
1206 $api= new vxg_googlesheets_api($crm);
1207
1208 return $api;
1209 }
1210 /**
1211 * get gravity forms entry
1212 *
1213 */
1214 public function get_gf_entry($entry_id){
1215 $entry=array();
1216 // Fetch entry (use new GF API from version 1.8)
1217 if( class_exists( 'GFAPI' ) && !empty( $entry_id ) ) {
1218 $entry = GFAPI::get_entry( $entry_id );
1219 } elseif( class_exists( 'RGFormsModel' ) && !empty( $entry_id ) ) {
1220 $entry = RGFormsModel::get_lead( $entry_id );
1221 }
1222 return $entry;
1223 }
1224 /**
1225 * get data object
1226 *
1227 */
1228 public function get_data_object(){
1229 require_once(self::$path . "includes/data.php");
1230 if(!is_object($this->data))
1231 $this->data=new vxg_googlesheets_data();
1232 return $this->data;
1233 }
1234 public function gf_entry_created_before($entry, $form){
1235 $this->gf_entry_created($entry, $form);
1236 }
1237 public function gf_entry_created_after($entry, $form){
1238 $this->gf_entry_created($entry, $form,'after_submit');
1239 }
1240 /**
1241 * gravity forms entry created
1242 *
1243 * @param mixed $entry
1244 * @param mixed $form
1245 */
1246 public function gf_entry_created( $entry, $form, $event='submit'){
1247
1248 if(is_array($entry) && isset($entry['status']) && $entry['status'] == 'active' && empty($entry['partial_entry_percent'])){
1249
1250 $entry_id=$this->post('id',$entry);
1251 if($this->do_actions()){
1252 do_action('vx_addons_save_entry',$entry_id,$entry,'gf',$form);
1253 }
1254 $this->push($entry,$form,$event,false);
1255 }
1256 }
1257
1258 public function gf_entry_paid_normal($entry,$pay_info){
1259 $this->gf_entry_paid($entry,$pay_info);
1260 }
1261 public function gf_entry_paid_subscription($entry,$pay_info){
1262 $this->gf_entry_paid($entry,$pay_info,'subscription_paid');
1263 }
1264 public function gf_entry_paid($entry,$pay_info,$event='paid'){
1265 // if($entry['payment_status'] == 'Paid'){
1266 $entry_id=$this->post('id',$entry);
1267 $form=array('id'=>$entry['form_id'],'title'=>'form id '.$entry['form_id']);
1268 if(!empty($feed['meta']['feedName'])){
1269 $form['title']=$feed['meta']['feedName'];
1270 }
1271 if($this->do_actions()){
1272 do_action('vx_addons_save_entry',$entry_id,$entry,'gf',$form);
1273 }
1274 $this->push($entry,$form,'paid',false);
1275 // }
1276 }
1277 /**
1278 * Send entry to crm on update
1279 *
1280 * @param mixed $form
1281 * @param mixed $lead_id
1282 */
1283 public function update_entry($form,$lead_id){
1284
1285 $meta=get_option($this->type.'_settings',array());
1286
1287 if(!empty($meta['update']) || isset($_POST[$this->id.'_update'])){
1288 $entry=$this->get_gf_entry($lead_id);
1289
1290 $push=$this->push($entry,$form,'update');
1291 if(!empty($push['msg'])){
1292 $this->screen_msg($push['msg'],$push['class']);
1293 }
1294 }
1295
1296 }
1297 public function update_entry_api($entry){
1298 $meta=get_option($this->type.'_settings',array());
1299 if(!empty($meta['update']) || isset($_POST[$this->id.'_update'])){
1300 if(!empty($entry['form_id'])){
1301 $form = GFAPI::get_form( $entry['form_id'] );
1302 $push=$this->push($entry,$form,'update');
1303 if(!empty($push['msg'])){
1304 $this->screen_msg($push['msg'],$push['class']);
1305 }
1306 }
1307 }
1308 }
1309 public function entry_status($id,$status,$old){
1310 $meta=get_option($this->type.'_settings',array());
1311 $option = '';
1312 if($status == 'active'){
1313 $option= 'restore';
1314 }else if($status == 'trash'){
1315 $option='delete';
1316 }
1317
1318 if( !empty($option) && !empty($meta[$option])){
1319 // $option= $option == 'restore' ? '' : $option;
1320 $entry=$this->get_gf_entry($id);
1321 $form=array();
1322 if(!empty($entry['form_id'])){
1323 $form = RGFormsModel::get_form_meta($entry['form_id']);
1324 }
1325 $this->push($entry,$form,$option);
1326 }
1327
1328 }
1329 /**
1330 * push form data to crm
1331 *
1332 * @param mixed $entry
1333 * @param mixed $form
1334 * @param mixed $is_admin
1335 */
1336 public function push($entry, $form,$event="",$is_admin=false,$log=""){
1337
1338
1339 $data_db=$this->get_data_object();
1340 $log_id=''; $feeds_meta=array();
1341 if(!empty($log)){
1342 if(isset($log['id'])){
1343 $log_id=$log['id'];
1344 }
1345 $log_feed=$data_db->get_feed($log['feed_id']);
1346 if(!empty($log_feed)){
1347 $feeds_meta=array($log_feed);
1348 }
1349 }else{
1350 //get feeds of a form
1351 $feeds=$data_db->get_feed_by_form($entry['form_id'],true);
1352
1353 if(is_array($feeds) && count($feeds)>0){
1354 $k=1000; $e=2000; $i=1;
1355 foreach($feeds as $feed){
1356 $data=isset($feed['data']) ? json_decode($feed['data'],true) : array();
1357 $meta=isset($feed['meta']) ? json_decode($feed['meta'],true) : array();
1358 $feed['meta']=$meta;
1359 $feed['data']=$data;
1360 $object=$this->post('object',$feed);
1361 if(!empty($data['contract_check']) || !empty($data['account_check'])|| !empty($data['contact_check'])){
1362 if($object == 'Order'){
1363 $feeds_meta[$e++]=$feed;
1364 }else{
1365 $feeds_meta[$k++]=$feed;
1366 }
1367 }else{
1368 $feeds_meta[$i++]=$feed;
1369 }
1370 }
1371 ksort($feeds_meta);
1372 //
1373 }
1374 }
1375 $form_id=0;
1376 if(isset($form['id'])){
1377 $form_id=$form['id'];
1378 }
1379
1380 $entry_id=$this->post('id',$entry);
1381 if(isset($entry['__vx_id'])){
1382 $entry_id=$entry['__vx_id'];
1383 }else{
1384 $entry=apply_filters('vx_crm_post_fields',$entry,$entry_id,'gf',$form);
1385 }
1386 //var_dump($entry); die();
1387 $n=0;
1388 $screen_msg_class="updated"; $notice="";
1389 if(is_array($feeds_meta) && count($feeds_meta)>0){
1390 while($feed=current($feeds_meta)){
1391 next($feeds_meta);
1392 $n++;
1393 $temp=array();
1394 $force_send=false;
1395 $post_comment=true;
1396 $screen_msg="";
1397 $parent_id=0;
1398 if(isset($entry['__vx_parent_id'])){
1399 $parent_id=$entry['__vx_parent_id'];
1400 }
1401 $object=$this->post('object',$feed);
1402 $data=$feed['data'];
1403 $meta=$feed['meta'];
1404 $account=$this->post('account',$feed);
1405
1406 $info=$this->get_info($account);
1407 $info_data=array();
1408 if(isset($info['data'])){
1409 $info_data=$info['data'];
1410 }
1411 $api_type=$this->post('api',$info_data);
1412
1413 if(!empty($object) && in_array($event,array('restore','update','delete','add_note','delete_note'))){
1414
1415 $search_object=$object;
1416 if(in_array($event,array('add_note','delete_note')) && !empty($log)){
1417
1418 if($event == 'add_note'){
1419 $note=json_decode($log['data'],true);
1420 if(!empty($note['Title']['value'])){
1421 self::$note=array('id'=>$log['parent_id']);
1422 self::$note['title']=$note['Title']['value'];
1423 self::$note['body']=$note['Body']['value'];
1424 }
1425 }
1426 }
1427 if($event == 'delete_note' && !empty(self::$note)){
1428 $parent_id=self::$note['id'];
1429 }
1430
1431 if(in_array($event,array('delete_note','add_note'))){
1432 //check feed
1433 $order_notes=$this->post('entry_notes',$data); //if notes sync not enabled in feed return
1434
1435 if( empty($order_notes)){
1436 continue;
1437 }
1438
1439 //change main object to Note
1440 $feed['related_object']=$object;
1441 $object=$feed['object']=!empty($meta['note_list']) ? 'ContentNote' : 'Note';
1442 }
1443 if($event == 'delete_note'){
1444 //when deleting note search note object
1445 $search_object='Note';
1446 }
1447 $_data=$this->get_data_object();
1448 $feed_log=$_data->get_feed_log($feed['id'],$entry_id,$search_object,$parent_id);
1449
1450 if($event == 'restore' && $feed_log['status'] != 5) { // only allow successfully deleted records
1451 continue;
1452 }
1453 if( in_array($event,array('update','delete') ) && !in_array($feed_log['status'],array(1,2) ) ){ // only allow successfully sent records
1454 continue;
1455 }
1456
1457 if(empty($feed_log['crm_id']) || empty($feed_log['object']) || $feed_log['object'] != $search_object){
1458
1459 continue;
1460 }
1461 //if($event !='restore'){
1462 $feed['crm_id']=$feed_log['crm_id'];
1463 // unset($feed['primary_key']);
1464 //}
1465 $feed['event']=$event;
1466 // add note and save related extra info
1467 if( $event == 'add_note' && !empty(self::$note)){
1468 $temp=array('Title'=>array('value'=>self::$note['title']),'Body'=>array('value'=>self::$note['body']),'ParentId'=>array('value'=> $feed['crm_id']));
1469
1470 $parent_id=self::$note['id'];
1471 $object_link=$feed_log['crm_id'];
1472 $feed['note_object_link']='<a href="'.$feed_log['link'].'" target="_blank">'.$feed_log['crm_id'].'</a>';
1473 }
1474 // delete not and save extra info
1475 if( $event == 'delete_note'){
1476
1477 $feed_log_arr= json_decode($feed_log['extra'],true);
1478 if(isset($feed_log_arr['note_object_link'])){
1479 $feed['note_object_link']=$feed_log_arr['note_object_link'];
1480 }
1481 $temp=array('ParentId'=>array('value'=> $feed['crm_id']));
1482 }
1483 //delete object
1484 if( $event == 'delete'){
1485 $temp=array('Id'=>array('value'=> $feed['crm_id']));
1486 }
1487 //
1488 if(!in_array($event , array('update','restore') )){
1489 //do not apply filters when adding note , deleting note , entry etc
1490 $force_send=true;
1491 }
1492 if($event == 'restore'){ // send as new entry
1493 // unset($feed['crm_id']);
1494 }
1495 //do not post comment in al other cases
1496 $post_comment=false;
1497
1498 }
1499 // var_dump(self::$note,$object,$feed['note_object'],$feed['object'],$feed['crm_id'],$feed['event'],$temp,$force_send);
1500 //continue;
1501 $feed_event=$this->post('manual_export',$data);
1502 if(!$is_admin){
1503 if($event == 'submit' && $feed_event != ''){ //if manual export is yes
1504 continue;
1505 }
1506 if($event == 'after_submit' && $feed_event != '4'){
1507 continue;
1508 }
1509 if($event == 'subscription_paid' && $feed_event != '3'){
1510 continue;
1511 }
1512 if($event == 'paid' && $feed_event != '2'){ // only process paid event, if set in feed
1513 continue;
1514 }
1515 }
1516 if(!$force_send && isset($data['map']) && is_array($data['map']) && count($data['map'])>0){
1517
1518
1519 $custom= isset($meta['fields']['fields']) && is_array($meta['fields']['fields']) ? $meta['fields']['fields'] : array();
1520 $skip_feed=false;
1521 foreach($data['map'] as $k=>$v){
1522
1523 $value=false;
1524 if(!empty($v)){ //if value not empty
1525 $field_type=$this->post('type',$v);
1526 if( !empty($field_type) ){ //custom value
1527 $value=trim($this->post('value',$v));
1528 $value=$this->process_tags($entry,$form,$value);
1529
1530
1531 }else{ //general field
1532 $field=$this->post('field',$v);
1533 if($field !=""){
1534 if(strpos($field,'_vx_feed-') !== false){
1535 $temp_feed_id=substr($field,9);
1536 if(isset(self::$feeds_res[$temp_feed_id])){
1537 $value= !empty(self::$feeds_res[$temp_feed_id]['id']) ? self::$feeds_res[$temp_feed_id]['id'] : '';
1538 }else if($n < count($feeds_meta) ){ // it is not last element
1539 $feeds_meta[]=$feed; $skip_feed=true;
1540 break;
1541 }
1542 }else{
1543 $value=$this->verify_field_val($entry,$form,$field,$k,$custom);
1544 $gf_field= RGFormsModel::get_field($form, $field);
1545 if(!empty($gf_field) && in_array($gf_field->type,array('checkbox')) && !empty($gf_field->choices) && count($gf_field->choices)< 2 ){
1546 if(!empty($value)){ $value='Yes'; }else{ $value='No'; } //single checkbox or acceptance field , googlesheets web2lead accepts only 1 for checkbox field
1547 }
1548 }
1549 }
1550
1551 }
1552
1553 if($value!== false){
1554 if(isset($custom[$k]['name'])){
1555 $temp[$k]=array('value'=>$value,'label'=>$custom[$k]['label']);
1556 }else if(isset($custom[$k]['name_c'])){
1557 $temp[$custom[$k]['name_c']]=array('value'=>$value,'label'=>$custom[$k]['name_c']);
1558 }
1559 }
1560 }
1561 }
1562 //var_dump($temp,$entry,$form); die();
1563 if($skip_feed){ continue; }
1564
1565 if($object == 'Order'){
1566 $temp['Status']=array('value'=>'Draft','label'=>'Draft');
1567 }
1568 //change owner id
1569 if(isset($data['owner']) && !empty($data['user'])){
1570 $temp['OwnerId']=array('value'=>apply_filters('vx_assigned_user_id',$data['user'],$this->id,$feed['id'],$entry,$form),'label'=>'Owner ID');
1571 }
1572
1573 //add account or contract
1574
1575 if(!empty($data['contract_check']) && !empty($data['object_contract'])){
1576 $contract_feed=$data['object_contract'];
1577 if( isset(self::$feeds_res[$contract_feed]) ){
1578
1579 $contract_res=self::$feeds_res[$contract_feed];
1580 /////
1581 if(!empty($contract_res['id'])){
1582 $temp['ContractId']=array('value'=> $contract_res['id'],'label'=>'Contract ID');
1583 }else{ //if empty continue
1584 continue;
1585 }
1586 }
1587 }
1588 if(!empty($data['account_check']) && !empty($data['object_account'])){
1589 $account_feed=$data['object_account'];
1590 if( isset(self::$feeds_res[$account_feed]) ){
1591
1592 $account_res=self::$feeds_res[$account_feed];
1593 /////
1594 if(!empty($account_res['id'])){
1595 $temp['AccountId']=array('value'=> $account_res['id'],'label'=>'Account ID');
1596 }else{ //if empty continue
1597 continue;
1598 }
1599 }
1600
1601 }
1602 if(!empty($data['contact_check']) && !empty($data['contact_feed'])){
1603 $contact_feed=$data['contact_feed'];
1604 if( isset(self::$feeds_res[$contact_feed]) ){
1605
1606 $contact_res=self::$feeds_res[$contact_feed];
1607 /////
1608 if(!empty($contact_res['id'])){
1609 $temp['contact_id']=$contact_res['id'];
1610 }else{ //if empty continue
1611 // continue;
1612 }
1613 }
1614 }
1615 //add note
1616 if(!empty($data['note_check']) ){
1617 $entry_note=''; $entry_note_title='';
1618 if(!empty($data['note_fields']) && is_array($data['note_fields'])){
1619 $data['note_val']='{'.implode("}\n{",$data['note_fields'])."}\n";
1620 }
1621 if(!empty($data['note_val'])){
1622 $entry_note=$this->process_tags($entry,$form,$data['note_val']);
1623 if(empty($entry_note_title)){
1624 $entry_note_title=substr($entry_note,0,20);
1625 }
1626 if(!empty($entry_note)){
1627 $feed['__vx_entry_note']=array('Title'=>$entry_note_title,'Body'=>$entry_note);
1628 }
1629 }
1630 }
1631 }
1632 $no_filter=true;
1633
1634 if(isset($_REQUEST['bulk_action']) && $_REQUEST['bulk_action'] =="send_to_crm_bulk_force" && !empty($log_id)){
1635 $force_send=true;
1636 }
1637 if(!$force_send && $this->post('optin_enabled',$data) == "1"){ //apply filters if not sending by force and optin is enabled
1638 $no_filter=$this->check_filter($data,$entry,$form);
1639 $res=array("status"=>"4","extra"=>array("filter"=>$this->filter_condition),"data"=>$temp);
1640 }
1641
1642 //echo json_encode($temp).'---------'.json_encode($entry); die();
1643
1644
1645 if($no_filter){ //get $res if no filter , other wise use filtered $res
1646 $api=$this->get_api($info);
1647 $feed_arr=$feed;
1648 if(is_array($meta) && is_array($data)){
1649 $feed_arr=array_merge($meta,$data,$feed);
1650 }
1651 $res=$api->push_object($feed['object'],$temp,$feed_arr);
1652 if($object == 'Contact' && !empty($res['id'])){
1653 $entry['sf_contact_id']=$res['id'];
1654 }
1655 }
1656
1657 $feed_id=$this->post('id',$feed);
1658 self::$feeds_res[$feed_id]=$res;
1659 $status=$res['status']; $error="";
1660 $id=$this->post('id',$res);
1661 $added=false;
1662 if($api_type != 'web' && !empty($id)){
1663 $added=true;
1664 }else if($api_type == 'web' && !empty($status)){
1665 $added=true;
1666 }
1667 if( $added){
1668 $id=$res['id'];
1669 $action=$this->post('action',$res);
1670 if($action == "Added"){
1671 if(empty($res['link'])){
1672 $msg=sprintf(__('Successfully Added to Google Sheets (%s) with ID # %s .', 'gravity-forms-googlesheets-crm'),$feed['object'],$res['id']);
1673 }else{
1674 $msg=sprintf(__('Successfully Added to Google Sheets (%s) with ID # %s . View entry at %s', 'gravity-forms-googlesheets-crm'),$feed['object'],$res['id'],$res['link']);
1675 }
1676 $screen_msg=__( 'Entry added in Google Sheets', 'gravity-forms-googlesheets-crm');
1677 }else{
1678 if(empty($res['link'])){
1679 $msg=sprintf(__('Successfully Updated to Google Sheets (%s) with ID # %s . View entry at %s', 'gravity-forms-googlesheets-crm'),$feed['object'],$res['id'],$res['link']);
1680 }else{
1681 $msg=sprintf(__('Successfully Updated to Google Sheets (%s) with ID # %s .', 'gravity-forms-googlesheets-crm'),$feed['object'],$res['id']);
1682 }
1683 $screen_msg=__( 'Entry updated in Google Sheets', 'gravity-forms-googlesheets-crm');
1684 }
1685
1686
1687 }else if($this->post('status',$res) == 4){
1688 $screen_msg=$msg=__( 'Entry filtered', 'gravity-forms-googlesheets-crm');
1689 }else{
1690 $status=0; $screen_msg_class="error";
1691 $screen_msg=__('Errors when adding to Google Sheets. Entry not sent! Check the Entry Notes below for more details.' , 'gravity-forms-googlesheets-crm' );
1692 if($log_id!=""){
1693 //message for bulk actions in logs
1694 $screen_msg=__('Errors when adding to Google Sheets. Entry not sent' , 'gravity-forms-googlesheets-crm' );
1695 }
1696 $msg=sprintf(__('Error while creating %s', 'gravity-forms-googlesheets-crm'),$feed['object']);
1697 if($this->post('error',$res)!=""){
1698 $error= is_array($res['error']) ? json_encode($res['error']) : $res['error'];
1699 $msg.=" ($error)";
1700
1701 $_REQUEST['VXGGoogle SheetsError']=$msg; //front end form error for admin only
1702 }
1703 if(!$is_admin){
1704 $info_data['msg']=$msg;
1705 $this->send_error_email($info_data,$entry,$form);
1706 }
1707 }
1708 //insert log
1709 $arr=array("object"=>$feed["object"],"form_id"=>$form_id,"status"=>$status,"entry_id"=>$entry_id,"crm_id"=>$id,"meta"=>$error,"time"=>date('Y-m-d H:i:s'),"data"=>$temp,"response"=>$this->post('response',$res),"extra"=>$this->post('extra',$res),"feed_id"=>$this->post('id',$feed),"link"=>$this->post('link',$res),'parent_id'=>$parent_id,'event'=>$event);
1710
1711
1712 $settings=get_option($this->type.'_settings',array());
1713 if($this->post('disable_log',$settings) !="yes"){
1714 $insert_id=$data_db->insert_log($arr,$log_id);
1715 }
1716 if(!empty($insert_id)){ //
1717 $log_url=admin_url( 'admin.php?page=gf_edit_forms&view=settings&subview='.$this->id.'&tab=log&log_id='.$insert_id.'&id='.$form_id);
1718 $log_link=' <a href="'.$log_url.'" class="vx_log_link" data-id="'.$insert_id.'">'.__('View Detail','gravity-forms-googlesheets-crm')."</a>";
1719 $screen_msg.=$log_link;
1720 }
1721 if($post_comment){
1722 //insert entry comment
1723
1724 // $this->add_note($entry["id"], $msg);
1725 }
1726
1727 if($notice!=""){
1728 $notice.='<br/>';
1729 }
1730 $notice.='<b>'.$object.': </b>'.$screen_msg;
1731
1732 }
1733 }
1734
1735 return array("msg"=>$notice,"class"=>$screen_msg_class);
1736 }
1737 public function process_tags($entry,$form,$value,$crm_field_id='',$custom=''){
1738 //starts with { and ends } , any char in brackets except {
1739 preg_match_all('/\{[^\{]+\}/',$value,$matches);
1740 if(!empty($matches[0])){
1741 $vals=array();
1742 foreach($matches[0] as $m){
1743 $m=trim($m,'{}');
1744 $val_cust=$this->verify_field_val($entry,$form,$m,$crm_field_id,$custom);
1745 if(is_array($val_cust)){ $val_cust=trim(implode(' ',$val_cust)); }
1746 $vals['{'.$m.'}']=$val_cust;
1747 }
1748
1749 $value=str_replace(array_keys($vals),array_values($vals),$value);
1750 }
1751 return $value;
1752 }
1753 /**
1754 * Send error email
1755 *
1756 * @param mixed $info
1757 * @param mixed $entry
1758 * @param mixed $form
1759 */
1760 public function send_error_email($info,$entry,$form){
1761 if( trim($this->post('error_email',$info))!=""){
1762 $subject="Error While Posting to Google Sheets";
1763 $entry_link=add_query_arg(array('page' => 'gf_entries','view'=>'entry', 'id' => $entry['form_id'],'lid'=>$entry['id']), admin_url('admin.php'));
1764 $page_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1765
1766 $detail=array(
1767 "Time"=>date('d/M/y H:i:s',current_time('timestamp')),
1768 "Page URL"=>'<a href="'.$page_url.'" style="word-break:break-all;">'.$page_url.'</a>',
1769 "Entry ID"=>'<a href="'.$entry_link.'" target="_blank" style="word-break:break-all;">'.$entry_link.'</a>'
1770 );
1771 if(isset($form['title'])){
1772 $detail["Form Name"]=$form['title'];
1773 $detail["Form Id"]=$form['id'];
1774 }
1775 $email_info=array("msg"=>$info['msg'],"title"=>__('Google Sheets','gravity-forms-googlesheets-crm')." Error","info_title"=>"More Detail","info"=>$detail);
1776 $email_body=$this->format_user_info($email_info,true);
1777
1778 $error_emails=explode(",",$info['error_email']);
1779 $headers = array('Content-Type: text/html; charset=UTF-8');
1780 foreach($error_emails as $email)
1781 wp_mail(trim($email),$subject, $email_body,$headers);
1782 }
1783 }
1784 /**
1785 * Get Objects from local options or from googlesheets
1786 *
1787 * @param mixed $check_option
1788 * @return array
1789 */
1790 public function get_objects($info="",$refresh=false){
1791
1792 $data=$this->post('data',$info);
1793 $api_type=$this->post('api',$data);
1794
1795 if(empty($info)){
1796 $option=get_option($this->id.'_meta',array());
1797
1798 return !empty($option['objects']) ? $option['objects'] : '';
1799 }
1800 $objects=array();
1801 $meta=$this->post('meta',$info);
1802
1803 if(! isset($meta['objects'])){
1804 $refresh=true;
1805 }else{
1806 $objects=$meta['objects'];
1807 }
1808 //get objects from googlesheets
1809 if($refresh){
1810 $api=$this->get_api($info);
1811 $objects=$api->get_crm_objects();
1812
1813 if(is_array($objects)){
1814 $option=get_option($this->id.'_meta',array());
1815
1816 $option_objects=$objects;
1817 if(!empty($option['objects']) && is_array($option['objects'])){
1818 $option_objects=array_merge($option['objects'],$option_objects);
1819 }
1820
1821 $option['objects']=$option_objects;
1822 update_option($this->id.'_meta',$option); //save objects for logs search option
1823 $meta["objects"]=$objects;
1824 $this->update_info(array("meta"=>$meta),$info['id']);
1825 }
1826 }
1827 return $objects;
1828 }
1829
1830 /**
1831 * check if user conected to crm
1832 *
1833 * @param mixed $settings
1834 */
1835 public function api_is_valid($info="") {
1836 if(!empty($info['data']['api']) && $info['data']['api'] == 'web'){
1837 return true;
1838 }
1839
1840 if(isset($info['data']) && is_array($info['data']) && isset($info['data']['access_token']) && !empty($info['data']['access_token'])){
1841 return true;
1842 }else{
1843 return false;}
1844 }
1845 }
1846
1847 endif;
1848 $vxg_googlesheets=new vxg_googlesheets();
1849 $vxg_googlesheets->instance();
1850 $vx_gf['vxg_googlesheets']='vxg_googlesheets';
1851