emcniece

GravityForms Modified form_display.php for footer jQuery

Feb 14th, 2013
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 124.31 KB | None | 0 0
  1. <?php
  2.  
  3. class GFFormDisplay{
  4.     public static $submission = array();
  5.     private static $init_scripts = array();
  6.  
  7.     const ON_PAGE_RENDER = 1;
  8.     const ON_CONDITIONAL_LOGIC = 2;
  9.  
  10.     public static function process_form($form_id){
  11.  
  12.         //reading form metadata
  13.         $form = RGFormsModel::get_form_meta($form_id);
  14.         $form = RGFormsModel::add_default_properties($form);
  15.         $lead = array();
  16.  
  17.         $field_values = RGForms::post("gform_field_values");
  18.  
  19.         $confirmation_message = "";
  20.  
  21.         $source_page_number = self::get_source_page($form_id);
  22.         $page_number = $source_page_number;
  23.         $target_page = self::get_target_page($form, $page_number, $field_values);
  24.  
  25.         //Loading files that have been uploaded to temp folder
  26.         $files = GFCommon::json_decode(stripslashes(RGForms::post("gform_uploaded_files")));
  27.         if(!is_array($files))
  28.             $files = array();
  29.  
  30.         RGFormsModel::$uploaded_files[$form["id"]] = $files;
  31.  
  32.         $is_valid = true;
  33.  
  34.         //don't validate when going to previous page
  35.         if(empty($target_page) || $target_page >= $page_number){
  36.             $failed_validation_page = $page_number;
  37.             $is_valid = self::validate($form, $field_values, $page_number, $failed_validation_page);
  38.         }
  39.  
  40.         //Upload files to temp folder when going to the next page or when submitting the form and it failed validation
  41.         if( $target_page >= $page_number || ($target_page == 0 && !$is_valid) ){
  42.             //Uploading files to temporary folder
  43.             $files = self::upload_files($form, $files);
  44.             RGFormsModel::$uploaded_files[$form["id"]] = $files;
  45.         }
  46.  
  47.         // Load target page if it did not fail validation or if going to the previous page
  48.         if($is_valid){
  49.             $page_number = $target_page;
  50.         }
  51.         else
  52.         {
  53.             $page_number = $failed_validation_page;
  54.         }
  55.  
  56.         $confirmation = "";
  57.         if($is_valid && $page_number == 0){
  58.             $ajax = isset($_POST["gform_ajax"]);
  59.  
  60.             //adds honeypot field if configured
  61.             if(rgar($form,"enableHoneypot"))
  62.                 $form["fields"][] = self::get_honeypot_field($form);
  63.  
  64.             $failed_honeypot = rgar($form,"enableHoneypot") && !self::validate_honeypot($form);
  65.  
  66.             if($failed_honeypot){
  67.                 //display confirmation but doesn't process the form when honeypot fails
  68.                 $confirmation = self::handle_confirmation($form, $lead, $ajax);
  69.                 $is_valid = false;
  70.             }
  71.             else{
  72.                 //pre submission action
  73.                 do_action("gform_pre_submission", $form);
  74.                 do_action("gform_pre_submission_{$form["id"]}", $form);
  75.  
  76.                 //pre submission filter
  77.                 $form = apply_filters("gform_pre_submission_filter_{$form["id"]}", apply_filters("gform_pre_submission_filter", $form));
  78.  
  79.                 //handle submission
  80.                 $confirmation = self::handle_submission($form, $lead, $ajax);
  81.  
  82.                 //after submission hook
  83.                 do_action("gform_after_submission", $lead, $form);
  84.                 do_action("gform_after_submission_{$form["id"]}", $lead, $form);
  85.             }
  86.  
  87.             if(is_array($confirmation) && isset($confirmation["redirect"])){
  88.                 header("Location: {$confirmation["redirect"]}");
  89.                 do_action("gform_post_submission", $lead, $form);
  90.                 do_action("gform_post_submission_{$form["id"]}", $lead, $form);
  91.  
  92.                 exit;
  93.             }
  94.         }
  95.         if(!isset(self::$submission[$form_id]))
  96.             self::$submission[$form_id] = array();
  97.  
  98.         self::set_submission_if_null($form_id, "is_valid", $is_valid);
  99.         self::set_submission_if_null($form_id, "form", $form);
  100.         self::set_submission_if_null($form_id, "lead", $lead);
  101.         self::set_submission_if_null($form_id, "confirmation_message", $confirmation);
  102.         self::set_submission_if_null($form_id, "page_number", $page_number);
  103.         self::set_submission_if_null($form_id, "source_page_number", $source_page_number);
  104.     }
  105.  
  106.     private static function set_submission_if_null($form_id, $key, $val){
  107.         if(!isset(self::$submission[$form_id][$key]))
  108.             self::$submission[$form_id][$key] = $val;
  109.     }
  110.  
  111.     private static function upload_files($form, $files){
  112.  
  113.         //Creating temp folder if it does not exist
  114.         $target_path = RGFormsModel::get_upload_path($form["id"]) . "/tmp/";
  115.         wp_mkdir_p($target_path);
  116.  
  117.         foreach($form["fields"] as $field){
  118.             $input_name = "input_{$field["id"]}";
  119.  
  120.             //skip fields that are not file upload fields or that don't have a file to be uploaded or that have failed validation
  121.             $input_type = RGFormsModel::get_input_type($field);
  122.             if(!in_array($input_type, array("fileupload", "post_image")) || $field["failed_validation"] || empty($_FILES[$input_name]["name"])){
  123.                 GFCommon::log_debug("upload_files() - skipping field: {$field["label"]}({$field["id"]} - {$field["type"]})");
  124.                 continue;
  125.             }
  126.  
  127.             $file_info = RGFormsModel::get_temp_filename($form["id"], $input_name);
  128.             GFCommon::log_debug("upload_files() - temp file info: " . print_r($file_info, true));
  129.  
  130.             if($file_info && move_uploaded_file($_FILES[$input_name]['tmp_name'], $target_path . $file_info["temp_filename"])){
  131.                 $files[$input_name] = $file_info["uploaded_filename"];
  132.                 GFCommon::log_debug("upload_files() - file uploaded successfully:  {$file_info["uploaded_filename"]}");
  133.             }
  134.             else{
  135.                 GFCommon::log_error("upload_files() - file could not be uploaded: tmp_name: {$_FILES[$input_name]['tmp_name']} - target location: " . $target_path . $file_info["temp_filename"]);
  136.             }
  137.         }
  138.  
  139.         return $files;
  140.     }
  141.  
  142.     public static function get_state($form, $field_values){
  143.         $product_fields = array();
  144.         foreach($form["fields"] as $field){
  145.             if(GFCommon::is_product_field($field["type"]) || $field["type"] == "donation"){
  146.                 $value = RGFormsModel::get_field_value($field, $field_values, false);
  147.                 $value = self::default_if_empty($field, $value);
  148.  
  149.                 switch($field["inputType"]){
  150.                     case "calculation" :
  151.                     case "singleproduct" :
  152.                     case "hiddenproduct" :
  153.                         $price = !is_array($value) || empty($value[$field["id"] . ".2"]) ? $field["basePrice"] : $value[$field["id"] . ".2"];
  154.                         if(empty($price))
  155.                             $price = 0;
  156.  
  157.                         $price = GFCommon::to_number($price);
  158.  
  159.                         $product_name = !is_array($value) || empty($value[$field["id"] . ".1"]) ? $field["label"] : $value[$field["id"] . ".1"];
  160.                         $product_fields[$field["id"]. ".1"] = wp_hash($product_name);
  161.                         $product_fields[$field["id"]. ".2"] = wp_hash($price);
  162.                     break;
  163.  
  164.                     case "singleshipping" :
  165.                         $price = !empty($value) ? $value : $field["basePrice"];
  166.                         $price = GFCommon::to_number($price);
  167.  
  168.                         $product_fields[$field["id"]] = wp_hash($price);
  169.                     break;
  170.                     case "radio" :
  171.                     case "select" :
  172.                         $product_fields[$field["id"]] = array();
  173.                         foreach($field["choices"] as $choice){
  174.                             $field_value = !empty($choice["value"]) || rgar($field,"enableChoiceValue") ? $choice["value"] : $choice["text"];
  175.                             if($field["enablePrice"])
  176.                                 $field_value .= "|" . GFCommon::to_number(rgar($choice,"price"));
  177.  
  178.                             $product_fields[$field["id"]][] = wp_hash($field_value);
  179.                         }
  180.                     break;
  181.                     case "checkbox" :
  182.                         $index = 1;
  183.                         foreach($field["choices"] as $choice){
  184.                             $field_value = !empty($choice["value"]) || $field["enableChoiceValue"] ? $choice["value"] : $choice["text"];
  185.                             if($field["enablePrice"])
  186.                                 $field_value .= "|" . GFCommon::to_number($choice["price"]);
  187.  
  188.                             if($index % 10 == 0) //hack to skip numbers ending in 0. so that 5.1 doesn't conflict with 5.10
  189.                                 $index++;
  190.  
  191.                             $product_fields[$field["id"] . "." . $index++] = wp_hash($field_value);
  192.                         }
  193.                     break;
  194.  
  195.                 }
  196.             }
  197.         }
  198.         $hash = serialize($product_fields);
  199.         $checksum = wp_hash(crc32($hash));
  200.         return base64_encode(serialize(array($hash, $checksum)));
  201.     }
  202.  
  203.     private static function has_pages($form){
  204.         return GFCommon::has_pages($form);
  205.     }
  206.  
  207.     private static function has_character_counter($form){
  208.  
  209.         if(!is_array($form["fields"]))
  210.             return false;
  211.  
  212.         foreach($form["fields"] as $field){
  213.             if(rgar($field, "maxLength") && !rgar($field, "inputMask"))
  214.                 return true;
  215.         }
  216.  
  217.         return false;
  218.     }
  219.  
  220.  
  221.     private static function has_enhanced_dropdown($form){
  222.  
  223.         if(!is_array($form["fields"]))
  224.             return false;
  225.  
  226.         foreach($form["fields"] as $field){
  227.             if(in_array(RGFormsModel::get_input_type($field), array("select", "multiselect")) && rgar($field, "enableEnhancedUI"))
  228.                 return true;
  229.         }
  230.  
  231.         return false;
  232.     }
  233.  
  234.     private static function has_password_strength($form){
  235.  
  236.         if(!is_array($form["fields"]))
  237.             return false;
  238.  
  239.         foreach($form["fields"] as $field){
  240.             if($field["type"] == "password" && RGForms::get("passwordStrengthEnabled", $field))
  241.                 return true;
  242.         }
  243.  
  244.         return false;
  245.     }
  246.  
  247.     private static function has_other_choice($form){
  248.  
  249.         if(!is_array($form["fields"]))
  250.             return false;
  251.  
  252.         foreach($form["fields"] as $field){
  253.             if($field["type"] == "radio" && rgget("enableOtherChoice", $field))
  254.                 return true;
  255.         }
  256.  
  257.         return false;
  258.     }
  259.  
  260.  
  261.     public static function get_target_page($form, $current_page, $field_values){
  262.         $page_number = RGForms::post("gform_target_page_number_{$form["id"]}");
  263.         $page_number = !is_numeric($page_number) ? 1 : $page_number;
  264.  
  265.         $direction = $page_number >= $current_page ? 1 : -1;
  266.  
  267.         //Finding next page that is not hidden by conditional logic
  268.         while(RGFormsModel::is_page_hidden($form, $page_number, $field_values)){
  269.             $page_number += $direction;
  270.         }
  271.  
  272.         //If all following pages are hidden, submit the form
  273.         if($page_number > self::get_max_page_number($form))
  274.             $page_number = 0;
  275.  
  276.         return $page_number;
  277.     }
  278.  
  279.     public static function get_source_page($form_id){
  280.         $page_number = RGForms::post("gform_source_page_number_{$form_id}");
  281.         return !is_numeric($page_number) ? 1 : $page_number;
  282.     }
  283.  
  284.     public static function set_current_page($form_id, $page_number){
  285.         self::$submission[$form_id]["page_number"] = $page_number;
  286.     }
  287.  
  288.     public static function get_current_page($form_id){
  289.         $page_number = isset(self::$submission[$form_id]) ? self::$submission[$form_id]["page_number"] : 1;
  290.         return $page_number;
  291.     }
  292.  
  293.     private static function is_page_active($form_id, $page_number){
  294.         return intval(self::get_current_page($form_id)) == intval($page_number);
  295.     }
  296.  
  297.     private static function get_limit_period_dates($period){
  298.         if(empty($period))
  299.             return array("start_date" => null, "end_date" => null);
  300.  
  301.         switch($period){
  302.             case "day" :
  303.                 return array(
  304.                     "start_date" => gmdate("Y-m-d"),
  305.                     "end_date" => gmdate("Y-m-d"));
  306.             break;
  307.  
  308.             case "week" :
  309.                 return array(
  310.                     "start_date" => gmdate("Y-m-d", strtotime("last Monday")),
  311.                     "end_date" => gmdate("Y-m-d", strtotime("next Sunday")));
  312.             break;
  313.  
  314.             case "month" :
  315.                 $month_start = gmdate("Y-m-1");
  316.                 return array(
  317.                     "start_date" => $month_start,
  318.                     "end_date" => gmdate("Y-m-d", strtotime("{$month_start} +1 month - 1 hour")));
  319.             break;
  320.  
  321.             case "year" :
  322.                 return array(
  323.                     "start_date" => gmdate("Y-1-1"),
  324.                     "end_date" => gmdate("Y-12-31"));
  325.             break;
  326.         }
  327.     }
  328.  
  329.     public static function get_form($form_id, $display_title=true, $display_description=true, $force_display=false, $field_values=null, $ajax=false, $tabindex = 1){
  330.  
  331.  
  332.         //looking up form id by form name
  333.         if(!is_numeric($form_id))
  334.             $form_id = RGFormsModel::get_form_id($form_id);
  335.  
  336.         //reading form metadata
  337.         $form = RGFormsModel::get_form_meta($form_id, true);
  338.         $form = RGFormsModel::add_default_properties($form);
  339.  
  340.         //disable ajax if form has a reCAPTCHA field (not supported).
  341.         if($ajax && self::has_recaptcha_field($form))
  342.             $ajax = false;
  343.  
  344.         $is_postback = false;
  345.         $is_valid = true;
  346.         $confirmation_message = "";
  347.         $page_number = 1;
  348.  
  349.         //If form was submitted, read variables set during form submission procedure
  350.         $submission_info = isset(self::$submission[$form_id]) ? self::$submission[$form_id] : false;
  351.         if($submission_info){
  352.             $is_postback = true;
  353.             $is_valid = rgar($submission_info, "is_valid") || rgar($submission_info, "is_confirmation");
  354.             $form = $submission_info["form"];
  355.             $lead = $submission_info["lead"];
  356.             $confirmation_message = rgget("confirmation_message", $submission_info);
  357.  
  358.             if($is_valid && !RGForms::get("is_confirmation", $submission_info)){
  359.  
  360.                 if($submission_info["page_number"] == 0){
  361.                     //post submission hook
  362.                     do_action("gform_post_submission", $lead, $form);
  363.                     do_action("gform_post_submission_{$form["id"]}", $lead, $form);
  364.                 }
  365.                 else{
  366.                     //change page hook
  367.                     do_action("gform_post_paging", $form, $submission_info["source_page_number"], $submission_info["page_number"]);
  368.                     do_action("gform_post_paging_{$form["id"]}", $form, $submission_info["source_page_number"], $submission_info["page_number"]);
  369.                 }
  370.             }
  371.         }
  372.         else if(!current_user_can("administrator")){
  373.             RGFormsModel::insert_form_view($form_id, $_SERVER['REMOTE_ADDR']);
  374.         }
  375.  
  376.         if(rgar($form,"enableHoneypot"))
  377.             $form["fields"][] = self::get_honeypot_field($form);
  378.  
  379.         //Fired right before the form rendering process. Allow users to manipulate the form object before it gets displayed in the front end
  380.         $form = apply_filters("gform_pre_render_$form_id", apply_filters("gform_pre_render", $form, $ajax), $ajax);
  381.  
  382.         if($form == null)
  383.             return "<p>" . __("Oops! We could not locate your form.", "gravityforms") . "</p>";
  384.  
  385.         $has_pages = self::has_pages($form);
  386.  
  387.         //calling tab index filter
  388.         GFCommon::$tab_index = apply_filters("gform_tabindex_{$form_id}", apply_filters("gform_tabindex", $tabindex, $form), $form);
  389.  
  390.         //Don't display inactive forms
  391.         if(!$force_display && !$is_postback) {
  392.  
  393.             $form_info = RGFormsModel::get_form($form_id);
  394.             if(!$form_info->is_active)
  395.                 return "";
  396.  
  397.             // If form requires login, check if user is logged in
  398.             if(rgar($form, "requireLogin")) {
  399.                 if(!is_user_logged_in())
  400.                     return empty($form["requireLoginMessage"]) ? "<p>" . __("Sorry. You must be logged in to view this form.", "gravityforms"). "</p>" : "<p>" . GFCommon::gform_do_shortcode($form["requireLoginMessage"]) . "</p>";
  401.             }
  402.  
  403.         }
  404.  
  405.         // show the form regardless of the following validations when force display is set to true
  406.         if(!$force_display) {
  407.  
  408.             $form_schedule_validation = self::validate_form_schedule($form);
  409.  
  410.             // if form schedule validation fails AND this is not a postback, display the validation error
  411.             // if form schedule validation fails AND this is a postback, make sure is not a valid submission (enables display of confirmation message)
  412.             if( ($form_schedule_validation && !$is_postback) || ($form_schedule_validation && $is_postback && !$is_valid) )
  413.                 return $form_schedule_validation;
  414.  
  415.             $entry_limit_validation = self::validate_entry_limit($form);
  416.  
  417.             // refer to form schedule condition notes above
  418.             if( ($entry_limit_validation && !$is_postback) || ($entry_limit_validation && $is_postback && !$is_valid) )
  419.                 return $entry_limit_validation;
  420.  
  421.         }
  422.  
  423.         $form_string = "";
  424.  
  425.         //When called via a template, this will enqueue the proper scripts
  426.         //When called via a shortcode, this will be ignored (too late to enqueue), but the scripts will be enqueued via the enqueue_scripts event
  427.         self::enqueue_form_scripts($form, $ajax);
  428.  
  429.         if(empty($confirmation_message)){
  430.             $wrapper_css_class = GFCommon::get_browser_class() . " gform_wrapper";
  431.  
  432.             if(!$is_valid)
  433.                 $wrapper_css_class .=" gform_validation_error";
  434.  
  435.             //Hidding entire form if conditional logic is on to prevent "hidden" fields from blinking. Form will be set to visible in the conditional_logic.php after the rules have been applied.
  436.             $style = self::has_conditional_logic($form) ? "style='display:none'" : "";
  437.             $custom_wrapper_css_class = !empty($form["cssClass"]) ? " {$form["cssClass"]}_wrapper": "";
  438.             $form_string .= "
  439.                <div class='{$wrapper_css_class}{$custom_wrapper_css_class}' id='gform_wrapper_$form_id' " . $style . ">";
  440.  
  441.             $action = add_query_arg(array());
  442.             $default_anchor = $has_pages || $ajax ? true : false;
  443.             $use_anchor = apply_filters("gform_confirmation_anchor_{$form["id"]}", apply_filters("gform_confirmation_anchor", $default_anchor));
  444.             if($use_anchor !== false){
  445.                 $form_string .="<a id='gf_$form_id' name='gf_$form_id' class='gform_anchor' ></a>";
  446.                 $action .= "#gf_$form_id";
  447.             }
  448.             $target = $ajax ? "target='gform_ajax_frame_{$form_id}'" : "";
  449.  
  450.             $form_css_class = !empty($form["cssClass"]) ? "class='{$form["cssClass"]}'": "";
  451.  
  452.             $action = esc_attr($action);
  453.             $form_string .= apply_filters("gform_form_tag_{$form_id}", apply_filters("gform_form_tag", "<form method='post' enctype='multipart/form-data' {$target} id='gform_{$form_id}' {$form_css_class} action='{$action}'>", $form), $form);
  454.  
  455.             if($display_title || $display_description){
  456.                 $form_string .= "
  457.                        <div class='gform_heading'>";
  458.                 if($display_title){
  459.                     $form_string .= "
  460.                            <h3 class='gform_title'>" . $form['title'] . "</h3>";
  461.                 }
  462.                 if($display_description){
  463.                     $form_string .= "
  464.                            <span class='gform_description'>" . rgar($form,'description') ."</span>";
  465.                 }
  466.                 $form_string .= "
  467.                        </div>";
  468.             }
  469.  
  470.             $current_page = self::get_current_page($form_id);
  471.             if($has_pages && !IS_ADMIN){
  472.                 $page_count = self::get_max_page_number($form);
  473.  
  474.                 if($form["pagination"]["type"] == "percentage"){
  475.                     $form_string .= self::get_progress_bar($form, $form_id,$confirmation_message);
  476.                 }
  477.                 else if($form["pagination"]["type"] == "steps"){
  478.                     $form_string .="
  479.                    <div id='gf_page_steps_{$form_id}' class='gf_page_steps'>";
  480.  
  481.                     for($i=0, $count = sizeof($form["pagination"]["pages"]); $i<$count; $i++){
  482.                         $step_number = $i+1;
  483.                         $active_class = $step_number == $current_page ? " gf_step_active" : "";
  484.                         $first_class = $i==0 ? " gf_step_first" : "";
  485.                         $last_class = $i+1 == $count ? " gf_step_last" : "";
  486.                         $complete_class = $step_number < $current_page ? " gf_step_completed" : "";
  487.                         $previous_class = $step_number + 1 == $current_page ? " gf_step_previous" : "";
  488.                         $next_class = $step_number - 1 == $current_page ? " gf_step_next" : "";
  489.                         $pending_class = $step_number > $current_page ? " gf_step_pending" : "";
  490.                         $classes = "gf_step" . $active_class . $first_class . $last_class . $complete_class . $previous_class . $next_class . $pending_class;
  491.  
  492.                         $classes = GFCommon::trim_all($classes);
  493.  
  494.                         $form_string .="
  495.                        <div id='gf_step_{$form_id}_{$step_number}' class='{$classes}'><span class='gf_step_number'>{$step_number}</span>&nbsp;{$form["pagination"]["pages"][$i]}</div>";
  496.                     }
  497.  
  498.                     $form_string .="
  499.                        <div class='gf_step_clear'></div>
  500.                    </div>";
  501.                 }
  502.             }
  503.  
  504.  
  505.             if($is_postback && !$is_valid){
  506.                 $validation_message = "<div class='validation_error'>" . __("There was a problem with your submission.", "gravityforms") . " " . __("Errors have been highlighted below.", "gravityforms") . "</div>";
  507.                 $form_string .= apply_filters("gform_validation_message_{$form["id"]}", apply_filters("gform_validation_message", $validation_message, $form), $form);
  508.             }
  509.  
  510.             $form_string .= "
  511.                        <div class='gform_body'>";
  512.  
  513.             //add first page if this form has any page fields
  514.             if($has_pages){
  515.                 $style = self::is_page_active($form_id, 1) ? "" : "style='display:none;'";
  516.                 $class = !empty($form["firstPageCssClass"]) ? " {$form["firstPageCssClass"]}" : "";
  517.                 $form_string .= "<div id='gform_page_{$form_id}_1' class='gform_page{$class}' {$style}>
  518.                                    <div class='gform_page_fields'>";
  519.             }
  520.  
  521.             $description_class = rgar($form,"descriptionPlacement") == "above" ? "description_above" : "description_below";
  522.  
  523.             $form_string .= "
  524.                            <ul id='gform_fields_$form_id' class='gform_fields {$form['labelPlacement']} {$description_class}'>";
  525.  
  526.                             if(is_array($form['fields']))
  527.                             {
  528.                                 foreach($form['fields'] as $field){
  529.                                     $field["conditionalLogicFields"] = self::get_conditional_logic_fields($form, $field["id"]);
  530.                                     $form_string .= self::get_field($field, RGFormsModel::get_field_value($field, $field_values), false, $form, $field_values);
  531.                                 }
  532.                             }
  533.             $form_string .= "
  534.                            </ul>";
  535.  
  536.              if($has_pages){
  537.                 $previous_button = self::get_form_button($form["id"], "gform_previous_button_{$form["id"]}", $form["lastPageButton"], __("Previous", "gravityforms"), "button gform_previous_button", __("Previous Page", "gravityforms"), self::get_current_page($form_id) -1);
  538.                 $form_string .= "</div>" . self::gform_footer($form, "gform_page_footer " . $form['labelPlacement'], $ajax, $field_values, $previous_button, $display_title, $display_description, $is_postback) . "
  539.                            </div>"; //closes gform_page
  540.              }
  541.  
  542.              $form_string .= "</div>"; //closes gform_body
  543.  
  544.              //suppress form footer for multi-page forms (footer will be included on the last page
  545.              if(!$has_pages)
  546.                 $form_string .= self::gform_footer($form, "gform_footer " . $form['labelPlacement'], $ajax, $field_values, "", $display_title, $display_description, $is_postback);
  547.  
  548.              $form_string .= "
  549.                </form>
  550.                </div>";
  551.  
  552.             if($ajax && $is_postback){
  553.                 global $wp_scripts;
  554.  
  555.                 $form_string = "<!DOCTYPE html><html><head>" .
  556.                                 "<meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $form_string . "</body></html>";
  557.             }
  558.  
  559.             if($ajax && !$is_postback){
  560.                 $spinner_url = apply_filters("gform_ajax_spinner_url_{$form_id}", apply_filters("gform_ajax_spinner_url", GFCommon::get_base_url() . "/images/spinner.gif", $form), $form);
  561.                 $scroll_position = array('default' => '', 'confirmation' => '');
  562.  
  563.                 if($use_anchor !== false) {
  564.                     $scroll_position['default'] = is_numeric($use_anchor) ? "jQuery(document).scrollTop(" . intval($use_anchor) . ");" : "jQuery(document).scrollTop(jQuery('#gform_wrapper_{$form_id}').offset().top);";
  565.                     $scroll_position['confirmation'] = is_numeric($use_anchor) ? "jQuery(document).scrollTop(" . intval($use_anchor) . ");" : "jQuery(document).scrollTop(jQuery('#gforms_confirmation_message').offset().top);";
  566.                 }
  567. /* Don't really need this here
  568.                 $form_string .="
  569.                 <iframe style='display:none;width:0px; height:0px;' src='about:blank' name='gform_ajax_frame_{$form_id}' id='gform_ajax_frame_{$form_id}'></iframe>
  570.                 <script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . "" .
  571.                     "function gformInitSpinner_{$form_id}(){" .
  572.                         "jQuery('#gform_{$form_id}').submit(function(){" .
  573.                             "if(jQuery('#gform_ajax_spinner_{$form_id}').length == 0){".
  574.                                 "jQuery('#gform_submit_button_{$form_id}, #gform_wrapper_{$form_id} .gform_previous_button, #gform_wrapper_{$form_id} .gform_next_button, #gform_wrapper_{$form_id} .gform_image_button').attr('disabled', true); " .
  575.                                 "jQuery('#gform_submit_button_{$form_id}, #gform_wrapper_{$form_id} .gform_next_button, #gform_wrapper_{$form_id} .gform_image_button').after('<' + 'img id=\"gform_ajax_spinner_{$form_id}\"  class=\"gform_ajax_spinner\" src=\"{$spinner_url}\" alt=\"\" />'); " .
  576.                             "}".
  577.                         "} );" .
  578.                     "}" .
  579.                     "jQuery(document).ready(function($){" .
  580.                         "gformInitSpinner_{$form_id}();" .
  581.                         "jQuery('#gform_ajax_frame_{$form_id}').load( function(){" .
  582.                             "var contents = jQuery(this).contents().find('*').html();" .
  583.                             "var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;" .
  584.                             "if(!is_postback){return;}" .
  585.                             "var form_content = jQuery(this).contents().find('#gform_wrapper_{$form_id}');" .
  586.                             "var is_redirect = contents.indexOf('gformRedirect(){') >= 0;".
  587.                             "jQuery('#gform_submit_button_{$form_id}').removeAttr('disabled');" .
  588.                             "var is_form = !(form_content.length <= 0 || is_redirect);".
  589.                             "if(is_form){" .
  590.                                 "jQuery('#gform_wrapper_{$form_id}').html(form_content.html());" .
  591.                                 "{$scroll_position['default']}" .
  592.                                 "if(window['gformInitDatepicker']) {gformInitDatepicker();}" .
  593.                                 "if(window['gformInitPriceFields']) {gformInitPriceFields();}" .
  594.                                 "var current_page = jQuery('#gform_source_page_number_{$form_id}').val();".
  595.                                 "gformInitSpinner_{$form_id}();" .
  596.                                 "jQuery(document).trigger('gform_page_loaded', [{$form_id}, current_page]);" .
  597.                             "}" .
  598.                             "else if(!is_redirect){" .
  599.                                 "var confirmation_content = jQuery(this).contents().find('#gforms_confirmation_message').html();" .
  600.                                 "if(!confirmation_content){".
  601.                                     "confirmation_content = contents;".
  602.                                 "}" .
  603.                                 "setTimeout(function(){" .
  604.                                     "jQuery('#gform_wrapper_{$form_id}').replaceWith('<' + 'div id=\'gforms_confirmation_message\' class=\'gform_confirmation_message_{$form_id}\'' + '>' + confirmation_content + '<' + '/div' + '>');" .
  605.                                     "{$scroll_position['confirmation']}" .
  606.                                     "jQuery(document).trigger('gform_confirmation_loaded', [{$form_id}]);" .
  607.                                 "}, 50);" .
  608.                             "}" .
  609.                             "else{" .
  610.                                 "jQuery('#gform_{$form_id}').append(contents);" .
  611.                                 "if(window['gformRedirect']) {gformRedirect();}" .
  612.                             "}" .
  613.                             "jQuery(document).trigger('gform_post_render', [{$form_id}, current_page]);" .
  614.                         "} );" .
  615.                     "} );" . apply_filters("gform_cdata_close", "") . "</script>";
  616.                     */
  617.                     add_action('wp_footer', 'form_script_footer', 100); // heavy weight to sit at bottom
  618.             }
  619.  
  620.             $is_first_load = !$is_postback;
  621.  
  622.             if((!$ajax || $is_first_load)) {
  623.  
  624.                 self::register_form_init_scripts($form, $field_values);
  625.  
  626.                 if(apply_filters("gform_init_scripts_footer", false)){
  627.                     add_action("wp_footer",            create_function('', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');'), 20);
  628.                     add_action("gform_preview_footer", create_function('', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');'));
  629.                 }
  630.                 else{
  631.                     $form_string .= self::get_form_init_scripts($form);
  632.                     $form_string .= "<script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . " jQuery(document).ready(function(){jQuery(document).trigger('gform_post_render', [{$form_id}, {$current_page}]) } ); " . apply_filters("gform_cdata_close", "") . "</script>";
  633.                 }
  634.             }
  635.  
  636.             return apply_filters('gform_get_form_filter',$form_string);
  637.         }
  638.         else{
  639.             $progress_confirmation = "";
  640.  
  641.             //check admin setting for whether the progress bar should start at zero
  642.             $start_at_zero = rgars($form, "pagination/display_progressbar_on_confirmation");
  643.             //check for filter
  644.             $start_at_zero = apply_filters("gform_progressbar_start_at_zero", $start_at_zero, $form);
  645.  
  646.             //show progress bar on confirmation
  647.             if($start_at_zero && $has_pages && !IS_ADMIN && ($form["confirmation"]["type"] == "message" && $form["pagination"]["type"] == "percentage") && $form["pagination"]["display_progressbar_on_confirmation"])
  648.             {
  649.                 $progress_confirmation = self::get_progress_bar($form, $form_id,$confirmation_message);
  650.                 if($ajax)
  651.                 {
  652.                     $progress_confirmation = "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $progress_confirmation . $confirmation_message . "</body></html>";
  653.                 }
  654.                 else
  655.                 {
  656.                     $progress_confirmation = $progress_confirmation . $confirmation_message;
  657.                 }
  658.             }
  659.             else
  660.             {
  661.                 //return regular confirmation message
  662.                 if($ajax)
  663.                 {
  664.                     $progress_confirmation = "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $confirmation_message . "</body></html>";
  665.                 }
  666.                 else
  667.                 {
  668.                  $progress_confirmation = $confirmation_message;
  669.                 }
  670.             }
  671.  
  672.             return $progress_confirmation;
  673.         }
  674.     }
  675.  
  676.     public static function footer_init_scripts($form_id){
  677.         global $_init_forms;
  678.  
  679.         $form = RGFormsModel::get_form_meta($form_id);
  680.         $form_string = self::get_form_init_scripts($form);
  681.         $current_page = self::get_current_page($form_id);
  682.         $form_string .= "<script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . " jQuery(document).ready(function(){jQuery(document).trigger('gform_post_render', [{$form_id}, {$current_page}]) } ); " . apply_filters("gform_cdata_close", "") . "</script>";
  683.  
  684.         if(!isset($_init_forms[$form_id])){
  685.             echo $form_string;
  686.             if(!is_array($_init_forms))
  687.                 $_init_forms = array();
  688.  
  689.             $_init_forms[$form_id] = true;
  690.         }
  691.     }
  692.  
  693.     public static function add_init_script($form_id, $script_name, $location, $script){
  694.         $key = $script_name . "_" . $location;
  695.  
  696.         if(!isset(self::$init_scripts[$form_id]))
  697.             self::$init_scripts[$form_id] = array();
  698.  
  699.         //add script if it hasn't been added before
  700.         if(!array_key_exists($key, self::$init_scripts[$form_id]))
  701.             self::$init_scripts[$form_id][$key] = array("location" => $location, "script" => $script);
  702.     }
  703.  
  704.     private static function get_form_button($form_id, $button_input_id, $button, $default_text, $class, $alt, $target_page_number){
  705.         $tabindex = GFCommon::get_tabindex();
  706.         $input_type='submit';
  707.         $onclick="";
  708.         if(!empty($target_page_number)){
  709.             $onclick = "onclick='jQuery(\"#gform_target_page_number_{$form_id}\").val(\"{$target_page_number}\"); jQuery(\"#gform_{$form_id}\").trigger(\"submit\",[true]); '";
  710.             $input_type='button';
  711.         }
  712.  
  713.         if($button["type"] == "text" || empty($button["imageUrl"])){
  714.             $button_text = !empty($button["text"]) ? $button["text"] : $default_text;
  715.             $button_input = "<input type='{$input_type}' id='{$button_input_id}' class='{$class}' value='" . esc_attr($button_text) . "' {$tabindex} {$onclick}/>";
  716.         }
  717.         else{
  718.             $imageUrl = $button["imageUrl"];
  719.             $button_input= "<input type='image' src='{$imageUrl}' id='{$button_input_id}' class='gform_image_button' alt='{$alt}' {$tabindex} {$onclick}/>";
  720.         }
  721.         return $button_input;
  722.     }
  723.  
  724.     private static function gform_footer($form, $class, $ajax, $field_values, $previous_button, $display_title, $display_description){
  725.         $form_id = $form["id"];
  726.         $footer = "
  727.        <div class='" . $class ."'>";
  728.         $button_input = self::get_form_button($form["id"], "gform_submit_button_{$form["id"]}", $form["button"], __("Submit", "gravityforms"), "button gform_button", __("Submit", "gravityforms"), 0);
  729.         $button_input = apply_filters("gform_submit_button", $button_input, $form);
  730.         $button_input = apply_filters("gform_submit_button_{$form_id}", $button_input, $form);
  731.         $footer .= $previous_button . " " . $button_input;
  732.  
  733.         if($ajax){
  734.             $footer .= "<input type='hidden' name='gform_ajax' value='" . esc_attr("form_id={$form_id}&amp;title={$display_title}&amp;description={$display_description}") . "' />";
  735.         }
  736.  
  737.         $current_page = self::get_current_page($form_id);
  738.         $next_page = $current_page + 1;
  739.         $next_page = $next_page > self::get_max_page_number($form) ? 0 : $next_page;
  740.         $field_values_str = is_array($field_values) ? http_build_query($field_values) : $field_values;
  741.         $files_input = "";
  742.         if(!empty(RGFormsModel::$uploaded_files[$form_id])){
  743.             $files = GFCommon::json_encode(RGFormsModel::$uploaded_files[$form_id]);
  744.             $files_input = "<input type='hidden' name='gform_uploaded_files' id='gform_uploaded_files_{$form_id}' value='" . str_replace("'", "&#039;", $files) . "' />";
  745.         }
  746.  
  747.         $footer .="
  748.            <input type='hidden' class='gform_hidden' name='is_submit_{$form_id}' value='1' />
  749.            <input type='hidden' class='gform_hidden' name='gform_submit' value='{$form_id}' />
  750.            <input type='hidden' class='gform_hidden' name='gform_unique_id' value='" . esc_attr(RGFormsModel::get_form_unique_id($form_id)) . "' />
  751.            <input type='hidden' class='gform_hidden' name='state_{$form_id}' value='" . self::get_state($form, $field_values) . "' />
  752.            <input type='hidden' class='gform_hidden' name='gform_target_page_number_{$form_id}' id='gform_target_page_number_{$form_id}' value='" . $next_page . "' />
  753.            <input type='hidden' class='gform_hidden' name='gform_source_page_number_{$form_id}' id='gform_source_page_number_{$form_id}' value='" . $current_page . "' />
  754.            <input type='hidden' name='gform_field_values' value='" . esc_attr($field_values_str) ."' />
  755.            {$files_input}
  756.        </div>";
  757.  
  758.         return $footer;
  759.     }
  760.  
  761.     private static function get_max_page_number($form){
  762.         $page_number = 0;
  763.         foreach($form["fields"] as $field){
  764.             if($field["type"] == "page"){
  765.                $page_number++;
  766.             }
  767.         }
  768.         return $page_number == 0 ? 0 : $page_number + 1;
  769.     }
  770.  
  771.  
  772.     private static function get_honeypot_field($form){
  773.         $max_id = self::get_max_field_id($form);
  774.         $labels = self::get_honeypot_labels();
  775.         return array("type" => "honeypot", "label" => $labels[rand(0, 3)], "id" => $max_id + 1, "cssClass" => "gform_validation_container", "description" => "This field is for validation purposes and should be left unchanged.");
  776.     }
  777.  
  778.     private static function get_max_field_id($form){
  779.         $max = 0;
  780.         foreach($form["fields"] as $field){
  781.             if(floatval($field["id"]) > $max)
  782.                 $max = floatval($field["id"]);
  783.         }
  784.         return $max;
  785.     }
  786.  
  787.     private static function get_honeypot_labels(){
  788.         return array("Name", "Email", "Phone", "Comments");
  789.     }
  790.  
  791.     public static function is_empty($field, $form_id=0){
  792.         switch(RGFormsModel::get_input_type($field)){
  793.             case "post_image" :
  794.             case "fileupload" :
  795.                 $input_name = "input_" . $field["id"];
  796.  
  797.                 $file_info = RGFormsModel::get_temp_filename($form_id, $input_name);
  798.                 return !$file_info && empty($_FILES[$input_name]['name']);
  799.  
  800.             case "list" :
  801.                 $value = rgpost("input_" . $field["id"]);
  802.                 if(is_array($value)){
  803.                     //empty if all inputs are empty (for inputs with the same name)
  804.                     foreach($value as $input){
  805.                         if(strlen(trim($input)) > 0 )
  806.                             return false;
  807.                     }
  808.                 }
  809.  
  810.                 return true;
  811.  
  812.             case 'singleproduct':
  813.                 $value = rgpost("input_" . $field["id"]);
  814.                 $quantity_id = $field["id"] . ".3";
  815.                 $quantity = rgpost($quantity_id, $value);
  816.  
  817.         }
  818.  
  819.  
  820.  
  821.         if(is_array($field["inputs"]))
  822.         {
  823.             foreach($field["inputs"] as $input){
  824.                 $value = rgpost("input_" . str_replace('.', '_', $input["id"]));
  825.                 if(is_array($value) && !empty($value)){
  826.                     return false;
  827.                 }
  828.  
  829.                 $strlen = strlen(trim($value));
  830.                 if(!is_array($value) && strlen(trim($value)) > 0)
  831.                     return false;
  832.             }
  833.             return true;
  834.         }
  835.         else{
  836.             $value = rgpost("input_" . $field["id"]);
  837.             if(is_array($value)){
  838.                 //empty if any of the inputs are empty (for inputs with the same name)
  839.                 foreach($value as $input){
  840.                     if(strlen(trim($input)) <= 0 )
  841.                         return true;
  842.                 }
  843.                 return false;
  844.             }
  845.             else if($field["enablePrice"]){
  846.                 list($label, $price) = explode("|", $value);
  847.                 $is_empty = (strlen(trim($price)) <= 0);
  848.                 return $is_empty;
  849.             }
  850.             else{
  851.                 $is_empty = (strlen(trim($value)) <= 0) || ($field["type"] == "post_category" && $value < 0);
  852.                 return $is_empty;
  853.             }
  854.         }
  855.     }
  856.  
  857.     private static function clean_extensions($extensions){
  858.         $count = sizeof($extensions);
  859.         for($i=0; $i<$count; $i++){
  860.             $extensions[$i] = str_replace(".", "",str_replace(" ", "", $extensions[$i]));
  861.         }
  862.         return $extensions;
  863.     }
  864.  
  865.     private static function validate_range($field, $value){
  866.  
  867.         if( !GFCommon::is_numeric($value, rgar($field, "numberFormat")) )
  868.             return false;
  869.  
  870.         $number = GFCommon::clean_number($value, rgar($field, "numberFormat"));
  871.         if( (is_numeric($field["rangeMin"]) && $number < $field["rangeMin"]) ||
  872.             (is_numeric($field["rangeMax"]) && $number > $field["rangeMax"])
  873.         )
  874.             return false;
  875.         else
  876.             return true;
  877.     }
  878.  
  879.     private static function validate_honeypot($form){
  880.         $honeypot_id = self::get_max_field_id($form);
  881.         return rgempty("input_{$honeypot_id}");
  882.     }
  883.  
  884.     public static function handle_submission($form, &$lead, $ajax=false){
  885.  
  886.         //creating entry in DB
  887.         RGFormsModel::save_lead($form, $lead);
  888.  
  889.         //reading entry that was just saved
  890.         $lead = RGFormsModel::get_lead($lead["id"]);
  891.  
  892.         $lead = GFFormsModel::set_entry_meta($lead, $form);
  893.         do_action('gform_entry_created', $lead, $form);
  894.  
  895.         //if Akismet plugin is installed, run lead through Akismet and mark it as Spam when appropriate
  896.         $is_spam = false;
  897.         if(GFCommon::akismet_enabled($form['id']) && GFCommon::is_akismet_spam($form, $lead)){
  898.             $is_spam = true;
  899.         }
  900.  
  901.         if(!$is_spam){
  902.             GFCommon::create_post($form, $lead);
  903.             //send auto-responder and notification emails
  904.             self::send_emails($form, $lead);
  905.         }
  906.         else{
  907.             //marking entry as spam
  908.             RGFormsModel::update_lead_property($lead["id"], "status", "spam", false, true);
  909.             $lead["status"] = "spam";
  910.         }
  911.  
  912.         //display confirmation message or redirect to confirmation page
  913.         return self::handle_confirmation($form, $lead, $ajax);
  914.     }
  915.  
  916.     public static function handle_confirmation($form, $lead, $ajax=false){
  917.  
  918.         if($form["confirmation"]["type"] == "message"){
  919.             $default_anchor = self::has_pages($form) ? 1 : 0;
  920.             $anchor = apply_filters("gform_confirmation_anchor_{$form["id"]}", apply_filters("gform_confirmation_anchor", $default_anchor)) ? "<a id='gf_{$form["id"]}' name='gf_{$form["id"]}' class='gform_anchor' ></a>" : "";
  921.             $nl2br = rgar($form["confirmation"],"disableAutoformat") ? false : true;
  922.             $confirmation = empty($form["confirmation"]["message"]) ? "{$anchor} " : "{$anchor}<div id='gforms_confirmation_message' class='gform_confirmation_message_{$form["id"]}'>" . GFCommon::replace_variables($form["confirmation"]["message"], $form, $lead, false, true, $nl2br) . "</div>";
  923.         }
  924.         else{
  925.             if(!empty($form["confirmation"]["pageId"])){
  926.                 $url = get_permalink($form["confirmation"]["pageId"]);
  927.             }
  928.             else{
  929.                 $url = GFCommon::replace_variables(trim($form["confirmation"]["url"]), $form, $lead, false, true);
  930.                 $url_info = parse_url($url);
  931.                 $query_string = $url_info["query"];
  932.                 $dynamic_query = GFCommon::replace_variables(trim($form["confirmation"]["queryString"]), $form, $lead, true);
  933.                 $query_string .= empty($url_info["query"]) || empty($dynamic_query) ? $dynamic_query : "&" . $dynamic_query;
  934.  
  935.                 if(!empty($url_info["fragment"]))
  936.                     $query_string .= "#" . $url_info["fragment"];
  937.  
  938.                 $url = $url_info["scheme"] . "://" . $url_info["host"];
  939.                 if(!empty($url_info["port"]))
  940.                     $url .= ":{$url_info["port"]}";
  941.  
  942.                 $url .= rgar($url_info,"path");
  943.                 if(!empty($query_string)){
  944.                     $url .= "?{$query_string}";
  945.                 }
  946.  
  947.             }
  948.  
  949.             if(headers_sent() || $ajax){
  950.                 //Perform client side redirect for AJAX forms, of if headers have already been sent
  951.                 $confirmation = self::get_js_redirect_confirmation($url, $ajax);
  952.             }
  953.             else{
  954.                 $confirmation = array("redirect" => $url);
  955.             }
  956.         }
  957.  
  958.         $confirmation = apply_filters("gform_confirmation_{$form["id"]}", apply_filters("gform_confirmation", $confirmation, $form, $lead, $ajax), $form, $lead, $ajax);
  959.  
  960.         if(!is_array($confirmation)){
  961.             $confirmation = GFCommon::gform_do_shortcode($confirmation); //enabling shortcodes
  962.         }
  963.         else if(headers_sent() || $ajax){
  964.             //Perform client side redirect for AJAX forms, of if headers have already been sent
  965.             $confirmation = self::get_js_redirect_confirmation($confirmation["redirect"], $ajax); //redirecting via client side
  966.         }
  967.  
  968.         return $confirmation;
  969.     }
  970.  
  971.     private static function get_js_redirect_confirmation($url, $ajax){
  972.         $confirmation = "<script type=\"text/javascript\">" . apply_filters("gform_cdata_open", "") . " function gformRedirect(){document.location.href='$url';}";
  973.         if(!$ajax)
  974.             $confirmation .="gformRedirect();";
  975.  
  976.         $confirmation .= apply_filters("gform_cdata_close", "") . "</script>";
  977.  
  978.         return $confirmation;
  979.     }
  980.  
  981.     public static function send_emails($form, $lead){
  982.         $disable_user_notification = apply_filters("gform_disable_user_notification_{$form["id"]}", apply_filters("gform_disable_user_notification", false, $form, $lead), $form, $lead);
  983.         if(!$disable_user_notification){
  984.             GFCommon::send_user_notification($form, $lead);
  985.         }
  986.  
  987.         $disable_admin_notification = apply_filters("gform_disable_admin_notification_{$form["id"]}", apply_filters("gform_disable_admin_notification", false, $form, $lead), $form, $lead);
  988.         if(!$disable_admin_notification){
  989.             GFCommon::send_admin_notification($form, $lead);
  990.         }
  991.     }
  992.  
  993.     public static function checkdate($month, $day, $year){
  994.         if(empty($month) || !is_numeric($month) || empty($day) || !is_numeric($day) || empty($year) || !is_numeric($year) || strlen($year) != 4)
  995.             return false;
  996.  
  997.         return checkdate($month, $day, $year);
  998.     }
  999.  
  1000.     public static function validate(&$form, $field_values, $page_number=0, &$failed_validation_page=0){
  1001.  
  1002.         $form = apply_filters('gform_pre_validation', $form);
  1003.  
  1004.         // validate form schedule
  1005.         if(self::validate_form_schedule($form))
  1006.             return false;
  1007.  
  1008.         // validate entry limit
  1009.         if(self::validate_entry_limit($form))
  1010.             return false;
  1011.  
  1012.         foreach($form["fields"] as &$field){
  1013.  
  1014.             //If a page number is specified, only validates fields that are on current page
  1015.             $field_in_other_page = $page_number > 0 && $field["pageNumber"] != $page_number;
  1016.  
  1017.             //validate fields with "no duplicate" functionality when they are present on pages before the current page.
  1018.             $validate_duplicate_feature = $field["noDuplicates"] && $page_number > 0 && $field["pageNumber"] <= $page_number;
  1019.  
  1020.             if($field_in_other_page && !$validate_duplicate_feature){
  1021.                 continue;
  1022.             }
  1023.  
  1024.             //ignore validation if field is hidden or admin only
  1025.             if(RGFormsModel::is_field_hidden($form, $field, $field_values) || $field["adminOnly"])
  1026.                 continue;
  1027.  
  1028.             $value = RGFormsModel::get_field_value($field);
  1029.  
  1030.             //display error message if field is marked as required and the submitted value is empty
  1031.             if($field["isRequired"] && self::is_empty($field, $form["id"])){
  1032.                 $field["failed_validation"] = true;
  1033.                 $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  1034.             }
  1035.             //display error if field does not allow duplicates and the submitted value already exists
  1036.             else if($field["noDuplicates"] && RGFormsModel::is_duplicate($form["id"], $field, $value)){
  1037.                 $field["failed_validation"] = true;
  1038.                 //set page number so the failed field displays if on multi-page form
  1039.                 $failed_validation_page = $field["pageNumber"];
  1040.  
  1041.                 $input_type = RGFormsModel::get_input_type($field);
  1042.                 switch($input_type){
  1043.                     case "date" :
  1044.                         $default_message = __("This date has already been taken. Please select a new date.", "gravityforms");
  1045.                     break;
  1046.  
  1047.                     default:
  1048.                         $default_message = is_array($value) ? __("This field requires an unique entry and the values you entered have been already been used.", "gravityforms") :
  1049.                                                               sprintf(__("This field requires an unique entry and '%s' has already been used", "gravityforms"), $value);
  1050.                     break;
  1051.                 }
  1052.  
  1053.                 $field["validation_message"] =  apply_filters("gform_duplicate_message_{$form["id"]}", apply_filters("gform_duplicate_message", $default_message, $form), $form);
  1054.  
  1055.             }
  1056.             else{
  1057.                 if(self::failed_state_validation($form["id"], $field, $value)){
  1058.                     $field["failed_validation"] = true;
  1059.                     $field["validation_message"] = in_array($field["inputType"], array("singleproduct", "singleshipping", "hiddenproduct")) ? __("Please enter a valid value.", "gravityforms") : __("Invalid selection. Please select one of the available choices.", "gravityforms");
  1060.                 }
  1061.                 else{
  1062.                     switch(RGFormsModel::get_input_type($field)){
  1063.                         case "password" :
  1064.                             $password =  $_POST["input_" . $field["id"]];
  1065.                             $confirm = $_POST["input_" . $field["id"] . "_2"];
  1066.                             if($password != $confirm){
  1067.                                 $field["failed_validation"] = true;
  1068.                                 $field["validation_message"] = __("Your passwords do not match.", "gravityforms");
  1069.                             }
  1070.                             else if(rgar($field,"passwordStrengthEnabled") && !rgempty("minPasswordStrength",$field) && !empty($password)){
  1071.                                 $strength = $_POST["input_" . $field["id"] . "_strength"];
  1072.  
  1073.                                 $levels = array("short" => 1, "bad" => 2, "good" => 3, "strong" => 4);
  1074.                                 if($levels[$strength] < $levels[$field["minPasswordStrength"]]){
  1075.                                     $field["failed_validation"] = true;
  1076.                                     $field["validation_message"] = empty($field["errorMessage"]) ? __("Your password does not meet the required strength. <br/>Hint: To make it stronger, use upper and lower case letters, numbers and symbols like ! \" ? $ % ^ & ).", "gravityforms") : $field["errorMessage"];
  1077.                                 }
  1078.                             }
  1079.                         break;
  1080.  
  1081.                         case "name" :
  1082.                             if($field["isRequired"] && $field["nameFormat"] != "simple")
  1083.                             {
  1084.                                 $first = $_POST["input_" . $field["id"] . "_3"];
  1085.                                 $last = $_POST["input_" . $field["id"] . "_6"];
  1086.                                 if(empty($first) || empty($last)){
  1087.                                     $field["failed_validation"] = true;
  1088.                                     $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required. Please enter the first and last name.", "gravityforms") : $field["errorMessage"];
  1089.                                 }
  1090.                             }
  1091.  
  1092.                         break;
  1093.  
  1094.                         case "address" :
  1095.                             if($field["isRequired"])
  1096.                             {
  1097.                                 $street = $_POST["input_" . $field["id"] . "_1"];
  1098.                                 $city = $_POST["input_" . $field["id"] . "_3"];
  1099.                                 $state = $_POST["input_" . $field["id"] . "_4"];
  1100.                                 $zip = $_POST["input_" . $field["id"] . "_5"];
  1101.                                 $country = $_POST["input_" . $field["id"] . "_6"];
  1102.                                 if(empty($street) || empty($city) || empty($zip) || (empty($state) && !$field["hideState"] ) || (empty($country) && !$field["hideCountry"])){
  1103.                                     $field["failed_validation"] = true;
  1104.                                     $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required. Please enter a complete address.", "gravityforms") : $field["errorMessage"];
  1105.                                 }
  1106.                             }
  1107.  
  1108.                         break;
  1109.  
  1110.                         case "creditcard" :
  1111.                             $card_number = rgpost("input_" . $field["id"] . "_1");
  1112.                             $expiration_date = rgpost("input_" . $field["id"] . "_2");
  1113.                             $security_code = rgpost("input_" . $field["id"] . "_3");
  1114.  
  1115.                             if(rgar($field, "isRequired") && (empty($card_number) || empty($security_code) || empty($expiration_date[0]) || empty($expiration_date[1]))){
  1116.                                 $field["failed_validation"] = true;
  1117.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter your credit card information.", "gravityforms") : $field["errorMessage"];
  1118.                             }
  1119.                             else if(!empty($card_number)){
  1120.                                 $card_type = GFCommon::get_card_type($card_number);
  1121.                                 $security_code = rgpost("input_" . $field["id"] . "_3");
  1122.  
  1123.                                 if(empty($security_code)){
  1124.                                     $field["failed_validation"] = true;
  1125.                                     $field["validation_message"] = __("Please enter your card's security code.", "gravityforms");
  1126.                                 }
  1127.                                 else if(!$card_type){
  1128.                                     $field["failed_validation"] = true;
  1129.                                     $field["validation_message"] = __("Invalid credit card number.", "gravityforms");
  1130.                                 }
  1131.                                 else if(!GFCommon::is_card_supported($field, $card_type["slug"])){
  1132.                                     $field["failed_validation"] = true;
  1133.                                     $field["validation_message"] = $card_type["name"] . " " . __("is not supported. Please enter one of the supported credit cards.", "gravityforms");
  1134.                                 }
  1135.                             }
  1136.                         break;
  1137.  
  1138.                         case "email" :
  1139.                             if(!rgblank($value) && !GFCommon::is_valid_email($value)){
  1140.                                 $field["failed_validation"] = true;
  1141.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid email address.", "gravityforms"): $field["errorMessage"];
  1142.                             }
  1143.                             else if(rgget("emailConfirmEnabled", $field) && !empty($value)){
  1144.                                 $confirm = rgpost("input_" . $field["id"] . "_2");
  1145.                                 if($confirm != $value){
  1146.                                     $field["failed_validation"] = true;
  1147.                                     $field["validation_message"] = __("Your emails do not match.", "gravityforms");
  1148.                                 }
  1149.                             }
  1150.                         break;
  1151.  
  1152.                         case "donation" :
  1153.                         case "price" :
  1154.  
  1155.                             if(!class_exists("RGCurrency"))
  1156.                                 require_once("currency.php");
  1157.  
  1158.                             $donation = GFCommon::to_number($value);
  1159.                             if(!rgblank($value) && ($donation === false || $donation < 0)){
  1160.                                $field["failed_validation"] = true;
  1161.                                $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid amount.", "gravityforms") : $field["errorMessage"];
  1162.  
  1163.                             }
  1164.                         break;
  1165.  
  1166.                         case "number" :
  1167.  
  1168.                             if(!rgblank($value) && !self::validate_range($field, $value) && !GFCommon::has_field_calculation($field)) {
  1169.                                 $field["failed_validation"] = true;
  1170.                                 $field["validation_message"] = empty($field["errorMessage"]) ? GFCommon::get_range_message($field) : $field["errorMessage"];
  1171.                             }
  1172.                             else if($field["type"] == "quantity" && intval($value) != $value){
  1173.                                 $field["failed_validation"] = true;
  1174.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid quantity. Quantity cannot contain decimals.", "gravityforms") : $field["errorMessage"];
  1175.                             }
  1176.  
  1177.                         break;
  1178.  
  1179.                         case "phone" :
  1180.  
  1181.                             $regex = '/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/';
  1182.                             if($field["phoneFormat"] == "standard" && !empty($value) && !preg_match($regex, $value)){
  1183.                                 $field["failed_validation"] = true;
  1184.                                 if(!empty($field["errorMessage"]))
  1185.                                     $field["validation_message"] = $field["errorMessage"];
  1186.                             }
  1187.                         break;
  1188.  
  1189.                         case "date" :
  1190.                             if(is_array($value) && rgempty(0, $value) && rgempty(1, $value)&& rgempty(2, $value))
  1191.                                 $value = null;
  1192.  
  1193.                             if(!empty($value)){
  1194.                                 $format = empty($field["dateFormat"]) ? "mdy" : $field["dateFormat"];
  1195.                                 $date = GFCommon::parse_date($value, $format);
  1196.  
  1197.                                 if(empty($date) || !self::checkdate($date["month"], $date["day"], $date["year"])){
  1198.                                     $field["failed_validation"] = true;
  1199.                                     $format_name = "";
  1200.                                     switch($format){
  1201.                                         case "mdy" :
  1202.                                             $format_name = "mm/dd/yyyy";
  1203.                                         break;
  1204.                                         case "dmy" :
  1205.                                             $format_name = "dd/mm/yyyy";
  1206.                                         break;
  1207.                                         case "dmy_dash" :
  1208.                                             $format_name = "dd-mm-yyyy";
  1209.                                         break;
  1210.                                         case "dmy_dot" :
  1211.                                             $format_name = "dd.mm.yyyy";
  1212.                                         break;
  1213.                                         case "ymd_slash" :
  1214.                                             $format_name = "yyyy/mm/dd";
  1215.                                         break;
  1216.                                         case "ymd_dash" :
  1217.                                             $format_name = "yyyy-mm-dd";
  1218.                                         break;
  1219.                                         case "ymd_dot" :
  1220.                                             $format_name = "yyyy.mm.dd";
  1221.                                         break;
  1222.                                     }
  1223.                                     $message = $field["dateType"] == "datepicker" ? sprintf(__("Please enter a valid date in the format (%s).", "gravityforms"), $format_name) : __("Please enter a valid date.", "gravityforms");
  1224.                                     $field["validation_message"] = empty($field["errorMessage"]) ? $message : $field["errorMessage"];
  1225.                                 }
  1226.                             }
  1227.                         break;
  1228.  
  1229.                         case "time" :
  1230.  
  1231.                             //create variable values if time came in one field
  1232.                             if(!is_array($value) && !empty($value)){
  1233.                                 preg_match('/^(\d*):(\d*) ?(.*)$/', $value, $matches);
  1234.                                 $value = array();
  1235.                                 $value[0] = $matches[1];
  1236.                                 $value[1] = $matches[2];
  1237.                             }
  1238.  
  1239.                             $hour = $value[0];
  1240.                             $minute = $value[1];
  1241.  
  1242.                             if(empty($hour) && empty($minute))
  1243.                                 break;
  1244.  
  1245.                             $is_valid_format = is_numeric($hour) && is_numeric($minute);
  1246.  
  1247.                             $min_hour = rgar($field, "timeFormat") == "24" ? 0 : 1;
  1248.                             $max_hour = rgar($field, "timeFormat") == "24" ? 23 : 12;
  1249.  
  1250.                             if(!$is_valid_format || $hour < $min_hour || $hour > $max_hour || $minute < 0 || $minute >= 60)
  1251.                             {
  1252.                                 $field["failed_validation"] = true;
  1253.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid time." , "gravityforms"): $field["errorMessage"];
  1254.                             }
  1255.                         break;
  1256.  
  1257.                         case "website" :
  1258.                             if(empty($value) || $value == "http://"){
  1259.                                 $value = "";
  1260.                                 if($field["isRequired"]){
  1261.                                     $field["failed_validation"] = true;
  1262.                                     $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  1263.                                 }
  1264.                             }
  1265.  
  1266.                             if(!empty($value) && !GFCommon::is_valid_url($value)){
  1267.                                 $field["failed_validation"] = true;
  1268.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid Website URL (i.e. http://www.gravityforms.com).", "gravityforms") : $field["errorMessage"];
  1269.                             }
  1270.                         break;
  1271.  
  1272.                         case "captcha" :
  1273.                             switch($field["captchaType"]){
  1274.                                 case "simple_captcha" :
  1275.                                     if(class_exists("ReallySimpleCaptcha")){
  1276.                                         $prefix = $_POST["input_captcha_prefix_{$field["id"]}"];
  1277.                                         $captcha_obj = GFCommon::get_simple_captcha();
  1278.  
  1279.                                         if(!$captcha_obj->check($prefix, str_replace(" ", "", $value))){
  1280.                                             $field["failed_validation"] = true;
  1281.                                             $field["validation_message"] = empty($field["errorMessage"]) ? __("The CAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  1282.                                         }
  1283.  
  1284.                                         //removes old files in captcha folder (older than 1 hour);
  1285.                                         $captcha_obj->cleanup();
  1286.                                     }
  1287.                                 break;
  1288.  
  1289.                                 case "math" :
  1290.                                     $prefixes = explode(",", $_POST["input_captcha_prefix_{$field["id"]}"]);
  1291.                                     $captcha_obj = GFCommon::get_simple_captcha();
  1292.  
  1293.                                     //finding first number
  1294.                                     $first = 0;
  1295.                                     for($first=0; $first<10; $first++){
  1296.                                         if($captcha_obj->check($prefixes[0], $first))
  1297.                                             break;
  1298.                                     }
  1299.  
  1300.                                     //finding second number
  1301.                                     $second = 0;
  1302.                                     for($second=0; $second<10; $second++){
  1303.                                         if($captcha_obj->check($prefixes[2], $second))
  1304.                                             break;
  1305.                                     }
  1306.  
  1307.                                     //if it is a +, perform the sum
  1308.                                     if($captcha_obj->check($prefixes[1], "+"))
  1309.                                         $result = $first + $second;
  1310.                                     else
  1311.                                         $result = $first - $second;
  1312.  
  1313.  
  1314.                                     if(intval($result) != intval($value)){
  1315.                                         $field["failed_validation"] = true;
  1316.                                         $field["validation_message"] = empty($field["errorMessage"]) ? __("The CAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  1317.                                     }
  1318.  
  1319.                                     //removes old files in captcha folder (older than 1 hour);
  1320.                                     $captcha_obj->cleanup();
  1321.  
  1322.                                 break;
  1323.  
  1324.                                 default :
  1325.                                     if(!function_exists("recaptcha_get_html")){
  1326.                                         require_once(GFCommon::get_base_path() . '/recaptchalib.php');
  1327.                                     }
  1328.  
  1329.                                     $privatekey = get_option("rg_gforms_captcha_private_key");
  1330.                                     $resp = recaptcha_check_answer ($privatekey,
  1331.                                             $_SERVER["REMOTE_ADDR"],
  1332.                                             $_POST["recaptcha_challenge_field"],
  1333.                                             $_POST["recaptcha_response_field"]);
  1334.  
  1335.                                     if (!$resp->is_valid) {
  1336.                                         $field["failed_validation"] = true;
  1337.                                         $field["validation_message"] = empty($field["errorMessage"]) ? __("The reCAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  1338.                                     }
  1339.                             }
  1340.                         break;
  1341.  
  1342.                         case "fileupload" :
  1343.                         case "post_image" :
  1344.                             $info = pathinfo($_FILES["input_" . $field["id"]]["name"]);
  1345.                             $allowedExtensions = self::clean_extensions(explode(",", strtolower($field["allowedExtensions"])));
  1346.                             $extension = strtolower(rgget("extension",$info));
  1347.  
  1348.                             if(empty($field["allowedExtensions"]) && in_array($extension, array("php", "asp", "exe", "com", "htaccess"))){
  1349.                                 $field["failed_validation"] = true;
  1350.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("The uploaded file type is not allowed.", "gravityforms")  : $field["errorMessage"];
  1351.                             }
  1352.                             else if(!empty($field["allowedExtensions"]) && !empty($info["basename"]) && !in_array($extension, $allowedExtensions)){
  1353.                                 $field["failed_validation"] = true;
  1354.                                 $field["validation_message"] = empty($field["errorMessage"]) ? sprintf(__("The uploaded file type is not allowed. Must be one of the following: %s", "gravityforms"), strtolower($field["allowedExtensions"]) )  : $field["errorMessage"];
  1355.                             }
  1356.                         break;
  1357.  
  1358.                         case "calculation" :
  1359.                         case "singleproduct" :
  1360.                         case "hiddenproduct" :
  1361.                             $quantity_id = $field["id"] . ".3";
  1362.                             $quantity = rgget($quantity_id, $value);
  1363.  
  1364.                             if($field["isRequired"] && rgblank($quantity) && !rgar($field, "disableQuantity") ){
  1365.                                 $field["failed_validation"] = true;
  1366.                                 $field["validation_message"] = rgempty("errorMessage", $field) ? __("This field is required.", "gravityforms") : rgar($field, "errorMessage");
  1367.                             }
  1368.                             else if(!empty($quantity) && (!is_numeric($quantity) || intval($quantity) != floatval($quantity)) ) {
  1369.                                 $field["failed_validation"] = true;
  1370.                                 $field["validation_message"] = __("Please enter a valid quantity", "gravityforms");
  1371.                             }
  1372.  
  1373.                         break;
  1374.  
  1375.                         case "radio" :
  1376.  
  1377.                             if(rgar($field, 'enableOtherChoice') && $value == 'gf_other_choice')
  1378.                                 $value = rgpost("input_{$field['id']}_other");
  1379.  
  1380.                             if($field["isRequired"] && rgar($field, 'enableOtherChoice') && $value == GFCommon::get_other_choice_value()) {
  1381.                                 $field["failed_validation"] = true;
  1382.                                 $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  1383.                             }
  1384.  
  1385.                         break;
  1386.                     }
  1387.                 }
  1388.             }
  1389.  
  1390.             $custom_validation_result = apply_filters("gform_field_validation", array("is_valid"=> rgar($field, "failed_validation") ? false : true, "message"=>rgar($field, "validation_message")), $value, $form, $field);
  1391.             $custom_validation_result = apply_filters("gform_field_validation_{$form["id"]}", $custom_validation_result, $value, $form, $field);
  1392.             $custom_validation_result = apply_filters("gform_field_validation_{$form["id"]}_{$field["id"]}", $custom_validation_result, $value, $form, $field);
  1393.  
  1394.             $field["failed_validation"] = rgar($custom_validation_result, "is_valid") ? false : true;
  1395.             $field["validation_message"] = rgar($custom_validation_result, "message");
  1396.         }
  1397.  
  1398.         $is_valid = true;
  1399.         foreach($form["fields"] as $f){
  1400.             if(rgar($f,"failed_validation")){
  1401.                 $is_valid = false;
  1402.                 break;
  1403.             }
  1404.         }
  1405.  
  1406.         $validation_result = apply_filters("gform_validation_{$form["id"]}", apply_filters("gform_validation", array("is_valid" => $is_valid, "form" => $form)) );
  1407.         $is_valid = $validation_result["is_valid"];
  1408.         $form = $validation_result["form"];
  1409.  
  1410.         return $is_valid;
  1411.     }
  1412.  
  1413.     public static function failed_state_validation($form_id, $field, $value){
  1414.  
  1415.         global $_gf_state;
  1416.  
  1417.         //if field can be populated dynamically, disable state validation
  1418.         if(rgar($field,"allowsPrepopulate")) {
  1419.             return false;
  1420.         } else if(!GFCommon::is_product_field($field["type"] && $field["type"] != "donation")) {
  1421.             return false;
  1422.         } else if (!in_array($field["inputType"], array("singleshipping", "singleproduct", "hiddenproduct", "checkbox", "radio", "select"))) {
  1423.             return false;
  1424.         }
  1425.  
  1426.         if(!isset($_gf_state)){
  1427.             $state = unserialize(base64_decode($_POST["state_{$form_id}"]));
  1428.  
  1429.             if(!$state || sizeof($state) != 2)
  1430.                 return true;
  1431.  
  1432.             //making sure state wasn't tampered with by validating checksum
  1433.             $checksum = wp_hash(crc32($state[0]));
  1434.  
  1435.             if($checksum != $state[1]){
  1436.                 return true;
  1437.             }
  1438.  
  1439.             $_gf_state = unserialize($state[0]);
  1440.         }
  1441.  
  1442.         if(!is_array($value)){
  1443.             $value = array($field["id"] => $value);
  1444.         }
  1445.  
  1446.         foreach($value as $key => $input_value){
  1447.             $state = isset($_gf_state[$key]) ? $_gf_state[$key] : false;
  1448.  
  1449.             //converting price to a number for single product fields and single shipping fields
  1450.             if( (in_array($field["inputType"], array("singleproduct", "hiddenproduct")) && $key == $field["id"] . ".2") || $field["inputType"] == "singleshipping")
  1451.                 $input_value = GFCommon::to_number($input_value);
  1452.  
  1453.             $hash = wp_hash($input_value);
  1454.  
  1455.             if(strlen($input_value) > 0 && $state !== false && ((is_array($state) && !in_array($hash, $state)) || (!is_array($state) && $hash != $state)) ){
  1456.                 return true;
  1457.             }
  1458.         }
  1459.         return false;
  1460.     }
  1461.  
  1462.     public static function enqueue_scripts(){
  1463.         global $wp_query;
  1464.         if(isset($wp_query->posts) && is_array($wp_query->posts)){
  1465.             foreach($wp_query->posts as $post){
  1466.                 $forms = self::get_embedded_forms($post->post_content, $ajax);
  1467.                 foreach($forms as $form){
  1468.                     self::enqueue_form_scripts($form, $ajax);
  1469.                 }
  1470.             }
  1471.         }
  1472.     }
  1473.  
  1474.     public static function get_embedded_forms($post_content, &$ajax){
  1475.         $forms = array();
  1476.         if(preg_match_all('/\[gravityform +.*?((id=.+?)|(name=.+?))\]/is', $post_content, $matches, PREG_SET_ORDER)){
  1477.             $ajax = false;
  1478.             foreach($matches as $match){
  1479.                 //parsing shortcode attributes
  1480.                 $attr = shortcode_parse_atts($match[1]);
  1481.                 $form_id = $attr["id"];
  1482.                 if(!is_numeric($form_id))
  1483.                     $form_id = RGFormsModel::get_form_id($attr["name"]);
  1484.  
  1485.                 $forms[] = RGFormsModel::get_form_meta($form_id);
  1486.                 $ajax = isset($attr["ajax"]) && strtolower(substr($attr["ajax"],0, 4)) == "true";
  1487.             }
  1488.         }
  1489.         return $forms;
  1490.     }
  1491.  
  1492.     public static function enqueue_form_scripts($form, $ajax=false){
  1493.         if(!get_option('rg_gforms_disable_css')){
  1494.             wp_enqueue_style("gforms_css", GFCommon::get_base_url() . "/css/forms.css", null, GFCommon::$version);
  1495.         }
  1496.  
  1497.         if(self::has_price_field($form) || self::has_password_strength($form) || GFCommon::has_list_field($form) || GFCommon::has_credit_card_field($form) || self::has_conditional_logic($form)){
  1498.             wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1499.         }
  1500.  
  1501.         if(self::has_conditional_logic($form)){
  1502.             wp_enqueue_script("gforms_conditional_logic_lib", GFCommon::get_base_url() . "/js/conditional_logic.js", array("jquery", "gforms_gravityforms"), GFCommon::$version);
  1503.         }
  1504.  
  1505.         if(self::has_date_field($form)){
  1506.             wp_enqueue_script("gforms_ui_datepicker", GFCommon::get_base_url() . "/js/jquery-ui/ui.datepicker.js", array("jquery"), GFCommon::$version, true);
  1507.             wp_enqueue_script("gforms_datepicker", GFCommon::get_base_url() . "/js/datepicker.js", array("gforms_ui_datepicker"), GFCommon::$version, true);
  1508.         }
  1509.  
  1510.         if(self::has_price_field($form) || self::has_password_strength($form) || GFCommon::has_list_field($form) || GFCommon::has_credit_card_field($form) || self::has_calculation_field($form)){
  1511.             wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1512.         }
  1513.  
  1514.         if(self::has_enhanced_dropdown($form) || self::has_pages($form) || self::has_fileupload_field($form)){
  1515.             wp_enqueue_script("gforms_json", GFCommon::get_base_url() . "/js/jquery.json-1.3.js", array("jquery"), GFCommon::$version, true);
  1516.             wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("gforms_json"), GFCommon::$version, false);
  1517.         }
  1518.  
  1519.         if(self::has_character_counter($form)){
  1520.             wp_enqueue_script("gforms_character_counter", GFCommon::get_base_url() . "/js/jquery.textareaCounter.plugin.js", array("jquery"), GFCommon::$version, false);
  1521.         }
  1522.  
  1523.         if(self::has_input_mask($form)){
  1524.             wp_enqueue_script("gforms_input_mask", GFCommon::get_base_url() . "/js/jquery.maskedinput-1.3.min.js", array("jquery"), GFCommon::$version, true);
  1525.         }
  1526.  
  1527.         if(self::has_enhanced_dropdown($form)){
  1528.             wp_enqueue_script("gforms_chosen", GFCommon::get_base_url() . "/js/chosen.jquery.min.js", array("jquery"), GFCommon::$version, false);
  1529.         }
  1530.  
  1531.         do_action("gform_enqueue_scripts", $form, $ajax);
  1532.         do_action("gform_enqueue_scripts_{$form["id"]}", $form, $ajax);
  1533.  
  1534.         // enqueue jQuery every time form is displayed to allow "gform_post_render" js hook
  1535.         // to be available to users even when GF is not using it
  1536.         wp_enqueue_script("jquery");
  1537.  
  1538.     }
  1539.  
  1540.     private static $printed_scripts = array();
  1541.  
  1542.     public static function print_form_scripts($form, $ajax){
  1543.  
  1544.         if(!get_option('rg_gforms_disable_css')){
  1545.             if(!wp_style_is("gforms_css", "queue")){
  1546.                 wp_enqueue_style("gforms_css", GFCommon::get_base_url() . "/css/forms.css", GFCommon::$version);
  1547.                 wp_print_styles(array("gforms_css"));
  1548.             }
  1549.         }
  1550.  
  1551.         if( (self::has_enhanced_dropdown($form) || self::has_price_field($form) || self::has_password_strength($form) || self::has_pages($form) || self::has_password_strength($form) || GFCommon::has_list_field($form) || GFCommon::has_credit_card_field($form)) && !wp_script_is("gforms_gravityforms", "queue")){
  1552.             wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1553.             wp_print_scripts(array("gforms_gravityforms"));
  1554.         }
  1555.  
  1556.         if(self::has_conditional_logic($form) && !wp_script_is("gforms_conditional_logic_lib", "queue")){
  1557.             wp_enqueue_script("gforms_conditional_logic_lib", GFCommon::get_base_url() . "/js/conditional_logic.js", array("jquery", "gforms_gravityforms"), GFCommon::$version);
  1558.             wp_print_scripts(array("gforms_conditional_logic_lib"));
  1559.         }
  1560.  
  1561.         if(self::has_date_field($form) && !wp_script_is("gforms_datepicker", "queue")){
  1562.             wp_enqueue_script("gforms_ui_datepicker", GFCommon::get_base_url() . "/js/jquery-ui/ui.datepicker.js", array("jquery"), GFCommon::$version, true);
  1563.             wp_enqueue_script("gforms_datepicker", GFCommon::get_base_url() . "/js/datepicker.js", array("gforms_ui_datepicker"), GFCommon::$version, true);
  1564.             wp_print_scripts(array("gforms_datepicker"));
  1565.         }
  1566.  
  1567.         if(self::has_pages($form) && !wp_script_is("gforms_json", "queue")){
  1568.             wp_enqueue_script("gforms_json", GFCommon::get_base_url() . "/js/jquery.json-1.3.js", array("jquery"), GFCommon::$version, true);
  1569.             wp_print_scripts(array("gforms_json"));
  1570.         }
  1571.  
  1572.         if( (self::has_enhanced_dropdown($form) || self::has_price_field($form) || self::has_password_strength($form) || self::has_pages($form) || self::has_password_strength($form) || GFCommon::has_list_field($form) || GFCommon::has_credit_card_field($form)) || self::has_calculation_field($form) && !wp_script_is("gforms_gravityforms", "queue")){
  1573.             wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1574.             wp_print_scripts(array("gforms_gravityforms"));
  1575.         }
  1576.  
  1577.         if(self::has_character_counter($form) && !wp_script_is("gforms_character_counter", "queue")){
  1578.             wp_enqueue_script("gforms_character_counter", GFCommon::get_base_url() . "/js/jquery.textareaCounter.plugin.js", array("jquery"), GFCommon::$version, false);
  1579.             wp_print_scripts(array("gforms_character_counter"));
  1580.         }
  1581.  
  1582.         if(self::has_input_mask($form) && !wp_script_is("gforms_input_mask", "queue")){
  1583.             wp_enqueue_script("gforms_input_mask", GFCommon::get_base_url() . "/js/jquery.maskedinput-1.3.min.js", array("jquery"), GFCommon::$version, true);
  1584.             wp_print_scripts(array("gforms_input_mask"));
  1585.         }
  1586.  
  1587.         if(self::has_enhanced_dropdown($form)&& !wp_script_is("gforms_chosen", "queue")){
  1588.             wp_enqueue_script("gforms_chosen", GFCommon::get_base_url() . "/js/chosen.jquery.min.js", array("jquery"), GFCommon::$version, false);
  1589.             wp_print_scripts(array("gforms_chosen"));
  1590.         }
  1591.  
  1592.         if(!wp_script_is("jquery", "queue")){
  1593.             wp_print_scripts(array("jquery"));
  1594.         }
  1595.  
  1596.         if(wp_script_is("gforms_gravityforms")) {
  1597.             require_once(GFCommon::get_base_path() . '/currency.php');
  1598.             echo '<script type="text/javascript"> var gf_global = { gf_currency_config: ' . GFCommon::json_encode(RGCurrency::get_currency(GFCommon::get_currency()))  . ' }; </script>';
  1599.         }
  1600.  
  1601.     }
  1602.  
  1603.     private static function has_conditional_logic($form){
  1604.         if(empty($form))
  1605.             return false;
  1606.  
  1607.         if(isset($form["button"]["conditionalLogic"]))
  1608.             return true;
  1609.  
  1610.         foreach(rgar($form,"fields") as $field){
  1611.             if(!empty($field["conditionalLogic"])){
  1612.                 return true;
  1613.             }
  1614.             else if(isset($field["nextButton"]) && !empty($field["nextButton"]["conditionalLogic"])){
  1615.                 return true;
  1616.             }
  1617.         }
  1618.         return false;
  1619.     }
  1620.  
  1621.     private static function get_conditional_logic($form, $field_values = array()){
  1622.         $logics = "";
  1623.         $dependents = "";
  1624.         $fields_with_logic = array();
  1625.         $default_values = array();
  1626.  
  1627.         foreach($form["fields"] as $field){
  1628.  
  1629.             //use section's logic if one exists
  1630.             $section = RGFormsModel::get_section($form, $field["id"]);
  1631.             $section_logic = !empty($section) ? rgar($section,"conditionalLogic") : null;
  1632.  
  1633.             $field_logic = $field["type"] != "page" ? RGForms::get("conditionalLogic", $field) : null; //page break conditional logic will be handled during the next button click
  1634.  
  1635.             $next_button_logic = isset($field["nextButton"]) && isset($field["nextButton"]["conditionalLogic"]) ? $field["nextButton"]["conditionalLogic"] : null;
  1636.  
  1637.             if(!empty($field_logic) || !empty($next_button_logic)){
  1638.  
  1639.                 $field_section_logic = array("field" => $field_logic, "nextButton" => $next_button_logic, "section" => $section_logic);
  1640.  
  1641.                 $logics .= $field["id"] . ": " . GFCommon::json_encode($field_section_logic) . ",";
  1642.  
  1643.                 $fields_with_logic[] = $field["id"];
  1644.  
  1645.                 $peers = $field["type"] == "section" ? GFCommon::get_section_fields($form, $field["id"]) : array($field);
  1646.                 $peer_ids = array();
  1647.  
  1648.                 foreach ($peers as $peer)
  1649.                     $peer_ids[] = $peer["id"];
  1650.  
  1651.                 $dependents .= $field["id"] . ": " . GFCommon::json_encode($peer_ids) . ",";
  1652.             }
  1653.  
  1654.             //-- Saving default values so that they can be restored when toggling conditional logic ---
  1655.             $field_val = "";
  1656.             $input_type = RGFormsModel::get_input_type($field);
  1657.  
  1658.             //get parameter value if pre-populate is enabled
  1659.             if(rgar($field, "allowsPrepopulate")){
  1660.                 if(is_array(rgar($field, "inputs"))){
  1661.                     $field_val = array();
  1662.                     foreach($field["inputs"] as $input){
  1663.                         $field_val["input_{$input["id"]}"] = RGFormsModel::get_parameter_value(rgar($input, "name"), $field, $field_values);
  1664.                     }
  1665.                 }
  1666.                 else if($input_type == "time"){
  1667.                     $parameter_val = RGFormsModel::get_parameter_value(rgar($field, "inputName"), $field, $field_values);
  1668.                     if(!empty($parameter_val) && preg_match('/^(\d*):(\d*) ?(.*)$/', $parameter_val, $matches)){
  1669.                         $field_val = array();
  1670.                         $field_val[] = esc_attr($matches[1]); //hour
  1671.                         $field_val[] = esc_attr($matches[2]); //minute
  1672.                         $field_val[] = rgar($matches,3); //am or pm
  1673.                     }
  1674.                 }
  1675.                 else if($input_type == "list"){
  1676.                     $parameter_val = RGFormsModel::get_parameter_value(rgar($field, "inputName"), $field, $field_values);
  1677.                     $field_val = explode(",", str_replace("|", ",", $parameter_val));
  1678.                 }
  1679.                 else {
  1680.                     $field_val = RGFormsModel::get_parameter_value(rgar($field, "inputName"), $field, $field_values);
  1681.                 }
  1682.             }
  1683.  
  1684.             //use default value if pre-populated value is empty
  1685.             $field_val = self::default_if_empty($field, $field_val);
  1686.  
  1687.             if(is_array(rgar($field, "choices")) && $input_type != "list"){
  1688.  
  1689.                 //radio buttons start at 0 and checkboxes start at 1
  1690.                 $choice_index = $input_type == "radio" ? 0 : 1;
  1691.  
  1692.                 foreach($field["choices"] as $choice){
  1693.  
  1694.                     if(rgar($choice,"isSelected") && $input_type == "select"){
  1695.                         $val = isset($choice["price"]) ? $choice["value"] . "|" . GFCommon::to_number($choice["price"]) :  $choice["value"];
  1696.                         $default_values[$field["id"]] = $val;
  1697.                     }
  1698.                     else if(rgar($choice,"isSelected")){
  1699.                         if(!isset($default_values[$field["id"]]))
  1700.                             $default_values[$field["id"]] = array();
  1701.  
  1702.                         $default_values[$field["id"]][] = "choice_{$field["id"]}_{$choice_index}";
  1703.                     }
  1704.                     $choice_index++;
  1705.                 }
  1706.             }
  1707.             else if(!empty($field_val)){
  1708.                 $default_values[$field["id"]] = $field_val;
  1709.             }
  1710.         }
  1711.  
  1712.         $button_conditional_script = "";
  1713.  
  1714.         //adding form button conditional logic if enabled
  1715.         if(isset($form["button"]["conditionalLogic"])){
  1716.             $logics .= "0: " . GFCommon::json_encode(array("field"=>$form["button"]["conditionalLogic"], "section" => null)) . ",";
  1717.             $dependents .= "0: " . GFCommon::json_encode(array(0)) . ",";
  1718.             $fields_with_logic[] = 0;
  1719.  
  1720.             $button_conditional_script = "jQuery('#gform_{$form['id']}').submit(" .
  1721.                                             "function(event, isButtonPress){" .
  1722.                                             "    var visibleButton = jQuery('.gform_next_button:visible, .gform_button:visible, .gform_image_button:visible');" .
  1723.                                             "    return visibleButton.length > 0 || isButtonPress == true;" .
  1724.                                             "}" .
  1725.                                         ");";
  1726.         }
  1727.  
  1728.         if(!empty($logics))
  1729.             $logics = substr($logics, 0, strlen($logics) - 1); //removing last comma;
  1730.  
  1731.         if(!empty($dependents))
  1732.             $dependents = substr($dependents, 0, strlen($dependents) - 1); //removing last comma;
  1733.  
  1734.         $animation = rgar($form,"enableAnimation") ? "1" : "0";
  1735.         global $wp_locale;
  1736.         $number_format = $wp_locale->number_format['decimal_point'] == "," ? "decimal_comma" : "decimal_dot";
  1737.  
  1738.         $str = "if(window['jQuery']){" .
  1739.  
  1740.                     "if(!window['gf_form_conditional_logic'])" .
  1741.                         "window['gf_form_conditional_logic'] = new Array();" .
  1742.                     "window['gf_form_conditional_logic'][{$form['id']}] = {'logic' : {" . $logics . " }, 'dependents' : {" . $dependents . " }, 'animation' : " . $animation . " , 'defaults' : " . json_encode($default_values) . " }; ".
  1743.                     "if(!window['gf_number_format'])" .
  1744.                         "window['gf_number_format'] = '" . $number_format . "';" .
  1745.  
  1746.                     "jQuery(document).ready(function(){" .
  1747.                         "gf_apply_rules({$form['id']}, " . json_encode($fields_with_logic) . ", true);" .
  1748.                         "jQuery('#gform_wrapper_{$form['id']}').show();" .
  1749.                         "jQuery(document).trigger('gform_post_conditional_logic', [{$form['id']}, null, true]);" .
  1750.                         $button_conditional_script .
  1751.  
  1752.                     "} );" .
  1753.  
  1754.                 "} ";
  1755.  
  1756.         return $str;
  1757.     }
  1758.  
  1759.  
  1760.     /**
  1761.     * Enqueue and retrieve all inline scripts that should be executed when the form is rendered.
  1762.     * Use add_init_script() function to enqueue scripts.
  1763.     *
  1764.     * @param mixed $form
  1765.     */
  1766.     private static function register_form_init_scripts($form, $field_values = array()) {
  1767.  
  1768.         // adding conditional logic script if conditional logic is configured for this form.
  1769.         // get_conditional_logic also adds the chosen script for the enhanced dropdown option.
  1770.         // if this form does not have conditional logic, add chosen script separately
  1771.         if(self::has_conditional_logic($form)){
  1772.             self::add_init_script($form["id"], "conditional_logic", self::ON_PAGE_RENDER, self::get_conditional_logic($form, $field_values));
  1773.         }
  1774.  
  1775.         //adding currency config if there are any product fields in the form
  1776.         if(self::has_price_field($form)){
  1777.             self::add_init_script($form["id"], "pricing", self::ON_PAGE_RENDER, self::get_pricing_init_script($form));
  1778.         }
  1779.  
  1780.         if(self::has_password_strength($form)){
  1781.             $password_script = self::get_password_strength_init_script($form);
  1782.             self::add_init_script($form["id"], "password", self::ON_PAGE_RENDER, $password_script);
  1783.         }
  1784.  
  1785.         if(self::has_enhanced_dropdown($form) ){
  1786.             $chosen_script = self::get_chosen_init_script($form);
  1787.             self::add_init_script($form["id"], "chosen", self::ON_PAGE_RENDER, $chosen_script);
  1788.             self::add_init_script($form["id"], "chosen", self::ON_CONDITIONAL_LOGIC, $chosen_script);
  1789.         }
  1790.  
  1791.         if(GFCommon::has_credit_card_field($form)) {
  1792.             self::add_init_script($form["id"], "credit_card", self::ON_PAGE_RENDER, self::get_credit_card_init_script($form));
  1793.         }
  1794.  
  1795.         if(self::has_character_counter($form)){
  1796.             self::add_init_script($form['id'], 'character_counter', self::ON_PAGE_RENDER, self::get_counter_init_script($form));
  1797.         }
  1798.  
  1799.         if(self::has_input_mask($form)) {
  1800.             self::add_init_script($form['id'], 'input_mask', self::ON_PAGE_RENDER, self::get_input_mask_init_script($form));
  1801.         }
  1802.  
  1803.         if(self::has_calculation_field($form)) {
  1804.             self::add_init_script($form['id'], 'calculation', self::ON_PAGE_RENDER, self::get_calculations_init_script($form));
  1805.         }
  1806.  
  1807.     }
  1808.  
  1809.     public static function get_form_init_scripts($form) {
  1810.  
  1811.         $script_string = '';
  1812.  
  1813.         // temporary solution for output gf_global obj until wp min version raised to 3.3
  1814.         if(wp_script_is("gforms_gravityforms")) {
  1815.             require_once(GFCommon::get_base_path() . '/currency.php');
  1816.             $gf_global_script = "if(typeof gf_global == 'undefined') var gf_global = {gf_currency_config: " . json_encode(RGCurrency::get_currency(GFCommon::get_currency())) . " };";
  1817.         }
  1818.  
  1819.         /* rendering initialization scripts */
  1820.         $init_scripts = rgar(self::$init_scripts, $form["id"]);
  1821.  
  1822.         if(!empty($init_scripts)){
  1823.             $script_string =
  1824.             "<script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . " ";
  1825.  
  1826.             $script_string .= isset($gf_global_script) ? $gf_global_script : '';
  1827.  
  1828.             $script_string .=
  1829.                 "jQuery(document).bind('gform_post_render', function(event, formId, currentPage){" .
  1830.                     "if(formId == {$form['id']}) {";
  1831.  
  1832.                     foreach($init_scripts as $init_script){
  1833.                         if($init_script["location"] == self::ON_PAGE_RENDER){
  1834.                             $script_string .= $init_script["script"];
  1835.                         }
  1836.                     }
  1837.  
  1838.             $script_string .=
  1839.                     "} ". //keep the space. needed to prevent plugins from replacing }} with ]}
  1840.                 "} );".
  1841.  
  1842.                 "jQuery(document).bind('gform_post_conditional_logic', function(event, formId, fields, isInit){" ;
  1843.                     foreach($init_scripts as $init_script){
  1844.                         if($init_script["location"] == self::ON_CONDITIONAL_LOGIC){
  1845.                             $script_string .= $init_script["script"];
  1846.                         }
  1847.                     }
  1848.  
  1849.             $script_string .=
  1850.  
  1851.                 "} );". apply_filters("gform_cdata_close", "") . "</script>";
  1852.         }
  1853.  
  1854.         return $script_string;
  1855.     }
  1856.  
  1857.     public static function get_chosen_init_script($form){
  1858.         $chosen_fields = array();
  1859.         foreach($form["fields"] as $field){
  1860.             if(rgar($field, "enableEnhancedUI"))
  1861.                 $chosen_fields[] = "#input_{$form["id"]}_{$field["id"]}";
  1862.         }
  1863.         return "gformInitChosenFields('" . implode(",", $chosen_fields) . "','" . esc_attr(apply_filters("gform_dropdown_no_results_text_{$form["id"]}", apply_filters("gform_dropdown_no_results_text", __("No results matched", "gravityforms"), $form["id"]), $form["id"])) . "');";
  1864.     }
  1865.  
  1866.     public static function get_counter_init_script($form){
  1867.  
  1868.         $script = "";
  1869.         foreach($form["fields"] as $field){
  1870.             $max_length = rgar($field,"maxLength");
  1871.             $field_id = "input_{$form["id"]}_{$field["id"]}";
  1872.             if(!empty($max_length) && !rgar($field,"adminOnly"))
  1873.             {
  1874.                 $field_script =
  1875.                         //******  make this callable only once ***********
  1876.                         "jQuery('#{$field_id}').textareaCount(" .
  1877.                         "    {" .
  1878.                         "    'maxCharacterSize': {$max_length}," .
  1879.                         "    'originalStyle': 'ginput_counter'," .
  1880.                         "    'displayFormat' : '#input " . __("of", "gravityforms") . " #max " . __("max characters", "gravityforms") . "'" .
  1881.                         "    } );";
  1882.  
  1883.                 $script .= apply_filters("gform_counter_script_{$form["id"]}", apply_filters("gform_counter_script", $field_script, $form["id"], $field_id, $max_length), $form["id"], $field_id, $max_length);
  1884.             }
  1885.         }
  1886.         return $script;
  1887.     }
  1888.  
  1889.     public static function get_credit_card_init_script($form) {
  1890.  
  1891.         $script = "";
  1892.  
  1893.         foreach($form["fields"] as $field){
  1894.  
  1895.             if($field['type'] != 'creditcard')
  1896.                 continue;
  1897.  
  1898.             $field_id = "input_{$form["id"]}_{$field["id"]}";
  1899.             $field_script = "jQuery(document).ready(function(){ { gformMatchCard(\"{$field_id}_1\"); } } );";
  1900.  
  1901.             if(rgar($field, "forceSSL") && !GFCommon::is_ssl() && !GFCommon::is_preview())
  1902.                 $field_script = "document.location.href='" . esc_js( RGFormsModel::get_current_page_url(true) ) . "';";
  1903.  
  1904.             $script .= $field_script;
  1905.         }
  1906.  
  1907.         $card_rules = self::get_credit_card_rules();
  1908.         $script = "if(!window['gf_cc_rules']){window['gf_cc_rules'] = new Array(); } window['gf_cc_rules'] = " . GFCommon::json_encode($card_rules) . "; $script";
  1909.  
  1910.         return $script;
  1911.     }
  1912.  
  1913.     public static function get_pricing_init_script($form) {
  1914.  
  1915.         if(!class_exists("RGCurrency"))
  1916.             require_once("currency.php");
  1917.  
  1918.         return "if(window[\"gformInitPriceFields\"]) jQuery(document).ready(function(){gformInitPriceFields();} );";
  1919.     }
  1920.  
  1921.     public static function get_password_strength_init_script($form) {
  1922.  
  1923.         $field_script = "if(!window['gf_text']){window['gf_text'] = new Array();} window['gf_text']['password_blank'] = '" . __("Strength indicator", "gravityforms") . "'; window['gf_text']['password_mismatch'] = '" . __("Mismatch", "gravityforms") . "';window['gf_text']['password_bad'] = '" . __("Bad", "gravityforms") . "'; window['gf_text']['password_short'] = '" . __("Short", "gravityforms") . "'; window['gf_text']['password_good'] = '" . __("Good", "gravityforms") . "'; window['gf_text']['password_strong'] = '" . __("Strong", "gravityforms") . "';";
  1924.  
  1925.         foreach($form['fields'] as $field) {
  1926.             if($field['type'] == 'password' && rgar($field, 'passwordStrengthEnabled')) {
  1927.                 $field_id = "input_{$form["id"]}_{$field["id"]}";
  1928.                 $field_script .= "gformShowPasswordStrength(\"$field_id\");";
  1929.             }
  1930.         }
  1931.  
  1932.         return $field_script;
  1933.     }
  1934.  
  1935.     public static function get_input_mask_init_script($form) {
  1936.  
  1937.         $script_str = '';
  1938.  
  1939.         foreach($form['fields'] as $field) {
  1940.  
  1941.             if(!rgar($field, 'inputMask') || !rgar($field, 'inputMaskValue'))
  1942.                 continue;
  1943.  
  1944.             $mask = rgar($field, 'inputMaskValue');
  1945.             $script = "jQuery('#input_{$form['id']}_{$field['id']}').mask('{$mask}').bind('keypress', function(e){if(e.which == 13){jQuery(this).blur();} } );";
  1946.  
  1947.             $script_str .= apply_filters("gform_input_mask_script_{$form['id']}", apply_filters("gform_input_mask_script", $script, $form['id'], $field['id'], $mask), $form['id'], $field['id'], $mask);
  1948.         }
  1949.  
  1950.         return $script_str;
  1951.     }
  1952.  
  1953.     public static function get_calculations_init_script($form) {
  1954.         require_once(GFCommon::get_base_path() . '/currency.php');
  1955.  
  1956.         $formula_fields = array();
  1957.  
  1958.         foreach($form['fields'] as $field) {
  1959.  
  1960.             if(!rgar($field, 'enableCalculation') || !rgar($field, 'calculationFormula'))
  1961.                 continue;
  1962.  
  1963.             $formula_fields[] = array('field_id' => $field['id'], 'formula' => rgar($field, 'calculationFormula'), 'rounding' => rgar($field, 'calculationRounding'), 'numberFormat' => rgar($field, 'numberFormat') );
  1964.  
  1965.         }
  1966.  
  1967.         if(empty($formula_fields))
  1968.             return '';
  1969.  
  1970.         $script = 'new GFCalc(' . $form['id'] . ', ' . GFCommon::json_encode($formula_fields) . ');';
  1971.  
  1972.         return $script;
  1973.     }
  1974.  
  1975.  
  1976.  
  1977.  
  1978.     private static function has_date_field($form){
  1979.         if(is_array($form["fields"])){
  1980.             foreach($form["fields"] as $field){
  1981.  
  1982.                 if(RGFormsModel::get_input_type($field) == "date")
  1983.                     return true;
  1984.             }
  1985.         }
  1986.         return false;
  1987.     }
  1988.  
  1989.     private static function has_price_field($form){
  1990.         $price_fields = GFCommon::get_fields_by_type($form, array("product", "donation"));
  1991.         return !empty($price_fields);
  1992.     }
  1993.  
  1994.     private static function has_fileupload_field($form){
  1995.         $fileupload_fields = GFCommon::get_fields_by_type($form, array("fileupload", "post_image"));
  1996.         if(is_array($form["fields"])){
  1997.             foreach($form["fields"] as $field){
  1998.                 $input_type = RGFormsModel::get_input_type($field);
  1999.                 if(in_array($input_type, array("fileupload", "post_image")))
  2000.                     return true;
  2001.             }
  2002.         }
  2003.         return false;
  2004.     }
  2005.  
  2006.     private static function has_recaptcha_field($form){
  2007.         if(is_array($form["fields"])){
  2008.             foreach($form["fields"] as $field){
  2009.                 if(($field["type"] == "captcha" || $field["inputType"] == "captcha") && !in_array($field["captchaType"], array("simple_captcha", "math")))
  2010.                     return true;
  2011.             }
  2012.         }
  2013.         return false;
  2014.     }
  2015.  
  2016.     public static function has_input_mask($form, $field = false){
  2017.  
  2018.         if($field) {
  2019.             if(self::has_field_input_mask($field))
  2020.                 return true;
  2021.         } else {
  2022.  
  2023.             if(!is_array($form["fields"]))
  2024.                 return false;
  2025.  
  2026.             foreach($form["fields"] as $field){
  2027.                 if(rgar($field, "inputMask") && rgar($field, "inputMaskValue") && !rgar($field, "enablePasswordInput"))
  2028.                     return true;
  2029.             }
  2030.  
  2031.         }
  2032.  
  2033.         return false;
  2034.     }
  2035.  
  2036.     public static function has_field_input_mask($field){
  2037.         if(rgar($field, "inputMask") && rgar($field, "inputMaskValue") && !rgar($field, "enablePasswordInput"))
  2038.             return true;
  2039.  
  2040.         return false;
  2041.     }
  2042.  
  2043.     public static function has_calculation_field($form) {
  2044.  
  2045.         if(!is_array($form["fields"]))
  2046.             return false;
  2047.  
  2048.         foreach($form['fields'] as $field) {
  2049.             if(GFCommon::has_field_calculation($field))
  2050.                 return true;
  2051.         }
  2052.         return false;
  2053.     }
  2054.  
  2055.     //Getting all fields that have a rule based on the specified field id
  2056.     private static function get_conditional_logic_fields($form, $fieldId){
  2057.         $fields = array();
  2058.  
  2059.         //adding submit button field if enabled
  2060.         if(isset($form["button"]["conditionalLogic"])){
  2061.             $fields[] = 0;
  2062.         }
  2063.  
  2064.         foreach($form["fields"] as $field){
  2065.  
  2066.             if($field["type"] != "page" && !empty($field["conditionalLogic"])){
  2067.                 foreach($field["conditionalLogic"]["rules"] as $rule){
  2068.                     if($rule["fieldId"] == $fieldId){
  2069.                         $fields[] = floatval($field["id"]);
  2070.  
  2071.                         //if field is a section, add all fields in the section that have conditional logic (to support nesting)
  2072.                         if($field["type"] == "section"){
  2073.                             $section_fields = GFCommon::get_section_fields($form, $field["id"]);
  2074.                             foreach($section_fields as $section_field)
  2075.                                 if(!empty($section_field["conditionalLogic"]))
  2076.                                     $fields[] = floatval($section_field["id"]);
  2077.                         }
  2078.                         break;
  2079.                     }
  2080.                 }
  2081.             }
  2082.             //adding fields with next button logic
  2083.             if(!empty($field["nextButton"]["conditionalLogic"])){
  2084.                 foreach($field["nextButton"]["conditionalLogic"]["rules"] as $rule){
  2085.                     if($rule["fieldId"] == $fieldId && !in_array($fieldId, $fields)){
  2086.                         $fields[] = floatval($field["id"]);
  2087.                         break;
  2088.                     }
  2089.                 }
  2090.             }
  2091.         }
  2092.         return $fields;
  2093.     }
  2094.  
  2095.     public static function get_field($field, $value="", $force_frontend_label = false, $form=null, $field_values=null){
  2096.         $custom_class = IS_ADMIN ? "" : rgget("cssClass", $field);
  2097.  
  2098.         if($field["type"] == "page"){
  2099.             if(IS_ADMIN && RG_CURRENT_VIEW == "entry"){
  2100.                 return; //ignore page breaks in the entry detail page
  2101.             }
  2102.             else if(!IS_ADMIN){
  2103.                 $next_button = self::get_form_button($form["id"], "gform_next_button_{$form["id"]}_{$field["id"]}", $field["nextButton"], __("Next", "gravityforms"), "button gform_next_button", __("Next Page", "gravityforms"), $field["pageNumber"]);
  2104.                 $previous_button = $field["pageNumber"] == 2 ? "" : self::get_form_button($form["id"], "gform_previous_button_{$form["id"]}_{$field["id"]}", $field["previousButton"], __("Previous", "gravityforms"), "button gform_previous_button", __("Previous Page", "gravityforms"), $field["pageNumber"]-2);
  2105.                 $style = self::is_page_active($form["id"], $field["pageNumber"]) ? "" : "style='display:none;'";
  2106.                 $custom_class = !empty($custom_class) ? " {$custom_class}" : "";
  2107.                 $html = "</ul>
  2108.                    </div>
  2109.                    <div class='gform_page_footer'>
  2110.                        {$previous_button} {$next_button}
  2111.                    </div>
  2112.                </div>
  2113.                <div id='gform_page_{$form["id"]}_{$field["pageNumber"]}' class='gform_page{$custom_class}' {$style}>
  2114.                    <div class='gform_page_fields'>
  2115.                        <ul class='gform_fields {$form['labelPlacement']}'>";
  2116.  
  2117.                 return $html;
  2118.             }
  2119.         }
  2120.  
  2121.         if($field["type"] == "post_category") {
  2122.  
  2123.  
  2124.  
  2125.         }
  2126.  
  2127.         if(!IS_ADMIN && rgar($field,"adminOnly"))
  2128.         {
  2129.             if($field["allowsPrepopulate"])
  2130.                 $field["inputType"] = "adminonly_hidden";
  2131.             else
  2132.                 return;
  2133.         }
  2134.  
  2135.         $id = $field["id"];
  2136.         $type = $field["type"];
  2137.         $input_type = RGFormsModel::get_input_type($field);
  2138.  
  2139.         $error_class = rgget("failed_validation", $field) ? "gfield_error" : "";
  2140.         $admin_only_class =  rgget("adminOnly", $field) ? "field_admin_only" : "";
  2141.         $selectable_class = IS_ADMIN ? "selectable" : "";
  2142.         $hidden_class = in_array($input_type, array("hidden", "hiddenproduct")) ? "gform_hidden" : "";
  2143.  
  2144.         $section_class = $field["type"] == "section" ? "gsection" : "";
  2145.         $page_class = $field["type"] == "page" ? "gpage" : "";
  2146.         $html_block_class = $field["type"] == "html" ? "gfield_html" : "";
  2147.         $html_formatted_class = $field["type"] == "html" && !IS_ADMIN && !rgget("disableMargins", $field) ? "gfield_html_formatted" : "";
  2148.         $html_no_follows_desc_class = $field["type"] == "html" && !IS_ADMIN && !self::prev_field_has_description($form, $field["id"]) ? "gfield_no_follows_desc" : "";
  2149.  
  2150.         $calculation_class = RGFormsModel::get_input_type($field) == 'number' && GFCommon::has_field_calculation($field) ? 'gfield_calculation' : '';
  2151.         $calculation_class = RGFormsModel::get_input_type($field) == 'calculation' ? 'gfield_calculation' : '';
  2152.  
  2153.         $product_suffix = "_{$form["id"]}_" . rgget("productField", $field);
  2154.         $option_class = $field["type"] == "option" ? "gfield_price gfield_price{$product_suffix} gfield_option{$product_suffix}" : "";
  2155.         $quantity_class = $field["type"] == "quantity" ? "gfield_price gfield_price{$product_suffix} gfield_quantity{$product_suffix}" : "";
  2156.         $shipping_class = $field["type"] == "shipping" ? "gfield_price gfield_shipping gfield_shipping_{$form["id"]}" : "";
  2157.         $product_class = $field["type"] == "product" ? "gfield_price gfield_price_{$form["id"]}_{$field["id"]} gfield_product_{$form["id"]}_{$field["id"]}" : "";
  2158.         $hidden_product_class = $input_type == "hiddenproduct" ? "gfield_hidden_product" : "";
  2159.         $donation_class = $field["type"] == "donation" ? "gfield_price gfield_price_{$form["id"]}_{$field["id"]} gfield_donation_{$form["id"]}_{$field["id"]}" : "";
  2160.         $required_class = rgar($field, "isRequired") ? "gfield_contains_required" : "";
  2161.         $creditcard_warning_class = $input_type == "creditcard" && !GFCommon::is_ssl() ? "gfield_creditcard_warning" : "";
  2162.  
  2163.         $css_class = "$selectable_class gfield $error_class $section_class $admin_only_class $custom_class $hidden_class $html_block_class $html_formatted_class $html_no_follows_desc_class $option_class $quantity_class $product_class $donation_class $shipping_class $page_class $required_class $hidden_product_class $creditcard_warning_class $calculation_class";
  2164.         $css_class = apply_filters("gform_field_css_class_{$form["id"]}", apply_filters("gform_field_css_class", trim($css_class), $field, $form), $field, $form);
  2165.  
  2166.         $style = !empty($form) && !IS_ADMIN && RGFormsModel::is_field_hidden($form, $field, $field_values) ? "style='display:none;'" : "";
  2167.  
  2168.         $field_id = IS_ADMIN || empty($form) ? "field_$id" : "field_" . $form["id"] . "_$id";
  2169.  
  2170.         return "<li id='$field_id' class='$css_class' $style>" . self::get_field_content($field, $value, $force_frontend_label, $form == null ? 0 : $form["id"]) . "</li>";
  2171.     }
  2172.  
  2173.     private static function prev_field_has_description($form, $field_id){
  2174.         if(!is_array($form["fields"]))
  2175.             return false;
  2176.  
  2177.         $prev = null;
  2178.         foreach($form["fields"] as $field){
  2179.             if($field["id"] == $field_id){
  2180.                 return $prev != null && !empty($prev["description"]);
  2181.             }
  2182.             $prev = $field;
  2183.         }
  2184.         return false;
  2185.     }
  2186.  
  2187.     public static function get_field_content($field, $value="", $force_frontend_label = false, $form_id=0){
  2188.         $id = $field["id"];
  2189.         $size = rgar($field,"size");
  2190.         $validation_message = (rgget("failed_validation", $field) && !empty($field["validation_message"])) ? sprintf("<div class='gfield_description validation_message'>%s</div>", $field["validation_message"]) : "";
  2191.  
  2192.         $duplicate_disabled = array('captcha', 'post_title', 'post_content', 'post_excerpt', 'total', 'shipping', 'creditcard');
  2193.         $duplicate_field_link = !in_array($field['type'], $duplicate_disabled) ? "<a class='field_duplicate_icon' id='gfield_duplicate_$id' title='" . __("click to duplicate this field", "gravityforms") . "' href='#' onclick='StartDuplicateField(this); return false;'>" . __("Duplicate", "gravityforms") . "</a>" : "";
  2194.         $duplicate_field_link = apply_filters("gform_duplicate_field_link", $duplicate_field_link);
  2195.  
  2196.         $delete_field_link = "<a class='field_delete_icon' id='gfield_delete_$id' title='" . __("click to delete this field", "gravityforms") . "' href='#' onclick='StartDeleteField(this); return false;'>" . __("Delete", "gravityforms") . "</a>";
  2197.         $delete_field_link = apply_filters("gform_delete_field_link", $delete_field_link);
  2198.         $field_type_title = GFCommon::get_field_type_title($field["type"]);
  2199.         $admin_buttons = IS_ADMIN ? "<div class='gfield_admin_icons'><div class='gfield_admin_header_title'>{$field_type_title} : " . __("Field ID", "gravityforms") . " {$field["id"]}</div>" . $delete_field_link . $duplicate_field_link . "<a class='field_edit_icon edit_icon_collapsed' title='" . __("click to edit this field", "gravityforms") . "'>" . __("Edit", "gravityforms") . "</a></div>" : "";
  2200.  
  2201.         $field_label = $force_frontend_label ? $field["label"] : GFCommon::get_label($field);
  2202.         if(rgar($field, "inputType") == "singleproduct" && !rgempty($field["id"] . ".1", $value))
  2203.             $field_label = rgar($value, $field["id"] . ".1");
  2204.  
  2205.  
  2206.         $field_id = IS_ADMIN || $form_id == 0 ? "input_$id" : "input_" . $form_id . "_$id";
  2207.  
  2208.         $required_div = IS_ADMIN || rgar($field, "isRequired") ? sprintf("<span class='gfield_required'>%s</span>", $field["isRequired"] ? "*" : "") : "";
  2209.         $target_input_id = "";
  2210.         $is_description_above = rgar($field, "descriptionPlacement") == "above";
  2211.  
  2212.         switch(RGFormsModel::get_input_type($field)){
  2213.             case "section" :
  2214.                 $description = self::get_description(rgget("description", $field), "gsection_description");
  2215.                 $field_content = sprintf("%s<h2 class='gsection_title'>%s</h2>%s", $admin_buttons,  esc_html($field_label), $description);
  2216.             break;
  2217.  
  2218.             case "page" :
  2219.                 //only executed on the form editor in the admin
  2220.                 $page_label = __("Page Break", "gravityforms");
  2221.                 $src = GFCommon::get_base_url() . "/images/gf_pagebreak_inline.png";
  2222.                 $field_content = "{$admin_buttons} <label class='gfield_label'>&nbsp;</label><img src='{$src}' alt='{$page_label}' title='{$page_label}' />";
  2223.             break;
  2224.  
  2225.             case "adminonly_hidden":
  2226.             case "hidden" :
  2227.             case "html" :
  2228.                 $field_content = !IS_ADMIN ? "{FIELD}" : $field_content = sprintf("%s<label class='gfield_label' for='%s'>%s</label>{FIELD}", $admin_buttons, $field_id, esc_html($field_label));
  2229.             break;
  2230.  
  2231.             case "checkbox":
  2232.             case "radio":
  2233.                 $description = self::get_description(rgget("description", $field),"gfield_description");
  2234.                 if($is_description_above)
  2235.                     $field_content = sprintf("%s<label class='gfield_label'>%s%s</label>%s{FIELD}%s", $admin_buttons, esc_html($field_label), $required_div , $description, $validation_message);
  2236.                 else
  2237.                     $field_content = sprintf("%s<label class='gfield_label'>%s%s</label>{FIELD}%s%s", $admin_buttons, esc_html($field_label), $required_div , $description, $validation_message);
  2238.             break;
  2239.  
  2240.             case "name" :
  2241.                 switch(rgar($field, "nameFormat")){
  2242.                     case "simple" :
  2243.                         $target_input_id = $field_id;
  2244.                         break;
  2245.  
  2246.                     case "extended" :
  2247.                         $target_input_id = $field_id . "_2";
  2248.                         break;
  2249.  
  2250.                     default :
  2251.                         $target_input_id = $field_id . "_3";
  2252.                 }
  2253.  
  2254.             case "address" :
  2255.                 if(empty($target_input_id))
  2256.                     $target_input_id = $field_id . "_1";
  2257.  
  2258.             default :
  2259.                 if(empty($target_input_id))
  2260.                     $target_input_id = $field_id;
  2261.  
  2262.                 $description = self::get_description(rgget("description", $field),"gfield_description");
  2263.                 if($is_description_above)
  2264.                     $field_content = sprintf("%s<label class='gfield_label' for='%s'>%s%s</label>%s{FIELD}%s", $admin_buttons, $target_input_id, esc_html($field_label), $required_div , $description, $validation_message);
  2265.                 else
  2266.                     $field_content = sprintf("%s<label class='gfield_label' for='%s'>%s%s</label>{FIELD}%s%s", $admin_buttons, $target_input_id, esc_html($field_label), $required_div , $description, $validation_message);
  2267.             break;
  2268.         }
  2269.  
  2270.         if(RGFormsModel::get_input_type($field) == "creditcard" && !GFCommon::is_ssl() && !IS_ADMIN){
  2271.             $field_content = "<div class='gfield_creditcard_warning_message'>" . __("This page is unsecured. Do not enter a real credit card number. Use this field only for testing purposes. ", "gravityforms") . "</div>" . $field_content;
  2272.         }
  2273.  
  2274.         $value = self::default_if_empty($field, $value);
  2275.  
  2276.         $field_content = str_replace("{FIELD}", GFCommon::get_field_input($field, $value, 0, $form_id), $field_content);
  2277.  
  2278.         $field_content = apply_filters("gform_field_content", $field_content, $field, $value, 0, $form_id);
  2279.  
  2280.         return $field_content;
  2281.     }
  2282.  
  2283.     private static function default_if_empty($field, $value){
  2284.  
  2285.         if(!GFCommon::is_empty_array($value))
  2286.             return $value;
  2287.  
  2288.         if(IS_ADMIN){
  2289.             $value = rgget("defaultValue", $field);
  2290.         }
  2291.         else{
  2292.             $value = rgar($field, "defaultValue");
  2293.             if(!is_array($value))
  2294.                 $value = GFCommon::replace_variables_prepopulate(rgget("defaultValue", $field));
  2295.         }
  2296.  
  2297.         return $value;
  2298.     }
  2299.  
  2300.     private static function get_description($description, $css_class){
  2301.         return IS_ADMIN || !empty($description) ? "<div class='$css_class'>" . $description . "</div>" : "";
  2302.     }
  2303.  
  2304.     public static function get_credit_card_rules() {
  2305.  
  2306.         $cards = GFCommon::get_card_types();
  2307.         //$supported_cards = //TODO: Only include enabled cards
  2308.         $rules = array();
  2309.  
  2310.         foreach($cards as $card) {
  2311.             $prefixes = explode(',', $card['prefixes']);
  2312.             foreach($prefixes as $prefix) {
  2313.                 $rules[$card['slug']][] = $prefix;
  2314.             }
  2315.         }
  2316.  
  2317.         return $rules;
  2318.     }
  2319.  
  2320.     private static function get_progress_bar($form, $form_id,$confirmation_message) {
  2321.  
  2322.         $progress_complete = false;
  2323.         $progress_bar = "";
  2324.         $page_count = self::get_max_page_number($form);
  2325.         $current_page = self::get_current_page($form_id);
  2326.         $page_name = rgar(rgar($form["pagination"],"pages"), $current_page -1);
  2327.         $page_name = !empty($page_name) ? " - " . $page_name : "";
  2328.         $style = $form["pagination"]["style"];
  2329.         $color = $style == "custom" ? " color:{$form["pagination"]["color"]};" : "";
  2330.         $bgcolor = $style == "custom" ? " background-color:{$form["pagination"]["backgroundColor"]};" : "";
  2331.  
  2332.         if (!empty($confirmation_message))
  2333.         {
  2334.             $progress_complete = true;
  2335.         }
  2336.         //check admin setting for whether the progress bar should start at zero
  2337.         $start_at_zero = rgars($form, "pagination/display_progressbar_on_confirmation");
  2338.         //check for filter
  2339.         $start_at_zero = apply_filters("gform_progressbar_start_at_zero", $start_at_zero, $form);
  2340.         $progressbar_page_count = $start_at_zero ? $current_page - 1 : $current_page;
  2341.         $percent = !$progress_complete ? floor(( ($progressbar_page_count) / $page_count ) * 100) . "%" : "100%";
  2342.         $percent_number = !$progress_complete ? floor(( ($progressbar_page_count) / $page_count ) * 100) . "" : "100";
  2343.  
  2344.         if ($progress_complete)
  2345.         {
  2346.             $wrapper_css_class = GFCommon::get_browser_class() . " gform_wrapper";
  2347.  
  2348.             //add on surrounding wrapper class when confirmation page
  2349.             $progress_bar = "<div class='{$wrapper_css_class}' id='gform_wrapper_$form_id' >";
  2350.             $page_name = !empty($form["pagination"]["progressbar_completion_text"]) ? $form["pagination"]["progressbar_completion_text"] : "";
  2351.         }
  2352.  
  2353.  
  2354.         $progress_bar .="
  2355.        <div id='gf_progressbar_wrapper_{$form_id}' class='gf_progressbar_wrapper'>
  2356.            <h3 class='gf_progressbar_title'>";
  2357.         $progress_bar .= !$progress_complete ? __("Step", "gravityforms") . " {$current_page} " . __("of", "gravityforms") . " {$page_count}{$page_name}" : "{$page_name}";
  2358.         $progress_bar .= "
  2359.        </h3>
  2360.            <div class='gf_progressbar'>
  2361.                <div class='gf_progressbar_percentage percentbar_{$style} percentbar_{$percent_number}' style='width:{$percent};{$color}{$bgcolor}'><span>{$percent}</span></div>
  2362.            </div></div>";
  2363.         //close div for surrounding wrapper class when confirmation page
  2364.         $progress_bar .= $progress_complete ? "</div>" : "";
  2365.  
  2366.         return $progress_bar;
  2367.     }
  2368.  
  2369.     /**
  2370.     * Validates the form's entry limit settings. Returns the entry limit message if entry limit exceeded.
  2371.     *
  2372.     * @param array $form current GF form object
  2373.     * @return string If entry limit exceeded returns entry limit setting.
  2374.     */
  2375.     public static function validate_entry_limit($form) {
  2376.  
  2377.         //If form has a limit of entries, check current entry count
  2378.         if(rgar($form,"limitEntries")) {
  2379.             $period = rgar($form, "limitEntriesPeriod");
  2380.             $range = self::get_limit_period_dates($period);
  2381.             $entry_count = RGFormsModel::get_lead_count($form['id'], "", null, null, $range["start_date"], $range["end_date"]);
  2382.  
  2383.             if($entry_count >= $form["limitEntriesCount"])
  2384.                 return empty($form["limitEntriesMessage"]) ? "<p>" . __("Sorry. This form is no longer accepting new submissions.", "gravityforms"). "</p>" : "<p>" . GFCommon::gform_do_shortcode($form["limitEntriesMessage"]) . "</p>";
  2385.         }
  2386.  
  2387.     }
  2388.  
  2389.     public static function validate_form_schedule($form) {
  2390.  
  2391.         //If form has a schedule, make sure it is within the configured start and end dates
  2392.         if(rgar($form, "scheduleForm")){
  2393.             $local_time_start = sprintf("%s %02d:%02d %s", $form["scheduleStart"], $form["scheduleStartHour"], $form["scheduleStartMinute"], $form["scheduleStartAmpm"]);
  2394.             $local_time_end = sprintf("%s %02d:%02d %s", $form["scheduleEnd"], $form["scheduleEndHour"], $form["scheduleEndMinute"], $form["scheduleEndAmpm"]);
  2395.             $timestamp_start = strtotime($local_time_start . ' +0000');
  2396.             $timestamp_end = strtotime($local_time_end . ' +0000');
  2397.             $now = current_time("timestamp");
  2398.  
  2399.             if( (!empty($form["scheduleStart"]) && $now < $timestamp_start) || (!empty($form["scheduleEnd"]) && $now > $timestamp_end))
  2400.                 return empty($form["scheduleMessage"]) ? "<p>" . __("Sorry. This form is no longer available.", "gravityforms") . "</p>" : "<p>" . GFCommon::gform_do_shortcode($form["scheduleMessage"]) . "</p>";
  2401.         }
  2402.  
  2403.     }
  2404. }
  2405.  
  2406.  
  2407. function form_script_footer(){
  2408.     $form_id = 1; // pass this down from add_
  2409.     $spinner_url = apply_filters("gform_ajax_spinner_url_{$form_id}",
  2410.         apply_filters("gform_ajax_spinner_url", GFCommon::get_base_url() . "/images/spinner.gif", $form), $form);
  2411.        
  2412. $form_string2 .="
  2413.                <iframe style='display:none;width:0px; height:0px;' src='about:blank' name='gform_ajax_frame_{$form_id}' id='gform_ajax_frame_{$form_id}'></iframe>
  2414.                <script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . "" .
  2415.                     "function gformInitSpinner_{$form_id}(){" .
  2416.                         "jQuery('#gform_{$form_id}').submit(function(){" .
  2417.                             "if(jQuery('#gform_ajax_spinner_{$form_id}').length == 0){".
  2418.                                 "jQuery('#gform_submit_button_{$form_id}, #gform_wrapper_{$form_id} .gform_previous_button, #gform_wrapper_{$form_id} .gform_next_button, #gform_wrapper_{$form_id} .gform_image_button').attr('disabled', true); " .
  2419.                                 "jQuery('#gform_submit_button_{$form_id}, #gform_wrapper_{$form_id} .gform_next_button, #gform_wrapper_{$form_id} .gform_image_button').after('<' + 'img id=\"gform_ajax_spinner_{$form_id}\"  class=\"gform_ajax_spinner\" src=\"{$spinner_url}\" alt=\"\" />'); " .
  2420.                             "}".
  2421.                         "} );" .
  2422.                     "}" .
  2423.                     "jQuery(document).ready(function($){" .
  2424.                         "gformInitSpinner_{$form_id}();" .
  2425.                         "jQuery('#gform_ajax_frame_{$form_id}').load( function(){" .
  2426.                             "var contents = jQuery(this).contents().find('*').html();" .
  2427.                             "var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;" .
  2428.                             "if(!is_postback){return;}" .
  2429.                             "var form_content = jQuery(this).contents().find('#gform_wrapper_{$form_id}');" .
  2430.                             "var is_redirect = contents.indexOf('gformRedirect(){') >= 0;".
  2431.                             "jQuery('#gform_submit_button_{$form_id}').removeAttr('disabled');" .
  2432.                             "var is_form = !(form_content.length <= 0 || is_redirect);".
  2433.                             "if(is_form){" .
  2434.                                 "jQuery('#gform_wrapper_{$form_id}').html(form_content.html());" .
  2435.                                 "{$scroll_position['default']}" .
  2436.                                 "if(window['gformInitDatepicker']) {gformInitDatepicker();}" .
  2437.                                 "if(window['gformInitPriceFields']) {gformInitPriceFields();}" .
  2438.                                 "var current_page = jQuery('#gform_source_page_number_{$form_id}').val();".
  2439.                                 "gformInitSpinner_{$form_id}();" .
  2440.                                 "jQuery(document).trigger('gform_page_loaded', [{$form_id}, current_page]);" .
  2441.                             "}" .
  2442.                             "else if(!is_redirect){" .
  2443.                                 "var confirmation_content = jQuery(this).contents().find('#gforms_confirmation_message').html();" .
  2444.                                 "if(!confirmation_content){".
  2445.                                     "confirmation_content = contents;".
  2446.                                 "}" .
  2447.                                 "setTimeout(function(){" .
  2448.                                     "jQuery('#gform_wrapper_{$form_id}').replaceWith('<' + 'div id=\'gforms_confirmation_message\' class=\'gform_confirmation_message_{$form_id}\'' + '>' + confirmation_content + '<' + '/div' + '>');" .
  2449.                                     "{$scroll_position['confirmation']}" .
  2450.                                     "jQuery(document).trigger('gform_confirmation_loaded', [{$form_id}]);" .
  2451.                                 "}, 50);" .
  2452.                             "}" .
  2453.                             "else{" .
  2454.                                 "jQuery('#gform_{$form_id}').append(contents);" .
  2455.                                 "if(window['gformRedirect']) {gformRedirect();}" .
  2456.                             "}" .
  2457.                             "jQuery(document).trigger('gform_post_render', [{$form_id}, current_page]);" .
  2458.                         "} );" .
  2459.                     "} );" . apply_filters("gform_cdata_close", "") . "</script>";
  2460.     echo $form_string2;
  2461. }
Add Comment
Please, Sign In to add comment