-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayout.pm
More file actions
2940 lines (2531 loc) · 90.5 KB
/
Layout.pm
File metadata and controls
2940 lines (2531 loc) · 90.5 KB
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
# -*- Mode: perl; indent-tabs-mode: nil -*-
# Copyright(c) 2003-2007 Robert L. Brown. This is licensed software
# only to be used with an explicit right-to-use license from the
# copyright holder.
package Layout;
use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION);
require Exporter;
$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(
&Footer
&PulldownMenu
&doInsertFromParams
&doUpdateFromParams
&doEditTable
&doEntryForm
&doHiddenForm
&doEditForm
&doStaticValues
&doAccessDenied
&fullURL
&doMustLogin
&doHeading
&setHeadingRight
&doSingleFormElement);
@EXPORT_OK = qw(); # Symbols to export on request
use CGI qw(:standard *table *ol *ul *Tr *td escape *p *div *script);
use Param;
use Login;
use Database;
use Argcvt;
use Utility;
use DateTime;
use LeftRightWidget;
use OptionMenuWidget;
use Opening;
use Data::Dumper;
##
## This string is placed under the "Home" link at the top right of the page
##
BEGIN {
$Layout::headstr = "";
};
##
## start_form - replacement for CGI's start_form
##
my $theForm = "";
my $theStatus = "";
my $formIndex = 0;
my $validatorScript;
my $variantScript;
my %variants;
my $initializeScript;
my $NoChangesMsg = "Form status: Nothing has changed.";
##
## Form Management
##
## Typical Pattern:
##
## # for editing an existing record:
##
## print Layout::startForm();
## print Layout::doEditForm({-table=> ,
## -record=> ,
## });
## print Layout::endForm();
##
## # in the POST routine
##
## Layout::doUpdateFromParams({-table=> ,
## });
##
##
## Layout::startForm/endForm - start and end form with validation and
## status line
##
## These are to be used in conjunction with the other form routines that
## call doSingleFormElement:
## doEditForm
## doEntryForm
## doHiddenForm
##
## Returns the HTML string to put at the top of a form.
##
## The args hash is the same as CGI::start_form with these exceptions:
## -status ... generate a line that says whether or not the form has
## changed.
##
## If -name is not given, a form name will be automatically generated.
## This is needed for the validation routines.
##
sub startForm
{
my $argv = shift;
$theForm = undef;
my $dostatus = 0;
autoEscape(undef);
## if an arglist if given, scan it for the -name parameter
## and extra argument (like -status)
if ( ref($argv) eq "HASH" ) {
foreach my $k ( keys %$argv ) {
if ( $k eq "-name" ) {
$theForm = $$argv{$k};
}
if ( $k eq "-status" ) {
$dostatus = 1;
delete $$argv{$k};
}
}
}
## Generate a synthetic form name if none was given
if ( !$theForm ) {
$theForm = sprintf("form%03d", $formIndex);
$$argv{'-name'} = $theForm;
}
if ( !$$argv{'-id'} ) {
$$argv{'-id'} = $$argv{'-name'};
}
$formIndex++;
## Start the form.
## $validatorScript ... this is where the javascript validations will
## be collected
## $result ...... where the resulting HTML string is collected
## $variantScript ... where the variables for managing variants are dumped
## %variants ........ hash of variants already dumped
## $initializeScript ... javascript that is executed once on each page
## XXX finish setting up initializeScript
$validatorScript = "";
$variantScript = "";
$initializeScript = "";
my $result = "\n\n<!-- FORM $theForm -->\n\n";
$result .= CGI::start_form($argv);
## if -status given, put out the form change status field.
if ( $dostatus ) {
$result .= addStatusLine();
}
return $result;
}
sub getForm
{
return $theForm;
}
sub addStatusLine
{
$theStatus = $theForm . "_status";
return div({-id=>$theStatus}, $NoChangesMsg) . "\n";
}
sub endForm
{
my $argv = shift;
my $str = CGI::end_form($argv) . "\n";
## Dump out the Javascript validations, if any
if ( length($validatorScript) > 0 ) {
$validatorScript = "\nvar v = new Validator(\"$theForm\");\n" . $validatorScript;
$str .= CGI::script($validatorScript) . "\n";
$validatorScript = "";
}
if ( length($variantScript) > 0 ) {
$str .= CGI::script($variantScript) . "\n";
$variantScript = "";
}
## initializeScript - JavaScript for initializing the form
if ( length($initializeScript) > 0 ) {
$str .= CGI::script($initializeScript) . "\n";
$initializeScript = "";
}
$theForm = undef;
$theStatus = undef;
return $str;
}
##
## Layout::addValidation - add a form element validation to the list of validators.
##
## Call this if you are creating form elements outside of one of the
## subroutines in this package.
##
## Required input parameters:
## -column ... refers to a column in a table metadata hash.
## This can be a reference to one element in the
## columns array, or it can be a string that is the name
## of the column. If it is a string,
## then -table MUST be provided as well
## Optional input parameters:
## -table .... required if -column is a string. Ref to a table metadata hash.
## -suffix ... optional suffix for the form element name
##
## Example:
## print CGI::textfield({-name=>"a_column_name", ... });
## Layout::addValidation({-column=>"a_column_name", -table=>\%::SomeTable});
##
sub addValidation
{
$validatorScript .= formValidate(@_);
}
##
## Layout::addInitialization - add a JavaScript form element initialization to
## the list of initializers.
##
sub addInitialization
{
$initializeScript .= join("\n", @_);
}
##
## Layout::addStatusCheck - add a status check -onchange argument to
## some CGI::arg list
##
## Use this routine if you are calling CGI form routines directly.
## It will add the proper -onchange argument to the args list so that
## the status line is updated correctly
##
## Required input parameters:
## args ... ref to a hash that will be passed to a CGI:: routine
## Optional input parameters:
## default ... default value for the form element, used to detect
## a real data change
## onchange .. additional javascript for the onchange element
##
## Example:
## my $args = { -name=>"some_form_element", ... };
## Layout::addStatusCheck({-args=>$args});
##
sub addStatusCheck
{
my $argv = shift;
argcvt($argv, ["args"], ['default']);
my $args = $$argv{'args'};
if ( $$args{'-onchange'} ) {
$$args{'-onchange'} .= ";";
}
$$args{'-onchange'} .= statusCheckOnChange($argv);
}
## Generate the combined "onchange" value having what the caller provided
## and the status line update call.
sub statusCheckOnChange
{
my $argv = shift;
argcvt($argv, [], ['args', 'default']);
my $result = "";
if ( $theStatus ) {
if ( exists $$argv{'default'} ) {
my $def = defined $$argv{'default'} ? $$argv{'default'} : "";
$def =~ s/\x0A/\\n/gs;
$result = "modified1(this, '" . $def . "', '$theStatus')";
} else {
$result = "modified0(this, '$theStatus')";
}
}
return $result;
}
## Generate the combined "onchange" value having what the caller provided
## and any table/column-specific action, plus any extra caller function
sub addOnChange
{
my $argv = shift;
argcvt($argv, ['table', 'column'], ['args', 'default', 'clientonchange']);
my $args = $$argv{'args'};
my $table = $$argv{'table'};
my $column = $$argv{'column'};
my $result = "";
if ( $$argv{'clientonchange'} ) {
if ( $$args{'-onchange'} ) {
$$args{'-onchange'} .= ';';
}
$$args{'-onchange'} .= $$argv{'clientonchange'};
}
if ( $column->{'changeHook'} ) {
if ( $$args{'-onchange'} ) {
$$args{'-onchange'} .= ";";
}
$$args{'-onchange'} .= &{$column->{'changeHook'}}($argv);
}
}
##
## addVariant - add the javascript to a form element to handle being
## part of a group.
##
##
sub addVariant
{
my $argv = shift;
argcvt($argv, ['table', 'column'], ['args', 'default']);
my $args = $$argv{'args'};
my $table = $$argv{'table'};
my $result;
# The column argument could be a ref into the table metadata table or
# it could be a column string name. Convert it. if needed, to a
# table hash reference, $tcol
my $tcol = ref($$argv{'column'}) eq "HASH" ?
$$argv{'column'} :
findColumn({-table=>$$argv{'table'},
-column=>$$argv{'column'}});
# This column must be member of a group to continue
if ( !exists $$tcol{'group'} ) {
return;
}
if ( exists $$tcol{'switch'} ) {
$result = addVariantOnOff({
-table=>$table,
-column=>$tcol,
});
## XXX generate more into $variantScript if not already in %variants,
## both the array and the call to the fix routine
if ( !exists $variants{$$tcol{'column'}} ) {
$variants{$$tcol{'column'}} = 1;
$variantScript .= "var variant_$$tcol{'column'} = [";
my $sep = "";
my $group = $$table{'groups'}{$$tcol{'group'}};
foreach my $g ( @{$$group{'cases'}} ) {
$variantScript .= "$sep\n [ '$$g{'column'}',\n";
$variantScript .= " [ " . join(",", map { "'$_'" } @{$$g{'value'}}) . " ]\n";
$variantScript .= " ]";
$sep = ",";
}
$variantScript .= "\n];\n";
$variantScript .= $result;
}
} else {
$result = "";
}
if ( $result ) {
if ( $$args{'-onchange'} ) {
$$args{'-onchange'} .= ";";
} else {
$$args{'-onchange'} = " ";
}
$$args{'-onchange'} .= $result;
}
}
# returns the onchange javascript for a variant switch value
sub addVariantOnOff
{
my $argv = shift;
argcvt($argv, ['table', 'column'], ['suffix']);
my $table = $$argv{'table'};
my $suffix = exists $$argv{'suffix'} ? $$argv{'suffix'} : "";
# The column argument could be a ref into the table metadata table already
my $tcol = ref($$argv{'column'}) eq "HASH" ?
$$argv{'column'} :
findColumn({-table=>$$argv{'table'},
-column=>$$argv{'column'}});
return undef if ( !$$tcol{'switch'} );
my $group = $$table{'groups'}{$$tcol{'group'}};
## Utility::ObjDump($group);
return "fix_variant('$theForm', '$$tcol{'column'}" . $suffix . "')";
}
##
## variantDiv - wrap text (a form element) in a div that can be used to turn a form element
## on and off
##
sub variantDiv
{
my $argv = shift;
argcvt($argv, ['column'], ['suffix']);
my $suffix = $$argv{'suffix'} ? $$argv{'suffix'} : "";
my $result;
$result = start_div({
-id=>"div_$theForm" . "_$$argv{'column'}$suffix",
});
$result .= join("", @_);
$result .= end_div;
return $result;
}
##
## Footer - short page footer
##
## Arguments:
## hidelogin ... 1=>don't show login/out footer
## hidesql ..... 1=>don't show SQL debug button
## url ......... URL of this page to return to if login/out used
sub Footer
{
Database::addQueryComment("Footer");
my $argv = $_[0];
if ( ref($argv) eq "HASH" ) {
argcvt($argv, []);
shift;
} else {
$argv = 0;
}
my $return;
if ( $argv && $$argv{'url'} ) {
$return = $$argv{'url'};
} else {
$return = Utility::rootURL();
}
$return = escape($return);
my $str = "\n<!-- FOOTER -->\n\n" . br();
$str .= start_table({-border=>"0", -width=>"100%", -align=>"center", -class=>"footer"}) . "\n";
$str .= start_Tr . "\n";
$str .= td({-align=>"center", -class=>"footer"}, a({-href=>Utility::rootURL()}, "Home")) . "\n";
if ( !($argv && $$argv{'hidelogin'}) ) {
$str .= td({-align=>"center", -class=>"footer"}, "|") . "\n";
$str .= td({-align=>"center", -class=>"footer"},
Login::isLoggedIn() ? (a({-href=>"loginout.cgi?op=logout&link=" . escape(url({-base=>1}))}, "Log out:"),
" ", Login::getLoginName()) :
a({-href=>"loginout.cgi?link=$return"}, "Log in")) . "\n";
}
if ( cookie("query") ) {
$str .= td({-align=>"center", -class=>"footer"}, "|") . "\n";
$str .= td({-align=>"center", -class=>"footer"}, a({-href=>cookie("query")}, "Previous Query")) . "\n";
}
## Send feedback to the author
$str .= td({-align=>"center", -class=>"footer"}, "|") . "\n";
$str .= td({-align=>"center", -class=>"footer"},
a({-href=>"mailto:candidate-tracker\@openeye.com?subject=Candidate%20Tracker%20Feedback"},
"Send Feeback")) . "\n";
# Create the "SQL" button if configured.
if ( Param::getValueByName("show-sql") eq 'Y' && !($argv && $$argv{'hidesql'}) ) {
$str .= td({-align=>"center", -class=>"footer"}, "|") . "\n";
$str .= td({-align=>"center", -class=>"footer"}, dumpQueries()) . "\n";
}
$str .= end_Tr . "\n";
$str .= end_table . "\n";
return $str;
}
#
# PulldownMenu - return a pulldown forms menu from a column in a table
#
# Required parameters:
# -table => name of the DB table
# -column => name of the column
# Optional parameters:
# -default => Value in the list of values that is the default selected
# -null => Define this if you want a "NONE" entry added to the menu
# -onchange => JavaScript command for onchange
# -name => form element name (defaults to column name)
# -skipfilters => a named filter or a ref to an array of named filters to skip. These
# are filters defined on the *Table hash.
#
# If filters are added, another "where" clause is added that makes sure that thde default
# value is always included.
#
# If the given column is an enum type, the enum values are put into the table.
# Otherwise, it is taken to be
# XXX the pattern here of concatenating filters and ORing in the default value needs
# to migrate to OptionWidget and (maybe) LeftRight
#
sub PulldownMenu
{
my $argv = shift;
argcvt($argv, ["table", "column"],
['null', 'default', 'onchange', 'name', 'suffix', 'skipfilters','id',
'clientonchange']);
my $table = $$argv{'table'};
my $column = findColumn($argv);
my @values = ();
my $result = "";
my %labels = ();
# Utility::ObjDump($argv);
TYPE: {
$column->{'type'} eq "enum" and do {
@values = EnumsList($table->{'table'}, $column->{'column'});
foreach my $v ( @values ) {
$labels{$v} = $v;
}
last TYPE;
};
$column->{'type'} eq "bitvector" and do {
for ( my $i=0 ; $i<scalar(@{$column->{'labels'}}) ; $i++ ) {
push @values, $i;
$labels{$i} = $column->{'labels'}->[$i];
}
last TYPE;
};
# the default type is that this is a FK to another table
# apply any filter, such as eliminating inactive users
# the 'filters" entry can be a single item or an array of items; this
# is too much flexibility but is this way for backward compatibility
my $where = undef;
if ( exists $table->{'filters'} ) {
my %skipfilters;
if ( exists $argv->{'skipfilters'} ) {
foreach my $filtername ( @{$argv->{'skipfilters'}} ) {
$skipfilters{$filtername} = 1;
}
}
if ( ref($table->{'filters'}) eq "ARRAY" ) {
my $sep = "";
foreach my $fref ( @{$table->{'filters'}} ) {
next if ( exists $fref->{'name'} && exists $skipfilters{$fref->{'name'}} );
if ( exists $fref->{'activeSQL'} ) {
$where .= $sep . &{$fref->{'activeSQL'}}();
$sep = " AND ";
}
}
} else {
if ( exists $table->{'filters'}->{'activeSQL'} ) {
next if ( exists $table->{'filters'}->{'name'} && exists $skipfilters{$table->{'filters'}->{'name'}} );
$where = &{$table->{'filters'}->{'activeSQL'}}();
}
}
# If there is a default value and there are filters, then make sure that thde default
# value gets included.
if ( $$argv{'default'} && $where ) {
$where = "( $where ) OR ( id = " . SQLQuote($$argv{'default'}) . " )";
}
}
my @recs = Database::getRecordsWhere({
-table => $table,
-where => $where,
});
foreach my $rec ( @recs ) {
push @values, $$rec{'id'};
if ( $$column{'labels'} ) {
$labels{$$rec{'id'}} = &{$$column{'labels'}}($rec);
} else {
$labels{$$rec{'id'}} = $$rec{$$column{'column'}};
}
}
};
if ( $$argv{'null'} ) {
unshift @values, 0;
$labels{"0"} = $$argv{'null'};
}
my $name = $$argv{'name'} ? $$argv{'name'} : $$argv{'column'};
if ( $$argv{'suffix'} ) {
$name .= $$argv{'suffix'};
}
my %args = (
-name=>$name,
-values => \@values,
-labels => \%labels,
);
exists $$argv{'default'} and $args{'default'} = $$argv{'default'};
exists $$argv{'onchange'} and $args{'onchange'} = $$argv{'onchange'};
$$argv{'id'} and $args{'id'} = $$argv{'id'};
return popup_menu(\%args);
}
sub findColumn
{
my $argv = shift;
argcvt($argv, ['table', 'column']);
my $table = $$argv{'table'};
my $column = $$argv{'column'};
foreach my $tcol ( @{$table->{'columns'}} ) {
if ( $tcol->{'column'} eq $column ) {
return $tcol;
}
}
Utility::redError("Can't find column \"$column\" in table metadata \"$table->{'table'}\"");
return undef;
}
##
## doInsertFromParams - insert a DB row based on params
##
## Required parameters:
## table ... ref to metatable hash
## Optional parameters:
## changes ... ref to changes record that will be updated with all changes
## suffix .... add this string to the end of every form element name
## record .... ref to a hash; fill in missing values from this record;
## suffix not applied.
##
## Any param data not in the meta data table is ignored. Hence, this function will
## pull only data relevant to the given table, and insert a row in the DB for it.
## If there is any data that should be put into the DB record that is not in
## param data, put it there first with param("the_column", $the_data)
##
## XXX:this does handle encrypting password fields!
sub doInsertFromParams
{
my $argv = shift;
argcvt($argv, ["table"], ['changes','suffix', 'join_table', 'join_id', 'record']);
my $table = $$argv{'table'};
my $record = $$argv{'record'};
## Is there a change object provided?
my $changes;
if ( exists $$argv{'changes'} ) {
$changes = $$argv{'changes'};
}
my $suffix = $$argv{'suffix'} ? $$argv{'suffix'} : "";
##
## This record collects the changes in order to do the validation later
##
my $rec;
my $collist = "";
my $vallist = "";
my $sep = "";
my $update = "";
my $value;
my $pkcol;
foreach my $tcol ( @{$table->{'columns'}} ) {
if ( $tcol->{'type'} eq "pk" ) {
$pkcol = $tcol;
next;
}
if ( $tcol->{'column'} eq "creation" || $tcol->{'column'} eq "modtime" ) {
$collist .= "$sep$tcol->{'column'}";
$vallist .= $sep . "NOW()";
$sep = ",";
##
## This is not used for anything other that perhaps a table-specific validator
##
my ($seconds, $minutes, $hours, $day_of_month, $month, $year,
$wday, $yday, $isdst) = localtime(time);
my $dt = sprintf("%04d-%02d-%02d %02d:%02d:%02d",
1900+$year, $month+1, $day_of_month, $hours, $minutes, $seconds);
$$rec{$$tcol{'column'}} = $dt;
next;
}
if ( defined param($tcol->{'column'} . $suffix) ) {
TYPE: {
# multivalues scalars (sets)
$$tcol{'type'} eq 'set' and do {
my @values = param($tcol->{'column'} . $suffix);
$value = join(",", @values);
last TYPE;
};
# single-valued scalars
$$tcol{'type'} eq "time" and do {
my $hour = param($$tcol{'column'} . $suffix . "_hour");
$$rec{$$tcol{'column'} . "_hour"} = $hour;
my $minute = param($$tcol{'column'} . $suffix . "_minute");
$$rec{$$tcol{'column'} . "_minute"} = $minute;
my $ampm = param($$tcol{'column'} . $suffix . "_ampm");
$$rec{$$tcol{'column'} . "_ampm"} = $ampm;
$value = sprintf("%02d:%02d:00", $hour+12*($ampm), $minute);
last TYPE;
};
# password types
$$tcol{'type'} eq "password" and do {
$value = Password::encrypt(param($tcol->{'column'} . $suffix));
last TYPE;
};
$value = param($tcol->{'column'} . $suffix);
}; # TYPE
$collist .= "$sep$tcol->{'column'}";
$vallist .= "$sep" . SQLQuote($value);
$sep = ",";
$$rec{$$tcol{'column'}} = $value;
if ( $changes && defined $value && $value ne "" ) {
$changes->add({-table=>$table->{'table'},
-row=>0, # filled in later
-column=>$tcol->{'column'},
-secure=>$tcol->{'secure'},
-new=>$value,
-type=>"ADD",
-user=>Login::getLoginId(),
-join_table=>$$argv{'join_table'},
-join_id=>$$argv{'join_id'},
});
}
}
}
##
## Add any elements from the default values record that are not already defined
##
if ( defined $record ) {
foreach my $k ( keys %$record ) {
if ( !exists $$rec{$k} ) {
$collist .= "$sep$k";
$vallist .= "$sep" . SQLQuote($$record{$k});
$sep = ",";
$$rec{$k} = $$record{$k};
}
}
}
##
## If there is a table-specific validator in the metadata table, call it
##
my $valid = 1;
if ( exists $table->{'preadd'} ) {
$valid = &{$$table{'preadd'}}($rec);
}
if ( !$valid ) {
return undef;
}
my $query = "INSERT INTO $table->{'table'} ( $collist ) VALUES ( $vallist )";
SQLSend($query);
SQLSend("Select LAST_INSERT_ID()");
my $pk = SQLFetchOneColumn();
$$rec{$pkcol->{'column'}} = $pk;
$changes && $changes->updateAll({-row=>$pk});
## If there are any N-N rels, get their values and update them now
# my $qq = new CGI;
# my $paramref = $qq->Vars();
# Utility::ObjDump($paramref);
foreach my $tcol ( @{$table->{'rels'}} ) {
if ( $tcol->{'type'} ne "N-N" ) {
next;
}
my @values;
WIDGET: {
$tcol->{'widget'} eq LeftRightWidget::type() and do {
@values = LeftRightWidget::getParamValue($tcol->{'hashkey'} . $suffix);
last WIDGET;
};
$tcol->{'widget'} eq OptionMenu::type() and do {
@values = param($tcol->{'hashkey'} . $suffix);
last WIDGET;
};
!exists $tcol->{'widget'} and do {
@values = param($tcol->{'hashkey'} . $suffix);
last WIDGET;
};
};
my $middletable = $tcol->{'table'};
my $middletcol = findColumn({-table=>$middletable,
-column=>$tcol->{'column'}[1]});
my $righttable = $middletcol->{'values'}->{'table'};
my $rightlabel = $middletcol->{'values'}->{'label'};
my $leftkey = $tcol->{'column'}[0];
my $rightkey = $tcol->{'column'}[1];
foreach my $k ( @values ) {
my $nnrec;
$nnrec->{$leftkey} = $pk;
$nnrec->{$rightkey} = $k;
writeSimpleRecord({-table=>$middletable,
-record=>$nnrec});
## Reach to the rightmost table to get the label value
if ( $changes ) {
my $rightrecord = getRecordById({-table=>$righttable,
-id=>$k});
$changes->add({-table=>$table->{'table'},
-row=>$pk,
-column=>$tcol->{'hashkey'},
-new=>$rightrecord->{$rightlabel},
-type=>"ADD",
-user=>Login::getLoginId(),
-join_table=>$$argv{'join_table'},
-join_id=>$$argv{'join_id'},
});
}
}
}
if ( exists $table->{'postadd'} ) {
$valid = &{$$table{'postadd'}}($rec);
}
return $pk;
}
##
## doUpdateFromParams - update DB from form data
##
## required named parameters:
## table .... table meta data of table being updated
## record ... hash of current values, keys match DB columns
## optional named parameters:
## changes .. a changes object to use to record changes
## new ...... if defined, the new record is put into this
## suffix ... optional suffix on form element names
## pk ....... name of the primary key form parameter
## debug .... enable debug prints to output
##
sub doUpdateFromParams
{
my $argv = shift;
argcvt($argv, ['table', 'record'], ['changes', 'new', 'suffix', 'pk', 'debug']);
my $table = $$argv{'table'};
my $rec = $$argv{'record'};
my $debug = $$argv{'debug'};
my $changes = 0;
if ( exists $$argv{'changes'} ) {
$changes = $$argv{'changes'};
}
my $newrec = 0;
if ( exists $$argv{'new'} ) {
$newrec = $$argv{'new'};
}
my $suffix = $$argv{'suffix'} ? $$argv{'suffix'} : "";
## This is due to the inconsistent naming of the primary key form parameter -
## This should be cleaned up in the code.
my $pk;
my $pkname;
my $paramname;
if ( defined $$argv{'pk'} && defined param($$argv{'pk'} . $suffix) ) {
$pkname = $$argv{'pk'};
$paramname = $$argv{'pk'};
} elsif ( defined param("pk" . $suffix) ) {
$pkname = "id";
$paramname = "pk";
} elsif ( defined param("id" . $suffix) ) {
$pkname = "id";
$paramname = "id";
} else {
Utility::redError("Neither pk nor id defined as a parameter");
return;
}
$pk = param($paramname . $suffix);
my $update = "";
my $sep = "";
my $mods = 0;
my $newval;
my $tcol;
foreach $tcol ( @{$table->{'columns'}} ) {
my $paramname = $tcol->{'column'} . $suffix;
if ( $newrec && exists $$rec{$$tcol{'column'}} ) {
$$newrec{$$tcol{'column'}} = $$rec{$$tcol{'column'}};
}
if ( $tcol->{'type'} eq "pk" ) {
next;
}
if ( $tcol->{'column'} eq "modtime" ) {
$update .= "$sep$tcol->{'column'} = NOW()";
$sep = ",";
next;
}
if ( defined param($paramname) ) {
$newval = undef;
##
## Handle arrays and scalars differently
##
TYPE: {
## array types:
$$tcol{'type'} eq "set" and do {
$newval = join(",", param($$tcol{'column'} . $suffix));
last TYPE;
};
## scalar types:
$$tcol{'type'} eq "time" and do {
my $hour = param($$tcol{'column'} . $suffix . "_hour");
my $minute = param($$tcol{'column'} . $suffix . "_minute");
my $ampm = param($$tcol{'column'} . $suffix . "_ampm");
$newval = sprintf("%02d:%02d:00", $hour+12*($ampm), $minute);
last TYPE;
};
$$tcol{'type'} eq "password" and do {
my $formdata = param($$tcol{'column'} . $suffix);
if ( (defined $formdata && defined $$rec{$tcol->{'column'}} &&
$formdata ne $$rec{$tcol->{'column'}} ) ||
(defined $formdata != defined $$rec{$tcol->{'column'}})) {
$newval = Password::encrypt($formdata);
} else {
$newval = $$rec{$tcol->{'column'}};
}
last TYPE;
};
$newval = param($$tcol{'column'} . $suffix);
}; #TYPE
if ( $debug ) {
print p("UpdateFromParams: \"$tcol->{'column'}\" old value=",
!exists $$rec{$tcol->{'column'}} ? "!exists" :
!defined $$rec{$tcol->{'column'}}?"undef":
$$rec{$tcol->{'column'}},
" parameter=",
!defined param($paramname)?"undef":
"\"" . param($paramname) . "\"" );
}
##
## Problem: if the old value is NULL (undefined) and the parameter value
## is empty, then the DB shouldn't be changed.
##
## OLD PARAMETER ACTION
## undefined empty string none
## undefined string update
## defined defined, same none
## defined defined, different update