File: ZAttachmentAttribute.py

package info (click to toggle)
zope-zattachmentattribute 2.21-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 324 kB
  • ctags: 238
  • sloc: sh: 1,365; python: 1,311; makefile: 89
file content (469 lines) | stat: -rw-r--r-- 17,347 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
##############################################################################
#
# Copyright (c) 2002 Ingeniweb SARL
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

"""
ZAttachmentAttribute product


Coding information :
  Permissions are set dynamically. That is, class is instanciated with access_permission and change_permission
  arguments, allowing a class to set its own permissions to content-accessing methods and to content-changing
  methods. Usually, it would be "Access Content Information" and "Change XXXs" permissions, but your mileage
  may vary.

  If you create a new method for ZAttachmentAttribute class, don't forget to map it in the __init__ file
  with declareProtected and declarePublic methods.
"""


import Acquisition
from Globals import Persistent
from Globals import MessageDialog, DTMLFile      # fakes a method from a DTML file
from Globals import InitializeClass
from AccessControl import Role
from AccessControl import ClassSecurityInfo
from AccessControl import Permissions
from AccessControl import Unauthorized
from AccessControl import getSecurityManager
from webdav.common import rfc1123_date
import OFS.SimpleItem
from OFS.ObjectManager import ObjectManager
from OFS.Traversable import Traversable
from global_symbols import *
try:
    from Products.CMFCore.utils import getToolByName
except:
    pass                # No CMF -> no charset converting

import ZDummyAttachment
import ZAttachmentRegistry

import urllib
import string
import os
import os.path
import sys

DEFAULT_ID = "attach"
ZAA_READ_PERMISSION = Permissions.access_contents_information
ZAA_WRITE_PERMISSION = Permissions.change_images_and_files


    

