1 # -*- coding: iso-8859-1 -*- 2 """ 3 MoinMoin - MoinShare library 4 5 @copyright: 2011, 2012, 2013 by Paul Boddie <paul@boddie.org.uk> 6 @copyright: 2003-2006 Edgewall Software 7 @copyright: 2006 MoinMoin:AlexanderSchremmer 8 @license: GNU GPL (v2 or later), see COPYING.txt for details. 9 """ 10 11 from ContentTypeSupport import getContentPreferences 12 from DateSupport import getCurrentTime, getDateTimeFromRFC2822 13 from MoinSupport import * 14 from MoinMoin.support.htmlmarkup import HTMLParseError, HTMLSanitizer, Markup 15 from MoinMoin import wikiutil 16 from email.parser import Parser 17 from codecs import getwriter 18 19 try: 20 from cStringIO import StringIO 21 except ImportError: 22 from StringIO import StringIO 23 24 _getFragments = getFragments 25 26 __version__ = "0.1" 27 28 # More Moin 1.9 compatibility functions. 29 30 def has_member(request, groupname, username): 31 if hasattr(request.dicts, "has_member"): 32 return request.dicts.has_member(groupname, username) 33 else: 34 return username in request.dicts.get(groupname, []) 35 36 # Fragments employ a "moinshare" attribute. 37 38 fragment_attribute = "moinshare" 39 40 def getFragments(s): 41 42 "Return all fragments in 's' having the MoinShare fragment attribute." 43 44 fragments = [] 45 for format, attributes, body in _getFragments(s): 46 if attributes.has_key(fragment_attribute): 47 fragments.append((format, attributes, body)) 48 return fragments 49 50 def getPreferredOutputTypes(request, mimetypes): 51 52 """ 53 Using the 'request', perform content negotiation, obtaining mimetypes common 54 to the fragment (given by 'mimetypes') and the client (found in the Accept 55 header). 56 """ 57 58 accept = getHeader(request, "Accept", "HTTP") 59 if accept: 60 prefs = getContentPreferences(accept) 61 return prefs.get_preferred_types(mimetypes) 62 else: 63 return mimetypes 64 65 def getUpdatedTime(metadata): 66 67 """ 68 Return the last updated time based on the given 'metadata', using the 69 current time if no explicit last modified time is specified. 70 """ 71 72 # NOTE: We could attempt to get the last edit time of a fragment. 73 74 latest_timestamp = metadata.get("last-modified") 75 if latest_timestamp: 76 return latest_timestamp 77 else: 78 return getCurrentTime() 79 80 # Entry/update classes. 81 82 class Update: 83 84 "A feed update entry." 85 86 def __init__(self): 87 self.title = None 88 self.link = None 89 self.content = None 90 self.content_type = None 91 self.updated = None 92 93 # Page-related attributes. 94 95 self.fragment = None 96 self.preferred = None 97 98 # Message-related attributes. 99 100 self.message_number = None 101 self.parts = None 102 103 # Message- and page-related attributes. 104 105 self.page = None 106 107 # Identification. 108 109 self.path = [] 110 111 def unique_id(self): 112 return "moinshare-tab-%s-%s" % (self.message_number, "-".join(map(str, self.path))) 113 114 def __cmp__(self, other): 115 if self.updated is None and other.updated is not None: 116 return 1 117 elif self.updated is not None and other.updated is None: 118 return -1 119 else: 120 return cmp(self.updated, other.updated) 121 122 def copy(self, part_number=None): 123 update = Update() 124 update.title = self.title 125 update.link = self.link 126 update.updated = self.updated 127 update.fragment = self.fragment 128 update.preferred = self.preferred 129 update.message_number = self.message_number 130 update.page = self.page 131 update.path = self.path[:] 132 if part_number is not None: 133 update.path.append(part_number) 134 return update 135 136 # Update retrieval from pages. 137 138 def getUpdatesFromPage(page, request): 139 140 """ 141 Get updates from the given 'page' using the 'request'. A list of update 142 objects is returned. 143 """ 144 145 updates = [] 146 147 # NOTE: Use the updated datetime from the page for updates. 148 # NOTE: The published and updated details would need to be deduced from 149 # NOTE: the page history instead of being taken from the page as a whole. 150 151 metadata = getMetadata(page) 152 updated = getUpdatedTime(metadata) 153 154 # Get the fragment regions for the page. 155 156 for n, (format, attributes, body) in enumerate(getFragments(page.get_raw_body())): 157 158 update = Update() 159 160 # Produce a fragment identifier. 161 # NOTE: Choose a more robust identifier where none is explicitly given. 162 163 update.fragment = attributes.get("fragment", str(n)) 164 update.title = attributes.get("summary", "Update #%d" % n) 165 166 # Get the preferred content types available for the fragment. 167 168 update.preferred = getPreferredOutputTypes(request, getOutputTypes(request, format)) 169 170 # Try and obtain some suitable content for the entry. 171 # NOTE: Could potentially get a summary for the fragment. 172 173 update.content = None 174 175 if "text/html" in update.preferred: 176 parser_cls = getParserClass(request, format) 177 178 if format == "html": 179 update.content = body 180 elif hasattr(parser_cls, "formatForOutputType"): 181 update.content = formatTextForOutputType(body, request, parser_cls, "text/html") 182 else: 183 fmt = request.html_formatter 184 fmt.setPage(page) 185 update.content = formatText(body, request, fmt, parser_cls) 186 187 update.content_type = "text/html" 188 189 update.page = page 190 191 # NOTE: The anchor would be supported in the page, but this requires 192 # NOTE: formatter modifications for the regions providing updates. 193 194 update.link = page.url(request, anchor=update.fragment) 195 update.updated = updated 196 197 updates.append(update) 198 199 return updates 200 201 # Update retrieval from message stores. 202 203 def getUpdatesFromStore(page, request): 204 205 """ 206 Get updates from the message store associated with the given 'page' using 207 the 'request'. A list of update objects is returned. 208 """ 209 210 updates = [] 211 212 metadata = getMetadata(page) 213 updated = getUpdatedTime(metadata) 214 215 store = ItemStore(page, "messages", "message-locks") 216 217 for n, message_text in enumerate(iter(store)): 218 219 update = Update() 220 message = Parser().parse(StringIO(message_text)) 221 222 # Produce a fragment identifier. 223 224 update.fragment = update.updated = getDateTimeFromRFC2822(message.get("date")) 225 update.title = message.get("subject", "Update #%d" % n) 226 227 update.page = page 228 update.message_number = n 229 230 update.content, update.content_type, update.parts = getUpdateContentFromPart(message) 231 232 updates.append(update) 233 234 return updates 235 236 def getUpdateContentFromPart(part): 237 238 """ 239 Return decoded content, the content type and any subparts in a tuple for a 240 given 'part'. 241 """ 242 243 # Determine whether the part has several representations. 244 245 # For a single part, use it as the update content. 246 247 if not part.is_multipart(): 248 content, content_type = getPartContent(part) 249 return content, content_type, None 250 251 # For a collection of related parts, use the first as the update content 252 # and assume that the formatter will reference the other parts. 253 254 elif part.get_content_subtype() == "related": 255 main_part = part.get_payload()[0] 256 content, content_type = getPartContent(main_part) 257 return content, content_type, [main_part] 258 259 # Otherwise, just obtain the parts for separate display. 260 261 else: 262 return None, part.get_content_type(), part.get_payload() 263 264 def getPartContent(part): 265 266 "Decode the 'part', returning the decoded payload and the content type." 267 268 charset = part.get_content_charset() 269 payload = part.get_payload(decode=True) 270 return (charset and unicode(payload, charset) or payload), part.get_content_type() 271 272 def getUpdateFromPart(parent, part, part_number): 273 274 "Using the 'parent' update, return an update object for the given 'part'." 275 276 update = parent.copy(part_number) 277 update.content, update.content_type, update.parts = getUpdateContentFromPart(part) 278 return update 279 280 # Source management. 281 282 def getUpdateSources(pagename, request): 283 284 "Return the update sources from the given 'pagename' using the 'request'." 285 286 sources = {} 287 288 source_definitions = getWikiDict(pagename, request) 289 290 if source_definitions: 291 for name, value in source_definitions.items(): 292 sources[name] = getSourceParameters(value) 293 294 return sources 295 296 def getSourceParameters(source_definition): 297 298 "Return the parameters from the given 'source_definition' string." 299 300 return parseDictEntry(source_definition, ("type", "location")) 301 302 # HTML parsing support. 303 304 class IncomingHTMLSanitizer(HTMLSanitizer): 305 306 "An HTML parser that rewrites references to attachments." 307 308 def __init__(self, out, request, page, message_number): 309 HTMLSanitizer.__init__(self, out) 310 self.request = request 311 self.message_number = message_number 312 self.page = page 313 314 def rewrite_reference(self, ref): 315 if ref.startswith("cid:"): 316 part = ref[len("cid:"):] 317 action_link = self.page.url(self.request, { 318 "action" : "ReadMessage", "doit" : "1", 319 "message" : self.message_number, "part" : part 320 }) 321 return action_link 322 else: 323 return ref 324 325 def handle_starttag(self, tag, attrs): 326 new_attrs = [] 327 for attrname, attrvalue in attrs: 328 if attrname in self.uri_attrs: 329 new_attrs.append((attrname, self.rewrite_reference(attrvalue))) 330 else: 331 new_attrs.append((attrname, attrvalue)) 332 HTMLSanitizer.handle_starttag(self, tag, new_attrs) 333 334 class IncomingMarkup(Markup): 335 336 "A special markup processor for incoming HTML." 337 338 def sanitize(self, request, page, message_number): 339 out = getwriter("utf-8")(StringIO()) 340 sanitizer = IncomingHTMLSanitizer(out, request, page, message_number) 341 sanitizer.feed(self.stripentities(keepxmlentities=True)) 342 return IncomingMarkup(unicode(out.getvalue(), "utf-8")) 343 344 class IncomingHTMLParser: 345 346 "Filters and rewrites incoming HTML content." 347 348 def __init__(self, raw, request, **kw): 349 self.raw = raw 350 self.request = request 351 self.message_number = None 352 self.page = None 353 354 def format(self, formatter, **kw): 355 356 "Send the text." 357 358 try: 359 self.request.write(formatter.rawHTML(IncomingMarkup(self.raw).sanitize(self.request, self.page, self.message_number))) 360 except HTMLParseError, e: 361 self.request.write(formatter.sysmsg(1) + 362 formatter.text(u'HTML parsing error: %s in "%s"' % (e.msg, 363 self.raw.splitlines()[e.lineno - 1].strip())) + 364 formatter.sysmsg(0)) 365 366 class MakeIncomingHTMLParser: 367 368 "A class that makes parsers configured for messages." 369 370 def __init__(self, page, message_number): 371 372 "Initialise with state that is used to configure instantiated parsers." 373 374 self.message_number = message_number 375 self.page = page 376 377 def __call__(self, *args, **kw): 378 parser = IncomingHTMLParser(*args, **kw) 379 parser.message_number = self.message_number 380 parser.page = self.page 381 return parser 382 383 def get_make_parser(page, message_number): 384 385 """ 386 Return a callable that will return a parser configured for the message from 387 the given 'page' with the given 'message_number'. 388 """ 389 390 return MakeIncomingHTMLParser(page, message_number) 391 392 # vim: tabstop=4 expandtab shiftwidth=4