示例#1
0
    def __init__(self, kw, context):
        self.context = ImplicitAcquisitionWrapper(self, context)
        self.created = kw['creation_date']
        self.last_modified = kw['modification_date']
        self.url = kw['_url']
        self.title = kw['title']
        self.description = kw['description']

        tz = kw['startDate'][-6:]
        minutes = tz[-2:]
        hours = tz[-5:-3]
        seconds = int(minutes) * 60 + int(hours) * 3600
        if tz[0] == '-':
            seconds = -seconds
        offset = timedelta(seconds=seconds)

        # We try CET first, because it's most common, and if none works, we use CET anyway.
        # So Brussels should be both first and last in this list:
        for tzname in ['Europe/Brussels', 'Europe/London', 'Europe/Helsinki', 'Atlantic/Reykjavik']:  # , 'Europe/Brussels']:
            zone = timezone(tzname)
            if tz[0] not in '-+':
                # Naive date time, just assume CET
                break

            # Verify this:
            if isotime2dt(kw['startDate'], zone).utcoffset() == offset:
                break

        self.start = isotime2dt(kw['startDate'], zone)
        self.end = isotime2dt(kw['endDate'], zone)
        self.timezone = tzname

        self.location = kw['location']
        self.attendees = kw['attendees']
        self.contact_name = kw['contactName']
        self.contact_email = kw['contactEmail']
        self.contact_phone = kw['contactPhone']
        self.event_url = kw['eventUrl']
        self.subjects = kw['subject']
        self.text = kw['text']
        self.organiser = u''

        if kw.get('attachment', None):
            self.attachment = True
            self.attachment_content_type = kw.get('_attachment_content_type')
            self.attachment_filename = kw.get('_attachment_filename')
            mtr = getToolByName(context, "mimetypes_registry")
            mime = list(mtr.lookup(self.attachment_content_type))
            mime.append(mtr.lookupExtension(self.attachment_filename))
            mime.append(mtr.lookup("application/octet-stream")[0])

            portal_url = api.portal.get().absolute_url()
            icon_paths = [m.icon_path for m in mime if m.icon_path]
            if icon_paths:
                self.attachment_icon = portal_url + "/" + icon_paths[0]
            else:

                self.attachment_icon = portal_url + "/" + guess_icon_path(mime[0])
        else:
            self.attachment = False
示例#2
0
 def getMimeTypeIcon(self, obj):
     fileo = obj.getObject().file
     portal_url = getNavigationRoot(self.context)
     mtt = getToolByName(self.context, 'mimetypes_registry')
     if fileo.contentType:
         ctype = mtt.lookup(fileo.contentType)
         return os.path.join(portal_url, guess_icon_path(ctype[0]))
     return None
 def getMimeTypeIcon(self, obj):
     fileo = obj.getObject().file
     portal_url = getNavigationRoot(self.context)
     mtt = getToolByName(self.context, 'mimetypes_registry')
     if fileo.contentType:
         ctype = mtt.lookup(fileo.contentType)
         return os.path.join(
             portal_url,
             guess_icon_path(ctype[0])
         )
     return None
示例#4
0
 def getMimeTypeIcon(self, node):
     try:
         if not node["normalized_portal_type"] == "file":
             return
         fileo = node["item"].getObject().file
         portal_url = getNavigationRoot(self.context)
         mtt = getToolByName(self.context, "mimetypes_registry")
         if fileo.contentType:
             ctype = mtt.lookup(fileo.contentType)
             return os.path.join(portal_url, guess_icon_path(ctype[0]))
     except AttributeError:
         pass
示例#5
0
 def getMimeTypeIcon(self, node):
     try:
         if not node['normalized_portal_type'] == 'file':
             return None
         fileo = node['item'].getObject().file
         portal_url = getNavigationRoot(self.context)
         mtt = getToolByName(self.context, 'mimetypes_registry')
         if fileo.contentType:
             ctype = mtt.lookup(fileo.contentType)
             return os.path.join(portal_url, guess_icon_path(ctype[0]))
     except AttributeError:
         return None
     return None
