-
Notifications
You must be signed in to change notification settings - Fork 0
/
_validation.php
1344 lines (1184 loc) · 47.7 KB
/
_validation.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
/*
File: _validation
This library holds form submission data and validation messaging along with
a host of form handling and validation functions.
Usage:
: require_once('/path/to/_validation.php');
Copyright:
Sunny Walker, University of Hawaii at Hilo, 2006-2007
<http://hilo.hawaii.edu/>
License:
MIT
A Note On Field Lists:
Various functions throughout this library accept a mixed format for a list of fields.
When so indicated, this list of fields can be in any of the following formats:
array - An array of field names: array('first_name','last_name','email').
comma string - A comma-delimited list of field names: 'first_name, last_name, email'.
single name - A single field name: 'first_name'.
blank - In some cases like <buildInsertSQL> and <buildUpdateSQL>, a blank field name
list will use *all* values from the global <form> array.
*/
////////////////////////////////////////
// Group: Variables
////////////////////////////////////////
/*
Variable: validation
The array which holds all the errors generated by <validateNotEmpty> and
<validateNotSpam> for specified fields, indexed on field names.
Default is an empty array.
*/
$validation = array();
/*
Variable: form
The an array which holds all of the "current" form data as filled by <post2Form>,
<resetFields>, <rs2Form> and $form['field']='value'.
Default is an empty array.
*/
$form = array();
/*
Variable: tiger_stripe
The boolean value containing the next state for <tigerStripe>.
Default is false.
*/
$tiger_stripe = false;
/*
Variable: validation_error_icon
This is the path to the icon which is printed when displaying validation errors next to fields (by <checkValidation>).
The icon size is preset to 16x16.
Default is "/images/silk/error.png".
*/
$validation_error_icon = '/images/silk/error.png';
////////////////////////////////////////
// Group: Data Functions
////////////////////////////////////////
/*
Function: buildInsertSQL
Create an INSERT INTO sql statement based on fields and values in <form>. Field types are "guessed" based on the name of the field.
Parameters:
table_name - Name of the database table to insert into.
fields - List of fields to grab from the global <form> array. This can be an array of field names, a comma-separated string, a single field as a string, or, if blank, all fields in the <form> array.
Returns:
string
See Also:
<guessFieldType>
*/
function buildInsertSQL($table_name, $fields='') {
global $form;
$insertSQL = "INSERT INTO $table_name";
//turn the field names into an array
if (is_array($fields)) {
$field_list = $fields;
} elseif (strpos($fields,',')!==false) {
$field_list = explode(',', $fields);
} elseif ($fields!='') {
$field_list = array($fields); //only one field, so turn it into an array
} else {
$field_list = array_keys($form); //just grab everything from $form
}
//now add the keys and values to the statement
$insertSQL .= ' ('.implode(', ', $field_list).') VALUES (';
$inserts = array();
foreach($field_list as $key) {
$key = trim($key);
$inserts[] = quoteF($key, guessFieldType($key));
}
$insertSQL .= implode(', ', $inserts);
$insertSQL .= ')';
return $insertSQL;
} //buildInsertSQL()
/*
Function: buildUpdateSQL
Create an UPDATE sql statement based on fields and values in <form>. Field types are "guessed" based on the name of the field.
Parameters:
table_name - Name of the database table to insert into.
update_key - Name of the key field to update.
update_id - Value of the key field to update.
fields - List of fields to grab from the global <form> array. This can be an array of field names, a comma-separated string, a single field as a string, or, if blank, all fields in the <form> array.
Returns:
string
See Also:
<guessFieldType>
*/
function buildUpdateSQL($table_name, $update_key, $update_id, $fields='') {
global $form;
$updateSQL = "UPDATE $table_name SET ";
//turn the field names into an array
if (is_array($fields)) {
$field_list = $fields;
} elseif (strpos($fields,',')!==false) {
$field_list = explode(',', $fields);
} elseif ($fields!='') {
$field_list = array($fields); //only one field, so turn it into an array
} else {
$field_list = array_keys($form); //just grab everything from $form
}
//now add the keys and values to the statement
$updates = array();
foreach($field_list as $key) {
$key = trim($key);
$updates[] = $key.'='.quoteF($key, guessFieldType($key));
}
$updateSQL .= implode(', ', $updates);
//append the update primary key
$updateSQL .= ' WHERE '.$update_key.'='.quote($update_id, guessFieldType($update_key));
return $updateSQL;
} //buildUpdateSQL()
/*
Function: isErrors
Return true or false if the validation array has errors in it, as put by <validateNotEmpty>.
Returns:
boolean
Example:
(start code)
<?php
if (isErrors()) {
setNotice('There were errors with your submission.<br />'.implode('<br />',$validation));
} else {
//no validation errors, so continue with the form processing
}
?>
(end)
See Also:
<setNotice>
*/
function isErrors() { global $validation; return count($validation)>0; }
/*
Function: post2Form
Gather $_POST data into <form> array on variables as indexes.
Parameters:
field_names - List of fields (array, comma-delimited list, single field name).
type - Type of data in field (see Data Types below).
date_format - Fields of type='date' are converted into the date_format format if not blank. Uses PHP's date() function formatting.
Data Types:
- array (for use with checkboxes or multi-selects)
- int
- posint (int or null if the value is less than 1)
- float
- float2 (2-decimal float)
- date (with format specified by date_format)
- year
*/
function post2Form($field_names, $type='text', $date_format='m/d/Y') {
global $form;
if (is_array($field_names)) {
//field_names is already an array
foreach($field_names as $name) post2Form($name, $type, $date_format);
} elseif (strpos($field_names,',')!==false) {
//field_names is comma-delimited
$field_names = explode(',',$field_names);
foreach($field_names as $name) post2Form(trim($name), $type, $date_format);
} elseif ($field_names!='') {
//assume field_names is one field
switch ($type) {
case 'array':
if (is_array($_POST[$field_names])) $form[$field_names]=$_POST[$field_names];
elseif ($_POST[$field_names]!='') $form[$field_names]=array($_POST[$field_names]);
else $form[$field_names]=array();
array_walk($form[$field_names], 'arrayMod', array('action'=>'trim'));
break;
case 'int': $form[$field_names] = intval($_POST[$field_names]); break;
case 'posint':
$form[$field_names] = intval($_POST[$field_names]);
if ($form[$field_names]<1) $form[$field_names] = NULL;
break;
case 'float': $form[$field_names] = floatval($_POST[$field_names]); break;
case 'float2': $form[$field_names] = number_format(floatval($_POST[$field_names]),2); break;
case 'date': $form[$field_names] = $_POST[$field_names]!=''?date($date_format, safeStrToTime($_POST[$field_names])):''; break;
case 'year': $form[$field_names] = intval($_POST[$field_names]>0)?intval($_POST[$field_names]):''; break;
case 'time': $form[$field_names] = $_POST[$field_names]!=''?date('g:i a', strtotime($_POST[$field_names])):''; break;
default: $form[$field_names] = trim($_POST[$field_names]);
}
}
} //post2Form()
/*
Function: resetFields
Set data in the global <form> array to the new_value with names as field name
indexes in the array.
Parameters:
field_names - List of fields (array, comma-delimited list, single field name)
new_value - The value to (re)set the field(s).
type - Data type to convert the field value (see Data Types below).
date_format - Fields of type='date' are converted into the date_format format if not blank. Uses PHP's date() function formatting.
Data Types:
- array (for use with checkboxes or multi-selects)
- int
- posint (int or null if the value is less than 1)
- float
- float2 (2 decimal place float)
- date (with format specified by date_format)
- year
Example:
(start code)
<?php
if (!isErrors()) {
$insertSQL = buildInsertSQL('contacts','first_name,last_name,email');
//run the insert query
setNotice(htmlspecialchars("$first_name $last_name has been added."));
resetFields('first_name,last_name,email'); //blank out the data input
}
(end)
*/
function resetFields($field_names, $new_value='', $type='text', $date_format='m/d/Y') {
global $form;
if (is_array($field_names)) {
//field_names is already an array
foreach($field_names as $name) resetFields($name, $new_value, $type, $date_format);
} elseif (strpos($field_names,',')!==false) {
//field_names is comma-delimited
$field_names = explode(',',$field_names);
foreach($field_names as $name) resetFields(trim($name), $new_value, $type, $date_format);
} elseif ($field_names!='') {
//assume field_names is one field
switch ($type) {
case 'array':
if (is_array($new_value)) $form[$field_names]=$new_value;
elseif ($new_value!='') $form[$field_names]=array($new_value);
else $form[$field_names]=array();
array_walk($form[$field_names], 'arrayMod', array('action'=>'trim'));
break;
case 'int': $form[$field_names] = intval($new_value); break;
case 'posint':
$form[$field_names] = intval($new_value);
if ($form[$field_names]<1) $form[$field_names] = NULL;
break;
case 'float': $form[$field_names] = floatval($new_value); break;
case 'float2': $form[$field_names] = number_format(floatval($new_value),2); break;
case 'date': $form[$field_names] = $new_value!=''?date($date_format, safeStrToTime($new_value)):''; break;
case 'year': $form[$field_names] = intval($new_value>0)?intval($new_value):''; break;
default: $form[$field_names] = trim($new_value);
}
}
} //resetFields()
/*
Function: rs2Form
Gather data from the row_rs recordset row into the global <form> array
based on field names as indexes.
Parameters:
field_names - List of fields (array, comma-delimited list, single field name)
row_rs - The recordset row to extract the data from.
type - The data type (see Data Types below)
date_format - Fields of type='date' are converted into the date_format format if not blank. Uses PHP's date() function formatting.
Data Types:
- date (with format specified by date_format)
- float
- float2 (2-decimal float)
- int
- posint (int or null if the value is less than 1)
- text
- year
*/
function rs2Form($field_names, $row_rs, $type='text', $date_format='m/d/Y') {
global $form;
if (is_array($field_names)) {
//field_names is already an array
foreach($field_names as $name) rs2Form($name, $row_rs, $type, $date_format);
} elseif (strpos($field_names,',')!==false) {
//field_names is comma-delimited
$field_names = explode(',',$field_names);
foreach($field_names as $name) rs2Form(trim($name), $row_rs, $type, $date_format);
} elseif ($field_names!='') {
//assume field_names is one field
switch ($type) {
case 'int': $form[$field_names] = intval($row_rs[$field_names]); break;
case 'posint':
$form[$field_names] = intval($row_rs[$field_names]);
if ($form[$field_names]<1) $form[$field_names] = NULL;
break;
case 'float': $form[$field_names] = floatval($row_rs[$field_names]); break;
case 'float2': $form[$field_names] = number_format(floatval($row_rs[$field_names]),2); break;
case 'date': $form[$field_names] = $row_rs[$field_names]!=''?date($date_format, safeStrToTime($row_rs[$field_names])):''; break;
case 'year': $form[$field_names] = intval($row_rs[$field_names]>0)?intval($row_rs[$field_names]):''; break;
case 'time': $form[$field_names] = $row_rs[$field_names]!=''?date('g:i a', strtotime($row_rs[$field_names])):''; break;
default: $form[$field_names] = trim($row_rs[$field_names]);
}
}
} //rs2Form()
/*
Function: safeStrToTime
Function similar to PHP's strtotime() but supports dates prior to Jan 1, 1970 (for PHP<5.1.0).
Parameters:
date_string - The date to convert into unixtime.
Returns:
Unixtime integer.
Used By:
- <post2Form>
- <quote>
- <resetFields>
- <rs2Form>
*/
function safeStrToTime($date_string) {
if (version_compare(PHP_VERSION,'5.1.0','>=')) return strtotime($date_string); //5.1.0+ handles pre-1970 dates
$base_time = 0;
if (preg_match ('/19(\d\d)/', $date_string, $m) && ($m[1] < 70)) {
$date_string = preg_replace ('/19\d\d/', 1900 + $m[1]+68, $date_string);
$base_time = 0x80000000 + 1570448; //turn the value negative
}
return $base_time + strtotime($date_string);
} //safeStrToTime()
/*
Function: setValidationError
Fill <validation> array with the specified error. This should be used only in cases where <validateNotEmpty> and <validateNotSpam> are not appropriate.
If a validation error already exists for that field, the message will be appended rather than replaced.
Parameters:
field_names - List of fields (array, comma-delimited list, single field name).
error_message - Validation error message.
Special Codes:
See <filterErrorMessage> for use of the special codes:
- <!FIELD_NAME!>
- <!#some message#>
Examples:
(start code)
<?php
if ($form['password']!=$form['retyped_password']) setValidationError('password,retyped_password','The <!#new password#> and the <!#retyped password#> did not match.');
if (mysql_num_rows($rsDupe)>0) setValidationError('username','<!#Username#> '.htmlspecialchars($form['username']).' is already in use.');
?>
(end)
*/
function setValidationError($field_names, $error_message) {
global $form, $validation;
if (is_array($field_names)) {
//field_names is already an array
foreach($field_names as $name) setValidationError($name, $error_message);
} elseif (strpos($field_names, ',')!==false) {
//field_names is comma-delimited
$field_names = explode(',', $field_names);
foreach($field_names as $name) setValidationError(trim($name), $error_message);
} elseif ($field_names!='') {
//assume field_names is one field
$validation[$field_names] = (isset($validation[$field_names])?' ':'').filterErrorMessage($field_names, $error_message);
}
} //setValidationError()
/*
Function: validateNotEmpty
Fill the global <validation> array with error_text of trimmed fields in the
global <form> array being empty (or less than number_less_than if an integer).
Parameters:
field_names - List of fields (array, comma-delimited list, single field name).
error_message - Message if the field does not validate based on its type.
type - Type of data to test against (see Data Types below).
number_less_than - Minimum number to validate if the type is int.
Data Types:
- int
- email (email address tested via <isValidEmail>)
- text
- password (must be >=5 characters and non-obvious like "secret" or "password")
Special Codes:
See <filterErrorMessage> for use of the special codes:
- <!FIELD_NAME!>
- <!#some message#>
Examples:
(start code)
<?php
validateNotEmpty('first_name,last_name,middle_initial','<!FIELD_NAME!> cannot be blank.');
validateNotEmpty('num_attending','Number of attending must be one or more.','int');
validateNotEmpty('email','Email address must be valid.','email');
?>
(end)
*/
function validateNotEmpty($field_names, $error_message, $type='text', $number_less_than=1) {
global $form, $validation;
if (is_array($field_names)) {
//names is already an array
foreach($field_names as $name) validateNotEmpty($name, $error_message, $type, $number_less_than);
} elseif (strpos($field_names, ',')!==false) {
//names is comma-delimited
$field_names = explode(',', $field_names);
foreach($field_names as $name) validateNotEmpty(trim($name), $error_message, $type, $number_less_than);
} elseif ($field_names!='') {
//assume the name is one field
$valid = true;
if ($type=='int') $valid = intval($form[$field_names])>=$number_less_than;
elseif ($type=='email') $valid = isValidEmail($form[$field_names]);
elseif ($type=='password') {
$tp = strtoupper($form[$field_names]);
if (strlen($form[$field_names])<5) $valid = false;
if (in_array(strtoupper($form[$field_names]),array('SECRET','PASSWORD','QWERTY','12345','ABCDE'))) $valid = false;
} else {
//all other type just test not empty
$valid = $form[$field_names]!='';
}
if (!$valid) $validation[$field_names] = filterErrorMessage($field_names, $error_message);
}
} //validateNotEmpty()
/*
Function: validateNotSpam
Fill <validation> array with any errors of fields containing spam.
Parameters:
field_names - List of fields (array, comma-delimited list, single field name).
error_message - Message if the field is spam.
Special Codes:
See <filterErrorMessage> for use of the special codes:
- <!FIELD_NAME!>
- <!#some message#>
Examples:
(start code)
<?php
validateNotSpam('first_name,last_name,middle_initial','<!FIELD_NAME!> appears to be spam.');
validateNotSpam('description','Description appears to be spam. Do not include any links.');
?>
(end)
See Also:
<isSpam>
*/
function validateNotSpam($field_names, $error_message) {
global $form, $validation;
if (is_array($field_names)) {
//field_names is already an array
foreach($field_names as $name) validateNotSpam($name, $error_message);
} elseif (strpos($field_names, ',')!==false) {
//field_names is comma-delimited
$field_names = explode(',', $field_names);
foreach($field_names as $name) validateNotSpam(trim($name), $error_message);
} elseif ($field_names!='') {
//assume field_names is one field
if (isSpam($field_names)) $validation[$field_names] = filterErrorMessage($field_names, $error_message);
}
} //validateNotSpam()
////////////////////////////////////////
// Group: Display Functions
////////////////////////////////////////
/*
Function: blankVal
Return an optional blank value if something is blank.
Parameters:
what - The value to print if not empty.
blank - The value to print if *what* is empty.
metaize - If true, filter *what* via htmlspecialchars().
Returns:
string
*/
function blankVal($what, $blank=' ', $metaize=true) { return ($what=='') ? $blank : (($metaize) ? htmlspecialchars($what) : $what); }
/*
Function: checkValidation
Print an error icon, <validation_error_icon>, if the specified field has an error in the validation array.
Parameters:
field_name - Name of the field to check for validation errors.
wrap_tag - Optional tag to wrap around the image icon or error message.
error_class - If no global <validation_error_icon> has been specified, apply this class to the printed error message.
Examples:
: <?php checkValidation('email'); ?>
: <?php checkValidation('email','abbr'); ?>
: <?php checkValidation('email','','warning'); ?>
Used By:
- <printCheckRadio>
- <printField>
- <printTextArea>
*/
function checkValidation($field_name, $wrap_tag='', $error_class='error') {
global $validation, $validation_error_icon;
if (!validatedOk($field_name)) {
if ($validation_error_icon!='') {
//if there is a global error icon
if ($wrap_tag!='') echo '<'.$wrap_tag.' title="'.htmlspecialchars(strip_tags($validation[$field_name])).'">';
echo '<img src="'.$validation_error_icon.'" alt="'.htmlspecialchars(strip_tags($validation[$field_name])).'"';
if ($wrap_tag=='') echo ' title="'.htmlspecialchars(strip_tags($validation[$field_name])).'"';
echo ' width="16" height="16" border="0" />';
if ($wrap_tag!='') echo "</$wrap_tag>";
echo ' ';
} else {
//no global error icon so just print the message
if ($error_class!='') echo '<span class="'.$error_class.'">';
echo $validation[$field_name]; //unfiltered
if ($error_class!='') echo '</span>';
}
}
} //checkValidation()
/*
Function: printCheckbox
Print the HTML for a checkbox input field with associated <label>
tag. The checkbox is checked if the value passed is also
equal to the value of the field_name in the global <form> array.
Parameters:
field_name - The name of the field to print with value from the global <form> array.
value - The value of the field, if selected.
label - The text printed in a <label> tag for selecting the checkbox/radio.
If label is omitted, the value will be used as the label.
options - Optional array of options (see below).
Options:
id - Use this id instead of the auto-generated id. (Default is empty/none.)
image - HTML for an image to display with the label. (Default is no image.)
with_validation - If true, call <checkValidation> prior to printing the input field. (Default is false.)
filter_label - Do not htmlspecialchars() the label. (Default is true.)
filter_value - Do not htmlspecialchars() the value. (Default is true.)
filter_image - Do not htmlspecialchars() the image. (Default is false.)
label_class - Attach this class to the label. (Default is no class.)
input_class - Attach this class to the input tag. (Default is no class.)
Examples:
: <p><?php printCheckbox('is_approved', 1, 'Approve this submission'); ?></p>
: <p>Which fruit do you like? (Check all that apply.)<br />
: <?php printCheckbox('fruit[]', 'Apple', '', array('with_validation'=>true)); ?><br />
: <?php printCheckbox('fruit[]', 'Orange'); ?><br />
: <?php printCheckbox('fruit[]', 'Banana'); ?></p>
*/
function printCheckbox($field_name, $value, $label='', $options=array()) {
global $form;
//options defaults
$defaults = array(
'id'=>'',
'image'=>'',
'with_validation'=>false,
'filter_label'=>true,
'filter_value'=>true,
'filter_image'=>false,
'label_class'=>'',
'input_class'=>'');
foreach ($defaults as $option_key=>$option_value) {
if (!isset($options[$option_key])) $options[$option_key] = $option_value;
}
if ($label=='') $label=$value; //if no label, use value as the label
$use_arrays = substr($field_name, -2)=='[]'; //detect whether the name is an array
$base_field_name = $use_arrays ? substr($field_name, 0, -2) : $field_name; //trim the field name if using an array
if ($options['with_validation']) checkValidation($base_field_name); //validate if asked
echo '<input';
echo ' name="'.htmlspecialchars($field_name).'"';
echo ' value="'.($options['filter_value']?htmlspecialchars($value):$value).'"';
echo ' type="checkbox"';
if ($use_arrays) $id = $options['id']!=''?$options['id']:htmlspecialchars($base_field_name.'_'.preg_replace('/[^\w\d]/','_',$value));
else $id = ($options['id']!=''?$options['id']:htmlspecialchars($field_name.'_'.preg_replace('/[^\w\d]/','_',$value)));
echo ' id="'.$id.'"';
if (($use_arrays && is_array($form[$base_field_name]) && is_array($form[$base_field_name]) && in_array($value, $form[$base_field_name])) || (!$use_arrays && $form[$field_name]==$value)) echo ' checked="checked"'; //check the box if it should be set
if ($options['input_class']!='') echo ' class="'.$options['input_class'].'"'; //add optional class
echo ' />';
if ($label!='' || $options['image']!='') {
echo ' <label for="'.$id.'"'.($options['label_class']!=''?' class="'.$options['label_class'].'"':'').'>';
echo trim(($options['filter_image']?htmlspecialchars($options['image']):$options['image']).' ');
echo ($options['filter_label']?htmlspecialchars($label):$label);
echo '</label>';
}
} //printCheckbox()
/*
Function: printField
Filter the value of the field name in the global <form> array and print it as HTML.
If size is specified larger than zero, printField() prints the whole input
field code, including validation markers via checkValidation(name) if
with_validation is true.
When the specified field type is "password", the value (password) is never printed.
Parameters:
field_name - The name and or value of the field to print from the global <form> array.
size - Size of the input field. If zero, only the field value will be printed. (Default is 0.)
max_size - Max length of the input field (only if size>0). (Default is 255.)
type - Convert data to specified type (see Data Types below).
This is normally done via <post2Form>, <resetFields>, and <rs2Form>. (Default is text.)
with_validation - If true, and size>0, call <checkValidation> prior to
printing the input field. (Default is true.)
with_validation (array) - If an array is passed, with_validation acts like the options array
of <printCheckbox>. See Options below.
Data Types:
- float2 (2-decimal float)
- password (no value is ever printed)
- text (no conversion)
Options (with_validation array):
id - Use this id instead of the auto-generated id. (Default is empty/none.)
with_class - Include this class when printing the field. (Default is empty/none.)
with_validation - If true, and size>0, call <checkValidation> prior to
printing the input field. (Default is true.)
without_valid_class - If printing the field with validation and the field passes
validation, set this option to true to stop the "valid" class from
being printed with the field. (Default is false.)
Simple Example:
Assuming...
: <?php $form['Username']='theuser'; ?>
Use...
: <input type="text" name="Username" id="Username" value="<?php printField('Username'); ?>" />
Outputs...
: <input type="text" name="Username" id="Username" value="theuser" />
Expanded Example:
Assuming...
: <?php $form['Username']='theuser'; ?>
Use...
: <?php printField('Username',20,50); ?>
Outputs...
: <input type="text" name="Username" id="Username" value="theuser" size="20" maxlength="50" />
Expanded with Error Example:
Assuming...
: <?php
: $form['Username']='';
: validateNotEmpty('Username','Username cannot be blank.');
: ?>
Use...
: <?php printField('Username',20,50); ?>
Outputs...
: <img ..[img code].. title="Username cannot be empty." />
: <input type="text" name="Username" id="Username" value="theuser" size="20" maxlength="50" class="error" />
Example call with options:
Using...
: <?php printField('Username',20,50,array('with_validation'=>false, 'with_class'=>'textinput')); ?>
Outputs...
: <input type="text" name="Username" id="Username" value="theuser" size="20" maxlength="50" class="textinput" />
*/
function printField($field_name, $size=0, $max_size=255, $type='text', $with_validation=true) {
global $form;
$value = $form[$field_name];
//options defaults
$defaults = array(
'id'=>'',
'with_class'=>'',
'with_validation'=>true,
'without_valid_class'=>false,
'strip_slashes'=>true);
if (is_array($with_validation)) { //new method with options array
foreach ($defaults as $option_key=>$option_value) {
if (!isset($with_validation[$option_key])) $options[$option_key] = $option_value;
else $options[$option_key] = $with_validation[$option_key];
}
} else { //old method with just with_validation parameter
foreach ($defaults as $option_key=>$option_value) {
$options[$option_key] = $option_value;
}
$options['with_validation']=$with_validation;
}
switch ($type) {
//case 'int': $value=intval($value); break;
//case 'float': $value=floatval($value); break;
case 'float2': $value=number_format($value,2); break;
}
if ($size>0) {
if ($options['with_validation']) checkValidation($field_name);
echo '<input';
echo ' type="'.$type.'"';
echo ' name="'.htmlspecialchars($field_name).'"';
echo ' id="'.($options['id']!=''?$options['id']:htmlspecialchars($field_name)).'"';
echo ' value="'.($type!='password'?htmlspecialchars($options['strip_slashes']?stripslashes($value):$value):'').'"';
echo ' size="'.$size.'"';
if ($max_size<255) echo ' maxlength="'.$max_size.'"';
$classes = array();
if ($options['with_class']!='') $classes[] = $options['with_class'];
if ($options['with_validation'] && !isValidatedOk($field_name)) $classes[] = 'error';
elseif ($options['with_validation'] && !$options['without_valid_class'] && $form[$field_name]!='' && isset($_POST['Submit'])) $classes[] = 'valid';
if (count($classes)>0) echo ' class="'.implode(' ',$classes).'"';
echo ' />';
} elseif ($type=='hidden') {
echo '<input type="hidden" name="'.htmlspecialchars($field_name).'" id="'.($options['id']!=''?$options['id']:htmlspecialchars($field_name)).'" value="'.htmlspecialchars($options['strip_slashes']?stripslashes($value):$value).'" />';
} elseif ($type!='password') {
echo htmlspecialchars($value);
}
} //printField()
/*
Function: printRadio
Print the HTML for a radio input field with associated <label>
tag. The radio selected if the value passed is also
equal to the value of the field_name in the global <form> array.
Parameters:
field_name - The name of the field to print with value from the global <form> array.
value - The value of the field, if selected.
label - The text printed in a <label> tag for selecting the checkbox/radio.
If label is omitted, the value will be used as the label.
options - Optional array of options (see below)
Options:
id - Use this id instead of the auto-generated id. (Default is empty/none.)
image - HTML for an image to display with the label. (Default is no image.)
with_validation - If true, call <checkValidation> prior to printing the input field. (Default is false.)
filter_label - Do not htmlspecialchars() the label. (Default is true.)
filter_value - Do not htmlspecialchars() the value. (Default is true.)
filter_image - Do not htmlspecialchars() the image. (Default is false.)
label_class - Attach this class to the label. (Default is no class.)
input_class - Attach this class to the input tag. (Default is no class.)
Examples:
: <p><label class="required">Sex:</label>
: <?php printRadio('sex','Female','',array('with_validation'=>false)); ?><br />
: <?php printRadio('sex','Male'); ?><br />
: <?php printRadio('sex','Not Disclosed'); ?></p>
*/
function printRadio($field_name, $value, $label='', $options=array()) {
global $form;
//options defaults
$defaults = array(
'id'=>'',
'image'=>'',
'with_validation'=>false,
'filter_label'=>true,
'filter_value'=>true,
'filter_image'=>false,
'label_class'=>'',
'input_class'=>'');
foreach ($defaults as $option_key=>$option_value) {
if (!isset($options[$option_key])) $options[$option_key] = $option_value;
}
if ($label=='') $label=$value; //if no label, use value as the label
if ($options['with_validation']) checkValidation($field_name); //validate if asked
echo '<input';
echo ' name="'.htmlspecialchars($field_name).'"';
echo ' value="'.($options['filter_value']?htmlspecialchars($value):$value).'"';
echo ' type="radio"';
$id = htmlspecialchars($field_name.'_'.preg_replace('/[^\w\d]/','_',$value));
echo ' id="'.$id.'"';
if ($form[$field_name]==$value) echo ' checked="checked"'; //check the radio if it should be set
if ($options['input_class']!='') echo ' class="'.$options['input_class'].'"'; //optional class
echo ' />';
if ($label!='' || $options['image']!='') {
echo ' <label for="'.$id.'"'.($options['label_class']!=''?' class="'.$options['label_class'].'"':'').'>';
echo trim(($options['filter_image']?htmlspecialchars($options['image']):$options['image']).' ');
echo ($options['filter_label']?htmlspecialchars($label):$label);
echo '</label>';
}
} //printRadio()
/*
Function: printTextArea
Filter the value of the field_name in the global <form> array and print it
as HTML wrapped in a <TEXTAREA> tag, including validation markers via
checkValidation(name,"abbr") if with_validation is true.
If cols is set zero, the "alt" class is applied to the textarea for extra
CSS formatting flexibility.
To just print the value that goes in the <TEXTAREA>, use <printField>.
Parameters:
field_name - The name of the field to print with value from the global <form> array.
rows - The height of the <TEXTAREA>, in lines. (Default is 3.)
cols - The width of the <TEXTAREA>. (Default is 0.)
with_validation - If true, also call <checkValidation> prior to printing the <TEXTAREA>.
(Default is true.)
with_validation (array) - If an array is passed, with_validation acts like the options array
of <printCheckbox>. See Options below.
Options (with_validation array):
id - Use this id instead of the auto-generated id. (Default is empty/none.)
with_class - Include this class when printing the field. (Default is empty/none.)
with_validation - If true, and size>0, call <checkValidation> prior to
printing the input field. (Default is true.)
wrap - Use this value for the wrap attribute. (Default is virtual.)
*/
function printTextArea($field_name, $rows=3, $cols=0, $with_validation=true) {
global $form;
$value = $form[$field_name];
//options defaults
$defaults = array(
'id'=>'',
'with_class'=>'',
'with_validation'=>true,
'wrap'=>'virtual',
'strip_slashes'=>true);
if (is_array($with_validation)) { //new method with options array
foreach ($defaults as $option_key=>$option_value) {
if (!isset($with_validation[$option_key])) $options[$option_key] = $option_value;
else $options[$option_key] = $with_validation[$option_key];
}
} else { //old method with just with_validation parameter
foreach ($defaults as $option_key=>$option_value) {
$options[$option_key] = $option_value;
}
$options['with_validation']=$with_validation;
}
if ($options['with_validation']) checkValidation($field_name);
echo '<textarea';
echo ' name="'.htmlspecialchars($field_name).'"';
echo ' id="'.($options['id']!=''?$options['id']:htmlspecialchars($field_name)).'"';
echo ' rows="'.$rows.'"';
if ($cols>0) echo ' cols="'.$cols.'"';
echo ' wrap="'.$options['wrap'].'"';
$classes = array();
if ($options['with_class']!='') $classes[] = $options['with_class'];
if ($cols==0) $classes[] = 'alt';
if ($with_validation && !isValidatedOk($field_name)) $classes[] = 'error';
elseif ($options['with_validation'] && $form[$field_name]!='' && isset($_POST['Submit'])) $classes[] = 'valid';
if (count($classes)>0) echo ' class="'.implode(' ',$classes).'"';
echo '>'.htmlspecialchars($options['strip_slashes']?stripslashes($value):$value).'</textarea>';
} //printTextArea()
/*
Function: quote
Wrap quotes around a value for an SQL statement and convert the data to
the appropriate type.
Parameters:
what - The value to be returned.
type - The data type to convert what into (see Data Types below).
true_value - The value to return if type is "defined" and what is not empty.
false_value - The value to return if type is "defined" and what is empty.
Data Types:
- text
- int
- posint (int or null if the value is less than 1)
- float
- date
- datetime
- year
- defined (if what is not empty, use the true_value, else use the false_value)
Returns:
string
Used By:
<quoteF>
*/
function quote($what, $type='text', $true_value='', $false_value='') {
$what = (!get_magic_quotes_gpc()) ? addslashes($what) : $what;
switch ($type) {
case 'text': $what = ($what != '') ? "'".trim($what)."'" : 'NULL'; break;
case 'int': $what = ($what!=''||$what>=0) ? intval($what) : 'NULL'; break;
case 'posint':
$what = intval($what);
if ($what<1) $what = 'NULL';
break;
case 'float': $what = ($what != '') ? "'".floatval($what)."'" : 'NULL'; break;
case 'date': $what = ($what != '') ? "'".date('Y-m-d', safeStrToTime($what))."'" : 'NULL'; break;
case 'datetime': $what = ($what != '') ? "'".date('Y-m-d H:i:s', safeStrToTime($what))."'" : 'NULL'; break;
case 'year': $what = intval($what>0) ? intval($what) : 'NULL'; break;
case 'time': $what = ($what != '') ? "'".date('H:i:s', strtotime($what))."'" : 'NULL'; break;
case 'defined': $what = ($what != '') ? $true_value : $false_value; break;
case 'password': $what = ($what != '') ? "'".md5($what)."'" : 'NULL'; break;
default: $what = ($what != '') ? "'".trim($what)."'" : 'NULL'; break;
}
return $what;
} //quote()
/*
Function: quoteF
As the <quote> function, except what is a specific name of a field in
the global <form> array.
These two statements are effectively the same:
: $output = quote($form['email']);
: $output = quoteF('email');
See Also:
<quote>
*/
function quoteF($what, $type='text', $trueVal='', $falseVal='') {
global $form;
return quote($form[$what], $type, $trueVal, $falseVal);
} //quoteF()
/*
Function: resetTigerStripe
Reset the tiger striping. Use this before subsequent sections that need to
start fresh--a second table on the same page, for example.
*/
function resetTigerStripe() { global $tiger_stripe; $tiger_stripe=false; }
/*
Function: selectIf
Print the appropriate HTML code to select a value for a select, checkbox,
or radio input type.
Parameters:
field_name - The name of the field in the <form> array.
compare_value - The value to compare to test for true.
type - The type of input field (see Select Types below).
Select Types:
select - Used for <select>.
check - Used for <input type="checkbox" />
checkbox - Used for <input type="checkbox" />
radio - Used for <input type="radio" />
Examples:
(start code)
<select name="college_id" id="college_id">
<?php do { ?>
<option value="<?php echo $row_rsColleges['id']; ?>"<?php selectIf('college_id',intval($row_rsColleges['id']),'select); ?>>
<?php echo htmlspecialchars($row_rsColleges['name']); ?>
</option>
<?php } while ($row_rsColleges = mysql_fetch_assoc($rsColleges)); ?>
</select>
<input name="is_enabled" type="checkbox" id="is_enabled" value="1"<?php selectIf('is_enabled',1,'check'); ?> />
<label for="is_enabled">Enabled</label>
(end)
Used By:
- <printCheckRadio>
*/
function selectIf($field_name, $compare_value, $type) {
global $form;
switch ($type) {
case 'select':
if ($form[$field_name]==$compare_value) echo ' selected="selected"';
break;
case 'checkbox':
case 'radio':
case 'check':
if ($form[$field_name]==$compare_value) echo ' checked="checked"';
break;
}
} //selectIf()
/*
Function: tigerStripe
This function serves as a binary switch for alternating the class of
elements like a table row.
Parameters:
return_class_only - If true, only return the class_name if at alternate.
If false, return nothing.
class_name - The name of the "alternate" class.
add_class - Class to add to the row in print mode--regardless of whether it is an alternate row or not.