]> git.mxchange.org Git - friendica.git/blob - mods/friendica-to-smarty-tpl.py
newline at end of header
[friendica.git] / mods / friendica-to-smarty-tpl.py
1 #!/usr/bin/python
2 #
3 # Script to convert Friendica internal template files into Smarty template files
4 # Copyright 2013 Zach Prezkuta
5 # Licensed under GPL v3
6
7 import os, re, string
8 import sys, getopt
9
10 ldelim = '{{'
11 rdelim = '}}'
12
13 def fToSmarty(matches):
14         match = matches.group(0)
15         if match == '$j':
16                 return match
17         match = string.replace(match, '[', '')
18         match = string.replace(match, ']', '')
19
20         ldel = ldelim
21         rdel = rdelim
22         if match.find("'") > -1:
23                 match = string.replace(match, "'", '')
24                 ldel = "'" + ldel
25                 rdel = rdel + "'"
26         elif match.find('"') > -1:
27                 match = string.replace(match, '"', '')
28                 ldel = '"' + ldel
29                 rdel = rdel + '"'
30
31         return ldel + match + rdel
32
33
34 def fix_element(element):
35         # Much of the positioning here is important, e.g. if you do element.find('if ') before you do
36         # element.find('endif'), then you may get some multiply-replaced delimiters
37
38         if element.find('endif') > -1:
39                 element = ldelim + '/if' + rdelim
40                 return element
41
42         if element.find('if ') > -1:
43                 element = string.replace(element, '{{ if', ldelim + 'if')
44                 element = string.replace(element, '{{if', ldelim + 'if')
45                 element = string.replace(element, ' }}', rdelim)
46                 element = string.replace(element, '}}', rdelim)
47                 return element
48
49         if element.find('else') > -1:
50                 element = ldelim + 'else' + rdelim
51                 return element
52
53         if element.find('endfor') > -1:
54                 element = ldelim + '/foreach' + rdelim
55                 return element
56
57         if element.find('for ') > -1:
58                 element = string.replace(element, '{{ for ', ldelim + 'foreach ')
59                 element = string.replace(element, '{{for ', ldelim + 'foreach ')
60                 element = string.replace(element, ' }}', rdelim)
61                 element = string.replace(element, '}}', rdelim)
62                 return element
63
64         if element.find('endinc') > -1:
65                 element = ''
66                 return element
67
68         if element.find('inc ') > -1:
69                 parts = element.split(' ')
70                 element = ldelim + 'include file="'
71
72                 # We need to find the file name. It'll either be in parts[1] if the element was written as {{ inc file.tpl }}
73                 # or it'll be in parts[2] if the element was written as {{inc file.tpl}}
74                 if parts[0].find('inc') > -1:
75                         first = 0
76                 else:
77                         first = 1
78
79                 if parts[first+1][0] == '$':
80                         # This takes care of elements where the filename is a variable, e.g. {{ inc $file }}
81                         element += ldelim + parts[first+1].rstrip('}') + rdelim
82                 else:
83                         # This takes care of elements where the filename is a path, e.g. {{ inc file.tpl }}
84                         element += parts[first+1].rstrip('}') 
85
86                 element += '"'
87
88                 if len(parts) > first + 1 and parts[first+2] == 'with':
89                         # Take care of variable substitutions, e.g. {{ inc file.tpl with $var=this_var }}
90                         element += ' ' + parts[first+3].rstrip('}')[1:]
91
92                 element += rdelim
93                 return element
94
95
96 def convert(filename, tofilename, php_tpl):
97         header = ldelim + "*\n *\tAUTOMATICALLY GENERATED TEMPLATE\n *\tDO NOT EDIT THIS FILE, CHANGES WILL BE OVERWRITTEN\n *\n *" + rdelim + "\n"
98         tofilename.write(header)
99
100         for line in filename:
101                 newline = ''
102                 st_pos = 0
103                 brack_pos = line.find('{{')
104
105                 if php_tpl:
106                         # If php_tpl is True, this script will only convert variables in quotes, like '$variable'
107                         # or "$variable". This is for .tpl files that produce PHP scripts, where you don't want
108                         # all the PHP variables converted into Smarty variables
109                         pattern1 = re.compile(r"""
110 ([\'\"]\$\[[a-zA-Z]\w*
111 (\.
112 (\d+|[a-zA-Z][\w-]*)
113 )*
114 (\|[\w\$:\.]*)*
115 \][\'\"])
116 """, re.VERBOSE)
117                         pattern2 = re.compile(r"""
118 ([\'\"]\$[a-zA-Z]\w*
119 (\.
120 (\d+|[a-zA-Z][\w-]*)
121 )*
122 (\|[\w\$:\.]*)*
123 [\'\"])
124 """, re.VERBOSE)
125                 else:
126                         # Compile the pattern for bracket-style variables, e.g. $[variable.key|filter:arg1:arg2|filter2:arg1:arg2]
127                         # Note that dashes are only allowed in array keys if the key doesn't start
128                         # with a number, e.g. $[variable.key-id] is ok but $[variable.12-id] isn't
129                         #
130                         # Doesn't currently process the argument position key 'x', i.e. filter:arg1:x:arg2 doesn't get
131                         # changed to arg1|filter:variable:arg2 like Smarty requires
132                         #
133                         # Filter arguments can be variables, e.g. $variable, but currently can't have array keys with dashes
134                         # like filter:$variable.key-name
135                         pattern1 = re.compile(r"""
136 (\$\[[a-zA-Z]\w*
137 (\.
138 (\d+|[a-zA-Z][\w-]*)
139 )*
140 (\|[\w\$:\.]*)*
141 \])
142 """, re.VERBOSE)
143
144                         # Compile the pattern for normal style variables, e.g. $variable.key
145                         pattern2 = re.compile(r"""
146 (\$[a-zA-Z]\w*
147 (\.
148 (\d+|[a-zA-Z][\w-]*)
149 )*
150 (\|[\w\$:\.]*)*
151 )
152 """, re.VERBOSE)
153
154                 while brack_pos > -1:
155                         if brack_pos > st_pos:
156                                 line_segment = line[st_pos:brack_pos]
157                                 line_segment = pattern2.sub(fToSmarty, line_segment)
158                                 newline += pattern1.sub(fToSmarty, line_segment)
159
160                         end_brack_pos = line.find('}}', brack_pos)
161                         if end_brack_pos < 0:
162                                 print "Error: no matching bracket found"
163
164                         newline += fix_element(line[brack_pos:end_brack_pos + 2])
165                         st_pos = end_brack_pos + 2
166
167                         brack_pos = line.find('{{', st_pos)
168
169                 line_segment = line[st_pos:]
170                 line_segment = pattern2.sub(fToSmarty, line_segment)
171                 newline += pattern1.sub(fToSmarty, line_segment)
172                 newline = newline.replace("{#", ldelim + "*")
173                 newline = newline.replace("#}", "*" + rdelim)
174                 tofilename.write(newline)
175
176
177 def help(pname):
178         print "\nUsage:"
179         print "\t" + pname + " -h\n\n\t\t\tShow this help screen\n"
180         print "\t" + pname + " -p directory\n\n\t\t\tConvert all .tpl files in directory to\n\t\t\tSmarty templates in directory/smarty3/\n"
181         print "\t" + pname + "\n\n\t\t\tInteractive mode\n"
182
183
184
185
186 #
187 # Main script
188 #
189
190 path = ''
191
192 try:
193         opts, args = getopt.getopt(sys.argv[1:], "hp:")
194         for opt, arg in opts:
195                 if opt == '-h':
196                         help(sys.argv[0])
197                         sys.exit()
198                 elif opt == '-p':
199                         path = arg
200 except getopt.GetoptError:
201         help(sys.argv[0])
202         sys.exit(2)
203         
204
205 if path == '':
206         path = raw_input('Path to template folder to convert: ')
207
208 if path[-1:] != '/':
209         path = path + '/'
210
211 outpath = path + 'smarty3/'
212
213 if not os.path.exists(outpath):
214         os.makedirs(outpath)
215
216 files = os.listdir(path)
217 for a_file in files:
218         if a_file == 'htconfig.tpl':
219                 php_tpl = True
220         else:
221                 php_tpl = False
222
223         filename = os.path.join(path,a_file)
224         ext = a_file.split('.')[-1]
225         if os.path.isfile(filename) and ext == 'tpl':
226                 f = open(filename, 'r')
227
228                 newfilename = os.path.join(outpath,a_file)
229                 outf = open(newfilename, 'w')
230
231                 print "Converting " + filename + " to " + newfilename
232                 convert(f, outf, php_tpl)
233
234                 outf.close()
235                 f.close()
236