参考:

让MoinMoin支持上传中文文件名的附件

http://www.linuxsir.org/bbs/thread368571.html

在1.9.7中修改解决。

 

MOINMOINWIKI1.9.7+WIN2012 X64

 

  1. # -*- coding: iso-8859-1 -*-
  2. """
  3.     MoinMoin - AttachFile action
  4.  
  5.     This action lets a page have multiple attachment files.
  6.     It creates a folder <data>/pages/<pagename>/attachments
  7.     and keeps everything in there.
  8.  
  9.     Form values: action=Attachment
  10.     1. with no 'do' key: returns file upload form
  11.     2. do=attach: accept file upload and saves the file in
  12.        ../attachment/pagename/
  13.     3. /pagename/fname?action=Attachment&do=get[&mimetype=type]:
  14.        return contents of the attachment file with the name fname.
  15.     4. /pathname/fname, do=view[&mimetype=type]:create a page
  16.        to view the content of the file
  17.  
  18.     To link to an attachment, use [[attachment:file.txt]],
  19.     to embed an attachment, use {{attachment:file.png}}.
  20.  
  21.     @copyright: 2001 by Ken Sugino (sugino@mediaone.net),
  22.                 2001-2004 by Juergen Hermann <jh@web.de>,
  23.                 2005 MoinMoin:AlexanderSchremmer,
  24.                 2005 DiegoOngaro at ETSZONE (diego@etszone.com),
  25.                 2005-2013 MoinMoin:ReimarBauer,
  26.                 2007-2008 MoinMoin:ThomasWaldmann
  27.     @license: GNU GPL, see COPYING for details.
  28. """
  29.  
  30. import os, time, zipfile, errno, datetime
  31. from StringIO import StringIO
  32.  
  33. from werkzeug import http_date
  34.  
  35. from MoinMoin import log
  36. logging = log.getLogger(__name__)
  37.  
  38. # keep both imports below as they are, order is important:
  39. from MoinMoin import wikiutil
  40. import mimetypes
  41.  
  42. from MoinMoin import config, packages
  43. from MoinMoin.Page import Page
  44. from MoinMoin.util import filesys, timefuncs
  45. from MoinMoin.security.textcha import TextCha
  46. from MoinMoin.events import FileAttachedEvent, FileRemovedEvent, send_event
  47. from MoinMoin.support import tarfile
  48.  
  49. action_name = __name__.split('.')[-1]
  50.  
  51. #############################################################################
  52. ### External interface - these are called from the core code
  53. #############################################################################
  54.  
  55. class AttachmentAlreadyExists(Exception):
  56.     pass
  57.  
  58.  
  59. def getBasePath(request):
  60.     """ Get base path where page dirs for attachments are stored. """
  61.     return request.rootpage.getPagePath('pages')
  62.  
  63.  
  64. def getAttachDir(request, pagename, create=0):
  65.     """ Get directory where attachments for page `pagename` are stored. """
  66.     if request.page and pagename == request.page.page_name:
  67.         page = request.page # reusing existing page obj is faster
  68.     else:
  69.         page = Page(request, pagename)
  70.     return page.getPagePath("attachments", check_create=create)
  71.  
  72.  
  73. def absoluteName(url, pagename):
  74.     """ Get (pagename, filename) of an attachment: link
  75.         @param url: PageName/filename.ext or filename.ext (unicode)
  76.         @param pagename: name of the currently processed page (unicode)
  77.         @rtype: tuple of unicode
  78.         @return: PageName, filename.ext
  79.     """
  80.     url = wikiutil.AbsPageName(pagename, url)
  81.     pieces = url.split(u'/')
  82.     if len(pieces) == 1:
  83.         return pagename, pieces[0]
  84.     else:
  85.         return u"/".join(pieces[:-1]), pieces[-1]
  86.  
  87.  
  88. def get_action(request, filename, do):
  89.     generic_do_mapping = {
  90.         # do -> action
  91.         'get': action_name,
  92.         'view': action_name,
  93.         'move': action_name,
  94.         'del': action_name,
  95.         'unzip': action_name,
  96.         'install': action_name,
  97.         'upload_form': action_name,
  98.     }
  99.     basename, ext = os.path.splitext(filename)
  100.     do_mapping = request.cfg.extensions_mapping.get(ext, {})
  101.     action = do_mapping.get(do, None)
  102.     if action is None:
  103.         # we have no special support for
    this,
  104.         # look up whether we have generic support:
  105.         action = generic_do_mapping.get(do, None)
  106.     return action
  107.  
  108.  
  109. def getAttachUrl(pagename, filename, request, addts=0, do='get'):
  110.     """ Get URL that points to attachment `filename` of page `pagename`.
  111.         For upload url, call with
    do='upload_form'.
  112.         Returns the URL to do the specified "do" action or None,
  113.         if
    this action is not supported.
  114.     """
  115.     action = get_action(request, filename, do)
  116.     if action:
  117.         args = dict(action=action, do=do, target=filename)
  118.         if
    do not in ['get', 'view', # harmless
  119.                       'modify', # just renders the applet html, which has own ticket
  120.                       'move', # renders rename form, which has own ticket
  121.             ]:
  122.             # create a ticket for the not so harmless operations
  123.             # we need action= here because the current action (e.g. "show" page
  124.             # with a macro AttachList) may not be the linked-to action, e.g.
  125.             # "AttachFile". Also, AttachList can list attachments of another page,
  126.             # thus we need to give pagename= also.
  127.             args['ticket'] = wikiutil.createTicket(request,
  128.                                                    pagename=pagename, action=action_name)
  129.         url = request.href(pagename, **args)
  130.         return url
  131.  
  132.  
  133. def getIndicator(request, pagename):
  134.     """ Get an attachment indicator for a page (linked clip image) or
  135.         an empty string if not attachments exist.
  136.     """
  137.     _ = request.getText
  138.     attach_dir = getAttachDir(request, pagename)
  139.     if not os.path.exists(attach_dir):
  140.         return ''
  141.  
  142.     files = os.listdir(attach_dir)
  143.     if not files:
  144.         return ''
  145.  
  146.     fmt = request.formatter
  147.     attach_count = _('[%d attachments]') % len(files)
  148.     attach_icon = request.theme.make_icon('attach', vars={'attach_count': attach_count})
  149.     attach_link = (fmt.url(1, request.href(pagename, action=action_name), rel='nofollow') +
  150.                    attach_icon +
  151.                    fmt.url(0))
  152.     return attach_link
  153.  
  154.  
  155. def getFilename(request, pagename, filename):
  156.     """ make complete pathfilename of file "name" attached to some page "pagename"
  157.         @param request: request object
  158.         @param pagename: name of page where the file is attached to (unicode)
  159.         @param filename: filename of attached file (unicode)
  160.         @rtype: string (in config.charset encoding)
  161.         @return: complete path/filename of attached file
  162.     """
  163.     if isinstance(filename, unicode):
  164.         #filename = filename.encode(config.charset)
  165.         filename = wikiutil.quoteWikinameFS(filename)
  166.     return os.path.join(getAttachDir(request, pagename, create=1), filename)
  167.  
  168.  
  169. def exists(request, pagename, filename):
  170.     """ check if page <pagename> has a file <filename> attached """
  171.     fpath = getFilename(request, pagename, filename)
  172.     return os.path.exists(fpath)
  173.  
  174.  
  175. def size(request, pagename, filename):
  176.     """ return file size of file attachment """
  177.     fpath = getFilename(request, pagename, filename)
  178.     return os.path.getsize(fpath)
  179.  
  180.  
  181. def info(pagename, request):
  182.     """ Generate snippet with info on the attachment for page `pagename`. """
  183.     _ = request.getText
  184.  
  185.     attach_dir = getAttachDir(request, pagename)
  186.     files = []
  187.     if os.path.isdir(attach_dir):
  188.         files = os.listdir(attach_dir)
  189.     page = Page(request, pagename)
  190.     link = page.url(request, {'action': action_name})
  191.     attach_info = _('There are <a href="%(link)s">%(count)s attachment(s)</a> stored for
    this page.') % {
  192.         'count': len(files),
  193.         'link': wikiutil.escape(link)
  194.         }
  195.     return "\n<p>\n%s\n</p>\n" % attach_info
  196.  
  197.  
  198. def _write_stream(content, stream, bufsize=8192):
  199.     if hasattr(content, 'read'): # looks file-like
  200.         import shutil
  201.         shutil.copyfileobj(content, stream, bufsize)
  202.     elif isinstance(content, str):
  203.         stream.write(content)
  204.     else:
  205.         logging.error("unsupported content object: %r" % content)
  206.         raise
  207.  
  208. def add_attachment(request, pagename, target, filecontent, overwrite=0):
  209.     """ save <filecontent> to an attachment <target> of page <pagename>
  210.  
  211.         filecontent can be either a str (in memory file content),
  212.         or an open file object (file content in e.g. a tempfile).
  213.     """
  214.     # replace illegal chars
  215.     #target = wikiutil.taintfilename(target)
  216.     target = wikiutil.quoteWikinameFS(wikiutil.taintfilename(target))
  217.  
  218.  
  219.     # get directory, and possibly create it
  220.     attach_dir = getAttachDir(request, pagename, create=1)
  221.     #fpath = os.path.join(attach_dir, target).encode(config.charset)
  222.     fpath = os.path.join(attach_dir, target)
  223.  
  224.     exists = os.path.exists(fpath)
  225.     if exists:
  226.         if overwrite:
  227.             remove_attachment(request, pagename, target)
  228.         else:
  229.             raise AttachmentAlreadyExists
  230.  
  231.     # save file
  232.     stream = open(fpath, 'wb')
  233.     try:
  234.         _write_stream(filecontent, stream)
  235.     finally:
  236.         stream.close()
  237.  
  238.     _addLogEntry(request, 'ATTNEW', pagename, target)
  239.  
  240.     filesize = os.path.getsize(fpath)
  241.     event = FileAttachedEvent(request, pagename, target, filesize)
  242.     send_event(event)
  243.  
  244.     return target, filesize
  245.  
  246.  
  247. def remove_attachment(request, pagename, target):
  248.     """ remove attachment <target> of page <pagename>
  249.     """
  250.     # replace illegal chars
  251.     target = wikiutil.taintfilename(target)
  252.     #target = wikiutil.quoteWikinameFS(wikiutil.taintfilename(target))
  253.  
  254.     # get directory, do not create it
  255.     attach_dir = getAttachDir(request, pagename, create=0)
  256.     # remove file
  257.     #fpath = os.path.join(attach_dir, target).encode(config.charset)
  258.     fpath = os.path.join(attach_dir, wikiutil.quoteWikinameFS(target))
  259.     try:
  260.         filesize = os.path.getsize(fpath)
  261.         os.remove(fpath)
  262.     except:
  263.         # either it is gone already or we have no rights - not much we can do about it
  264.         filesize = 0
  265.     else:
  266.         _addLogEntry(request, 'ATTDEL', pagename, target)
  267.  
  268.         event = FileRemovedEvent(request, pagename, target, filesize)
  269.         send_event(event)
  270.  
  271.     return target, filesize
  272.  
  273.  
  274. #############################################################################
  275. ### Internal helpers
  276. #############################################################################
  277.  
  278. def _addLogEntry(request, action, pagename, filename):
  279.     """ Add an entry to the edit log on uploads and deletes.
  280.  
  281.         `action` should be "ATTNEW" or "ATTDEL"
  282.     """
  283.     from MoinMoin.logfile import editlog
  284.     t = wikiutil.timestamp2version(time.time())
  285.     fname = wikiutil.url_quote(filename)
  286.  
  287.     # Write to global log
  288.     log = editlog.EditLog(request)
  289.     log.add(request, t, 99999999, action, pagename, request.remote_addr, fname)
  290.  
  291.     # Write to local log
  292.     log = editlog.EditLog(request, rootpagename=pagename)
  293.     log.add(request, t, 99999999, action, pagename, request.remote_addr, fname)
  294.  
  295.  
  296. def _access_file(pagename, request):
  297.     """ Check form parameter `target` and return a tuple of
  298.         `(pagename, filename, filepath)` for an existing attachment.
  299.  
  300.         Return `(pagename, None, None)` if an error occurs.
  301.     """
  302.     _ = request.getText
  303.  
  304.     error = None
  305.     if not request.values.get('target'):
  306.         error = _("Filename of attachment not specified!")
  307.     else:
  308.         filename = wikiutil.taintfilename(request.values['target'])
  309.         fpath = getFilename(request, pagename, filename)
  310.  
  311.         if os.path.isfile(fpath):
  312.             return (pagename, filename, fpath)
  313.         error = _("Attachment '%(filename)s' does not exist!") % {'filename': filename}
  314.  
  315.     error_msg(pagename, request, error)
  316.     return (pagename, None, None)
  317.  
  318.  
  319. def _build_filelist(request, pagename, showheader, readonly, mime_type='*', filterfn=None):
  320.     _ = request.getText
  321.     fmt = request.html_formatter
  322.  
  323.     # access directory
  324.     attach_dir = getAttachDir(request, pagename)
  325.     files = _get_files(request, pagename)
  326.  
  327.     if mime_type != '*':
  328.         files = [fname for fname in files if mime_type == mimetypes.guess_type(fname)[0]]
  329.     if filterfn is not None:
  330.         files = [fname for fname in files if filterfn(fname)]
  331.  
  332.     html = []
  333.     if files:
  334.         if showheader:
  335.             html.append(fmt.rawHTML(_(
  336.                 "To refer to attachments on a page, use '''{{{attachment:filename}}}''', \n"
  337.                 "as shown below in the list of files. \n"
  338.                 "Do '''NOT''' use the URL of the {{{[get]}}} link, \n"
  339.                 "since this is subject to change and can break easily.",
  340.                 wiki=True
  341.             )))
  342.  
  343.         label_del = _("del")
  344.         label_move = _("move")
  345.         label_get = _("get")
  346.         label_edit = _("edit")
  347.         label_view = _("view")
  348.         label_unzip = _("unzip")
  349.         label_install = _("install")
  350.  
  351.         may_read = request.user.may.read(pagename)
  352.         may_write = request.user.may.write(pagename)
  353.         may_delete = request.user.may.delete(pagename)
  354.  
  355.         html.append(fmt.bullet_list(1))
  356.         for file in files:
  357.             mt = wikiutil.MimeType(filename=file)
  358.             #fullpath = os.path.join(attach_dir, file).encode(config.charset)
  359.             fullpath = os.path.join(attach_dir, wikiutil.quoteWikinameFS(file))
  360.             st = os.stat(fullpath)
  361.             base, ext = os.path.splitext(file)
  362.             parmdict = {'file': wikiutil.escape(file),
  363.                         'fsize': "%.1f" % (float(st.st_size) / 1024),
  364.                         'fmtime': request.user.getFormattedDateTime(st.st_mtime),
  365.                        }
  366.  
  367.             links = []
  368.             if may_delete and not readonly:
  369.                 links.append(fmt.url(1, getAttachUrl(pagename, file, request, do='del')) +
  370.                              fmt.text(label_del) +
  371.                              fmt.url(0))
  372.  
  373.             if may_delete and not readonly:
  374.                 links.append(fmt.url(1, getAttachUrl(pagename, file, request, do='move')) +
  375.                              fmt.text(label_move) +
  376.                              fmt.url(0))
  377.  
  378.             links.append(fmt.url(1, getAttachUrl(pagename, file, request)) +
  379.                          fmt.text(label_get) +
  380.                          fmt.url(0))
  381.  
  382.             links.append(fmt.url(1, getAttachUrl(pagename, file, request, do='view')) +
  383.                          fmt.text(label_view) +
  384.                          fmt.url(0))
  385.  
  386.             if may_write and not readonly:
  387.                 edit_url = getAttachUrl(pagename, file, request, do='modify')
  388.                 if edit_url:
  389.                     links.append(fmt.url(1, edit_url) +
  390.                                  fmt.text(label_edit) +
  391.                                  fmt.url(0))
  392.  
  393.             try:
  394.                 is_zipfile = zipfile.is_zipfile(fullpath)
  395.                 if is_zipfile and not readonly:
  396.                     is_package = packages.ZipPackage(request, fullpath).isPackage()
  397.                     if is_package and request.user.isSuperUser():
  398.                         links.append(fmt.url(1, getAttachUrl(pagename, file, request, do='install')) +
  399.                                      fmt.text(label_install) +
  400.                                      fmt.url(0))
  401.                     elif (not is_package and mt.minor == 'zip' and
  402.                           may_read and may_write and may_delete):
  403.                         links.append(fmt.url(1, getAttachUrl(pagename, file, request, do='unzip')) +
  404.                                      fmt.text(label_unzip) +
  405.                                      fmt.url(0))
  406.             except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile):
  407.                 # We don't want to crash with a traceback here (an exception
  408.                 # here could be caused by an uploaded defective zip file - and
  409.                 # if we crash here, the user does not get a UI to remove the
  410.                 # defective zip file again).
  411.                 # RuntimeError is raised by zipfile stdlib module in
    case of
  412.                 # problems (like inconsistent slash and backslash usage in the
  413.                 # archive).
  414.                 # BadZipfile/LargeZipFile are raised when there are some
  415.                 # specific problems with the archive file.
  416.                 logging.exception("An exception within zip file attachment handling occurred:")
  417.  
  418.             html.append(fmt.listitem(1))
  419.             html.append("[%s]" % "&nbsp;| ".join(links))
  420.             html.append(" (%(fmtime)s, %(fsize)s KB) [[attachment:%(file)s]]" % parmdict)
  421.             html.append(fmt.listitem(0))
  422.         html.append(fmt.bullet_list(0))
  423.  
  424.     else:
  425.         if showheader:
  426.             html.append(fmt.paragraph(1))
  427.             html.append(fmt.text(_("No attachments stored for %(pagename)s") % {
  428.                                    'pagename': pagename}))
  429.             html.append(fmt.paragraph(0))
  430.  
  431.     return ''.join(html)
  432.  
  433.  
  434. def _get_files(request, pagename):
  435.     attach_dir = getAttachDir(request, pagename)
  436.     if os.path.isdir(attach_dir):
  437.         #files = [fn.decode(config.charset) for fn in os.listdir(attach_dir)]
  438.         files = [wikiutil.unquoteWikiname(fn) for fn in os.listdir(attach_dir)]
  439.         files.sort()
  440.     else:
  441.         files = []
  442.     return files
  443.  
  444.  
  445. def _get_filelist(request, pagename):
  446.     return _build_filelist(request, pagename, 1, 0)
  447.  
  448.  
  449. def error_msg(pagename, request, msg):
  450.     msg = wikiutil.escape(msg)
  451.     request.theme.add_msg(msg, "error")
  452.     Page(request, pagename).send_page()
  453.  
  454.  
  455. #############################################################################
  456. ### Create parts of the Web interface
  457. #############################################################################
  458.  
  459. def send_link_rel(request, pagename):
  460.     files = _get_files(request, pagename)
  461.     for fname in files:
  462.         url = getAttachUrl(pagename, fname, request, do='view')
  463.         request.write(u'<link rel="Appendix" title="%s" href="%s">\n' % (
  464.                       wikiutil.escape(fname, 1),
  465.                       wikiutil.escape(url, 1)))
  466.  
  467. def send_uploadform(pagename, request):
  468.     """ Send the HTML code for the list of already stored attachments and
  469.         the file upload form.
  470.     """
  471.     _ = request.getText
  472.  
  473.     if not request.user.may.read(pagename):
  474.         request.write('<p>%s</p>' % _('You are not allowed to view this page.'))
  475.         return
  476.  
  477.     writeable = request.user.may.write(pagename)
  478.  
  479.     # First send out the upload new attachment form on top of everything else.
  480.     # This avoids usability issues if you have to scroll down a lot to upload
  481.     # a new file when the page already has lots of attachments:
  482.     if writeable:
  483.         request.write('<h2>' + _("New Attachment") + '</h2>')
  484.         request.write("""
  485. <form action="%(url)s" method="POST" enctype="multipart/form-data">
  486. <dl>
  487. <dt>%(upload_label_file)s</dt>
  488. <dd><input type=""></dd>
  489. <dt>%(upload_label_target)s</dt>
  490. <dd><input type="" value="%(target)s"></dd>
  491. <dt>%(upload_label_overwrite)s</dt>
  492. <dd><input type="" %(overwrite_checked)s></dd>
  493. </dl>
  494. %(textcha)s
  495. <p>
  496. <input type="hidden" name="action" value="%(action_name)s">
  497. <input type="hidden" name="do" value="upload">
  498. <input type="hidden" name="ticket" value="%(ticket)s">
  499. <input type="submit" value="%(upload_button)s">
  500. </p>
  501. </form>
  502. """ % {
  503.     'url': request.href(pagename),
  504.     'action_name': action_name,
  505.     'upload_label_file': _('File to upload'),
  506.     'upload_label_target': _('Rename to'),
  507.     'target': wikiutil.escape(request.values.get('target', ''), 1),
  508.     'upload_label_overwrite': _('Overwrite existing attachment of same name'),
  509.     'overwrite_checked': ('', 'checked')[request.form.get('overwrite', '0') == '1'],
  510.     'upload_button': _('Upload'),
  511.     'textcha': TextCha(request).render(),
  512.     'ticket': wikiutil.createTicket(request),
  513. })
  514.  
  515.     request.write('<h2>' + _("Attached Files") + '</h2>')
  516.     request.write(_get_filelist(request, pagename))
  517.  
  518.     if not writeable:
  519.         request.write('<p>%s</p>' % _('You are not allowed to attach a file to this page.'))
  520.  
  521. #############################################################################
  522. ### Web interface
    for file upload, viewing and deletion
  523. #############################################################################
  524.  
  525. def execute(pagename, request):
  526.     """ Main dispatcher for the 'AttachFile' action. """
  527.     _ = request.getText
  528.  
  529.     do = request.values.get('do', 'upload_form')
  530.     handler = globals().get('_do_%s' % do)
  531.     if handler:
  532.         msg = handler(pagename, request)
  533.     else:
  534.         msg = _('Unsupported AttachFile sub-action: %s') % do
  535.     if msg:
  536.         error_msg(pagename, request, msg)
  537.  
  538.  
  539. def _do_upload_form(pagename, request):
  540.     upload_form(pagename, request)
  541.  
  542.  
  543. def upload_form(pagename, request, msg=''):
  544.     if msg:
  545.         msg = wikiutil.escape(msg)
  546.     _ = request.getText
  547.  
  548.     # Use user interface language for
    this generated page
  549.     request.setContentLanguage(request.lang)
  550.     request.theme.add_msg(msg, "dialog")
  551.     request.theme.send_title(_('Attachments for "%(pagename)s"') % {'pagename': pagename}, pagename=pagename)
  552.     request.write('<div id="content">\n') # start content div
  553.     send_uploadform(pagename, request)
  554.     request.write('</div>\n') # end content div
  555.     request.theme.send_footer(pagename)
  556.     request.theme.send_closing_html()
  557.  
  558.  
  559. def _do_upload(pagename, request):
  560.     _ = request.getText
  561.  
  562.     if not wikiutil.checkTicket(request, request.form.get('ticket', '')):
  563.         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.upload' }
  564.  
  565.     # Currently we only check TextCha for upload (this is what spammers ususally do),
  566.     # but it could be extended to more/all attachment write access
  567.     if not TextCha(request).check_answer_from_form():
  568.         return _('TextCha: Wrong answer! Go back and try again...')
  569.  
  570.     form = request.form
  571.  
  572.     file_upload = request.files.get('file')
  573.     if not file_upload:
  574.         # This might happen when trying to upload file names
  575.         # with non-ascii characters on Safari.
  576.         return _("No file content. Delete non ASCII characters from the file name and try again.")
  577.  
  578.     try:
  579.         overwrite = int(form.get('overwrite', '0'))
  580.     except:
  581.         overwrite = 0
  582.  
  583.     if not request.user.may.write(pagename):
  584.         return _('You are not allowed to attach a file to this page.')
  585.  
  586.     if overwrite and not request.user.may.delete(pagename):
  587.         return _('You are not allowed to overwrite a file attachment of this page.')
  588.  
  589.     target = form.get('target', u'').strip()
  590.     if not target:
  591.         target = file_upload.filename or u''
  592.  
  593.     target = wikiutil.clean_input(target)
  594.  
  595.     if not target:
  596.         return _("Filename of attachment not specified!")
  597.  
  598.     # add the attachment
  599.     try:
  600.         target, bytes = add_attachment(request, pagename, target, file_upload.stream, overwrite=overwrite)
  601.         msg = _("Attachment '%(target)s' (remote name '%(filename)s')"
  602.                 " with %(bytes)d bytes saved.") % {
  603.                 #'target': target, 'filename': file_upload.filename, 'bytes': bytes}
  604.         'target': wikiutil.unquoteWikiname(target), 'filename': file_upload.filename, 'bytes': bytes}
  605.  
  606.     except AttachmentAlreadyExists:
  607.         msg = _("Attachment '%(target)s' (remote name '%(filename)s') already exists.") % {
  608.           # 'target': target, 'filename': file_upload.filename}
  609.             'target': wikiutil.unquoteWikiname(target), 'filename': file_upload.filename}
  610.  
  611.     # return attachment list
  612.     upload_form(pagename, request, msg)
  613.  
  614.  
  615. class ContainerItem:
  616.     """ A storage container (multiple objects in 1 tarfile) """
  617.  
  618.     def __init__(self, request, pagename, containername):
  619.         """
  620.         @param pagename: a wiki page name
  621.         @param containername: the filename of the tar file.
  622.                               Make sure this is a simple filename, NOT containing any path components.
  623.                               Use wikiutil.taintfilename() to avoid somebody giving a container
  624.                               name that starts with e.g. ../../filename or you'll create a
  625.                               directory traversal and code execution vulnerability.
  626.         """
  627.         self.request = request
  628.         self.pagename = pagename
  629.         self.containername = containername
  630.         self.container_filename = getFilename(request, pagename, containername)
  631.  
  632.     def member_url(self, member):
  633.         """ return URL for accessing container member
  634.             (we use same URL for get (GET) and put (POST))
  635.         """
  636.         url = Page(self.request, self.pagename).url(self.request, {
  637.             'action': 'AttachFile',
  638.             'do': 'box', # shorter to type than 'container'
  639.             'target': self.containername,
  640.             #'member': member,
  641.         })
  642.         return url + '&member=%s' % member
  643.         # member needs to be last in qs because twikidraw looks for "file extension" at the end
  644.  
  645.     def get(self, member):
  646.         """ return a file-like object with the member file data
  647.         """
  648.         tf = tarfile.TarFile(self.container_filename)
  649.         return tf.extractfile(member)
  650.  
  651.     def put(self, member, content, content_length=None):
  652.         """ save data into a container's member """
  653.         tf = tarfile.TarFile(self.container_filename, mode='a')
  654.         if isinstance(member, unicode):
  655.             member = member.encode('utf-8')
  656.         ti = tarfile.TarInfo(member)
  657.         if isinstance(content, str):
  658.             if content_length is None:
  659.                 content_length = len(content)
  660.             content = StringIO(content) # we need a file obj
  661.         elif not hasattr(content, 'read'):
  662.             logging.error("unsupported content object: %r" % content)
  663.             raise
  664.         assert content_length >= 0 # we don't want -1 interpreted as 4G-1
  665.         ti.size = content_length
  666.         tf.addfile(ti, content)
  667.         tf.close()
  668.  
  669.     def truncate(self):
  670.         f = open(self.container_filename, 'w')
  671.         f.close()
  672.  
  673.     def exists(self):
  674.         return os.path.exists(self.container_filename)
  675.  
  676. def _do_del(pagename, request):
  677.     _ = request.getText
  678.  
  679.     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  680.         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.del' }
  681.  
  682.     pagename, filename, fpath = _access_file(pagename, request)
  683.     if not request.user.may.delete(pagename):
  684.         return _('You are not allowed to delete attachments on this page.')
  685.     if not filename:
  686.         return # error msg already sent in _access_file
  687.  
  688.     remove_attachment(request, pagename, filename)
  689.  
  690.     upload_form(pagename, request, msg=_("Attachment '%(filename)s' deleted.") % {'filename': filename})
  691.  
  692.  
  693. def move_file(request, pagename, new_pagename, attachment, new_attachment):
  694.     """
  695.     move a file attachment from pagename:attachment to new_pagename:new_attachment
  696.  
  697.     @param pagename: original pagename
  698.     @param new_pagename: new pagename (may be same as original pagename)
  699.     @param attachment: original attachment filename
  700.                        note: attachment filename must not contain a path,
  701.                              use wikiutil.taintfilename() before calling move_file
  702.     @param new_attachment: new attachment filename (may be same as original filename)
  703.                        note: attachment filename must not contain a path,
  704.                              use wikiutil.taintfilename() before calling move_file
  705.     """
  706.     _ = request.getText
  707.  
  708.     newpage = Page(request, new_pagename)
  709.     if newpage.exists(includeDeleted=1) and request.user.may.write(new_pagename) and request.user.may.delete(pagename):
  710.         new_attachment_path = os.path.join(getAttachDir(request, new_pagename,
  711.                               #create=1), new_attachment).encode(config.charset)
  712.                          create=1), wikiutil.quoteWikinameFS(new_attachment))
  713.         attachment_path = os.path.join(getAttachDir(request, pagename),
  714.                          # attachment).encode(config.charset)
  715.                                        wikiutil.quoteWikinameFS(attachment))
  716.  
  717.         if os.path.exists(new_attachment_path):
  718.             upload_form(pagename, request,
  719.                 msg=_("Attachment '%(new_pagename)s/%(new_filename)s' already exists.") % {
  720.                     'new_pagename': new_pagename,
  721.                     'new_filename': new_attachment})
  722.             return
  723.  
  724.         if new_attachment_path != attachment_path:
  725.             filesize = os.path.getsize(attachment_path)
  726.             filesys.rename(attachment_path, new_attachment_path)
  727.             _addLogEntry(request, 'ATTDEL', pagename, attachment)
  728.             event = FileRemovedEvent(request, pagename, attachment, filesize)
  729.             send_event(event)
  730.             _addLogEntry(request, 'ATTNEW', new_pagename, new_attachment)
  731.             event = FileAttachedEvent(request, new_pagename, new_attachment, filesize)
  732.             send_event(event)
  733.             upload_form(pagename, request,
  734.                         msg=_("Attachment '%(pagename)s/%(filename)s' moved to '%(new_pagename)s/%(new_filename)s'.") % {
  735.                             'pagename': pagename,
  736.                             'filename': attachment,
  737.                             'new_pagename': new_pagename,
  738.                             'new_filename': new_attachment})
  739.         else:
  740.             upload_form(pagename, request, msg=_("Nothing changed"))
  741.     else:
  742.         upload_form(pagename, request, msg=_("Page '%(new_pagename)s' does not exist or you don't have enough rights.") % {
  743.             'new_pagename': new_pagename})
  744.  
  745.  
  746. def _do_attachment_move(pagename, request):
  747.     _ = request.getText
  748.  
  749.     if 'cancel' in request.form:
  750.         return _('Move aborted!')
  751.     if not wikiutil.checkTicket(request, request.form.get('ticket', '')):
  752.         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.move' }
  753.     if not request.user.may.delete(pagename):
  754.         return _('You are not allowed to move attachments from this page.')
  755.  
  756.     if 'newpagename' in request.form:
  757.         new_pagename = request.form.get('newpagename')
  758.     else:
  759.         upload_form(pagename, request, msg=_("Move aborted because new page name is empty."))
  760.     if 'newattachmentname' in request.form:
  761.         new_attachment = request.form.get('newattachmentname')
  762.         if new_attachment != wikiutil.taintfilename(new_attachment):
  763.             upload_form(pagename, request, msg=_("Please use a valid filename for attachment '%(filename)s'.") % {
  764.                                   'filename': new_attachment})
  765.             return
  766.     else:
  767.         upload_form(pagename, request, msg=_("Move aborted because new attachment name is empty."))
  768.  
  769.     attachment = request.form.get('oldattachmentname')
  770.     if attachment != wikiutil.taintfilename(attachment):
  771.         upload_form(pagename, request, msg=_("Please use a valid filename for attachment '%(filename)s'.") % {
  772.                               'filename': attachment})
  773.         return
  774.     move_file(request, pagename, new_pagename, attachment, new_attachment)
  775.  
  776.  
  777. def _do_move(pagename, request):
  778.     _ = request.getText
  779.  
  780.     pagename, filename, fpath = _access_file(pagename, request)
  781.     if not request.user.may.delete(pagename):
  782.         return _('You are not allowed to move attachments from this page.')
  783.     if not filename:
  784.         return # error msg already sent in _access_file
  785.  
  786.     # move file
  787.     d = {'action': action_name,
  788.          'url': request.href(pagename),
  789.          'do': 'attachment_move',
  790.          'ticket': wikiutil.createTicket(request),
  791.          'pagename': wikiutil.escape(pagename, 1),
  792.          'attachment_name': wikiutil.escape(filename, 1),
  793.          'move': _('Move'),
  794.          'cancel': _('Cancel'),
  795.          'newname_label': _("New page name"),
  796.          'attachment_label': _("New attachment name"),
  797.         }
  798.     formhtml = '''
  799. <form action="%(url)s" method="POST">
  800. <input type="hidden" name="action" value="%(action)s">
  801. <input type="hidden" name="do" value="%(do)s">
  802. <input type="hidden" name="ticket" value="%(ticket)s">
  803. <table>
  804.     <tr>
  805.         <td class="label"><label>%(newname_label)s</label></td>
  806.         <td class="content">
  807.             <input type="">
  808.         </td>
  809.     </tr>
  810.     <tr>
  811.         <td class="label"><label>%(attachment_label)s</label></td>
  812.         <td class="content">
  813.             <input type="">
  814.         </td>
  815.     </tr>
  816.     <tr>
  817.         <td></td>
  818.         <td class="buttons">
  819.             <input type="hidden" name="oldattachmentname" value="%(attachment_name)s">
  820.             <input type="submit" name="move" value="%(move)s">
  821.             <input type="submit" name="cancel" value="%(cancel)s">
  822.         </td>
  823.     </tr>
  824. </table>
  825. </form>''' % d
  826.     thispage = Page(request, pagename)
  827.     request.theme.add_msg(formhtml, "dialog")
  828.     return thispage.send_page()
  829.  
  830.  
  831. def _do_box(pagename, request):
  832.     _ = request.getText
  833.  
  834.     pagename, filename, fpath = _access_file(pagename, request)
  835.     if not request.user.may.read(pagename):
  836.         return _('You are not allowed to get attachments from this page.')
  837.     if not filename:
  838.         return # error msg already sent in _access_file
  839.  
  840.     timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
  841.     if_modified = request.if_modified_since
  842.     if if_modified and if_modified >= timestamp:
  843.         request.status_code = 304
  844.     else:
  845.         ci = ContainerItem(request, pagename, filename)
  846.         filename = wikiutil.taintfilename(request.values['member'])
  847.         mt = wikiutil.MimeType(filename=filename)
  848.         content_type = mt.content_type()
  849.         mime_type = mt.mime_type()
  850.  
  851.         # TODO: fix the encoding here, plain 8 bit is not allowed according to the RFCs
  852.         # There is no solution that is compatible to IE except stripping non-ascii chars
  853.         #filename_enc = filename.encode(config.charset)
  854.         if 'MSIE' in request.http_user_agent:
  855.             filename_enc = filename.encode('gbk')
  856.         else:
  857.             filename_enc = filename.encode(config.charset)
  858.  
  859.         # for dangerous files (like .html), when we are in danger of cross-site-scripting attacks,
  860.         # we just let the user store them to disk ('attachment').
  861.         # For safe files, we directly show them inline (this also works better for IE).
  862.         dangerous = mime_type in request.cfg.mimetypes_xss_protect
  863.         content_dispo = dangerous and 'attachment' or 'inline'
  864.  
  865.         now = time.time()
  866.         request.headers['Date'] = http_date(now)
  867.         request.headers['Content-Type'] = content_type
  868.         request.headers['Last-Modified'] = http_date(timestamp)
  869.         request.headers['Expires'] = http_date(now - 365 * 24 * 3600)
  870.         #request.headers['Content-Length'] = os.path.getsize(fpath)
  871.         content_dispo_string = '%s; filename="%s"' % (content_dispo, filename_enc)
  872.         request.headers['Content-Disposition'] = content_dispo_string
  873.  
  874.         # send data
  875.         request.send_file(ci.get(filename))
  876.  
  877.  
  878. def _do_get(pagename, request):
  879.     _ = request.getText
  880.  
  881.     pagename, filename, fpath = _access_file(pagename, request)
  882.     if not request.user.may.read(pagename):
  883.         return _('You are not allowed to get attachments from this page.')
  884.     if not filename:
  885.         return # error msg already sent in _access_file
  886.  
  887.     timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
  888.     if_modified = request.if_modified_since
  889.     if if_modified and if_modified >= timestamp:
  890.         request.status_code = 304
  891.     else:
  892.         mt = wikiutil.MimeType(filename=filename)
  893.         content_type = mt.content_type()
  894.         mime_type = mt.mime_type()
  895.  
  896.         # TODO: fix the encoding here, plain 8 bit is not allowed according to the RFCs
  897.         # There is no solution that is compatible to IE except stripping non-ascii chars
  898.         #filename_enc = filename.encode(config.charset)
  899.         if 'MSIE' in request.http_user_agent:
  900.             filename_enc = filename.encode('gbk')
  901.         else:
  902.             filename_enc = filename.encode(config.charset)
  903.  
  904.         # for dangerous files (like .html), when we are in danger of cross-site-scripting attacks,
  905.         # we just let the user store them to disk ('attachment').
  906.         # For safe files, we directly show them inline (this also works better for IE).
  907.         dangerous = mime_type in request.cfg.mimetypes_xss_protect
  908.         content_dispo = dangerous and 'attachment' or 'inline'
  909.  
  910.         now = time.time()
  911.         request.headers['Date'] = http_date(now)
  912.         request.headers['Content-Type'] = content_type
  913.         request.headers['Last-Modified'] = http_date(timestamp)
  914.         request.headers['Expires'] = http_date(now - 365 * 24 * 3600)
  915.         request.headers['Content-Length'] = os.path.getsize(fpath)
  916.         content_dispo_string = '%s; filename="%s"' % (content_dispo, filename_enc)
  917.         request.headers['Content-Disposition'] = content_dispo_string
  918.  
  919.         # send data
  920.         request.send_file(open(fpath, 'rb'))
  921.  
  922.  
  923. def _do_install(pagename, request):
  924.     _ = request.getText
  925.  
  926.     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  927.         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.install' }
  928.  
  929.     pagename, target, targetpath = _access_file(pagename, request)
  930.     if not request.user.isSuperUser():
  931.         return _('You are not allowed to install files.')
  932.     if not target:
  933.         return
  934.  
  935.     package = packages.ZipPackage(request, targetpath)
  936.  
  937.     if
    package.isPackage():
  938.         if
    package.installPackage():
  939.             msg = _("Attachment '%(filename)s' installed.") % {'filename': target}
  940.         else:
  941.             msg = _("Installation of '%(filename)s' failed.") % {'filename': target}
  942.         if
    package.msg:
  943.             msg += "
    " + package.msg
  944.     else:
  945.         msg = _('The file %s is not a MoinMoin package file.') % target
  946.  
  947.     upload_form(pagename, request, msg=msg)
  948.  
  949.  
  950. def _do_unzip(pagename, request, overwrite=False):
  951.     _ = request.getText
  952.  
  953.     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  954.         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.unzip' }
  955.  
  956.     pagename, filename, fpath = _access_file(pagename, request)
  957.     if not (request.user.may.delete(pagename) and request.user.may.read(pagename) and request.user.may.write(pagename)):
  958.         return _('You are not allowed to unzip attachments of this page.')
  959.  
  960.     if not filename:
  961.         return # error msg already sent in _access_file
  962.  
  963.     try:
  964.         if not zipfile.is_zipfile(fpath):
  965.             return _('The file %(filename)s is not a .zip file.') % {'filename': filename}
  966.  
  967.         # determine how which attachment names we have and how much space each is occupying
  968.         curr_fsizes = dict([(f, size(request, pagename, f)) for f in _get_files(request, pagename)])
  969.  
  970.         # Checks for the existance of one common prefix path shared among
  971.         # all files in the zip file. If this is the case, remove the common prefix.
  972.         # We also prepare a dict of the new filenames->filesizes.
  973.         zip_path_sep = '/' # we assume '/' is as zip standard suggests
  974.         fname_index = None
  975.         mapping = []
  976.         new_fsizes = {}
  977.         zf = zipfile.ZipFile(fpath)
  978.         for zi in zf.infolist():
  979.             name = zi.filename
  980.             if not name.endswith(zip_path_sep): # a file (not a directory)
  981.                 if fname_index is None:
  982.                     fname_index = name.rfind(zip_path_sep) + 1
  983.                     path = name[:fname_index]
  984.                 if (name.rfind(zip_path_sep) + 1 != fname_index # different prefix len
  985.                     or
  986.                     name[:fname_index] != path): # same len, but still different
  987.                     mapping = [] # zip is not acceptable
  988.                     break
  989.                 if zi.file_size >= request.cfg.unzip_single_file_size: # file too big
  990.                     mapping = [] # zip is not acceptable
  991.                     break
  992.                 finalname = name[fname_index:] # remove common path prefix
  993.                 finalname = finalname.decode(config.charset, 'replace') # replaces trash with \uFFFD char
  994.                 mapping.append((name, finalname))
  995.                 new_fsizes[finalname] = zi.file_size
  996.  
  997.         # now we either have an empty mapping (if the zip is not acceptable),
  998.         # an identity mapping (no subdirs in zip, just all flat), or
  999.         # a mapping (origname, finalname) where origname is the zip member filename
  1000.         # (including some prefix path) and finalname is a simple filename.
  1001.  
  1002.         # calculate resulting total file size / count after unzipping:
  1003.         if overwrite:
  1004.             curr_fsizes.update(new_fsizes)
  1005.             total = curr_fsizes
  1006.         else:
  1007.             new_fsizes.update(curr_fsizes)
  1008.             total = new_fsizes
  1009.         total_count = len(total)
  1010.         total_size = sum(total.values())
  1011.  
  1012.         if not mapping:
  1013.             msg = _("Attachment '%(filename)s' not unzipped because some files in the zip "
  1014.                     "are either not in the same directory or exceeded the single file size limit (%(maxsize_file)d kB)."
  1015.                    ) % {'filename': filename,
  1016.                         'maxsize_file': request.cfg.unzip_single_file_size / 1000, }
  1017.         elif total_size > request.cfg.unzip_attachments_space:
  1018.             msg = _("Attachment '%(filename)s' not unzipped because it would have exceeded "
  1019.                     "the per page attachment storage size limit (%(size)d kB).") % {
  1020.                         'filename': filename,
  1021.                         'size': request.cfg.unzip_attachments_space / 1000, }
  1022.         elif total_count > request.cfg.unzip_attachments_count:
  1023.             msg = _("Attachment '%(filename)s' not unzipped because it would have exceeded "
  1024.                     "the per page attachment count limit (%(count)d).") % {
  1025.                         'filename': filename,
  1026.                         'count': request.cfg.unzip_attachments_count, }
  1027.         else:
  1028.             not_overwritten = []
  1029.             for origname, finalname in mapping:
  1030.                 try:
  1031.                     # Note: reads complete zip member file into memory. ZipFile does not offer block-wise reading:
  1032.                     add_attachment(request, pagename, finalname, zf.read(origname), overwrite)
  1033.                 except AttachmentAlreadyExists:
  1034.                     not_overwritten.append(finalname)
  1035.             if not_overwritten:
  1036.                 msg = _("Attachment '%(filename)s' partially unzipped (did not overwrite: %(filelist)s).") % {
  1037.                         'filename': filename,
  1038.                         'filelist': ', '.join(not_overwritten), }
  1039.             else:
  1040.                 msg = _("Attachment '%(filename)s' unzipped.") % {'filename': filename}
  1041.     except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile), err:
  1042.         # We don't want to crash with a traceback here (an exception
  1043.         # here could be caused by an uploaded defective zip file - and
  1044.         # if we crash here, the user does not get a UI to remove the
  1045.         # defective zip file again).
  1046.         # RuntimeError is raised by zipfile stdlib module in
    case of
  1047.         # problems (like inconsistent slash and backslash usage in the
  1048.         # archive).
  1049.         # BadZipfile/LargeZipFile are raised when there are some
  1050.         # specific problems with the archive file.
  1051.         logging.exception("An exception within zip file attachment handling occurred:")
  1052.         msg = _("A severe error occurred:") + ' ' + str(err)
  1053.  
  1054.     upload_form(pagename, request, msg=msg)
  1055.  
  1056.  
  1057. def send_viewfile(pagename, request):
  1058.     _ = request.getText
  1059.     fmt = request.html_formatter
  1060.  
  1061.     pagename, filename, fpath = _access_file(pagename, request)
  1062.     if not filename:
  1063.         return
  1064.  
  1065.     request.write('<h2>' + _("Attachment '%(filename)s'") % {'filename': filename} + '</h2>')
  1066.     # show a download link above the content
  1067.     label = _('Download')
  1068.     link = (fmt.url(1, getAttachUrl(pagename, filename, request, do='get'), css_class="download") +
  1069.             fmt.text(label) +
  1070.             fmt.url(0))
  1071.     request.write('%s<br><br>' % link)
  1072.  
  1073.     if filename.endswith('.tdraw') or filename.endswith('.adraw'):
  1074.         request.write(fmt.attachment_drawing(filename, ''))
  1075.         return
  1076.  
  1077.     mt = wikiutil.MimeType(filename=filename)
  1078.  
  1079.     # destinguishs if browser need a plugin in place
  1080.     if mt.major == 'image' and mt.minor in config.browser_supported_images:
  1081.         url = getAttachUrl(pagename, filename, request)
  1082.         request.write('<img src="%s" alt="%s">' % (
  1083.             wikiutil.escape(url, 1),
  1084.             wikiutil.escape(filename, 1)))
  1085.         return
  1086.     elif mt.major == 'text':
  1087.         ext = os.path.splitext(filename)[1]
  1088.         Parser = wikiutil.getParserForExtension(request.cfg, ext)
  1089.         if Parser is not None:
  1090.             try:
  1091.                 content = file(fpath, 'r').read()
  1092.                 content = wikiutil.decodeUnknownInput(content)
  1093.                 colorizer = Parser(content, request, filename=filename)
  1094.                 colorizer.format(request.formatter)
  1095.                 return
  1096.             except IOError:
  1097.                 pass
  1098.  
  1099.         request.write(request.formatter.preformatted(1))
  1100.         # If we have text but no colorizing parser we try to decode file contents.
  1101.         content = open(fpath, 'r').read()
  1102.         content = wikiutil.decodeUnknownInput(content)
  1103.         content = wikiutil.escape(content)
  1104.         request.write(request.formatter.text(content))
  1105.         request.write(request.formatter.preformatted(0))
  1106.         return
  1107.  
  1108.     try:
  1109.         package = packages.ZipPackage(request, fpath)
  1110.         if
    package.isPackage():
  1111.             request.write("<pre><b>%s</b>\n%s</pre>" % (_("Package script:"), wikiutil.escape(package.getScript())))
  1112.             return
  1113.  
  1114.         if zipfile.is_zipfile(fpath) and mt.minor == 'zip':
  1115.             zf = zipfile.ZipFile(fpath, mode='r')
  1116.             request.write("<pre>%-46s %19s %12s\n" % (_("File Name"), _("Modified")+"
    "*5, _("Size")))
  1117.             for zinfo in zf.filelist:
  1118.                 date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time
  1119.                 request.write(wikiutil.escape("%-46s %s %12d\n" % (zinfo.filename, date, zinfo.file_size)))
  1120.             request.write("</pre>")
  1121.             return
  1122.     except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile):
  1123.         # We don't want to crash with a traceback here (an exception
  1124.         # here could be caused by an uploaded defective zip file - and
  1125.         # if we crash here, the user does not get a UI to remove the
  1126.         # defective zip file again).
  1127.         # RuntimeError is raised by zipfile stdlib module in
    case of
  1128.         # problems (like inconsistent slash and backslash usage in the
  1129.         # archive).
  1130.         # BadZipfile/LargeZipFile are raised when there are some
  1131.         # specific problems with the archive file.
  1132.         logging.exception("An exception within zip file attachment handling occurred:")
  1133.         return
  1134.  
  1135.     from MoinMoin import macro
  1136.     from MoinMoin.parser.text import Parser
  1137.  
  1138.     macro.request = request
  1139.     macro.formatter = request.html_formatter
  1140.     p = Parser("##\n", request)
  1141.     m = macro.Macro(p)
  1142.  
  1143.     # use EmbedObject to view valid mime types
  1144.     if mt is None:
  1145.         request.write('<p>' + _("Unknown file type, cannot display this attachment inline.") + '</p>')
  1146.         link = (fmt.url(1, getAttachUrl(pagename, filename, request)) +
  1147.                 fmt.text(filename) +
  1148.                 fmt.url(0))
  1149.         request.write('For using an external program follow this link %s' % link)
  1150.         return
  1151.     request.write(m.execute('EmbedObject', u'target="%s", pagename="%s"' % (filename, pagename)))
  1152.     return
  1153.  
  1154.  
  1155. def _do_view(pagename, request):
  1156.     _ = request.getText
  1157.  
  1158.     orig_pagename = pagename
  1159.     pagename, filename, fpath = _access_file(pagename, request)
  1160.     if not request.user.may.read(pagename):
  1161.         return _('You are not allowed to view attachments of this page.')
  1162.     if not filename:
  1163.         return
  1164.  
  1165.     request.formatter.page = Page(request, pagename)
  1166.  
  1167.     # send header & title
  1168.     # Use user interface language for
    this generated page
  1169.     request.setContentLanguage(request.lang)
  1170.     title = _('attachment:%(filename)s of %(pagename)s') % {
  1171.         'filename': filename, 'pagename': pagename}
  1172.     request.theme.send_title(title, pagename=pagename)
  1173.  
  1174.     # send body
  1175.     request.write(request.formatter.startContent())
  1176.     send_viewfile(orig_pagename, request)
  1177.     send_uploadform(pagename, request)
  1178.     request.write(request.formatter.endContent())
  1179.  
  1180.     request.theme.send_footer(pagename)
  1181.     request.theme.send_closing_html()
  1182.  
  1183.  
  1184. #############################################################################
  1185. ### File attachment administration
  1186. #############################################################################
  1187.  
  1188. def do_admin_browser(request):
  1189.     """ Browser for SystemAdmin macro. """
  1190.     from MoinMoin.util.dataset import TupleDataset, Column
  1191.     _ = request.getText
  1192.  
  1193.     data = TupleDataset()
  1194.     data.columns = [
  1195.         Column('page', label=('Page')),
  1196.         Column('file', label=('Filename')),
  1197.         Column('size', label=_('Size'), align='right'),
  1198.     ]
  1199.  
  1200.     # iterate over pages that might have attachments
  1201.     pages = request.rootpage.getPageList()
  1202.     for pagename in pages:
  1203.         # check for attachments directory
  1204.         page_dir = getAttachDir(request, pagename)
  1205.         if os.path.isdir(page_dir):
  1206.             # iterate over files of the page
  1207.             files = os.listdir(page_dir)
  1208.             for filename in files:
  1209.                 filepath = os.path.join(page_dir, filename)
  1210.                 data.addRow((
  1211.                     (Page(request, pagename).link_to(request,
  1212.                                 querystr="action=AttachFile"), wikiutil.escape(pagename, 1)),
  1213.                     #wikiutil.escape(filename.decode(config.charset)),
  1214.                     wikiutil.escape(wikiutil.unquoteWikiname(filename)),
  1215.                     os.path.getsize(filepath),
  1216.                 ))
  1217.  
  1218.     if data:
  1219.         from MoinMoin.widget.browser import DataBrowserWidget
  1220.  
  1221.         browser = DataBrowserWidget(request)
  1222.         browser.setData(data, sort_columns=[0, 1])
  1223.         return browser.render(method="GET")
  1224.  
  1225.     return ''

 

 

 

Moinmoin wiki 中文附件名的解决办法的更多相关文章

  1. PHPMailer发送邮件中文附件名是乱码

    可能使用了PHPMailer发送邮件的朋友带中文附件名时会出现乱码,下面我来介绍一个解决办法. 比如我们要发送的附件是"测试.txt",如果在添加附件的时候强制使用指定文件名的方式 ...

  2. linux中文显示乱码的解决办法

    linux中文显示乱码的解决办法 linux中文显示乱码是一件让人很头疼的事情. linux中文显示乱码的解决办法:[root@kk]#vi /etc/sysconfig/i18n将文件中的内容修改为 ...

  3. .NET在IE9中页面间URL传递中文变成乱码的解决办法

     在.Net的项目中,鼠标点击查询按钮,转到查询页面,但URL中包含中文时,传到服务器端后,中文变成了乱码(只有IE9出现该问题).       尝试使用Server.UrlEncode()进行编码, ...

  4. codeblocks中文乱码原因及解决办法

    原因:(本地化做得不够好)默认情况下codeblocks编辑器保存源文件是保存为windows本地编码,就是WINDOWS-936字符集,即GBK:但CB的编辑器在默认编辑的时候是按照UTF-8来解析 ...

  5. eclipse中js中文乱码问题的解决办法

    在Eclipse中编辑JS文件简直是一种折磨,但是却总是很无奈得要去适应. 这里说一下Eclipse中,编辑JS文件时候,出现中文乱码问题的解决办法. 这个问题很容易想到是文件编码的问题,因此通常是修 ...

  6. request.getParameter()获取URL中文参数乱码的解决办法

    这个问题耽误好长时间,URL传中文参数出现乱码,就算首次使用request接收就添加 request.setCharacterEncoding("UTf-8"); 依然报错不误. ...

  7. Firefox下载附件乱码的解决办法

    通过在http的header里设置fileName下载附件时,中文文件名通过chrome浏览器下载时正常,通过firefox下载时为乱码: 原来的Java代码: response.addHeader( ...

  8. Linux系统中关于Sqlite3中文乱码问题及解决办法

    新做的一个项目在本地(Win8)测试时没有问题,但传到服务器(Linux)时从Sqlite3数据库查询到的数据中文却是乱码(数据库中是正常的) 将php文件.html文件都设置成统一的utf8还是一样 ...

  9. 远程工具(SSH Secure)连接Centos出现中文乱码问题的解决办法

    问题原因 使用远程工具进行连接时,如果linux有中文文件或目录,显示时会出现乱码,原因是linux编码是UTF-8,而远程工具默认是当前系统本地编码即GBK.所以解决方案是统一两者编码就OK了,但是 ...

随机推荐

  1. C语言学习002:第一个完整的C程序代码

    #include <stdio.h>//引用相关的外部库,stdio.h包含了终端读写数据的代码 //程序入口,程序通过main函数的返回值判断程序是否运行成功,0表示成功,非0表示程序运 ...

  2. C# ~ 泛型委托

    泛型 应用 1.  比较 2 个对象的大小? 参考 1.  .NET面试题系列 - 对象大小比较:由一个泛型方法想到的 - 对象大小比较:

  3. 启用数据库的 Service Broker

    --is_broker_enabled为0未启用,为1启用SELECT name,is_broker_enabled FROM sys.databases WHERE name = 'DBNAME' ...

  4. jquery取消超链接

  5. JSON的简单例子

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 下载JSON所需要的jar文件并加入工程后,编写如下代码: package com.hzhi.json; ...

  6. python CGI编程Apache配置

    1. 编辑http.conf,添加两行,路径可以自定义 <Directory "C:/AppServ/www/cgi-bin"> AllowOverride None ...

  7. 通过rsync+inotify实现数据实时备份同步

    一.环境描述 测试环境 需求:服务器A与服务器B为主备服务模式,需要保持文件一致性,现采用sersync基于rsync+inotify实现数据实时同步 环境描述: 主服务器172.26.7.50 ,从 ...

  8. PDF.NET SOD 开源框架红包派送活动 && 新手快速入门指引

    一.框架的由来  快速入门 有关框架的更多信息,请看框架官方主页! 本套框架的思想是借鉴Java平台的Hibernate 和 iBatis 而来,兼有ORM和SQL-MAP的特性,同时还参考了后来.N ...

  9. something

    var colors=['red','green','yellow']; console.log(colors)//['red','green','yellow'] console.log(color ...

  10. FingerprintJS - 在浏览器端实现指纹识别

    FingerprintJS 是一个快速的浏览器指纹库,纯 JavaScript 实现,没有依赖关系.默认情况下,使用 Murmur Hash 算法返回一个32位整数.Hash 函数可以很容易地更换. ...