1 #!/usr/bin/env python 2 3 """ 4 HTML linking scheme. 5 6 Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from moinformat.links.common import Linker, resolve 23 from urllib import quote, quote_plus 24 from urlparse import urlparse 25 26 class HTMLLinker(Linker): 27 28 "Translate Moin links into HTML links." 29 30 name = "html" 31 32 def get_top_level(self): 33 34 "Return a relative link to the top level." 35 36 # The root page is at the top level already. 37 38 pagename = self.metadata.get("pagename", "") 39 40 if pagename == self.root_pagename: 41 return "" 42 43 # Siblings of the root page are actually one level below. 44 45 levels = pagename.count("/") + 1 46 return "/".join([".."] * levels) 47 48 def is_url(self, target): 49 50 "Return whether the 'target' references a URL." 51 52 scheme, host, path, params, query, fragment = urlparse(target) 53 return scheme and target or None 54 55 def normalise(self, path): 56 57 "Return a normalised form of 'path'." 58 59 return not path.endswith("/") and "%s/" % path or path 60 61 def translate(self, target): 62 63 """ 64 Translate the 'target', returning a tuple containing the rewritten 65 target string and a suitable default label. 66 """ 67 68 target = target.rstrip("/") 69 70 # Fragments. Remove the leading hash for the label. 71 72 if target.startswith("#"): 73 return self.quote(target), target.lstrip("#") 74 75 # Sub-pages. Remove the leading slash for the label. 76 77 if target.startswith("/"): 78 return self.translate_pagename(target), target.lstrip("/") 79 80 # Sibling (of ancestor) pages. 81 82 if target.startswith("../"): 83 return self.translate_pagename(target), None 84 85 # Attachment or interwiki link. 86 87 rewritten = self.translate_qualified_link(target) 88 if rewritten: 89 return rewritten # includes label 90 91 # Plain URL. 92 93 rewritten = self.is_url(target) 94 if rewritten: 95 return rewritten, None 96 97 # Top-level pages. 98 99 return self.translate_pagename(target), None 100 101 def translate_pagename(self, target): 102 103 "Translate the pagename in 'target'." 104 105 # Obtain the target pagename and the fragment. 106 # Split the pagename into path components. 107 108 t = target.split("#", 1) 109 p = t[0].rstrip("/").split("/") 110 111 # Determine the actual pagename referenced. 112 # Replace the root pagename if it appears. 113 114 pagename = self.metadata.get("pagename", "") 115 resolved = resolve(t[0], pagename, self.root_pagename) 116 117 # Rewrite the target using a relative link to the top level and then the 118 # resolved pagename. 119 120 top_level = self.get_top_level() 121 t[0] = "%s%s" % (top_level and "%s/" % top_level or "", resolved) 122 123 return self.quote("#".join(t)) 124 125 def translate_qualified_link(self, target): 126 127 """ 128 Translate a possible qualified link 'target', returning a tuple 129 containing a rewritten target and a suitable default label. 130 131 Return None if the link is not suitable. 132 """ 133 134 t = target.split(":", 1) 135 if len(t) != 2: 136 return None 137 138 prefix, target = t 139 140 # Attachment links. 141 142 if prefix == "attachment": 143 return self.translate_attachment(target), target 144 145 # Interwiki links. 146 147 url = self.mapping.get(prefix) 148 if url: 149 return self.translate_interwiki(url, target), target 150 151 return None 152 153 # Specific link translators. 154 155 def translate_attachment(self, target): 156 157 "Return a translation of the given attachment 'target'." 158 159 return self.quote("./attachments/%s" % target) 160 161 def translate_interwiki(self, url, target): 162 163 "Return a translation of the given interwiki 'target'." 164 165 return "%s%s" % (self.normalise(url), self.quote(target)) 166 167 # Path encoding. 168 169 def quote(self, s): 170 171 """ 172 Quote URL path 's', preserving path separators and fragment indicators, 173 encoding fragment identifiers. 174 """ 175 176 parts = s.split("#", 1) 177 178 if len(parts) > 1: 179 parts[1] = self.make_id(parts[1]) 180 181 return "#".join(map(quote, parts)) 182 183 # Identifier encoding. 184 185 def make_id(self, s): 186 187 "Make a suitable identifier for HTML element identification." 188 189 # NOTE: This reproduces the Moin algorithm for compatibility. 190 # NOTE: There may well be improvements possible, possibly by replacing plus 191 # NOTE: with something less cumbersome, even though plus may be unusual in 192 # NOTE: things like headings, anyway. 193 194 # The desired output is the following pattern: 195 196 # [A-Za-z][-_:.A-Za-z0-9]* 197 198 # The Python UTF-7 encoder preserves symbols and it encodes + as +- with an 199 # output range as follows (in addition to A-Za-z0-9): 200 201 # -_:.%+ !"#$&\'()*,/;<=>?@[]^`{|} 202 203 # The quote_plus function converts space to plus, preserves -_:. and encodes 204 # all other symbols (including original occurrences of plus and percent) and 205 # non-alphanumeric (ASCII) characters using percent encoding. 206 207 # With colons preserved, the resulting output is in the following range 208 # (in addition to A-Za-z0-9): 209 210 # -_:.%+ 211 212 # Percent will only occur as an encoding prefix. Plus will only occur as a 213 # replacement for space. 214 215 # Combining quote_plus and UTF-7 gives the following range (in addition to 216 # A-Za-z0-9): 217 218 # -_:.%+ 219 220 # Examples: 221 222 # UTF-7 quote_plus replace percent and plus 223 # : -> : -> : -> : 224 # - -> - -> - -> - 225 # . -> . -> . -> . 226 # % -> % -> %25 -> .25 227 # + -> +- -> %2B- -> .2B- 228 # _ -> _ -> _ -> _ 229 # space -> space -> + -> _ 230 231 # See: RFC2152 - UTF-7 A Mail-Safe Transformation Format of Unicode 232 233 quoted = quote_plus(s.encode("utf-7"), ":").replace("%", ".").replace("+", "_") 234 235 # Ensure that the identifier starts with an alphabetical character. 236 237 if not quoted[0].isalpha(): 238 return "A%s" % quoted 239 else: 240 return quoted 241 242 linker = HTMLLinker 243 244 # vim: tabstop=4 expandtab shiftwidth=4