Bug 5917 : Yet more scoping
[koha.git] / installer / html-template-to-template-toolkit.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Carp;
6 use Data::Dumper;
7
8 use Getopt::Long;
9 use File::Basename;
10 use File::Copy;
11
12 my $help_msg = <<EOH;
13 This script does a first-cut conversion of koha HTML::Template template files (.tmpl).
14 It creates a mirror of koha-tmpl called koha-tt where converted files will be placed.
15 By default all files will be converted: use the --file (-f) argument to specify
16   individual files to process.
17
18 Options:
19     --koharoot (-r): Root directory of koha installation.
20     --type (-t): template file extenstions to match
21         (defaults to tmpl|inc|xsl).
22     --copyall (-c): Also copy across all files in template directory
23     --file (-f): specify individual files to process
24     --debug (-d): output more information.
25 EOH
26
27 my $tmpl_in_dir      = 'koha-tmpl';
28 my $tmpl_out_dir     = 'koha-tt';
29
30 # template toolkit variables NOT to scope, in other words, variables that need to remain global (case sensitive)
31 my @globals = ("themelang","JacketImages","OPACAmazonCoverImages","GoogleJackets","BakerTaylorEnabled",
32 "SyndeticsEnabled", "OpacRenewalAllowed", "item_level_itypes","noItemTypeImages");
33
34 # Arguments:
35 my $KOHA_ROOT;
36 my $tmpl_extn_match  = "tmpl|inc|xsl"; # Type match defaults to *.tmpl plus *.inc if not specified
37 my $copy_other_files = 0;
38 my @template_files;
39 my @files_w_tmpl_loops;
40 my $verbose          = 0;
41 GetOptions (
42     "koharoot=s"        => \$KOHA_ROOT,
43     "type|t=s"          => \$tmpl_extn_match,
44     "copyall|c"         => \$copy_other_files,
45     "file|f=s"          => \@template_files,         # array of filenames
46     "verbose+"          => \$verbose,                # incremental flag
47 ) or die $help_msg;
48
49 if ( ! $KOHA_ROOT || ! -d $KOHA_ROOT ) {
50     croak "Koha root not passed or is not correct.";
51 }
52 if ( ! -d "$KOHA_ROOT/$tmpl_in_dir" ) {
53     croak "Cannot find template dir ($tmpl_in_dir)";
54 }
55
56 # Attempt to create koha-tt dir..
57 if ( ! -d "$KOHA_ROOT/$tmpl_out_dir" ) {
58     mkdir("$KOHA_ROOT/$tmpl_out_dir") #, '0755'
59        or croak "Cannot create $tmpl_out_dir directory in $KOHA_ROOT: $!";
60 }
61
62 # Obtain list of files to process - go recursively through tmpl_in_dir and subdirectories..
63 unless ( scalar(@template_files) ) {
64     @template_files = mirror_template_dir_structure_return_files("$KOHA_ROOT/$tmpl_in_dir", "$tmpl_extn_match");
65 }
66 foreach my $file (@template_files) {
67     (my $new_path = $file) =~ s/$tmpl_in_dir/$tmpl_out_dir/;
68     $new_path =~ s/\.tmpl/.tt/;
69     $new_path = "$KOHA_ROOT/$new_path" unless ( $new_path =~ m/^$KOHA_ROOT/ );
70
71     open my $ITMPL, '<', $file or croak "Can't open $file for input: $!";
72     open my $OTT, '>', $new_path or croak "Can't open $new_path for output: $!";
73
74     # allows 'proper' handling of for loop scope
75     # cur_scope is a stack of scopes, the last being the current
76     #   when opening a for loop push scope onto end, when closing for loop pop
77     my @cur_scope = ("");
78     # flag representing if we've found a for loop this iteration
79     my $for_loop_found = 0;
80
81     for my $input_tmpl(<$ITMPL>){
82         my @parts = split "<", $input_tmpl;
83         for( my $i=0; $i<=$#parts; ++$i ){
84             my $input_tmpl = $i ? "<" . $parts[$i] : $parts[$i]; # add < sign back in to every part except the first
85         $for_loop_found = 0;
86
87         # handle poorly names variable such as f1!, f1+, f1-, f1| and mod
88         $input_tmpl =~ s/"(\w+)\|"/"$1pipe"/ig;
89         $input_tmpl =~ s/"(\w+)\+"/"$1plus"/ig;
90         $input_tmpl =~ s/"(\w+)\-"/"$1minus"/ig;
91         $input_tmpl =~ s/"(\w+)!"/"$1exclamation"/ig;
92         $input_tmpl =~ s/"(\w+),(\w+)"/"$1comma$2"/ig; #caused a problem in patron search
93         $input_tmpl =~ s/NAME="mod"/NAME="modname"/ig;
94         # handle 'naked' TMPL_VAR "parameter" by turning them into what they should be, TMPL_VAR NAME="parameter"
95         $input_tmpl =~ s/TMPL_VAR\s+"(\w+)"/TMPL_VAR NAME="$1"/ig;
96         # make an end (ESCAPE NAME DEFAULT) into a ned (NAME ESCAPE DEFAULT)
97         $input_tmpl =~ s/ESCAPE="(\w+?)"\s+NAME=['"](\w+?)['"]\s+DEFAULT=['"](.+?)['"]/NAME="$2" ESCAPE="$1" DEFAULT="$3"/ig;
98
99         # Process..
100         # NB: if you think you're seeing double, you probably are, *some* (read:most) patterns appear twice: once with quotations marks, once without.
101         #     trying to combine them into a single pattern proved troublesome as a regex like ['"]?(.*?)['"]? was causing problems and fixing the problem caused (alot) more complex regex
102
103         # variables
104         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+NAME\s?=\s?['"]?\s*(\w*?)\s*['"]?\s+ESCAPE=['"](\w*?)['"]\s+DEFAULT=['"]?(.*?)['"]?\s*-*>/[% DEFAULT $cur_scope[-1]$1="$3" |$2 %]/ig;
105         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+NAME\s?=\s?['"]\s*(\w*?)\s*['"]\s+ESCAPE=['"]?(\w*?)['"]?\s*-*>/[% $cur_scope[-1]$1 |$2 %]/ig;
106         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+NAME\s?=\s?(\w*?)\s+ESCAPE=['"]?(\w*?)['"]?\s*-*>/[% $cur_scope[-1]$1 |$2 %]/ig;
107         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+ESCAPE=['"]?(\w*?)['"]?\s+NAME\s?=\s?['"]?([\w-]*?)['"]?\s*-*>/[% $cur_scope[-1]$2 |$1 %]/ig;
108         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+NAME\s?=\s?['"]?(\w*?)['"]?\s+DEFAULT=['"](.*?)['"]\s*-*>/[% DEFAULT $cur_scope[-1]$1="$2" %]/ig;
109         $input_tmpl =~ s/<[!-]*\s*TMPL_VAR\s+NAME\s?=\s?['"]?\s*(\w*?)\s*['"]?\s+DEFAULT=(.*?)\s*-*>/[% DEFAULT $cur_scope[-1]$1=$2 %]/ig;
110         $input_tmpl =~ s/<[!-]*\s*TMPL[_\s]VAR\s+NAME\s?=\s?['"]?\s*(\w*?)\s*['"]?\s*-*>/[% $cur_scope[-1]$1 %]/ig;
111         $input_tmpl =~ s/<[!-]*\s*TMPL[_\s]VAR\s+EXPR\s?=\s?['"](.*?)['"]\s*-*>/[% $1 %]/ig;     # TMPL_VAR NAME and TMPL_VAR EXPR are logically equiv
112         $input_tmpl =~ s/<[!-]*\s*TMPL[_\s]VAR\s+EXPR\s?=\s?(.*?)\s*-*>/[% $1 %]/ig;
113
114         # if, elseif and unless blocks
115         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+EXPR\s?=\s?['"](.*?)['"]\s*-*>/[% IF ( $1 ) %]/ig;
116         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+EXPR\s?=\s?(.*?)\s*-*>/[% IF ( $1 ) %]/ig;
117         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+NAME\s?=\s?['"]\s*(\w*?)\s*['"]\s*-*>/[% IF ( $cur_scope[-1]$1 ) %]/ig;
118         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+NAME\s?=\s?(\w*?)\s*-*>/[% IF ( $cur_scope[-1]$1 ) %]/ig;
119         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+['"](.*?)['"]\s*-*>/[% IF ( $cur_scope[-1]$1 ) %]/ig;
120         $input_tmpl =~ s/<[!-]*\s*TMPL_IF\s+([\w\s]*?)\s*-*>/[% IF ( $cur_scope[-1]$1 ) %]/ig;
121
122         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+EXPR\s?=\s?['"](.*?)['"]\s*-*>/[% ELSIF ( $1 ) %]/ig;
123         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+EXPR\s?=\s?(.*?)\s*-*>/[% ELSIF ( $1 ) %]/ig;
124         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+NAME\s?=\s?['"](\w*?)['"]\s*-*>/[% ELSIF ( $cur_scope[-1]$1 ) %]/ig;
125         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+NAME\s?=\s?(\w*?)\s*-*>/[% ELSIF ( $cur_scope[-1]$1 ) %]/ig;
126         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+['"](\w*?)['"]\s*-*>/[% ELSIF ( $cur_scope[-1]$1 ) %]/ig;
127         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSIF\s+(\w*?)\s*-*>/[% ELSIF ( $cur_scope[-1]$1 ) %]/ig;
128
129         $input_tmpl =~ s/<[!-]*\s*TMPL_ELSE\s*-*>/[% ELSE %]/ig;
130         $input_tmpl =~ s/<[!-]*\s*\/TMPL_IF\s*-*>/[% END %]/ig;
131
132         $input_tmpl =~ s/<[!-]*\s*TMPL_UNLESS\s+NAME\s?=\s?['"]?(\w*?)['"]?\s*-*>/[% UNLESS ( $cur_scope[-1]$1 ) %]/ig;
133         $input_tmpl =~ s/<[!-]*\s*\/TMPL_UNLESS\s*-*>/[% END %]/ig;
134         # includes
135         $input_tmpl =~ s/<[!-]*\s*TMPL_INCLUDE\s+NAME\s?=\s?"(.*?\.inc)"\s*-*>/[% INCLUDE '$1' %]/ig;
136         $input_tmpl =~ s/<[!-]*\s*TMPL_INCLUDE\s+NAME\s?=\s?"(.*?)"\s*-*>/[% INCLUDE $1 %]/ig;
137
138         #reverse scoping bug fix
139         for my $tag (@globals){
140             next unless $cur_scope[-1];
141             $input_tmpl =~ s/$cur_scope[-1]$tag/$tag/g;
142         }
143
144         if ($input_tmpl =~ m/<[!-]*\s*TMPL_LOOP/i ){
145             $for_loop_found = 1;
146         }
147
148         $input_tmpl =~ s/<[!-]*\s*TMPL_LOOP\s+NAME\s?=\s?['"](?<SCOPE>.*?)['"]\s*-*>/"[% FOREACH " . substr($+{SCOPE}, 0, -1) . " IN $cur_scope[-1]$1 %]"/ieg;
149         $input_tmpl =~ s/<[!-]*\s*TMPL_LOOP\s+NAME\s?=\s?(?<SCOPE>.*?)\s*-*>/"[% FOREACH " . substr($+{SCOPE}, 0, -1) . " IN $cur_scope[-1]$1 %]"/ieg;
150
151         # handle new scope
152         if($for_loop_found){
153             my $scope = substr($+{SCOPE}, 0, -1) . ".";
154             push(@cur_scope, $scope);
155             $for_loop_found = 0;
156         }
157
158         # handle loops and old scope
159         if ( $input_tmpl =~ m/<!--[\s\/]*TMPL_LOOP\s*-->/i ) {
160             push(@files_w_tmpl_loops, $new_path);
161             pop(@cur_scope);
162         }
163
164         $input_tmpl =~ s/<[!-]*\s*\/TMPL_LOOP\s*-*>/[% END %]/ig;
165
166         # misc 'patches'
167         $input_tmpl =~ s/\seq\s/ == /ig;
168         $input_tmpl =~ s/HTML/html/g;
169         $input_tmpl =~ s/URL/url/g;
170         $input_tmpl =~ s/dhtmlcalendar_dateformat/DHTMLcalendar_dateformat/ig;
171         $input_tmpl =~ s/\w*\.__first__/loop.first/ig;
172         $input_tmpl =~ s/\w*\.__last__/loop.last/ig;
173         $input_tmpl =~ s/\w*\.__odd__/loop.odd/ig;
174         $input_tmpl =~ s/\w*\.__even__/loop.even/ig;
175         $input_tmpl =~ s/\w*\.__counter__/loop.count/ig; #loop.count gives the range (0..max) whereas loop.index gives the range (1..max+1), __counter__ is unknown
176
177         # hack to get around lack of javascript filter
178         $input_tmpl =~ s/\|\s*JS/|replace("'", "\\'") |replace('"', '\\"') |replace('\\n', '\\\\n') |replace('\\r', '\\\\r')/ig;
179     
180         # Write out..
181         print $OTT $input_tmpl;
182         }
183     }
184     close $ITMPL;
185     close $OTT;
186 }
187
188 if ( scalar(@files_w_tmpl_loops) && $verbose ) {
189     print "\nThese files contain TMPL_LOOPs that need double checking:\n";
190     foreach my $file (@files_w_tmpl_loops) {
191         print "$file\n";
192     }
193 }
194
195 ## SUB-ROUTINES ##
196
197 # Create new directory structure and return list of template files
198 sub mirror_template_dir_structure_return_files {
199     my($dir, $type) = @_;
200
201     my @files = ();
202     if ( opendir(DIR, $dir) ) {
203         my @dirent = readdir DIR;   # because DIR is shared when recursing
204         closedir DIR;
205         for my $dirent (@dirent) {
206             my $path = "$dir/$dirent";
207             if ( $dirent =~ /^\./ ) {
208               ;
209             }
210             elsif ( -f $path ) {
211                 (my $new_path = $path) =~ s/$tmpl_in_dir/$tmpl_out_dir/;
212                 $new_path = "$KOHA_ROOT/$new_path" unless ( $new_path =~ m/^$KOHA_ROOT/ );
213                 if ( !defined $type || $dirent =~ /\.(?:$type)$/) {
214                     push(@files, $path);
215                 }
216                 elsif ( $copy_other_files ) {
217                     copy($path, $new_path)
218                       or croak "Failed to copy $path to $new_path: $!";
219                 }
220             }
221             elsif ( -d $path ) {
222                 (my $new_path = $path) =~ s/$tmpl_in_dir/$tmpl_out_dir/;
223                 $new_path = "$KOHA_ROOT/$new_path" unless ( $new_path =~ m/^$KOHA_ROOT/ );
224                 if ( ! -d $new_path ) {
225                     mkdir($new_path) #, '0755'
226                       or croak "Failed to create " . $new_path ." directory: $!";
227                 }
228                 my @sub_files = mirror_template_dir_structure_return_files($path, $type);
229                 push(@files, @sub_files) if ( scalar(@sub_files) );
230             }
231         }
232     } else {
233         warn("Cannot open $dir: $! ... skipping");
234     }
235
236     return @files;
237 }