Moinmoin wiki 中文附件名的解决办法

参考:

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 /pages//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 ([email protected]),
  22.                 2001-2004 by Juergen Hermann ,
  23.                 2005 MoinMoin:AlexanderSchremmer,
  24.                 2005 DiegoOngaro at ETSZONE ([email protected]),
  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 has a file 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 %(link)s">%(count)s attachment(s) stored for this page.') % {
  192.         'count': len(files),
  193.         'link': wikiutil.escape(link)
  194.         }
  195.     return "\n

    \n%s\n

    \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 to an attachment of page
  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 of page
  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]" % " | ".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'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('

    %s

    ' % _('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('

    ' + _("New Attachment") + '

    ')
  484.         request.write("""
  485. %(url)s" method="POST" enctype="multipart/form-data">
  486. %(upload_label_file)s
  487. file" name="file" size="50">
  488. %(upload_label_target)s
  489. text" name="target" size="50" value="%(target)s">
  490. %(upload_label_overwrite)s
  491. checkbox" name="overwrite" value="1" %(overwrite_checked)s>
  492. %(textcha)s
  493. hidden" name="action" value="%(action_name)s">
  494. hidden" name="do" value="upload">
  495. hidden" name="ticket" value="%(ticket)s">
  496. submit" value="%(upload_button)s">
  497. """ % {
  498.     'url': request.href(pagename),
  499.     'action_name': action_name,
  500.     'upload_label_file': _('File to upload'),
  501.     'upload_label_target': _('Rename to'),
  502.     'target': wikiutil.escape(request.values.get('target', ''), 1),
  503.     'upload_label_overwrite': _('Overwrite existing attachment of same name'),
  504.     'overwrite_checked': ('', 'checked')[request.form.get('overwrite', '0') == '1'],
  505.     'upload_button': _('Upload'),
  506.     'textcha': TextCha(request).render(),
  507.     'ticket': wikiutil.createTicket(request),
  508. })
  509.  
  510.     request.write('

    ' + _("Attached Files") + '

    ')
  511.     request.write(_get_filelist(request, pagename))
  512.  
  513.     if not writeable:
  514.         request.write('

    %s

    ' % _('You are not allowed to attach a file to this page.'))
  515.  
  516. #############################################################################
  517. ### Web interface for file upload, viewing and deletion
  518. #############################################################################
  519.  
  520. def execute(pagename, request):
  521.     """ Main dispatcher for the 'AttachFile' action. """
  522.     _ = request.getText
  523.  
  524.     do = request.values.get('do', 'upload_form')
  525.     handler = globals().get('_do_%s' % do)
  526.     if handler:
  527.         msg = handler(pagename, request)
  528.     else:
  529.         msg = _('Unsupported AttachFile sub-action: %s') % do
  530.     if msg:
  531.         error_msg(pagename, request, msg)
  532.  
  533.  
  534. def _do_upload_form(pagename, request):
  535.     upload_form(pagename, request)
  536.  
  537.  
  538. def upload_form(pagename, request, msg=''):
  539.     if msg:
  540.         msg = wikiutil.escape(msg)
  541.     _ = request.getText
  542.  
  543.     # Use user interface language for this generated page
  544.     request.setContentLanguage(request.lang)
  545.     request.theme.add_msg(msg, "dialog")
  546.     request.theme.send_title(_('Attachments for "%(pagename)s"') % {'pagename': pagename}, pagename=pagename)
  547.     request.write('
    content">\n') # start content div
  548.     send_uploadform(pagename, request)
  549.     request.write('
    \n') # end content div
  •     request.theme.send_footer(pagename)
  •     request.theme.send_closing_html()
  •  
  •  
  • def _do_upload(pagename, request):
  •     _ = request.getText
  •  
  •     if not wikiutil.checkTicket(request, request.form.get('ticket', '')):
  •         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.upload' }
  •  
  •     # Currently we only check TextCha for upload (this is what spammers ususally do),
  •     # but it could be extended to more/all attachment write access
  •     if not TextCha(request).check_answer_from_form():
  •         return _('TextCha: Wrong answer! Go back and try again...')
  •  
  •     form = request.form
  •  
  •     file_upload = request.files.get('file')
  •     if not file_upload:
  •         # This might happen when trying to upload file names
  •         # with non-ascii characters on Safari.
  •         return _("No file content. Delete non ASCII characters from the file name and try again.")
  •  
  •     try:
  •         overwrite = int(form.get('overwrite', '0'))
  •     except:
  •         overwrite = 0
  •  
  •     if not request.user.may.write(pagename):
  •         return _('You are not allowed to attach a file to this page.')
  •  
  •     if overwrite and not request.user.may.delete(pagename):
  •         return _('You are not allowed to overwrite a file attachment of this page.')
  •  
  •     target = form.get('target', u'').strip()
  •     if not target:
  •         target = file_upload.filename or u''
  •  
  •     target = wikiutil.clean_input(target)
  •  
  •     if not target:
  •         return _("Filename of attachment not specified!")
  •  
  •     # add the attachment
  •     try:
  •         target, bytes = add_attachment(request, pagename, target, file_upload.stream, overwrite=overwrite)
  •         msg = _("Attachment '%(target)s' (remote name '%(filename)s')"
  •                 " with %(bytes)d bytes saved.") % {
  •                 #'target': target, 'filename': file_upload.filename, 'bytes': bytes}
  •         'target': wikiutil.unquoteWikiname(target), 'filename': file_upload.filename, 'bytes': bytes}
  •  
  •     except AttachmentAlreadyExists:
  •         msg = _("Attachment '%(target)s' (remote name '%(filename)s') already exists.") % {
  •           # 'target': target, 'filename': file_upload.filename}
  •             'target': wikiutil.unquoteWikiname(target), 'filename': file_upload.filename}
  •  
  •     # return attachment list
  •     upload_form(pagename, request, msg)
  •  
  •  
  • class ContainerItem:
  •     """ A storage container (multiple objects in 1 tarfile) """
  •  
  •     def __init__(self, request, pagename, containername):
  •         """
  •         @param pagename: a wiki page name
  •         @param containername: the filename of the tar file.
  •                               Make sure this is a simple filename, NOT containing any path components.
  •                               Use wikiutil.taintfilename() to avoid somebody giving a container
  •                               name that starts with e.g. ../../filename or you'll create a
  •                               directory traversal and code execution vulnerability.
  •         """
  •         self.request = request
  •         self.pagename = pagename
  •         self.containername = containername
  •         self.container_filename = getFilename(request, pagename, containername)
  •  
  •     def member_url(self, member):
  •         """ return URL for accessing container member
  •             (we use same URL for get (GET) and put (POST))
  •         """
  •         url = Page(self.request, self.pagename).url(self.request, {
  •             'action': 'AttachFile',
  •             'do': 'box', # shorter to type than 'container'
  •             'target': self.containername,
  •             #'member': member,
  •         })
  •         return url + '&member=%s' % member
  •         # member needs to be last in qs because twikidraw looks for "file extension" at the end
  •  
  •     def get(self, member):
  •         """ return a file-like object with the member file data
  •         """
  •         tf = tarfile.TarFile(self.container_filename)
  •         return tf.extractfile(member)
  •  
  •     def put(self, member, content, content_length=None):
  •         """ save data into a container's member """
  •         tf = tarfile.TarFile(self.container_filename, mode='a')
  •         if isinstance(member, unicode):
  •             member = member.encode('utf-8')
  •         ti = tarfile.TarInfo(member)
  •         if isinstance(content, str):
  •             if content_length is None:
  •                 content_length = len(content)
  •             content = StringIO(content) # we need a file obj
  •         elif not hasattr(content, 'read'):
  •             logging.error("unsupported content object: %r" % content)
  •             raise
  •         assert content_length >= 0 # we don't want -1 interpreted as 4G-1
  •         ti.size = content_length
  •         tf.addfile(ti, content)
  •         tf.close()
  •  
  •     def truncate(self):
  •         f = open(self.container_filename, 'w')
  •         f.close()
  •  
  •     def exists(self):
  •         return os.path.exists(self.container_filename)
  •  
  • def _do_del(pagename, request):
  •     _ = request.getText
  •  
  •     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  •         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.del' }
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not request.user.may.delete(pagename):
  •         return _('You are not allowed to delete attachments on this page.')
  •     if not filename:
  •         return # error msg already sent in _access_file
  •  
  •     remove_attachment(request, pagename, filename)
  •  
  •     upload_form(pagename, request, msg=_("Attachment '%(filename)s' deleted.") % {'filename': filename})
  •  
  •  
  • def move_file(request, pagename, new_pagename, attachment, new_attachment):
  •     """
  •     move a file attachment from pagename:attachment to new_pagename:new_attachment
  •  
  •     @param pagename: original pagename
  •     @param new_pagename: new pagename (may be same as original pagename)
  •     @param attachment: original attachment filename
  •                        note: attachment filename must not contain a path,
  •                              use wikiutil.taintfilename() before calling move_file
  •     @param new_attachment: new attachment filename (may be same as original filename)
  •                        note: attachment filename must not contain a path,
  •                              use wikiutil.taintfilename() before calling move_file
  •     """
  •     _ = request.getText
  •  
  •     newpage = Page(request, new_pagename)
  •     if newpage.exists(includeDeleted=1) and request.user.may.write(new_pagename) and request.user.may.delete(pagename):
  •         new_attachment_path = os.path.join(getAttachDir(request, new_pagename,
  •                               #create=1), new_attachment).encode(config.charset)
  •                          create=1), wikiutil.quoteWikinameFS(new_attachment))
  •         attachment_path = os.path.join(getAttachDir(request, pagename),
  •                          # attachment).encode(config.charset)
  •                                        wikiutil.quoteWikinameFS(attachment))
  •  
  •         if os.path.exists(new_attachment_path):
  •             upload_form(pagename, request,
  •                 msg=_("Attachment '%(new_pagename)s/%(new_filename)s' already exists.") % {
  •                     'new_pagename': new_pagename,
  •                     'new_filename': new_attachment})
  •             return
  •  
  •         if new_attachment_path != attachment_path:
  •             filesize = os.path.getsize(attachment_path)
  •             filesys.rename(attachment_path, new_attachment_path)
  •             _addLogEntry(request, 'ATTDEL', pagename, attachment)
  •             event = FileRemovedEvent(request, pagename, attachment, filesize)
  •             send_event(event)
  •             _addLogEntry(request, 'ATTNEW', new_pagename, new_attachment)
  •             event = FileAttachedEvent(request, new_pagename, new_attachment, filesize)
  •             send_event(event)
  •             upload_form(pagename, request,
  •                         msg=_("Attachment '%(pagename)s/%(filename)s' moved to '%(new_pagename)s/%(new_filename)s'.") % {
  •                             'pagename': pagename,
  •                             'filename': attachment,
  •                             'new_pagename': new_pagename,
  •                             'new_filename': new_attachment})
  •         else:
  •             upload_form(pagename, request, msg=_("Nothing changed"))
  •     else:
  •         upload_form(pagename, request, msg=_("Page '%(new_pagename)s' does not exist or you don't have enough rights.") % {
  •             'new_pagename': new_pagename})
  •  
  •  
  • def _do_attachment_move(pagename, request):
  •     _ = request.getText
  •  
  •     if 'cancel' in request.form:
  •         return _('Move aborted!')
  •     if not wikiutil.checkTicket(request, request.form.get('ticket', '')):
  •         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.move' }
  •     if not request.user.may.delete(pagename):
  •         return _('You are not allowed to move attachments from this page.')
  •  
  •     if 'newpagename' in request.form:
  •         new_pagename = request.form.get('newpagename')
  •     else:
  •         upload_form(pagename, request, msg=_("Move aborted because new page name is empty."))
  •     if 'newattachmentname' in request.form:
  •         new_attachment = request.form.get('newattachmentname')
  •         if new_attachment != wikiutil.taintfilename(new_attachment):
  •             upload_form(pagename, request, msg=_("Please use a valid filename for attachment '%(filename)s'.") % {
  •                                   'filename': new_attachment})
  •             return
  •     else:
  •         upload_form(pagename, request, msg=_("Move aborted because new attachment name is empty."))
  •  
  •     attachment = request.form.get('oldattachmentname')
  •     if attachment != wikiutil.taintfilename(attachment):
  •         upload_form(pagename, request, msg=_("Please use a valid filename for attachment '%(filename)s'.") % {
  •                               'filename': attachment})
  •         return
  •     move_file(request, pagename, new_pagename, attachment, new_attachment)
  •  
  •  
  • def _do_move(pagename, request):
  •     _ = request.getText
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not request.user.may.delete(pagename):
  •         return _('You are not allowed to move attachments from this page.')
  •     if not filename:
  •         return # error msg already sent in _access_file
  •  
  •     # move file
  •     d = {'action': action_name,
  •          'url': request.href(pagename),
  •          'do': 'attachment_move',
  •          'ticket': wikiutil.createTicket(request),
  •          'pagename': wikiutil.escape(pagename, 1),
  •          'attachment_name': wikiutil.escape(filename, 1),
  •          'move': _('Move'),
  •          'cancel': _('Cancel'),
  •          'newname_label': _("New page name"),
  •          'attachment_label': _("New attachment name"),
  •         }
  •     formhtml = '''
  • %(url)s" method="POST">
  • hidden" name="action" value="%(action)s">
  • hidden" name="do" value="%(do)s">
  • hidden" name="ticket" value="%(ticket)s">
  •     
  •         
  •         
  •     
  •     
  •         
  •         
  •     
  •     
  •         
  •         
  •     
  • class="label"> class="content">
  •             text" name="newpagename" value="%(pagename)s" size="80">
  •         
  • class="label"> class="content">
  •             text" name="newattachmentname" value="%(attachment_name)s" size="80">
  •         
  • class="buttons">
  •             hidden" name="oldattachmentname" value="%(attachment_name)s">
  •             submit" name="move" value="%(move)s">
  •             submit" name="cancel" value="%(cancel)s">
  •         
  • ''' % d
  •     thispage = Page(request, pagename)
  •     request.theme.add_msg(formhtml, "dialog")
  •     return thispage.send_page()
  •  
  •  
  • def _do_box(pagename, request):
  •     _ = request.getText
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not request.user.may.read(pagename):
  •         return _('You are not allowed to get attachments from this page.')
  •     if not filename:
  •         return # error msg already sent in _access_file
  •  
  •     timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
  •     if_modified = request.if_modified_since
  •     if if_modified and if_modified >= timestamp:
  •         request.status_code = 304
  •     else:
  •         ci = ContainerItem(request, pagename, filename)
  •         filename = wikiutil.taintfilename(request.values['member'])
  •         mt = wikiutil.MimeType(filename=filename)
  •         content_type = mt.content_type()
  •         mime_type = mt.mime_type()
  •  
  •         # TODO: fix the encoding here, plain 8 bit is not allowed according to the RFCs
  •         # There is no solution that is compatible to IE except stripping non-ascii chars
  •         #filename_enc = filename.encode(config.charset)
  •         if 'MSIE' in request.http_user_agent:
  •             filename_enc = filename.encode('gbk')
  •         else:
  •             filename_enc = filename.encode(config.charset)
  •  
  •         # for dangerous files (like .html), when we are in danger of cross-site-scripting attacks,
  •         # we just let the user store them to disk ('attachment').
  •         # For safe files, we directly show them inline (this also works better for IE).
  •         dangerous = mime_type in request.cfg.mimetypes_xss_protect
  •         content_dispo = dangerous and 'attachment' or 'inline'
  •  
  •         now = time.time()
  •         request.headers['Date'] = http_date(now)
  •         request.headers['Content-Type'] = content_type
  •         request.headers['Last-Modified'] = http_date(timestamp)
  •         request.headers['Expires'] = http_date(now - 365 * 24 * 3600)
  •         #request.headers['Content-Length'] = os.path.getsize(fpath)
  •         content_dispo_string = '%s; filename="%s"' % (content_dispo, filename_enc)
  •         request.headers['Content-Disposition'] = content_dispo_string
  •  
  •         # send data
  •         request.send_file(ci.get(filename))
  •  
  •  
  • def _do_get(pagename, request):
  •     _ = request.getText
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not request.user.may.read(pagename):
  •         return _('You are not allowed to get attachments from this page.')
  •     if not filename:
  •         return # error msg already sent in _access_file
  •  
  •     timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
  •     if_modified = request.if_modified_since
  •     if if_modified and if_modified >= timestamp:
  •         request.status_code = 304
  •     else:
  •         mt = wikiutil.MimeType(filename=filename)
  •         content_type = mt.content_type()
  •         mime_type = mt.mime_type()
  •  
  •         # TODO: fix the encoding here, plain 8 bit is not allowed according to the RFCs
  •         # There is no solution that is compatible to IE except stripping non-ascii chars
  •         #filename_enc = filename.encode(config.charset)
  •         if 'MSIE' in request.http_user_agent:
  •             filename_enc = filename.encode('gbk')
  •         else:
  •             filename_enc = filename.encode(config.charset)
  •  
  •         # for dangerous files (like .html), when we are in danger of cross-site-scripting attacks,
  •         # we just let the user store them to disk ('attachment').
  •         # For safe files, we directly show them inline (this also works better for IE).
  •         dangerous = mime_type in request.cfg.mimetypes_xss_protect
  •         content_dispo = dangerous and 'attachment' or 'inline'
  •  
  •         now = time.time()
  •         request.headers['Date'] = http_date(now)
  •         request.headers['Content-Type'] = content_type
  •         request.headers['Last-Modified'] = http_date(timestamp)
  •         request.headers['Expires'] = http_date(now - 365 * 24 * 3600)
  •         request.headers['Content-Length'] = os.path.getsize(fpath)
  •         content_dispo_string = '%s; filename="%s"' % (content_dispo, filename_enc)
  •         request.headers['Content-Disposition'] = content_dispo_string
  •  
  •         # send data
  •         request.send_file(open(fpath, 'rb'))
  •  
  •  
  • def _do_install(pagename, request):
  •     _ = request.getText
  •  
  •     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  •         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.install' }
  •  
  •     pagename, target, targetpath = _access_file(pagename, request)
  •     if not request.user.isSuperUser():
  •         return _('You are not allowed to install files.')
  •     if not target:
  •         return
  •  
  •     package = packages.ZipPackage(request, targetpath)
  •  
  •     if package.isPackage():
  •         if package.installPackage():
  •             msg = _("Attachment '%(filename)s' installed.") % {'filename': target}
  •         else:
  •             msg = _("Installation of '%(filename)s' failed.") % {'filename': target}
  •         if package.msg:
  •             msg += " " + package.msg
  •     else:
  •         msg = _('The file %s is not a MoinMoin package file.') % target
  •  
  •     upload_form(pagename, request, msg=msg)
  •  
  •  
  • def _do_unzip(pagename, request, overwrite=False):
  •     _ = request.getText
  •  
  •     if not wikiutil.checkTicket(request, request.args.get('ticket', '')):
  •         return _('Please use the interactive user interface to use action %(actionname)s!') % {'actionname': 'AttachFile.unzip' }
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not (request.user.may.delete(pagename) and request.user.may.read(pagename) and request.user.may.write(pagename)):
  •         return _('You are not allowed to unzip attachments of this page.')
  •  
  •     if not filename:
  •         return # error msg already sent in _access_file
  •  
  •     try:
  •         if not zipfile.is_zipfile(fpath):
  •             return _('The file %(filename)s is not a .zip file.') % {'filename': filename}
  •  
  •         # determine how which attachment names we have and how much space each is occupying
  •         curr_fsizes = dict([(f, size(request, pagename, f)) for f in _get_files(request, pagename)])
  •  
  •         # Checks for the existance of one common prefix path shared among
  •         # all files in the zip file. If this is the case, remove the common prefix.
  •         # We also prepare a dict of the new filenames->filesizes.
  •         zip_path_sep = '/' # we assume '/' is as zip standard suggests
  •         fname_index = None
  •         mapping = []
  •         new_fsizes = {}
  •         zf = zipfile.ZipFile(fpath)
  •         for zi in zf.infolist():
  •             name = zi.filename
  •             if not name.endswith(zip_path_sep): # a file (not a directory)
  •                 if fname_index is None:
  •                     fname_index = name.rfind(zip_path_sep) + 1
  •                     path = name[:fname_index]
  •                 if (name.rfind(zip_path_sep) + 1 != fname_index # different prefix len
  •                     or
  •                     name[:fname_index] != path): # same len, but still different
  •                     mapping = [] # zip is not acceptable
  •                     break
  •                 if zi.file_size >= request.cfg.unzip_single_file_size: # file too big
  •                     mapping = [] # zip is not acceptable
  •                     break
  •                 finalname = name[fname_index:] # remove common path prefix
  •                 finalname = finalname.decode(config.charset, 'replace') # replaces trash with \uFFFD char
  •                 mapping.append((name, finalname))
  •                 new_fsizes[finalname] = zi.file_size
  •  
  •         # now we either have an empty mapping (if the zip is not acceptable),
  •         # an identity mapping (no subdirs in zip, just all flat), or
  •         # a mapping (origname, finalname) where origname is the zip member filename
  •         # (including some prefix path) and finalname is a simple filename.
  •  
  •         # calculate resulting total file size / count after unzipping:
  •         if overwrite:
  •             curr_fsizes.update(new_fsizes)
  •             total = curr_fsizes
  •         else:
  •             new_fsizes.update(curr_fsizes)
  •             total = new_fsizes
  •         total_count = len(total)
  •         total_size = sum(total.values())
  •  
  •         if not mapping:
  •             msg = _("Attachment '%(filename)s' not unzipped because some files in the zip "
  •                     "are either not in the same directory or exceeded the single file size limit (%(maxsize_file)d kB)."
  •                    ) % {'filename': filename,
  •                         'maxsize_file': request.cfg.unzip_single_file_size / 1000, }
  •         elif total_size > request.cfg.unzip_attachments_space:
  •             msg = _("Attachment '%(filename)s' not unzipped because it would have exceeded "
  •                     "the per page attachment storage size limit (%(size)d kB).") % {
  •                         'filename': filename,
  •                         'size': request.cfg.unzip_attachments_space / 1000, }
  •         elif total_count > request.cfg.unzip_attachments_count:
  •             msg = _("Attachment '%(filename)s' not unzipped because it would have exceeded "
  •                     "the per page attachment count limit (%(count)d).") % {
  •                         'filename': filename,
  •                         'count': request.cfg.unzip_attachments_count, }
  •         else:
  •             not_overwritten = []
  •             for origname, finalname in mapping:
  •                 try:
  •                     # Note: reads complete zip member file into memory. ZipFile does not offer block-wise reading:
  •                     add_attachment(request, pagename, finalname, zf.read(origname), overwrite)
  •                 except AttachmentAlreadyExists:
  •                     not_overwritten.append(finalname)
  •             if not_overwritten:
  •                 msg = _("Attachment '%(filename)s' partially unzipped (did not overwrite: %(filelist)s).") % {
  •                         'filename': filename,
  •                         'filelist': ', '.join(not_overwritten), }
  •             else:
  •                 msg = _("Attachment '%(filename)s' unzipped.") % {'filename': filename}
  •     except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile), err:
  •         # We don't want to crash with a traceback here (an exception
  •         # here could be caused by an uploaded defective zip file - and
  •         # if we crash here, the user does not get a UI to remove the
  •         # defective zip file again).
  •         # RuntimeError is raised by zipfile stdlib module in case of
  •         # problems (like inconsistent slash and backslash usage in the
  •         # archive).
  •         # BadZipfile/LargeZipFile are raised when there are some
  •         # specific problems with the archive file.
  •         logging.exception("An exception within zip file attachment handling occurred:")
  •         msg = _("A severe error occurred:") + ' ' + str(err)
  •  
  •     upload_form(pagename, request, msg=msg)
  •  
  •  
  • def send_viewfile(pagename, request):
  •     _ = request.getText
  •     fmt = request.html_formatter
  •  
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not filename:
  •         return
  •  
  •     request.write('

    ' + _("Attachment '%(filename)s'") % {'filename': filename} + '

    ')
  •     # show a download link above the content
  •     label = _('Download')
  •     link = (fmt.url(1, getAttachUrl(pagename, filename, request, do='get'), css_class="download") +
  •             fmt.text(label) +
  •             fmt.url(0))
  •     request.write('%s

    ' % link)
  •  
  •     if filename.endswith('.tdraw') or filename.endswith('.adraw'):
  •         request.write(fmt.attachment_drawing(filename, ''))
  •         return
  •  
  •     mt = wikiutil.MimeType(filename=filename)
  •  
  •     # destinguishs if browser need a plugin in place
  •     if mt.major == 'image' and mt.minor in config.browser_supported_images:
  •         url = getAttachUrl(pagename, filename, request)
  •         request.write('%s" alt="%s">' % (
  •             wikiutil.escape(url, 1),
  •             wikiutil.escape(filename, 1)))
  •         return
  •     elif mt.major == 'text':
  •         ext = os.path.splitext(filename)[1]
  •         Parser = wikiutil.getParserForExtension(request.cfg, ext)
  •         if Parser is not None:
  •             try:
  •                 content = file(fpath, 'r').read()
  •                 content = wikiutil.decodeUnknownInput(content)
  •                 colorizer = Parser(content, request, filename=filename)
  •                 colorizer.format(request.formatter)
  •                 return
  •             except IOError:
  •                 pass
  •  
  •         request.write(request.formatter.preformatted(1))
  •         # If we have text but no colorizing parser we try to decode file contents.
  •         content = open(fpath, 'r').read()
  •         content = wikiutil.decodeUnknownInput(content)
  •         content = wikiutil.escape(content)
  •         request.write(request.formatter.text(content))
  •         request.write(request.formatter.preformatted(0))
  •         return
  •  
  •     try:
  •         package = packages.ZipPackage(request, fpath)
  •         if package.isPackage():
  •             request.write("
    %s\n%s
    " % (_("Package script:"), wikiutil.escape(package.getScript())))
  •             return
  •  
  •         if zipfile.is_zipfile(fpath) and mt.minor == 'zip':
  •             zf = zipfile.ZipFile(fpath, mode='r')
  •             request.write("
    %-46s %19s %12s\n" % (_("File Name"), _("Modified")+" "*5, _("Size")))  
       
  •             for zinfo in zf.filelist:
  •                 date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time
  •                 request.write(wikiutil.escape("%-46s %s %12d\n" % (zinfo.filename, date, zinfo.file_size)))
  •             request.write("")
  •             return
  •     except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile):
  •         # We don't want to crash with a traceback here (an exception
  •         # here could be caused by an uploaded defective zip file - and
  •         # if we crash here, the user does not get a UI to remove the
  •         # defective zip file again).
  •         # RuntimeError is raised by zipfile stdlib module in case of
  •         # problems (like inconsistent slash and backslash usage in the
  •         # archive).
  •         # BadZipfile/LargeZipFile are raised when there are some
  •         # specific problems with the archive file.
  •         logging.exception("An exception within zip file attachment handling occurred:")
  •         return
  •  
  •     from MoinMoin import macro
  •     from MoinMoin.parser.text import Parser
  •  
  •     macro.request = request
  •     macro.formatter = request.html_formatter
  •     p = Parser("##\n", request)
  •     m = macro.Macro(p)
  •  
  •     # use EmbedObject to view valid mime types
  •     if mt is None:
  •         request.write('

    ' + _("Unknown file type, cannot display this attachment inline.") + '

    ')
  •         link = (fmt.url(1, getAttachUrl(pagename, filename, request)) +
  •                 fmt.text(filename) +
  •                 fmt.url(0))
  •         request.write('For using an external program follow this link %s' % link)
  •         return
  •     request.write(m.execute('EmbedObject', u'target="%s", pagename="%s"' % (filename, pagename)))
  •     return
  •  
  •  
  • def _do_view(pagename, request):
  •     _ = request.getText
  •  
  •     orig_pagename = pagename
  •     pagename, filename, fpath = _access_file(pagename, request)
  •     if not request.user.may.read(pagename):
  •         return _('You are not allowed to view attachments of this page.')
  •     if not filename:
  •         return
  •  
  •     request.formatter.page = Page(request, pagename)
  •  
  •     # send header & title
  •     # Use user interface language for this generated page
  •     request.setContentLanguage(request.lang)
  •     title = _('attachment:%(filename)s of %(pagename)s') % {
  •         'filename': filename, 'pagename': pagename}
  •     request.theme.send_title(title, pagename=pagename)
  •  
  •     # send body
  •     request.write(request.formatter.startContent())
  •     send_viewfile(orig_pagename, request)
  •     send_uploadform(pagename, request)
  •     request.write(request.formatter.endContent())
  •  
  •     request.theme.send_footer(pagename)
  •     request.theme.send_closing_html()
  •  
  •  
  • #############################################################################
  • ### File attachment administration
  • #############################################################################
  •  
  • def do_admin_browser(request):
  •     """ Browser for SystemAdmin macro. """
  •     from MoinMoin.util.dataset import TupleDataset, Column
  •     _ = request.getText
  •  
  •     data = TupleDataset()
  •     data.columns = [
  •         Column('page', label=('Page')),
  •         Column('file', label=('Filename')),
  •         Column('size', label=_('Size'), align='right'),
  •     ]
  •  
  •     # iterate over pages that might have attachments
  •     pages = request.rootpage.getPageList()
  •     for pagename in pages:
  •         # check for attachments directory
  •         page_dir = getAttachDir(request, pagename)
  •         if os.path.isdir(page_dir):
  •             # iterate over files of the page
  •             files = os.listdir(page_dir)
  •             for filename in files:
  •                 filepath = os.path.join(page_dir, filename)
  •                 data.addRow((
  •                     (Page(request, pagename).link_to(request,
  •                                 querystr="action=AttachFile"), wikiutil.escape(pagename, 1)),
  •                     #wikiutil.escape(filename.decode(config.charset)),
  •                     wikiutil.escape(wikiutil.unquoteWikiname(filename)),
  •                     os.path.getsize(filepath),
  •                 ))
  •  
  •     if data:
  •         from MoinMoin.widget.browser import DataBrowserWidget
  •  
  •         browser = DataBrowserWidget(request)
  •         browser.setData(data, sort_columns=[0, 1])
  •         return browser.render(method="GET")
  •  
  •     return ''
  •  

     

     

    你可能感兴趣的:(Moinmoin wiki 中文附件名的解决办法)