PageRenderTime 65ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 1ms

/plugins/gravityforms/forms_model.php

https://github.com/petergibbons/OpenCounterWP
PHP | 2738 lines | 2154 code | 484 blank | 100 comment | 392 complexity | 2f6009b54b6509716289be16ffd848b2 MD5 | raw file
  1. <?php
  2. require_once(ABSPATH . "/wp-includes/post.php");
  3. define("GFORMS_MAX_FIELD_LENGTH", 200);
  4. class RGFormsModel{
  5. public static $uploaded_files = array();
  6. public static function get_form_table_name(){
  7. global $wpdb;
  8. return $wpdb->prefix . "rg_form";
  9. }
  10. public static function get_meta_table_name(){
  11. global $wpdb;
  12. return $wpdb->prefix . "rg_form_meta";
  13. }
  14. public static function get_form_view_table_name(){
  15. global $wpdb;
  16. return $wpdb->prefix . "rg_form_view";
  17. }
  18. public static function get_lead_table_name(){
  19. global $wpdb;
  20. return $wpdb->prefix . "rg_lead";
  21. }
  22. public static function get_lead_meta_table_name(){
  23. global $wpdb;
  24. return $wpdb->prefix . "rg_lead_meta";
  25. }
  26. public static function get_lead_notes_table_name(){
  27. global $wpdb;
  28. return $wpdb->prefix . "rg_lead_notes";
  29. }
  30. public static function get_lead_details_table_name(){
  31. global $wpdb;
  32. return $wpdb->prefix . "rg_lead_detail";
  33. }
  34. public static function get_lead_details_long_table_name(){
  35. global $wpdb;
  36. return $wpdb->prefix . "rg_lead_detail_long";
  37. }
  38. public static function get_lead_view_name(){
  39. global $wpdb;
  40. return $wpdb->prefix . "rg_lead_view";
  41. }
  42. public static function get_forms($is_active = null, $sort="title ASC"){
  43. global $wpdb;
  44. $form_table_name = self::get_form_table_name();
  45. $lead_table_name = self::get_lead_table_name();
  46. $view_table_name = self::get_form_view_table_name();
  47. $active_clause = $is_active !== null ? $wpdb->prepare("WHERE is_active=%d", $is_active) : "";
  48. $order_by = !empty($sort) ? "ORDER BY $sort" : "";
  49. $sql = "SELECT f.id, f.title, f.date_created, f.is_active, 0 as lead_count, 0 view_count
  50. FROM $form_table_name f
  51. $active_clause
  52. $order_by";
  53. //Getting all forms
  54. $forms = $wpdb->get_results($sql);
  55. //Getting entry count per form
  56. $sql = "SELECT form_id, count(id) as lead_count FROM $lead_table_name l WHERE status='active' GROUP BY form_id";
  57. $entry_count = $wpdb->get_results($sql);
  58. //Getting view count per form
  59. $sql = "SELECT form_id, sum(count) as view_count FROM $view_table_name GROUP BY form_id";
  60. $view_count = $wpdb->get_results($sql);
  61. //Adding entry counts and to form array
  62. foreach($forms as &$form){
  63. foreach($view_count as $count){
  64. if($count->form_id == $form->id){
  65. $form->view_count = $count->view_count;
  66. break;
  67. }
  68. }
  69. foreach($entry_count as $count){
  70. if($count->form_id == $form->id){
  71. $form->lead_count = $count->lead_count;
  72. break;
  73. }
  74. }
  75. }
  76. return $forms;
  77. }
  78. public static function get_forms_by_id($ids){
  79. global $wpdb;
  80. $form_table_name = self::get_form_table_name();
  81. $meta_table_name = self::get_meta_table_name();
  82. if(is_array($ids))
  83. $ids = implode(",", $ids);
  84. $results = $wpdb->get_results(" SELECT display_meta FROM {$form_table_name} f
  85. INNER JOIN {$meta_table_name} m ON f.id = m.form_id
  86. WHERE id in({$ids})", ARRAY_A);
  87. foreach ($results as &$result)
  88. $result = maybe_unserialize($result["display_meta"]);
  89. return $results;
  90. }
  91. public static function get_form_payment_totals($form_id){
  92. global $wpdb;
  93. $lead_table_name = self::get_lead_table_name();
  94. $sql = $wpdb->prepare(" SELECT sum(payment_amount) revenue, count(l.id) orders
  95. FROM $lead_table_name l
  96. WHERE form_id=%d AND payment_amount IS NOT null", $form_id);
  97. $totals = $wpdb->get_row($sql, ARRAY_A);
  98. $active = $wpdb->get_var($wpdb->prepare(" SELECT count(id) as active
  99. FROM $lead_table_name
  100. WHERE form_id=%d AND payment_status='Active'", $form_id));
  101. if(empty($active))
  102. $active = 0;
  103. $totals["active"] = $active;
  104. return $totals;
  105. }
  106. public static function get_form_counts($form_id){
  107. global $wpdb;
  108. $lead_table_name = self::get_lead_table_name();
  109. $sql = $wpdb->prepare(
  110. "SELECT
  111. (SELECT count(0) FROM $lead_table_name WHERE form_id=%d AND status='active') as total,
  112. (SELECT count(0) FROM $lead_table_name WHERE is_read=0 AND status='active' AND form_id=%d) as unread,
  113. (SELECT count(0) FROM $lead_table_name WHERE is_starred=1 AND status='active' AND form_id=%d) as starred,
  114. (SELECT count(0) FROM $lead_table_name WHERE status='spam' AND form_id=%d) as spam,
  115. (SELECT count(0) FROM $lead_table_name WHERE status='trash' AND form_id=%d) as trash",
  116. $form_id, $form_id, $form_id, $form_id, $form_id);
  117. $results = $wpdb->get_results($sql, ARRAY_A);
  118. return $results[0];
  119. }
  120. public static function get_form_summary(){
  121. global $wpdb;
  122. $form_table_name = self::get_form_table_name();
  123. $lead_table_name = self::get_lead_table_name();
  124. $sql = "SELECT l.form_id, count(l.id) as unread_count
  125. FROM $lead_table_name l
  126. WHERE is_read=0 AND status='active'
  127. GROUP BY form_id";
  128. //getting number of unread and total leads for all forms
  129. $unread_results = $wpdb->get_results($sql, ARRAY_A);
  130. $sql = "SELECT l.form_id, max(l.date_created) as last_lead_date, count(l.id) as total_leads
  131. FROM $lead_table_name l
  132. WHERE status='active'
  133. GROUP BY form_id";
  134. $lead_date_results = $wpdb->get_results($sql, ARRAY_A);
  135. $sql = "SELECT id, title, '' as last_lead_date, 0 as unread_count
  136. FROM $form_table_name
  137. WHERE is_active=1
  138. ORDER BY title";
  139. $forms = $wpdb->get_results($sql, ARRAY_A);
  140. for($i=0; $count = sizeof($forms), $i<$count; $i++){
  141. if(is_array($unread_results)){
  142. foreach($unread_results as $unread_result){
  143. if($unread_result["form_id"] == $forms[$i]["id"]){
  144. $forms[$i]["unread_count"] = $unread_result["unread_count"];
  145. break;
  146. }
  147. }
  148. }
  149. if(is_array($lead_date_results)){
  150. foreach($lead_date_results as $lead_date_result){
  151. if($lead_date_result["form_id"] == $forms[$i]["id"]){
  152. $forms[$i]["last_lead_date"] = $lead_date_result["last_lead_date"];
  153. $forms[$i]["total_leads"] = $lead_date_result["total_leads"];
  154. break;
  155. }
  156. }
  157. }
  158. }
  159. return $forms;
  160. }
  161. public static function get_form_count(){
  162. global $wpdb;
  163. $form_table_name = self::get_form_table_name();
  164. $results = $wpdb->get_results("SELECT count(0) as count FROM $form_table_name UNION ALL SELECT count(0) as count FROM $form_table_name WHERE is_active=1 ");
  165. return array( "total" => intval($results[0]->count),
  166. "active" => intval($results[1]->count),
  167. "inactive" => intval($results[0]->count) - intval($results[1]->count)
  168. );
  169. }
  170. public static function get_form_id($form_title){
  171. $forms = self::get_forms();
  172. foreach($forms as $form){
  173. $sanitized_name = str_replace("[", "", str_replace("]","", $form->title));
  174. if($form->title == $form_title || $sanitized_name == $form_title)
  175. return $form->id;
  176. }
  177. return 0;
  178. }
  179. public static function get_form($form_id){
  180. global $wpdb;
  181. $table_name = self::get_form_table_name();
  182. $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE id=%d", $form_id));
  183. return $results[0];
  184. }
  185. public static function get_form_meta($form_id){
  186. global $wpdb;
  187. $table_name = self::get_meta_table_name();
  188. $form = maybe_unserialize($wpdb->get_var($wpdb->prepare("SELECT display_meta FROM $table_name WHERE form_id=%d", $form_id)));
  189. $page_number = 1;
  190. $description_placement = rgar($form, "descriptionPlacement") == "above" ? "above" : "below";
  191. if(is_array($form["fields"])){
  192. foreach($form["fields"] as &$field){
  193. $field["formId"] = $form["id"];
  194. $field["pageNumber"] = $page_number;
  195. $field["descriptionPlacement"] = $description_placement;
  196. if($field["type"] == "page"){
  197. $page_number++;
  198. $field["pageNumber"] = $page_number;
  199. }
  200. }
  201. }
  202. return $form;
  203. }
  204. public static function add_default_properties($form){
  205. if(is_array($form["fields"])){
  206. $all_fields = array("adminLabel"=>"","adminOnly"=>"","allowsPrepopulate"=>"","defaultValue"=>"","description"=>"","content"=>"","cssClass"=>"",
  207. "errorMessage"=>"","id"=>"","inputName"=>"","isRequired"=>"","label"=>"","noDuplicates"=>"",
  208. "size"=>"","type"=>"","postCustomFieldName"=>"","displayAllCategories"=>"","displayCaption"=>"","displayDescription"=>"",
  209. "displayTitle"=>"","inputType"=>"","rangeMin"=>"","rangeMax"=>"","calendarIconType"=>"",
  210. "calendarIconUrl"=>"", "dateType"=>"","dateFormat"=>"","phoneFormat"=>"","addressType"=>"","defaultCountry"=>"","defaultProvince"=>"",
  211. "defaultState"=>"","hideAddress2"=>"","hideCountry"=>"","hideState"=>"","inputs"=>"","nameFormat"=>"","allowedExtensions"=>"",
  212. "captchaType"=>"","page_number"=>"","captchaTheme"=>"","simpleCaptchaSize"=>"","simpleCaptchaFontColor"=>"","simpleCaptchaBackgroundColor"=>"",
  213. "failed_validation"=>"", "productField" => "", "enablePasswordInput" => "", "maxLength" => "", "enablePrice" => "", "basePrice" => "");
  214. foreach($form["fields"] as &$field)
  215. $field = wp_parse_args($field, $all_fields);
  216. }
  217. return $form;
  218. }
  219. public static function get_grid_column_meta($form_id){
  220. global $wpdb;
  221. $table_name = self::get_meta_table_name();
  222. return maybe_unserialize($wpdb->get_var($wpdb->prepare("SELECT entries_grid_meta FROM $table_name WHERE form_id=%d", $form_id)));
  223. }
  224. public static function update_grid_column_meta($form_id, $columns){
  225. global $wpdb;
  226. $table_name = self::get_meta_table_name();
  227. $meta = maybe_serialize(stripslashes_deep($columns) );
  228. $wpdb->query( $wpdb->prepare("UPDATE $table_name SET entries_grid_meta=%s WHERE form_id=%d", $meta, $form_id) );
  229. }
  230. public static function get_lead_detail_id($current_fields, $field_number){
  231. foreach($current_fields as $field)
  232. if($field->field_number == $field_number)
  233. return $field->id;
  234. return 0;
  235. }
  236. public static function update_form_active($form_id, $is_active){
  237. global $wpdb;
  238. $form_table = self::get_form_table_name();
  239. $sql = $wpdb->prepare("UPDATE $form_table SET is_active=%d WHERE id=%d", $is_active, $form_id);
  240. $wpdb->query($sql);
  241. }
  242. public static function update_forms_active($forms, $is_active){
  243. foreach($forms as $form_id)
  244. self::update_form_active($form_id, $is_active);
  245. }
  246. public static function update_leads_property($leads, $property_name, $property_value){
  247. foreach($leads as $lead)
  248. self::update_lead_property($lead, $property_name, $property_value);
  249. }
  250. public static function update_lead_property($lead_id, $property_name, $property_value, $update_akismet=true, $disable_hook=false){
  251. global $wpdb;
  252. $lead_table = self::get_lead_table_name();
  253. $lead = self::get_lead($lead_id);
  254. //marking entry as "spam" or "not spam" with Akismet if the plugin is installed
  255. if($update_akismet && GFCommon::akismet_enabled($lead["form_id"]) && $property_name == "status" && in_array($property_value, array("active", "spam"))){
  256. $current_status = $lead["status"];
  257. if($current_status == "spam" && $property_value == "active"){
  258. $form = self::get_form_meta($lead["form_id"]);
  259. GFCommon::mark_akismet_spam($form, $lead, false);
  260. }
  261. else if($current_status == "active" && $property_value == "spam"){
  262. $form = self::get_form_meta($lead["form_id"]);
  263. GFCommon::mark_akismet_spam($form, $lead, true);
  264. }
  265. }
  266. //updating lead
  267. $wpdb->update($lead_table, array($property_name => $property_value ), array("id" => $lead_id));
  268. if(!$disable_hook){
  269. $previous_value = rgar($lead, $property_name);
  270. if($previous_value != $property_value) {
  271. // if property is status, prev value is spam and new value is active
  272. if($property_name == 'status' && $previous_value == 'spam' && $property_value == 'active' && !rgar($lead, 'post_id')) {
  273. $lead[$property_name] = $property_value;
  274. $lead['post_id'] = GFCommon::create_post($form, $lead);
  275. }
  276. do_action("gform_update_{$property_name}", $lead_id, $property_value, $previous_value);
  277. }
  278. }
  279. }
  280. public static function update_lead($lead){
  281. global $wpdb;
  282. $lead_table = self::get_lead_table_name();
  283. $payment_date = strtotime(rgar($lead,"payment_date")) ? "'{$lead["payment_date"]}'" : "NULL";
  284. $payment_amount = !rgempty("payment_amount", $lead) ? $lead["payment_amount"] : "NULL";
  285. $transaction_type = !rgempty("transaction_type", $lead) ? $lead["transaction_type"] : "NULL";
  286. $status = !rgempty("status", $lead) ? $lead["status"] : "active";
  287. $sql = $wpdb->prepare("UPDATE $lead_table SET
  288. form_id=%d,
  289. post_id=%d,
  290. is_starred=%d,
  291. is_read=%d,
  292. ip=%s,
  293. source_url=%s,
  294. user_agent=%s,
  295. currency=%s,
  296. payment_status=%s,
  297. payment_date={$payment_date},
  298. payment_amount={$payment_amount},
  299. transaction_id=%s,
  300. is_fulfilled=%d,
  301. transaction_type={$transaction_type},
  302. status='{$status}'
  303. WHERE id=%d", rgar($lead,"form_id"), rgar($lead,"post_id"), rgar($lead,"is_starred"), rgar($lead,"is_read"), rgar($lead,"ip"), rgar($lead,"source_url"), rgar($lead,"user_agent"),
  304. rgar($lead,"currency"), rgar($lead,"payment_status"), rgar($lead,"transaction_id"), rgar($lead,"is_fulfilled"), rgar($lead,"id"));
  305. $wpdb->query($sql);
  306. }
  307. public static function delete_leads($leads){
  308. foreach($leads as $lead_id)
  309. self::delete_lead($lead_id);
  310. }
  311. public static function delete_forms($forms){
  312. foreach($forms as $form_id)
  313. self::delete_form($form_id);
  314. }
  315. public static function delete_leads_by_form($form_id, $status=""){
  316. global $wpdb;
  317. if(!GFCommon::current_user_can_any("gravityforms_delete_entries"))
  318. die(__("You don't have adequate permission to delete entries.", "gravityforms"));
  319. $lead_table = self::get_lead_table_name();
  320. $lead_notes_table = self::get_lead_notes_table_name();
  321. $lead_detail_table = self::get_lead_details_table_name();
  322. $lead_detail_long_table = self::get_lead_details_long_table_name();
  323. //deleting uploaded files
  324. self::delete_files_by_form($form_id, $status);
  325. $status_filter = empty($status) ? "" : $wpdb->prepare("AND status=%s", $status);
  326. //Delete from detail long
  327. $sql = $wpdb->prepare(" DELETE FROM $lead_detail_long_table
  328. WHERE lead_detail_id IN(
  329. SELECT ld.id FROM $lead_detail_table ld
  330. INNER JOIN $lead_table l ON l.id = ld.lead_id
  331. WHERE l.form_id=%d AND ld.form_id=%d {$status_filter}
  332. )", $form_id, $form_id);
  333. $wpdb->query($sql);
  334. //Delete from lead details
  335. $sql = $wpdb->prepare(" DELETE FROM $lead_detail_table
  336. WHERE lead_id IN (
  337. SELECT id FROM $lead_table WHERE form_id=%d {$status_filter}
  338. )", $form_id);
  339. $wpdb->query($sql);
  340. //Delete from lead notes
  341. $sql = $wpdb->prepare(" DELETE FROM $lead_notes_table
  342. WHERE lead_id IN (
  343. SELECT id FROM $lead_table WHERE form_id=%d {$status_filter}
  344. )", $form_id);
  345. $wpdb->query($sql);
  346. //Delete from lead
  347. $sql = $wpdb->prepare("DELETE FROM $lead_table WHERE form_id=%d {$status_filter}", $form_id);
  348. $wpdb->query($sql);
  349. }
  350. public static function delete_views($form_id){
  351. global $wpdb;
  352. $form_view_table = self::get_form_view_table_name();
  353. //Delete form view
  354. $sql = $wpdb->prepare("DELETE FROM $form_view_table WHERE form_id=%d", $form_id);
  355. $wpdb->query($sql);
  356. }
  357. public static function delete_form($form_id){
  358. global $wpdb;
  359. if(!GFCommon::current_user_can_any("gravityforms_delete_forms"))
  360. die(__("You don't have adequate permission to delete forms.", "gravityforms"));
  361. do_action("gform_before_delete_form", $form_id);
  362. $form_meta_table = self::get_meta_table_name();
  363. $form_table = self::get_form_table_name();
  364. //Deleting form Entries
  365. self::delete_leads_by_form($form_id);
  366. //Delete form meta
  367. $sql = $wpdb->prepare("DELETE FROM $form_meta_table WHERE form_id=%d", $form_id);
  368. $wpdb->query($sql);
  369. //Deleting form Views
  370. self::delete_views($form_id);
  371. //Delete form
  372. $sql = $wpdb->prepare("DELETE FROM $form_table WHERE id=%d", $form_id);
  373. $wpdb->query($sql);
  374. do_action("gform_after_delete_form", $form_id);
  375. }
  376. public static function duplicate_form($form_id){
  377. global $wpdb;
  378. if(!GFCommon::current_user_can_any("gravityforms_create_form"))
  379. die(__("You don't have adequate permission to create forms.", "gravityforms"));
  380. //finding unique title
  381. $form = self::get_form($form_id);
  382. $count = 2;
  383. $title = $form->title . " - Copy 1";
  384. while(!self::is_unique_title($title)){
  385. $title = $form->title . " - Copy $count";
  386. $count++;
  387. }
  388. //creating new form
  389. $new_id = self::insert_form($title);
  390. //copying form meta
  391. $meta = self::get_form_meta($form_id);
  392. $meta["title"] = $title;
  393. $meta["id"] = $new_id;
  394. self::update_form_meta($new_id, $meta);
  395. return $new_id;
  396. }
  397. public static function is_unique_title($title){
  398. $forms = self::get_forms();
  399. foreach($forms as $form){
  400. if(strtolower($form->title) == strtolower($title))
  401. return false;
  402. }
  403. return true;
  404. }
  405. public static function insert_form($form_title){
  406. global $wpdb;
  407. $form_table_name = $wpdb->prefix . "rg_form";
  408. //creating new form
  409. $wpdb->query($wpdb->prepare("INSERT INTO $form_table_name(title, date_created) VALUES(%s, utc_timestamp())", $form_title));
  410. //returning newly created form id
  411. return $wpdb->insert_id;
  412. }
  413. public static function update_form_meta($form_id, $form_meta){
  414. global $wpdb;
  415. $meta_table_name = self::get_meta_table_name();
  416. $form_meta = maybe_serialize($form_meta);
  417. if(intval($wpdb->get_var($wpdb->prepare("SELECT count(0) FROM $meta_table_name WHERE form_id=%d", $form_id))) > 0)
  418. $wpdb->query( $wpdb->prepare("UPDATE $meta_table_name SET display_meta=%s WHERE form_id=%d", $form_meta, $form_id) );
  419. else
  420. $wpdb->query( $wpdb->prepare("INSERT INTO $meta_table_name(form_id, display_meta) VALUES(%d, %s)", $form_id, $form_meta ) );
  421. }
  422. public static function delete_files($lead_id, $form=null){
  423. $lead = self::get_lead($lead_id);
  424. if($form == null)
  425. $form = self::get_form_meta($lead["form_id"]);
  426. $fields = GFCommon::get_fields_by_type($form, array("fileupload", "post_image"));
  427. if(is_array($fields)){
  428. foreach($fields as $field){
  429. $value = self::get_lead_field_value($lead, $field);
  430. self::delete_physical_file($value);
  431. }
  432. }
  433. }
  434. public static function delete_files_by_form($form_id, $status=""){
  435. global $wpdb;
  436. $form = self::get_form_meta($form_id);
  437. $fields = GFCommon::get_fields_by_type($form, array("fileupload", "post_image"));
  438. if(empty($fields))
  439. return;
  440. $status_filter = empty($status) ? "" : $wpdb->prepare("AND status=%s", $status);
  441. $results = $wpdb->get_results($wpdb->prepare("SELECT id FROM {$wpdb->prefix}rg_lead WHERE form_id=%d {$status_filter}", $form_id), ARRAY_A);
  442. foreach($results as $result){
  443. self::delete_files($result["id"], $form);
  444. }
  445. }
  446. public static function delete_file($lead_id, $field_id){
  447. global $wpdb;
  448. if($lead_id == 0 || $field_id == 0)
  449. return;
  450. $lead_detail_table = self::get_lead_details_table_name();
  451. //Deleting file
  452. $sql = $wpdb->prepare("SELECT value FROM $lead_detail_table WHERE lead_id=%d AND field_number BETWEEN %f AND %f", $lead_id, $field_id - 0.001, $field_id + 0.001);
  453. $file_path = $wpdb->get_var($sql);
  454. self::delete_physical_file($file_path);
  455. //Delete from lead details
  456. $sql = $wpdb->prepare("DELETE FROM $lead_detail_table WHERE lead_id=%d AND field_number BETWEEN %f AND %f", $lead_id, $field_id - 0.001, $field_id + 0.001);
  457. $wpdb->query($sql);
  458. }
  459. private static function delete_physical_file($file_url){
  460. $ary = explode("|:|", $file_url);
  461. $url = rgar($ary,0);
  462. if(empty($url))
  463. return;
  464. //Convert from url to physical path
  465. if (is_multisite()) {
  466. $file_path = preg_replace("|^(.*?)/files/gravity_forms/|", BLOGUPLOADDIR . "gravity_forms/", $url);
  467. }
  468. else {
  469. $file_path = str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $url);
  470. }
  471. if(file_exists($file_path)){
  472. unlink($file_path);
  473. }
  474. }
  475. public static function delete_field($form_id, $field_id){
  476. global $wpdb;
  477. if($form_id == 0)
  478. return;
  479. do_action("gform_before_delete_field", $form_id, $field_id);
  480. $lead_table = self::get_lead_table_name();
  481. $lead_detail_table = self::get_lead_details_table_name();
  482. $lead_detail_long_table = self::get_lead_details_long_table_name();
  483. $form = self::get_form_meta($form_id);
  484. $field_type = "";
  485. //Deleting field from form meta
  486. $count = sizeof($form["fields"]);
  487. for($i = $count-1; $i >= 0; $i--){
  488. $field = $form["fields"][$i];
  489. //Deleting associated conditional logic rules
  490. if(!empty($field["conditionalLogic"])){
  491. $rule_count = sizeof($field["conditionalLogic"]["rules"]);
  492. for($j = $rule_count-1; $j >= 0; $j--){
  493. if($field["conditionalLogic"]["rules"][$j]["fieldId"] == $field_id){
  494. unset($form["fields"][$i]["conditionalLogic"]["rules"][$j]);
  495. }
  496. }
  497. $form["fields"][$i]["conditionalLogic"]["rules"] = array_values($form["fields"][$i]["conditionalLogic"]["rules"]);
  498. //If there aren't any rules, remove the conditional logic
  499. if(sizeof($form["fields"][$i]["conditionalLogic"]["rules"]) == 0){
  500. $form["fields"][$i]["conditionalLogic"] = false;
  501. }
  502. }
  503. //Deleting field from form meta
  504. if($field["id"] == $field_id){
  505. $field_type = $field["type"];
  506. unset($form["fields"][$i]);
  507. }
  508. }
  509. //removing post content and title template if the field being deleted is a post content field or post title field
  510. if($field_type == "post_content"){
  511. $form["postContentTemplateEnabled"] = false;
  512. $form["postContentTemplate"] = "";
  513. }
  514. else if($field_type == "post_title"){
  515. $form["postTitleTemplateEnabled"] = false;
  516. $form["postTitleTemplate"] = "";
  517. }
  518. //Deleting associated routing rules
  519. if(!empty($form["notification"]["routing"])){
  520. $routing_count = sizeof($form["notification"]["routing"]);
  521. for($j = $routing_count-1; $j >= 0; $j--){
  522. if(intval($form["notification"]["routing"][$j]["fieldId"]) == $field_id){
  523. unset($form["notification"]["routing"][$j]);
  524. }
  525. }
  526. $form["notification"]["routing"] = array_values($form["notification"]["routing"]);
  527. //If there aren't any routing, remove it
  528. if(sizeof($form["notification"]["routing"]) == 0){
  529. $form["notification"]["routing"] = null;
  530. }
  531. }
  532. $form["fields"] = array_values($form["fields"]);
  533. self::update_form_meta($form_id, $form);
  534. //Delete from grid column meta
  535. $columns = self::get_grid_column_meta($form_id);
  536. $count = sizeof($columns);
  537. for($i = $count -1; $i >=0; $i--)
  538. {
  539. if(intval(rgar($columns,$i)) == intval($field_id)){
  540. unset($columns[$i]);
  541. }
  542. }
  543. self::update_grid_column_meta($form_id, $columns);
  544. //Delete from detail long
  545. $sql = $wpdb->prepare(" DELETE FROM $lead_detail_long_table
  546. WHERE lead_detail_id IN(
  547. SELECT id FROM $lead_detail_table WHERE form_id=%d AND field_number >= %d AND field_number < %d
  548. )", $form_id, $field_id, $field_id + 1);
  549. $wpdb->query($sql);
  550. //Delete from lead details
  551. $sql = $wpdb->prepare("DELETE FROM $lead_detail_table WHERE form_id=%d AND field_number >= %d AND field_number < %d", $form_id, $field_id, $field_id + 1);
  552. $wpdb->query($sql);
  553. //Delete leads with no details
  554. $sql = $wpdb->prepare(" DELETE FROM $lead_table
  555. WHERE form_id=%d
  556. AND id NOT IN(
  557. SELECT DISTINCT(lead_id) FROM $lead_detail_table WHERE form_id=%d
  558. )", $form_id, $form_id);
  559. $wpdb->query($sql);
  560. do_action("gform_after_delete_field", $form_id, $field_id);
  561. }
  562. public static function delete_lead($lead_id){
  563. global $wpdb;
  564. if(!GFCommon::current_user_can_any("gravityforms_delete_entries"))
  565. die(__("You don't have adequate permission to delete entries.", "gravityforms"));
  566. do_action("gform_delete_lead", $lead_id);
  567. $lead_table = self::get_lead_table_name();
  568. $lead_notes_table = self::get_lead_notes_table_name();
  569. $lead_detail_table = self::get_lead_details_table_name();
  570. $lead_detail_long_table = self::get_lead_details_long_table_name();
  571. //deleting uploaded files
  572. self::delete_files($lead_id);
  573. //Delete from detail long
  574. $sql = $wpdb->prepare(" DELETE FROM $lead_detail_long_table
  575. WHERE lead_detail_id IN(
  576. SELECT id FROM $lead_detail_table WHERE lead_id=%d
  577. )", $lead_id);
  578. $wpdb->query($sql);
  579. //Delete from lead details
  580. $sql = $wpdb->prepare("DELETE FROM $lead_detail_table WHERE lead_id=%d", $lead_id);
  581. $wpdb->query($sql);
  582. //Delete from lead notes
  583. $sql = $wpdb->prepare("DELETE FROM $lead_notes_table WHERE lead_id=%d", $lead_id);
  584. $wpdb->query($sql);
  585. //Delete from lead meta
  586. gform_delete_meta($lead_id);
  587. //Delete from lead
  588. $sql = $wpdb->prepare("DELETE FROM $lead_table WHERE id=%d", $lead_id);
  589. $wpdb->query($sql);
  590. }
  591. public static function add_note($lead_id, $user_id, $user_name, $note){
  592. global $wpdb;
  593. $table_name = self::get_lead_notes_table_name();
  594. $sql = $wpdb->prepare("INSERT INTO $table_name(lead_id, user_id, user_name, value, date_created) values(%d, %d, %s, %s, utc_timestamp())", $lead_id, $user_id, $user_name, $note);
  595. $wpdb->query($sql);
  596. }
  597. public static function delete_note($note_id){
  598. global $wpdb;
  599. if(!GFCommon::current_user_can_any("gravityforms_edit_entry_notes"))
  600. die(__("You don't have adequate permission to delete notes.", "gravityforms"));
  601. $table_name = self::get_lead_notes_table_name();
  602. $sql = $wpdb->prepare("DELETE FROM $table_name WHERE id=%d", $note_id);
  603. $wpdb->query($sql);
  604. }
  605. public static function delete_notes($notes){
  606. if(!is_array($notes))
  607. return;
  608. foreach($notes as $note_id){
  609. self::delete_note($note_id);
  610. }
  611. }
  612. public static function get_ip(){
  613. $ip = rgget("HTTP_X_FORWARDED_FOR", $_SERVER);
  614. if (!$ip)
  615. $ip = rgget("REMOTE_ADDR", $_SERVER);
  616. $ip_array = explode(",", $ip); //HTTP_X_FORWARDED_FOR can return a comma separated list of IPs. Using the first one.
  617. return $ip_array[0];
  618. }
  619. public static function save_lead($form, &$lead){
  620. global $wpdb;
  621. if(IS_ADMIN && !GFCommon::current_user_can_any("gravityforms_edit_entries"))
  622. die(__("You don't have adequate permission to edit entries.", "gravityforms"));
  623. $lead_detail_table = self::get_lead_details_table_name();
  624. //Inserting lead if null
  625. if($lead == null){
  626. global $current_user;
  627. $user_id = $current_user && $current_user->ID ? $current_user->ID : 'NULL';
  628. $lead_table = RGFormsModel::get_lead_table_name();
  629. $user_agent = strlen($_SERVER["HTTP_USER_AGENT"]) > 250 ? substr($_SERVER["HTTP_USER_AGENT"], 0, 250) : $_SERVER["HTTP_USER_AGENT"];
  630. $currency = GFCommon::get_currency();
  631. $wpdb->query($wpdb->prepare("INSERT INTO $lead_table(form_id, ip, source_url, date_created, user_agent, currency, created_by) VALUES(%d, %s, %s, utc_timestamp(), %s, %s, {$user_id})", $form["id"], self::get_ip(), self::get_current_page_url(), $user_agent, $currency));
  632. //reading newly created lead id
  633. $lead_id = $wpdb->insert_id;
  634. $lead = array("id" => $lead_id);
  635. }
  636. $current_fields = $wpdb->get_results($wpdb->prepare("SELECT id, field_number FROM $lead_detail_table WHERE lead_id=%d", $lead["id"]));
  637. $original_post_id = rgget("post_id", $lead);
  638. $total_field = null;
  639. $calculation_fields = array();
  640. $recalculate_total = false;
  641. foreach($form["fields"] as $field){
  642. //Ignore fields that are marked as display only
  643. if(rgget("displayOnly", $field) && $field["type"] != "password"){
  644. continue;
  645. }
  646. //ignore pricing fields in the entry detail
  647. if(RG_CURRENT_VIEW == "entry" && GFCommon::is_pricing_field($field["type"])){
  648. continue;
  649. }
  650. //process total field after all fields have been saved
  651. if($field["type"] == "total"){
  652. $total_field = $field;
  653. continue;
  654. }
  655. // process calculation fields after all fields have been saved
  656. if(GFCommon::has_field_calculation($field)) {
  657. $calculation_fields[] = $field;
  658. continue;
  659. }
  660. //only save fields that are not hidden (except on entry screen)
  661. if(RG_CURRENT_VIEW == "entry" || !RGFormsModel::is_field_hidden($form, $field, array()) ){
  662. if($field['type'] == 'post_category')
  663. $field = GFCommon::add_categories_as_choices($field, '');
  664. if(isset($field["inputs"]) && is_array($field["inputs"])){
  665. foreach($field["inputs"] as $input)
  666. self::save_input($form, $field, $lead, $current_fields, $input["id"]);
  667. }
  668. else{
  669. self::save_input($form, $field, $lead, $current_fields, $field["id"]);
  670. }
  671. }
  672. }
  673. if(!empty($calculation_fields)) {
  674. foreach($calculation_fields as $calculation_field) {
  675. if(isset($calculation_field["inputs"]) && is_array($calculation_field["inputs"])){
  676. foreach($calculation_field["inputs"] as $input) {
  677. self::save_input($form, $calculation_field, $lead, $current_fields, $input["id"]);
  678. }
  679. }
  680. else{
  681. self::save_input($form, $calculation_field, $lead, $current_fields, $calculation_field["id"]);
  682. }
  683. }
  684. self::refresh_product_cache($form, $lead = RGFormsModel::get_lead($lead['id']));
  685. }
  686. //saving total field as the last field of the form.
  687. if($total_field) {
  688. self::save_input($form, $total_field, $lead, $current_fields, $total_field["id"]);
  689. }
  690. }
  691. public static function refresh_product_cache($form, $lead, $use_choice_text = false, $use_admin_label = false) {
  692. $cache_options = array(
  693. array(false, false),
  694. array(false, true),
  695. array(true, false),
  696. array(true, true)
  697. );
  698. foreach($cache_options as $cache_option) {
  699. list($use_choice_text, $use_admin_label) = $cache_option;
  700. if( gform_get_meta( rgar($lead,'id'), "gform_product_info_{$use_choice_text}_{$use_admin_label}") ) {
  701. gform_delete_meta(rgar($lead,'id'), "gform_product_info_{$use_choice_text}_{$use_admin_label}");
  702. GFCommon::get_product_fields($form, $lead, $use_choice_text, $use_admin_label);
  703. }
  704. }
  705. }
  706. public static function is_field_hidden($form, $field, $field_values, $lead=null){
  707. $section = self::get_section($form, $field["id"]);
  708. $section_display = self::get_field_display($form, $section, $field_values, $lead);
  709. //if section is hidden, hide field no matter what. if section is visible, see if field is supposed to be visible
  710. if($section_display == "hide")
  711. return true;
  712. else if(self::is_page_hidden($form, rgar($field,"page_number"), $field_values, $lead)){
  713. return true;
  714. }
  715. else{
  716. $display = self::get_field_display($form, $field, $field_values, $lead);
  717. return $display == "hide";
  718. }
  719. }
  720. public static function is_page_hidden($form, $page_number, $field_values, $lead=null){
  721. $page = self::get_page_by_number($form, $page_number);
  722. if(!$page)
  723. return false;
  724. $display = self::get_field_display($form, $page, $field_values, $lead);
  725. return $display == "hide";
  726. }
  727. public static function get_page_by_number($form, $page_number){
  728. foreach($form["fields"] as $field){
  729. if($field["type"] == "page" && $field["pageNumber"] == $page_number)
  730. return $field;
  731. }
  732. return null;
  733. }
  734. public static function get_page_by_field($form, $field){
  735. return get_page_by_number($field["page_number"]);
  736. }
  737. //gets the section that the specified field belongs to, or null if none
  738. public static function get_section($form, $field_id){
  739. $current_section = null;
  740. foreach($form["fields"] as $field){
  741. if($field["type"] == "section")
  742. $current_section = $field;
  743. //stop section at a page break (sections don't go cross page)
  744. if($field["type"] == "page")
  745. $current_section = null;
  746. if($field["id"] == $field_id)
  747. return $current_section;
  748. }
  749. return null;
  750. }
  751. public static function is_value_match($field_value, $target_value, $operation="is", $source_field=null){
  752. if($source_field && $source_field["type"] == "post_category"){
  753. $field_value = GFCommon::prepare_post_category_value($field_value, $source_field, "conditional_logic");
  754. }
  755. if(is_array($field_value)){
  756. foreach($field_value as $val){
  757. if(self::matches_operation(GFCommon::get_selection_value($val), $target_value, $operation))
  758. return true;
  759. }
  760. }
  761. else if(self::matches_operation(GFCommon::get_selection_value($field_value), $target_value, $operation)){
  762. return true;
  763. }
  764. return false;
  765. }
  766. private static function try_convert_float($text){
  767. global $wp_locale;
  768. $number_format = $wp_locale->number_format['decimal_point'] == "," ? "decimal_comma" : "decimal_dot";
  769. if(GFCommon::is_numeric($text, $number_format))
  770. return GFCommon::clean_number($text, $number_format);
  771. return $text;
  772. }
  773. public static function matches_operation($val1, $val2, $operation){
  774. $val1 = !empty($val1) ? strtolower($val1) : "";
  775. $val2 = !empty($val2) ? strtolower($val2) : "";
  776. switch($operation){
  777. case "is" :
  778. return $val1 == $val2;
  779. break;
  780. case "isnot" :
  781. return $val1 != $val2;
  782. break;
  783. case "greater_than":
  784. case ">" :
  785. $val1 = self::try_convert_float($val1);
  786. $val2 = self::try_convert_float($val2);
  787. return $val1 > $val2;
  788. break;
  789. case "less_than":
  790. case "<" :
  791. $val1 = self::try_convert_float($val1);
  792. $val2 = self::try_convert_float($val2);
  793. return $val1 < $val2;
  794. break;
  795. case "contains" :
  796. return !empty($val2) && strpos($val1, $val2) !== false;
  797. break;
  798. case "starts_with" :
  799. return !empty($val2) && strpos($val1, $val2) === 0;
  800. break;
  801. case "ends_with" :
  802. $start = strlen($val1) - strlen($val2);
  803. if($start < 0)
  804. return false;
  805. $tail = substr($val1, $start);
  806. return $val2 == $tail;
  807. break;
  808. }
  809. return false;
  810. }
  811. private static function get_field_display($form, $field, $field_values, $lead=null){
  812. $logic = RGForms::get("conditionalLogic", $field);
  813. //if this field does not have any conditional logic associated with it, it won't be hidden
  814. if(empty($logic))
  815. return "show";
  816. $match_count = 0;
  817. foreach($logic["rules"] as $rule){
  818. $source_field = RGFormsModel::get_field($form, $rule["fieldId"]);
  819. $field_value = empty($lead) ? self::get_field_value($source_field, $field_values) : self::get_lead_field_value($lead, $source_field);
  820. $is_value_match = self::is_value_match($field_value, $rule["value"], $rule["operator"], $source_field);
  821. if($is_value_match)
  822. $match_count++;
  823. }
  824. $do_action = ($logic["logicType"] == "all" && $match_count == sizeof($logic["rules"]) ) || ($logic["logicType"] == "any" && $match_count > 0);
  825. $is_hidden = ($do_action && $logic["actionType"] == "hide") || (!$do_action && $logic["actionType"] == "show");
  826. return $is_hidden ? "hide" : "show";
  827. }
  828. public static function get_custom_choices(){
  829. $choices = get_option("gform_custom_choices");
  830. if(!$choices)
  831. $choices = array();
  832. return $choices;
  833. }
  834. public static function delete_custom_choice($name){
  835. $choices = self::get_custom_choices();
  836. if(array_key_exists($name, $choices))
  837. unset($choices[$name]);
  838. update_option("gform_custom_choices", $choices);
  839. }
  840. public static function save_custom_choice($previous_name, $new_name, $choices){
  841. $all_choices = self::get_custom_choices();
  842. if(array_key_exists($previous_name, $all_choices))
  843. unset($all_choices[$previous_name]);
  844. $all_choices[$new_name] = $choices;
  845. update_option("gform_custom_choices", $all_choices);
  846. }
  847. public static function get_field_value($field, $field_values = array(), $get_from_post=true){
  848. if($field['type'] == 'post_category')
  849. $field = GFCommon::add_categories_as_choices($field, '');
  850. $value = array();
  851. switch(RGFormsModel::get_input_type($field)){
  852. case "post_image" :
  853. $value[$field["id"] . ".1"] = self::get_input_value($field, "input_" . $field["id"] . "_1", $get_from_post);
  854. $value[$field["id"] . ".4"] = self::get_input_value($field, "input_" . $field["id"] . "_4", $get_from_post);
  855. $value[$field["id"] . ".7"] = self::get_input_value($field, "input_" . $field["id"] . "_7", $get_from_post);
  856. break;
  857. case "checkbox" :
  858. $parameter_values = self::get_parameter_value($field["inputName"], $field_values, $field);
  859. if(!empty($parameter_values) && !is_array($parameter_values)){
  860. $parameter_values = explode(",", $parameter_values);
  861. }
  862. if(!is_array($field["inputs"]))
  863. return "";
  864. $choice_index = 0;
  865. foreach($field["inputs"] as $input){
  866. if(!empty($_POST["is_submit_" . $field["formId"]]) && $get_from_post){
  867. $value[strval($input["id"])] = rgpost("input_" . str_replace('.', '_', strval($input["id"])));
  868. }
  869. else{
  870. if(is_array($parameter_values)){
  871. foreach($parameter_values as $item){
  872. $item = trim($item);
  873. if(self::choice_value_match($field, $field["choices"][$choice_index], $item))
  874. {
  875. $value[$input["id"] . ""] = $item;
  876. break;
  877. }
  878. }
  879. }
  880. }
  881. $choice_index++;
  882. }
  883. break;
  884. case "list" :
  885. $value = self::get_input_value($field, "input_" . $field["id"], rgar($field, "inputName"), $field_values, $get_from_post);
  886. $value = self::create_list_array($field, $value);
  887. break;
  888. default:
  889. if(isset($field["inputs"]) && is_array($field["inputs"])){
  890. foreach($field["inputs"] as $input){
  891. $value[strval($input["id"])] = self::get_input_value($field, "input_" . str_replace('.', '_', strval($input["id"])), RGForms::get("name", $input), $field_values, $get_from_post);
  892. }
  893. }
  894. else{
  895. $value = self::get_input_value($field, "input_" . $field["id"], rgar($field, "inputName"), $field_values, $get_from_post);
  896. }
  897. break;
  898. }
  899. return $value;
  900. }
  901. private static function get_input_value($field, $standard_name, $custom_name = "", $field_values=array(), $get_from_post=true){
  902. if(!empty($_POST["is_submit_" . rgar($field,"formId")]) && $get_from_post){
  903. return rgpost($standard_name);
  904. }
  905. else if(rgar($field, "allowsPrepopulate")){
  906. return self::get_parameter_value($custom_name, $field_values, $field);
  907. }
  908. }
  909. private static function get_parameter_value($name, $field_values, $field){
  910. $value = stripslashes(rgget($name));
  911. if(empty($value))
  912. $value = rgget($name, $field_values);
  913. //converting list format
  914. if(RGFormsModel::get_input_type($field) == "list"){
  915. //transforms this: col1|col2,col1b|col2b into this: col1,col2,col1b,col2b
  916. $column_count = count(rgar($field,"choices"));
  917. $rows = explode(",", $value);
  918. $ary_rows = array();
  919. if(!empty($rows)){
  920. foreach($rows as $row)
  921. $ary_rows = array_merge($ary_rows, rgexplode("|", $row, $column_count));
  922. $value = $ary_rows;
  923. }
  924. }
  925. return apply_filters("gform_field_value_$name", $value);
  926. }
  927. public static function get_default_value($field, $input_id){
  928. if(!is_array(rgar($field,"choices"))){
  929. if(is_array(rgar($field, "inputs"))){
  930. $input = RGFormsModel::get_input($field, $input_id);
  931. return rgar($input, "defaultValue");
  932. }
  933. else{
  934. return IS_ADMIN ? $field["defaultValue"] : GFCommon::replace_variables_prepopulate($field["defaultValue"]);
  935. }
  936. }
  937. else if($field["type"] == "checkbox"){
  938. for($i=0, $count=sizeof($field["inputs"]); $i<$count; $i++){
  939. $input = $field["inputs"][$i];
  940. $choice = $field["choices"][$i];
  941. if($input["id"] == $input_id && $choice["isSelected"]){
  942. return $choice["value"];
  943. }
  944. }
  945. return "";
  946. }
  947. else{
  948. foreach($field["choices"] as $choice){
  949. if($choice["isSelected"] || $field["type"] == "post_category")
  950. return $choice["value"];
  951. }
  952. return "";
  953. }
  954. }
  955. public static function get_input_type($field){
  956. return empty($field["inputType"]) ? rgar($field,"type") : $field["inputType"];
  957. }
  958. private static function get_post_field_value($field, $lead){
  959. if(is_array($field["inputs"])){
  960. $value = array();
  961. foreach($field["inputs"] as $input){
  962. $val = isset($lead[strval($input["id"])]) ? $lead[strval($input["id"])] : "";
  963. if(!empty($val))
  964. $value[] = $val;
  965. }
  966. $value = implode(",", $value);
  967. }
  968. else{
  969. $value = isset($lead[$field["id"]]) ? $lead[$field["id"]] : "";
  970. }
  971. return $value;
  972. }
  973. private static function get_post_fields($form, $lead) {
  974. $post_data = array();
  975. $post_data["post_custom_fields"] = array();
  976. $post_data["tags_input"] = array();
  977. $categories = array();
  978. $images = array();
  979. foreach($form["fields"] as $field){
  980. if($field['type'] == 'post_category')
  981. $field = GFCommon::add_categories_as_choices($field, '');
  982. $value = self::get_post_field_value($field, $lead);
  983. switch($field["type"]){
  984. case "post_title" :
  985. case "post_excerpt" :
  986. case "post_content" :
  987. $post_data[$field["type"]] = $value;
  988. break;
  989. case "post_tags" :
  990. $tags = explode(",", $value);
  991. if(is_array($tags) && sizeof($tags) > 0)
  992. $post_data["tags_input"] = array_merge($post_data["tags_input"], $tags) ;
  993. break;
  994. case "post_custom_field" :
  995. $meta_name = $field["postCustomFieldName"];
  996. if(!isset($post_data["post_custom_fields"][$meta_name])){
  997. $post_data["post_custom_fields"][$meta_name] = $value;
  998. }
  999. else if(!is_array($post_data["post_custom_fields"][$meta_name])){
  1000. $post_data["post_custom_fields"][$meta_name] = array($post_data["post_custom_fields"][$meta_name], $value);
  1001. }
  1002. else{
  1003. $post_data["post_custom_fields"][$meta_name][] = $value;
  1004. }
  1005. break;
  1006. case "post_category" :
  1007. foreach(explode(',', $value) as $cat_string) {
  1008. list($cat_name, $cat_id) = rgexplode(":", $cat_string, 2);
  1009. array_push($categories, $cat_id);
  1010. }
  1011. break;
  1012. case "post_image" :
  1013. $ary = !empty($value) ? explode("|:|", $value) : array();
  1014. $url = count($ary) > 0 ? $ary[0] : "";
  1015. $title = count($ary) > 1 ? $ary[1] : "";
  1016. $caption = count($ary) > 2 ? $ary[2] : "";
  1017. $description = count($ary) > 3 ? $ary[3] : "";
  1018. array_push($images, array("field_id" => $field["id"], "url" => $url, "title" => $title, "description" => $description, "caption" => $caption));
  1019. break;
  1020. }
  1021. }
  1022. $post_data["post_status"] = rgar($form, "postStatus");
  1023. $post_data["post_category"] = !empty($categories) ? $categories : array($form["postCategory"]);
  1024. $post_data["images"] = $images;
  1025. //setting current user as author depending on settings
  1026. $post_data["post_author"] = $form["useCurrentUserAsAuthor"] && !empty($lead["created_by"]) ? $lead["created_by"] : $form["postAuthor"];
  1027. return $post_data;
  1028. }
  1029. public static function get_custom_field_names(){
  1030. global $wpdb;
  1031. $keys = $wpdb->get_col( "
  1032. SELECT meta_key
  1033. FROM $wpdb->postmeta
  1034. WHERE meta_key NOT LIKE '\_%'
  1035. GROUP BY meta_key
  1036. ORDER BY meta_id DESC");
  1037. if ( $keys )
  1038. natcasesort($keys);
  1039. return $keys;
  1040. }
  1041. public static function get_input_masks(){
  1042. $masks = array(
  1043. 'US Phone' => '(999) 999-9999',
  1044. 'US Phone + Ext' => '(999) 999-9999? x99999',
  1045. 'Date' => '99/99/9999',
  1046. 'Tax ID' => '99-9999999',
  1047. 'SSN' => '999-99-9999',
  1048. 'Zip Code' => '99999',
  1049. 'Full Zip Code' => '99999?-9999'
  1050. );
  1051. return apply_filters('gform_input_masks', $masks);
  1052. }
  1053. private static function get_default_post_title(){
  1054. global $wpdb;
  1055. $title = "Untitled";
  1056. $count = 1;
  1057. $titles = $wpdb->get_col("SELECT post_title FROM $wpdb->posts WHERE post_title like '%Untitled%'");
  1058. $titles = array_values($titles);
  1059. while(in_array($title, $titles)){
  1060. $title = "Untitled_$count";
  1061. $count++;
  1062. }
  1063. return $title;
  1064. }
  1065. public static function prepare_date($date_format, $value){
  1066. $format = empty($date_format) ? "mdy" : $date_format;
  1067. $date_info = GFCommon::parse_date($value, $format);
  1068. if(!empty($date_info))
  1069. $value = sprintf("%s-%02d-%02d", $date_info["year"], $date_info["month"], $date_info["day"]);
  1070. else
  1071. $value = "";
  1072. return $value;
  1073. }
  1074. public static function prepare_value($form, $field, $value, $input_name, $lead_id){
  1075. $form_id = $form["id"];
  1076. $input_type = self::get_input_type($field);
  1077. switch($input_type)
  1078. {
  1079. case "total" :
  1080. $lead = RGFormsModel::get_lead($lead_id);
  1081. $value = GFCommon::get_order_total($form, $lead);
  1082. break;
  1083. case "calculation" :
  1084. // ignore submitted value and recalculate price in backend
  1085. list(,,$input_id) = rgexplode("_", $input_name, 3);
  1086. if($input_id == 2) {
  1087. require_once(GFCommon::get_base_path() . '/currency.php');
  1088. $currency = new RGCurrency(GFCommon::get_currency());
  1089. $lead = RGFormsModel::get_lead($lead_id);
  1090. $value = $currency->to_money(GFCommon::calculate($field, $form, $lead));
  1091. }
  1092. break;
  1093. case "phone" :
  1094. if($field["phoneFormat"] == "standard" && preg_match('/^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/', $value, $matches))
  1095. $value = sprintf("(%s)%s-%s", $matches[1], $matches[2], $matches[3]);
  1096. break;
  1097. case "time":
  1098. if(!is_array($value) && !empty($value)){
  1099. preg_match('/^(\d*):(\d*) ?(.*)$/', $value, $matches);
  1100. $value = array();
  1101. $value[0] = $matches[1];
  1102. $value[1] = $matches[2];
  1103. $value[2] = rgar($matches,3);
  1104. }
  1105. $hour = empty($value[0]) ? "0" : strip_tags($value[0]);
  1106. $minute = empty($value[1]) ? "0" : strip_tags($value[1]);
  1107. $ampm = strip_tags(rgar($value,2));
  1108. if(!empty($ampm))
  1109. $ampm = " $ampm";
  1110. if(!(empty($hour) && empty($minute)))
  1111. $value = sprintf("%02d:%02d%s", $hour, $minute, $ampm);
  1112. else
  1113. $value = "";
  1114. break;
  1115. case "date" :
  1116. $value = self::prepare_date($field["dateFormat"], $value);
  1117. break;
  1118. case "post_image":
  1119. $url = self::get_fileupload_value($form_id, $input_name);
  1120. $image_title = isset($_POST["{$input_name}_1"]) ? strip_tags($_POST["{$input_name}_1"]) : "";
  1121. $image_caption = isset($_POST["{$input_name}_4"]) ? strip_tags($_POST["{$input_name}_4"]) : "";
  1122. $image_description = isset($_POST["{$input_name}_7"]) ? strip_tags($_POST["{$input_name}_7"]) : "";
  1123. $value = !empty($url) ? $url . "|:|" . $image_title . "|:|" . $image_caption . "|:|" . $image_description : "";
  1124. break;
  1125. case "fileupload" :
  1126. $value = self::get_fileupload_value($form_id, $input_name);
  1127. break;
  1128. case "number" :
  1129. $lead = RGFormsModel::get_lead($lead_id);
  1130. $value = GFCommon::has_field_calculation($field) ? GFCommon::calculate($field, $form, $lead) : GFCommon::clean_number($value, rgar($field, "numberFormat"));
  1131. break;
  1132. case "website" :
  1133. if($value == "http://")
  1134. $value = "";
  1135. break;
  1136. case "list" :
  1137. if(GFCommon::is_empty_array($value))
  1138. $value = "";
  1139. else{
  1140. $value = self::create_list_array($field, $value);
  1141. $value = serialize($value);
  1142. }
  1143. break;
  1144. case "radio" :
  1145. if(rgar($field, 'enableOtherChoice') && $value == 'gf_other_choice')
  1146. $value = rgpost("input_{$field['id']}_other");
  1147. break;
  1148. case "multiselect" :
  1149. $value = empty($value) ? "" : implode(",", $value);
  1150. break;
  1151. case "creditcard" :
  1152. //saving last 4 digits of credit card
  1153. list($input_token, $field_id_token, $input_id) = rgexplode("_", $input_name, 3);
  1154. if($input_id == "1"){
  1155. $value = str_replace(" ", "", $value);
  1156. $card_number_length = strlen($value);
  1157. $value = substr($value, -4, 4);
  1158. $value = str_pad($value, $card_number_length, "X", STR_PAD_LEFT);
  1159. }
  1160. else if($input_id == "4")
  1161. {
  1162. $card_number = rgpost("input_{$field_id_token}_1");
  1163. $card_type = GFCommon::get_card_type($card_number);
  1164. $value = $card_type ? $card_type["name"] : "";
  1165. }
  1166. else{
  1167. $value = "";
  1168. }
  1169. break;
  1170. default:
  1171. //allow HTML for certain field types
  1172. $allow_html = in_array($field["type"], array("post_custom_field", "post_title", "post_content", "post_excerpt", "post_tags")) || in_array($input_type, array("checkbox", "radio")) ? true : false;
  1173. $allowable_tags = apply_filters("gform_allowable_tags_{$form_id}", apply_filters("gform_allowable_tags", $allow_html, $field, $form_id), $field, $form_id);
  1174. if($allowable_tags !== true)
  1175. $value = strip_tags($value, $allowable_tags);
  1176. break;
  1177. }
  1178. // special format for Post Category fields
  1179. if($field['type'] == 'post_category') {
  1180. $full_values = array();
  1181. if(!is_array($value))
  1182. $value = explode(',', $value);
  1183. foreach($value as $cat_id) {
  1184. $cat = get_term($cat_id, 'category');
  1185. $full_values[] = !is_wp_error($cat) && is_object($cat) ? $cat->name . ":" . $cat_id : "";
  1186. }
  1187. $value = implode(',', $full_values);
  1188. }
  1189. //do not save price fields with blank price
  1190. if(rgar($field, "enablePrice")){
  1191. $ary = explode("|", $value);
  1192. $label = count($ary) > 0 ? $ary[0] : "";
  1193. $price = count($ary) > 1 ? $ary[1] : "";
  1194. $is_empty = (strlen(trim($price)) <= 0);
  1195. if($is_empty)
  1196. $value = "";
  1197. }
  1198. return $value;
  1199. }
  1200. private static function create_list_array($field, $value){
  1201. if(!rgar($field,"enableColumns")){
  1202. return $value;
  1203. }
  1204. else{
  1205. $col_count = count(rgar($field, "choices"));
  1206. $rows = array();
  1207. $row_count = count($value)/$col_count;
  1208. $col_index = 0;
  1209. for($i=0; $i<$row_count; $i++){
  1210. $row = array();
  1211. foreach($field["choices"] as $column){
  1212. $row[$column["text"]] = $value[$col_index];
  1213. $col_index++;
  1214. }
  1215. $rows[] = $row;
  1216. }
  1217. return $rows;
  1218. }
  1219. }
  1220. private static function get_fileupload_value($form_id, $input_name){
  1221. global $_gf_uploaded_files;
  1222. if(empty($_gf_uploaded_files))
  1223. $_gf_uploaded_files = array();
  1224. if(!isset($_gf_uploaded_files[$input_name])){
  1225. //check if file has already been uploaded by previous step
  1226. $file_info = self::get_temp_filename($form_id, $input_name);
  1227. $temp_filepath = self::get_upload_path($form_id) . "/tmp/" . $file_info["temp_filename"];
  1228. if($file_info && file_exists($temp_filepath)){
  1229. $_gf_uploaded_files[$input_name] = self::move_temp_file($form_id, $file_info);
  1230. }
  1231. else if (!empty($_FILES[$input_name]["name"])){
  1232. $_gf_uploaded_files[$input_name] = self::upload_file($form_id, $_FILES[$input_name]);
  1233. }
  1234. }
  1235. return rgget($input_name, $_gf_uploaded_files);
  1236. }
  1237. public static function get_form_unique_id($form_id){
  1238. if(RGForms::post("gform_submit") == $form_id)
  1239. return RGForms::post("gform_unique_id");
  1240. else
  1241. return uniqid();
  1242. }
  1243. public static function get_temp_filename($form_id, $input_name){
  1244. $uploaded_filename = !empty($_FILES[$input_name]["name"]) ? $_FILES[$input_name]["name"] : "";
  1245. if(empty($uploaded_filename) && isset(self::$uploaded_files[$form_id]))
  1246. $uploaded_filename = rgget($input_name, self::$uploaded_files[$form_id]);
  1247. if(empty($uploaded_filename))
  1248. return false;
  1249. $form_unique_id = self::get_form_unique_id($form_id);
  1250. $pathinfo = pathinfo($uploaded_filename);
  1251. return array("uploaded_filename" => $uploaded_filename, "temp_filename" => "{$form_unique_id}_{$input_name}.{$pathinfo["extension"]}");
  1252. }
  1253. public static function get_choice_text($field, $value, $input_id=0){
  1254. if(!is_array(rgar($field, "choices")))
  1255. return $value;
  1256. foreach($field["choices"] as $choice){
  1257. if(is_array($value) && self::choice_value_match($field, $choice, $value[$input_id])){
  1258. return $choice["text"];
  1259. }
  1260. else if(!is_array($value) && self::choice_value_match($field, $choice, $value)){
  1261. return $choice["text"];
  1262. }
  1263. }
  1264. return is_array($value) ? "" : $value;
  1265. }
  1266. public static function choice_value_match($field, $choice, $value){
  1267. if($choice["value"] == $value){
  1268. return true;
  1269. }
  1270. else if(rgget("enablePrice", $field)){
  1271. $ary = explode("|", $value);
  1272. $val = count($ary) > 0 ? $ary[0] : "";
  1273. $price = count($ary) > 1 ? $ary[1] : "";
  1274. if($val == $choice["value"])
  1275. return true;
  1276. }
  1277. // add support for prepopulating multiselects @alex
  1278. else if(RGFormsModel::get_input_type($field) == 'multiselect') {
  1279. $values = explode(',', $value);
  1280. if(in_array($choice['value'], $values))
  1281. return true;
  1282. }
  1283. return false;
  1284. }
  1285. public static function choices_value_match($field, $choices, $value) {
  1286. foreach($choices as $choice){
  1287. if(self::choice_value_match($field, $choice, $value))
  1288. return true;
  1289. }
  1290. return false;
  1291. }
  1292. public static function create_post($form, &$lead){
  1293. $has_post_field = false;
  1294. foreach($form["fields"] as $field){
  1295. $is_hidden = self::is_field_hidden($form, $field, array(), $lead);
  1296. if(!$is_hidden && in_array($field["type"], array("post_category","post_title","post_content","post_excerpt","post_tags","post_custom_fields","post_image"))){
  1297. $has_post_field = true;
  1298. break;
  1299. }
  1300. }
  1301. //if this form does not have any post fields, don't create a post
  1302. if(!$has_post_field)
  1303. return $lead;
  1304. //processing post fields
  1305. $post_data = self::get_post_fields($form, $lead);
  1306. //allowing users to change post fields before post gets created
  1307. $post_data = apply_filters("gform_post_data_{$form["id"]}", apply_filters("gform_post_data", $post_data , $form, $lead), $form, $lead);
  1308. //adding default title if none of the required post fields are in the form (will make sure wp_insert_post() inserts the post)
  1309. if(empty($post_data["post_title"]) && empty($post_data["post_content"]) && empty($post_data["post_excerpt"])){
  1310. $post_data["post_title"] = self::get_default_post_title();
  1311. }
  1312. //inserting post
  1313. $post_id = wp_insert_post($post_data);
  1314. //adding form id and entry id hidden custom fields
  1315. add_post_meta($post_id, "_gform-form-id", $form["id"]);
  1316. add_post_meta($post_id, "_gform-entry-id", $lead["id"]);
  1317. //creating post images
  1318. $post_images = array();
  1319. foreach($post_data["images"] as $image){
  1320. $image_meta= array( "post_excerpt" => $image["caption"],
  1321. "post_content" => $image["description"]);
  1322. //adding title only if it is not empty. It will default to the file name if it is not in the array
  1323. if(!empty($image["title"]))
  1324. $image_meta["post_title"] = $image["title"];
  1325. if(!empty($image["url"])){
  1326. $media_id = self::media_handle_upload($image["url"], $post_id, $image_meta);
  1327. if($media_id){
  1328. //save media id for post body/title template variable replacement (below)
  1329. $post_images[$image["field_id"]] = $media_id;
  1330. $lead[$image["field_id"]] .= "|:|$media_id";
  1331. // set featured image
  1332. $field = RGFormsModel::get_field($form, $image["field_id"]);
  1333. if(rgar($field, 'postFeaturedImage'))
  1334. set_post_thumbnail($post_id, $media_id);
  1335. }
  1336. }
  1337. }
  1338. //adding custom fields
  1339. foreach($post_data["post_custom_fields"] as $meta_name => $meta_value) {
  1340. if(!is_array($meta_value))
  1341. $meta_value = array($meta_value);
  1342. $meta_index = 0;
  1343. foreach($meta_value as $value){
  1344. $custom_field = self::get_custom_field($form, $meta_name, $meta_index);
  1345. //replacing template variables if template is enabled
  1346. if($custom_field && rgget("customFieldTemplateEnabled", $custom_field)){
  1347. //replacing post image variables
  1348. $value = GFCommon::replace_variables_post_image($custom_field["customFieldTemplate"], $post_images, $lead);
  1349. //replacing all other variables
  1350. $value = GFCommon::replace_variables($value, $form, $lead, false, false, false);
  1351. // replace conditional shortcodes
  1352. $value = do_shortcode($value);
  1353. }
  1354. switch(RGFormsModel::get_input_type($custom_field)){
  1355. case "list" :
  1356. $value = maybe_unserialize($value);
  1357. if(is_array($value)){
  1358. foreach($value as $item){
  1359. if(is_array($item))
  1360. $item = implode("|", $item);
  1361. if(!rgblank($item))
  1362. add_post_meta($post_id, $meta_name, $item);
  1363. }
  1364. }
  1365. break;
  1366. case "multiselect" :
  1367. case "checkbox" :
  1368. $value = explode(",", $value);
  1369. if(is_array($value)){
  1370. foreach($value as $item){
  1371. if(!rgblank($item))
  1372. add_post_meta($post_id, $meta_name, $item);
  1373. }
  1374. }
  1375. break;
  1376. case "date" :
  1377. $value = GFCommon::date_display($value, rgar($custom_field, "dateFormat"));
  1378. if(!rgblank($value))
  1379. add_post_meta($post_id, $meta_name, $value);
  1380. break;
  1381. default :
  1382. if(!rgblank($value))
  1383. add_post_meta($post_id, $meta_name, $value);
  1384. break;
  1385. }
  1386. $meta_index++;
  1387. }
  1388. }
  1389. $has_content_field = sizeof(GFCommon::get_fields_by_type($form, array("post_content"))) > 0;
  1390. $has_title_field = sizeof(GFCommon::get_fields_by_type($form, array("post_title"))) > 0;
  1391. //if a post field was configured with a content or title template, process template
  1392. if( (rgar($form, "postContentTemplateEnabled") && $has_content_field) || (rgar($form, "postTitleTemplateEnabled") && $has_title_field) ){
  1393. $post = get_post($post_id);
  1394. if($form["postContentTemplateEnabled"] && $has_content_field){
  1395. //replacing post image variables
  1396. $post_content = GFCommon::replace_variables_post_image($form["postContentTemplate"], $post_images, $lead);
  1397. //replacing all other variables
  1398. $post_content = GFCommon::replace_variables($post_content, $form, $lead, false, false, false);
  1399. //updating post content
  1400. $post->post_content = $post_content;
  1401. }
  1402. if($form["postTitleTemplateEnabled"] && $has_title_field){
  1403. //replacing post image variables
  1404. $post_title = GFCommon::replace_variables_post_image($form["postTitleTemplate"], $post_images, $lead);
  1405. //replacing all other variables
  1406. $post_title = GFCommon::replace_variables($post_title, $form, $lead, false, false, false);
  1407. // replace conditional shortcodes
  1408. $post_title = do_shortcode($post_title);
  1409. //updating post
  1410. $post->post_title = $post_title;
  1411. $post->post_name = $post_title;
  1412. }
  1413. wp_update_post($post);
  1414. }
  1415. //adding post format
  1416. if(current_theme_supports('post-formats') && rgar($form, 'postFormat')) {
  1417. $formats = get_theme_support('post-formats');
  1418. $post_format = rgar($form, 'postFormat');
  1419. if(is_array($formats)) {
  1420. $formats = $formats[0];
  1421. if(in_array( $post_format, $formats)) {
  1422. set_post_format($post_id, $post_format);
  1423. } else if('0' == $post_format) {
  1424. set_post_format($post_id, false);
  1425. }
  1426. }
  1427. }
  1428. //update post_id field if a post was created
  1429. $lead["post_id"] = $post_id;
  1430. self::update_lead($lead);
  1431. return $post_id;
  1432. }
  1433. private static function get_custom_field($form, $meta_name, $meta_index){
  1434. $custom_fields = GFCommon::get_fields_by_type($form, array("post_custom_field"));
  1435. $index = 0;
  1436. foreach($custom_fields as $field){
  1437. if($field["postCustomFieldName"] == $meta_name){
  1438. if($meta_index == $index){
  1439. return $field;
  1440. }
  1441. $index++;
  1442. }
  1443. }
  1444. return false;
  1445. }
  1446. private static function copy_post_image($url, $post_id){
  1447. $time = current_time('mysql');
  1448. if ( $post = get_post($post_id) ) {
  1449. if ( substr( $post->post_date, 0, 4 ) > 0 )
  1450. $time = $post->post_date;
  1451. }
  1452. //making sure there is a valid upload folder
  1453. if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
  1454. return false;
  1455. $name = basename($url);
  1456. $filename = wp_unique_filename($uploads['path'], $name);
  1457. // Move the file to the uploads dir
  1458. $new_file = $uploads['path'] . "/$filename";
  1459. $uploaddir = wp_upload_dir();
  1460. $path = str_replace($uploaddir["baseurl"], $uploaddir["basedir"], $url);
  1461. if(!copy($path, $new_file))
  1462. return false;
  1463. // Set correct file permissions
  1464. $stat = stat( dirname( $new_file ));
  1465. $perms = $stat['mode'] & 0000666;
  1466. @ chmod( $new_file, $perms );
  1467. // Compute the URL
  1468. $url = $uploads['url'] . "/$filename";
  1469. if ( is_multisite() )
  1470. delete_transient( 'dirsize_cache' );
  1471. $type = wp_check_filetype($new_file);
  1472. return array("file" => $new_file, "url" => $url, "type" => $type["type"]);
  1473. }
  1474. private static function media_handle_upload($url, $post_id, $post_data = array()) {
  1475. //WordPress Administration API required for the media_handle_upload() function
  1476. require_once(ABSPATH . 'wp-admin/includes/image.php');
  1477. $name = basename($url);
  1478. $file = self::copy_post_image($url, $post_id);
  1479. if(!$file)
  1480. return false;
  1481. $name_parts = pathinfo($name);
  1482. $name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
  1483. $url = $file['url'];
  1484. $type = $file['type'];
  1485. $file = $file['file'];
  1486. $title = $name;
  1487. $content = '';
  1488. // use image exif/iptc data for title and caption defaults if possible
  1489. if ( $image_meta = @wp_read_image_metadata($file) ) {
  1490. if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
  1491. $title = $image_meta['title'];
  1492. if ( trim( $image_meta['caption'] ) )
  1493. $content = $image_meta['caption'];
  1494. }
  1495. // Construct the attachment array
  1496. $attachment = array_merge( array(
  1497. 'post_mime_type' => $type,
  1498. 'guid' => $url,
  1499. 'post_parent' => $post_id,
  1500. 'post_title' => $title,
  1501. 'post_content' => $content,
  1502. ), $post_data );
  1503. // Save the data
  1504. $id = wp_insert_attachment($attachment, $file, $post_id);
  1505. if ( !is_wp_error($id) ) {
  1506. wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
  1507. }
  1508. return $id;
  1509. }
  1510. public static function save_input($form, $field, &$lead, $current_fields, $input_id){
  1511. global $wpdb;
  1512. $lead_detail_table = self::get_lead_details_table_name();
  1513. $lead_detail_long_table = self::get_lead_details_long_table_name();
  1514. $input_name = "input_" . str_replace('.', '_', $input_id);
  1515. $value = rgpost($input_name);
  1516. //ignore file upload when nothing was sent in the admin
  1517. //ignore post fields in the admin
  1518. if(RG_CURRENT_VIEW == "entry" && self::get_input_type($field) == "fileupload" && empty($_FILES[$input_name]["name"]))
  1519. return;
  1520. else if(RG_CURRENT_VIEW == "entry" && in_array($field["type"], array("post_category","post_title","post_content","post_excerpt","post_tags","post_custom_field","post_image")))
  1521. return;
  1522. if(empty($value) && rgar($field, "adminOnly") && !IS_ADMIN){
  1523. $value = self::get_default_value($field, $input_id);
  1524. }
  1525. //processing values so that they are in the correct format for each input type
  1526. $value = self::prepare_value($form, $field, $value, $input_name, rgar($lead, "id"));
  1527. //ignore fields that have not changed
  1528. if($lead != null && $value == rgget($input_id, $lead))
  1529. return;
  1530. if(!empty($value) || $value === "0"){
  1531. $value = apply_filters("gform_save_field_value", $value, $lead, $field, $form);
  1532. $truncated_value = substr($value, 0, GFORMS_MAX_FIELD_LENGTH);
  1533. $lead_detail_id = self::get_lead_detail_id($current_fields, $input_id);
  1534. if($lead_detail_id > 0){
  1535. $wpdb->update($lead_detail_table, array("value" => $truncated_value), array("id" => $lead_detail_id), array("%s"), array("%d"));
  1536. //insert, update or delete long value
  1537. $sql = $wpdb->prepare("SELECT count(0) FROM $lead_detail_long_table WHERE lead_detail_id=%d", $lead_detail_id);
  1538. $has_long_field = intval($wpdb->get_var($sql)) > 0;
  1539. //delete long field if value has been shortened
  1540. if($has_long_field && strlen($value) <= GFORMS_MAX_FIELD_LENGTH){
  1541. $sql = $wpdb->prepare("DELETE FROM $lead_detail_long_table WHERE lead_detail_id=%d", $lead_detail_id);
  1542. $wpdb->query($sql);
  1543. }
  1544. //update long field
  1545. else if($has_long_field){
  1546. $wpdb->update($lead_detail_long_table, array("value" => $value), array("lead_detail_id" => $lead_detail_id), array("%s"), array("%d"));
  1547. }
  1548. //insert long field (value has been increased)
  1549. else if(strlen($value) > GFORMS_MAX_FIELD_LENGTH){
  1550. $wpdb->insert($lead_detail_long_table, array("lead_detail_id" => $lead_detail_id, "value" => $value), array("%d", "%s"));
  1551. }
  1552. }
  1553. else{
  1554. $wpdb->insert($lead_detail_table, array("lead_id" => $lead["id"], "form_id" => $form["id"], "field_number" => $input_id, "value" => $truncated_value), array("%d", "%d", "%f", "%s"));
  1555. if(strlen($value) > GFORMS_MAX_FIELD_LENGTH){
  1556. //read newly created lead detal id
  1557. $lead_detail_id = $wpdb->insert_id;
  1558. //insert long value
  1559. $wpdb->insert($lead_detail_long_table, array("lead_detail_id" => $lead_detail_id, "value" => $value), array("%d", "%s"));
  1560. }
  1561. }
  1562. }
  1563. else{
  1564. //Deleting details for this field
  1565. $sql = $wpdb->prepare("DELETE FROM $lead_detail_table WHERE lead_id=%d AND field_number BETWEEN %f AND %f ", $lead["id"], $input_id - 0.001, $input_id + 0.001);
  1566. $wpdb->query($sql);
  1567. //Deleting long field if there is one
  1568. $sql = $wpdb->prepare("DELETE FROM $lead_detail_long_table
  1569. WHERE lead_detail_id IN(
  1570. SELECT id FROM $lead_detail_table WHERE lead_id=%d AND field_number BETWEEN %f AND %f
  1571. )",
  1572. $lead["id"], $input_id - 0,001, $input_id + 0.001);
  1573. $wpdb->query($sql);
  1574. }
  1575. }
  1576. private static function move_temp_file($form_id, $tempfile_info){
  1577. $target = self::get_file_upload_path($form_id, $tempfile_info["uploaded_filename"]);
  1578. $source = self::get_upload_path($form_id) . "/tmp/" . $tempfile_info["temp_filename"];
  1579. if(rename($source, $target["path"])){
  1580. self::set_permissions($target["path"]);
  1581. return $target["url"];
  1582. }
  1583. else{
  1584. return "FAILED (Temporary file could not be moved.)";
  1585. }
  1586. }
  1587. private static function set_permissions($path){
  1588. $permission = apply_filters("gform_file_permission", 0644, $path);
  1589. if($permission){
  1590. chmod($path, $permission);
  1591. }
  1592. }
  1593. public static function upload_file($form_id, $file){
  1594. $target = self::get_file_upload_path($form_id, $file["name"]);
  1595. if(!$target)
  1596. return "FAILED (Upload folder could not be created.)";
  1597. if(move_uploaded_file($file['tmp_name'], $target["path"])){
  1598. self::set_permissions($target["path"]);
  1599. return $target["url"];
  1600. }
  1601. else{
  1602. return "FAILED (Temporary file could not be copied.)";
  1603. }
  1604. }
  1605. public static function get_upload_root(){
  1606. $dir = wp_upload_dir();
  1607. if($dir["error"])
  1608. return null;
  1609. return $dir["basedir"] . "/gravity_forms/";
  1610. }
  1611. public static function get_upload_url_root(){
  1612. $dir = wp_upload_dir();
  1613. if($dir["error"])
  1614. return null;
  1615. return $dir["baseurl"] . "/gravity_forms/";
  1616. }
  1617. public static function get_upload_path($form_id){
  1618. return self::get_upload_root() . $form_id . "-" . wp_hash($form_id);
  1619. }
  1620. public static function get_upload_url($form_id){
  1621. $dir = wp_upload_dir();
  1622. return $dir["baseurl"] . "/gravity_forms/$form_id" . "-" . wp_hash($form_id);
  1623. }
  1624. public static function get_file_upload_path($form_id, $file_name){
  1625. if (get_magic_quotes_gpc())
  1626. $file_name = stripslashes($file_name);
  1627. // Where the file is going to be placed
  1628. // Generate the yearly and monthly dirs
  1629. $time = current_time( 'mysql' );
  1630. $y = substr( $time, 0, 4 );
  1631. $m = substr( $time, 5, 2 );
  1632. $target_root = self::get_upload_path($form_id) . "/$y/$m/";
  1633. $target_root_url = self::get_upload_url($form_id) . "/$y/$m/";
  1634. //adding filter to upload root path and url
  1635. $upload_root_info = array("path" => $target_root, "url" => $target_root_url);
  1636. $upload_root_info = apply_filters("gform_upload_path_{$form_id}", apply_filters("gform_upload_path", $upload_root_info, $form_id));
  1637. $target_root = $upload_root_info["path"];
  1638. $target_root_url = $upload_root_info["url"];
  1639. if(!is_dir($target_root)){
  1640. if(!wp_mkdir_p($target_root))
  1641. return false;
  1642. //adding index.html files to all subfolders
  1643. if(!file_exists(self::get_upload_root() . "/index.html")){
  1644. GFCommon::recursive_add_index_file(self::get_upload_root());
  1645. }
  1646. else if(!file_exists(self::get_upload_path($form_id) . "/index.html")){
  1647. GFCommon::recursive_add_index_file(self::get_upload_path($form_id));
  1648. }
  1649. else if(!file_exists(self::get_upload_path($form_id) . "/$y/index.html")){
  1650. GFCommon::recursive_add_index_file(self::get_upload_path($form_id) . "/$y");
  1651. }
  1652. else{
  1653. GFCommon::recursive_add_index_file(self::get_upload_path($form_id) . "/$y/$m");
  1654. }
  1655. }
  1656. //Add the original filename to our target path.
  1657. //Result is "uploads/filename.extension"
  1658. $file_info = pathinfo($file_name);
  1659. $extension = $file_info["extension"];
  1660. $file_name = basename($file_info["basename"], "." . $extension);
  1661. $file_name = sanitize_file_name($file_name);
  1662. $counter = 1;
  1663. $target_path = $target_root . $file_name . "." . $extension;
  1664. while(file_exists($target_path)){
  1665. $target_path = $target_root . $file_name . "$counter" . "." . $extension;
  1666. $counter++;
  1667. }
  1668. //creating url
  1669. $target_url = str_replace($target_root, $target_root_url, $target_path);
  1670. return array("path" => $target_path, "url" => $target_url);
  1671. }
  1672. public static function drop_tables(){
  1673. global $wpdb;
  1674. $wpdb->query("DROP TABLE IF EXISTS " . self::get_lead_details_long_table_name());
  1675. $wpdb->query("DROP TABLE IF EXISTS " . self::get_lead_notes_table_name());
  1676. $wpdb->query("DROP TABLE IF EXISTS " . self::get_lead_details_table_name());
  1677. $wpdb->query("DROP TABLE IF EXISTS " . self::get_lead_table_name());
  1678. $wpdb->query("DROP TABLE IF EXISTS " . self::get_form_view_table_name());
  1679. $wpdb->query("DROP TABLE IF EXISTS " . self::get_meta_table_name());
  1680. $wpdb->query("DROP TABLE IF EXISTS " . self::get_form_table_name());
  1681. $wpdb->query("DROP TABLE IF EXISTS " . self::get_lead_meta_table_name());
  1682. }
  1683. public static function insert_form_view($form_id, $ip){
  1684. global $wpdb;
  1685. $table_name = self::get_form_view_table_name();
  1686. $sql = $wpdb->prepare(" SELECT id FROM $table_name
  1687. WHERE form_id=%d
  1688. AND year(date_created) = year(utc_timestamp())
  1689. AND month(date_created) = month(utc_timestamp())
  1690. AND day(date_created) = day(utc_timestamp())
  1691. AND hour(date_created) = hour(utc_timestamp())", $form_id);
  1692. $id = $wpdb->get_var($sql, 0, 0);
  1693. if(empty($id))
  1694. $wpdb->query($wpdb->prepare("INSERT INTO $table_name(form_id, date_created, ip) values(%d, utc_timestamp(), %s)", $form_id, $ip));
  1695. else
  1696. $wpdb->query($wpdb->prepare("UPDATE $table_name SET count = count+1 WHERE id=%d", $id));
  1697. }
  1698. public static function is_duplicate($form_id, $field, $value){
  1699. global $wpdb;
  1700. $lead_detail_table_name = self::get_lead_details_table_name();
  1701. $lead_table_name = self::get_lead_table_name();
  1702. switch(RGFormsModel::get_input_type($field)){
  1703. case "time" :
  1704. $value = sprintf("%d:%02d %s", $value[0], $value[1], $value[2]);
  1705. break;
  1706. case "date" :
  1707. $value = self::prepare_date(rgar($field, "dateFormat"), $value);
  1708. break;
  1709. }
  1710. $inner_sql_template = " SELECT %s as input, ld.lead_id
  1711. FROM $lead_detail_table_name ld
  1712. INNER JOIN $lead_table_name l ON l.id = ld.lead_id
  1713. WHERE l.form_id=%d AND ld.form_id=%d
  1714. AND ld.field_number between %s AND %s
  1715. AND ld.value=%s";
  1716. $sql = "SELECT count(distinct input) as match_count FROM ( ";
  1717. $input_count = 1;
  1718. if(is_array($field["inputs"])){
  1719. $input_count = sizeof($field["inputs"]);
  1720. foreach($field["inputs"] as $input){
  1721. $union = empty($inner_sql) ? "" : " UNION ALL ";
  1722. $inner_sql .= $union . $wpdb->prepare($inner_sql_template, $input["id"], $form_id, $form_id, $input["id"] - 0.001, $input["id"] + 0.001, $value[$input["id"]]);
  1723. }
  1724. }
  1725. else{
  1726. $inner_sql = $wpdb->prepare($inner_sql_template, $field["id"], $form_id, $form_id, $field["id"] - 0.001, $field["id"] + 0.001, $value);
  1727. }
  1728. $sql .= $inner_sql . "
  1729. ) as count
  1730. GROUP BY lead_id
  1731. ORDER BY match_count DESC";
  1732. $count = apply_filters("gform_is_duplicate_{$form_id}", apply_filters('gform_is_duplicate', $wpdb->get_var($sql), $form_id, $field, $value), $form_id, $field, $value);
  1733. return $count != null && $count >= $input_count;
  1734. }
  1735. public static function get_lead($lead_id){
  1736. global $wpdb;
  1737. $lead_detail_table_name = self::get_lead_details_table_name();
  1738. $lead_table_name = self::get_lead_table_name();
  1739. $results = $wpdb->get_results($wpdb->prepare(" SELECT l.*, field_number, value
  1740. FROM $lead_table_name l
  1741. INNER JOIN $lead_detail_table_name ld ON l.id = ld.lead_id
  1742. WHERE l.id=%d", $lead_id));
  1743. $leads = self::build_lead_array($results, true);
  1744. return sizeof($leads) == 1 ? $leads[0] : false;
  1745. }
  1746. public static function get_lead_notes($lead_id){
  1747. global $wpdb;
  1748. $notes_table = self::get_lead_notes_table_name();
  1749. return $wpdb->get_results($wpdb->prepare(" SELECT n.id, n.user_id, n.date_created, n.value, ifnull(u.display_name,n.user_name) as user_name, u.user_email
  1750. FROM $notes_table n
  1751. LEFT OUTER JOIN $wpdb->users u ON n.user_id = u.id
  1752. WHERE lead_id=%d ORDER BY id", $lead_id));
  1753. }
  1754. public static function get_lead_field_value($lead, $field){
  1755. if(empty($lead))
  1756. return;
  1757. $max_length = GFORMS_MAX_FIELD_LENGTH;
  1758. $value = array();
  1759. if(is_array(rgar($field, "inputs"))){
  1760. //making sure values submitted are sent in the value even if
  1761. //there isn't an input associated with it
  1762. $lead_field_keys = array_keys($lead);
  1763. foreach($lead_field_keys as $input_id){
  1764. if(is_numeric($input_id) && absint($input_id) == absint($field["id"])){
  1765. $val = $lead[$input_id];
  1766. if(strlen($val) >= ($max_length-10)) {
  1767. if(empty($form))
  1768. $form = RGFormsModel::get_form_meta($lead["form_id"]);
  1769. $long_choice = self::get_field_value_long($lead, $input_id, $form);
  1770. }
  1771. else{
  1772. $long_choice = $val;
  1773. }
  1774. $value[$input_id] = !empty($long_choice) ? $long_choice : $val;
  1775. }
  1776. }
  1777. }
  1778. else{
  1779. $val = rgget($field["id"], $lead);
  1780. //To save a database call to get long text, only getting long text if regular field is "somewhat" large (i.e. max - 50)
  1781. if(strlen($val) >= ($max_length - 50)){
  1782. if(empty($form))
  1783. $form = RGFormsModel::get_form_meta($lead["form_id"]);
  1784. $long_text = self::get_field_value_long($lead, $field["id"], $form);
  1785. }
  1786. $value = !empty($long_text) ? $long_text : $val;
  1787. }
  1788. //filtering lead value
  1789. $value = apply_filters("gform_get_field_value", $value, $lead, $field);
  1790. return $value;
  1791. }
  1792. public static function get_field_value_long($lead, $field_number, $form, $apply_filter=true){
  1793. global $wpdb;
  1794. $detail_table_name = self::get_lead_details_table_name();
  1795. $long_table_name = self::get_lead_details_long_table_name();
  1796. $sql = $wpdb->prepare(" SELECT l.value FROM $detail_table_name d
  1797. INNER JOIN $long_table_name l ON l.lead_detail_id = d.id
  1798. WHERE lead_id=%d AND field_number BETWEEN %f AND %f", $lead["id"], $field_number - 0.001, $field_number + 0.001);
  1799. $val = $wpdb->get_var($sql);
  1800. //running aform_get_input_value when needed
  1801. if($apply_filter){
  1802. $field = RGFormsModel::get_field($form, $field_number);
  1803. $input_id = (string)$field_number == (string)$field["id"] ? "" : $field_number;
  1804. $val = apply_filters("gform_get_input_value", $val, $lead, $field, $input_id);
  1805. }
  1806. return $val;
  1807. }
  1808. public static function get_leads($form_id, $sort_field_number=0, $sort_direction='DESC', $search='', $offset=0, $page_size=30, $star=null, $read=null, $is_numeric_sort = false, $start_date=null, $end_date=null, $status='active'){
  1809. global $wpdb;
  1810. if($sort_field_number == 0)
  1811. $sort_field_number = "date_created";
  1812. if(is_numeric($sort_field_number))
  1813. $sql = self::sort_by_custom_field_query($form_id, $sort_field_number, $sort_direction, $search, $offset, $page_size, $star, $read, $is_numeric_sort, $status);
  1814. else
  1815. $sql = self::sort_by_default_field_query($form_id, $sort_field_number, $sort_direction, $search, $offset, $page_size, $star, $read, $is_numeric_sort, $start_date, $end_date, $status);
  1816. //initializing rownum
  1817. $wpdb->query("select @rownum:=0");
  1818. //getting results
  1819. $results = $wpdb->get_results($sql);
  1820. $leads = self::build_lead_array($results);
  1821. return $leads;
  1822. }
  1823. private static function sort_by_custom_field_query($form_id, $sort_field_number=0, $sort_direction='DESC', $search='', $offset=0, $page_size=30, $star=null, $read=null, $is_numeric_sort = false, $status='active'){
  1824. global $wpdb;
  1825. if(!is_numeric($form_id) || !is_numeric($sort_field_number)|| !is_numeric($offset)|| !is_numeric($page_size))
  1826. return "";
  1827. $lead_detail_table_name = self::get_lead_details_table_name();
  1828. $lead_table_name = self::get_lead_table_name();
  1829. $orderby = $is_numeric_sort ? "ORDER BY query, (value+0) $sort_direction" : "ORDER BY query, value $sort_direction";
  1830. $search_term = "%$search%";
  1831. $search_filter = empty($search) ? "" : $wpdb->prepare("WHERE d.value LIKE %s", $search_term);
  1832. //starred clause
  1833. $where = empty($search_filter) ? "WHERE" : "AND";
  1834. $search_filter .= $star !== null && $status == 'active' ? $wpdb->prepare("$where is_starred=%d AND status='active' ", $star) : "";
  1835. //read clause
  1836. $where = empty($search_filter) ? "WHERE" : "AND";
  1837. $search_filter .= $read !== null && $status == 'active' ? $wpdb->prepare("$where is_read=%d AND status='active' ", $read) : "";
  1838. //status clause
  1839. $where = empty($search_filter) ? "WHERE" : "AND";
  1840. $search_filter .= $wpdb->prepare("$where status=%s ", $status);
  1841. $field_number_min = $sort_field_number - 0.001;
  1842. $field_number_max = $sort_field_number + 0.001;
  1843. $sql = "
  1844. SELECT filtered.sort, l.*, d.field_number, d.value
  1845. FROM $lead_table_name l
  1846. INNER JOIN $lead_detail_table_name d ON d.lead_id = l.id
  1847. INNER JOIN (
  1848. SELECT distinct sorted.sort, l.id
  1849. FROM $lead_table_name l
  1850. INNER JOIN $lead_detail_table_name d ON d.lead_id = l.id
  1851. INNER JOIN (
  1852. SELECT @rownum:=@rownum+1 as sort, id FROM (
  1853. SELECT 0 as query, lead_id as id, value
  1854. FROM $lead_detail_table_name
  1855. WHERE form_id=$form_id
  1856. AND field_number between $field_number_min AND $field_number_max
  1857. UNION ALL
  1858. SELECT 1 as query, l.id, d.value
  1859. FROM $lead_table_name l
  1860. LEFT OUTER JOIN $lead_detail_table_name d ON d.lead_id = l.id AND field_number between $field_number_min AND $field_number_max
  1861. WHERE l.form_id=$form_id
  1862. AND d.lead_id IS NULL
  1863. ) sorted1
  1864. $orderby
  1865. ) sorted ON d.lead_id = sorted.id
  1866. $search_filter
  1867. LIMIT $offset,$page_size
  1868. ) filtered ON filtered.id = l.id
  1869. ORDER BY filtered.sort";
  1870. return $sql;
  1871. }
  1872. private static function sort_by_default_field_query($form_id, $sort_field, $sort_direction='DESC', $search='', $offset=0, $page_size=30, $star=null, $read=null, $is_numeric_sort = false, $start_date=null, $end_date=null, $status='active'){
  1873. global $wpdb;
  1874. if(!is_numeric($form_id) || !is_numeric($offset)|| !is_numeric($page_size)){
  1875. return "";
  1876. }
  1877. $lead_detail_table_name = self::get_lead_details_table_name();
  1878. $lead_table_name = self::get_lead_table_name();
  1879. $search_term = "%$search%";
  1880. $search_filter = empty($search) ? "" : $wpdb->prepare(" AND value LIKE %s", $search_term);
  1881. $star_filter = $star !== null && $status == 'active' ? $wpdb->prepare(" AND is_starred=%d AND status='active' ", $star) : "";
  1882. $read_filter = $read !== null && $status == 'active' ? $wpdb->prepare(" AND is_read=%d AND status='active' ", $read) : "";
  1883. $status_filter = $wpdb->prepare(" AND status=%s ", $status);
  1884. $start_date_filter = empty($start_date) ? "" : " AND datediff(date_created, '$start_date') >=0";
  1885. $end_date_filter = empty($end_date) ? "" : " AND datediff(date_created, '$end_date') <=0";
  1886. $sql = "
  1887. SELECT filtered.sort, l.*, d.field_number, d.value
  1888. FROM $lead_table_name l
  1889. INNER JOIN $lead_detail_table_name d ON d.lead_id = l.id
  1890. INNER JOIN
  1891. (
  1892. SELECT @rownum:=@rownum + 1 as sort, id
  1893. FROM
  1894. (
  1895. SELECT distinct l.id
  1896. FROM $lead_table_name l
  1897. INNER JOIN $lead_detail_table_name d ON d.lead_id = l.id
  1898. WHERE l.form_id=$form_id
  1899. $search_filter
  1900. $star_filter
  1901. $read_filter
  1902. $status_filter
  1903. $start_date_filter
  1904. $end_date_filter
  1905. ORDER BY $sort_field $sort_direction
  1906. LIMIT $offset,$page_size
  1907. ) page
  1908. ) filtered ON filtered.id = l.id
  1909. ORDER BY filtered.sort";
  1910. return $sql;
  1911. }
  1912. public static function build_lead_array($results, $use_long_values = false){
  1913. $leads = array();
  1914. $lead = array();
  1915. $form_id = 0;
  1916. if(is_array($results) && sizeof($results) > 0){
  1917. $form_id = $results[0]->form_id;
  1918. $lead = array("id" => $results[0]->id, "form_id" => $results[0]->form_id, "date_created" => $results[0]->date_created, "is_starred" => intval($results[0]->is_starred), "is_read" => intval($results[0]->is_read), "ip" => $results[0]->ip, "source_url" => $results[0]->source_url, "post_id" => $results[0]->post_id, "currency" => $results[0]->currency, "payment_status" => $results[0]->payment_status, "payment_date" => $results[0]->payment_date, "transaction_id" => $results[0]->transaction_id, "payment_amount" => $results[0]->payment_amount, "is_fulfilled" => $results[0]->is_fulfilled, "created_by" => $results[0]->created_by, "transaction_type" => $results[0]->transaction_type, "user_agent" => $results[0]->user_agent, "status" => $results[0]->status);
  1919. }
  1920. $form = RGFormsModel::get_form_meta($form_id);
  1921. $prev_lead_id=0;
  1922. foreach($results as $result){
  1923. if($prev_lead_id <> $result->id && $prev_lead_id > 0){
  1924. array_push($leads, $lead);
  1925. $lead = array("id" => $result->id, "form_id" => $result->form_id, "date_created" => $result->date_created, "is_starred" => intval($result->is_starred), "is_read" => intval($result->is_read), "ip" => $result->ip, "source_url" => $result->source_url, "post_id" => $result->post_id, "currency" => $result->currency, "payment_status" => $result->payment_status, "payment_date" => $result->payment_date, "transaction_id" => $result->transaction_id, "payment_amount" => $result->payment_amount, "is_fulfilled" => $result->is_fulfilled, "created_by" => $result->created_by, "transaction_type" => $result->transaction_type, "user_agent" => $result->user_agent, "status" => $result->status);
  1926. }
  1927. $field_value = $result->value;
  1928. //using long values if specified
  1929. if($use_long_values && strlen($field_value) >= (GFORMS_MAX_FIELD_LENGTH-10)){
  1930. $field = RGFormsModel::get_field($form, $result->field_number);
  1931. $long_text = RGFormsModel::get_field_value_long($lead, $result->field_number, $form, false);
  1932. $field_value = !empty($long_text) ? $long_text : $field_value;
  1933. }
  1934. $lead[$result->field_number] = $field_value;
  1935. $prev_lead_id = $result->id;
  1936. }
  1937. //adding last lead.
  1938. if(sizeof($lead) > 0)
  1939. array_push($leads, $lead);
  1940. //running entry through gform_get_field_value filter
  1941. foreach($leads as &$lead){
  1942. foreach($form["fields"] as $field){
  1943. if(isset($field["inputs"]) && is_array($field["inputs"])){
  1944. foreach($field["inputs"] as $input){
  1945. $lead[(string)$input["id"]] = apply_filters("gform_get_input_value", rgar($lead, (string)$input["id"]), $lead, $field, $input["id"]);
  1946. }
  1947. }
  1948. else{
  1949. $lead[$field["id"]] = apply_filters("gform_get_input_value", rgar($lead, (string)$field["id"]), $lead, $field, "");
  1950. }
  1951. }
  1952. }
  1953. return $leads;
  1954. }
  1955. public static function save_key($key){
  1956. $current_key = get_option("rg_gforms_key");
  1957. if(empty($key)){
  1958. delete_option("rg_gforms_key");
  1959. }
  1960. else if($current_key != $key){
  1961. $key = trim($key);
  1962. update_option("rg_gforms_key", md5($key));
  1963. }
  1964. }
  1965. public static function get_lead_count($form_id, $search, $star=null, $read=null, $start_date=null, $end_date=null, $status=null){
  1966. global $wpdb;
  1967. if(!is_numeric($form_id))
  1968. return "";
  1969. $detail_table_name = self::get_lead_details_table_name();
  1970. $lead_table_name = self::get_lead_table_name();
  1971. $star_filter = $star !== null ? $wpdb->prepare("AND is_starred=%d ", $star) : "";
  1972. $read_filter = $read !== null ? $wpdb->prepare("AND is_read=%d ", $read) : "";
  1973. $start_date_filter = empty($start_date) ? "" : " AND datediff(date_created, '$start_date') >=0";
  1974. $end_date_filter = empty($end_date) ? "" : " AND datediff(date_created, '$end_date') <=0";
  1975. $status_filter = $status !== null ? $wpdb->prepare(" AND status='%s' ", $status) : "";
  1976. $search_term = "%$search%";
  1977. $search_filter = empty($search) ? "" : $wpdb->prepare("AND value LIKE %s", $search_term);
  1978. $sql = "SELECT count(distinct l.id)
  1979. FROM $lead_table_name l
  1980. INNER JOIN $detail_table_name ld ON l.id = ld.lead_id
  1981. WHERE l.form_id=$form_id
  1982. AND ld.form_id=$form_id
  1983. $star_filter
  1984. $read_filter
  1985. $start_date_filter
  1986. $end_date_filter
  1987. $status_filter
  1988. $search_filter";
  1989. return $wpdb->get_var($sql);
  1990. }
  1991. public static function get_grid_columns($form_id, $input_label_only=false){
  1992. $form = self::get_form_meta($form_id);
  1993. $field_ids = self::get_grid_column_meta($form_id);
  1994. if(!is_array($field_ids)){
  1995. $field_ids = array();
  1996. for($i=0, $count=sizeof($form["fields"]); $i<$count && $i<5; $i++){
  1997. $field = $form["fields"][$i];
  1998. if(RGForms::get("displayOnly",$field) || self::get_input_type($field) == "list")
  1999. continue;
  2000. if(isset($field["inputs"]) && is_array($field["inputs"])){
  2001. if($field["type"] == "name"){
  2002. $field_ids[] = $field["id"] . '.3'; //adding first name
  2003. $field_ids[] = $field["id"] . '.6'; //adding last name
  2004. }
  2005. else{
  2006. $field_ids[] = $field["inputs"][0]["id"]; //getting first input
  2007. }
  2008. }
  2009. else{
  2010. $field_ids[] = $field["id"];
  2011. }
  2012. }
  2013. }
  2014. $columns = array();
  2015. foreach($field_ids as $field_id){
  2016. switch($field_id){
  2017. case "id" :
  2018. $columns[$field_id] = array("label" => "Entry Id", "type" => "id");
  2019. break;
  2020. case "ip" :
  2021. $columns[$field_id] = array("label" => "User IP", "type" => "ip");
  2022. break;
  2023. case "date_created" :
  2024. $columns[$field_id] = array("label" => "Entry Date", "type" => "date_created");
  2025. break;
  2026. case "source_url" :
  2027. $columns[$field_id] = array("label" => "Source Url", "type" => "source_url");
  2028. break;
  2029. case "payment_status" :
  2030. $columns[$field_id] = array("label" => "Payment Status", "type" => "payment_status");
  2031. break;
  2032. case "transaction_id" :
  2033. $columns[$field_id] = array("label" => "Transaction Id", "type" => "transaction_id");
  2034. break;
  2035. case "payment_date" :
  2036. $columns[$field_id] = array("label" => "Payment Date", "type" => "payment_date");
  2037. break;
  2038. case "payment_amount" :
  2039. $columns[$field_id] = array("label" => "Payment Amount", "type" => "payment_amount");
  2040. break;
  2041. case "created_by" :
  2042. $columns[$field_id] = array("label" => "User", "type" => "created_by");
  2043. break;
  2044. default :
  2045. $field = self::get_field($form, $field_id);
  2046. if($field)
  2047. $columns[strval($field_id)] = array("label" => self::get_label($field, $field_id, $input_label_only), "type" => rgget("type", $field), "inputType" => rgget("inputType", $field));
  2048. }
  2049. }
  2050. return $columns;
  2051. }
  2052. public static function get_label($field, $input_id = 0, $input_only = false){
  2053. $field_label = (IS_ADMIN || RG_CURRENT_PAGE == "select_columns.php" || RG_CURRENT_PAGE == "print-entry.php" || rgget("gf_page", $_GET) == "select_columns" || rgget("gf_page", $_GET) == "print-entry") && !rgempty("adminLabel", $field) ? rgar($field,"adminLabel") : rgar($field,"label");
  2054. $input = self::get_input($field, $input_id);
  2055. if(rgget("type", $field) == "checkbox" && $input != null)
  2056. return $input["label"];
  2057. else if($input != null)
  2058. return $input_only ? $input["label"] : $field_label . ' (' . $input["label"] . ')';
  2059. else
  2060. return $field_label;
  2061. }
  2062. public static function get_input($field, $id){
  2063. if(isset($field["inputs"]) && is_array($field["inputs"])){
  2064. foreach($field["inputs"] as $input)
  2065. {
  2066. if($input["id"] == $id)
  2067. return $input;
  2068. }
  2069. }
  2070. return null;
  2071. }
  2072. function has_input($field, $input_id){
  2073. if(!is_array($field["inputs"]))
  2074. return false;
  2075. else{
  2076. foreach($field["inputs"] as $input)
  2077. {
  2078. if($input["id"] == $input_id)
  2079. return true;
  2080. }
  2081. return false;
  2082. }
  2083. }
  2084. public function get_current_page_url($force_ssl=false) {
  2085. $pageURL = 'http';
  2086. if (RGForms::get("HTTPS",$_SERVER) == "on" || $force_ssl)
  2087. $pageURL .= "s";
  2088. $pageURL .= "://";
  2089. $pageURL .= RGForms::get("HTTP_HOST", $_SERVER) . rgget("REQUEST_URI", $_SERVER);
  2090. return $pageURL;
  2091. }
  2092. public static function get_submitted_fields($form_id){
  2093. global $wpdb;
  2094. $lead_detail_table_name = self::get_lead_details_table_name();
  2095. $field_list = "";
  2096. $fields = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT field_number FROM $lead_detail_table_name WHERE form_id=%d", $form_id));
  2097. foreach($fields as $field)
  2098. $field_list .= intval($field->field_number) . ',';
  2099. if(!empty($field_list))
  2100. $field_list = substr($field_list, 0, strlen($field_list) -1);
  2101. return $field_list;
  2102. }
  2103. public static function get_field($form, $field_id){
  2104. if(is_numeric($field_id))
  2105. $field_id = intval($field_id); //removing floating part of field (i.e 1.3 -> 1) to return field by input id
  2106. if(!is_array($form["fields"]))
  2107. return null;
  2108. foreach($form["fields"] as $field){
  2109. if($field["id"] == $field_id)
  2110. return $field;
  2111. }
  2112. return null;
  2113. }
  2114. public static function is_html5_enabled(){
  2115. return get_option("rg_gforms_enable_html5");
  2116. }
  2117. }
  2118. global $_gform_lead_meta;
  2119. $_gform_lead_meta = array();
  2120. //functions to handle lead meta
  2121. function gform_get_meta($entry_id, $meta_key){
  2122. global $wpdb, $_gform_lead_meta;
  2123. //get from cache if available
  2124. $cache_key = $entry_id . "_" . $meta_key;
  2125. if(array_key_exists($cache_key, $_gform_lead_meta))
  2126. return $_gform_lead_meta[$cache_key];
  2127. $table_name = RGFormsModel::get_lead_meta_table_name();
  2128. $value = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$table_name} WHERE lead_id=%d AND meta_key=%s", $entry_id, $meta_key));
  2129. $meta_value = $value == null ? false : maybe_unserialize($value);
  2130. $_gform_lead_meta[$cache_key] = $meta_value;
  2131. return $meta_value;
  2132. }
  2133. function gform_update_meta($entry_id, $meta_key, $meta_value){
  2134. global $wpdb, $_gform_lead_meta;
  2135. $table_name = RGFormsModel::get_lead_meta_table_name();
  2136. $meta_value = maybe_serialize($meta_value);
  2137. $meta_exists = gform_get_meta($entry_id, $meta_key) !== false;
  2138. if($meta_exists){
  2139. $wpdb->update($table_name, array("meta_value" => $meta_value), array("lead_id" => $entry_id, "meta_key" => $meta_key),array("%s"), array("%d", "%s"));
  2140. }
  2141. else{
  2142. $wpdb->insert($table_name, array("lead_id" => $entry_id, "meta_key" => $meta_key, "meta_value" => $meta_value), array("%d", "%s", "%s"));
  2143. }
  2144. //updates cache
  2145. $cache_key = $entry_id . "_" . $meta_key;
  2146. if(array_key_exists($cache_key, $_gform_lead_meta))
  2147. $_gform_lead_meta[$cache_key] = maybe_unserialize($meta_value);
  2148. }
  2149. function gform_delete_meta($entry_id, $meta_key=""){
  2150. global $wpdb, $_gform_lead_meta;
  2151. $table_name = RGFormsModel::get_lead_meta_table_name();
  2152. $meta_filter = empty($meta_key) ? "" : $wpdb->prepare("AND meta_key=%s", $meta_key);
  2153. $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE lead_id=%d {$meta_filter}", $entry_id));
  2154. //clears cache.
  2155. $_gform_lead_meta = array();
  2156. }
  2157. ?>