示例#6
0
    def getMimeTypeIcon(self, content_file):
        context = aq_inner(self.context)
        pstate = getMultiAdapter(
            (context, self.request),
            name=u'plone_portal_state'
        )
        portal_url = pstate.portal_url()
        mtr = getToolByName(context, "mimetypes_registry")
        mime = list(mtr.lookup(content_file.contentType))
        mime.append(mtr.lookupExtension(content_file.filename))
        mime.append(mtr.lookup("application/octet-stream")[0])

        return portal_url + "/" + guess_icon_path(mime[0])
 def getMimeTypeIcon(self, node):
     try:
         if node.portal_type != 'File':
             return None
         fileo = node.file
         portal_url = getNavigationRoot(self.context)
         mtt = getToolByName(self.context, 'mimetypes_registry')
         if fileo.contentType:
             ctype = mtt.lookup(fileo.contentType)
             return os.path.join(
                 portal_url,
                 guess_icon_path(ctype[0])
             )
     except AttributeError:
         return None
     return None
    def MimeTypeIcon(self):
        mimeicon = None
        navroot = getNavigationRoot(self._brain)
        contenttype = aq_base(getattr(self._brain, 'mime_type', None), )
        if contenttype:
            mtt = getToolByName(
                self._brain,
                'mimetypes_registry',
            )
            ctype = mtt.lookup(contenttype)
            mimeicon = os.path.join(
                navroot,
                guess_icon_path(ctype[0]),
            )

        return mimeicon
    def getMimeTypeIcon(self, content_file):
        context = aq_inner(self.context)
        pstate = getMultiAdapter((context, self.request), name=u"plone_portal_state")
        portal_url = pstate.portal_url()
        mtr = getToolByName(context, "mimetypes_registry")
        mime = []
        if content_file.contentType:
            mime.append(mtr.lookup(content_file.contentType))
        if content_file.filename:
            mime.append(mtr.lookupExtension(content_file.filename))
        mime.append(mtr.lookup("application/octet-stream")[0])
        icon_paths = [m.icon_path for m in mime if hasattr(m, "icon_path")]
        if icon_paths:
            return icon_paths[0]

        return portal_url + "/" + guess_icon_path(mime[0])
示例#10
0
文件: files.py 项目: sm2x/castle.cms
    def get_mimetype_icon(self):
        context = aq_inner(self.context)
        pstate = getMultiAdapter((context, self.request),
                                 name=u'plone_portal_state')
        portal_url = pstate.portal_url()
        mtr = getToolByName(context, "mimetypes_registry")
        mime = []
        if self.content_type:
            mime.append(mtr.lookup(self.content_type))
        if self.filename:
            mime.append(mtr.lookupExtension(self.filename))
        mime.append(mtr.lookup("application/octet-stream")[0])
        icon_paths = [m.icon_path for m in mime if hasattr(m, 'icon_path')]
        if icon_paths:
            return portal_url + "/" + icon_paths[0]

        return portal_url + "/" + guess_icon_path(mime[0])
    def MimeTypeIcon(self):
        mimeicon = None
        navroot = getNavigationRoot(self._brain)
        contenttype = aq_base(
            getattr(self._brain, 'mime_type', None),
        )
        if contenttype:
            mtt = getToolByName(
                self._brain,
                'mimetypes_registry',
            )
            ctype = mtt.lookup(contenttype)
            mimeicon = os.path.join(
                navroot,
                guess_icon_path(ctype[0]),
            )

        return mimeicon
示例#12
0
 def MimeTypeIcon(self):
     mime_type = self.get("mime_type", None)
     if not mime_type:
         return ""
     mtt = api.portal.get_tool(name="mimetypes_registry")
     navroot_url = api.portal.get().absolute_url()
     ctype = mtt.lookup(mime_type)
     mimeicon = None
     if not ctype:
         if HAS_RER_THEME:
             if IDesignPloneThemeLayer.providedBy(self.request):
                 mimeicon = os.path.join(
                     navroot_url,
                     "++plone++design.plone.theme/icons/default.svg",
                 )
     else:
         mimeicon = os.path.join(navroot_url, guess_icon_path(ctype[0]))
     return mimeicon
