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