PageRenderTime 69ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/plugins/gravityforms/form_display.php

https://github.com/petergibbons/OpenCounterWP
PHP | 2273 lines | 2022 code | 195 blank | 56 comment | 205 complexity | a191c52941c7534290aaeb132dcaa2d6 MD5 | raw file
  1. <?php
  2. class GFFormDisplay{
  3. public static $submission = array();
  4. private static $init_scripts = array();
  5. const ON_PAGE_RENDER = 1;
  6. const ON_CONDITIONAL_LOGIC = 2;
  7. public static function process_form($form_id){
  8. //reading form metadata
  9. $form = RGFormsModel::get_form_meta($form_id);
  10. $form = RGFormsModel::add_default_properties($form);
  11. $lead = array();
  12. $field_values = RGForms::post("gform_field_values");
  13. $confirmation_message = "";
  14. $source_page_number = self::get_source_page($form_id);
  15. $page_number = $source_page_number;
  16. $target_page = self::get_target_page($form, $page_number, $field_values);
  17. //Loading files that have been uploaded to temp folder
  18. $files = GFCommon::json_decode(stripslashes(RGForms::post("gform_uploaded_files")));
  19. if(!is_array($files))
  20. $files = array();
  21. RGFormsModel::$uploaded_files[$form["id"]] = $files;
  22. $is_valid = true;
  23. //don't validate when going to previous page
  24. if(empty($target_page) || $target_page >= $page_number){
  25. $is_valid = self::validate($form, $field_values, $page_number);
  26. }
  27. //Upload files to temp folder when going to the next page or when submitting the form and it failed validation
  28. if( $target_page >= $page_number || ($target_page == 0 && !$is_valid) ){
  29. //Uploading files to temporary folder
  30. $files = self::upload_files($form, $files);
  31. RGFormsModel::$uploaded_files[$form["id"]] = $files;
  32. }
  33. // Load target page if it did not fail validation or if going to the previous page
  34. if($is_valid){
  35. $page_number = $target_page;
  36. }
  37. $confirmation = "";
  38. if($is_valid && $page_number == 0){
  39. $ajax = isset($_POST["gform_ajax"]);
  40. //adds honeypot field if configured
  41. if(rgar($form,"enableHoneypot"))
  42. $form["fields"][] = self::get_honeypot_field($form);
  43. $failed_honeypot = rgar($form,"enableHoneypot") && !self::validate_honeypot($form);
  44. if($failed_honeypot){
  45. //display confirmation but doesn't process the form when honeypot fails
  46. $confirmation = self::handle_confirmation($form, $lead, $ajax);
  47. $is_valid = false;
  48. }
  49. else{
  50. //pre submission action
  51. do_action("gform_pre_submission", $form);
  52. do_action("gform_pre_submission_{$form["id"]}", $form);
  53. //pre submission filter
  54. $form = apply_filters("gform_pre_submission_filter_{$form["id"]}", apply_filters("gform_pre_submission_filter", $form));
  55. //handle submission
  56. $confirmation = self::handle_submission($form, $lead, $ajax);
  57. //after submission hook
  58. do_action("gform_after_submission", $lead, $form);
  59. do_action("gform_after_submission_{$form["id"]}", $lead, $form);
  60. }
  61. if(is_array($confirmation) && isset($confirmation["redirect"])){
  62. header("Location: {$confirmation["redirect"]}");
  63. do_action("gform_post_submission", $lead, $form);
  64. do_action("gform_post_submission_{$form["id"]}", $lead, $form);
  65. exit;
  66. }
  67. }
  68. if(!isset(self::$submission[$form_id]))
  69. self::$submission[$form_id] = array();
  70. self::set_submission_if_null($form_id, "is_valid", $is_valid);
  71. self::set_submission_if_null($form_id, "form", $form);
  72. self::set_submission_if_null($form_id, "lead", $lead);
  73. self::set_submission_if_null($form_id, "confirmation_message", $confirmation);
  74. self::set_submission_if_null($form_id, "page_number", $page_number);
  75. self::set_submission_if_null($form_id, "source_page_number", $source_page_number);
  76. }
  77. private static function set_submission_if_null($form_id, $key, $val){
  78. if(!isset(self::$submission[$form_id][$key]))
  79. self::$submission[$form_id][$key] = $val;
  80. }
  81. private static function upload_files($form, $files){
  82. //Creating temp folder if it does not exist
  83. $target_path = RGFormsModel::get_upload_path($form["id"]) . "/tmp/";
  84. wp_mkdir_p($target_path);
  85. foreach($form["fields"] as $field){
  86. $input_name = "input_{$field["id"]}";
  87. //skip fields that are not file upload fields or that don't have a file to be uploaded or that have failed validation
  88. $input_type = RGFormsModel::get_input_type($field);
  89. if(!in_array($input_type, array("fileupload", "post_image")) || $field["failed_validation"] || empty($_FILES[$input_name]["name"])){
  90. continue;
  91. }
  92. $file_info = RGFormsModel::get_temp_filename($form["id"], $input_name);
  93. if($file_info && move_uploaded_file($_FILES[$input_name]['tmp_name'], $target_path . $file_info["temp_filename"])){
  94. $files[$input_name] = $file_info["uploaded_filename"];
  95. }
  96. }
  97. return $files;
  98. }
  99. public static function get_state($form, $field_values){
  100. $product_fields = array();
  101. foreach($form["fields"] as $field){
  102. if(GFCommon::is_product_field($field["type"]) || $field["type"] == "donation"){
  103. $value = RGFormsModel::get_field_value($field, $field_values, false);
  104. $value = self::default_if_empty($field, $value);
  105. switch($field["inputType"]){
  106. case "calculation" :
  107. case "singleproduct" :
  108. case "hiddenproduct" :
  109. $price = !is_array($value) || empty($value[$field["id"] . ".2"]) ? $field["basePrice"] : $value[$field["id"] . ".2"];
  110. if(empty($price))
  111. $price = 0;
  112. $price = GFCommon::to_number($price);
  113. $product_name = !is_array($value) || empty($value[$field["id"] . ".1"]) ? $field["label"] : $value[$field["id"] . ".1"];
  114. $product_fields[$field["id"]. ".1"] = wp_hash($product_name);
  115. $product_fields[$field["id"]. ".2"] = wp_hash($price);
  116. break;
  117. case "singleshipping" :
  118. $price = !empty($value) ? $value : $field["basePrice"];
  119. $price = GFCommon::to_number($price);
  120. $product_fields[$field["id"]] = wp_hash($price);
  121. break;
  122. case "radio" :
  123. case "select" :
  124. $product_fields[$field["id"]] = array();
  125. foreach($field["choices"] as $choice){
  126. $field_value = !empty($choice["value"]) || rgar($field,"enableChoiceValue") ? $choice["value"] : $choice["text"];
  127. if($field["enablePrice"])
  128. $field_value .= "|" . GFCommon::to_number(rgar($choice,"price"));
  129. $product_fields[$field["id"]][] = wp_hash($field_value);
  130. }
  131. break;
  132. case "checkbox" :
  133. $index = 1;
  134. foreach($field["choices"] as $choice){
  135. $field_value = !empty($choice["value"]) || $field["enableChoiceValue"] ? $choice["value"] : $choice["text"];
  136. if($field["enablePrice"])
  137. $field_value .= "|" . GFCommon::to_number($choice["price"]);
  138. if($index % 10 == 0) //hack to skip numbers ending in 0. so that 5.1 doesn't conflict with 5.10
  139. $index++;
  140. $product_fields[$field["id"] . "." . $index++] = wp_hash($field_value);
  141. }
  142. break;
  143. }
  144. }
  145. }
  146. $hash = serialize($product_fields);
  147. $checksum = wp_hash(crc32($hash));
  148. return base64_encode(serialize(array($hash, $checksum)));
  149. }
  150. private static function has_pages($form){
  151. return GFCommon::has_pages($form);
  152. }
  153. private static function has_character_counter($form){
  154. if(!is_array($form["fields"]))
  155. return false;
  156. foreach($form["fields"] as $field){
  157. if(rgar($field, "maxLength") && !rgar($field, "inputMask"))
  158. return true;
  159. }
  160. return false;
  161. }
  162. private static function has_enhanced_dropdown($form){
  163. if(!is_array($form["fields"]))
  164. return false;
  165. foreach($form["fields"] as $field){
  166. if(in_array(RGFormsModel::get_input_type($field), array("select", "multiselect")) && rgar($field, "enableEnhancedUI"))
  167. return true;
  168. }
  169. return false;
  170. }
  171. private static function has_password_strength($form){
  172. if(!is_array($form["fields"]))
  173. return false;
  174. foreach($form["fields"] as $field){
  175. if($field["type"] == "password" && RGForms::get("passwordStrengthEnabled", $field))
  176. return true;
  177. }
  178. return false;
  179. }
  180. private static function has_other_choice($form){
  181. if(!is_array($form["fields"]))
  182. return false;
  183. foreach($form["fields"] as $field){
  184. if($field["type"] == "radio" && rgget("enableOtherChoice", $field))
  185. return true;
  186. }
  187. return false;
  188. }
  189. public static function get_target_page($form, $current_page, $field_values){
  190. $page_number = RGForms::post("gform_target_page_number_{$form["id"]}");
  191. $page_number = !is_numeric($page_number) ? 1 : $page_number;
  192. $direction = $page_number >= $current_page ? 1 : -1;
  193. //Finding next page that is not hidden by conditional logic
  194. while(RGFormsModel::is_page_hidden($form, $page_number, $field_values)){
  195. $page_number += $direction;
  196. }
  197. //If all following pages are hidden, submit the form
  198. if($page_number > self::get_max_page_number($form))
  199. $page_number = 0;
  200. return $page_number;
  201. }
  202. public static function get_source_page($form_id){
  203. $page_number = RGForms::post("gform_source_page_number_{$form_id}");
  204. return !is_numeric($page_number) ? 1 : $page_number;
  205. }
  206. public static function set_current_page($form_id, $page_number){
  207. self::$submission[$form_id]["page_number"] = $page_number;
  208. }
  209. public static function get_current_page($form_id){
  210. $page_number = isset(self::$submission[$form_id]) ? self::$submission[$form_id]["page_number"] : 1;
  211. return $page_number;
  212. }
  213. private static function is_page_active($form_id, $page_number){
  214. return intval(self::get_current_page($form_id)) == intval($page_number);
  215. }
  216. private static function get_limit_period_dates($period){
  217. if(empty($period))
  218. return array("start_date" => null, "end_date" => null);
  219. switch($period){
  220. case "day" :
  221. return array(
  222. "start_date" => gmdate("Y-m-d"),
  223. "end_date" => gmdate("Y-m-d"));
  224. break;
  225. case "week" :
  226. return array(
  227. "start_date" => gmdate("Y-m-d", strtotime("last Monday")),
  228. "end_date" => gmdate("Y-m-d", strtotime("next Sunday")));
  229. break;
  230. case "month" :
  231. $month_start = gmdate("Y-m-1");
  232. return array(
  233. "start_date" => $month_start,
  234. "end_date" => gmdate("Y-m-d", strtotime("{$month_start} +1 month - 1 hour")));
  235. break;
  236. case "year" :
  237. return array(
  238. "start_date" => gmdate("Y-1-1"),
  239. "end_date" => gmdate("Y-12-31"));
  240. break;
  241. }
  242. }
  243. public static function get_form($form_id, $display_title=true, $display_description=true, $force_display=false, $field_values=null, $ajax=false, $tabindex = 1){
  244. //looking up form id by form name
  245. if(!is_numeric($form_id))
  246. $form_id = RGFormsModel::get_form_id($form_id);
  247. //reading form metadata
  248. $form = RGFormsModel::get_form_meta($form_id, true);
  249. $form = RGFormsModel::add_default_properties($form);
  250. //disable ajax if form has a reCAPTCHA field (not supported).
  251. if($ajax && self::has_recaptcha_field($form))
  252. $ajax = false;
  253. $is_postback = false;
  254. $is_valid = true;
  255. $confirmation_message = "";
  256. $page_number = 1;
  257. //If form was submitted, read variables set during form submission procedure
  258. $submission_info = isset(self::$submission[$form_id]) ? self::$submission[$form_id] : false;
  259. if($submission_info){
  260. $is_postback = true;
  261. $is_valid = rgar($submission_info, "is_valid") || rgar($submission_info, "is_confirmation");
  262. $form = $submission_info["form"];
  263. $lead = $submission_info["lead"];
  264. $confirmation_message = rgget("confirmation_message", $submission_info);
  265. if($is_valid && !RGForms::get("is_confirmation", $submission_info)){
  266. if($submission_info["page_number"] == 0){
  267. //post submission hook
  268. do_action("gform_post_submission", $lead, $form);
  269. do_action("gform_post_submission_{$form["id"]}", $lead, $form);
  270. }
  271. else{
  272. //change page hook
  273. do_action("gform_post_paging", $form, $submission_info["source_page_number"], $submission_info["page_number"]);
  274. do_action("gform_post_paging_{$form["id"]}", $form, $submission_info["source_page_number"], $submission_info["page_number"]);
  275. }
  276. }
  277. }
  278. else if(!current_user_can("administrator")){
  279. RGFormsModel::insert_form_view($form_id, $_SERVER['REMOTE_ADDR']);
  280. }
  281. if(rgar($form,"enableHoneypot"))
  282. $form["fields"][] = self::get_honeypot_field($form);
  283. //Fired right before the form rendering process. Allow users to manipulate the form object before it gets displayed in the front end
  284. $form = apply_filters("gform_pre_render_$form_id", apply_filters("gform_pre_render", $form, $ajax), $ajax);
  285. if($form == null)
  286. return "<p>" . __("Oops! We could not locate your form.", "gravityforms") . "</p>";
  287. $has_pages = self::has_pages($form);
  288. //calling tab index filter
  289. GFCommon::$tab_index = apply_filters("gform_tabindex_{$form_id}", apply_filters("gform_tabindex", $tabindex, $form), $form);
  290. //Don't display inactive forms
  291. if(!$force_display && !$is_postback) {
  292. $form_info = RGFormsModel::get_form($form_id);
  293. if(!$form_info->is_active)
  294. return "";
  295. // If form requires login, check if user is logged in
  296. if(rgar($form, "requireLogin")) {
  297. if(!is_user_logged_in())
  298. 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>";
  299. }
  300. }
  301. // show the form regardless of the following validations when force display is set to true
  302. if(!$force_display) {
  303. $form_schedule_validation = self::validate_form_schedule($form);
  304. // if form schedule validation fails AND this is not a postback, display the validation error
  305. // if form schedule validation fails AND this is a postback, make sure is not a valid submission (enables display of confirmation message)
  306. if( ($form_schedule_validation && !$is_postback) || ($form_schedule_validation && $is_postback && !$is_valid) )
  307. return $form_schedule_validation;
  308. $entry_limit_validation = self::validate_entry_limit($form);
  309. // refer to form schedule condition notes above
  310. if( ($entry_limit_validation && !$is_postback) || ($entry_limit_validation && $is_postback && !$is_valid) )
  311. return $entry_limit_validation;
  312. }
  313. $form_string = "";
  314. //When called via a template, this will enqueue the proper scripts
  315. //When called via a shortcode, this will be ignored (too late to enqueue), but the scripts will be enqueued via the enqueue_scripts event
  316. self::enqueue_form_scripts($form, $ajax);
  317. if(empty($confirmation_message)){
  318. $wrapper_css_class = GFCommon::get_browser_class() . " gform_wrapper";
  319. if(!$is_valid)
  320. $wrapper_css_class .=" gform_validation_error";
  321. //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.
  322. $style = self::has_conditional_logic($form) ? "style='display:none'" : "";
  323. $custom_wrapper_css_class = !empty($form["cssClass"]) ? " {$form["cssClass"]}_wrapper": "";
  324. $form_string .= "
  325. <div class='{$wrapper_css_class}{$custom_wrapper_css_class}' id='gform_wrapper_$form_id' " . $style . ">";
  326. $action = add_query_arg(array());
  327. $default_anchor = $has_pages || $ajax ? true : false;
  328. $use_anchor = apply_filters("gform_confirmation_anchor_{$form["id"]}", apply_filters("gform_confirmation_anchor", $default_anchor));
  329. if($use_anchor !== false){
  330. $form_string .="<a id='gf_$form_id' name='gf_$form_id' class='gform_anchor' ></a>";
  331. $action .= "#gf_$form_id";
  332. }
  333. $target = $ajax ? "target='gform_ajax_frame_{$form_id}'" : "";
  334. $form_css_class = !empty($form["cssClass"]) ? "class='{$form["cssClass"]}'": "";
  335. $action = esc_attr($action);
  336. $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);
  337. if($display_title || $display_description){
  338. $form_string .= "
  339. <div class='gform_heading'>";
  340. if($display_title){
  341. $form_string .= "
  342. <h3 class='gform_title'>" . $form['title'] . "</h3>";
  343. }
  344. if($display_description){
  345. $form_string .= "
  346. <span class='gform_description'>" . rgar($form,'description') ."</span>";
  347. }
  348. $form_string .= "
  349. </div>";
  350. }
  351. $current_page = self::get_current_page($form_id);
  352. if($has_pages && !IS_ADMIN){
  353. $page_count = self::get_max_page_number($form);
  354. if($form["pagination"]["type"] == "percentage"){
  355. $form_string .= self::get_progress_bar($form, $form_id,$confirmation_message);
  356. }
  357. else if($form["pagination"]["type"] == "steps"){
  358. $form_string .="
  359. <div id='gf_page_steps_{$form_id}' class='gf_page_steps'>";
  360. for($i=0, $count = sizeof($form["pagination"]["pages"]); $i<$count; $i++){
  361. $step_number = $i+1;
  362. $active_class = $step_number == $current_page ? " gf_step_active" : "";
  363. $first_class = $i==0 ? " gf_step_first" : "";
  364. $last_class = $i+1 == $count ? " gf_step_last" : "";
  365. $complete_class = $step_number < $current_page ? " gf_step_completed" : "";
  366. $previous_class = $step_number + 1 == $current_page ? " gf_step_previous" : "";
  367. $next_class = $step_number - 1 == $current_page ? " gf_step_next" : "";
  368. $pending_class = $step_number > $current_page ? " gf_step_pending" : "";
  369. $classes = "gf_step" . $active_class . $first_class . $last_class . $complete_class . $previous_class . $next_class . $pending_class;
  370. $classes = GFCommon::trim_all($classes);
  371. $form_string .="
  372. <div id='gf_step_{$form_id}_{$step_number}' class='{$classes}'><span class='gf_step_number'>{$step_number}</span>&nbsp;{$form["pagination"]["pages"][$i]}</div>";
  373. }
  374. $form_string .="
  375. <div class='gf_step_clear'></div>
  376. </div>";
  377. }
  378. }
  379. if($is_postback && !$is_valid){
  380. $validation_message = "<div class='validation_error'>" . __("There was a problem with your submission.", "gravityforms") . " " . __("Errors have been highlighted below.", "gravityforms") . "</div>";
  381. $form_string .= apply_filters("gform_validation_message_{$form["id"]}", apply_filters("gform_validation_message", $validation_message, $form), $form);
  382. }
  383. $form_string .= "
  384. <div class='gform_body'>";
  385. //add first page if this form has any page fields
  386. if($has_pages){
  387. $style = self::is_page_active($form_id, 1) ? "" : "style='display:none;'";
  388. $class = !empty($form["firstPageCssClass"]) ? " {$form["firstPageCssClass"]}" : "";
  389. $form_string .= "<div id='gform_page_{$form_id}_1' class='gform_page{$class}' {$style}>
  390. <div class='gform_page_fields'>";
  391. }
  392. $description_class = rgar($form,"descriptionPlacement") == "above" ? "description_above" : "description_below";
  393. $form_string .= "
  394. <ul id='gform_fields_$form_id' class='gform_fields {$form['labelPlacement']} {$description_class}'>";
  395. if(is_array($form['fields']))
  396. {
  397. foreach($form['fields'] as $field){
  398. $field["conditionalLogicFields"] = self::get_conditional_logic_fields($form, $field["id"]);
  399. $form_string .= self::get_field($field, RGFormsModel::get_field_value($field, $field_values), false, $form, $field_values);
  400. }
  401. }
  402. $form_string .= "
  403. </ul>";
  404. if($has_pages){
  405. $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);
  406. $form_string .= "</div>" . self::gform_footer($form, "gform_page_footer " . $form['labelPlacement'], $ajax, $field_values, $previous_button, $display_title, $display_description, $is_postback) . "
  407. </div>"; //closes gform_page
  408. }
  409. $form_string .= "</div>"; //closes gform_body
  410. //suppress form footer for multi-page forms (footer will be included on the last page
  411. if(!$has_pages)
  412. $form_string .= self::gform_footer($form, "gform_footer " . $form['labelPlacement'], $ajax, $field_values, "", $display_title, $display_description, $is_postback);
  413. $form_string .= "
  414. </form>
  415. </div>";
  416. if($ajax && $is_postback){
  417. global $wp_scripts;
  418. $form_string = "<!DOCTYPE html><html><head>" .
  419. "<meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $form_string . "</body></html>";
  420. }
  421. if($ajax && !$is_postback){
  422. $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);
  423. $scroll_position = array('default' => '', 'confirmation' => '');
  424. if($use_anchor !== false) {
  425. $scroll_position['default'] = is_numeric($use_anchor) ? "jQuery(document).scrollTop(" . intval($use_anchor) . ");" : "jQuery(document).scrollTop(jQuery('#gform_wrapper_{$form_id}').offset().top);";
  426. $scroll_position['confirmation'] = is_numeric($use_anchor) ? "jQuery(document).scrollTop(" . intval($use_anchor) . ");" : "jQuery(document).scrollTop(jQuery('#gforms_confirmation_message').offset().top);";
  427. }
  428. $form_string .="
  429. <iframe style='display:none;width:0px; height:0px;' src='about:blank' name='gform_ajax_frame_{$form_id}' id='gform_ajax_frame_{$form_id}'></iframe>
  430. <script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . "" .
  431. "function gformInitSpinner_{$form_id}(){" .
  432. "jQuery('#gform_{$form_id}').submit(function(){" .
  433. "jQuery('#gform_submit_button_{$form_id}').attr('disabled', true).after('<' + 'img id=\"gform_ajax_spinner_{$form_id}\" class=\"gform_ajax_spinner\" src=\"{$spinner_url}\" alt=\"\" />');" .
  434. "jQuery('#gform_wrapper_{$form_id} .gform_previous_button').attr('disabled', true); " .
  435. "jQuery('#gform_wrapper_{$form_id} .gform_next_button').attr('disabled', true).after('<' + 'img id=\"gform_ajax_spinner_{$form_id}\" class=\"gform_ajax_spinner\" src=\"{$spinner_url}\" alt=\"\" />');" .
  436. "});" .
  437. "}" .
  438. "jQuery(document).ready(function($){" .
  439. "gformInitSpinner_{$form_id}();" .
  440. "jQuery('#gform_ajax_frame_{$form_id}').load( function(){" .
  441. "var contents = jQuery(this).contents().find('*').html();" .
  442. "var is_postback = contents.indexOf('GF_AJAX_POSTBACK') >= 0;" .
  443. "if(!is_postback){return;}" .
  444. "var form_content = jQuery(this).contents().find('#gform_wrapper_{$form_id}');" .
  445. "var is_redirect = contents.indexOf('gformRedirect(){') >= 0;".
  446. "jQuery('#gform_submit_button_{$form_id}').removeAttr('disabled');" .
  447. "if(form_content.length > 0){" .
  448. "jQuery('#gform_wrapper_{$form_id}').html(form_content.html());" .
  449. "{$scroll_position['default']}" .
  450. "if(window['gformInitDatepicker']) {gformInitDatepicker();}" .
  451. "if(window['gformInitPriceFields']) {gformInitPriceFields();}" .
  452. "var current_page = jQuery('#gform_source_page_number_{$form_id}').val();".
  453. "gformInitSpinner_{$form_id}();" .
  454. "jQuery(document).trigger('gform_page_loaded', [{$form_id}, current_page]);" .
  455. "}" .
  456. "else if(!is_redirect){" .
  457. "var confirmation_content = jQuery(this).contents().find('#gforms_confirmation_message').html();" .
  458. "if(!confirmation_content){".
  459. "confirmation_content = contents;".
  460. "}" .
  461. "setTimeout(function(){" .
  462. "jQuery('#gform_wrapper_{$form_id}').replaceWith('<' + 'div id=\'gforms_confirmation_message\' class=\'gform_confirmation_message_{$form_id}\'' + '>' + confirmation_content + '<' + '/div' + '>');" .
  463. "{$scroll_position['confirmation']}" .
  464. "jQuery(document).trigger('gform_confirmation_loaded', [{$form_id}]);" .
  465. "}, 50);" .
  466. "}" .
  467. "else{" .
  468. "jQuery('#gform_{$form_id}').append(contents);" .
  469. "if(window['gformRedirect']) gformRedirect();" .
  470. "}" .
  471. "jQuery(document).trigger('gform_post_render', [{$form_id}, current_page]);" .
  472. "});" .
  473. "});" . apply_filters("gform_cdata_close", "") . "</script>";
  474. }
  475. $is_first_load = !$is_postback;
  476. if(!$ajax || $is_first_load) {
  477. $form_string .= self::get_form_init_scripts($form);
  478. $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>";
  479. }
  480. return apply_filters('gform_get_form_filter',$form_string);
  481. }
  482. else{
  483. $progress_confirmation = "";
  484. //check admin setting for whether the progress bar should start at zero
  485. $start_at_zero = rgars($form, "pagination/display_progressbar_on_confirmation");
  486. //check for filter
  487. $start_at_zero = apply_filters("gform_progressbar_start_at_zero", $start_at_zero, $form);
  488. //show progress bar on confirmation
  489. if($start_at_zero && $has_pages && !IS_ADMIN && ($form["confirmation"]["type"] == "message" && $form["pagination"]["type"] == "percentage") && $form["pagination"]["display_progressbar_on_confirmation"])
  490. {
  491. $progress_confirmation = self::get_progress_bar($form, $form_id,$confirmation_message);
  492. if($ajax)
  493. {
  494. $progress_confirmation = "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $progress_confirmation . $confirmation_message . "</body></html>";
  495. }
  496. else
  497. {
  498. $progress_confirmation = $progress_confirmation . $confirmation_message;
  499. }
  500. }
  501. else
  502. {
  503. //return regular confirmation message
  504. if($ajax)
  505. {
  506. $progress_confirmation = "<!DOCTYPE html><html><head><meta charset='UTF-8' /></head><body class='GF_AJAX_POSTBACK'>" . $confirmation_message . "</body></html>";
  507. }
  508. else
  509. {
  510. $progress_confirmation = $confirmation_message;
  511. }
  512. }
  513. return $progress_confirmation;
  514. }
  515. }
  516. public static function add_init_script($form_id, $script_name, $location, $script){
  517. $key = $script_name . "_" . $location;
  518. if(!isset(self::$init_scripts[$form_id]))
  519. self::$init_scripts[$form_id] = array();
  520. //add script if it hasn't been added before
  521. if(!array_key_exists($key, self::$init_scripts[$form_id]))
  522. self::$init_scripts[$form_id][$key] = array("location" => $location, "script" => $script);
  523. }
  524. private static function get_form_button($form_id, $button_input_id, $button, $default_text, $class, $alt, $target_page_number){
  525. $tabindex = GFCommon::get_tabindex();
  526. $input_type='submit';
  527. $onclick="";
  528. if(!empty($target_page_number)){
  529. $onclick = "onclick='jQuery(\"#gform_target_page_number_{$form_id}\").val(\"{$target_page_number}\"); jQuery(\"#gform_{$form_id}\").trigger(\"submit\",[true]); '";
  530. $input_type='button';
  531. }
  532. if($button["type"] == "text" || empty($button["imageUrl"])){
  533. $button_text = !empty($button["text"]) ? $button["text"] : $default_text;
  534. $button_input = "<input type='{$input_type}' id='{$button_input_id}' class='{$class}' value='" . esc_attr($button_text) . "' {$tabindex} {$onclick}/>";
  535. }
  536. else{
  537. $imageUrl = $button["imageUrl"];
  538. $button_input= "<input type='image' src='{$imageUrl}' id='{$button_input_id}' class='gform_image_button' alt='{$alt}' {$tabindex} {$onclick}/>";
  539. }
  540. return $button_input;
  541. }
  542. private static function gform_footer($form, $class, $ajax, $field_values, $previous_button, $display_title, $display_description){
  543. $form_id = $form["id"];
  544. $footer = "
  545. <div class='" . $class ."'>";
  546. $button_input = self::get_form_button($form["id"], "gform_submit_button_{$form["id"]}", $form["button"], __("Submit", "gravityforms"), "button gform_button", __("Submit", "gravityforms"), 0);
  547. $button_input = apply_filters("gform_submit_button", $button_input, $form);
  548. $button_input = apply_filters("gform_submit_button_{$form_id}", $button_input, $form);
  549. $footer .= $previous_button . " " . $button_input;
  550. if($ajax){
  551. $footer .= "<input type='hidden' name='gform_ajax' value='" . esc_attr("form_id={$form_id}&amp;title={$display_title}&amp;description={$display_description}") . "' />";
  552. }
  553. $current_page = self::get_current_page($form_id);
  554. $next_page = $current_page + 1;
  555. $next_page = $next_page > self::get_max_page_number($form) ? 0 : $next_page;
  556. $field_values_str = is_array($field_values) ? http_build_query($field_values) : "";
  557. $files_input = "";
  558. if(!empty(RGFormsModel::$uploaded_files[$form_id])){
  559. $files = GFCommon::json_encode(RGFormsModel::$uploaded_files[$form_id]);
  560. $files_input = "<input type='hidden' name='gform_uploaded_files' id='gform_uploaded_files_{$form_id}' value='" . str_replace("'", "&#039;", $files) . "' />";
  561. }
  562. $footer .="
  563. <input type='hidden' class='gform_hidden' name='is_submit_{$form_id}' value='1' />
  564. <input type='hidden' class='gform_hidden' name='gform_submit' value='{$form_id}' />
  565. <input type='hidden' class='gform_hidden' name='gform_unique_id' value='" . esc_attr(RGFormsModel::get_form_unique_id($form_id)) . "' />
  566. <input type='hidden' class='gform_hidden' name='state_{$form_id}' value='" . self::get_state($form, $field_values) . "' />
  567. <input type='hidden' class='gform_hidden' name='gform_target_page_number_{$form_id}' id='gform_target_page_number_{$form_id}' value='" . $next_page . "' />
  568. <input type='hidden' class='gform_hidden' name='gform_source_page_number_{$form_id}' id='gform_source_page_number_{$form_id}' value='" . $current_page . "' />
  569. <input type='hidden' name='gform_field_values' value='{$field_values_str}' />
  570. {$files_input}
  571. </div>";
  572. return $footer;
  573. }
  574. private static function get_max_page_number($form){
  575. $page_number = 0;
  576. foreach($form["fields"] as $field){
  577. if($field["type"] == "page"){
  578. $page_number++;
  579. }
  580. }
  581. return $page_number == 0 ? 0 : $page_number + 1;
  582. }
  583. private static function get_honeypot_field($form){
  584. $max_id = self::get_max_field_id($form);
  585. $labels = self::get_honeypot_labels();
  586. 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.");
  587. }
  588. private static function get_max_field_id($form){
  589. $max = 0;
  590. foreach($form["fields"] as $field){
  591. if(floatval($field["id"]) > $max)
  592. $max = floatval($field["id"]);
  593. }
  594. return $max;
  595. }
  596. private static function get_honeypot_labels(){
  597. return array("Name", "Email", "Phone", "Comments");
  598. }
  599. public static function is_empty($field, $form_id=0){
  600. switch(RGFormsModel::get_input_type($field)){
  601. case "post_image" :
  602. case "fileupload" :
  603. $input_name = "input_" . $field["id"];
  604. $file_info = RGFormsModel::get_temp_filename($form_id, $input_name);
  605. return !$file_info && empty($_FILES[$input_name]['name']);
  606. case "list" :
  607. $value = rgpost("input_" . $field["id"]);
  608. if(is_array($value)){
  609. //empty if all inputs are empty (for inputs with the same name)
  610. foreach($value as $input){
  611. if(strlen(trim($input)) > 0 )
  612. return false;
  613. }
  614. }
  615. return true;
  616. }
  617. if(is_array($field["inputs"]))
  618. {
  619. foreach($field["inputs"] as $input){
  620. $value = rgpost("input_" . str_replace('.', '_', $input["id"]));
  621. if(is_array($value) && !empty($value)){
  622. return false;
  623. }
  624. if(!is_array($value) && strlen(trim($value)) > 0)
  625. return false;
  626. }
  627. return true;
  628. }
  629. else{
  630. $value = rgpost("input_" . $field["id"]);
  631. if(is_array($value)){
  632. //empty if any of the inputs are empty (for inputs with the same name)
  633. foreach($value as $input){
  634. if(strlen(trim($input)) <= 0 )
  635. return true;
  636. }
  637. return false;
  638. }
  639. else if($field["enablePrice"]){
  640. list($label, $price) = explode("|", $value);
  641. $is_empty = (strlen(trim($price)) <= 0);
  642. return $is_empty;
  643. }
  644. else{
  645. $is_empty = (strlen(trim($value)) <= 0) || ($field["type"] == "post_category" && $value < 0);
  646. return $is_empty;
  647. }
  648. }
  649. }
  650. private static function clean_extensions($extensions){
  651. $count = sizeof($extensions);
  652. for($i=0; $i<$count; $i++){
  653. $extensions[$i] = str_replace(".", "",str_replace(" ", "", $extensions[$i]));
  654. }
  655. return $extensions;
  656. }
  657. private static function validate_range($field, $value){
  658. if( !GFCommon::is_numeric($value, rgar($field, "numberFormat")) )
  659. return false;
  660. $number = GFCommon::clean_number($value, rgar($field, "numberFormat"));
  661. if( (is_numeric($field["rangeMin"]) && $number < $field["rangeMin"]) ||
  662. (is_numeric($field["rangeMax"]) && $number > $field["rangeMax"])
  663. )
  664. return false;
  665. else
  666. return true;
  667. }
  668. private static function validate_honeypot($form){
  669. $honeypot_id = self::get_max_field_id($form);
  670. return rgempty("input_{$honeypot_id}");
  671. }
  672. public static function handle_submission($form, &$lead, $ajax=false){
  673. //creating entry in DB
  674. RGFormsModel::save_lead($form, $lead);
  675. //reading entry that was just saved
  676. $lead = RGFormsModel::get_lead($lead["id"]);
  677. do_action('gform_entry_created', $lead, $form);
  678. //if Akismet plugin is installed, run lead through Akismet and mark it as Spam when appropriate
  679. $is_spam = false;
  680. if(GFCommon::akismet_enabled($form['id']) && GFCommon::is_akismet_spam($form, $lead)){
  681. $is_spam = true;
  682. }
  683. if(!$is_spam){
  684. GFCommon::create_post($form, $lead);
  685. //send auto-responder and notification emails
  686. self::send_emails($form, $lead);
  687. }
  688. else{
  689. //marking entry as spam
  690. RGFormsModel::update_lead_property($lead["id"], "status", "spam", false, true);
  691. $lead["status"] = "spam";
  692. }
  693. //display confirmation message or redirect to confirmation page
  694. return self::handle_confirmation($form, $lead, $ajax);
  695. }
  696. public static function handle_confirmation($form, $lead, $ajax=false){
  697. if($form["confirmation"]["type"] == "message"){
  698. $default_anchor = self::has_pages($form) ? 1 : 0;
  699. $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>" : "";
  700. $nl2br = rgar($form["confirmation"],"disableAutoformat") ? false : true;
  701. $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>";
  702. }
  703. else{
  704. if(!empty($form["confirmation"]["pageId"])){
  705. $url = get_permalink($form["confirmation"]["pageId"]);
  706. }
  707. else{
  708. $url = GFCommon::replace_variables(trim($form["confirmation"]["url"]), $form, $lead, false, true);
  709. $url_info = parse_url($url);
  710. $query_string = $url_info["query"];
  711. $dynamic_query = GFCommon::replace_variables(trim($form["confirmation"]["queryString"]), $form, $lead, true);
  712. $query_string .= empty($url_info["query"]) || empty($dynamic_query) ? $dynamic_query : "&" . $dynamic_query;
  713. if(!empty($url_info["fragment"]))
  714. $query_string .= "#" . $url_info["fragment"];
  715. $url = $url_info["scheme"] . "://" . $url_info["host"] . $url_info["path"] . "?" . $query_string;
  716. }
  717. if(headers_sent() || $ajax){
  718. //Perform client side redirect for AJAX forms, of if headers have already been sent
  719. $confirmation = self::get_js_redirect_confirmation($url, $ajax);
  720. }
  721. else{
  722. $confirmation = array("redirect" => $url);
  723. }
  724. }
  725. $confirmation = apply_filters("gform_confirmation_{$form["id"]}", apply_filters("gform_confirmation", $confirmation, $form, $lead, $ajax), $form, $lead, $ajax);
  726. if(!is_array($confirmation)){
  727. $confirmation = GFCommon::gform_do_shortcode($confirmation); //enabling shortcodes
  728. }
  729. else if(headers_sent() || $ajax){
  730. //Perform client side redirect for AJAX forms, of if headers have already been sent
  731. $confirmation = self::get_js_redirect_confirmation($confirmation["redirect"], $ajax); //redirecting via client side
  732. }
  733. return $confirmation;
  734. }
  735. private static function get_js_redirect_confirmation($url, $ajax){
  736. $confirmation = "<script type=\"text/javascript\">" . apply_filters("gform_cdata_open", "") . " function gformRedirect(){document.location.href='$url';}";
  737. if(!$ajax)
  738. $confirmation .="gformRedirect();";
  739. $confirmation .= apply_filters("gform_cdata_close", "") . "</script>";
  740. return $confirmation;
  741. }
  742. public static function send_emails($form, $lead){
  743. $disable_user_notification = apply_filters("gform_disable_user_notification_{$form["id"]}", apply_filters("gform_disable_user_notification", false, $form, $lead), $form, $lead);
  744. if(!$disable_user_notification){
  745. GFCommon::send_user_notification($form, $lead);
  746. }
  747. $disable_admin_notification = apply_filters("gform_disable_admin_notification_{$form["id"]}", apply_filters("gform_disable_admin_notification", false, $form, $lead), $form, $lead);
  748. if(!$disable_admin_notification){
  749. GFCommon::send_admin_notification($form, $lead);
  750. }
  751. }
  752. public static function checkdate($month, $day, $year){
  753. if(empty($month) || !is_numeric($month) || empty($day) || !is_numeric($day) || empty($year) || !is_numeric($year) || strlen($year) != 4)
  754. return false;
  755. return checkdate($month, $day, $year);
  756. }
  757. public static function validate(&$form, $field_values, $page_number=0){
  758. // validate form schedule
  759. if(self::validate_form_schedule($form))
  760. return false;
  761. // validate entry limit
  762. if(self::validate_entry_limit($form))
  763. return false;
  764. foreach($form["fields"] as &$field){
  765. //If a page number is specified, only validates fields that are on current page
  766. if($page_number > 0 && $field["pageNumber"] != $page_number)
  767. continue;
  768. //ignore validation if field is hidden or admin only
  769. if(RGFormsModel::is_field_hidden($form, $field, $field_values) || $field["adminOnly"])
  770. continue;
  771. $value = RGFormsModel::get_field_value($field);
  772. //display error message if field is marked as required and the submitted value is empty
  773. if($field["isRequired"] && self::is_empty($field, $form["id"])){
  774. $field["failed_validation"] = true;
  775. $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  776. }
  777. //display error if field does not allow duplicates and the submitted value already exists
  778. else if($field["noDuplicates"] && RGFormsModel::is_duplicate($form["id"], $field, $value)){
  779. $field["failed_validation"] = true;
  780. $input_type = RGFormsModel::get_input_type($field);
  781. switch($input_type){
  782. case "date" :
  783. $default_message = __("This date has already been taken. Please select a new date.", "gravityforms");
  784. break;
  785. default:
  786. $default_message = is_array($value) ? __("This field requires an unique entry and the values you entered have been already been used.", "gravityforms") :
  787. sprintf(__("This field requires an unique entry and '%s' has already been used", "gravityforms"), $value);
  788. break;
  789. }
  790. $field["validation_message"] = apply_filters("gform_duplicate_message_{$form["id"]}", apply_filters("gform_duplicate_message", $default_message, $form), $form);
  791. }
  792. else{
  793. if(self::failed_state_validation($form["id"], $field, $value)){
  794. $field["failed_validation"] = true;
  795. $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");
  796. }
  797. else{
  798. switch(RGFormsModel::get_input_type($field)){
  799. case "password" :
  800. $password = $_POST["input_" . $field["id"]];
  801. $confirm = $_POST["input_" . $field["id"] . "_2"];
  802. if($password != $confirm){
  803. $field["failed_validation"] = true;
  804. $field["validation_message"] = __("Your passwords do not match.", "gravityforms");
  805. }
  806. else if(rgar($field,"passwordStrengthEnabled") && !rgempty("minPasswordStrength",$field) && !empty($password)){
  807. $strength = $_POST["input_" . $field["id"] . "_strength"];
  808. $levels = array("short" => 1, "bad" => 2, "good" => 3, "strong" => 4);
  809. if($levels[$strength] < $levels[$field["minPasswordStrength"]]){
  810. $field["failed_validation"] = true;
  811. $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"];
  812. }
  813. }
  814. break;
  815. case "name" :
  816. if($field["isRequired"] && $field["nameFormat"] != "simple")
  817. {
  818. $first = $_POST["input_" . $field["id"] . "_3"];
  819. $last = $_POST["input_" . $field["id"] . "_6"];
  820. if(empty($first) || empty($last)){
  821. $field["failed_validation"] = true;
  822. $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required. Please enter the first and last name.", "gravityforms") : $field["errorMessage"];
  823. }
  824. }
  825. break;
  826. case "address" :
  827. if($field["isRequired"])
  828. {
  829. $street = $_POST["input_" . $field["id"] . "_1"];
  830. $city = $_POST["input_" . $field["id"] . "_3"];
  831. $state = $_POST["input_" . $field["id"] . "_4"];
  832. $zip = $_POST["input_" . $field["id"] . "_5"];
  833. $country = $_POST["input_" . $field["id"] . "_6"];
  834. if(empty($street) || empty($city) || empty($zip) || (empty($state) && !$field["hideState"] ) || (empty($country) && !$field["hideCountry"])){
  835. $field["failed_validation"] = true;
  836. $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required. Please enter a complete address.", "gravityforms") : $field["errorMessage"];
  837. }
  838. }
  839. break;
  840. case "creditcard" :
  841. $card_number = rgpost("input_" . $field["id"] . "_1");
  842. $expiration_date = rgpost("input_" . $field["id"] . "_2");
  843. $security_code = rgpost("input_" . $field["id"] . "_3");
  844. if(rgar($field, "isRequired") && (empty($card_number) || empty($security_code) || empty($expiration_date[0]) || empty($expiration_date[1]))){
  845. $field["failed_validation"] = true;
  846. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter your credit card information.", "gravityforms") : $field["errorMessage"];
  847. }
  848. else if(!empty($card_number)){
  849. $card_type = GFCommon::get_card_type($card_number);
  850. $security_code = rgpost("input_" . $field["id"] . "_3");
  851. if(empty($security_code)){
  852. $field["failed_validation"] = true;
  853. $field["validation_message"] = __("Please enter your card's security code.", "gravityforms");
  854. }
  855. else if(!$card_type){
  856. $field["failed_validation"] = true;
  857. $field["validation_message"] = __("Invalid credit card number.", "gravityforms");
  858. }
  859. else if(!GFCommon::is_card_supported($field, $card_type["slug"])){
  860. $field["failed_validation"] = true;
  861. $field["validation_message"] = $card_type["name"] . " " . __("is not supported. Please enter one of the supported credit cards.", "gravityforms");
  862. }
  863. }
  864. break;
  865. case "email" :
  866. if(!rgblank($value) && !GFCommon::is_valid_email($value)){
  867. $field["failed_validation"] = true;
  868. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid email address.", "gravityforms"): $field["errorMessage"];
  869. }
  870. else if(rgget("emailConfirmEnabled", $field) && !empty($value)){
  871. $confirm = rgpost("input_" . $field["id"] . "_2");
  872. if($confirm != $value){
  873. $field["failed_validation"] = true;
  874. $field["validation_message"] = __("Your emails do not match.", "gravityforms");
  875. }
  876. }
  877. break;
  878. case "donation" :
  879. case "price" :
  880. if(!class_exists("RGCurrency"))
  881. require_once("currency.php");
  882. $donation = GFCommon::to_number($value);
  883. if(!rgblank($value) && ($donation === false || $donation < 0)){
  884. $field["failed_validation"] = true;
  885. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid amount.", "gravityforms") : $field["errorMessage"];
  886. }
  887. break;
  888. case "number" :
  889. if(!rgblank($value) && !self::validate_range($field, $value) && !GFCommon::has_field_calculation($field)) {
  890. $field["failed_validation"] = true;
  891. $field["validation_message"] = empty($field["errorMessage"]) ? GFCommon::get_range_message($field) : $field["errorMessage"];
  892. }
  893. else if($field["type"] == "quantity" && intval($value) != $value){
  894. $field["failed_validation"] = true;
  895. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid quantity. Quantity cannot contain decimals.", "gravityforms") : $field["errorMessage"];
  896. }
  897. break;
  898. case "phone" :
  899. $regex = '/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/';
  900. if($field["phoneFormat"] == "standard" && !empty($value) && !preg_match($regex, $value)){
  901. $field["failed_validation"] = true;
  902. if(!empty($field["errorMessage"]))
  903. $field["validation_message"] = $field["errorMessage"];
  904. }
  905. break;
  906. case "date" :
  907. if(is_array($value) && rgempty(0, $value) && rgempty(1, $value)&& rgempty(2, $value))
  908. $value = null;
  909. if(!empty($value)){
  910. $format = empty($field["dateFormat"]) ? "mdy" : $field["dateFormat"];
  911. $date = GFCommon::parse_date($value, $format);
  912. if(empty($date) || !self::checkdate($date["month"], $date["day"], $date["year"])){
  913. $field["failed_validation"] = true;
  914. $format_name = "";
  915. switch($format){
  916. case "mdy" :
  917. $format_name = "mm/dd/yyyy";
  918. break;
  919. case "dmy" :
  920. $format_name = "dd/mm/yyyy";
  921. break;
  922. case "dmy_dash" :
  923. $format_name = "dd-mm-yyyy";
  924. break;
  925. case "dmy_dot" :
  926. $format_name = "dd.mm.yyyy";
  927. break;
  928. case "ymd_slash" :
  929. $format_name = "yyyy/mm/dd";
  930. break;
  931. case "ymd_dash" :
  932. $format_name = "yyyy-mm-dd";
  933. break;
  934. case "ymd_dot" :
  935. $format_name = "yyyy.mm.dd";
  936. break;
  937. }
  938. $message = $field["dateType"] == "datepicker" ? sprintf(__("Please enter a valid date in the format (%s).", "gravityforms"), $format_name) : __("Please enter a valid date.", "gravityforms");
  939. $field["validation_message"] = empty($field["errorMessage"]) ? $message : $field["errorMessage"];
  940. }
  941. }
  942. break;
  943. case "time" :
  944. //create variable values if time came in one field
  945. if(!is_array($value) && !empty($value)){
  946. preg_match('/^(\d*):(\d*) ?(.*)$/', $value, $matches);
  947. $value = array();
  948. $value[0] = $matches[1];
  949. $value[1] = $matches[2];
  950. }
  951. $hour = $value[0];
  952. $minute = $value[1];
  953. if(empty($hour) && empty($minute))
  954. break;
  955. $is_valid_format = is_numeric($hour) && is_numeric($minute);
  956. $min_hour = rgar($field, "timeFormat") == "24" ? 0 : 1;
  957. $max_hour = rgar($field, "timeFormat") == "24" ? 23 : 12;
  958. if(!$is_valid_format || $hour < $min_hour || $hour > $max_hour || $minute < 0 || $minute >= 60)
  959. {
  960. $field["failed_validation"] = true;
  961. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid time." , "gravityforms"): $field["errorMessage"];
  962. }
  963. break;
  964. case "website" :
  965. if(empty($value) || $value == "http://"){
  966. $value = "";
  967. if($field["isRequired"]){
  968. $field["failed_validation"] = true;
  969. $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  970. }
  971. }
  972. if(!empty($value) && !GFCommon::is_valid_url($value)){
  973. $field["failed_validation"] = true;
  974. $field["validation_message"] = empty($field["errorMessage"]) ? __("Please enter a valid Website URL (i.e. http://www.gravityforms.com).", "gravityforms") : $field["errorMessage"];
  975. }
  976. break;
  977. case "captcha" :
  978. switch($field["captchaType"]){
  979. case "simple_captcha" :
  980. if(class_exists("ReallySimpleCaptcha")){
  981. $prefix = $_POST["input_captcha_prefix_{$field["id"]}"];
  982. $captcha_obj = GFCommon::get_simple_captcha();
  983. if(!$captcha_obj->check($prefix, str_replace(" ", "", $value))){
  984. $field["failed_validation"] = true;
  985. $field["validation_message"] = empty($field["errorMessage"]) ? __("The CAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  986. }
  987. //removes old files in captcha folder (older than 1 hour);
  988. $captcha_obj->cleanup();
  989. }
  990. break;
  991. case "math" :
  992. $prefixes = explode(",", $_POST["input_captcha_prefix_{$field["id"]}"]);
  993. $captcha_obj = GFCommon::get_simple_captcha();
  994. //finding first number
  995. $first = 0;
  996. for($first=0; $first<10; $first++){
  997. if($captcha_obj->check($prefixes[0], $first))
  998. break;
  999. }
  1000. //finding second number
  1001. $second = 0;
  1002. for($second=0; $second<10; $second++){
  1003. if($captcha_obj->check($prefixes[2], $second))
  1004. break;
  1005. }
  1006. //if it is a +, perform the sum
  1007. if($captcha_obj->check($prefixes[1], "+"))
  1008. $result = $first + $second;
  1009. else
  1010. $result = $first - $second;
  1011. if(intval($result) != intval($value)){
  1012. $field["failed_validation"] = true;
  1013. $field["validation_message"] = empty($field["errorMessage"]) ? __("The CAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  1014. }
  1015. //removes old files in captcha folder (older than 1 hour);
  1016. $captcha_obj->cleanup();
  1017. break;
  1018. default :
  1019. if(!function_exists("recaptcha_get_html")){
  1020. require_once(GFCommon::get_base_path() . '/recaptchalib.php');
  1021. }
  1022. $privatekey = get_option("rg_gforms_captcha_private_key");
  1023. $resp = recaptcha_check_answer ($privatekey,
  1024. $_SERVER["REMOTE_ADDR"],
  1025. $_POST["recaptcha_challenge_field"],
  1026. $_POST["recaptcha_response_field"]);
  1027. if (!$resp->is_valid) {
  1028. $field["failed_validation"] = true;
  1029. $field["validation_message"] = empty($field["errorMessage"]) ? __("The reCAPTCHA wasn't entered correctly. Go back and try it again.", "gravityforms") : $field["errorMessage"];
  1030. }
  1031. }
  1032. break;
  1033. case "fileupload" :
  1034. case "post_image" :
  1035. $info = pathinfo($_FILES["input_" . $field["id"]]["name"]);
  1036. $allowedExtensions = self::clean_extensions(explode(",", strtolower($field["allowedExtensions"])));
  1037. $extension = strtolower(rgget("extension",$info));
  1038. if(empty($field["allowedExtensions"]) && in_array($extension, array("php", "asp", "exe", "com", "htaccess"))){
  1039. $field["failed_validation"] = true;
  1040. $field["validation_message"] = empty($field["errorMessage"]) ? __("The uploaded file type is not allowed.", "gravityforms") : $field["errorMessage"];
  1041. }
  1042. else if(!empty($field["allowedExtensions"]) && !empty($info["basename"]) && !in_array($extension, $allowedExtensions)){
  1043. $field["failed_validation"] = true;
  1044. $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"];
  1045. }
  1046. break;
  1047. case "calculation" :
  1048. case "singleproduct" :
  1049. case "hiddenproduct" :
  1050. $quantity_id = $field["id"] . ".3";
  1051. $quantity = rgget($quantity_id, $value);
  1052. if(empty($quantity))
  1053. $quantity = 0;
  1054. if(!is_numeric($quantity) || intval($quantity) != floatval($quantity))
  1055. {
  1056. $field["failed_validation"] = true;
  1057. $field["validation_message"] = __("Please enter a valid quantity", "gravityforms");
  1058. }
  1059. else if($field["isRequired"] && empty($quantity) && !rgar($field, "disableQuantity") ){
  1060. $field["failed_validation"] = true;
  1061. $field["validation_message"] = rgempty("errorMessage", $field) ? __("This field is required.", "gravityforms") : rgar($field, "errorMessage");
  1062. }
  1063. break;
  1064. case "radio" :
  1065. if(rgar($field, 'enableOtherChoice') && $value == 'gf_other_choice')
  1066. $value = rgpost("input_{$field['id']}_other");
  1067. if($field["isRequired"] && rgar($field, 'enableOtherChoice') && $value == GFCommon::get_other_choice_value()) {
  1068. $field["failed_validation"] = true;
  1069. $field["validation_message"] = empty($field["errorMessage"]) ? __("This field is required.", "gravityforms") : $field["errorMessage"];
  1070. }
  1071. break;
  1072. }
  1073. }
  1074. }
  1075. $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);
  1076. $custom_validation_result = apply_filters("gform_field_validation_{$form["id"]}", $custom_validation_result, $value, $form, $field);
  1077. $custom_validation_result = apply_filters("gform_field_validation_{$form["id"]}_{$field["id"]}", $custom_validation_result, $value, $form, $field);
  1078. $field["failed_validation"] = rgar($custom_validation_result, "is_valid") ? false : true;
  1079. $field["validation_message"] = rgar($custom_validation_result, "message");
  1080. }
  1081. $is_valid = true;
  1082. foreach($form["fields"] as $f){
  1083. if(rgar($f,"failed_validation")){
  1084. $is_valid = false;
  1085. break;
  1086. }
  1087. }
  1088. $validation_result = apply_filters("gform_validation_{$form["id"]}", apply_filters("gform_validation", array("is_valid" => $is_valid, "form" => $form)) );
  1089. $is_valid = $validation_result["is_valid"];
  1090. $form = $validation_result["form"];
  1091. return $is_valid;
  1092. }
  1093. public static function failed_state_validation($form_id, $field, $value){
  1094. global $_gf_state;
  1095. //if field can be populated dynamically, disable state validation
  1096. if(rgar($field,"allowsPrepopulate")) {
  1097. return false;
  1098. } else if(!GFCommon::is_product_field($field["type"] && $field["type"] != "donation")) {
  1099. return false;
  1100. } else if (!in_array($field["inputType"], array("singleshipping", "singleproduct", "hiddenproduct", "checkbox", "radio", "select"))) {
  1101. return false;
  1102. }
  1103. if(!isset($_gf_state)){
  1104. $state = unserialize(base64_decode($_POST["state_{$form_id}"]));
  1105. if(!$state || sizeof($state) != 2)
  1106. return true;
  1107. //making sure state wasn't tampered with by validating checksum
  1108. $checksum = wp_hash(crc32($state[0]));
  1109. if($checksum != $state[1]){
  1110. return true;
  1111. }
  1112. $_gf_state = unserialize($state[0]);
  1113. }
  1114. if(!is_array($value)){
  1115. $value = array($field["id"] => $value);
  1116. }
  1117. foreach($value as $key => $input_value){
  1118. $state = isset($_gf_state[$key]) ? $_gf_state[$key] : false;
  1119. //converting price to a number for single product fields and single shipping fields
  1120. if( (in_array($field["inputType"], array("singleproduct", "hiddenproduct")) && $key == $field["id"] . ".2") || $field["inputType"] == "singleshipping")
  1121. $input_value = GFCommon::to_number($input_value);
  1122. $hash = wp_hash($input_value);
  1123. if(strlen($input_value) > 0 && $state !== false && ((is_array($state) && !in_array($hash, $state)) || (!is_array($state) && $hash != $state)) ){
  1124. return true;
  1125. }
  1126. }
  1127. return false;
  1128. }
  1129. public static function enqueue_scripts(){
  1130. global $wp_query;
  1131. if(isset($wp_query->posts) && is_array($wp_query->posts)){
  1132. foreach($wp_query->posts as $post){
  1133. $forms = self::get_embedded_forms($post->post_content, $ajax);
  1134. foreach($forms as $form){
  1135. self::enqueue_form_scripts($form, $ajax);
  1136. }
  1137. }
  1138. }
  1139. }
  1140. public static function get_embedded_forms($post_content, &$ajax){
  1141. $forms = array();
  1142. if(preg_match_all('/\[gravityform +.*?((id=.+?)|(name=.+?))\]/is', $post_content, $matches, PREG_SET_ORDER)){
  1143. $ajax = false;
  1144. foreach($matches as $match){
  1145. //parsing shortcode attributes
  1146. $attr = shortcode_parse_atts($match[1]);
  1147. $form_id = $attr["id"];
  1148. if(!is_numeric($form_id))
  1149. $form_id = RGFormsModel::get_form_id($attr["name"]);
  1150. $forms[] = RGFormsModel::get_form_meta($form_id);
  1151. $ajax = isset($attr["ajax"]) && strtolower(substr($attr["ajax"],0, 4)) == "true";
  1152. }
  1153. }
  1154. return $forms;
  1155. }
  1156. public static function enqueue_form_scripts($form, $ajax=false){
  1157. if(!get_option('rg_gforms_disable_css')){
  1158. wp_enqueue_style("gforms_css", GFCommon::get_base_url() . "/css/forms.css", null, GFCommon::$version);
  1159. }
  1160. 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)){
  1161. wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1162. }
  1163. if(self::has_conditional_logic($form)){
  1164. wp_enqueue_script("gforms_conditional_logic_lib", GFCommon::get_base_url() . "/js/conditional_logic.js", array("jquery", "gforms_gravityforms"), GFCommon::$version);
  1165. }
  1166. if(self::has_date_field($form)){
  1167. wp_enqueue_script("gforms_ui_datepicker", GFCommon::get_base_url() . "/js/jquery-ui/ui.datepicker.js", array("jquery"), GFCommon::$version, true);
  1168. wp_enqueue_script("gforms_datepicker", GFCommon::get_base_url() . "/js/datepicker.js", array("gforms_ui_datepicker"), GFCommon::$version, true);
  1169. }
  1170. 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)){
  1171. wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1172. }
  1173. if(self::has_enhanced_dropdown($form) || self::has_pages($form) || self::has_fileupload_field($form)){
  1174. wp_enqueue_script("gforms_json", GFCommon::get_base_url() . "/js/jquery.json-1.3.js", array("jquery"), GFCommon::$version, true);
  1175. wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("gforms_json"), GFCommon::$version, false);
  1176. }
  1177. if(self::has_character_counter($form)){
  1178. wp_enqueue_script("gforms_character_counter", GFCommon::get_base_url() . "/js/jquery.textareaCounter.plugin.js", array("jquery"), GFCommon::$version, true);
  1179. }
  1180. if(self::has_input_mask($form)){
  1181. wp_enqueue_script("gforms_input_mask", GFCommon::get_base_url() . "/js/jquery.maskedinput-1.3.min.js", array("jquery"), GFCommon::$version, true);
  1182. }
  1183. if(self::has_enhanced_dropdown($form)){
  1184. wp_enqueue_script("gforms_chosen", GFCommon::get_base_url() . "/js/chosen.jquery.min.js", array("jquery"), GFCommon::$version, false);
  1185. }
  1186. if(wp_script_is("gforms_gravityforms")) {
  1187. require_once(GFCommon::get_base_path() . '/currency.php');
  1188. wp_localize_script('gforms_gravityforms', 'gf_global', array( 'gf_currency_config' => RGCurrency::get_currency(GFCommon::get_currency()) ));
  1189. }
  1190. do_action("gform_enqueue_scripts", $form, $ajax);
  1191. do_action("gform_enqueue_scripts_{$form["id"]}", $form, $ajax);
  1192. // enqueue jQuery every time form is displayed to allow "gform_post_render" js hook
  1193. // to be available to users even when GF is not using it
  1194. wp_enqueue_script("jquery");
  1195. }
  1196. private static $printed_scripts = array();
  1197. public static function print_form_scripts($form, $ajax){
  1198. if(!get_option('rg_gforms_disable_css')){
  1199. if(!wp_style_is("gforms_css", "queue")){
  1200. wp_enqueue_style("gforms_css", GFCommon::get_base_url() . "/css/forms.css", GFCommon::$version);
  1201. wp_print_styles(array("gforms_css"));
  1202. }
  1203. }
  1204. 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")){
  1205. wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1206. wp_print_scripts(array("gforms_gravityforms"));
  1207. }
  1208. if(self::has_conditional_logic($form) && !wp_script_is("gforms_conditional_logic_lib", "queue")){
  1209. wp_enqueue_script("gforms_conditional_logic_lib", GFCommon::get_base_url() . "/js/conditional_logic.js", array("jquery", "gforms_gravityforms"), GFCommon::$version);
  1210. wp_print_scripts(array("gforms_conditional_logic_lib"));
  1211. }
  1212. if(self::has_date_field($form) && !wp_script_is("gforms_datepicker", "queue")){
  1213. wp_enqueue_script("gforms_ui_datepicker", GFCommon::get_base_url() . "/js/jquery-ui/ui.datepicker.js", array("jquery"), GFCommon::$version, true);
  1214. wp_enqueue_script("gforms_datepicker", GFCommon::get_base_url() . "/js/datepicker.js", array("gforms_ui_datepicker"), GFCommon::$version, true);
  1215. wp_print_scripts(array("gforms_datepicker"));
  1216. }
  1217. if(self::has_pages($form) && !wp_script_is("gforms_json", "queue")){
  1218. wp_enqueue_script("gforms_json", GFCommon::get_base_url() . "/js/jquery.json-1.3.js", array("jquery"), GFCommon::$version, true);
  1219. wp_print_scripts(array("gforms_json"));
  1220. }
  1221. 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")){
  1222. wp_enqueue_script("gforms_gravityforms", GFCommon::get_base_url() . "/js/gravityforms.js", array("jquery"), GFCommon::$version, false);
  1223. wp_print_scripts(array("gforms_gravityforms"));
  1224. }
  1225. if(self::has_character_counter($form) && !wp_script_is("gforms_character_counter", "queue")){
  1226. wp_enqueue_script("gforms_character_counter", GFCommon::get_base_url() . "/js/jquery.textareaCounter.plugin.js", array("jquery"), GFCommon::$version, true);
  1227. wp_print_scripts(array("gforms_character_counter"));
  1228. }
  1229. if(self::has_input_mask($form) && !wp_script_is("gforms_input_mask", "queue")){
  1230. wp_enqueue_script("gforms_input_mask", GFCommon::get_base_url() . "/js/jquery.maskedinput-1.3.min.js", array("jquery"), GFCommon::$version, true);
  1231. wp_print_scripts(array("gforms_input_mask"));
  1232. }
  1233. if(self::has_enhanced_dropdown($form)&& !wp_script_is("gforms_chosen", "queue")){
  1234. wp_enqueue_script("gforms_chosen", GFCommon::get_base_url() . "/js/chosen.jquery.min.js", array("jquery"), GFCommon::$version, false);
  1235. wp_print_scripts(array("gforms_chosen"));
  1236. }
  1237. if(!wp_script_is("jquery", "queue")){
  1238. wp_print_scripts(array("jquery"));
  1239. }
  1240. if(wp_script_is("gforms_gravityforms")) {
  1241. require_once(GFCommon::get_base_path() . '/currency.php');
  1242. echo '<script type="text/javascript"> var gf_global = { gf_currency_config: ' . GFCommon::json_encode(RGCurrency::get_currency(GFCommon::get_currency())) . ' }; </script>';
  1243. }
  1244. }
  1245. private static function has_conditional_logic($form){
  1246. if(empty($form))
  1247. return false;
  1248. if(isset($form["button"]["conditionalLogic"]))
  1249. return true;
  1250. foreach($form["fields"] as $field){
  1251. if(!empty($field["conditionalLogic"])){
  1252. return true;
  1253. }
  1254. else if(isset($field["nextButton"]) && !empty($field["nextButton"]["conditionalLogic"])){
  1255. return true;
  1256. }
  1257. }
  1258. return false;
  1259. }
  1260. private static function get_conditional_logic($form){
  1261. $logics = "";
  1262. $dependents = "";
  1263. $fields_with_logic = array();
  1264. foreach($form["fields"] as $field){
  1265. //use section's logic if one exists
  1266. $section = RGFormsModel::get_section($form, $field["id"]);
  1267. $section_logic = !empty($section) ? rgar($section,"conditionalLogic") : null;
  1268. $field_logic = $field["type"] != "page" ? RGForms::get("conditionalLogic", $field) : null; //page break conditional logic will be handled during the next button click
  1269. $next_button_logic = isset($field["nextButton"]) && isset($field["nextButton"]["conditionalLogic"]) ? $field["nextButton"]["conditionalLogic"] : null;
  1270. if(!empty($field_logic) || !empty($next_button_logic)){
  1271. $field_section_logic = array("field" => $field_logic, "nextButton" => $next_button_logic, "section" => $section_logic);
  1272. $logics .= $field["id"] . ": " . GFCommon::json_encode($field_section_logic) . ",";
  1273. $fields_with_logic[] = $field["id"];
  1274. $peers = $field["type"] == "section" ? GFCommon::get_section_fields($form, $field["id"]) : array($field);
  1275. $peer_ids = array();
  1276. foreach ($peers as $peer)
  1277. $peer_ids[] = $peer["id"];
  1278. $dependents .= $field["id"] . ": " . GFCommon::json_encode($peer_ids) . ",";
  1279. }
  1280. }
  1281. $button_conditional_script = "";
  1282. //adding form button conditional logic if enabled
  1283. if(isset($form["button"]["conditionalLogic"])){
  1284. $logics .= "0: " . GFCommon::json_encode(array("field"=>$form["button"]["conditionalLogic"], "section" => null)) . ",";
  1285. $dependents .= "0: " . GFCommon::json_encode(array(0)) . ",";
  1286. $fields_with_logic[] = 0;
  1287. $button_conditional_script = "jQuery('#gform_{$form['id']}').submit(" .
  1288. "function(event, isButtonPress){" .
  1289. " var visibleButton = jQuery('.gform_next_button:visible, .gform_button:visible, .gform_image_button:visible');" .
  1290. " return visibleButton.length > 0 || isButtonPress == true;" .
  1291. "}" .
  1292. ");";
  1293. }
  1294. if(!empty($logics))
  1295. $logics = substr($logics, 0, strlen($logics) - 1); //removing last comma;
  1296. if(!empty($dependents))
  1297. $dependents = substr($dependents, 0, strlen($dependents) - 1); //removing last comma;
  1298. $animation = rgar($form,"enableAnimation") ? "1" : "0";
  1299. global $wp_locale;
  1300. $number_format = $wp_locale->number_format['decimal_point'] == "," ? "decimal_comma" : "decimal_dot";
  1301. $str = "if(window['jQuery']){" .
  1302. "if(!window['gf_form_conditional_logic'])" .
  1303. "window['gf_form_conditional_logic'] = new Array();" .
  1304. "window['gf_form_conditional_logic'][{$form['id']}] = {'logic' : {" . $logics . " }, 'dependents' : {" . $dependents . " }, 'animation' : " . $animation . " }; ".
  1305. "if(!window['gf_number_format'])" .
  1306. "window['gf_number_format'] = '" . $number_format . "';" .
  1307. "jQuery(document).ready(function(){" .
  1308. "gf_apply_rules({$form['id']}, " . GFCommon::json_encode($fields_with_logic) . ", true);" .
  1309. "jQuery('#gform_wrapper_{$form['id']}').show();" .
  1310. "jQuery(document).trigger('gform_post_conditional_logic', [{$form['id']}, null, true]);" .
  1311. $button_conditional_script .
  1312. "});" .
  1313. "} ";
  1314. return $str;
  1315. }
  1316. /**
  1317. * Enqueue and retrieve all inline scripts that should be executed when the form is rendered.
  1318. * Use add_init_script() function to enqueue scripts.
  1319. *
  1320. * @param mixed $form
  1321. */
  1322. private static function get_form_init_scripts($form) {
  1323. $script_string = '';
  1324. // adding conditional logic script if conditional logic is configured for this form.
  1325. // get_conditional_logic also adds the chosen script for the enhanced dropdown option.
  1326. // if this form does not have conditional logic, add chosen script separately
  1327. if(self::has_conditional_logic($form)){
  1328. self::add_init_script($form["id"], "conditional_logic", self::ON_PAGE_RENDER, self::get_conditional_logic($form));
  1329. }
  1330. //adding currency config if there are any product fields in the form
  1331. if(self::has_price_field($form)){
  1332. self::add_init_script($form["id"], "pricing", self::ON_PAGE_RENDER, self::get_pricing_init_script($form));
  1333. }
  1334. if(self::has_password_strength($form)){
  1335. $password_script = self::get_password_strength_init_script($form);
  1336. self::add_init_script($form["id"], "password", self::ON_PAGE_RENDER, $password_script);
  1337. }
  1338. if(self::has_enhanced_dropdown($form) ){
  1339. $chosen_script = self::get_chosen_init_script($form);
  1340. self::add_init_script($form["id"], "chosen", self::ON_PAGE_RENDER, $chosen_script);
  1341. self::add_init_script($form["id"], "chosen", self::ON_CONDITIONAL_LOGIC, $chosen_script);
  1342. }
  1343. if(GFCommon::has_credit_card_field($form)) {
  1344. self::add_init_script($form["id"], "credit_card", self::ON_PAGE_RENDER, self::get_credit_card_init_script($form));
  1345. }
  1346. if(self::has_character_counter($form)){
  1347. self::add_init_script($form['id'], 'character_counter', self::ON_PAGE_RENDER, self::get_counter_init_script($form));
  1348. }
  1349. if(self::has_input_mask($form)) {
  1350. self::add_init_script($form['id'], 'input_mask', self::ON_PAGE_RENDER, self::get_input_mask_init_script($form));
  1351. }
  1352. if(self::has_calculation_field($form)) {
  1353. self::add_init_script($form['id'], 'calculation', self::ON_PAGE_RENDER, self::get_calculations_init_script($form));
  1354. }
  1355. /* rendering initialization scripts */
  1356. $init_scripts = rgar(self::$init_scripts, $form["id"]);
  1357. if(!empty($init_scripts)){
  1358. $script_string =
  1359. "<script type='text/javascript'>" . apply_filters("gform_cdata_open", "") . " " .
  1360. "jQuery(document).bind('gform_post_render', function(event, formId, currentPage){" .
  1361. "if(formId == {$form['id']}) {";
  1362. foreach($init_scripts as $init_script){
  1363. if($init_script["location"] == self::ON_PAGE_RENDER){
  1364. $script_string .= $init_script["script"];
  1365. }
  1366. }
  1367. $script_string .=
  1368. "} ". //keep the space. needed to prevent plugins from replacing }} with ]}
  1369. "} );".
  1370. "jQuery(document).bind('gform_post_conditional_logic', function(event, formId, fields, isInit){" ;
  1371. foreach($init_scripts as $init_script){
  1372. if($init_script["location"] == self::ON_CONDITIONAL_LOGIC){
  1373. $script_string .= $init_script["script"];
  1374. }
  1375. }
  1376. $script_string .=
  1377. "});". apply_filters("gform_cdata_close", "") . "</script>";
  1378. }
  1379. return $script_string;
  1380. }
  1381. public static function get_chosen_init_script($form){
  1382. $chosen_fields = array();
  1383. foreach($form["fields"] as $field){
  1384. if(rgar($field, "enableEnhancedUI"))
  1385. $chosen_fields[] = "#input_{$form["id"]}_{$field["id"]}";
  1386. }
  1387. 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"])) . "');";
  1388. }
  1389. public static function get_counter_init_script($form){
  1390. $script = "";
  1391. foreach($form["fields"] as $field){
  1392. $max_length = rgar($field,"maxLength");
  1393. $field_id = "input_{$form["id"]}_{$field["id"]}";
  1394. if(!empty($max_length))
  1395. {
  1396. $field_script =
  1397. //****** make this callable only once ***********
  1398. "jQuery('#{$field_id}').textareaCount(" .
  1399. " {" .
  1400. " 'maxCharacterSize': {$max_length}," .
  1401. " 'originalStyle': 'ginput_counter'," .
  1402. " 'displayFormat' : '#input " . __("of", "gravityforms") . " #max " . __("max characters", "gravityforms") . "'" .
  1403. " });";
  1404. $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);
  1405. }
  1406. }
  1407. return $script;
  1408. }
  1409. public static function get_credit_card_init_script($form) {
  1410. $script = "";
  1411. foreach($form["fields"] as $field){
  1412. if($field['type'] != 'creditcard')
  1413. continue;
  1414. $field_id = "input_{$form["id"]}_{$field["id"]}";
  1415. $field_script = "jQuery(document).ready(function(){ { gformMatchCard(\"{$field_id}_1\"); } });";
  1416. if(rgar($field, "forceSSL") && !GFCommon::is_ssl() && !GFCommon::is_preview())
  1417. $field_script = "document.location.href='" . esc_js( RGFormsModel::get_current_page_url(true) ) . "'";
  1418. $script .= $field_script;
  1419. }
  1420. $card_rules = self::get_credit_card_rules();
  1421. $script = "if(!window['gf_cc_rules']){window['gf_cc_rules'] = new Array(); } window['gf_cc_rules'] = " . GFCommon::json_encode($card_rules) . "; $script";
  1422. return $script;
  1423. }
  1424. public static function get_pricing_init_script($form) {
  1425. if(!class_exists("RGCurrency"))
  1426. require_once("currency.php");
  1427. return "if(window[\"gformInitPriceFields\"]) jQuery(document).ready(function(){gformInitPriceFields();});";
  1428. }
  1429. public static function get_password_strength_init_script($form) {
  1430. $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") . "';";
  1431. foreach($form['fields'] as $field) {
  1432. if($field['type'] == 'password' && rgar($field, 'passwordStrengthEnabled')) {
  1433. $field_id = "input_{$form["id"]}_{$field["id"]}";
  1434. $field_script .= "gformShowPasswordStrength(\"$field_id\");";
  1435. }
  1436. }
  1437. return $field_script;
  1438. }
  1439. public static function get_input_mask_init_script($form) {
  1440. $script_str = '';
  1441. foreach($form['fields'] as $field) {
  1442. if(!rgar($field, 'inputMask') || !rgar($field, 'inputMaskValue'))
  1443. continue;
  1444. $mask = rgar($field, 'inputMaskValue');
  1445. $script = "jQuery('#input_{$form['id']}_{$field['id']}').mask('{$mask}'); ";
  1446. $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);
  1447. }
  1448. return $script_str;
  1449. }
  1450. public static function get_calculations_init_script($form) {
  1451. require_once(GFCommon::get_base_path() . '/currency.php');
  1452. $formula_fields = array();
  1453. foreach($form['fields'] as $field) {
  1454. if(!rgar($field, 'enableCalculation') || !rgar($field, 'calculationFormula'))
  1455. continue;
  1456. $formula_fields[] = array('field_id' => $field['id'], 'formula' => rgar($field, 'calculationFormula'), 'rounding' => rgar($field, 'calculationRounding'));
  1457. }
  1458. if(empty($formula_fields))
  1459. return '';
  1460. $script = 'new GFCalc(' . $form['id'] . ', ' . GFCommon::json_encode($formula_fields) . ');';
  1461. return $script;
  1462. }
  1463. private static function has_date_field($form){
  1464. if(is_array($form["fields"])){
  1465. foreach($form["fields"] as $field){
  1466. if(RGFormsModel::get_input_type($field) == "date")
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. private static function has_price_field($form){
  1473. $price_fields = GFCommon::get_fields_by_type($form, array("product", "donation"));
  1474. return !empty($price_fields);
  1475. }
  1476. private static function has_fileupload_field($form){
  1477. $fileupload_fields = GFCommon::get_fields_by_type($form, array("fileupload", "post_image"));
  1478. if(is_array($form["fields"])){
  1479. foreach($form["fields"] as $field){
  1480. $input_type = RGFormsModel::get_input_type($field);
  1481. if(in_array($input_type, array("fileupload", "post_image")))
  1482. return true;
  1483. }
  1484. }
  1485. return false;
  1486. }
  1487. private static function has_recaptcha_field($form){
  1488. if(is_array($form["fields"])){
  1489. foreach($form["fields"] as $field){
  1490. if(($field["type"] == "captcha" || $field["inputType"] == "captcha") && !in_array($field["captchaType"], array("simple_captcha", "math")))
  1491. return true;
  1492. }
  1493. }
  1494. return false;
  1495. }
  1496. public static function has_input_mask($form, $field = false){
  1497. if($field) {
  1498. if(self::has_field_input_mask($field))
  1499. return true;
  1500. } else {
  1501. if(!is_array($form["fields"]))
  1502. return false;
  1503. foreach($form["fields"] as $field){
  1504. if(rgar($field, "inputMask") && rgar($field, "inputMaskValue") && !rgar($field, "enablePasswordInput"))
  1505. return true;
  1506. }
  1507. }
  1508. return false;
  1509. }
  1510. public static function has_field_input_mask($field){
  1511. if(rgar($field, "inputMask") && rgar($field, "inputMaskValue") && !rgar($field, "enablePasswordInput"))
  1512. return true;
  1513. return false;
  1514. }
  1515. public static function has_calculation_field($form) {
  1516. if(!is_array($form["fields"]))
  1517. return false;
  1518. foreach($form['fields'] as $field) {
  1519. if(GFCommon::has_field_calculation($field))
  1520. return true;
  1521. }
  1522. return false;
  1523. }
  1524. //Getting all fields that have a rule based on the specified field id
  1525. private static function get_conditional_logic_fields($form, $fieldId){
  1526. $fields = array();
  1527. //adding submit button field if enabled
  1528. if(isset($form["button"]["conditionalLogic"])){
  1529. $fields[] = 0;
  1530. }
  1531. foreach($form["fields"] as $field){
  1532. if($field["type"] != "page" && !empty($field["conditionalLogic"])){
  1533. foreach($field["conditionalLogic"]["rules"] as $rule){
  1534. if($rule["fieldId"] == $fieldId){
  1535. $fields[] = $field["id"];
  1536. //if field is a section, add all fields in the section that have conditional logic (to support nesting)
  1537. if($field["type"] == "section"){
  1538. $section_fields = GFCommon::get_section_fields($form, $field["id"]);
  1539. foreach($section_fields as $section_field)
  1540. if(!empty($section_field["conditionalLogic"]))
  1541. $fields[] = $section_field["id"];
  1542. }
  1543. break;
  1544. }
  1545. }
  1546. }
  1547. //adding fields with next button logic
  1548. if(!empty($field["nextButton"]["conditionalLogic"])){
  1549. foreach($field["nextButton"]["conditionalLogic"]["rules"] as $rule){
  1550. if($rule["fieldId"] == $fieldId && !in_array($fieldId, $fields)){
  1551. $fields[] = $field["id"];
  1552. break;
  1553. }
  1554. }
  1555. }
  1556. }
  1557. return $fields;
  1558. }
  1559. public static function get_field($field, $value="", $force_frontend_label = false, $form=null, $field_values=null){
  1560. $custom_class = IS_ADMIN ? "" : rgget("cssClass", $field);
  1561. if($field["type"] == "page"){
  1562. if(IS_ADMIN && RG_CURRENT_VIEW == "entry"){
  1563. return; //ignore page breaks in the entry detail page
  1564. }
  1565. else if(!IS_ADMIN){
  1566. $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"]);
  1567. $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);
  1568. $style = self::is_page_active($form["id"], $field["pageNumber"]) ? "" : "style='display:none;'";
  1569. $custom_class = !empty($custom_class) ? " {$custom_class}" : "";
  1570. $html = "</ul>
  1571. </div>
  1572. <div class='gform_page_footer'>
  1573. {$previous_button} {$next_button}
  1574. </div>
  1575. </div>
  1576. <div id='gform_page_{$form["id"]}_{$field["pageNumber"]}' class='gform_page{$custom_class}' {$style}>
  1577. <div class='gform_page_fields'>
  1578. <ul class='gform_fields {$form['labelPlacement']}'>";
  1579. return $html;
  1580. }
  1581. }
  1582. if($field["type"] == "post_category") {
  1583. }
  1584. if(!IS_ADMIN && rgar($field,"adminOnly"))
  1585. {
  1586. if($field["allowsPrepopulate"])
  1587. $field["inputType"] = "adminonly_hidden";
  1588. else
  1589. return;
  1590. }
  1591. $id = $field["id"];
  1592. $type = $field["type"];
  1593. $input_type = RGFormsModel::get_input_type($field);
  1594. $error_class = rgget("failed_validation", $field) ? "gfield_error" : "";
  1595. $admin_only_class = rgget("adminOnly", $field) ? "field_admin_only" : "";
  1596. $selectable_class = IS_ADMIN ? "selectable" : "";
  1597. $hidden_class = in_array($input_type, array("hidden", "hiddenproduct")) ? "gform_hidden" : "";
  1598. $section_class = $field["type"] == "section" ? "gsection" : "";
  1599. $page_class = $field["type"] == "page" ? "gpage" : "";
  1600. $html_block_class = $field["type"] == "html" ? "gfield_html" : "";
  1601. $html_formatted_class = $field["type"] == "html" && !IS_ADMIN && !rgget("disableMargins", $field) ? "gfield_html_formatted" : "";
  1602. $html_no_follows_desc_class = $field["type"] == "html" && !IS_ADMIN && !self::prev_field_has_description($form, $field["id"]) ? "gfield_no_follows_desc" : "";
  1603. $calculation_class = RGFormsModel::get_input_type($field) == 'number' && GFCommon::has_field_calculation($field) ? 'gfield_calculation' : '';
  1604. $calculation_class = RGFormsModel::get_input_type($field) == 'calculation' ? 'gfield_calculation' : '';
  1605. $product_suffix = "_{$form["id"]}_" . rgget("productField", $field);
  1606. $option_class = $field["type"] == "option" ? "gfield_price gfield_price{$product_suffix} gfield_option{$product_suffix}" : "";
  1607. $quantity_class = $field["type"] == "quantity" ? "gfield_price gfield_price{$product_suffix} gfield_quantity{$product_suffix}" : "";
  1608. $shipping_class = $field["type"] == "shipping" ? "gfield_price gfield_shipping gfield_shipping_{$form["id"]}" : "";
  1609. $product_class = $field["type"] == "product" ? "gfield_price gfield_price_{$form["id"]}_{$field["id"]} gfield_product_{$form["id"]}_{$field["id"]}" : "";
  1610. $hidden_product_class = $input_type == "hiddenproduct" ? "gfield_hidden_product" : "";
  1611. $donation_class = $field["type"] == "donation" ? "gfield_price gfield_price_{$form["id"]}_{$field["id"]} gfield_donation_{$form["id"]}_{$field["id"]}" : "";
  1612. $required_class = rgar($field, "isRequired") ? "gfield_contains_required" : "";
  1613. $creditcard_warning_class = $input_type == "creditcard" && !GFCommon::is_ssl() ? "gfield_creditcard_warning" : "";
  1614. $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";
  1615. $css_class = apply_filters("gform_field_css_class_{$form["id"]}", apply_filters("gform_field_css_class", trim($css_class), $field, $form), $field, $form);
  1616. $style = !empty($form) && !IS_ADMIN && RGFormsModel::is_field_hidden($form, $field, $field_values) ? "style='display:none;'" : "";
  1617. $field_id = IS_ADMIN || empty($form) ? "field_$id" : "field_" . $form["id"] . "_$id";
  1618. return "<li id='$field_id' class='$css_class' $style>" . self::get_field_content($field, $value, $force_frontend_label, $form == null ? 0 : $form["id"]) . "</li>";
  1619. }
  1620. private static function prev_field_has_description($form, $field_id){
  1621. if(!is_array($form["fields"]))
  1622. return false;
  1623. $prev = null;
  1624. foreach($form["fields"] as $field){
  1625. if($field["id"] == $field_id){
  1626. return $prev != null && !empty($prev["description"]);
  1627. }
  1628. $prev = $field;
  1629. }
  1630. return false;
  1631. }
  1632. public static function get_field_content($field, $value="", $force_frontend_label = false, $form_id=0){
  1633. $id = $field["id"];
  1634. $size = rgar($field,"size");
  1635. $validation_message = (rgget("failed_validation", $field) && !empty($field["validation_message"])) ? sprintf("<div class='gfield_description validation_message'>%s</div>", $field["validation_message"]) : "";
  1636. $duplicate_disabled = array('captcha', 'post_title', 'post_content', 'post_excerpt', 'total', 'shipping', 'creditcard');
  1637. $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>" : "";
  1638. $duplicate_field_link = apply_filters("gform_duplicate_field_link", $duplicate_field_link);
  1639. $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>";
  1640. $delete_field_link = apply_filters("gform_delete_field_link", $delete_field_link);
  1641. $field_type_title = GFCommon::get_field_type_title($field["type"]);
  1642. $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>" : "";
  1643. $field_label = $force_frontend_label ? $field["label"] : GFCommon::get_label($field);
  1644. if(rgar($field, "inputType") == "singleproduct" && !rgempty($field["id"] . ".1", $value))
  1645. $field_label = rgar($value, $field["id"] . ".1");
  1646. $field_id = IS_ADMIN || $form_id == 0 ? "input_$id" : "input_" . $form_id . "_$id";
  1647. $required_div = IS_ADMIN || rgar($field, "isRequired") ? sprintf("<span class='gfield_required'>%s</span>", $field["isRequired"] ? "*" : "") : "";
  1648. $target_input_id = "";
  1649. $is_description_above = rgar($field, "descriptionPlacement") == "above";
  1650. switch(RGFormsModel::get_input_type($field)){
  1651. case "section" :
  1652. $description = self::get_description(rgget("description", $field), "gsection_description");
  1653. $field_content = sprintf("%s<h2 class='gsection_title'>%s</h2>%s", $admin_buttons, esc_html($field_label), $description);
  1654. break;
  1655. case "page" :
  1656. //only executed on the form editor in the admin
  1657. $page_label = __("Page Break", "gravityforms");
  1658. $src = GFCommon::get_base_url() . "/images/gf_pagebreak_inline.png";
  1659. $field_content = "{$admin_buttons} <label class='gfield_label'>&nbsp;</label><img src='{$src}' alt='{$page_label}' title='{$page_label}' />";
  1660. break;
  1661. case "adminonly_hidden":
  1662. case "hidden" :
  1663. case "html" :
  1664. $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));
  1665. break;
  1666. case "checkbox":
  1667. case "radio":
  1668. $description = self::get_description(rgget("description", $field),"gfield_description");
  1669. if($is_description_above)
  1670. $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);
  1671. else
  1672. $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);
  1673. break;
  1674. case "name" :
  1675. switch(rgar($field, "nameFormat")){
  1676. case "simple" :
  1677. $target_input_id = $field_id;
  1678. break;
  1679. case "extended" :
  1680. $target_input_id = $field_id . "_2";
  1681. break;
  1682. default :
  1683. $target_input_id = $field_id . "_3";
  1684. }
  1685. case "address" :
  1686. if(empty($target_input_id))
  1687. $target_input_id = $field_id . "_1";
  1688. default :
  1689. if(empty($target_input_id))
  1690. $target_input_id = $field_id;
  1691. $description = self::get_description(rgget("description", $field),"gfield_description");
  1692. if($is_description_above)
  1693. $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);
  1694. else
  1695. $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);
  1696. break;
  1697. }
  1698. if(RGFormsModel::get_input_type($field) == "creditcard" && !GFCommon::is_ssl() && !IS_ADMIN){
  1699. $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;
  1700. }
  1701. $value = self::default_if_empty($field, $value);
  1702. $field_content = str_replace("{FIELD}", GFCommon::get_field_input($field, $value, 0, $form_id), $field_content);
  1703. $field_content = apply_filters("gform_field_content", $field_content, $field, $value, 0, $form_id);
  1704. return $field_content;
  1705. }
  1706. private static function default_if_empty($field, $value){
  1707. if(!GFCommon::is_empty_array($value))
  1708. return $value;
  1709. if(IS_ADMIN){
  1710. $value = rgget("defaultValue", $field);
  1711. }
  1712. else{
  1713. $value = rgar($field, "defaultValue");
  1714. if(!is_array($value))
  1715. $value = GFCommon::replace_variables_prepopulate(rgget("defaultValue", $field));
  1716. }
  1717. return $value;
  1718. }
  1719. private static function get_description($description, $css_class){
  1720. return IS_ADMIN || !empty($description) ? "<div class='$css_class'>" . $description . "</div>" : "";
  1721. }
  1722. public static function get_credit_card_rules() {
  1723. $cards = GFCommon::get_card_types();
  1724. //$supported_cards = //TODO: Only include enabled cards
  1725. $rules = array();
  1726. foreach($cards as $card) {
  1727. $prefixes = explode(',', $card['prefixes']);
  1728. foreach($prefixes as $prefix) {
  1729. $rules[$card['slug']][] = $prefix;
  1730. }
  1731. }
  1732. return $rules;
  1733. }
  1734. private static function get_progress_bar($form, $form_id,$confirmation_message) {
  1735. $progress_complete = false;
  1736. $progress_bar = "";
  1737. $page_count = self::get_max_page_number($form);
  1738. $current_page = self::get_current_page($form_id);
  1739. $page_name = rgar(rgar($form["pagination"],"pages"), $current_page -1);
  1740. $page_name = !empty($page_name) ? " - " . $page_name : "";
  1741. $style = $form["pagination"]["style"];
  1742. $color = $style == "custom" ? " color:{$form["pagination"]["color"]};" : "";
  1743. $bgcolor = $style == "custom" ? " background-color:{$form["pagination"]["backgroundColor"]};" : "";
  1744. if (!empty($confirmation_message))
  1745. {
  1746. $progress_complete = true;
  1747. }
  1748. //check admin setting for whether the progress bar should start at zero
  1749. $start_at_zero = rgars($form, "pagination/display_progressbar_on_confirmation");
  1750. //check for filter
  1751. $start_at_zero = apply_filters("gform_progressbar_start_at_zero", $start_at_zero, $form);
  1752. $progressbar_page_count = $start_at_zero ? $current_page - 1 : $current_page;
  1753. $percent = !$progress_complete ? floor(( ($progressbar_page_count) / $page_count ) * 100) . "%" : "100%";
  1754. $percent_number = !$progress_complete ? floor(( ($progressbar_page_count) / $page_count ) * 100) . "" : "100";
  1755. if ($progress_complete)
  1756. {
  1757. $wrapper_css_class = GFCommon::get_browser_class() . " gform_wrapper";
  1758. //add on surrounding wrapper class when confirmation page
  1759. $progress_bar = "<div class='{$wrapper_css_class}' id='gform_wrapper_$form_id' ";
  1760. $progress_bar .= self::has_conditional_logic($form) ? "style='display:none'" : "" . ">";
  1761. $page_name = !empty($form["pagination"]["progressbar_completion_text"]) ? $form["pagination"]["progressbar_completion_text"] : "";
  1762. }
  1763. $progress_bar .="
  1764. <div id='gf_progressbar_wrapper_{$form_id}' class='gf_progressbar_wrapper'>
  1765. <h3 class='gf_progressbar_title'>";
  1766. $progress_bar .= !$progress_complete ? __("Step", "gravityforms") . " {$current_page} " . __("of", "gravityforms") . " {$page_count}{$page_name}" : "{$page_name}";
  1767. $progress_bar .= "
  1768. </h3>
  1769. <div class='gf_progressbar'>
  1770. <div class='gf_progressbar_percentage percentbar_{$style} percentbar_{$percent_number}' style='width:{$percent};{$color}{$bgcolor}'><span>{$percent}</span></div>
  1771. </div></div>";
  1772. //close div for surrounding wrapper class when confirmation page
  1773. $progress_bar .= $progress_complete ? "</div>" : "";
  1774. return $progress_bar;
  1775. }
  1776. /**
  1777. * Validates the form's entry limit settings. Returns the entry limit message if entry limit exceeded.
  1778. *
  1779. * @param array $form current GF form object
  1780. * @return string If entry limit exceeded returns entry limit setting.
  1781. */
  1782. public static function validate_entry_limit($form) {
  1783. //If form has a limit of entries, check current entry count
  1784. if(rgar($form,"limitEntries")) {
  1785. $period = rgar($form, "limitEntriesPeriod");
  1786. $range = self::get_limit_period_dates($period);
  1787. $entry_count = RGFormsModel::get_lead_count($form['id'], "", null, null, $range["start_date"], $range["end_date"]);
  1788. if($entry_count >= $form["limitEntriesCount"])
  1789. return empty($form["limitEntriesMessage"]) ? "<p>" . __("Sorry. This form is no longer accepting new submissions.", "gravityforms"). "</p>" : "<p>" . GFCommon::gform_do_shortcode($form["limitEntriesMessage"]) . "</p>";
  1790. }
  1791. }
  1792. public static function validate_form_schedule($form) {
  1793. //If form has a schedule, make sure it is within the configured start and end dates
  1794. if(rgar($form, "scheduleForm")){
  1795. $local_time_start = sprintf("%s %02d:%02d %s", $form["scheduleStart"], $form["scheduleStartHour"], $form["scheduleStartMinute"], $form["scheduleStartAmpm"]);
  1796. $local_time_end = sprintf("%s %02d:%02d %s", $form["scheduleEnd"], $form["scheduleEndHour"], $form["scheduleEndMinute"], $form["scheduleEndAmpm"]);
  1797. $timestamp_start = strtotime($local_time_start . ' +0000');
  1798. $timestamp_end = strtotime($local_time_end . ' +0000');
  1799. $now = current_time("timestamp");
  1800. if( (!empty($form["scheduleStart"]) && $now < $timestamp_start) || (!empty($form["scheduleEnd"]) && $now > $timestamp_end))
  1801. return empty($form["scheduleMessage"]) ? "<p>" . __("Sorry. This form is no longer available.", "gravityforms") . "</p>" : "<p>" . GFCommon::gform_do_shortcode($form["scheduleMessage"]) . "</p>";
  1802. }
  1803. }
  1804. }
  1805. ?>