This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdb.php
1856 lines (1586 loc) · 60.1 KB
/
db.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
class fm_db_class{
public $formsTable;
public $itemsTable;
public $settingsTable;
public $templatesTable;
public $showerr;
private $lastErrorMessage;
private $lastPostFailed;
private $lastUniqueName;
// fails silently if an install is detected, but without tables.
// - fixes a bug with multisite during a clone; MySQL error when loading the settings table
// - fixes a bug when security plugins rename tables;
static function Construct($formsTable, $itemsTable, $settingsTable, $templatesTable, $conn){
global $wpdb;
$installedVersion = get_option( 'fm-version', false );
// if there is an install detected, check that the tables exist
if ( $installedVersion !== false ){
$tables = array ($formsTable, $itemsTable, $settingsTable, $templatesTable);
foreach ( $tables as $tableName ){
if ( $wpdb->query("SHOW TABLES LIKE '".$tableName."'") != 1 ){
return null;
}
}
}
// all the checks passed, create the object
return new fm_db_class($formsTable, $itemsTable, $settingsTable, $templatesTable, $conn);
}
// use the above static method to create the fm_db_class object
protected function __construct($formsTable, $itemsTable, $settingsTable, $templatesTable){
$this->formsTable = $formsTable;
$this->itemsTable = $itemsTable;
$this->settingsTable = $settingsTable;
$this->templatesTable = $templatesTable;
$this->cachedInfo = array();
$this->lastPostFailed = false;
$this->showerr = true;
$this->initDefaultSettings();
$this->lastPostFailed = false;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
function query($q){
global $wpdb;
return $wpdb->query($q);
}
function get_results($q){
global $wpdb;
return $wpdb->get_results($q,ARRAY_A);
}
function get_row($q){
global $wpdb;
return $wpdb->get_row($q,ARRAY_A);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//Cache
//the fm_db_class appears stateless to the user; however we can keep track of some things to make fewer queries.
// the $cachedInfo variable is an array of arrays indexed by formID; this should only be used to cache data
// that will not change (such as data table names) and may be queried more than once.
protected $cachedInfo;
protected function getCache($formID, $key){
if(!isset($this->cachedInfo[$formID]) || !isset($this->cachedInfo[$formID][$key])) return null; //return null on cache miss, in order to distinguish from 'false'
else return $this->cachedInfo[$formID][$key];
}
protected function setCache($formID, $key, $value){
if(!isset($this->cachedInfo[$formID])) $this->cachedInfo[$formID] = array($key => $value);
else $this->cachedInfo[$formID][$key] = $value;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//values are the form defaults
public $formSettingsKeys;
public $itemKeys;
public $globalSettings;
function initDefaultSettings(){
$this->formSettingsKeys = array(
'title' => '',
'submitted_msg' => '',
'submit_btn_text' => __('Submit', 'wordpress-form-manager'),
'required_msg' => '',
'reg_user_only_msg' => '',
'action' => '',
'data_index' => '',
'shortcode' => '',
'type' => 'form',
'email_list' => '',
'behaviors' => '',
'email_user_field' => '',
'form_template' => '',
'email_template' => '',
'email_from' => '',
'email_subject' => '',
'summary_template' => '',
'template_values' => '',
'show_summary' => 0,
'use_advanced_email' => 0,
'advanced_email' => '',
'publish_post' => 0,
'publish_post_category' => '',
'publish_post_status' => 'publish',
'publish_post_title' => __('[form title] Submission', 'wordpress-form-manager'),
'auto_redirect' => 0,
'auto_redirect_page' => 0,
'auto_redirect_timeout' => 5,
'conditions' => '',
'summary_hide_empty' => 0,
'exact_form_action' => '',
'enable_autocomplete' => 1,
);
$this->itemKeys = array (
'type' => 0,
'index' => 0,
'extra' => 0,
'nickname' => 0,
'label' => 0,
'required' => 0,
'db_type' => 0,
'description' => 0,
'set' => 0,
);
$this->globalSettings = array(
'recaptcha_public' => '',
'recaptcha_private' => '',
'recaptcha_theme' => 'red',
'recaptcha_lang' => substr(get_bloginfo('language'), 0, 2),
/* translators: the default name of a new form */
'title' => __("New Form", 'wordpress-form-manager'),
'submitted_msg' => __('Thank you! Your data has been submitted.', 'wordpress-form-manager'),
/* translators: the default message given if a required item is left blank. You must include a backslash before any single quotes */
'required_msg' => stripslashes(__("\'%s\' is required.", 'wordpress-form-manager')),
'reg_user_only_msg' => __("'%s' is only available to registered users.", 'wordpress-form-manager'),
'email_admin' => "YES",
'email_reg_users' => "YES",
'email_subject' => __("[form title] Submission", 'wordpress-form-manager'),
'email_from' => "[admin email]",
'template_form' => '',
'text_validator_count' => 8,
'text_validator_0' => array('name' => 'number',
/* translators: the following are for the numbers only validator */
'label' => __('Numbers Only', 'wordpress-form-manager'),
'message' => __("'%s' must be a valid number", 'wordpress-form-manager'),
'regexp' => '/^\s*[0-9]*[\.]?[0-9]+\s*$/'
),
'text_validator_1' => array('name' => 'phone',
/* translators: the following are for the phone number validator */
'label' => __('Phone Number', 'wordpress-form-manager'),
'message' => __("'%s' must be a valid phone number", 'wordpress-form-manager'),
/* translators: the regular expression for US phone numbers (XXX XXX XXXX). */
'regexp' => __('/^.*[0-9]{3}.*[0-9]{3}.*[0-9]{4}.*$/', 'wordpress-form-manager')
),
'text_validator_2' => array('name' => 'email',
/* translators: the following are for the e-mail validator */
'label' => __("E-Mail", 'wordpress-form-manager'),
'message' => __("'%s' must be a valid e-mail address", 'wordpress-form-manager'),
'regexp' => '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'
),
'text_validator_3' => array('name' => 'date',
/* translators: the following are for the date validator */
'label' => __("Date (MM/DD/YY)", 'wordpress-form-manager'),
'message' => __("'%s' must be a date (MM/DD/YY)", 'wordpress-form-manager'),
'regexp' => '/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/'
),
'text_validator_4' => array('name' => 'state',
'label' => __("State (U.S.)", 'wordpress-form-manager'),
'message' => __("'%s' must be a valid state abbreviation", 'wordpress-form-manager'),
'regexp' => '/^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/i'
),
'text_validator_5' => array('name' => 'zip',
'label' => __("Zip code (U.S.)", 'wordpress-form-manager'),
'message' => __("'%s' must be a valid zip code", 'wordpress-form-manager'),
'regexp' => '/^\d{5}$/'
),
'text_validator_6' => array('name' => 'dimensions',
'label' => __("Dimensions (L x W x H)", 'wordpress-form-manager'),
'message' => __("'%s' must be dimensions (L x W x H)", 'wordpress-form-manager'),
'regexp' => '/^\s*(\d+(\.\d+)?)\s*(x|X)\s*(\d+(\.\d+)?)\s*(x|X)\s*(\d+(\.\d+)?)\s*$/'
),
'text_validator_7' => array('name' => 'date2',
/* translators: the following are for the date validator */
'label' => __("Date (DD/MM/YY)", 'wordpress-form-manager'),
'message' => __("'%s' must be a date (DD/MM/YY)", 'wordpress-form-manager'),
'regexp' => '/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/'
),
);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Database setup & removal
function setupFormManager(){
$charset_collate = $this->getCharsetCollation();
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
//////////////////////////////////////////////////////////////////
//form definitions table - stores ID, title, options, and name of data table for each form
/*
ID - stores the unique integer ID of the form
title - form title
submitted_msg - message displayed when user submits data
submit_btn_text - text on the 'submit' button
required_msg - message shown in the 'required' popup; use %s in the string to show the field label. If no string is given, default message is used.
data_table - table where the form's submissions are stored
action - form 'action' attribute
data_index - data table primary key, if it has one
shortcode - shortcode for the form in question (wordpress only)
type - type of form ('form', 'template')
email_list - list of e-mails to send notifications to
behaviors - comma separated list of 'behaviors', such as reg_user_only, etc.
email_user_field - the unique name of a field within the form that will contain an e-mail address upon submission, which will be sent a notification
form_template - the file name of the form template to use. if blank, uses the default template
email_template - same as above, as applies to email notifications
email_subject - subject line of the e-mail notifications (shortcoded)
email_from - from header of the e-mail notofications (shortcoded)
summary_template - same as aoove, as applies to the summaries displayed for single submission / user profile style forms
template_values - associative array of the template specific values, as set in the form editor
show_summary - whether or not to show a summary of the submitted data along with the submission acknowledgment
use_advanced_email - whether or not to override the 'E-Mail Notifications' settings on the main form editor
advanced_email - the advanced email settings, a block of text defining e-mails, headers, etc.
publish_post - whether or not to publish form submissions to a post category
publish_post_category - the post category to publish submissions to
publish_post_title - the title of published posts
auto_redirect - whether or not to do the automatic redirect
auto_redirect_page - the page / post ID of the page to go to after (timeout) seconds
auto_redirect_timeout - the timeout for the automatic redirect
conditions - associative array structure, specifying form interface behavior conditions (e.g., only show elements if other elements have certain values)
*/
$sql = "CREATE TABLE `".$this->formsTable."` (
`ID` INT DEFAULT '0' NOT NULL,
`title` TEXT NOT NULL,
`submitted_msg` TEXT NOT NULL,
`submit_btn_text` VARCHAR( 32 ) DEFAULT '' NOT NULL,
`required_msg` TEXT NOT NULL,
`data_table` VARCHAR( 32 ) DEFAULT '' NOT NULL,
`action` TEXT NOT NULL,
`data_index` VARCHAR( 32 ) DEFAULT '' NOT NULL,
`shortcode` VARCHAR( 64 ) DEFAULT '' NOT NULL,
`type` VARCHAR( 32 ) DEFAULT '' NOT NULL,
`email_list` TEXT NOT NULL,
`behaviors` VARCHAR( 256 ) DEFAULT '' NOT NULL,
`email_user_field` VARCHAR( 64 ) DEFAULT '' NOT NULL,
`form_template` VARCHAR( 128 ) DEFAULT '' NOT NULL,
`email_template` VARCHAR( 128 ) DEFAULT '' NOT NULL,
`email_subject` VARCHAR( 1024 ) DEFAULT '' NOT NULL,
`email_from` VARCHAR( 1024 ) DEFAULT '' NOT NULL,
`summary_template` VARCHAR( 128 ) DEFAULT '' NOT NULL,
`template_values` TEXT NOT NULL,
`show_summary` BOOL DEFAULT '0' NOT NULL,
`use_advanced_email` BOOL DEFAULT '0' NOT NULL,
`advanced_email` TEXT NOT NULL,
`publish_post` BOOL DEFAULT '0' NOT NULL,
`publish_post_category` TEXT NOT NULL,
`publish_post_title` TEXT NOT NULL,
`publish_post_status` VARCHAR( 16 ) DEFAULT 'publish' NOT NULL,
`auto_redirect` BOOL DEFAULT '0' NOT NULL,
`auto_redirect_page` INT DEFAULT '0' NOT NULL,
`auto_redirect_timeout` INT DEFAULT '5' NOT NULL,
`conditions` TEXT NOT NULL,
`reg_user_only_msg` TEXT NOT NULL,
`summary_hide_empty` BOOL DEFAULT '0' NOT NULL,
`exact_form_action` VARCHAR( 1024 ) DEFAULT '' NOT NULL,
`enable_autocomplete` BOOL DEFAULT '1' NOT NULL,
PRIMARY KEY (`ID`)
) ".$charset_collate.";";
dbDelta($sql);
//create a settings row
$this->initFormsTable();
//////////////////////////////////////////////////////////////////
//global settings table
$sql = "CREATE TABLE " . $this->settingsTable . " (
`setting_name` VARCHAR( 32 ) NOT NULL,
`setting_value` TEXT NOT NULL,
PRIMARY KEY (`setting_name`)
) ".$charset_collate.";";
dbDelta($sql);
$this->initSettingsTable();
//////////////////////////////////////////////////////////////////
//form items - stores the items on all forms
$sql = "CREATE TABLE `".$this->itemsTable."` (
`ID` INT DEFAULT '0' NOT NULL ,
`index` INT DEFAULT '0' NOT NULL ,
`unique_name` VARCHAR( 64 ) DEFAULT '' NOT NULL ,
`type` VARCHAR( 32 ) DEFAULT '' NOT NULL ,
`extra` TEXT NOT NULL ,
`nickname` TEXT NOT NULL ,
`label` TEXT NOT NULL ,
`required` BOOL DEFAULT '0' NOT NULL ,
`db_type` VARCHAR( 16 ) DEFAULT '' NOT NULL ,
`description` TEXT NOT NULL ,
`set` INT DEFAULT '0' NOT NULL ,
INDEX ( `ID` ) ,
UNIQUE (`unique_name`)
) ".$charset_collate.";";
dbDelta($sql);
//////////////////////////////////////////////////////////////////
//templates - even though these are used as files, they are kept track of by and stored in the database so they persist across updates
$sql = "CREATE TABLE `".$this->templatesTable."` (
`title` TEXT NOT NULL,
`filename` TEXT NOT NULL,
`content` TEXT NOT NULL,
`status` VARCHAR( 32 ) DEFAULT '' NOT NULL,
`modified` BIGINT NOT NULL
) ".$charset_collate.";";
dbDelta($sql);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// for upgrading the database
//for 1.5.29 to 1.6.0+
function fixItemMeta(){
$this->query(
"ALTER TABLE `".$this->itemsTable."` ADD `set` INT DEFAULT '0' NOT NULL"
);
$caps = array();
$results = $this->get_results("SELECT * FROM `".$this->itemsTable."`");
foreach( $results as $row ){
$meta = unserialize($row['meta']);
$item = $this->unpackItem($row);
if($meta['private'] == '1'){
$item['set'] = '1';
if(!empty($meta['capability'])){
if(!isset($caps[$item['ID']])) $caps[$item['ID']] = array();
$caps[$item['ID']][$item['unique_name']] = $meta['capability'];
}
switch($item['type']){
case 'text':
case 'textarea':
case 'checkbox':
case 'custom_list':
$item['type'] = 'meta'.$item['type'];
break;
default:
$item['set'] = 0;
}
$this->updateFormItem($row['ID'], $item['unique_name'], $item);
}
}
$q = "ALTER TABLE `".$this->itemsTable."` DROP `meta`";
$this->query($q);
//now create default settings for each form
$q = "SELECT `ID` FROM `".$this->formsTable."`";
$results = $this->get_results($q);
foreach( $results as $row )
{
if(isset($caps[$row['ID']])){
$ds = $this->getDataPageSettings($row['ID']);
foreach($caps[$row['ID']] as $uniqueName => $capability){
$ds['edit_capabilities'][$uniqueName] = $capability;
}
update_option('fm-ds-'.$row['ID'], $ds);
}
}
}
//fix the collation on the data tables
function fixCollation(){
$charset_collate = $this->getCharsetCollation();
// do nothing if there is no collation or charset information
if ( $charset_collage == "" )
return;
//build a list of tables to fix
$tableList = array($this->formsTable, $this->itemsTable, $this->settingsTable);
$formList = $this->getFormList();
if(sizeof($formList) > 0)
foreach($formList as $form)
$tableList[] = $form['data_table'];
//fix the tables
foreach($tableList as $table){
$q = "ALTER TABLE `".$table."` DEFAULT ".$charset_collate;
$this->query($q);
$q = "SHOW FULL COLUMNS FROM `".$table."`";
$results = $this->get_results($q);
$cols = array();
foreach( $results as $row ) {
if(!is_null($row['Collation']))
$cols[] = $row;
}
if(sizeof($cols)>0){
$q = "ALTER TABLE `".$table."` ";
for($x=0;$x<sizeof($cols);$x++)
$cols[$x] = "CHANGE `".$cols[$x]['Field']."` `".$cols[$x]['Field']."` ".$cols[$x]['Type']." ".$charset_collate." NOT NULL";
$q.= implode(" , ", $cols);
$this->query($q);
}
}
}
function getCharsetCollation(){
global $wpdb;
$charset_collate = "";
//establish the current charset / collation
if (!empty($wpdb->charset))
$charset_collate = "CHARACTER SET ".$wpdb->charset;
if (!empty($wpdb->collate))
$charset_collate.= " COLLATE ".$wpdb->collate;
return $charset_collate;
}
//converts from storing certain appearance settings as columns in the database versus options in the standard template
function convertAppearanceSettings(){
//check if this is a fresh install
$q = "SHOW TABLES LIKE '".$this->formsTable."'";
if($this->query($q) == 0) return false;
//check if the old columns exist; if not, no need to do anything
$q = "SHOW COLUMNS FROM `".$this->formsTable."`";
$results = $this->get_results($q);
$found = false;
foreach ( $results as $row ){
if($row['Field'] == 'labels_on_top')
$found = true;
}
if(!$found) return false;
$q = "ALTER TABLE `".$this->formsTable."` ADD `template_values` TEXT NOT NULL ";
$this->query($q);
$q = "SELECT * FROM `".$this->formsTable."`";
$results = $this->get_results($q);
$forms = array();
foreach ( $results as $row ){
$forms[] = $row;
}
foreach($forms as $form){
$values = array( 'showFormTitle' => ($form['show_title']==1?"true":"false"),
'showBorder' => ($form['show_border']==1?"true":"false"),
'labelPosition' => ($form['labels_on_top']==1?"top":"left"),
'labelWidth' => $form['label_width']
);
$q = "UPDATE `".$this->formsTable."` SET `template_values` = '".addslashes(serialize($values))."' WHERE `ID` = '".$form['ID']."'";
$this->query($q);
}
$q = "ALTER TABLE `".$this->formsTable."`
DROP `labels_on_top`,
DROP `show_title`,
DROP `show_border`,
DROP `label_width`;";
$this->query($q);
}
//fix data tables from prior versions.
function updateDataTables(){
$q = "SELECT `ID`, `data_table` FROM `".$this->formsTable."` WHERE `ID` > 0";
$dataTables = array();
$results = $this->get_results($q);
foreach ( $results as $row ){
$dataTables[] = $row['data_table'];
}
foreach($dataTables as $dataTable){
$q = "SHOW COLUMNS FROM `".$dataTable."`";
$found = false;
$postIDfound = false;
$uniqueIDfound = false;
$parentPostFound = false;
$results = $this->get_results( $q );
foreach ( $results as $row ){
if($row['Field'] == 'user_ip')
$found = true;
if($row['Field'] == 'post_id')
$postIDfound = true;
if($row['Field'] == 'unique_id')
$uniqueIDfound = true;
if($row['Field'] == 'parent_post_id')
$parentPostFound = true;
}
if(!$found){
$q = "ALTER TABLE `".$dataTable."` ADD `user_ip` VARCHAR( 64 ) DEFAULT '' NOT NULL";
$this->query($q);
}
if(!$postIDfound){
$q = "ALTER TABLE `".$dataTable."` ADD `post_id` INT DEFAULT '0' NOT NULL";
$this->query($q);
}
if(!$uniqueIDfound){
$q = "ALTER TABLE `".$dataTable."` ADD `unique_id` VARCHAR( 32 ) DEFAULT '' NOT NULL";
$this->query($q);
$q = "ALTER TABLE `".$dataTable."` ADD INDEX (`unique_id`)";
$this->query($q);
}
if(!$parentPostFound){
$q = "ALTER TABLE `".$dataTable."` ADD `parent_post_id` INT DEFAULT '0' NOT NULL";
$this->query($q);
}
//now add unique IDs if none exist
$q = "SELECT COUNT(*) as `count` FROM `".$dataTable."`";
$row = $this->get_row($q);
$count = $row['count'];
for($x=0; $x<$count; $x++){
$q = "UPDATE `".$dataTable."` SET `unique_id` = '".uniqid()."' WHERE `unique_id` = '' LIMIT 1";
$this->query($q);
}
}
}
function fixTemplatesTableModified(){
$q = "SHOW COLUMNS FROM `".$this->templatesTable."`";
$results = $this->get_results($q);
foreach ( $results as $row ){
if($row['Field'] == 'modified' && strpos(strtolower($row['Type']), 'bigint') !== false){
$q = "ALTER TABLE `".$this->templatesTable."` CHANGE `modified` `modified` BIGINT NOT NULL ";
$this->query($q);
}
}
}
function fixDBTypeBug(){
$q = "SELECT `unique_name`, `db_type` FROM `".$this->itemsTable."`";
$results = $this->get_results($q);
foreach ( $results as $row ){
$dbType = $row['db_type'];
if(trim($dbType) != "NONE"){
$q = "UPDATE `".$this->itemsTable."` SET `db_type` = 'DATA' WHERE `unique_name` = '".$row['unique_name']."'";
$this->query($q);
}
}
}
function fixDateValidator(){
$count = $this->getGlobalSetting('text_validator_count');
$val = $this->getGlobalSetting('text_validator_3');
if($val['regexp'] == '/^([0-9]{1,2}[/]){2}([0-9]{2}|[0-9]{4})$/'){
$val['regexp'] = '/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/';
$this->setGlobalSetting('text_validator_3', $val);
}
if($val['regexp'] == '/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/.'){
$val['regexp'] = '/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/';
$this->setGlobalSetting('text_validator_3', $val);
}
}
function fixFormEmailOptions(){
if ( version_compare( get_option('fm-version'), '1.6.16', '<' ) ){
$q = "UPDATE `".$this->formsTable."` SET
`email_subject` = '".$this->globalSettings['email_subject']."',
`email_from` = '".$this->globalSettings['email_from']."'
WHERE `ID` > 0";
$this->query($q);
}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
function removeFormManager(){
$q = "SHOW TABLES LIKE '{$this->formsTable}'";
$res = $this->query($q);
if($res>0){
$q = "SELECT `data_table`, `ID` FROM `{$this->formsTable}`";
$results = $this->get_results($q);
foreach ( $results as $row ){
if($row['data_table'] != ""){
$q = "SHOW TABLES LIKE '".$row['data_table']."'";
if($this->query($q) > 0){
$q="DROP TABLE IF EXISTS `".$row['data_table']."`";
$this->query($q);
}
}
delete_option('fm-ds-'.$row['ID']);
}
}
$q = "DROP TABLE IF EXISTS `{$this->formsTable}`";
$this->query($q);
$q = "DROP TABLE IF EXISTS `{$this->itemsTable}`";
$this->query($q);
$q = "DROP TABLE IF EXISTS `{$this->settingsTable}`";
$this->query($q);
$q = "DROP TABLE IF EXISTS `{$this->templatesTable}`";
$this->query($q);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Templates
function storeTemplate($filename, $title, $content, $modified){
$this->removeTemplate($filename);
$q = "INSERT INTO `".$this->templatesTable."` SET ".
"`title` = '".addslashes($title)."', ".
"`filename` = '".addslashes($filename)."', ".
"`content` = '".addslashes($content)."', ".
"`modified` = '".addslashes($modified)."'";
$this->query($q);
}
function getTemplate($filename, $content = true){
if($content)
$q = "SELECT * FROM `".$this->templatesTable."` WHERE `filename` = '".$filename."'";
else
$q = "SELECT `title`, `filename`, `status`, `modified` FROM `".$this->templatesTable."` WHERE `filename` = '".$filename."'";
return $this->get_row($q);
}
function getTemplateList(){
$q = "SELECT `title`, `filename`, `modified` FROM `".$this->templatesTable."`";
$results = $this->get_results($q);
$list = array();
foreach ( $results as $row ){
$list[$row['filename']] = $row;
}
return $list;
}
function removeTemplate($filename){
$q = "DELETE FROM `".$this->templatesTable."` WHERE `filename` = '".$filename."'";
$this->query($q);
}
function flushTemplates(){
$q = "TRUNCATE TABLE `".$this->templatesTable."`";
$this->query($q);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Form Settings
public function getTextValidators(){
$arr = array();
$count = $this->getGlobalSetting('text_validator_count');
for($x=0;$x<$count;$x++){
// getGlobalSetting automatically deserializes if possible
$val = $this->getGlobalSetting('text_validator_'.$x);
$arr[$val['name']] = $val;
}
return $arr;
}
public function setTextValidators($validatorList){
$x=0;
foreach($validatorList as $validator)
$this->setGlobalSetting('text_validator_'.$x++, $validator, true);
$this->setGlobalSetting('text_validator_count', sizeof($validatorList));
}
public function setFormSettingsDefaults($opt){
foreach($this->formSettingsKeys as $k=>$v){
if(array_key_exists($k, $opt)) $this->formSettingsKeys[$k] = $opt[$k];
}
}
function initFormsTable(){
//see if a settings row exists
$q = "SELECT * FROM `".$this->formsTable."` WHERE `ID` < 0";
$res = $this->query($q);
if($res == 0){
$this->query( $this->getDefaultSettingsQuery() );
}
}
function initSettingsTable(){
foreach($this->globalSettings as $k=>$v){
$this->setGlobalSetting($k, $v, false);
}
//Add any default validators that aren't in the database
$validators = $this->getTextValidators();
for($x=0;$x<$this->globalSettings['text_validator_count'];$x++){
$name = $this->globalSettings['text_validator_'.$x]['name'];
if(!isset($validators[$name]))
$validators[$name] = $this->globalSettings['text_validator_'.$x];
}
$this->setTextValidators($validators);
}
//returns true if something was written, false otherwise.
// $overwrite : overwrite the old setting, if one exists.
function setGlobalSetting($settingName, $settingValue, $overwrite = true){
$val = $this->getGlobalSetting($settingName);
if(is_array($settingValue))
$settingValue = addslashes(serialize($settingValue));
else
$settingValue = addslashes($settingValue);
if($val === false){
$q = "INSERT INTO `".$this->settingsTable."` SET `setting_name` = '{$settingName}', `setting_value` = '{$settingValue}'";
$this->query($q);
return true;
}
else if($overwrite){
$q = "UPDATE `".$this->settingsTable."` SET `setting_value` = '{$settingValue}' WHERE `setting_name` = '{$settingName}'";
$this->query($q);
return true;
}
return false;
}
function getGlobalSetting($settingName){
$q = "SELECT `setting_value` FROM `".$this->settingsTable."` WHERE `setting_name` = '".$settingName."'";
$row = $this->get_row($q);
if($row === null) return false;
if(is_serialized($row['setting_value']))
return unserialize($row['setting_value']);
return $row['setting_value'];
}
function getGlobalSettings(){
$q = "SELECT * FROM `".$this->settingsTable."`";
$vals = array();
$results = $this->get_results($q);
foreach ( $results as $row ){
if(is_serialized($row['setting_value']))
$row['setting_value'] = unserialize($row['setting_value']);
$vals[$row['setting_name']] = $row['setting_value'];
}
return $vals;
}
//generate the default form settings query
function getDefaultSettingsQuery(){
$q = "INSERT INTO `".$this->formsTable."` SET `ID` = '-1' ";
foreach($this->formSettingsKeys as $setting=>$value)
$q.=", `{$setting}` = '{$value}'";
return $q;
}
// Get the default settings row
function getSettings(){
$formSettingsRow = $this->formSettingsKeys;
$settingsTableData = $this->getGlobalSettings();
foreach($formSettingsRow as $k=>$v){
if(isset($settingsTableData[$k]))
$formSettingsRow[$k] = $settingsTableData[$k];
}
return $formSettingsRow;
}
// Get a particular setting
function getSetting($settingName){
$val = $this->getGlobalSetting($settingName);
if($val !== false) return $val;
$q = "SELECT `".$settingName."` FROM `".$this->formsTable."` WHERE `ID` < 0";
$row = $this->get_row($q);
return $row[$settingName];
}
// Get a new unique form (integer) ID
function getUniqueFormID(){
// God only knows why I chose to do this... not trusting autoincrement? why????
$q = "SELECT `ID` FROM `".$this->formsTable."` WHERE `ID` < 0";
$row = $this->get_row($q);
$intID = (int)$row['ID'];
$nextID = $intID - 1;
$q = "UPDATE `".$this->formsTable."` SET `ID` = '".$nextID."' WHERE `ID` = '".$intID."'";
$this->query($q);
return $intID*(-1);
}
function getUniqueItemID($type){
return uniqid($type."-");
}
function getDataPageSettings($formID){
$dataPageSettings = get_option('fm-ds-'.$formID);
$settingsDefaults = array(
'hide' => array(),
'noedit' => array(),
'nosummary' => array(),
'date' => array( 'range' => 'all' ),
'showoptions' => 'no',
'search' => array(),
'results' => array(),
);
$flag = false;
if(!is_array($dataPageSettings)){
$dataPageSettings = $settingsDefaults;
$flag = true;
}
else
foreach($settingsDefaults as $k=>$v)
if(!isset($dataPageSettings[$k])){
$dataPageSettings[$k] = $v;
$flag = true;
}
if($flag)
update_option('fm-ds-'.$formID, $dataPageSettings);
return $dataPageSettings;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Forms
//////////////////////////////////////////////////////////////////
//Submission data
function isForm($formID){
$q = "SELECT `ID` FROM `{$this->formsTable}` WHERE `ID` = '{$formID}'";
return ( $this->query($q) > 0 );
}
function processPost($formID, $extraInfo = NULL, $overwrite = false, $ignoreTypes = NULL, $uniqueNames = NULL){
global $fm_controls;
global $msg;
$this->lastPostFailed = false;
$formInfo = $this->getForm($formID, 0);
$metaItems = $this->getFormItems($formID, 1);
$formInfo['items'] = array_merge( $formInfo['items'], $metaItems );
$dataTable = $this->getDataTableName($formID);
if ( $this-> submissionIDExists( $extraInfo['unique_id'], $dataTable ) )
return false;
$postData = $this->getProcessPost($formInfo, $ignoreTypes, $uniqueNames);
if($extraInfo != null && is_array($extraInfo) && sizeof($extraInfo)>0)
$postData = array_merge($postData, $extraInfo);
//add blanks for non-existent fields
foreach($formInfo['items'] as $item){
if(!isset($postData[$item['unique_name']]) && $item['db_type'] != "NONE")
$postData[$item['unique_name']] = "";
}
if($this->lastPostFailed === false){
if($overwrite){
$q = "DELETE FROM `{$dataTable}` WHERE `user` = '".$postData['user']."'";
$this->query($q);
}
if($this->insertSubmissionData($formID, $dataTable, $postData) === false) {
$this->lastPostFailed = true;
$this->setErrorMessage( "Insertion failed" );
}
}
return $postData;
}
function getProcessPost($formInfo, $ignoreTypes = NULL, $uniqueNames = NULL){
global $fm_controls;
$postData = array();
foreach($formInfo['items'] as $item){
if($ignoreTypes === NULL || !in_array($item['type'], $ignoreTypes) ){
if($uniqueNames === NULL)
$uniqueName = $item['unique_name'];
else
$uniqueName = $uniqueNames[$item['unique_name']];
$processed = $fm_controls[$item['type']]->processPost($uniqueName, $item);
if($processed === false) {
$this->lastPostFailed = true;
$name = $item['nickname'] != "" ? $item['nickname'] : $item['unique_name'];
}
//check if the item is a data column AFTER processing; it might be a recatpcha or something like that
if($processed !== NULL && $this->isDataCol($item['unique_name']))
$postData[$item['unique_name']] = $processed;
}
}
return $postData;
}
function processFailed(){
return $this->lastPostFailed;
}
function setErrorMessage($message, $for = ""){
$this->lastErrorMessage .= $message;
$this->lastUniqueName = $for;
}
function getErrorMessage(){
return $this->lastErrorMessage;
}
function getErrorUniqueName(){
return $this->lastUniqueName;
}
function submissionIDExists( $uniqueID, $dataTable ) {
$q = "SELECT `unique_id` FROM `{$dataTable}` WHERE `unique_id` = '".$uniqueID."'";
return ( $this->query($q) > 0 );
}
function insertSubmissionData($formID, $dataTable, &$postData){
$q = "INSERT INTO `{$dataTable}` SET ";
$arr = array();
$postData['timestamp'] = fm_get_time();
foreach($postData as $k=>$v)
$arr[] = "`{$k}` = '".$v."'";
$q .= implode(",",$arr);
$this->query($q);
}
function getFormSubmissionDataCSV($formID, $query, $ignoreFields = NULL){
global $fm_controls;
if($ignoreFields === NULL){
$ignoreFields = array('post_id', 'unique_id');
}
$baseFields = array('timestamp' => 'Timestamp',
'user' => 'User',
'user_ip' => 'IP Address',
'post_id' => 'Post ID',
'unique_id' => 'Unique Identifier',
);
$formInfo = $this->getForm($formID);
$metaFields = $this->getFormItems($formID, 1);
$formInfo['items'] = array_merge($formInfo['items'], $metaFields);
//remove fields that need to be ignored
foreach($baseFields as $k=>$f){
if(in_array($k, $ignoreFields)) unset($baseFields[$k]);
}
foreach($formInfo['items'] as $k=>$item){
if(in_array($item['unique_name'], $ignoreFields)) unset($formInfo['items'][$k]);
}
//remove fields that are not in the result
$results = $this->get_results($query);
$firstRow = reset( $results );
foreach($baseFields as $k=>$f){
if(!isset($firstRow[$k])) unset($baseFields[$k]);
}
foreach($formInfo['items'] as $k=>$item){
if(!isset($firstRow[$item['unique_name']])) unset($formInfo['items'][$k]);