Advertisement
Guest User

mailchimp.php

a guest
Aug 3rd, 2018
1,896
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 25.24 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Mailchimp signup form
  4.  *
  5.  * Creates a mailschimp signup form
  6.  */
  7. if ( ! defined( 'ABSPATH' ) ) {  exit;  }    // Exit if accessed directly
  8.  
  9.  
  10. if ( !class_exists( 'avia_sc_mailchimp' ) )
  11. {
  12.     class avia_sc_mailchimp extends aviaShortcodeTemplate
  13.     {
  14.            
  15.             //mailchimp api key
  16.             var $api_key = "";
  17.            
  18.             // form fields
  19.             var $fields;
  20.            
  21.             /**
  22.              * Create the config array for the shortcode button
  23.              */
  24.             function shortcode_insert_button()
  25.             {
  26.                 $this->api_key = avia_get_option('mailchimp_api');
  27.                
  28.                 $this->config['self_closing']   =   'no';
  29.                
  30.                 $this->config['name']       = __('Mailchimp Signup', 'avia_framework' );
  31.                 $this->config['tab']        = __('Content Elements', 'avia_framework' );
  32.                 $this->config['icon']       = AviaBuilder::$path['imagesURL']."sc-contact.png";
  33.                 $this->config['order']      = 10;
  34.                 $this->config['target']     = 'avia-target-insert';
  35.                 $this->config['shortcode']  = 'av_mailchimp';
  36.                 $this->config['shortcode_nested'] = array('av_mailchimp_field');
  37.                 $this->config['tooltip']    = __('Creates a mailschimp signup form', 'avia_framework' );
  38.                 $this->config['preview']    = false;
  39.                 $this->config['disabling_allowed'] = true;
  40.             }
  41.            
  42.             function extra_assets()
  43.             {
  44.                 //load css
  45.                 wp_enqueue_style( 'avia-module-contact' , AviaBuilder::$path['pluginUrlRoot'].'avia-shortcodes/contact/contact.css' , array('avia-layout'), false );
  46.                
  47.                     //load js
  48.                 wp_enqueue_script( 'avia-module-contact' , AviaBuilder::$path['pluginUrlRoot'].'avia-shortcodes/contact/contact.js' , array('avia-shortcodes'), false, TRUE );
  49.            
  50.             }
  51.  
  52.             /**
  53.              * Popup Elements
  54.              *
  55.              * If this function is defined in a child class the element automatically gets an edit button, that, when pressed
  56.              * opens a modal window that allows to edit the element properties
  57.              *
  58.              * @return void
  59.              */
  60.             function popup_elements()
  61.             {
  62.                 $api = false;
  63.                 $owner = "";
  64.                 $lists = array();
  65.                
  66.                 //load the api only when the popup gets opened
  67.                 if(!empty($_POST) && !empty($_POST['action']) && $_POST['action'] == "avia_ajax_av_mailchimp")
  68.                 {
  69.                    
  70.                     $api   = new av_mailchimp_api( $this->api_key );
  71.                     $owner = $api->api_owner();
  72.                    
  73.                     if(empty( $this->api_key ) || !$owner)
  74.                     {
  75.                         $this->elements = array(
  76.                             array(
  77.                                 "name"  => __("No Mailchimp API key found",'avia_framework' ),
  78.                                 "desc"  => __("Please enter a valid Mailchimp API key, otherwise we will not be able to retrieve the lists that your visitors may subscribe to.", 'avia_framework' ).
  79.                                 '<br/><br/><a target="_blank" href="'.admin_url('admin.php?page=avia#goto_newsletter').'">'.__("You can enter your API key here",'avia_framework' )."</a>",
  80.                                 "type"  => "heading",
  81.                                 "description_class" => "av-builder-note av-error",
  82.                                 )
  83.                             );
  84.                            
  85.                         return;
  86.                     }
  87.                    
  88.                     $api->store_lists();
  89.                     $lists = $api->get_list_ids();
  90.                    
  91.                     if(!empty( $this->api_key ) && ( empty( $lists ) || !is_array($lists) ))
  92.                     {
  93.                         $this->elements = array(
  94.                             array(
  95.                                 "name"  => __("No Mailchimp Lists found",'avia_framework' ),
  96.                                 "desc"  => __("We could not find any lists that your customers can subscribe to. Please check if the API key you have entered in your Enfold Theme Panel is valid and also check if you have at least one list created on mailchimp", 'avia_framework' ).
  97.                                 '<br/><br/><a target="_blank" href="'.admin_url('admin.php?page=avia#goto_newsletter').'">'.__("Check API key here",'avia_framework' ).'</a> | <a target="_blank" href="https://login.mailchimp.com/">'.__("Go to Mailchimp",'avia_framework' )."</a>",
  98.                                 "type"  => "heading",
  99.                                 "description_class" => "av-builder-note av-error",
  100.                                 )
  101.                             );
  102.                            
  103.                         return;
  104.                     }
  105.                
  106.                     $newlist = array();
  107.                     foreach($lists as $key => $list_item)
  108.                     {
  109.                         $newlist[$list_item['name']] = $key;
  110.                     }
  111.    
  112.                     $lists = $newlist;
  113.                     $first = array(__("Select a mailchimp list...","avia_framework") => '' );
  114.                    
  115.                     $lists = array_merge($first, $lists);
  116.                
  117.                 }
  118.                
  119.                
  120.                
  121.                 //default elements that gets loaded if
  122.                 $this->elements = apply_filters( 'avf_sc_mailchimp_popup_elements',  array(
  123.                        
  124.                         array(
  125.                                 "type"  => "tab_container", 'nodescription' => true
  126.                             ),
  127.                            
  128.                         array(
  129.                                 "type"  => "tab",
  130.                                 "name"  => __("Form" , 'avia_framework'),
  131.                                 'nodescription' => true
  132.                             ),
  133.                            
  134.                         array(
  135.                             "name"  => __("Mailchimp active",'avia_framework' ),
  136.                             "desc"  => __("This installation is connected to the Mailchimp account: ", 'avia_framework' )."'".$owner."'<br/><br/>".
  137.                                        "<strong>".__("Please note:", 'avia_framework' )."</strong> ".
  138.                                        __("This element currently only supports basic list subscription with basic form fields (text and dropdowns). Please let us know if you would like to see more advanced features.", 'avia_framework' ),
  139.                             "type"  => "heading",
  140.                             "description_class" => "av-builder-note av-notice",
  141.                             ),
  142.                        
  143.                        
  144.                         array(
  145.                         "name"  => __("Lists", 'avia_framework' ),
  146.                         "desc"  => __("Select the list that the user should be added to. The form will be build automatically based on the list that you have set up in mailchimp.", 'avia_framework' ),
  147.                         "id"    => "list",
  148.                         "type"  => "mailchimp_list",
  149.                         "std"   => "",
  150.                         "subtype"   => $lists,
  151.                         "api"       => $api,
  152.                         "std"   => ""),
  153.                        
  154.                         array(
  155.                             "name" => __("Edit Contact Form Elements", 'avia_framework' ),
  156.                         "desc" => __("Once you have selected a list above the available form fields will be displayed here", 'avia_framework' )."<br/>".
  157.                                   "<br/><strong>".__("Please note:", 'avia_framework' )."</strong>".
  158.                                   "<ul>".
  159.                                   "<li>".__("You can only hide form fields that are not required", 'avia_framework' )."</li>".
  160.                                   "<li>".__("Currently only text and dropdown elements are supported properly", 'avia_framework' )."</li>".
  161.                                   "</ul>",
  162.                                  
  163.  
  164.                             "type"          => "modal_group",
  165.                             "id"            => "content",
  166.                             "modal_title"   => __("Edit Form Element", 'avia_framework' ),
  167.                             "disable_manual"=> true,
  168.                             "class"         => "av-automated-inserts",
  169.                             "std"           => array(),
  170.  
  171.                             'subelements'   => array(
  172.                                    
  173.                                     array(
  174.                                     "id"    => 'id',
  175.                                     "std"   => '',
  176.                                     "type"  => "hidden"),
  177.                                    
  178.                                     array(
  179.                                     "id"    => 'type',
  180.                                     "std"   => '',
  181.                                     "type"  => "hidden"),
  182.                                    
  183.                                     array(
  184.                                     "id"    => 'check',
  185.                                     "std"   => '',
  186.                                     "type"  => "hidden"),
  187.                                    
  188.                                     array(
  189.                                     "id"    => 'options',
  190.                                     "std"   => '',
  191.                                     "type"  => "hidden"),
  192.                                    
  193.                                     array(
  194.                                     "name"  => __("Form Element hidden", 'avia_framework' ),
  195.                                     "desc"  => __("Check if you want to hide this form element", 'avia_framework' ),
  196.                                     "id"    => "disabled",
  197.                                     "type"  => "checkbox",
  198.                                     "std"   => "",
  199.                                     "required" => array('check','equals',''),
  200.                                      ),
  201.                                      
  202.                                     array(
  203.                                     "name"  => __("Form Element Label", 'avia_framework' ),
  204.                                     "desc"  => "",
  205.                                     "id"    => "label",
  206.                                     "std"   => "",
  207.                                     "type"  => "input"),                                   
  208.  
  209.                                      array(
  210.                                     "name"  => __("Form Element Width", 'avia_framework' ),
  211.                                     "desc"  => __("Change the width of your elements and let them appear beside each other instead of underneath", 'avia_framework' ) ,
  212.                                     "id"    => "width",
  213.                                     "type"  => "select",
  214.                                     "std"   => "",
  215.                                     "no_first"=>true,
  216.                                     "subtype" => array( "Fullwidth" =>'', "1/2" =>'element_half', "1/3" =>'element_third' , "2/3" =>'element_two_third', "1/4" => 'element_fourth', "3/4" => 'element_three_fourth')),
  217.  
  218.                         )
  219.                     ),
  220.                        
  221.                        
  222.                         array( 
  223.                             "name"  => __("Double opt-in?", 'avia_framework' ),
  224.                             "desc"  => __("Check if you want people to confirm their email address before being subscribed (highly recommended)", 'avia_framework' ) ,
  225.                             "id"    => "double_opt_in",
  226.                             "std"   => "true",
  227.                             "type"  => "checkbox"),
  228.                            
  229.                            
  230.                         array(
  231.                         "name"  => __("What should happen once the form gets sent?", 'avia_framework' ),
  232.                         "desc"  => "",
  233.                         "id"    => "on_send",
  234.                         "type"  => "select",
  235.                         "std"   => "text",
  236.                         "no_first"=>true,
  237.                         "subtype" => array( __('Display a short message on the same page', 'avia_framework' ) =>'',
  238.                                             __('Redirect the user to another page', 'avia_framework' ) =>'redirect',
  239.                                             )),
  240.                        
  241.  
  242.                         array(
  243.                         "name"  => __("Message Sent label", 'avia_framework' ),
  244.                         "desc"  => __("What should be displayed once the message is sent?", 'avia_framework' ),
  245.                         "id"    => "sent",
  246.                         "required" => array('on_send','not','redirect'),
  247.                         "std"   => __("Thank you for subscribing to our newsletter!", 'avia_framework' ),
  248.                         "type"  => "input"),
  249.                        
  250.                        
  251.                         array(
  252.                         "name"  => __("Redirect", 'avia_framework' ),
  253.                         "desc"  => __("To which page do you want the user send to?", 'avia_framework' ),
  254.                         "id"    => "link",
  255.                         "type"  => "linkpicker",
  256.                         "fetchTMPL" => true,
  257.                         "std"   => "",
  258.                         "required" => array('on_send','equals','redirect'),
  259.                         "subtype" => array(
  260.                             __('Set Manually', 'avia_framework' ) =>'manually',
  261.                             __('Single Entry', 'avia_framework' ) =>'single'
  262.                         ),
  263.                         "std"   => ""),
  264.                        
  265.                        
  266.                        
  267.                        
  268.                         array(
  269.                             "type"  => "close_div",
  270.                             'nodescription' => true
  271.                         ),
  272.                    
  273.                     array(
  274.                             "type"  => "tab",
  275.                             "name"  => __("Form Styling",'avia_framework' ),
  276.                             'nodescription' => true
  277.                         ),
  278.                    
  279.                    
  280.                     array(
  281.                             "name"  => __("Form Color Scheme", 'avia_framework' ),
  282.                             "desc"  => __("Select a form color scheme here", 'avia_framework' ),
  283.                             "id"    => "color",
  284.                             "type"  => "select",
  285.                             "std"   => "",
  286.                             "subtype" => array( __('Default', 'avia_framework' )=>'',
  287.                                                 __('Light transparent', 'avia_framework' )=>'av-custom-form-color av-light-form',
  288.                                                 __('Dark transparent', 'avia_framework' ) =>'av-custom-form-color av-dark-form'),
  289.                     ),
  290.                    
  291.                     array( 
  292.                             "name"  => __("Hide Form Labels", 'avia_framework' ),
  293.                             "desc"  => __("Check if you want to hide form labels above the form elements. The form will instead try to use an inline label (not supported on old browsers)", 'avia_framework' ) ,
  294.                             "id"    => "hide_labels",
  295.                             "std"   => "",
  296.                             "type"  => "checkbox"),
  297.                    
  298.                            
  299.                     array(
  300.                             "type"  => "close_div",
  301.                             'nodescription' => true
  302.                         ),
  303.                        
  304.                         array(
  305.                                     "type"  => "tab",
  306.                                     "name"  => __("Screen Options",'avia_framework' ),
  307.                                     'nodescription' => true
  308.                                 ),
  309.                                
  310.                                
  311.                                 array(
  312.                                 "name"  => __("Element Visibility",'avia_framework' ),
  313.                                 "desc"  => __("Set the visibility for this element, based on the device screensize.", 'avia_framework' ),
  314.                                 "type"  => "heading",
  315.                                 "description_class" => "av-builder-note av-neutral",
  316.                                 ),
  317.                            
  318.                                 array( 
  319.                                         "desc"  => __("Hide on large screens (wider than 990px - eg: Desktop)", 'avia_framework'),
  320.                                         "id"    => "av-desktop-hide",
  321.                                         "std"   => "",
  322.                                         "container_class" => 'av-multi-checkbox',
  323.                                         "type"  => "checkbox"),
  324.                                
  325.                                 array( 
  326.                                    
  327.                                         "desc"  => __("Hide on medium sized screens (between 768px and 989px - eg: Tablet Landscape)", 'avia_framework'),
  328.                                         "id"    => "av-medium-hide",
  329.                                         "std"   => "",
  330.                                         "container_class" => 'av-multi-checkbox',
  331.                                         "type"  => "checkbox"),
  332.                                        
  333.                                 array( 
  334.                                    
  335.                                         "desc"  => __("Hide on small screens (between 480px and 767px - eg: Tablet Portrait)", 'avia_framework'),
  336.                                         "id"    => "av-small-hide",
  337.                                         "std"   => "",
  338.                                         "container_class" => 'av-multi-checkbox',
  339.                                         "type"  => "checkbox"),
  340.                                        
  341.                                 array( 
  342.                                    
  343.                                         "desc"  => __("Hide on very small screens (smaller than 479px - eg: Smartphone Portrait)", 'avia_framework'),
  344.                                         "id"    => "av-mini-hide",
  345.                                         "std"   => "",
  346.                                         "container_class" => 'av-multi-checkbox',
  347.                                         "type"  => "checkbox"),
  348.    
  349.                                
  350.                             array(
  351.                                     "type"  => "close_div",
  352.                                     'nodescription' => true
  353.                                 ), 
  354.                        
  355.                     array(
  356.                             "type"  => "close_div",
  357.                             'nodescription' => true
  358.                         ),
  359.  
  360.  
  361.                 ));
  362.                
  363.                
  364.                
  365.  
  366.             }
  367.  
  368.             /**
  369.              * Editor Sub Element - this function defines the visual appearance of an element that is displayed within a modal window and on click opens its own modal window
  370.              * Works in the same way as Editor Element
  371.              * @param array $params this array holds the default values for $content and $args.
  372.              * @return $params the return array usually holds an innerHtml key that holds item specific markup.
  373.              */
  374.             function editor_sub_element($params)
  375.             {
  376.                 $template = $this->update_template("label", "<span class='av-mailchimp-el-label'>".__("Element", 'avia_framework' ). "</span><span class='av-mailchimp-btn-label'>".__("Button", 'avia_framework' ). "</span>: {{label}}");
  377.  
  378.                 $params['innerHtml']  = "";
  379.                 $params['innerHtml'] .= "<div class='avia_title_container'>";
  380.                 $params['innerHtml'] .= "<div ".$this->class_by_arguments('check' ,$params['args']).">";
  381.                 $params['innerHtml'] .= "<div ".$this->class_by_arguments('id' ,$params['args']).">";
  382.                 $params['innerHtml'] .= "<div ".$this->class_by_arguments('disabled' ,$params['args']).">";
  383.                 $params['innerHtml'] .= "<span {$template} ><span class='av-mailchimp-el-label'>".__("Element", 'avia_framework' ). "</span><span class='av-mailchimp-btn-label'>".__("Button", 'avia_framework' ). "</span>: ".$params['args']['label']."</span>";
  384.                 $params['innerHtml'] .= "<span class='av-required-indicator'> *</span>";
  385.                 $params['innerHtml'] .= "</div>";
  386.                 $params['innerHtml'] .= "</div>";
  387.                 $params['innerHtml'] .= "</div>";
  388.                 $params['innerHtml'] .= "</div>";
  389.  
  390.                 return $params;
  391.             }
  392.  
  393.  
  394.  
  395.             /**
  396.              * Frontend Shortcode Handler
  397.              *
  398.              * @param array $atts array of attributes
  399.              * @param string $content text within enclosing form of shortcode element
  400.              * @param string $shortcodename the shortcode found, when == callback name
  401.              * @return string $output returns the modified html string
  402.              */
  403.             function shortcode_handler($atts, $content = "", $shortcodename = "", $meta = "")
  404.             {
  405.                 if(empty($this->api_key)) return;
  406.                
  407.                 $lists      = get_option('av_chimplist');
  408.                 $newlist    = array();
  409.            
  410.                 if(empty($lists))
  411.                 {
  412.                     return;
  413.                 }
  414.                
  415.                 foreach($lists as $key => $list_item)
  416.                 {
  417.                     $newlist[$list_item['name']] = $key;
  418.                 }
  419.                
  420.                 $lists = $newlist;
  421.                
  422.                 extract(AviaHelper::av_mobile_sizes($atts)); //return $av_font_classes, $av_title_font_classes and $av_display_classes
  423.                
  424.                 $atts =  shortcode_atts(
  425.                             apply_filters( 'avf_sc_mailchimp_atts',
  426.                                         array(
  427.                                             'list' => "",
  428.                                             'email'         => get_option('admin_email'),
  429.                                             'button'        => __("Submit", 'avia_framework' ),
  430.                                             'captcha'       => '',
  431.                                             'subject'       => '',
  432.                                             'on_send'       => '',
  433.                                             'link'          => '',
  434.                                             'sent'          => __("Thank you for subscribing to our newsletter!", 'avia_framework' ),
  435.                                             'color'         => "",
  436.                                             'hide_labels'   => "",
  437.                                             'form_align'    => "",
  438.                                              'listonly'     => false, //if we should only use the list items or sub shortcodes
  439.                                              'double_opt_in'=> ""
  440.  
  441.                                              )), $atts, $this->config['shortcode']);
  442.                
  443.                 if( empty( $atts['list'] ) ) return;
  444.                
  445.                 //extract form fields
  446.                
  447.                 if($atts['listonly'])
  448.                 {
  449.                     $form_fields = $this->convert_fields_from_list( $atts['list'] );
  450.                 }
  451.                 else
  452.                 {
  453.                     $content = str_replace("\,", "&#44;", $content );
  454.                     $form_fields = $this->helper_array2form_fields(ShortcodeHelper::shortcode2array($content, 1));
  455.                 }
  456.                
  457.                 if( empty( $form_fields ) ) return;
  458.                
  459.                 extract($atts);
  460.  
  461.                 $post_id  = function_exists('avia_get_the_id') ? avia_get_the_id() : get_the_ID();
  462.                 $redirect = !empty($on_send) ? AviaHelper::get_url($link) : "";
  463.                
  464.                 if(!empty($form_align)) $meta['el_class'] .= " av-centered-form ";
  465.                
  466.                 $form_args = array(
  467.                     "heading"               => "",
  468.                     "success"               => "<h3 class='avia-form-success avia-mailchimp-success'>".$sent."</h3>",
  469.                     "submit"                => $button,
  470.                     "myemail"               => $email,
  471.                     "action"                => get_permalink($post_id),
  472.                     "myblogname"            => get_option('blogname'),
  473.                     "subject"               => $subject,
  474.                     "form_class"            => $meta['el_class']." ".$color." avia-mailchimp-form"." ".$av_display_classes,
  475.                     "form_data"             => array('av-custom-send'=>'mailchimp_send'),
  476.                     "multiform"             => true, //allows creation of multiple forms without id collision
  477.                     "label_first"           => true,
  478.                     "redirect"              => $redirect,
  479.                     "placeholder"           => $hide_labels,
  480.                     "mailchimp"             => $atts['list'],
  481.                     "custom_send"           => array($this, 'send'),
  482.                     "double_opt_in"         => $atts['double_opt_in'],
  483.                    
  484.                    
  485.                 );
  486.                
  487.                
  488.                
  489.                 if(trim($form_args['myemail']) == '') $form_args['myemail'] = get_option('admin_email');
  490.  
  491.  
  492.                 $content = str_replace("\,", "&#44;", $content );
  493.  
  494.                 //fake username field that is not visible. if the field has a value a spam bot tried to send the form
  495.                 $elements['avia_username']  = array('type'=>'decoy', 'label'=>'', 'check'=>'must_empty');
  496.  
  497.                 //captcha field for the user to verify that he is real
  498.                 if($captcha)
  499.                 $elements['avia_age'] = array('type'=>'captcha', 'check'=>'captcha', 'label'=> __('Please prove that you are human by solving the equation','avia_framework' ));
  500.  
  501.                 //merge all fields
  502.                 $form_fields = apply_filters('ava_mailchimp_contact_form_elements', array_merge($form_fields, $elements));
  503.                 $form_fields = apply_filters('avf_sc_mailchimp_form_elements', $form_fields, $atts );
  504.                 $form_args   = apply_filters('avia_mailchimp_form_args', $form_args, $post_id);
  505.  
  506.                 $contact_form = new avia_form($form_args);
  507.                 $contact_form->create_elements($form_fields);
  508.                 $output = $contact_form->display_form(true);
  509.  
  510.                
  511.                 return $output;
  512.                
  513.             }
  514.            
  515.             public function send( &$instance )
  516.             {
  517.                 $params = $instance->form_params;
  518.                
  519.                 if( isset( $_POST['avia_generated_form' . $params['avia_formID']] ) )
  520.                 {
  521.                     $form_suffix    = '_' . $params['avia_formID'];
  522.                     $suffix_length  = (strlen($form_suffix) * -1);
  523.                     $merge_fields   = array();
  524.                     $post_data      = array();
  525.                     $mail           = "";
  526.                     $status         = !empty( $params['double_opt_in'] ) ? "pending" : "subscribed"; // subscribed // pending
  527.                    
  528.                     foreach($_POST as $key => $value)
  529.                     {
  530.                         $key = substr($key, 0, $suffix_length);
  531.                         $key = str_replace('avia_','',$key);
  532.                        
  533.                         if(isset($_POST['ajax_mailchimp']))
  534.                         {
  535.                             $value = urldecode($value);
  536.                         }
  537.                        
  538.                         $post_data[ $key ] = $value;
  539.                        
  540.                     }
  541.                    
  542.                     //make sure that the username is not filled in, otherwise a bot has sent the form. if so simply fake the send event
  543.                     if(!empty($post_data['username']) ) return true;
  544.                    
  545.                     //iterate over form fields to generate the merge field data
  546.                     if( empty( $this->fields ) )
  547.                     {
  548.                         $all_fields     = get_option('av_chimplist_field');
  549.                         $this->fields   = $all_fields[$params['mailchimp']];
  550.                     }
  551.                    
  552.                     foreach ($this->fields as $field)
  553.                     {
  554.                         $value = !empty( $post_data[ $field->merge_id ] ) ? $post_data[ $field->merge_id ] : false;
  555.                        
  556.                         if($value !== false)
  557.                         {
  558.                             if($field->merge_id != 0)
  559.                             {
  560.                                 $merge_fields[ $field->tag ] = $value;
  561.                             }
  562.                             else
  563.                             {
  564.                                 $mail = $value;
  565.                             }
  566.                         }
  567.                     }
  568.                    
  569.                     $data_to_send = array(
  570.                         'email_address' => $mail,
  571.                         'status'        => $status,
  572.                     );
  573.                    
  574.                     if( !empty( $merge_fields ) )
  575.                     {
  576.                         $data_to_send['merge_fields'] = $merge_fields;
  577.                     }
  578.                    
  579.                     $data_to_send   = apply_filters( 'avf_mailchimp_subscriber_data' , $data_to_send , $this );
  580.                     $api            = new av_mailchimp_api( $this->api_key );
  581.                     $this->add_user = $api->post( 'lists/'.$params['mailchimp'].'/members' ,$data_to_send);
  582.            
  583.                     //user was successfully added
  584.                     if( isset($this->add_user->id))
  585.                     {
  586.                         return true;
  587.                     }
  588.                    
  589.                     //if we got no id the user was not added which means we got an error.
  590.                     $error_key = "general";
  591.                    
  592.                     if($this->add_user->title == "Invalid Resource")
  593.                     {
  594.                         $error_key = 'all';
  595.                        
  596.                         if( strpos($this->add_user->detail, 'email') !== false)
  597.                         {
  598.                             $error_key = 'email';
  599.                         }
  600.                        
  601.                         if( strpos($this->add_user->detail, 'merge fields') !== false)
  602.                         {
  603.                             $error_key = 'invalid_field';
  604.                         }
  605.                     }
  606.                    
  607.                     if($this->add_user->title == "Member Exists")
  608.                     {
  609.                         $error_key = 'already';
  610.                     }
  611.                    
  612.                     $instance->error_msg = "<div class='avia-mailchimp-ajax-error av-form-error-container'>". $api->message($error_key) ."</div>";
  613.                    
  614.                    
  615.                     add_action('wp_footer', array($this, 'print_js_error'), 2, 100000);
  616.                 }
  617.                
  618.                
  619.                
  620.                 return false;
  621.             }
  622.            
  623.             public function print_js_error()
  624.             {
  625.                 echo "<script type='text/javascript'>";
  626.                 echo "var av_mailchimp_errors = ".json_encode( $this->add_user ).";";
  627.                 echo "if(console) console.log( 'Mailchimp Error:' , av_mailchimp_errors );";
  628.                 echo "</script>";
  629.             }
  630.            
  631.            
  632.             public function sort_elements($a, $b)
  633.             {
  634.                 return $a['order'] - $b['order'];
  635.             }
  636.  
  637.  
  638.             /*helper function that converts the shortcode sub array into the format necessary for the contact form*/
  639.             private function convert_fields_from_list( $key )
  640.             {
  641.                 $all_fields     = get_option('av_chimplist_field');
  642.                 $this->fields   = $all_fields[$key];
  643.                
  644.                 $converted  = array();
  645.                
  646.                 if(!empty($this->fields))
  647.                 {
  648.                     foreach ($this->fields as $field)
  649.                     {
  650.                         if($field->public == 1)
  651.                         {
  652.                             $required   = $field->required;
  653.                             $options    = isset( $field->options->choices ) ? $field->options->choices : "";
  654.                             $type       = "text";
  655.                             $check      = "";
  656.                            
  657.                             switch( $field->type )
  658.                             {
  659.                                 case "dropdown":    $type = "select"; break;
  660.                                 case "date":        $type = "datepicker"; break;
  661.                                 case "radio":       $type = "select"; break;
  662.                                 case "number":      if(!empty($required)){ $check = "is_number"; } break;
  663.                                 case "email":       $type = "text"; if(!empty($required)){ $check = "is_email";  } break;
  664.                                 default:            $type = 'text';
  665.                             }
  666.                            
  667.                             if( empty($check) )
  668.                             {
  669.                                 $check = !empty($required) ? "is_empty" : "";
  670.                             }
  671.                            
  672.                             $converted[ $field->merge_id ] = array(
  673.                                
  674.                                 'id'        => $field->merge_id,
  675.                                 'label'     => $field->name,
  676.                                 'type'      => $type,
  677.                                 'check'     => $check,
  678.                                 'options'   => $options,
  679.                                 'order'     => $field->display_order,
  680.                                 'value'     => $field->default_value
  681.                             );
  682.                         }
  683.                     }
  684.                
  685.                     usort($converted, array( $this , 'sort_elements') );
  686.                 }
  687.                
  688.                 return $converted;
  689.             }
  690.            
  691.             /*helper function that converts the shortcode sub array into the format necessary for the contact form*/
  692.             function helper_array2form_fields($base)
  693.             {
  694.                 $form_fields = array();
  695.                 $labels = array();
  696.  
  697.                 if(is_array($base))
  698.                 {
  699.                     foreach($base as $key => $field)
  700.                     {
  701.                         if(!empty($field['attr']['disabled']) && empty( $field['attr']['check'] ) && $field['attr']['type'] != "button" ) continue;
  702.                        
  703.                         switch( $field['attr']['type'] )
  704.                         {
  705.                             case "dropdown":    $field['attr']['type'] = "select"; break;
  706.                             case "date":        $field['attr']['type'] = "datepicker"; break;
  707.                             case "radio":       $field['attr']['type'] = "select"; break;
  708.                             case "button":      $field['attr']['type'] = "button"; break;
  709.                             case "number":      $field['attr']['type'] = "number"; break;
  710.                             default:            $field['attr']['type'] = 'text';
  711.                         }
  712.                    
  713.                         $sanizited_id = $field['attr']['id'];
  714.  
  715.                         $labels[$sanizited_id] = empty($labels[$sanizited_id]) ? 1 : $labels[$sanizited_id] + 1;
  716.                         if($labels[$sanizited_id] > 1) $sanizited_id = $sanizited_id . '_' . $labels[$sanizited_id];
  717.  
  718.                         $form_fields[$sanizited_id] = $field['attr'];
  719.                         if(!empty($field['content'])) $form_fields[$sanizited_id]['content'] = ShortcodeHelper::avia_apply_autop($field['content']);
  720.                     }
  721.                 }
  722.  
  723.                 return $form_fields;
  724.             }
  725.  
  726.     }
  727. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement