wcs/wcs/wf/attachment.py

191 lines
6.6 KiB
Python

# w.c.s. - web application for online forms
# Copyright (C) 2005-2010 Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import random
import string
from quixote import get_response
from quixote.html import htmltext
from quixote.directory import Directory, AccessControlled
from quixote.util import FileStream
from wcs.workflows import *
from qommon.errors import *
from wcs.forms.common import FormStatusPage
def form_attachment(self):
self.check_receiver()
try:
fn = get_request().form['f']
except (KeyError, ValueError):
raise TraversalError()
found = False
for evo in self.filled.evolution:
if evo.parts:
for p in evo.parts:
if not isinstance(p, AttachmentEvolutionPart):
continue
if os.path.basename(p.filename) == fn:
found = True
break
if found:
break
if not found:
raise TraversalError()
try:
fd = open(p.filename, 'rb')
except:
raise TraversalError()
size = os.path.getsize(p.filename)
response = get_response()
if p.content_type:
response.set_content_type(p.content_type)
else:
response.set_content_type('application/octet-stream')
if p.charset:
response.set_charset(p.charset)
if p.base_filename:
if p.content_type and p.content_type.startswith('image/'):
response.set_header(
'content-disposition', 'inline; filename="%s"' % p.base_filename)
else:
response.set_header(
'content-disposition', 'attachment; filename="%s"' % p.base_filename)
return FileStream(fd, size)
class AttachmentEvolutionPart:
orig_filename = None
base_filename = None
content_type = None
charset = None
def __init__(self, f):
self.orig_filename = f.orig_filename
self.base_filename = f.base_filename
self.content_type = f.content_type
self.charset = f.charset
self.fp = f.fp
def __getstate__(self):
odict = self.__dict__.copy()
if not odict.has_key('fp'):
return odict
del odict['fp']
dirname = os.path.join(get_publisher().app_dir, 'attachments')
if not os.path.exists(dirname):
os.mkdir(dirname)
def get_new_filename():
r = random.SystemRandom()
while True:
id = ''.join([r.choice(string.lowercase) for x in range(16)])
filename = os.path.join(dirname, id)
if not os.path.exists(filename):
return filename
odict['filename'] = get_new_filename()
self.fp.seek(0)
fd = file(odict['filename'], 'w')
fd.write(self.fp.read())
fd.close()
return odict
def view(self):
return htmltext('<p><a href="attachment?f=%s">%s</a>' % (
os.path.basename(self.filename), self.orig_filename))
class AddAttachmentWorkflowStatusItem(WorkflowStatusItem):
description = N_('Allow Addition of an Attachment')
key = 'addattachment'
endpoint = False
waitpoint = True
title = None
display_title = True
button_label = None
display_button = True
required = False
hint = None
by = []
def init(cls):
FormStatusPage._q_extra_exports.append('attachment')
FormStatusPage.attachment = form_attachment
init = classmethod(init)
def render_as_line(self):
if self.by:
return _('Allow Addition of an Attachment by %s') % self.render_list_of_roles(self.by)
else:
return _('Allow Addition of an Attachment (not completed)')
def fill_form(self, form, formdata, user):
if self.display_title:
title = self.title or _('Upload File')
else:
title = None
form.add(FileWidget, 'attachment%s' % self.id, title=title,
required=self.required, hint=self.hint)
if self.display_button:
form.add_submit('button%s' % self.id, self.button_label or _('Upload File'))
def submit_form(self, form, formdata, user, evo):
if form.get_widget('attachment%s' % self.id):
f = form.get_widget('attachment%s' % self.id).parse()
if f is None:
if self.required:
form.set_error('attachment%s' % self.id, _('Missing file'))
return
evo.add_part(AttachmentEvolutionPart(f))
def get_parameters(self):
return ('by', 'required', 'title', 'display_title', 'button_label', 'display_button', 'hint')
def add_parameters_widgets(self, form, parameters, prefix='', formdef=None):
if 'by' in parameters:
form.add(WidgetList, '%sby' % prefix, title = _('By'),
element_type = SingleSelectWidget,
value = self.by,
add_element_label = _('Add Role'),
element_kwargs={'render_br': False,
'options': [(None, '---')] + self.get_list_of_roles()})
if 'required' in parameters:
form.add(CheckboxWidget, '%srequired' % prefix, title = _('Required'), value = self.required)
if 'title' in parameters:
form.add(StringWidget, '%stitle' % prefix, size=40, title=_('Title'), value=self.title or _('Upload File'))
if 'display_title' in parameters:
form.add(CheckboxWidget, '%sdisplay_title' % prefix, title = _('Display Title'), value = self.display_title)
if 'button_label' in parameters:
form.add(StringWidget, '%sbutton_label' % prefix, title=_('Button Label'),
value=self.button_label or _('Upload File'))
if 'display_button' in parameters:
form.add(CheckboxWidget, '%sdisplay_button' % prefix, title = _('Display Button'), value = self.display_button)
if 'hint' in parameters:
form.add(StringWidget, '%shint' % prefix, size=40, title=_('Hint'), value=self.hint)
register_item_class(AddAttachmentWorkflowStatusItem)