Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

241 lines
6.2 KiB

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