My static website generator using poole https://www.xythobuz.de
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.

macros.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import itertools
  4. import email.utils
  5. import os.path
  6. import time
  7. import codecs
  8. from datetime import datetime
  9. DEFAULT_LANG = "en"
  10. BASE_URL = "https://www.xythobuz.de"
  11. # -----------------------------------------------------------------------------
  12. # sub page helper macro
  13. # -----------------------------------------------------------------------------
  14. def backToParent():
  15. url = page.get("parent", "") + ".html"
  16. posts = [p for p in pages if p.url == url]
  17. if len(posts) > 0:
  18. p = posts[0]
  19. print '<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>'
  20. # -----------------------------------------------------------------------------
  21. # table helper macro
  22. # -----------------------------------------------------------------------------
  23. def tableHelper(style, header, content):
  24. print "<table>"
  25. if (header != None) and (len(header) == len(style)):
  26. print "<tr>"
  27. for h in header:
  28. print "<th>" + h + "</th>"
  29. print "</tr>"
  30. for ci in range(0, len(content)):
  31. if len(content[ci]) != len(style):
  32. # invalid call of table helper!
  33. continue
  34. print "<tr>"
  35. for i in range(0, len(style)):
  36. s = style[i]
  37. td_style = ""
  38. if "monospaced" in s:
  39. td_style += " font-family: monospace;"
  40. if "align-last-right" in s:
  41. if ci == (len(content) - 1):
  42. td_style += " text-align: right;"
  43. else:
  44. if "align-center" in s:
  45. td_style += " text-align: center;"
  46. elif "align-right" in s:
  47. td_style += " text-align: right;"
  48. elif "align-center" in s:
  49. td_style += " text-align: center;"
  50. td_args = ""
  51. if td_style != "":
  52. td_args = " style=\"" + td_style + "\""
  53. print "<td" + td_args + ">"
  54. if isinstance(content[ci][i], tuple):
  55. text, link = content[ci][i]
  56. print "<a href=\"" + link + "\">" + text + "</a>"
  57. else:
  58. text = content[ci][i]
  59. print text
  60. print "</td>"
  61. print "</tr>"
  62. print "</table>"
  63. # -----------------------------------------------------------------------------
  64. # menu helper macro
  65. # -----------------------------------------------------------------------------
  66. def githubCommitBadge(p, showInline = False):
  67. ret = ""
  68. if p.get("github", "") != "":
  69. link = p.get("git", p.github)
  70. linkParts = p.github.split("/")
  71. if len(linkParts) >= 5:
  72. ret += "<a href=\"" + link + "\"><img "
  73. if showInline:
  74. ret += "style =\"vertical-align: top;\" "
  75. ret += "src=\"https://img.shields.io/github/last-commit/"
  76. ret += linkParts[3] + "/" + linkParts[4]
  77. ret += ".svg?logo=git&style=flat\" /></a>"
  78. return ret
  79. def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStartDate = False, nicelyFormatFullDate = False, lastyear = "0", lang = "", showLastCommit = True):
  80. title = p.title
  81. if lang != "":
  82. if p.get("title_" + lang, "") != "":
  83. title = p.get("title_" + lang, "")
  84. if title == "Blog":
  85. title = p.post
  86. year = p.get("date", "")[0:4]
  87. if year != lastyear:
  88. lastyear = year
  89. if yearsAsHeading:
  90. print "\n\n#### %s\n" % (year)
  91. dateto = ""
  92. if p.get("date", "" != ""):
  93. year = p.get("date", "")[0:4]
  94. if showOnlyStartDate:
  95. dateto = " (%s)" % (year)
  96. if p.get("update", "") != "" and p.get("update", "")[0:4] != year:
  97. if showDateSpan:
  98. dateto = " (%s - %s)" % (year, p.get("update", "")[0:4])
  99. if nicelyFormatFullDate:
  100. dateto = " - " + datetime.strptime(p.get("update", p.date), "%Y-%m-%d").strftime("%B %d, %Y")
  101. print " * **[%s](%s)**%s" % (title, p.url, dateto)
  102. if p.get("description", "") != "":
  103. description = p.get("description", "")
  104. if lang != "":
  105. if p.get("description_" + lang, "") != "":
  106. description = p.get("description_" + lang, "")
  107. print "<br><span class=\"listdesc\">" + description + "</span>"
  108. if showLastCommit:
  109. link = githubCommitBadge(p)
  110. if len(link) > 0:
  111. print "<br>" + link
  112. return lastyear
  113. def printRecentMenu(count = 5):
  114. posts = [p for p in pages if "date" in p and p.lang == "en"]
  115. posts.sort(key=lambda p: p.get("update", p.get("date")), reverse=True)
  116. if count > 0:
  117. posts = posts[0:count]
  118. for p in posts:
  119. printMenuItem(p, False, False, False, True, "0", "", False)
  120. def printBlogMenu():
  121. posts = [p for p in pages if "post" in p and p.lang == "en"]
  122. posts.sort(key=lambda p: p.get("date", "9999-01-01"), reverse=True)
  123. lastyear = "0"
  124. for p in posts:
  125. lastyear = printMenuItem(p, True, False, False, True, lastyear)
  126. def printProjectsMenu():
  127. # prints all pages with parent 'projects' or 'stuff'.
  128. # first the ones without date, sorted by position.
  129. # then afterwards those with date, split by year.
  130. # also supports blog posts with parent.
  131. enpages = [p for p in pages if p.lang == "en"]
  132. dpages = [p for p in enpages if p.get("date", "") == ""]
  133. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  134. mpages.sort(key=lambda p: [int(p.get("position", "999"))])
  135. for p in mpages:
  136. printMenuItem(p)
  137. dpages = [p for p in enpages if p.get("date", "") != ""]
  138. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  139. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  140. lastyear = "0"
  141. for p in mpages:
  142. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  143. def print3DPrintingMenu():
  144. mpages = [p for p in pages if p.get("parent", "") == "3d-printing" and p.lang == "en"]
  145. mpages.sort(key=lambda p: int(p["position"]))
  146. for p in mpages:
  147. printMenuItem(p, False, True, True)
  148. def printInputDevicesMenu():
  149. mpages = [p for p in pages if p.get("parent", "") == "input_devices" and p.lang == "en"]
  150. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  151. for p in mpages:
  152. printMenuItem(p, False, True, True)
  153. def printInputDevicesRelatedMenu():
  154. mpages = [p for p in pages if p.get("show_in_input_devices", "false") == "true"]
  155. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  156. for p in mpages:
  157. printMenuItem(p, False, True, True)
  158. def printSmarthomeMenu():
  159. mpages = [p for p in pages if p.get("parent", "") == "smarthome" and p.lang == "en"]
  160. mpages.sort(key=lambda p: int(p["position"]))
  161. for p in mpages:
  162. printMenuItem(p, False, True, True)
  163. def printQuadcopterMenu():
  164. mpages = [p for p in pages if p.get("parent", "") == "quadcopters" and p.lang == "en"]
  165. mpages.sort(key=lambda p: int(p["position"]))
  166. for p in mpages:
  167. printMenuItem(p, False, True, True)
  168. def printQuadcopterRelatedMenu():
  169. mpages = [p for p in pages if p.get("show_in_quadcopters", "false") == "true"]
  170. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  171. for p in mpages:
  172. printMenuItem(p, False, True, True)
  173. def printRobotMenuEnglish():
  174. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "en"]
  175. mpages.sort(key=lambda p: int(p["position"]))
  176. for p in mpages:
  177. printMenuItem(p)
  178. def printRobotMenuDeutsch():
  179. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "de"]
  180. mpages.sort(key=lambda p: int(p["position"]))
  181. for p in mpages:
  182. printMenuItem(p, False, False, False, False, "0", "de")
  183. # -----------------------------------------------------------------------------
  184. # lightgallery helper macro
  185. # -----------------------------------------------------------------------------
  186. # call this macro like this:
  187. # lightgallery([
  188. # [ "image-link", "description" ],
  189. # [ "image-link", "thumbnail-link", "description" ],
  190. # [ "youtube-link", "thumbnail-link", "description" ],
  191. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ],
  192. # [ "video-link", "mime", "", "", "description" ],
  193. # ])
  194. # it will also auto-generate thumbnails and resize and strip EXIF from images
  195. # using the included web-image-resize script.
  196. # and it can generate video thumbnails and posters with the video-thumb script.
  197. def lightgallery_check_thumbnail(link, thumb):
  198. # only check local image links
  199. if not link.startswith('img/'):
  200. return
  201. # generate thumbnail filename web-image-resize will create
  202. x = link.rfind('.')
  203. img = link[:x] + '_small' + link[x:]
  204. # only run when desired thumb path matches calculated ones
  205. if thumb != img:
  206. return
  207. # generate fs path to images
  208. path = os.path.join(os.getcwd(), 'static', link)
  209. img = os.path.join(os.getcwd(), 'static', thumb)
  210. # no need to generate thumb again
  211. if os.path.exists(img):
  212. return
  213. # run web-image-resize to generate thumbnail
  214. script = os.path.join(os.getcwd(), 'web-image-resize')
  215. os.system(script + ' ' + path)
  216. def lightgallery_check_thumbnail_video(link, thumb, poster):
  217. # only check local image links
  218. if not link.startswith('img/'):
  219. return
  220. # generate thumbnail filenames video-thumb will create
  221. x = link.rfind('.')
  222. thumb_l = link[:x] + '_thumb.png'
  223. poster_l = link[:x] + '_poster.png'
  224. # only run when desired thumb path matches calculated ones
  225. if (thumb_l != thumb) or (poster_l != poster):
  226. return
  227. # generate fs path to images
  228. path = os.path.join(os.getcwd(), 'static', link)
  229. thumb_p = os.path.join(os.getcwd(), 'static', thumb)
  230. poster_p = os.path.join(os.getcwd(), 'static', poster)
  231. # no need to generate thumb again
  232. if os.path.exists(thumb_p) or os.path.exists(poster_p):
  233. return
  234. # run video-thumb to generate thumbnail
  235. script = os.path.join(os.getcwd(), 'video-thumb')
  236. os.system(script + ' ' + path)
  237. def lightgallery(links):
  238. videos = [l for l in links if len(l) == 5]
  239. v_i = -1
  240. for v in videos:
  241. link, mime, thumb, poster, alt = v
  242. v_i += 1
  243. print '<div style="display:none;" id="video' + str(v_i) + '">'
  244. print '<video class="lg-video-object lg-html5" controls preload="none">'
  245. print '<source src="' + link + '" type="' + mime + '">'
  246. print 'Your browser does not support HTML5 video.'
  247. print '</video>'
  248. print '</div>'
  249. print '<div class="lightgallery">'
  250. v_i = -1
  251. for l in links:
  252. if (len(l) == 3) or (len(l) == 2):
  253. link = img = alt = ""
  254. if len(l) == 3:
  255. link, img, alt = l
  256. else:
  257. link, alt = l
  258. x = link.rfind('.')
  259. img = link[:x] + '_small' + link[x:]
  260. lightgallery_check_thumbnail(link, img)
  261. print '<div class="border" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"></a></div>'
  262. elif len(l) == 5:
  263. v_i += 1
  264. link, mime, thumb, poster, alt = videos[v_i]
  265. if len(thumb) <= 0:
  266. x = link.rfind('.')
  267. thumb = link[:x] + '_thumb.png'
  268. if len(poster) <= 0:
  269. x = link.rfind('.')
  270. poster = link[:x] + '_poster.png'
  271. lightgallery_check_thumbnail_video(link, thumb, poster)
  272. print '<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>'
  273. else:
  274. raise NameError('Invalid number of arguments for lightgallery')
  275. print '</div>'
  276. # -----------------------------------------------------------------------------
  277. # github helper macros
  278. # -----------------------------------------------------------------------------
  279. import urllib, json
  280. def restRequest(url):
  281. response = urllib.urlopen(url)
  282. if response.getcode() != 200:
  283. raise Exception("invalid response code", response.getcode())
  284. data = json.loads(response.read())
  285. return data
  286. def restReleases(user, repo):
  287. s = "https://api.github.com/repos/"
  288. s += user
  289. s += "/"
  290. s += repo
  291. s += "/releases"
  292. return restRequest(s)
  293. def printLatestRelease(user, repo):
  294. repo_url = "https://github.com/" + user + "/" + repo
  295. print("<div class=\"releasecard\">")
  296. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  297. releases = restReleases(user, repo)
  298. if len(releases) <= 0:
  299. print("No release has been published on GitHub yet.")
  300. print("</div>")
  301. return
  302. releases.sort(key=lambda x: x["published_at"], reverse=True)
  303. r = releases[0]
  304. release_url = r["html_url"]
  305. print("Latest release of <a href=\"" + repo_url + "\">" + repo + "</a>, at the time of this writing: <a href=\"" + release_url + "\">" + r["name"] + "</a> (" + datetime.strptime(r["published_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%Y-%m-%d %H:%M:%S") + ")\n")
  306. if len(r["assets"]) <= 0:
  307. print("<br>No release assets have been published on GitHub for that.")
  308. print("</div>")
  309. return
  310. print("<ul>")
  311. print("Release Assets:")
  312. for a in r["assets"]:
  313. size = int(a["size"])
  314. ss = " "
  315. if size >= (1024 * 1024):
  316. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  317. elif size >= 1024:
  318. ss += "(%d KiB)" % (size // 1024)
  319. else:
  320. ss += "(%d Byte)" % (size)
  321. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  322. print("</ul></div>")
  323. def include_url(url):
  324. response = urllib.urlopen(url)
  325. if response.getcode() != 200:
  326. raise Exception("invalid response code", response.getcode())
  327. data = response.read()
  328. print data,
  329. # -----------------------------------------------------------------------------
  330. # preconvert hooks
  331. # -----------------------------------------------------------------------------
  332. # -----------------------------------------------------------------------------
  333. # multi language support
  334. # -----------------------------------------------------------------------------
  335. def hook_preconvert_anotherlang():
  336. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  337. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  338. vpages = [] # Set of all virtual pages
  339. for p in pages:
  340. current_lang = DEFAULT_LANG # Default language
  341. langs = [] # List of languages for the current page
  342. page_vpages = {} # Set of virtual pages for the current page
  343. text_lang = re.split(_re_lang, p.source)
  344. text_grouped = dict(zip([current_lang,] + \
  345. [lang.strip() for lang in text_lang[1::2]], \
  346. text_lang[::2]))
  347. for lang, text in text_grouped.iteritems():
  348. spath = p.fname.split(os.path.sep)
  349. langs.append(lang)
  350. if lang == "en":
  351. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  352. else:
  353. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  354. vp = Page(filename, virtual=text)
  355. # Copy real page attributes to the virtual page
  356. for attr in p:
  357. if not vp.has_key(attr):
  358. vp[attr] = p[attr]
  359. # Define a title in the proper language
  360. vp["title"] = p["title_%s" % lang] \
  361. if p.has_key("title_%s" % lang) \
  362. else p["title"]
  363. # Keep track of the current lang of the virtual page
  364. vp["lang"] = lang
  365. page_vpages[lang] = vp
  366. # Each virtual page has to know about its sister vpages
  367. for lang, vpage in page_vpages.iteritems():
  368. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  369. vpage["other_lang"] = langs # set other langs and link
  370. vpages += page_vpages.values()
  371. pages[:] = vpages
  372. # -----------------------------------------------------------------------------
  373. # compatibility redirect for old website URLs
  374. # -----------------------------------------------------------------------------
  375. _COMPAT = """ case "%s":
  376. $loc = "%s/%s";
  377. break;
  378. """
  379. _COMPAT_404 = """ default:
  380. $loc = "%s";
  381. break;
  382. """
  383. def hook_preconvert_compat():
  384. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  385. fp.write("<?\n")
  386. fp.write("// Auto generated xyCMS compatibility index.php\n")
  387. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  388. fp.write("if (isset($_GET['p'])) {\n")
  389. fp.write(" if (isset($_GET['lang'])) {\n")
  390. fp.write(" $_GET['p'] .= 'EN';\n")
  391. fp.write(" }\n")
  392. fp.write(" switch($_GET['p']) {\n")
  393. for p in pages:
  394. if p.get("compat", "") != "":
  395. tmp = p["compat"]
  396. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  397. tmp = tmp + "EN"
  398. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  399. fp.write("\n")
  400. fp.write(_COMPAT_404 % "/404.html")
  401. fp.write(" }\n")
  402. fp.write("}\n")
  403. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  404. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  405. fp.write(" header('Status: 301 Moved Permanently');\n")
  406. fp.write(" } else {\n")
  407. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  408. fp.write(" }\n")
  409. fp.write("}\n");
  410. fp.write("header('Location: '.$loc);\n")
  411. fp.write("?>")
  412. fp.close()
  413. # -----------------------------------------------------------------------------
  414. # sitemap generation
  415. # -----------------------------------------------------------------------------
  416. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  417. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  418. %s
  419. </urlset>
  420. """
  421. _SITEMAP_URL = """
  422. <url>
  423. <loc>%s/%s</loc>
  424. <lastmod>%s</lastmod>
  425. <changefreq>%s</changefreq>
  426. <priority>%s</priority>
  427. </url>
  428. """
  429. def hook_preconvert_sitemap():
  430. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  431. urls = []
  432. for p in pages:
  433. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  434. fname = os.path.join(options.project, "output", "sitemap.xml")
  435. fp = open(fname, 'w')
  436. fp.write(_SITEMAP % "".join(urls))
  437. fp.close()
  438. # -----------------------------------------------------------------------------
  439. # postconvert hooks
  440. # -----------------------------------------------------------------------------
  441. # -----------------------------------------------------------------------------
  442. # rss feed generation
  443. # -----------------------------------------------------------------------------
  444. _RSS = """<?xml version="1.0" encoding="UTF-8"?>
  445. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  446. <channel>
  447. <title>%s</title>
  448. <link>%s</link>
  449. <atom:link href="%s" rel="self" type="application/rss+xml" />
  450. <description>%s</description>
  451. <language>en-us</language>
  452. <pubDate>%s</pubDate>
  453. <lastBuildDate>%s</lastBuildDate>
  454. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  455. <generator>Poole</generator>
  456. <ttl>720</ttl>
  457. %s
  458. </channel>
  459. </rss>
  460. """
  461. _RSS_ITEM = """
  462. <item>
  463. <title>%s</title>
  464. <link>%s</link>
  465. <description>%s</description>
  466. <pubDate>%s</pubDate>
  467. <atom:updated>%s</atom:updated>
  468. <guid>%s</guid>
  469. </item>
  470. """
  471. def hook_postconvert_rss():
  472. items = []
  473. # all pages with "date" get put into feed
  474. posts = [p for p in pages if "date" in p]
  475. # sort by update if available, date else
  476. posts.sort(key=lambda p: p.get("update", p.date), reverse=True)
  477. # only put 20 most recent items in feed
  478. posts = posts[:20]
  479. for p in posts:
  480. title = p.title
  481. if "post" in p:
  482. title = p.post
  483. link = "%s/%s" % (BASE_URL, p.url)
  484. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  485. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  486. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  487. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  488. desc = htmlspecialchars(desc)
  489. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  490. date = email.utils.formatdate(date)
  491. update = time.mktime(time.strptime("%s 12" % p.get("update", p.date), "%Y-%m-%d %H"))
  492. update = email.utils.formatdate(update)
  493. items.append(_RSS_ITEM % (title, link, desc, date, update, link))
  494. items = "".join(items)
  495. title = "xythobuz.de Blog"
  496. link = "%s" % BASE_URL
  497. feed = "%s/rss.xml" % BASE_URL
  498. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  499. date = email.utils.formatdate()
  500. rss = _RSS % (title, link, feed, desc, date, date, items)
  501. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  502. fp.write(rss)
  503. fp.close()
  504. # -----------------------------------------------------------------------------
  505. # compatibility redirect for old mobile pages
  506. # -----------------------------------------------------------------------------
  507. _COMPAT_MOB = """ case "%s":
  508. $loc = "%s/%s";
  509. break;
  510. """
  511. _COMPAT_404_MOB = """ default:
  512. $loc = "%s";
  513. break;
  514. """
  515. def hook_postconvert_mobilecompat():
  516. directory = os.path.join(output, "mobile")
  517. if not os.path.exists(directory):
  518. os.makedirs(directory)
  519. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  520. fp.write("<?\n")
  521. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  522. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  523. fp.write("if (isset($_GET['p'])) {\n")
  524. fp.write(" if (isset($_GET['lang'])) {\n")
  525. fp.write(" $_GET['p'] .= 'EN';\n")
  526. fp.write(" }\n")
  527. fp.write(" switch($_GET['p']) {\n")
  528. for p in pages:
  529. if p.get("compat", "") != "":
  530. tmp = p["compat"]
  531. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  532. tmp = tmp + "EN"
  533. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  534. fp.write("\n")
  535. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  536. fp.write(" }\n")
  537. fp.write("}\n")
  538. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  539. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  540. fp.write(" header('Status: 301 Moved Permanently');\n")
  541. fp.write(" } else {\n")
  542. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  543. fp.write(" }\n")
  544. fp.write("}\n");
  545. fp.write("header('Location: '.$loc);\n")
  546. fp.write("?>")
  547. fp.close()
  548. # -----------------------------------------------------------------------------
  549. # displaying filesize for download links
  550. # -----------------------------------------------------------------------------
  551. def hook_postconvert_size():
  552. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'plist'])
  553. def matched_link(matchobj):
  554. try:
  555. path = matchobj.group(1)
  556. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  557. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  558. elif path.startswith("/"):
  559. path = path.strip("/")
  560. path = os.path.join("static/", path)
  561. size = os.path.getsize(path)
  562. if size >= (1024 * 1024):
  563. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  564. elif size >= 1024:
  565. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  566. else:
  567. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  568. except:
  569. print "Unable to estimate file size for %s" % matchobj.group(1)
  570. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  571. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  572. for p in pages:
  573. p.html = re.sub(_re_url, matched_link, p.html)