My static website generator using poole https://www.xythobuz.de
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

macros.py 30KB

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