public static function add_page_script($form)
 {
     self::log_debug('Adding page script to ' . $form['id']);
     $script = "(function(\$){" . "\$('#gform_" . $form['id'] . "').sisyphus();" . "})(jQuery);";
     GFFormDisplay::add_init_script($form['id'], 'gravity-forms-js-validate', GFFormDisplay::ON_PAGE_RENDER, $script);
     return $form;
 }
 /**
  * initialise instance
  * @param array $form
  */
 public function __construct(&$form)
 {
     // check for last page
     $current_page = GFFormDisplay::get_source_page($form['id']);
     $target_page = GFFormDisplay::get_target_page($form, $current_page, rgpost('gform_field_values'));
     $this->isLastPageFlag = $target_page == 0;
     // load the form data
     $this->loadForm($form);
 }
Exemplo n.º 3
0
 public function register_init_scripts($form)
 {
     if (!$this->has_copy_cat_field($form)) {
         return;
     }
     $copy_fields = $this->get_copy_cat_fields($form);
     $enable_overwrite = gf_apply_filters('gpcc_overwrite_existing_values', $form['id'], false, $form);
     $script = 'new gwCopyObj( ' . $form['id'] . ', ' . json_encode($copy_fields) . ', ' . ($enable_overwrite ? 'true' : 'false') . ' );';
     GFFormDisplay::add_init_script($form['id'], 'gp-copy-cat', GFFormDisplay::ON_PAGE_RENDER, $script);
 }
function sticky_pre_populate_the_form($form)
{
    if ($form['isSticky']) {
        $current_page = GFFormDisplay::get_current_page($form["id"]);
        if ($current_page == 1) {
            global $valid;
            // Get the stored entry ID
            $entry_id = sticky_getEntryOptionKeyForGF($form);
            // If the form has been submited, is valid and we are not in the preview area
            if ($valid && strpos($_SERVER['REQUEST_URI'], 'preview') == false) {
                // We have a previously saved entry
                if (get_option($entry_id)) {
                    // Get the entry
                    $form_fields = RGFormsModel::get_lead(get_option($entry_id));
                    // If an entry is found we need prepare if for insertion into the form
                    if ($form_fields && $form_fields["status"] != "trash") {
                        // Create new correctly formated keys and get rid of the old ones
                        foreach ($form_fields as $key => &$value) {
                            // If the key is numeric we need to change it from [X.X] to [input_X_X]
                            if (is_numeric($key)) {
                                $new_key = str_replace(".", "_", "input_{$key}");
                                $form_fields[$new_key] = $form_fields[$key];
                                unset($form_fields[$key]);
                                // If we have an upload field
                                if (strpos($value, "uploads/")) {
                                    $upload = $value;
                                }
                            }
                        }
                        // Add is_submit_id field
                        $form_id = $form['id'];
                        $form_fields["is_submit_{$form_id}"] = "1";
                        $_POST = $form_fields;
                        // If no entry is found; unset the stored entry ID
                    } else {
                        update_option($entry_id, "");
                    }
                }
            }
        }
    }
    // Replace {upload} with reference to uploaded file
    if (isset($upload)) {
        foreach ($form["fields"] as &$field) {
            foreach ($field as $key => &$value) {
                if ($key == "content") {
                    $value = str_replace("{upload}", $upload, $value);
                }
            }
        }
    }
    return $form;
}
function getFormInitScripts()
{
    if (intval(get_query_var('getFormInitScripts')) != '') {
        require_once GFCommon::get_base_path() . '/form_display.php';
        $form = GFAPI::get_form(get_query_var('getFormInitScripts'));
        $field_values = array();
        // the array of parameter names and values if any fields are being populated
        GFFormDisplay::register_form_init_scripts($form, $field_values);
        $form_string = GFFormDisplay::get_form_init_scripts($form);
        echo strip_tags($form_string);
        exit;
    }
}
 public function render($form, $ajax)
 {
     if (!class_exists('GFFormDisplay') || self::isDisabled()) {
         return $form;
     }
     self::enqueueScripts($form, $ajax);
     self::updateRenderedCount();
     $next = GFFormDisplay::get_max_field_id($form) + 1;
     $template = sprintf($this->template, get_option('rg_gforms_captcha_public_key'));
     $opts = array('type' => 'section', '_is_entry_detail' => NULL, 'id' => $next, 'label' => '', 'adminLabel' => '', 'isRequired' => false, 'size' => 'medium', 'errorMessage' => '', 'inputs' => NULL, 'displayOnly' => true, 'labelPlacement' => '', 'content' => '', 'formId' => $form['id'], 'pageNumber' => GFFormDisplay::get_current_page($form['id']), 'conditionalLogic' => '', 'cssClass' => $this->buCAPTCHAIdentifier . '_section');
     $form['fields'][] = GF_Fields::create($opts);
     $captcha_opts = array('type' => 'html', 'id' => $next + 1, 'content' => apply_filters('bu_gravityforms_global_recaptcha_div', $template), 'cssClass' => $this->buCAPTCHAIdentifier);
     $form['fields'][] = GF_Fields::create(array_merge($opts, $captcha_opts));
     return $form;
 }
 function is_applicable_field($field, $form)
 {
     if ($field['pageNumber'] != GFFormDisplay::get_source_page($form['id'])) {
         return false;
     }
     if ($field['type'] != 'list' || RGFormsModel::is_field_hidden($form, $field, array())) {
         return false;
     }
     // if the field has already failed validation, we don't need to fail it again
     if (!$field['isRequired'] || $field['failed_validation']) {
         return false;
     }
     if (empty($this->field_ids)) {
         return true;
     }
     return in_array($field['id'], $this->field_ids);
 }
 public static function add_page_script($form)
 {
     self::log_debug('Adding page script to ' . $form['id']);
     $script = "(function(\$){" . "var container;" . "\$('.gfield_contains_required').each(function(i, e){" . "\$(e).find('input, select, textarea').attr('required', true);" . "});" . "\$('#gform_" . $form['id'] . "').validate({" . "debug: true," . "errorElement: 'div'," . "errorClass: 'gfield_error'," . "errorPlacement: function(error, element){" . "container = element.closest('.gfield');" . "},";
     // Get messages for each input
     $script .= "messages: {";
     foreach ($form['fields'] as $field) {
         $field_name = 'input_' . $field['id'];
         // test
         $field_errorMessage = "'" . $field['errorMessage'] . "',";
         if ($field['errorMessage'] !== '') {
             $script = $script . $field_name . ": " . $field_errorMessage;
         }
     }
     $script .= "},";
     $script .= "groups: getGroups()," . "focusCleanup: true," . "highlight: function(element, errorClass, validClass) {" . "\$(element).closest('.gfield').addClass(errorClass).removeClass(validClass);" . "}," . "unhighlight: function(element, errorClass, validClass) {" . "\$(element).closest('.gfield').removeClass(errorClass).addClass(validClass);" . "}," . "invalidHandler: function(event, validator) {" . "gf_submitting_" . $form['id'] . " = false;" . "}" . "});" . "})(jQuery);";
     self::log_debug('Script is: ' . $script);
     GFFormDisplay::add_init_script($form['id'], 'gf_js_validate', GFFormDisplay::ON_PAGE_RENDER, $script);
     return $form;
 }
 public function validation($validation_result)
 {
     if (!GFFormDisplay::is_last_page($validation_result['form'])) {
         return $validation_result;
     }
     $has_authorize = $this->payment_method_is_overridden('authorize');
     $has_subscribe = $this->payment_method_is_overridden('subscribe');
     if (!$has_authorize && !$has_subscribe) {
         return $validation_result;
     }
     //Getting submission data
     $form = $validation_result["form"];
     $entry = GFFormsModel::create_lead($form);
     $feed = $this->get_payment_feed($entry, $form);
     if (!$feed) {
         return $validation_result;
     }
     $do_authorization = $has_authorize && $feed["meta"]["transactionType"] == "product";
     $do_subscription = $has_subscribe && $feed["meta"]["transactionType"] == "subscription";
     if (!$do_authorization && !$do_subscription) {
         return $validation_result;
     }
     $submission_data = $this->get_submission_data($feed, $form, $entry);
     //Running an authorization only transaction if function is implemented and this is a single payment
     if ($do_authorization) {
         $this->authorization = $this->authorize($feed, $submission_data, $form, $entry);
     } else {
         if ($do_subscription) {
             $subscription = $this->subscribe($feed, $submission_data, $form, $entry);
             $this->authorization["is_authorized"] = $subscription["is_success"];
             $this->authorization["error_message"] = rgar($subscription, "error_message");
             $this->authorization["subscription"] = $subscription;
         }
     }
     $this->authorization["feed"] = $feed;
     $this->authorization["submission_data"] = $submission_data;
     if (!$this->authorization["is_authorized"]) {
         $validation_result = $this->get_validation_result($validation_result, $this->authorization);
         //Setting up current page to point to the credit card page since that will be the highlighted field
         GFFormDisplay::set_current_page($validation_result["form"]["id"], $validation_result["credit_card_page"]);
     }
     return $validation_result;
 }
