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 ItemSupport import ItemStore 15 from MoinMessage import GPG, is_encrypted, is_signed, MoinMessageError 16 from MoinMessageSupport import get_homedir, get_username_for_fingerprint 17 from MoinMoin.support.htmlmarkup import HTMLParseError, HTMLSanitizer, Markup 18 from MoinMoin import wikiutil 19 from email.parser import Parser 20 from codecs import getwriter 21 22 try: 23 from cStringIO import StringIO 24 except ImportError: 25 from StringIO import StringIO 26 27 _getFragments = getFragments 28 29 __version__ = "0.1" 30 31 # More Moin 1.9 compatibility functions. 32 33 def has_member(request, groupname, username): 34 if hasattr(request.dicts, "has_member"): 35 return request.dicts.has_member(groupname, username) 36 else: 37 return username in request.dicts.get(groupname, []) 38 39 # Fragments employ a "moinshare" attribute. 40 41 fragment_attribute = "moinshare" 42 43 def getFragments(s): 44 45 "Return all fragments in 's' having the MoinShare fragment attribute." 46 47 fragments = [] 48 for format, attributes, body in _getFragments(s): 49 if attributes.has_key(fragment_attribute): 50 fragments.append((format, attributes, body)) 51 return fragments 52 53 def getPreferredOutputTypes(request, mimetypes): 54 55 """ 56 Using the 'request', perform content negotiation, obtaining mimetypes common 57 to the fragment (given by 'mimetypes') and the client (found in the Accept 58 header). 59 """ 60 61 accept = getHeader(request, "Accept", "HTTP") 62 if accept: 63 prefs = getContentPreferences(accept) 64 return prefs.get_preferred_types(mimetypes) 65 else: 66 return mimetypes 67 68 def getUpdatedTime(metadata): 69 70 """ 71 Return the last updated time based on the given 'metadata', using the 72 current time if no explicit last modified time is specified. 73 """ 74 75 # NOTE: We could attempt to get the last edit time of a fragment. 76 77 latest_timestamp = metadata.get("last-modified") 78 if latest_timestamp: 79 return latest_timestamp 80 else: 81 return getCurrentTime() 82 83 # Entry/update classes. 84 85 class Update: 86 87 "A feed update entry." 88 89 def __init__(self): 90 self.title = None 91 self.link = None 92 self.content = None 93 self.content_type = None 94 self.updated = None 95 self.author = None 96 97 # Page-related attributes. 98 99 self.fragment = None 100 self.preferred = None 101 102 # Message-related attributes. 103 104 self.message_number = None 105 self.parts = None 106 107 # Message- and page-related attributes. 108 109 self.page = None 110 111 # Identification. 112 113 self.path = [] 114 115 def unique_id(self): 116 return "moinshare-tab-%s-%s" % (self.message_number, "-".join(map(str, self.path))) 117 118 def __cmp__(self, other): 119 if self.updated is None and other.updated is not None: 120 return 1 121 elif self.updated is not None and other.updated is None: 122 return -1 123 else: 124 return cmp(self.updated, other.updated) 125 126 def copy(self, part_number=None): 127 update = Update() 128 update.title = self.title 129 update.link = self.link 130 update.updated = self.updated 131 update.author = self.author 132 update.fragment = self.fragment 133 update.preferred = self.preferred 134 update.message_number = self.message_number 135 update.page = self.page 136 update.path = self.path[:] 137 if part_number is not None: 138 update.path.append(part_number) 139 return update 140 141 # Update retrieval from pages. 142 143 def getUpdatesFromPage(page, request): 144 145 """ 146 Get updates from the given 'page' using the 'request'. A list of update 147 objects is returned. 148 """ 149 150 updates = [] 151 152 # NOTE: Use the updated datetime from the page for updates. 153 # NOTE: The published and updated details would need to be deduced from 154 # NOTE: the page history instead of being taken from the page as a whole. 155 156 metadata = getMetadata(page) 157 updated = getUpdatedTime(metadata) 158 159 # Get the fragment regions for the page. 160 161 for n, (format, attributes, body) in enumerate(getFragments(page.get_raw_body())): 162 163 update = Update() 164 165 # Produce a fragment identifier. 166 # NOTE: Choose a more robust identifier where none is explicitly given. 167 168 update.fragment = attributes.get("fragment", str(n)) 169 update.title = attributes.get("summary", "Update #%d" % n) 170 171 # Get the preferred content types available for the fragment. 172 173 update.preferred = getPreferredOutputTypes(request, getOutputTypes(request, format)) 174 175 # Try and obtain some suitable content for the entry. 176 # NOTE: Could potentially get a summary for the fragment. 177 178 update.content = None 179 180 if "text/html" in update.preferred: 181 parser_cls = getParserClass(request, format) 182 183 if format == "html": 184 update.content = body 185 elif hasattr(parser_cls, "formatForOutputType"): 186 update.content = formatTextForOutputType(body, request, parser_cls, "text/html") 187 else: 188 fmt = request.html_formatter 189 fmt.setPage(page) 190 update.content = formatText(body, request, fmt, parser_cls) 191 192 update.content_type = "text/html" 193 194 update.page = page 195 196 # NOTE: The anchor would be supported in the page, but this requires 197 # NOTE: formatter modifications for the regions providing updates. 198 199 update.link = page.url(request, anchor=update.fragment) 200 update.updated = updated 201 202 updates.append(update) 203 204 return updates 205 206 # Update retrieval from message stores. 207 208 def getUpdatesFromStore(page, request): 209 210 """ 211 Get updates from the message store associated with the given 'page' using 212 the 'request'. A list of update objects is returned. 213 """ 214 215 updates = [] 216 217 metadata = getMetadata(page) 218 updated = getUpdatedTime(metadata) 219 220 store = ItemStore(page, "messages", "message-locks") 221 222 for n, message_text in enumerate(iter(store)): 223 update = getUpdateFromMessageText(message_text, n, request) 224 update.page = page 225 updates.append(update) 226 227 return updates 228 229 def getUpdateFromMessageText(message_text, message_number, request): 230 231 "Return an update for the given 'message_text' and 'message_number'." 232 233 update = Update() 234 message = Parser().parse(StringIO(message_text)) 235 236 # Produce a fragment identifier. 237 238 update.fragment = update.updated = getDateTimeFromRFC2822(message.get("date")) 239 update.title = message.get("subject", "Update #%d" % message_number) 240 update.author = message.get("moin-user") 241 242 update.message_number = message_number 243 244 update.content, update.content_type, update.parts, actual_author = \ 245 getUpdateContentFromPart(message, request) 246 247 if actual_author: 248 update.author = actual_author 249 250 return update 251 252 def getUpdateContentFromPart(part, request): 253 254 """ 255 Return decoded content, the content type, any subparts, and any author 256 identity in a tuple for a given 'part'. 257 """ 258 259 # Determine whether the part has several representations. 260 261 # For a single part, use it as the update content. 262 263 if not part.is_multipart(): 264 content, content_type = getPartContent(part) 265 return content, content_type, None, None 266 267 # For a collection of related parts, use the first as the update content 268 # and assume that the formatter will reference the other parts. 269 270 elif part.get_content_subtype() == "related": 271 main_part = part.get_payload()[0] 272 content, content_type = getPartContent(main_part) 273 return content, content_type, [main_part], None 274 275 # Encrypted content cannot be meaningfully separated. 276 277 elif part.get_content_subtype() == "encrypted": 278 try: 279 part, author = getDecryptedParts(part, request) 280 content, content_type, parts, _author = getUpdateContentFromPart(part, request) 281 return content, content_type, parts, author 282 except MoinMessageError: 283 return None, part.get_content_type(), part.get_payload(), None 284 285 # Otherwise, just obtain the parts for separate display. 286 287 else: 288 return None, part.get_content_type(), part.get_payload(), None 289 290 def getDecryptedParts(part, request): 291 292 "Decrypt the given 'part', returning the decoded content." 293 294 homedir = get_homedir(request) 295 gpg = GPG(homedir) 296 297 # Decrypt the part. 298 299 if is_encrypted(part): 300 text = gpg.decryptMessage(part) 301 part = Parser().parse(StringIO(text)) 302 303 # Extract any signature details. 304 305 if is_signed(part): 306 result = gpg.verifyMessage(part) 307 if result: 308 fingerprint, identity, content = result 309 return content, get_username_for_fingerprint(request, fingerprint) 310 311 return part, None 312 313 def getPartContent(part): 314 315 "Decode the 'part', returning the decoded payload and the content type." 316 317 charset = part.get_content_charset() 318 payload = part.get_payload(decode=True) 319 return (charset and unicode(payload, charset) or payload), part.get_content_type() 320 321 def getUpdateFromPart(parent, part, part_number, request): 322 323 "Using the 'parent' update, return an update object for the given 'part'." 324 325 update = parent.copy(part_number) 326 update.content, update.content_type, update.parts = getUpdateContentFromPart(part, request) 327 return update 328 329 def getUpdatesForFormatting(update, request): 330 331 "Get a list of updates for formatting given 'update'." 332 333 updates = [] 334 335 # Handle multipart/alternative and other non-related multiparts. 336 337 if update.parts: 338 for n, part in enumerate(update.parts): 339 update_part = getUpdateFromPart(update, part, n, request) 340 updates += getUpdatesForFormatting(update_part, request) 341 else: 342 updates.append(update) 343 344 return updates 345 346 # Update formatting. 347 348 def getFormattedUpdate(update, request, fmt): 349 350 """ 351 Return the formatted form of the given 'update' using the given 'request' 352 and 'fmt'. 353 """ 354 355 # NOTE: Some control over the HTML and XHTML should be exercised. 356 357 if update.content: 358 if update.content_type == "text/html" and update.message_number is not None: 359 parsers = [get_make_parser(update.page, update.message_number)] 360 else: 361 parsers = getParsersForContentType(request.cfg, update.content_type) 362 363 if parsers: 364 for parser_cls in parsers: 365 if hasattr(parser_cls, "formatForOutputType"): 366 return formatTextForOutputType(update.content, request, parser_cls, "text/html") 367 else: 368 return formatText(update.content, request, fmt, parser_cls=parser_cls) 369 break 370 else: 371 return None 372 else: 373 return None 374 375 def formatUpdate(update, request, fmt): 376 377 "Format the given 'update' using the given 'request' and 'fmt'." 378 379 result = [] 380 append = result.append 381 382 updates = getUpdatesForFormatting(update, request) 383 single = len(updates) == 1 384 385 # Format some navigation tabs. 386 387 if not single: 388 append(fmt.div(on=1, css_class="moinshare-alternatives")) 389 390 first = True 391 392 for update_part in updates: 393 append(fmt.url(1, "#%s" % update_part.unique_id())) 394 append(fmt.text(update_part.content_type)) 395 append(fmt.url(0)) 396 397 first = False 398 399 append(fmt.div(on=0)) 400 401 # Format the content. 402 403 first = True 404 405 for update_part in updates: 406 407 # Encapsulate each alternative if many exist. 408 409 if not single: 410 css_class = first and "moinshare-default" or "moinshare-other" 411 append(fmt.div(on=1, css_class="moinshare-alternative %s" % css_class, id=update_part.unique_id())) 412 413 # Include the content. 414 415 append(formatUpdatePart(update_part, request, fmt)) 416 417 if not single: 418 append(fmt.div(on=0)) 419 420 first = False 421 422 return "".join(result) 423 424 def formatUpdatePart(update, request, fmt): 425 426 "Format the given 'update' using the given 'request' and 'fmt'." 427 428 _ = request.getText 429 430 result = [] 431 append = result.append 432 433 # Encapsulate the content. 434 435 append(fmt.div(on=1, css_class="moinshare-content")) 436 text = getFormattedUpdate(update, request, fmt) 437 if text: 438 append(text) 439 else: 440 append(fmt.text(_("Update cannot be shown for content of type %s.") % update.content_type)) 441 append(fmt.div(on=0)) 442 443 return "".join(result) 444 445 # Source management. 446 447 def getUpdateSources(pagename, request): 448 449 "Return the update sources from the given 'pagename' using the 'request'." 450 451 sources = {} 452 453 source_definitions = getWikiDict(pagename, request) 454 455 if source_definitions: 456 for name, value in source_definitions.items(): 457 sources[name] = getSourceParameters(value) 458 459 return sources 460 461 def getSourceParameters(source_definition): 462 463 "Return the parameters from the given 'source_definition' string." 464 465 return parseDictEntry(source_definition, ("type", "location")) 466 467 # HTML parsing support. 468 469 class IncomingHTMLSanitizer(HTMLSanitizer): 470 471 "An HTML parser that rewrites references to attachments." 472 473 def __init__(self, out, request, page, message_number): 474 HTMLSanitizer.__init__(self, out) 475 self.request = request 476 self.message_number = message_number 477 self.page = page 478 479 def rewrite_reference(self, ref): 480 if ref.startswith("cid:"): 481 part = ref[len("cid:"):] 482 action_link = self.page.url(self.request, { 483 "action" : "ReadMessage", "doit" : "1", 484 "message" : self.message_number, "part" : part 485 }) 486 return action_link 487 else: 488 return ref 489 490 def handle_starttag(self, tag, attrs): 491 new_attrs = [] 492 for attrname, attrvalue in attrs: 493 if attrname in self.uri_attrs: 494 new_attrs.append((attrname, self.rewrite_reference(attrvalue))) 495 else: 496 new_attrs.append((attrname, attrvalue)) 497 HTMLSanitizer.handle_starttag(self, tag, new_attrs) 498 499 class IncomingMarkup(Markup): 500 501 "A special markup processor for incoming HTML." 502 503 def sanitize(self, request, page, message_number): 504 out = getwriter("utf-8")(StringIO()) 505 sanitizer = IncomingHTMLSanitizer(out, request, page, message_number) 506 sanitizer.feed(self.stripentities(keepxmlentities=True)) 507 return IncomingMarkup(unicode(out.getvalue(), "utf-8")) 508 509 class IncomingHTMLParser: 510 511 "Filters and rewrites incoming HTML content." 512 513 def __init__(self, raw, request, **kw): 514 self.raw = raw 515 self.request = request 516 self.message_number = None 517 self.page = None 518 519 def format(self, formatter, **kw): 520 521 "Send the text." 522 523 try: 524 self.request.write(formatter.rawHTML(IncomingMarkup(self.raw).sanitize(self.request, self.page, self.message_number))) 525 except HTMLParseError, e: 526 self.request.write(formatter.sysmsg(1) + 527 formatter.text(u'HTML parsing error: %s in "%s"' % (e.msg, 528 self.raw.splitlines()[e.lineno - 1].strip())) + 529 formatter.sysmsg(0)) 530 531 class MakeIncomingHTMLParser: 532 533 "A class that makes parsers configured for messages." 534 535 def __init__(self, page, message_number): 536 537 "Initialise with state that is used to configure instantiated parsers." 538 539 self.message_number = message_number 540 self.page = page 541 542 def __call__(self, *args, **kw): 543 parser = IncomingHTMLParser(*args, **kw) 544 parser.message_number = self.message_number 545 parser.page = self.page 546 return parser 547 548 def get_make_parser(page, message_number): 549 550 """ 551 Return a callable that will return a parser configured for the message from 552 the given 'page' with the given 'message_number'. 553 """ 554 555 return MakeIncomingHTMLParser(page, message_number) 556 557 # vim: tabstop=4 expandtab shiftwidth=4