def initialize(registry):
    # Find things that are not in the specially registered mimetypes
    # and add them using some default policy, none of these will impl
    # iclassifier

    # Read our included mime.types file, in addition to whatever the
    # mimetypes python module might have found.
    mimes_initialize()

    # Initialize from registry known mimetypes if we are on Windows
    # and pywin32 is available.
    try:
        from .windows_mimetypes import initialize

        initialize()
    except ImportError:
        pass

    for ext, mt in pymimetypes.types_map.items():
        if not ext:
            continue
        if ext.startswith("."):
            ext = ext[1:]
        if registry.lookupExtension(ext):
            continue
        if ext in skip_extensions:
            continue

        try:
            mto = registry.lookup(mt)
        except MimeTypeException:
            # malformed MIME type
            continue
        if mto:
            mto = mto[0]
            if ext not in mto.extensions:
                registry.register_extension(ext, mto)
                mto.extensions += (ext,)
                # here we guess icon path again, to find icon match the new ext
                mto.icon_path = guess_icon_path(mto)
            continue
        isBin = mt.split("/", 1)[0] != "text"
        registry.register(MimeTypeItem(mt, (mt,), (ext,), isBin))
示例#14
0
def initialize(registry):
    # Find things that are not in the specially registered mimetypes
    # and add them using some default policy, none of these will impl
    # iclassifier

    # Read our included mime.types file, in addition to whatever the
    # mimetypes python module might have found.
    mimes_initialize()

    # Initialize from registry known mimetypes if we are on Windows
    # and pywin32 is available.
    try:
        from .windows_mimetypes import initialize
        initialize()
    except ImportError:
        pass

    for ext, mt in pymimetypes.types_map.items():
        if not ext:
            continue
        if ext.startswith('.'):
            ext = ext[1:]
        if registry.lookupExtension(ext):
            continue
        if ext in skip_extensions:
            continue

        try:
            mto = registry.lookup(mt)
        except MimeTypeException:
            # malformed MIME type
            continue
        if mto:
            mto = mto[0]
            if ext not in mto.extensions:
                registry.register_extension(ext, mto)
                mto.extensions += (ext, )
                # here we guess icon path again, to find icon match the new ext
                mto.icon_path = guess_icon_path(mto)
            continue
        isBin = mt.split('/', 1)[0] != "text"
        registry.register(MimeTypeItem(mt, (mt,), (ext,), isBin))
示例#15
0
    def getMimeTypeIcon(self, content_file):
        context = aq_inner(self.context)
        pstate = getMultiAdapter(
            (context, self.request),
            name=u'plone_portal_state'
        )
        portal_url = pstate.portal_url()
        mtr = getToolByName(context, 'mimetypes_registry')
        mime = []
        if content_file.contentType:
            mime.append(mtr.lookup(content_file.contentType))
        if content_file.filename:
            mime.append(mtr.lookupExtension(content_file.filename))
        mime.append(mtr.lookup('application/octet-stream')[0])
        icon_paths = ['++resource++mimetype.icons/' + m.icon_path
                      for m in mime if hasattr(m, 'icon_path')]
        if icon_paths:
            return icon_paths[0]

        return portal_url + '/' + guess_icon_path(mime[0])
示例#16
0
    def getMimeTypeIcon(self, content_file):
        # Get possible mime types, and try to find an icon path.
        # Keep the first one, in case there is no good match.
        first = None
        for mime in self._get_mimes(content_file):
            if first is None:
                first = mime
            if hasattr(mime, "icon_path"):
                icon_path = mime.icon_path
                if not icon_path.startswith("++"):
                    icon_path = PREFIX + icon_path
                return icon_path

        if first is None:
            # Probably does not happen in practice.
            return ""
        context = aq_inner(self.context)
        pstate = getMultiAdapter((context, self.request),
                                 name=u"plone_portal_state")
        portal_url = pstate.portal_url()
        return portal_url + "/" + guess_icon_path(first)
示例#17
0
    def getFileMimeTypeIcon(self, content_file):
        context = aq_inner(self.context)
        pstate = getMultiAdapter((context, self.request),
                                 name=u'plone_portal_state')
        portal_url = pstate.portal_url()
        mtr = getToolByName(context, "mimetypes_registry")
        mime = []
        preadapter = IPreviewable(context, None)
        if preadapter != None:
            ftype = preadapter.getFileType()
        elif content_file.contentType:
            ftype = content_file.contentType

        if bool(ftype):
            mime.append(mtr.lookup(ftype)[0])
        if content_file.filename:
            mime.append(mtr.lookupExtension(content_file.filename))
        mime.append(mtr.lookup("application/octet-stream")[0])
        icon_paths = [m.icon_path for m in mime if hasattr(m, 'icon_path')]
        if icon_paths:
            return icon_paths[0]

        return portal_url + "/" + guess_icon_path(mime[0])
