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 30KB

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