Massively refactor the document() view.

This splits up the original monolithic document() view into quite a
few pieces. Many operations have been pulled out into standalone
utility functions, for ease of future maintenance and tracing the
control flow. Additionally, two of the original exit points (showing
deletion logs for a deleted Document, and showing a raw Document) have
been spun out into views of their own.

Along the way, some code has been cleaned up or tightened for better
Pythonic style, and the "set_common_headers" closure has been promoted
into its own standalone function, albeit with a different signature
than the original (the ability to pass in a set of response headers
and have them preserved was never actually used).
additional tweaks
Merge pull request #2076 from groovecoder/document-view-refactor

Document view refactor