Exemplo n.º 10
0
 public static function refresh_field_preview()
 {
     check_ajax_referer('rg_refresh_field_preview', 'rg_refresh_field_preview');
     $field_json = stripslashes_deep($_POST['field']);
     $field_properties = GFCommon::json_decode($field_json, true);
     $field = GF_Fields::create($field_properties);
     $form_id = absint($_POST['formId']);
     $form = GFFormsModel::get_form_meta($form_id);
     require_once GFCommon::get_base_path() . '/form_display.php';
     $field_content = GFFormDisplay::get_field_content($field, '', true, $form_id, $form);
     $args['fieldString'] = $field_content;
     $args_json = json_encode($args);
     die($args_json);
 }
Exemplo n.º 11
0
 public static function get_form($form_id, $display_title = true, $display_description = true, $force_display = false, $field_values = null, $ajax = false, $tabindex = 1)
 {
     /**
      * Provides the ability to modify the options used to display the form
      *
      * @param array An array of Form Arguments when adding it to a page/post (Like the ID, Title, AJAX or not, etc)
      */
     $form_args = apply_filters('gform_form_args', compact('form_id', 'display_title', 'display_description', 'force_display', 'field_values', 'ajax', 'tabindex'));
     extract($form_args);
     //looking up form id by form name
     if (!is_numeric($form_id)) {
         $form_id = RGFormsModel::get_form_id($form_id);
     }
     //reading form metadata
     $form = GFAPI::get_form($form_id);
     $form = self::maybe_add_review_page($form);
     $action = remove_query_arg('gf_token');
     //disable ajax if form has a reCAPTCHA field (not supported).
     if ($ajax && self::has_recaptcha_field($form)) {
         $ajax = false;
     }
     if (isset($_POST['gform_send_resume_link'])) {
         $save_email_confirmation = self::handle_save_email_confirmation($form, $ajax);
         if (is_wp_error($save_email_confirmation)) {
             // Failed email validation
             $resume_token = rgpost('gform_resume_token');
             $resume_token = sanitize_key($resume_token);
             $incomplete_submission_info = GFFormsModel::get_incomplete_submission_values($resume_token);
             if ($incomplete_submission_info['form_id'] == $form_id) {
                 $submission_details_json = $incomplete_submission_info['submission'];
                 $submission_details = json_decode($submission_details_json, true);
                 $partial_entry = $submission_details['partial_entry'];
                 $form = self::update_confirmation($form, $partial_entry, 'form_saved');
                 $confirmation_message = rgar($form['confirmation'], 'message');
                 $nl2br = rgar($form['confirmation'], 'disableAutoformat') ? false : true;
                 $confirmation_message = GFCommon::replace_variables($confirmation_message, $form, $partial_entry, false, true, $nl2br);
                 return self::handle_save_confirmation($form, $resume_token, $confirmation_message, $ajax);
             }
         } else {
             return $save_email_confirmation;
         }
     }
     $is_postback = false;
     $is_valid = true;
     $confirmation_message = '';
     //If form was submitted, read variables set during form submission procedure
     $submission_info = isset(self::$submission[$form_id]) ? self::$submission[$form_id] : false;
     if (rgar($submission_info, 'saved_for_later') == true) {
         $resume_token = $submission_info['resume_token'];
         $confirmation_message = rgar($submission_info, 'confirmation_message');
         return self::handle_save_confirmation($form, $resume_token, $confirmation_message, $ajax);
     }
     $partial_entry = $submitted_values = false;
     if (isset($_GET['gf_token'])) {
         $incomplete_submission_info = GFFormsModel::get_incomplete_submission_values($_GET['gf_token']);
         if ($incomplete_submission_info['form_id'] == $form_id) {
             $submission_details_json = $incomplete_submission_info['submission'];
             $submission_details = json_decode($submission_details_json, true);
             $partial_entry = $submission_details['partial_entry'];
             $submitted_values = $submission_details['submitted_values'];
             $field_values = $submission_details['field_values'];
             GFFormsModel::$unique_ids[$form_id] = $submission_details['gform_unique_id'];
             GFFormsModel::$uploaded_files[$form_id] = $submission_details['files'];
             self::set_submission_if_null($form_id, 'resuming_incomplete_submission', true);
             self::set_submission_if_null($form_id, 'form_id', $form_id);
             $max_page_number = self::get_max_page_number($form);
             $page_number = $submission_details['page_number'] > $max_page_number ? $max_page_number : $submission_details['page_number'];
             self::set_submission_if_null($form_id, 'page_number', $page_number);
         }
     }
     if (!is_array($partial_entry)) {
         /**
          * A filter that allows disabling of the form view counter
          *
          * @param int $form_id The Form ID to filter when disabling the form view counter
          * @param bool Default set to false (view counter enabled), can be set to true to disable the counter
          */
         $view_counter_disabled = gf_apply_filters(array('gform_disable_view_counter', $form_id), false);
         if ($submission_info) {
             $is_postback = true;
             $is_valid = rgar($submission_info, 'is_valid') || rgar($submission_info, 'is_confirmation');
             $form = $submission_info['form'];
             $lead = $submission_info['lead'];
             $confirmation_message = rgget('confirmation_message', $submission_info);
             if ($is_valid && !RGForms::get('is_confirmation', $submission_info)) {
                 if ($submission_info['page_number'] == 0) {
                     /**
                      * Fired after form submission
                      *
                      * @param array $lead The Entry object
                      * @param array $form The Form object
                      */
                     gf_do_action(array('gform_post_submission', $form['id']), $lead, $form);
                 } else {
                     /**
                      * Fired after the page changes on a multi-page form
                      *
                      * @param array $form                                  The Form object
                      * @param int   $submission_info['source_page_number'] The page that was submitted
                      * @param int   $submission_info['page_number']        The page that the user is being sent to
                      */
                     gf_do_action(array('gform_post_paging', $form['id']), $form, $submission_info['source_page_number'], $submission_info['page_number']);
                 }
             }
         } elseif (!current_user_can('administrator') && !$view_counter_disabled) {
             RGFormsModel::insert_form_view($form_id, $_SERVER['REMOTE_ADDR']);
         }
     }
     if (rgar($form, 'enableHoneypot')) {
         $form['fields'][] = self::get_honeypot_field($form);
     }
     //Fired right before the form rendering process. Allow users to manipulate the form object before it gets displayed in the front end
     $form = gf_apply_filters(array('gform_pre_render', $form_id), $form, $ajax, $field_values);
     if ($form == null) {
         return '<p class="gform_not_found">' . esc_html__('Oops! We could not locate your form.', 'gravityforms') . '</p>';
     }
     $has_pages = self::has_pages($form);
     //calling tab index filter
     GFCommon::$tab_index = gf_apply_filters(array('gform_tabindex', $form_id), $tabindex, $form);
     //Don't display inactive forms
     if (!$force_display && !$is_postback) {
         $form_info = RGFormsModel::get_form($form_id);
         if (empty($form_info) || !$form_info->is_active) {
             return '';
         }
         // If form requires login, check if user is logged in
         if (rgar($form, 'requireLogin')) {
             if (!is_user_logged_in()) {
                 return empty($form['requireLoginMessage']) ? '<p>' . esc_html__('Sorry. You must be logged in to view this form.', 'gravityforms') . '</p>' : '<p>' . GFCommon::gform_do_shortcode($form['requireLoginMessage']) . '</p>';
             }
         }
     }
     // show the form regardless of the following validations when force display is set to true
     if (!$force_display || $is_postback) {
         $form_schedule_validation = self::validate_form_schedule($form);
         // if form schedule validation fails AND this is not a postback, display the validation error
         // if form schedule validation fails AND this is a postback, make sure is not a valid submission (enables display of confirmation message)
         if ($form_schedule_validation && !$is_postback || $form_schedule_validation && $is_postback && !$is_valid) {
             return $form_schedule_validation;
         }
         $entry_limit_validation = self::validate_entry_limit($form);
         // refer to form schedule condition notes above
         if ($entry_limit_validation && !$is_postback || $entry_limit_validation && $is_postback && !$is_valid) {
             return $entry_limit_validation;
         }
     }
     $form_string = '';
     //When called via a template, this will enqueue the proper scripts
     //When called via a shortcode, this will be ignored (too late to enqueue), but the scripts will be enqueued via the enqueue_scripts event
     self::enqueue_form_scripts($form, $ajax);
     $is_form_editor = GFCommon::is_form_editor();
     $is_entry_detail = GFCommon::is_entry_detail();
     $is_admin = $is_form_editor || $is_entry_detail;
     if (empty($confirmation_message)) {
         $wrapper_css_class = GFCommon::get_browser_class() . ' gform_wrapper';
         if (!$is_valid) {
             $wrapper_css_class .= ' gform_validation_error';
         }
         $form_css_class = esc_attr(rgar($form, 'cssClass'));
         //Hiding 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.
         $style = self::has_conditional_logic($form) ? "style='display:none'" : '';
         // Split form CSS class by spaces and apply wrapper to each.
         $custom_wrapper_css_class = '';
         if (!empty($form_css_class)) {
             // Separate the CSS classes.
             $form_css_classes = explode(' ', $form_css_class);
             // Append _wrapper to each class.
             foreach ($form_css_classes as &$wrapper_class) {
                 $wrapper_class .= '_wrapper';
             }
             // Merge back into a string.
             $custom_wrapper_css_class = ' ' . implode(' ', $form_css_classes);
         }
         $form_string .= "\n                <div class='{$wrapper_css_class}{$custom_wrapper_css_class}' id='gform_wrapper_{$form_id}' " . $style . '>';
         $default_anchor = $has_pages || $ajax ? true : false;
         $use_anchor = gf_apply_filters(array('gform_confirmation_anchor', $form_id), $default_anchor, $form);
         if ($use_anchor !== false) {
             $form_string .= "<a id='gf_{$form_id}' class='gform_anchor' ></a>";
             $action .= "#gf_{$form_id}";
         }
         $target = $ajax ? "target='gform_ajax_frame_{$form_id}'" : '';
         $form_css_class = !empty($form['cssClass']) ? "class='{$form_css_class}'" : '';
         $action = esc_url($action);
         $form_string .= gf_apply_filters(array('gform_form_tag', $form_id), "<form method='post' enctype='multipart/form-data' {$target} id='gform_{$form_id}' {$form_css_class} action='{$action}'>", $form);
         if ($display_title || $display_description) {
             $form_string .= "\n                        <div class='gform_heading'>";
             if ($display_title) {
                 $form_string .= "\n                            <h3 class='gform_title'>" . $form['title'] . '</h3>';
             }
             if ($display_description) {
                 $form_string .= "\n                            <span class='gform_description'>" . rgar($form, 'description') . '</span>';
             }
             $form_string .= '
                     </div>';
         }
         /* If the form was submitted, has multiple pages and is invalid, set the current page to the first page with an invalid field. */
         if ($has_pages && $is_postback && !$is_valid) {
             self::set_current_page($form_id, GFFormDisplay::get_first_page_with_error($form));
         }
         $current_page = self::get_current_page($form_id);
         if ($has_pages && !$is_admin) {
             if ($form['pagination']['type'] == 'percentage') {
                 $form_string .= self::get_progress_bar($form, $current_page, $confirmation_message);
             } else {
                 if ($form['pagination']['type'] == 'steps') {
                     $form_string .= self::get_progress_steps($form, $current_page);
                 }
             }
         }
         if ($is_postback && !$is_valid) {
             $validation_message = "<div class='validation_error'>" . esc_html__('There was a problem with your submission.', 'gravityforms') . ' ' . esc_html__('Errors have been highlighted below.', 'gravityforms') . '</div>';
             $form_string .= gf_apply_filters(array('gform_validation_message', $form_id), $validation_message, $form);
         }
         $form_string .= "\n                        <div class='gform_body'>";
         //add first page if this form has any page fields
         if ($has_pages) {
             $style = self::is_page_active($form_id, 1) ? '' : "style='display:none;'";
             $class = !empty($form['firstPageCssClass']) ? " {$form['firstPageCssClass']}" : '';
             $class = esc_attr($class);
             $form_string .= "<div id='gform_page_{$form_id}_1' class='gform_page{$class}' {$style}>\n                                    <div class='gform_page_fields'>";
         }
         $description_class = rgar($form, 'descriptionPlacement') == 'above' ? 'description_above' : 'description_below';
         $sublabel_class = rgar($form, 'subLabelPlacement') == 'above' ? 'form_sublabel_above' : 'form_sublabel_below';
         $form_string .= "<ul id='gform_fields_{$form_id}' class='" . GFCommon::get_ul_classes($form) . "'>";
         if (is_array($form['fields'])) {
             foreach ($form['fields'] as $field) {
                 /* @var GF_Field $field */
                 $field->conditionalLogicFields = self::get_conditional_logic_fields($form, $field->id);
                 if (is_array($submitted_values)) {
                     $field_value = rgar($submitted_values, $field->id);
                 } else {
                     $field_value = GFFormsModel::get_field_value($field, $field_values);
                 }
                 $form_string .= self::get_field($field, $field_value, false, $form, $field_values);
             }
         }
         $form_string .= '
                         </ul>';
         if ($has_pages) {
             $previous_button_alt = rgempty('imageAlt', $form['lastPageButton']) ? __('Previous Page', 'gravityforms') : $form['lastPageButton']['imageAlt'];
             $previous_button = self::get_form_button($form['id'], "gform_previous_button_{$form['id']}", $form['lastPageButton'], __('Previous', 'gravityforms'), 'gform_previous_button', $previous_button_alt, self::get_current_page($form_id) - 1);
             /**
              * Filter through the form previous button when paged
              *
              * @param int $form_id The Form ID to filter through
              * @param string $previous_button The HTML rendered button (rendered with the form ID and the function get_form_button)
              * @param array $form The Form object to filter through
              */
             $previous_button = gf_apply_filters(array('gform_previous_button', $form_id), $previous_button, $form);
             $form_string .= '</div>' . self::gform_footer($form, 'gform_page_footer ' . $form['labelPlacement'], $ajax, $field_values, $previous_button, $display_title, $display_description, $is_postback) . '
                     </div>';
             //closes gform_page
         }
         $form_string .= '</div>';
         //closes gform_body
         //suppress form footer for multi-page forms (footer will be included on the last page
         if (!$has_pages) {
             $form_string .= self::gform_footer($form, 'gform_footer ' . $form['labelPlacement'], $ajax, $field_values, '', $display_title, $display_description, $tabindex);
         }
         $form_string .= '
                     </form>
                     </div>';
         if ($ajax && $is_postback) {
             global $wp_scripts;
             $form_string = apply_filters('gform_ajax_iframe_content', '<!DOCTYPE html><html><head>' . "<meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $form_string . '</body></html>');
         }
         if ($ajax && !$is_postback) {
             $spinner_url = gf_apply_filters(array('gform_ajax_spinner_url', $form_id), GFCommon::get_base_url() . '/images/spinner.gif', $form);
             $scroll_position = array('default' => '', 'confirmation' => '');
             if ($use_anchor !== false) {
                 $scroll_position['default'] = is_numeric($use_anchor) ? 'jQuery(document).scrollTop(' . intval($use_anchor) . ');' : "jQuery(document).scrollTop(jQuery('#gform_wrapper_{$form_id}').offset().top);";
                 $scroll_position['confirmation'] = is_numeric($use_anchor) ? 'jQuery(document).scrollTop(' . intval($use_anchor) . ');' : "jQuery(document).scrollTop(jQuery('#gforms_confirmation_message_{$form_id}').offset().top);";
             }
             $iframe_style = defined('GF_DEBUG') && GF_DEBUG ? 'display:block;width:600px;height:300px;border:1px solid #eee;' : 'display:none;width:0px;height:0px;';
             $is_html5 = RGFormsModel::is_html5_enabled();
             $iframe_title = $is_html5 ? " title='Ajax Frame'" : '';
             $form_string .= "\n                <iframe style='{$iframe_style}' src='about:blank' name='gform_ajax_frame_{$form_id}' id='gform_ajax_frame_{$form_id}'" . $iframe_title . ">" . esc_html__('This iframe contains the logic required to handle AJAX powered Gravity Forms.', 'gravityforms') . "</iframe>\n                <script type='text/javascript'>" . apply_filters('gform_cdata_open', '') . '' . 'jQuery(document).ready(function($){' . "gformInitSpinner( {$form_id}, '{$spinner_url}' );" . "jQuery('#gform_ajax_frame_{$form_id}').load( function(){" . "var contents = jQuery(this).contents().find('*').html();" . "var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;" . 'if(!is_postback){return;}' . "var form_content = jQuery(this).contents().find('#gform_wrapper_{$form_id}');" . "var is_confirmation = jQuery(this).contents().find('#gform_confirmation_wrapper_{$form_id}').length > 0;" . "var is_redirect = contents.indexOf('gformRedirect(){') >= 0;" . 'var is_form = form_content.length > 0 && ! is_redirect && ! is_confirmation;' . 'if(is_form){' . "jQuery('#gform_wrapper_{$form_id}').html(form_content.html());" . "if(form_content.hasClass('gform_validation_error')){jQuery('#gform_wrapper_{$form_id}').addClass('gform_validation_error');} else {jQuery('#gform_wrapper_{$form_id}').removeClass('gform_validation_error');}" . "setTimeout( function() { /* delay the scroll by 50 milliseconds to fix a bug in chrome */ {$scroll_position['default']} }, 50 );" . "if(window['gformInitDatepicker']) {gformInitDatepicker();}" . "if(window['gformInitPriceFields']) {gformInitPriceFields();}" . "var current_page = jQuery('#gform_source_page_number_{$form_id}').val();" . "gformInitSpinner( {$form_id}, '{$spinner_url}' );" . "jQuery(document).trigger('gform_page_loaded', [{$form_id}, current_page]);" . "window['gf_submitting_{$form_id}'] = false;" . '}' . 'else if(!is_redirect){' . "var confirmation_content = jQuery(this).contents().find('#gforms_confirmation_message_{$form_id}').html();" . 'if(!confirmation_content){' . 'confirmation_content = contents;' . '}' . 'setTimeout(function(){' . "jQuery('#gform_wrapper_{$form_id}').replaceWith('<' + 'div id=\\'gforms_confirmation_message_{$form_id}\\' class=\\'gform_confirmation_message_{$form_id} gforms_confirmation_message\\'' + '>' + confirmation_content + '<' + '/div' + '>');" . "{$scroll_position['confirmation']}" . "jQuery(document).trigger('gform_confirmation_loaded', [{$form_id}]);" . "window['gf_submitting_{$form_id}'] = false;" . '}, 50);' . '}' . 'else{' . "jQuery('#gform_{$form_id}').append(contents);" . "if(window['gformRedirect']) {gformRedirect();}" . '}' . "jQuery(document).trigger('gform_post_render', [{$form_id}, current_page]);" . '} );' . '} );' . apply_filters('gform_cdata_close', '') . '</script>';
         }
         $is_first_load = !$is_postback;
         if (!$ajax || $is_first_load) {
             self::register_form_init_scripts($form, $field_values, $ajax);
             if (apply_filters('gform_init_scripts_footer', false)) {
                 add_action('wp_footer', create_function('', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');'), 20);
                 add_action('gform_preview_footer', create_function('', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');'));
             } else {
                 $form_string .= self::get_form_init_scripts($form);
                 $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>';
             }
         }
         return gf_apply_filters(array('gform_get_form_filter', $form_id), $form_string, $form);
     } else {
         $progress_confirmation = '';
         //check admin setting for whether the progress bar should start at zero
         $start_at_zero = rgars($form, 'pagination/display_progressbar_on_confirmation');
         $start_at_zero = apply_filters('gform_progressbar_start_at_zero', $start_at_zero, $form);
         //show progress bar on confirmation
         if ($start_at_zero && $has_pages && !$is_admin && ($form['confirmation']['type'] == 'message' && $form['pagination']['type'] == 'percentage')) {
             $progress_confirmation = self::get_progress_bar($form, 0, $confirmation_message);
             if ($ajax) {
                 $progress_confirmation = apply_filters('gform_ajax_iframe_content', "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $progress_confirmation . '</body></html>');
             }
         } else {
             //return regular confirmation message
             if ($ajax) {
                 $progress_confirmation = apply_filters('gform_ajax_iframe_content', "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $confirmation_message . '</body></html>');
             } else {
                 $progress_confirmation = $confirmation_message;
             }
         }
         return $progress_confirmation;
     }
 }
Exemplo n.º 12
0
 function should_field_be_validated($form, $field)
 {
     if ($field['pageNumber'] != GFFormDisplay::get_source_page($form['id'])) {
         return false;
     }
     // if no limits provided for this field
     if (!$this->get_field_limits($field['id'])) {
         return false;
     }
     // or if this field is not a checkbox
     if (RGFormsModel::get_input_type($field) != 'checkbox') {
         return false;
     }
     // or if this field is hidden
     if (RGFormsModel::is_field_hidden($form, $field, array())) {
         return false;
     }
     return true;
 }
 function add_init_script($return)
 {
     $start_field_format = false;
     $end_field_format = false;
     foreach ($this->form['fields'] as &$field) {
         if ($field['id'] == $this->start_field_id) {
             $start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
         }
         if ($field['id'] == $this->end_field_id) {
             $end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
         }
     }
     $script = " \n\t\t\n\t\tnew gwdc({\n                formId:             {$this->form['id']},\n                startFieldId:       {$this->start_field_id},\n                startDateFormat:    '{$start_field_format}',\n                endFieldId:         {$this->end_field_id},\n                endDateFormat:      '{$end_field_format}',\n                countFieldId:       {$this->count_field_id},\n                countAdjust:        {$this->count_adjust}\n            });\n\t\t\t\n\t\t\t";
     $slug = implode('_', array('gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id));
     // GFFormDisplay::add_init_script( $this->form['id'], 'gw_display_count_' . $this->count_field_id, GFFormDisplay::ON_PAGE_RENDER, $script );
     GFFormDisplay::add_init_script($this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script);
     // remove filter so init script is not output on subsequent forms
     remove_filter('gform_init_scripts_footer', array(&$this, 'add_init_script'));
     return $return;
 }
    function get_form($options)
    {
        global $woocommerce;
        $product = null;
        if (function_exists('get_product')) {
            $product = get_product($this->product_id);
        } else {
            $product = new WC_Product($this->product_id);
        }
        extract(shortcode_atts(array('display_title' => true, 'display_description' => true, 'display_inactive' => false, 'field_values' => false, 'ajax' => false, 'tabindex' => 1, 'label_subtotal' => __('Subtotal', 'wc_gf_addons'), 'label_options' => __('Options', 'wc_gf_addons'), 'label_total' => __('Total', 'wc_gf_addons'), 'disable_label_subtotal' => 'no', 'disable_label_options' => 'no', 'disable_label_total' => 'no', 'disable_calculations' => 'no'), $options));
        //Get the form meta so we can make sure the form exists.
        $form_meta = RGFormsModel::get_form_meta($this->form_id);
        if (!empty($form_meta)) {
            if (!empty($_POST)) {
                $_POST['gform_submit'] = isset($_POST['gform_old_submit']) ? $_POST['gform_old_submit'] : '';
                $_POST['gform_old_submit'] = $_POST['gform_submit'];
            }
            $form = RGForms::get_form($this->form_id, $display_title, $display_description, $display_inactive, $field_values, $ajax, $tabindex);
            unset($_POST['gform_submit']);
            $form = str_replace('</form>', '', $form);
            $form = str_replace('gform_submit', 'gform_old_submit', $form);
            $this->current_page = GFFormDisplay::get_current_page($this->form_id);
            $this->next_page = $this->current_page + 1;
            $this->previous_page = $this->current_page - 1;
            $this->next_page = $this->next_page > $this->get_max_page_number($form_meta) ? 0 : $this->next_page;
            if ($product->product_type == 'variable' || $product->product_type == 'variable-subscription') {
                echo '<div class="gform_variation_wrapper gform_wrapper single_variation_wrap">';
            } else {
                echo '<div class="gform_variation_wrapper gform_wrapper">';
            }
            if ($product->is_type('variable')) {
                //echo '<input type="hidden" name="add-to-cart" value="variation" />';
                echo '<input type="hidden" id="product_id" name="product_id" value="' . $this->product_id . '" />';
            } elseif ($product->has_child()) {
                //echo '<input type="hidden" name="add-to-cart" value="group" />';
                echo '<input type="hidden" id="product_id" name="product_id" value="' . $this->product_id . '" />';
            } else {
                //echo '<input type="hidden" name="add-to-cart" value="' . $this->product_id . '" />';
                echo '<input type="hidden" id="product_id" name="product_id" value="' . $this->product_id . '" />';
            }
            if (wc_is_21x()) {
                wp_nonce_field('add_to_cart');
            } else {
                $woocommerce->nonce_field('add_to_cart');
            }
            echo '<a id="_form_' . $this->form_id . '" href="#_form_' . $this->form_id . '" class="gform_anchor"></a>';
            echo $form;
            echo '<input type="hidden" name="gform_form_id" id="gform_form_id" value="' . $this->form_id . '" />';
            echo '<input type="hidden" id="woocommerce_get_action" value="" />';
            echo '<input type="hidden" id="woocommerce_product_base_price" value="' . $product->get_price() . '" />';
            $description_class = rgar($form_meta, "descriptionPlacement") == "above" ? "description_above" : "description_below";
            ?>

			<?php 
            $this->on_print_scripts();
            if ($disable_calculations == 'no') {
                ?>

				<div class="product_totals">
					<ul id="gform_totals_<?php 
                echo $this->form_id;
                ?>
" class="gform_fields <?php 
                echo $form_meta['labelPlacement'] . ' ' . $description_class;
                ?>
">
						<li class="gfield" <?php 
                if ($disable_label_subtotal == 'yes') {
                    echo 'style="display:none;"';
                }
                ?>
 >
							<label class="gfield_label"><?php 
                echo $label_subtotal;
                ?>
</label>
							<div class="ginput_container">
								<span class="formattedBasePrice ginput_total"></span>
							</div>
						</li>
						<li class="gfield" <?php 
                if ($disable_label_options == 'yes') {
                    echo 'style="display:none;"';
                }
                ?>
 >
							<label class="gfield_label"><?php 
                echo $label_options;
                ?>
</label>
							<div class="ginput_container">
								<span class="formattedVariationTotal ginput_total"></span>
							</div>
						</li>
						<li class="gfield" <?php 
                if ($disable_label_total == 'yes') {
                    echo 'style="display:none;"';
                }
                ?>
 >
							<label class="gfield_label"><?php 
                echo $label_total;
                ?>
</label>
							<div class="ginput_container">
								<span class="formattedTotalPrice ginput_total"></span>
							</div>
						</li>
					</ul>
				</div>
				<style>
					.single_variation .price {
						display:none !important;
					}
				</style>
			<?php 
            }
            ?>
			<style>
				.hidden-total {
					display:none !important;
				}
			</style>



			<?php 
            echo '</div>';
        }
    }
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title><?php 
echo esc_html($form['title']);
?>
</title>
<style type="text/css">
body {
	padding: 0;
	font-family: sans-serif;
	font-size: 13px;
}
</style>
</head>
<body>
<?php 
GFFormDisplay::print_form_scripts($form_id, false);
// ajax = false
gravity_form($form_id, $display_title, $display_description);
wp_footer();
?>
</body>
</html>
 public function maybe_save_confirmation()
 {
     /* On paged forms all processing is suppressed, so we still need to do something */
     $form_id = isset($_POST['gform_submit']) ? $_POST['gform_submit'] : 0;
     if (!$form_id) {
         return;
     }
     if (!isset($_POST['gform_save_state_' . $form_id])) {
         return;
     }
     $form_info = RGFormsModel::get_form($form_id);
     $is_valid_form = $form_info && $form_info->is_active;
     if (!$is_valid_form) {
         return;
     }
     $form = RGFormsModel::get_form_meta($form_id);
     if (!isset($form['requireLogin']) || !isset($form['enableFormState'])) {
         return;
     }
     if (!$form['requireLogin'] || !$form['enableFormState']) {
         return;
     }
     if (!GFCommon::has_pages($form)) {
         return;
     }
     /* Spoof the page number and make-believe */
     $_POST["gform_target_page_number_{$form_id}"] = 65535;
     require_once GFCommon::get_base_path() . '/form_display.php';
     GFFormDisplay::process_form($form_id);
 }
Exemplo n.º 17
0
        <link rel='stylesheet' href='<?php 
echo GFCommon::get_base_url();
?>
/css/reset.css' type='text/css' />
        <link rel='stylesheet' href='<?php 
echo GFCommon::get_base_url();
?>
/css/forms.css' type='text/css' />
        <link rel='stylesheet' href='<?php 
echo GFCommon::get_base_url();
?>
/css/preview.css' type='text/css' />
        <?php 
require_once GFCommon::get_base_path() . "/form_display.php";
$form = RGFormsModel::get_form_meta($_GET["id"]);
GFFormDisplay::enqueue_form_scripts($form);
wp_print_scripts();
$styles = apply_filters("gform_preview_styles", false, $form);
if (!empty($styles)) {
    wp_print_styles($styles);
}
?>

    </head>
    <body>
    <div id="preview_top">
	    <div id="preview_hdr">
		    <div><span class="actionlinks"><a href="javascript:window.close()" class="close_window"><?php 
_e("close window", "gravityforms");
?>
</a></span><?php 
Exemplo n.º 18
0
 public static function gform_do_shortcode($content)
 {
     $is_ajax = false;
     $forms = GFFormDisplay::get_embedded_forms($content, $is_ajax);
     foreach ($forms as $form) {
         GFFormDisplay::print_form_scripts($form, $is_ajax);
     }
     return do_shortcode($content);
 }
Exemplo n.º 19
0
 public function validate_credit_card($validation_result)
 {
     if (!$this->has_feed($validation_result['form']['id'], true)) {
         return $validation_result;
     }
     foreach ($validation_result['form']['fields'] as &$field) {
         $current_page = GFFormDisplay::get_source_page($validation_result['form']['id']);
         $field_on_curent_page = $current_page > 0 && $field['pageNumber'] == $current_page;
         if (GFFormsModel::get_input_type($field) != 'creditcard' || !$field_on_curent_page) {
             continue;
         }
         if ($this->get_stripe_js_error()) {
             $field['failed_validation'] = true;
             $field['validation_message'] = $this->get_stripe_js_error();
         } else {
             // override validation in case user has marked field as required allowing stripe to handle cc validation
             $field['failed_validation'] = false;
         }
         // only one cc field per form, break once we've found it
         break;
     }
     // revalidate the validaiton result
     $validation_result['is_valid'] = true;
     foreach ($validation_result['form']['fields'] as &$field) {
         if ($field['failed_validation']) {
             $validation_result['is_valid'] = false;
             break;
         }
     }
     return $validation_result;
 }
Exemplo n.º 20
0
 /**
  * Prepare Javascript for creating credit card tokens.
  *
  * @access public
  *
  * @param array $form
  * @param array $field_values
  * @param bool $is_ajax
  *
  * @return void
  */
 public function register_creditcard_token_script($form, $field_values, $is_ajax)
 {
     if (!$this->enqueue_creditcard_token_script($form)) {
         return;
     }
     /* Prepare GFToken object. */
     $gftoken = array('callback' => 'GF_' . str_replace(' ', '', $this->_short_title), 'feeds' => $this->creditcard_token_info($form), 'formId' => rgar($form, 'id'), 'hasPages' => GFCommon::has_pages($form), 'pageCount' => GFFormDisplay::get_max_page_number($form), 'responseField' => '#gf_' . str_replace('gravityforms', '', $this->_slug) . '_response');
     /* Get needed fields. */
     $gftoken['fields'] = $this->get_creditcard_token_entry_fields($gftoken['feeds']);
     $script = 'new GFToken( ' . json_encode($gftoken) . ' );';
     GFFormDisplay::add_init_script($form['id'], 'GFToken', GFFormDisplay::ON_PAGE_RENDER, $script);
 }
 public static function print_form_scripts($form, $ajax)
 {
     require_once GFCommon::get_base_path() . "/form_display.php";
     GFFormDisplay::print_form_scripts($form, $ajax);
 }
 public static function change_input_type()
 {
     check_ajax_referer('rg_change_input_type', 'rg_change_input_type');
     $field_json = stripslashes_deep($_POST["field"]);
     $field = GFCommon::json_decode($field_json, true);
     $id = $field["id"];
     $type = $field["inputType"];
     require_once GFCommon::get_base_path() . "/form_display.php";
     $field_content = GFFormDisplay::get_field_content($field, "");
     die("EndChangeInputType('{$id}', '{$type}', \"{$field_content}\");");
 }
Exemplo n.º 23
0
 public static function maybe_thankyou_page()
 {
     if (!self::is_gravityforms_supported()) {
         return;
     }
     if ($str = RGForms::get("gf_paypal_return")) {
         $str = base64_decode($str);
         parse_str($str, $query);
         if (wp_hash("ids=" . $query["ids"]) == $query["hash"]) {
             list($form_id, $lead_id) = explode("|", $query["ids"]);
             $form = RGFormsModel::get_form_meta($form_id);
             $lead = RGFormsModel::get_lead($lead_id);
             if (!class_exists("GFFormDisplay")) {
                 require_once GFCommon::get_base_path() . "/form_display.php";
             }
             $confirmation = GFFormDisplay::handle_confirmation($form, $lead, false);
             if (is_array($confirmation) && isset($confirmation["redirect"])) {
                 header("Location: {$confirmation["redirect"]}");
                 exit;
             }
             GFFormDisplay::$submission[$form_id] = array("is_confirmation" => true, "confirmation_message" => $confirmation, "form" => $form, "lead" => $lead);
         }
     }
 }
Exemplo n.º 24
0
 public static function maybe_thankyou_page()
 {
     $instance = self::get_instance();
     if (!$instance->is_gravityforms_supported()) {
         return;
     }
     if ($str = rgget('gf_paypal_return')) {
         $str = base64_decode($str);
         parse_str($str, $query);
         if (wp_hash('ids=' . $query['ids']) == $query['hash']) {
             list($form_id, $lead_id) = explode('|', $query['ids']);
             $form = GFAPI::get_form($form_id);
             $lead = GFAPI::get_entry($lead_id);
             if (!class_exists('GFFormDisplay')) {
                 require_once GFCommon::get_base_path() . '/form_display.php';
             }
             $confirmation = GFFormDisplay::handle_confirmation($form, $lead, false);
             if (is_array($confirmation) && isset($confirmation['redirect'])) {
                 header("Location: {$confirmation['redirect']}");
                 exit;
             }
             GFFormDisplay::$submission[$form_id] = array('is_confirmation' => true, 'confirmation_message' => $confirmation, 'form' => $form, 'lead' => $lead);
         }
     }
 }
Exemplo n.º 25
0
 /**
  * Registers the script returned by get_form_inline_script_on_page_render() for display on the front-end.
  *
  * @param array $form The Form Object currently being processed.
  */
 public function register_form_init_scripts($form)
 {
     GFFormDisplay::add_init_script($form['id'], $this->type . '_' . $this->id, GFFormDisplay::ON_PAGE_RENDER, $this->get_form_inline_script_on_page_render($form));
 }
Exemplo n.º 26
0
 /**
  * Submits a form. Use this function to send input values through the complete form submission process.
  * Supports field validation, notifications, confirmations, multiple-pages and save & continue.
  *
  * Example usage:
  * $input_values['input_1']   = 'Single line text';
  * $input_values['input_2_3'] = 'First name';
  * $input_values['input_2_6'] = 'Last name';
  * $input_values['input_5']   = 'A paragraph of text.';
  * //$input_values['gform_save'] = true; // support for save and continue
  *
  * $result = GFAPI::submit_form( 52, $input_values );
  *
  * Example output for a successful submission:
  * 'is_valid' => boolean true
  * 'page_number' => int 0
  * 'source_page_number' => int 1
  * 'confirmation_message' => string 'confirmation message [snip]'
  *
  * Example output for failed validation:
  * 'is_valid' => boolean false
  * 'validation_messages' =>
  *      array (size=1)
  *          2 => string 'This field is required. Please enter the first and last name.'
  *	'page_number' => int 1
  *  'source_page_number' => int 1
  *	'confirmation_message' => string ''
  *
  *
  * Example output for save and continue:
  * 'is_valid' => boolean true
  * 'page_number' => int 1
  * 'source_page_number' => int 1
  * 'confirmation_message' => string 'Please use the following link to return to your form from any computer. [snip]'
  * 'resume_token' => string '045f941cc4c04d479556bab1db6d3495'
  *
  *
  * @param int $form_id The Form ID
  * @param array $input_values An array of values. Not $_POST, that will be automatically merged with the $input_values.
  * @param array $field_values Optional.
  * @param int $target_page Optional.
  * @param int $source_page Optional.
  *
  * @return array An array containing the result of the submission.
  */
 public static function submit_form($form_id, $input_values, $field_values = array(), $target_page = 0, $source_page = 1)
 {
     $form_id = absint($form_id);
     $form = GFAPI::get_form($form_id);
     if (empty($form) || !$form['is_active'] || $form['is_trash']) {
         return new WP_Error('form_not_found', __('Your form could not be found', 'gravityforms'));
     }
     $input_values['is_submit_' . $form_id] = true;
     $input_values['gform_submit'] = $form_id;
     $input_values['gform_target_page_number_' . $form_id] = absint($target_page);
     $input_values['gform_source_page_number_' . $form_id] = absint($source_page);
     $input_values['gform_field_values'] = $field_values;
     require_once GFCommon::get_base_path() . '/form_display.php';
     if (!isset($_POST)) {
         $_POST = array();
     }
     $_POST = array_merge_recursive($_POST, $input_values);
     try {
         GFFormDisplay::process_form($form_id);
     } catch (Exception $ex) {
         return new WP_Error('error_processing_form', __('There was an error while processing the form:', 'gravityforms') . ' ' . $ex->getCode() . ' ' . $ex->getMessage());
     }
     if (empty(GFFormDisplay::$submission)) {
         return new WP_Error('error_processing_form', __('There was an error while processing the form:', 'gravityforms'));
     }
     $submissions_array = GFFormDisplay::$submission;
     $submission_details = $submissions_array[$form_id];
     $result = array();
     $result['is_valid'] = $submission_details['is_valid'];
     if ($result['is_valid'] == false) {
         $validation_messages = array();
         foreach ($submission_details['form']['fields'] as $field) {
             if ($field->failed_validation) {
                 $validation_messages[$field->id] = $field->validation_message;
             }
         }
         $result['validation_messages'] = $validation_messages;
     }
     $result['page_number'] = $submission_details['page_number'];
     $result['source_page_number'] = $submission_details['source_page_number'];
     $result['confirmation_message'] = $submission_details['confirmation_message'];
     if (isset($submission_details['resume_token'])) {
         $result['resume_token'] = $submission_details['resume_token'];
         $form = self::get_form($form_id);
         $result['confirmation_message'] = GFFormDisplay::replace_save_variables($result['confirmation_message'], $form, $result['resume_token']);
     }
     return $result;
 }
 function is_last_page($form)
 {
     $page_number = GFFormDisplay::get_current_page($form['id']);
     $last_page = count($form['pagination']['pages']);
     return $page_number >= $last_page;
 }
Exemplo n.º 28
0
 /**
  * Make validation work for Edit Entry
  *
  * Because we're calling the GFFormDisplay::validate() in an unusual way (as a front-end
  * form pretending to be a back-end form), validate() doesn't know we _can't_ edit post
  * fields. This goes through all the fields and if they're an invalid post field, we
  * set them as valid. If there are still issues, we'll return false.
  *
  * @param  [type] $validation_results [description]
  * @return [type]                     [description]
  */
 function custom_validation($validation_results)
 {
     do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results: ', $validation_results);
     do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] $_POSTed data (sanitized): ', esc_html(print_r($_POST, true)));
     $gv_valid = true;
     foreach ($validation_results['form']['fields'] as $key => &$field) {
         $value = RGFormsModel::get_field_value($field);
         $field_type = RGFormsModel::get_input_type($field);
         // Validate always
         switch ($field_type) {
             case 'fileupload':
                 // in case nothing is uploaded but there are already files saved
                 if (!empty($field->failed_validation) && !empty($field->isRequired) && !empty($value)) {
                     $field->failed_validation = false;
                     unset($field->validation_message);
                 }
                 // validate if multi file upload reached max number of files [maxFiles] => 2
                 if (rgar($field, 'maxFiles') && rgar($field, 'multipleFiles')) {
                     $input_name = 'input_' . $field->id;
                     //uploaded
                     $file_names = isset(GFFormsModel::$uploaded_files[$validation_results['form']['id']][$input_name]) ? GFFormsModel::$uploaded_files[$validation_results['form']['id']][$input_name] : array();
                     //existent
                     $entry = $this->get_entry();
                     $value = NULL;
                     if (isset($entry[$field->id])) {
                         $value = json_decode($entry[$field->id], true);
                     }
                     // count uploaded files and existent entry files
                     $count_files = count($file_names) + count($value);
                     if ($count_files > $field->maxFiles) {
                         $field->validation_message = __('Maximum number of files reached', 'gravityview');
                         $field->failed_validation = 1;
                         $gv_valid = false;
                         // in case of error make sure the newest upload files are removed from the upload input
                         GFFormsModel::$uploaded_files[$validation_results['form']['id']] = null;
                     }
                 }
                 break;
         }
         // This field has failed validation.
         if (!empty($field->failed_validation)) {
             do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field is invalid.', array('field' => $field, 'value' => $value));
             switch ($field_type) {
                 // Captchas don't need to be re-entered.
                 case 'captcha':
                     // Post Image fields aren't editable, so we un-fail them.
                 // Post Image fields aren't editable, so we un-fail them.
                 case 'post_image':
                     $field->failed_validation = false;
                     unset($field->validation_message);
                     break;
             }
             // You can't continue inside a switch, so we do it after.
             if (empty($field->failed_validation)) {
                 continue;
             }
             // checks if the No Duplicates option is not validating entry against itself, since
             // we're editing a stored entry, it would also assume it's a duplicate.
             if (!empty($field->noDuplicates)) {
                 $entry = $this->get_entry();
                 // If the value of the entry is the same as the stored value
                 // Then we can assume it's not a duplicate, it's the same.
                 if (!empty($entry) && $value == $entry[$field->id]) {
                     //if value submitted was not changed, then don't validate
                     $field->failed_validation = false;
                     unset($field->validation_message);
                     do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Field not a duplicate; it is the same entry.', $entry);
                     continue;
                 }
             }
             // if here then probably we are facing the validation 'At least one field must be filled out'
             if (GFFormDisplay::is_empty($field, $this->form_id) && empty($field->isRequired)) {
                 unset($field->validation_message);
                 $field->validation_message = false;
                 continue;
             }
             $gv_valid = false;
         }
     }
     $validation_results['is_valid'] = $gv_valid;
     do_action('gravityview_log_debug', 'GravityView_Edit_Entry[custom_validation] Validation results.', $validation_results);
     // We'll need this result when rendering the form ( on GFFormDisplay::get_form )
     $this->form_after_validation = $validation_results['form'];
     return $validation_results;
 }
Exemplo n.º 29
0
 public static function enqueue_form_scripts($form_id, $is_ajax = false)
 {
     require_once GFCommon::get_base_path() . '/form_display.php';
     $form = RGFormsModel::get_form_meta($form_id);
     GFFormDisplay::enqueue_form_scripts($form, $is_ajax);
     $addons = GFAddOn::get_registered_addons();
     foreach ($addons as $addon) {
         $a = call_user_func(array($addon, 'get_instance'));
         $a->enqueue_scripts($form, $is_ajax);
     }
 }
 public function validation($validation_result)
 {
     if (!$validation_result['is_valid'] || !GFFormDisplay::is_last_page($validation_result['form'])) {
         return $validation_result;
     }
     $form = $validation_result['form'];
     $entry = GFFormsModel::create_lead($form);
     $feed = $this->get_payment_feed($entry, $form);
     if (!$feed) {
         return $validation_result;
     }
     $submission_data = $this->get_submission_data($feed, $form, $entry);
     //Do not process payment if payment amount is 0 or less
     if (intval($submission_data['payment_amount']) <= 0) {
         $this->log_debug('Payment amount is $0.00 or less. Not sending to payment gateway.');
         return $validation_result;
     }
     $this->is_payment_gateway = true;
     $this->current_feed = $feed;
     $this->current_submission_data = $submission_data;
     $performed_authorization = false;
     $is_subscription = $feed["meta"]["transactionType"] == "subscription";
     if ($this->payment_method_is_overridden('authorize') && !$is_subscription) {
         //Running an authorization only transaction if function is implemented and this is a single payment
         $this->authorization = $this->authorize($feed, $submission_data, $form, $entry);
         $performed_authorization = true;
     } else {
         if ($this->payment_method_is_overridden('subscribe') && $is_subscription) {
             $subscription = $this->subscribe($feed, $submission_data, $form, $entry);
             $this->authorization['is_authorized'] = $subscription['is_success'];
             $this->authorization['error_message'] = rgar($subscription, 'error_message');
             $this->authorization['subscription'] = $subscription;
             $performed_authorization = true;
         }
     }
     if ($performed_authorization && !$this->authorization['is_authorized']) {
         $validation_result = $this->get_validation_result($validation_result, $this->authorization);
         //Setting up current page to point to the credit card page since that will be the highlighted field
         GFFormDisplay::set_current_page($validation_result['form']['id'], $validation_result['credit_card_page']);
     }
     return $validation_result;
 }