示例#18
0
 def iconurl(self):
     "get URL for showing the icon"
     base = api.portal.get().absolute_url()
     mt = self.mimetype()
     return (base + '/' + guess_icon_path(mt)) if mt else ""
示例#19
0
    def __call__(self):
        """
        Accepts GET parameters of:
        name: Name of the vocabulary
        field: Name of the field the vocabulary is being retrieved for
        query: string or json object of criteria and options.
            json value consists of a structure:
                {
                    criteria: object,
                    sort_on: index,
                    sort_order: (asc|reversed)
                }
        attributes: comma seperated, or json object list
        batch: {
            page: 1-based page of results,
            size: size of paged results
        }
        """
        context = self.get_context()
        self.request.response.setHeader(
            'Content-Type', 'application/json; charset=utf-8'
        )

        try:
            vocabulary = self.get_vocabulary()
        except VocabLookupException as e:
            return json_dumps({'error': e.args[0]})

        results_are_brains = False
        if hasattr(vocabulary, 'search_catalog'):
            query = self.parsed_query()
            results = vocabulary.search_catalog(query)
            results_are_brains = True
        elif hasattr(vocabulary, 'search'):
            try:
                query = self.parsed_query()['SearchableText']['query']
            except KeyError:
                results = iter(vocabulary)
            else:
                results = vocabulary.search(query)
        else:
            results = vocabulary

        try:
            total = len(results)
        except TypeError:
            # do not error if object does not support __len__
            # we'll check again later if we can figure some size
            # out
            total = 0

        # get batch
        batch = _parseJSON(self.request.get('batch', ''))
        if batch and ('size' not in batch or 'page' not in batch):
            batch = None  # batching not providing correct options
        if batch:
            # must be slicable for batching support
            page = int(batch['page'])
            size = int(batch['size'])
            if size > MAX_BATCH_SIZE:
                raise Exception('Max batch size is 500')
            # page is being passed in is 1-based
            start = (max(page - 1, 0)) * size
            end = start + size
            # Try __getitem__-based slice, then iterator slice.
            # The iterator slice has to consume the iterator through
            # to the desired slice, but that shouldn't be the end
            # of the world because at some point the user will hopefully
            # give up scrolling and search instead.
            try:
                results = results[start:end]
            except TypeError:
                results = itertools.islice(results, start, end)

        # build result items
        items = []

        attributes = _parseJSON(self.request.get('attributes', ''))
        if isinstance(attributes, six.string_types) and attributes:
            attributes = attributes.split(',')

        translate_ignored = self.get_translated_ignored()
        if attributes:
            base_path = self.get_base_path(context)
            sm = getSecurityManager()
            can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context)
            mtt = getToolByName(self.context, 'mimetypes_registry')
            for vocab_item in results:
                if not results_are_brains:
                    vocab_item = vocab_item.value
                item = {}
                for attr in attributes:
                    key = attr
                    if ':' in attr:
                        key, attr = attr.split(':', 1)
                    if attr in _unsafe_metadata and not can_edit:
                        continue
                    if key == 'path':
                        attr = 'getPath'
                    val = getattr(vocab_item, attr, None)
                    if callable(val):
                        if attr in _safe_callable_metadata:
                            val = val()
                        else:
                            continue
                    if key == 'path':
                        val = val[len(base_path):]
                    if (
                        key not in translate_ignored and
                        isinstance(val, six.string_types)
                    ):
                        item[key] = translate(
                            _(safe_unicode(val)),
                            context=self.request
                        )
                    else:
                        item[key] = val
                    if key == 'getMimeIcon':
                        item[key] = None
                        # get mime type icon url from mimetype registry'
                        contenttype = aq_base(
                            getattr(vocab_item, 'mime_type', None))
                        if contenttype:
                            ctype = mtt.lookup(contenttype)
                            item[key] = '/'.join([
                                base_path,
                                guess_icon_path(ctype[0])])
                items.append(item)
        else:
            items = [{'id': item.value,
                      'text': item.title} for item in results]

        if total == 0:
            total = len(items)

        return json_dumps({
            'results': items,
            'total': total
        })