class ZAttachmentAttribute(Acquisition.Implicit, Persistent, Traversable, ):
    """
    ZAttachmentAttribute is a (base) class that can be used to store attachment information
    WARNING : SUBCLASSING THIS CLASS may break our security policy !
    """
    security = ClassSecurityInfo()
    
    # Other information
    content_type = ""
    filename = ""
    attachment_id = DEFAULT_ID

    def __init__(
        self,
        access_permission = Permissions.access_contents_information,
        change_permission = Permissions.change_images_and_files,
        title = "",
        id = None,                                                          # Default id
        ):
        """
        __init__(
            self,
            access_permission = Permissions.access_contents_information,
            change_permission = Permissions.change_images_and_files
            title = ''
        ) => Init method
        access_permission is the permission that will be mapped as access content permission
        and file modifying permission.
        """
        # Store permission information
        self.__access_permission = access_permission
        self.__change_permission = change_permission

        # Store title and attachement id
        if id is None:
            id = DEFAULT_ID
            Log(LOG_WARNING, "Warning: ZAttachmentAttribute initialization without an id is deprecated!")
        self.title = title
        self.attachment_id = id

        # Underlying file : this is the variable the actual file abstraction class will be stored in
        self.__underlyingFile__ = ZDummyAttachment.ZDummyAttachment()
        self.updateCache()

    #We need manage_afterAdd, manage_beforeDelete and manage_afterClone
    #For example, without manage_beforeDelete, the method of the container
    #will be called, which can lead to strange bugs. We have to support
    #the interface of SimpleItem or Item to some level here.
    def manage_afterAdd(self, item, container):
        pass

    def manage_beforeDelete(self, item, container): 
        pass

    def manage_afterClone(self, item):
        pass

    #                                                                           #
    #                             Public interface                              #
    #                                                                           #

    security.declareProtected(ZAA_READ_PERMISSION, 'getContentType')
    def getContentType(self,):
        """
        getContentType(self,) => this is explicit ! ;-)
        """
        return self.content_type

    security.declareProtected(ZAA_READ_PERMISSION, 'getIcon')
    def getIcon(self,):
        """
        getIcon(self,) => return the underlying file class icon
        """
        try:
            dummy = self.icon
        except AttributeError:
            self.updateCache()
        return self.icon

    security.declareProtected(ZAA_READ_PERMISSION, 'getSmallIcon')
    def getSmallIcon(self,):
        """
        getSmallIcon(self,) => return the underlying file class icon
        """
        try:
            dummy = self.icon_small
        except AttributeError:
            self.updateCache()
        return self.icon_small

    security.declareProtected(ZAA_WRITE_PERMISSION, 'delete')
    def delete(self, REQUEST = {}):
        """
        delete(self, REQUEST = {}) => delete the file
        """
        self.__underlyingFile__ = ZDummyAttachment.ZDummyAttachment()
        self.title = ''
        self.filename = ''
        self.updateCache()


    security.declareProtected(ZAA_WRITE_PERMISSION, 'upload')
    def upload(self, file, REQUEST = {}):
        """
        upload(self, file, REQUEST = {}) => uploads the file

        This method selects the right ZAbstractAttachment-based attachment class
        from the file's content_type and delegates the job to self.uploadAttachment().

        As usual, a REDIRECT variable can be transmitted in REQUEST so that the
        method will redirect to a nice place.
        """
        # Check the file type
        content_type = string.lower(file.headers['Content-Type'])
        Log(LOG_DEBUG, content_type)
        (attachment_class, class_globals, converter) = ZAttachmentRegistry.AttachmentRegistry.getAttachmentClass(content_type)
        self.content_type = content_type

        # Compute filename.
        # We cannot use os.path.split here because, for example, if the server is under Unix and the client under Windows, the os.path.split would remove "/" and not "\\".
        fn = file.filename
        fn = string.split(fn, '/')[-1]
        fn = string.split(fn, '\\')[-1]
        self.filename = fn
        
        # Manual uploading
        Log(LOG_DEBUG, content_type, attachment_class.__name__)
        self.uploadAttachment(attachment_class, class_globals, converter, content_type, file)

        # Update the internal persistancy state
        self._p_changed = 1                             # (See http://www.zope.org/Documentation/Developer/Models/ZODB/ZODB_Persistent_Objects_Persistent__p_changed_Doc.html)

        # Redirect
        Log(LOG_DEBUG, "File uploaded...")
        if REQUEST.has_key('RESPONSE'):
            redir = REQUEST.get('REDIRECT', None)
            if redir:
                return REQUEST.RESPONSE.redirect(redir)

    security.declareProtected(ZAA_READ_PERMISSION, 'getIndexableValue')
    def getIndexableValue(self,):
        """
        getIndexableValue(self,) => return the underlying indexable value as a (possibly big) string
        """
        return "%s %s" % (self.__underlyingFile__.getIndexableValue(), self.title_or_id(), )


    security.declareProtected(ZAA_READ_PERMISSION, 'listIndexableValues')
    def listIndexableValues(self,):
        """
        listIndexableValues(self,) => return the undelying indexable value as a lowercased string of unique words
        """
        return self.__underlyingFile__.listIndexableValues()


    security.declareProtected(ZAA_READ_PERMISSION, 'SearchableText')
    def SearchableText(self,):
        """
        SearchableText(self,) => ZCatalog support
        """
        Log(LOG_DEBUG, "SearchableText")
        return "%s %s" % (self.__underlyingFile__.SearchableText(), self.title_or_id(), )


    security.declareProtected(ZAA_READ_PERMISSION, 'getFile')
    def getFile(self, **kw): 
        """
        getFile(self, **kw) => return file content
        """
        return self.__underlyingFile__.getContent()


    security.declareProtected(ZAA_READ_PERMISSION, 'isEmpty')
    def isEmpty(self,):
        """
        isEmpty(self,) => return 1 if file is empty
        """
        try:
            dummy = self.cached_size
        except AttributeError:
            self.updateCache()
        return not self.cached_size

    security.declareProtected(ZAA_READ_PERMISSION, 'getSize')
    def getSize(self,):
        """
        getSize(self,) => return 1 if file is empty
        """
        try:
            dummy = self.cached_size
        except AttributeError:
            self.updateCache()
        return self.cached_size

    security.declareProtected(ZAA_READ_PERMISSION, 'getFilename')
    def getFilename(self,):
        """
        getFilename(self,) => return filename
        """
        return self.filename


    def __bobo_traverse__(self, REQUEST, name=None):
        # Return file content if it is accessed through its name
        if name == self.getFilename():
            Log(LOG_DEBUG, "filename matches")
            return self.index_html

        # if a known attribute is referenced (e.g. title_or_id), return that
        if hasattr(self, name):
            return getattr(self, name)

        # Return additional files that may be stored along with the attachment data.
        # (especially images with MSWord documents)
        related = self.__underlyingFile__.getRelatedFile(name, None)
        if related:
            Log(LOG_DEBUG, "Found related for", name)
            raise "Redirect", "%s/related_content?content=%s" % (REQUEST.URL1, urllib.quote_plus(name), )

        # Pass the request
        return getattr(self, name)
    

    security.declareProtected(ZAA_READ_PERMISSION, 'related_content')
    def related_content(self, content):
        """
        related_content(self, content) => HTTP stream

        This is useful to specify related content through an HTTP request.
        """
        Log(LOG_DEBUG, "In related_content")
        REQUEST = self.REQUEST
        related = self.__underlyingFile__.getRelatedFile(content)
        return self.returnContent(REQUEST, REQUEST.RESPONSE, related['data'], related['content_type'], )
        

    security.declareProtected(ZAA_READ_PERMISSION, 'returnContent')
    def returnContent(self, REQUEST, RESPONSE, data, content_type, ):
        """
        returnContent(self, REQUEST, RESPONSE, data, content_type, ) => HTTP response
        """
        # HTTP If-Modified-Since header handling.
        Log(LOG_DEBUG, "In returnContent")
        header=REQUEST.get_header('If-Modified-Since', None)
        if header is not None:
            header=header.split( ';')[0]
            try:    mod_since=long(DateTime(header).timeTime())
            except: mod_since=None

        RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))
        RESPONSE.setHeader('Content-Type', content_type)
        RESPONSE.setHeader('Content-Length', len(data))
        RESPONSE.setHeader('Accept-Ranges', 'none')

        Log(LOG_DEBUG, "Returning data")
        return data
        

    security.declareProtected(ZAA_READ_PERMISSION, 'index_html')
    def index_html(self, REQUEST, RESPONSE, ):
        """
        The default view of the contents of a File or Image.

        Returns the contents of the file or image.  Also, sets the
        Content-Type HTTP header to the objects content type.

        THIS WAS TAKEN FROM OFS.Image MODULE !
        """
        return self.returnContent(REQUEST, RESPONSE, self.__underlyingFile__.content, self.content_type)

    #                                                                           #
    #                              Title management                             #
    #                                                                           #

    security.declareProtected(ZAA_READ_PERMISSION, 'title_or_id')
    def title_or_id(self):
        """Utility that returns the title if it is not blank and the id
        otherwise."""
        return self.title or self.getFilename()

    security.declareProtected(ZAA_READ_PERMISSION, 'title_and_id')
    def title_and_id(self):
        """Utility that returns the title if it is not blank and the id
        otherwise.  If the title is not blank, then the id is included
        in parens."""
        t=self.title
        return t and ("%s (%s)" % (t, self.getFilename())) or self.getFilename()

    security.declareProtected(ZAA_WRITE_PERMISSION, 'setTitle')
    def setTitle(self, title):
        """
        setTitle(self, title)
        """
        self.title = title


    #                                                                           #
    #                              Other facilities                             #
    #                                                                           #

    security.declareProtected(ZAA_READ_PERMISSION, 'isIndexed')
    def isIndexed(self,):
        """
        return 1 if the attach. is indexed properly
        """
        return self.__underlyingFile__.indexing_done

    security.declareProtected(ZAA_READ_PERMISSION, 'getCharset')
    def getCharset(self):
        """
        Return site default charset, or utf-8
        """
        try:
            getToolByName
        except NameError:
            return
        purl = getToolByName(self, 'portal_url')
        container = purl.getPortalObject()
        if getattr(container, 'getCharset', None):
            return container.getCharset()

        encoding = 'utf-8'
        p_props = getToolByName(self, 'portal_properties', None)
        if p_props is not None:
            site_props = getattr(p_props, 'site_properties', None)
            if site_props is not None:
                encoding = site_props.getProperty('default_charset')

        return encoding

    security.declareProtected(ZAA_READ_PERMISSION, 'preview')
    def preview(self,):
        """
        Return an HTML rendering of the document
        """
        # Get preview content
        datum = self.__underlyingFile__.getPreview()

        # Convert it if possible / necessary
        # FIXME: we really need an unicode policy !
        Log(LOG_DEBUG, "preview is type", type(datum))
        if type(datum) is type(''):
            cs = self.__underlyingFile__.getEncoding()
            if cs:
                Log(LOG_DEBUG, "Converting", cs, "to unicode")
                datum = unicode(datum, cs, "ignore")
            
        if type(datum) is type(u''):
            cs = self.getCharset()
            if cs:
                Log(LOG_DEBUG, "Converting unicode to", cs)
                datum = datum.encode(cs, "ignore")
                
        return datum

    security.declareProtected(ZAA_READ_PERMISSION, 'getPreview')
    def getPreview(self,):
        """
        Alias / Same as preview()
        """
        return self.preview()

    security.declareProtected(ZAA_READ_PERMISSION, 'getSmallPreview')
    def getSmallPreview(self,):
        """
        getSmallPreview(self,) => string or None

        Default behaviour : if the preview string is shorter than MAX_PREVIEW_SIZE, return it, else return None.
        """
        return self.__underlyingFile__.getSmallPreview()

    security.declareProtected(ZAA_READ_PERMISSION, 'isPreviewAvailable')
    def isPreviewAvailable(self,):
        """
        Return true if it possible to preview this attachment as HTML
        """
        return self.__underlyingFile__.isPreviewAvailable()


    #                                                                           #
    #                                 Internals...                              #
    #                                                                           #

    security.declareProtected(ZAA_WRITE_PERMISSION, 'uploadAttachment')
    def uploadAttachment(self, attachment_class, attach_globals, converter, content_type, data_stream):
        """
        uploadAttachment(self, attachment_class, attach_globals, converter, content_type, data_stream) => actual subclassing & uploading.
        This method should be only called for test purposes. It delegates actual data
        management to attachmentClass (ZAbstractAttachment-based) class.
        data_stream is the file data as a STREAM.
        """
        self.__underlyingFile__ = eval("""attachment_class(content_type, data_stream, converter, )""", attach_globals, locals())
        self.updateCache()

    
    security.declarePrivate('updateCache')
    def updateCache(self):
        Log(LOG_DEBUG, "updateCache")
        self.icon       = self.__underlyingFile__.getIcon()
        self.icon_small = self.__underlyingFile__.getSmallIcon()
        self.cached_size= len(self.__underlyingFile__.content)
        self._p_changed = 1



InitializeClass(ZAttachmentAttribute)