My static website generator using poole https://www.xythobuz.de
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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