示例#20
0
    def __call__(self):
        """
        Accepts GET parameters of:
        name: Name of the vocabulary
        field: Name of the field the vocabulary is being retrieved for
        query: string or json object of criteria and options.
            json value consists of a structure:
                {
                    criteria: object,
                    sort_on: index,
                    sort_order: (asc|reversed)
                }
        attributes: comma seperated, or json object list
        batch: {
            page: 1-based page of results,
            size: size of paged results
        }
        """
        context = self.get_context()
        self.request.response.setHeader('Content-Type',
                                        'application/json; charset=utf-8')

        try:
            vocabulary = self.get_vocabulary()
        except VocabLookupException as e:
            return json_dumps({'error': e.message})

        results_are_brains = False
        if hasattr(vocabulary, 'search_catalog'):
            query = self.parsed_query()
            results = vocabulary.search_catalog(query)
            results_are_brains = True
        elif hasattr(vocabulary, 'search'):
            try:
                query = self.parsed_query()['SearchableText']['query']
            except KeyError:
                results = iter(vocabulary)
            else:
                results = vocabulary.search(query)
        else:
            results = vocabulary

        try:
            total = len(results)
        except TypeError:
            # do not error if object does not support __len__
            # we'll check again later if we can figure some size
            # out
            total = 0

        # get batch
        batch = _parseJSON(self.request.get('batch', ''))
        if batch and ('size' not in batch or 'page' not in batch):
            batch = None  # batching not providing correct options
        if batch:
            # must be slicable for batching support
            page = int(batch['page'])
            size = int(batch['size'])
            if size > MAX_BATCH_SIZE:
                raise Exception('Max batch size is 500')
            # page is being passed in is 1-based
            start = (max(page - 1, 0)) * size
            end = start + size
            # Try __getitem__-based slice, then iterator slice.
            # The iterator slice has to consume the iterator through
            # to the desired slice, but that shouldn't be the end
            # of the world because at some point the user will hopefully
            # give up scrolling and search instead.
            try:
                results = results[start:end]
            except TypeError:
                results = itertools.islice(results, start, end)

        # build result items
        items = []

        attributes = _parseJSON(self.request.get('attributes', ''))
        if isinstance(attributes, six.string_types) and attributes:
            attributes = attributes.split(',')

        translate_ignored = self.get_translated_ignored()
        if attributes:
            base_path = self.get_base_path(context)
            sm = getSecurityManager()
            can_edit = sm.checkPermission(DEFAULT_PERMISSION_SECURE, context)
            mtt = getToolByName(self.context, 'mimetypes_registry')
            for vocab_item in results:
                if not results_are_brains:
                    vocab_item = vocab_item.value
                item = {}
                for attr in attributes:
                    key = attr
                    if ':' in attr:
                        key, attr = attr.split(':', 1)
                    if attr in _unsafe_metadata and not can_edit:
                        continue
                    if key == 'path':
                        attr = 'getPath'
                    val = getattr(vocab_item, attr, None)
                    if callable(val):
                        if attr in _safe_callable_metadata:
                            val = val()
                        else:
                            continue
                    if key == 'path':
                        val = val[len(base_path):]
                    if (key not in translate_ignored
                            and isinstance(val, six.string_types)):
                        item[key] = translate(_(safe_unicode(val)),
                                              context=self.request)
                    else:
                        item[key] = val
                    if key == 'getMimeIcon':
                        item[key] = None
                        # get mime type icon url from mimetype registry'
                        contenttype = aq_base(
                            getattr(vocab_item, 'mime_type', None))
                        if contenttype:
                            ctype = mtt.lookup(contenttype)
                            item[key] = '/'.join(
                                [base_path,
                                 guess_icon_path(ctype[0])])
                items.append(item)
        else:
            items = [{
                'id': item.value,
                'text': item.title
            } for item in results]

        if total == 0:
            total = len(items)

        return json_dumps({'results': items, 'total': total})
示例#21
0
 def iconurl(self):
    "get URL for showing the icon"
    base =  api.portal.get().absolute_url()
    mt = self.mimetype()
    return (base + '/' + guess_icon_path(mt)) if mt else ""