Beispiel #1
0
    def getDetails(self):
        """Builds a JSON object based on the details
           of this object.
        """

        utility = getToolByName(aq_inner(self.context), 'portal_tinymce')
        anchor_portal_types = {}
        for apt in utility.containsanchors.splitlines():
            if apt and '|' in apt:
                type_, field = apt.split('|', 1)
            else:
                type_ = apt
                field = ''
            anchor_portal_types[type_] = field

        image_portal_types = utility.imageobjects.splitlines()

        portal_type = self.context.portal_type

        results = {}
        results['title'] = self.context.title_or_id()
        results['url'] = self.context.absolute_url()
        results['description'] = self.context.Description()
        results['portal_type'] = portal_type
        results['uid_relative_url'] = 'resolveuid/' + uuidFor(self.context)
        results['uid_url'] = self._getPloneUrl() + '/resolveuid/' + uuidFor(self.context)

        if portal_type in image_portal_types:
            images = self.context.restrictedTraverse('@@images')

            # TODO: support other contenttypes
            field_name = 'image'
            results['thumb'] = '%s/@@images/%s/%s' % (results['uid_url'], field_name, 'thumb')
            sizes = images.getAvailableSizes(field_name)
            scales = [{'value': '@@images/%s/%s' % (field_name, key),
                       'size': size,
                       'title': key.capitalize()} for key, size in sizes.items()]
            scales.sort(key=lambda x: x['size'][0])
            original_size = images.getImageSize(field_name)
            if original_size[0] < 0 or original_size[1] < 0:
                original_size = (0, 0)
            scales.insert(0, {'value': '',
                              'title': 'Original',
                              'size': original_size})
            results['scales'] = scales
        else:
            results['thumb'] = ""

        if portal_type in anchor_portal_types:
            content_anchors = self.context.restrictedTraverse('@@content_anchors')
            fieldname = anchor_portal_types[portal_type]
            results['anchors'] = content_anchors.listAnchorNames(fieldname)
        else:
            results['anchors'] = []
        results.update(self.additionalDetails())

        self.context.REQUEST.response.setHeader("Content-type", "application/json")
        return json.dumps(results)
Beispiel #2
0
    def _setfile(self, obj):
        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityImage(obj):
                return self.errorMessage(
                    _("The content-type '%s' has no image-field!" % metatype))
        else:
            form = self.context.REQUEST
            if not 'uploadfile' in form:
                return self.errorMessage("Could not find file in request")
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, form['uploadfile'])
            from Products.Archetypes.event import ObjectInitializedEvent
            notify(ObjectInitializedEvent(obj))

        if not obj:
            return self.errorMessage("Could not upload the file")

        obj.reindexObject()

        if self.utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return path
    def getDetails(self):
        """Builds a JSON object based on the details
           of this object.
        """

        utility = getUtility(ITinyMCE)
        anchor_portal_types = utility.containsanchors.split('\n')
        image_portal_types = utility.imageobjects.split('\n')

        results = {}
        results['title'] = self.context.title_or_id()
        results['description'] = self.context.Description()

        if self.context.portal_type in image_portal_types:
            image_url = self._getPloneUrl() + '/resolveuid/' + uuidFor(self.context)
            field_name = 'image'
            images = self.context.restrictedTraverse('@@images')

            results['thumb'] = '%s/@@images/%s/%s' % (image_url, field_name, 'thumb')
            sizes = images.getAvailableSizes(field_name)
            scales = [{'value': '@@images/%s/%s' % (field_name, key),
                       'size': size,
                       'title': key.capitalize()} for key, size in sizes.items()]
            scales.sort(lambda x, y: cmp(x['size'][0], y['size'][0]))
            original_size = images.getImageSize(field_name)
            if original_size[0] < 0 or original_size[1] < 0:
                original_size = (0, 0)
            scales.insert(0, {'value': '',
                              'title': 'Original',
                              'size': original_size})
            results['scales'] = scales
        else:
            results['thumb'] = ""

        if self.context.portal_type in anchor_portal_types:
            content_anchors = self.context.restrictedTraverse('@@content_anchors')
            results['anchors'] = content_anchors.listAnchorNames()
        else:
            results['anchors'] = []
        results.update(self.additionalDetails())

        return json.dumps(results)
Beispiel #4
0
    def upload(self):
        """Adds uploaded file"""

        object = aq_inner(self.context)
        if not IFolderish.providedBy(object):
            object = object.getParentNode()

        context = self.context
        request = context.REQUEST
        ctr_tool = getToolByName(self.context, 'content_type_registry')
        id = request['uploadfile'].filename

        content_type = request['uploadfile'].headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if we are allowed to create an Image in folder
        if not typename in [t.id for t in context.getAllowedTypes()]:
            return self.errorMessage(_("Not allowed to upload a file of this type to this folder"))

        # 2) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission('Add portal content', context):
            return self.errorMessage(_("You do not have permission to upload files in this folder"))

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        title = request['uploadtitle']
        description = request['uploaddescription']

        newid = context.invokeFactory(type_name=typename, id=id)

        if newid is None or newid == '':
            newid = id

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses a custom storage

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        # set primary field
        pf = obj.getPrimaryField()
        pf.set(obj, request['uploadfile'])

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()

        utility = getUtility(ITinyMCE)
        if utility.link_using_uids:
            return self.okMessage("resolveuid/%s" % (uuidFor(obj)))
        return self.okMessage("%s" % (obj.absolute_url()))
Beispiel #5
0
    def upload(self):
        """Adds uploaded file"""
        context = aq_inner(self.context)
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        context = self.context
        request = context.REQUEST
        ctr_tool = getToolByName(context, 'content_type_registry')
        id = request['uploadfile'].filename

        content_type = request['uploadfile'].headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if we are allowed to create an Image in folder
        if not typename in [t.id for t in context.getAllowedTypes()]:
            return self.errorMessage(
                "Not allowed to upload a file of this type to this folder")

        # 2) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
                'Add portal content', context):
            return self.errorMessage(
                "You do not have permission to upload files in this folder")

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        title = request['uploadtitle']
        description = request['uploaddescription']

        newid = context.invokeFactory(type_name=typename, id=id)

        if newid is None or newid == '':
            newid = id

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses a custom storage

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityImage(obj):
                return self.errorMessage(
                    _("The content-type '%s' has no image-field!" % metatype))
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, request['uploadfile'])

        if not obj:
            return self.errorMessage("Could not upload the file")

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        utility = getToolByName(context, 'portal_tinymce')
        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return self.okMessage(path, folder)
Beispiel #6
0
    def upload(self):  # NOQA
        """Adds uploaded file"""
        context = aq_inner(self.context)
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        request = context.REQUEST
        ctr_tool = getToolByName(context, 'content_type_registry')
        utility = getToolByName(context, 'portal_tinymce')

        uploadfile = request['uploadfile']
        id = uploadfile.filename
        content_type = uploadfile.headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
                'Add portal content', context):
            return self.errorMessage(
                _("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split('/')[0] == 'image':
            image_portal_types = utility.imageobjects.split('\n')
            uploadable_types += [
                t for t in image_portal_types
                if t in allowed_types and t not in uploadable_types
            ]

        # limitfilesizepanel check
        size_check = self.check_file_size(uploadable_types, request)
        if size_check and not size_check.get('valid', False):
            msg = lfspmf(
                'validation_error',
                default=
                u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)",  # NOQA
                mapping={
                    'size': safe_unicode("%.1f" % size_check.get('sizeMB')),
                    'max': safe_unicode("%.1f" % size_check.get('maxsize'))
                })
            return self.errorMessage(msg)
        # end otf limitfilesizepanel check

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id)
                if newid is None or newid == '':
                    newid = id
                break
            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(
                _("Not allowed to upload a file of this type to this folder"))

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses
        # a custom storage
        title = request['uploadtitle']
        description = request['uploaddescription']

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityItem(obj, uploadfile, id):
                msg = _(
                    "The content-type '${type}' has no image- or file-field!",
                    mapping={'type': metatype})
                return self.errorMessage(msg)
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, uploadfile)

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()

        tiny_pkg = pkg_resources.get_distribution("Products.TinyMCE")
        if tiny_pkg.version.startswith('1.2'):
            # Plone < 4.3
            return self.okMessage(path)
        else:
            # Plone >= 4.3
            return self.okMessage(path, folder)
    def upload(self):
        """Adds uploaded file"""

        object = aq_inner(self.context)
        if not IFolderish.providedBy(object):
            object = aq_parent(object)

        context = self.context
        request = context.REQUEST
        ctr_tool = getToolByName(self.context, "content_type_registry")
        utility = getUtility(ITinyMCE)

        id = request["uploadfile"].filename
        content_type = request["uploadfile"].headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission("Add portal content", context):
            return self.errorMessage(_("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split("/")[0] == "image":
            image_portal_types = utility.imageobjects.split("\n")
            uploadable_types += [t for t in image_portal_types if t in allowed_types and t not in uploadable_types]

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        title = request["uploadtitle"]
        description = request["uploaddescription"]

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id)
                if newid is None or newid == "":
                    newid = id

                obj = getattr(context, newid, None)

                # set primary field
                pf = obj.getPrimaryField()
                pf.set(obj, request["uploadfile"])
                break

            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(_("Not allowed to upload a file of this type to this folder"))

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses a custom storage
        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()

        if utility.link_using_uids:
            return self.okMessage("resolveuid/%s" % (uuidFor(obj)))

        return self.okMessage("%s" % (obj.absolute_url()))
Beispiel #8
0
    def object_check(self, object):
        """Check the relative links within this object."""
        def checklink(match):
            matched = match.group(0)
            newlink = link = decodeEntities(match.group('href'))
            classification, uid, relpath, tail = self.classifyLink(link, base)

            if self.action=='check':
                if classification=='bad':
                    abslink = urljoin(base, link)
                    before, after = self.link_summary(data, match.start(), link)
                    summary = {'text':link, 'url':abslink,
                        'before': before,
                        'after': after, }
                    info.append(summary)
            elif self.action=='touid':
                if classification=='internal':
                    if uid and uid==objuid:
                        newlink = tail
                    elif uid:
                        newlink = 'resolveuid/%s%s' % (uid, tail)
                    else:
                        newlink = relpath+tail

            elif self.action=='topath':
                if classification=='internal':
                    newlink = relpath+tail

            if newlink != link:
                prefix = match.group('prefix')
                newlink = html_quote(newlink).encode('ascii', 'xmlcharrefreplace')
                changes.append((match.start()+len(prefix), match.end(), newlink))
                return prefix + newlink
            return matched

        info = []
        changes = []
        try:
            objuid = uuidFor(aq_base(object))
        except:
            return None  # only archetypes objects

        baseobj = object
        if object.portal_type==FRAGMENT_TYPE:
            baseobj = object.aq_parent.aq_parent.aq_parent
        base = baseobj.absolute_url()
        if getattr(baseobj.aq_explicit, 'isPrincipiaFolderish', 0):
            base += '/'

        field = object.getField(self.fieldname)
        if field is None:
            return None

        content_type = field.getContentType(object)
        if content_type != 'text/html':
            # Don't attempt to modify non-html
            return None
            
        data = field.getEditAccessor(object)().decode('utf8')
        __traceback_info__ = (object, data)
        newdata = LINK_PATTERN.sub(checklink, data)
        if data != newdata and self.commit_changes:
            mutator = field.getMutator(object)
            if mutator:
                mutator(newdata.encode('utf8'), mimetype='text/html')
                object.reindexObject() # Need to flag update

        if info or changes:
            self.found += 1
            title = object.Title()
            if not title:
                title = object.getId()
            if not title:
                title = '<object>'
            if object.portal_type == FRAGMENT_TYPE:
                title = "%s (%s)" % (baseobj.title_or_id(), title)
            if data != newdata:
                diffs = htmlchanges(data, changes)
            else:
                diffs = None
            return dict(title=title, uid = objuid, info=info, url=baseobj.absolute_url_path(),
                diffs=diffs)
        return None
Beispiel #9
0
    def upload(self):
        """Adds uploaded file.

        Required params: uploadfile, uploadtitle, uploaddescription
        """
        context = aq_inner(self.context)
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        request = context.REQUEST
        ctr_tool = getToolByName(context, 'content_type_registry')
        utility = getToolByName(context, 'portal_tinymce')

        file_id = request['uploadfile'].filename
        content_type = request['uploadfile'].headers["Content-Type"]
        typename = ctr_tool.findTypeName(file_id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
                'Add portal content', context):
            return self.errorMessage(
                _("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split('/')[0] == 'image':
            image_portal_types = utility.imageobjects.split('\n')
            uploadable_types += [t for t in image_portal_types
                                 if t in allowed_types
                                 and t not in uploadable_types]

        # Get an unused filename without path
        file_id = self.cleanupFilename(file_id)

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=file_id)
                if newid is None or newid == '':
                    newid = file_id
                break
            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(
                _("Not allowed to upload a file of this type to this folder"))

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses
        # a custom storage
        title = request['uploadtitle']
        description = request['uploaddescription']

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityObject(obj, file_id):
                return self.errorMessage(
                        _("The content-type '${type}' has no image- or file-field!",
                          mapping={'type': metatype}))
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, request['uploadfile'])

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return self.okMessage(path, folder)
    def upload(self):  # NOQA
        """Adds uploaded file"""
        context = aq_inner(self.context)
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        request = context.REQUEST
        ctr_tool = getToolByName(context, 'content_type_registry')
        utility = getToolByName(context, 'portal_tinymce')

        uploadfile = request['uploadfile']
        id = uploadfile.filename
        content_type = uploadfile.headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
                'Add portal content', context):
            return self.errorMessage(
                _("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split('/')[0] == 'image':
            image_portal_types = utility.imageobjects.split('\n')
            uploadable_types += [
                t for t in image_portal_types
                if t in allowed_types and t not in uploadable_types]

        # limitfilesizepanel check
        size_check = self.check_file_size(uploadable_types, request)
        if size_check and not size_check.get('valid', False):
            msg = lfspmf(
                'validation_error',
                default=u"Validation failed. Uploaded data is too large: ${size}MB (max ${max}MB)",  # NOQA
                mapping={
                    'size': safe_unicode("%.1f" % size_check.get('sizeMB')),
                    'max': safe_unicode("%.1f" % size_check.get('maxsize'))
                }
            )
            return self.errorMessage(msg)
        # end otf limitfilesizepanel check

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id)
                if newid is None or newid == '':
                    newid = id
                break
            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(
                _("Not allowed to upload a file of this type to this folder"))

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses
        # a custom storage
        title = request['uploadtitle']
        description = request['uploaddescription']

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityItem(obj, uploadfile, id):
                msg = _(
                    "The content-type '${type}' has no image- or file-field!",
                    mapping={'type': metatype})
                return self.errorMessage(msg)
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, uploadfile)

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()

        tiny_pkg = pkg_resources.get_distribution("Products.TinyMCE")
        if tiny_pkg.version.startswith('1.2'):
            # Plone < 4.3
            return self.okMessage(path)
        else:
            # Plone >= 4.3
            return self.okMessage(path, folder)
Beispiel #11
0
    def info_object(self, obj, allowLink=True):
        '''Get information from a content object'''

        # Parent folder might not be accessible if we came here from a
        # search.
        if not self.security.checkPermission('View', obj):
            return None

        __traceback_info__ = (obj, allowLink)
        id = None
        UID = None
        try:
            UID = uuidFor(obj.aq_explicit)
            if UID:
                id = UID
            else:
                id = obj.absolute_url(relative=1)

            portal_type = getattr(obj, 'portal_type','')
            collection = portal_type in self.coll_types
            tool = self.tool
            url = obj.absolute_url()
            preview = tool.getPreviewUrl(portal_type, url)

            if collection and self.resource_type.allow_browse:
                src = obj.absolute_url()
                if not src.endswith('/'): src += '/'
                src += self.srctail
            else:
                src = None

            if UID and self.linkbyuid:
                url = self.base+'/resolveuid/%s' % UID

            if self.showimagesize:
                normal = tool.getNormalUrl(portal_type, url)
            else:
                normal = url

            sizes = self.get_image_sizes(obj, portal_type, url)
            defscale = self.tool.getDefaultScaleForType(portal_type)

            media = self.media(portal_type)
            classes = self.classes(portal_type)

            icon = self.icon(portal_type)
            size, width, height = self.sizes(obj)

            title = filterControlChars(obj.Title() or obj.getId())
            description = newline_to_br(html_quote(obj.Description()))

            linkable = None
            if allowLink:
                linkable = True
                collection = False

            anchor = portal_type in self.anchor_types
            review_state, className = self.getState(self.workflow_tool.getInfoFor(obj, 'review_state', None))

            return {
                'id': id,
                'url': normal,
                'portal_type': portal_type,
                'collection':  collection,
                'icon': icon,
                'size': size,
                'width': width,
                'height': height,
                'preview': preview,
                'sizes': sizes,
                'defscale': defscale,
                'media': media,
                'classes': classes,
                'title': title,
                'description': description,
                'linkable': linkable,
                'src': src,
                'anchor': anchor,
                'state': review_state,
                'class': className,
                }
        except Unauthorized:
            return None
Beispiel #12
0
    def upload(self):
        """Adds uploaded file"""

        object = aq_inner(self.context)
        if not IFolderish.providedBy(object):
            object = aq_parent(object)

        context = self.context
        request = context.REQUEST
        ctr_tool = getToolByName(self.context, 'content_type_registry')
        utility = getUtility(ITinyMCE)

        id = request['uploadfile'].filename
        content_type = request['uploadfile'].headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
                'Add portal content', context):
            return self.errorMessage(
                _("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split('/')[0] == 'image':
            image_portal_types = utility.imageobjects.split('\n')
            uploadable_types += [
                t for t in image_portal_types
                if t in allowed_types and t not in uploadable_types
            ]

        # Get an unused filename without path
        id = self.cleanupFilename(id)

        title = request['uploadtitle']
        description = request['uploaddescription']

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id)
                if newid is None or newid == '':
                    newid = id

                obj = getattr(context, newid, None)

                # set primary field
                pf = obj.getPrimaryField()
                pf.set(obj, request['uploadfile'])
                break

            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(
                _("Not allowed to upload a file of this type to this folder"))

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses a custom storage
        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()

        if utility.link_using_uids:
            return self.okMessage("resolveuid/%s" % (uuidFor(obj)))

        return self.okMessage("%s" % (obj.absolute_url()))
Beispiel #13
0
    def upload(self):
        """Adds uploaded file.

        Required params: uploadfile, uploadtitle, uploaddescription
        """
        context = aq_inner(self.context)
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        request = context.REQUEST
        ctr_tool = getToolByName(context, 'content_type_registry')
        utility = getToolByName(context, 'portal_tinymce')

        uploadfile = request['uploadfile']
        id = uploadfile.filename
        content_type = uploadfile.headers["Content-Type"]
        typename = ctr_tool.findTypeName(id, content_type, "")
        

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission(
            'Add portal content', context):
            return self.errorMessage(
                _("You do not have permission to upload files in this folder"))

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        if typename in allowed_types:
            uploadable_types = [typename]
        else:
            uploadable_types = []

        if content_type.split('/')[0] == 'image':
            image_portal_types = utility.imageobjects.split('\n')
            uploadable_types += [t for t in image_portal_types
                                    if t in allowed_types
                                       and t not in uploadable_types]
        
        
        # Change ksuess 22.01.2016 Begrenze Filegroesse
        # print "uploadfile zhkathch", uploadfile        
        portal = getSite()
        properties = getToolByName(portal, 'portal_properties')
        site_properties = getattr(properties, 'site_properties')
        maxFileSize = site_properties.getProperty('maxFileSize', 5000)
        maxImageSize = site_properties.getProperty('maxImageSize', 1000)
        maxsize = (typename=='Image' and maxImageSize or maxFileSize)
        value = uploadfile
        value.seek(0, 2) # eof
        size = value.tell()
        value.seek(0)
        size = float(size)
        sizeKB = (size / 1024)
        # print "sizeKB", sizeKB
        
        if sizeKB==0:
            msg = "Die Datei ist leer."
            return self.errorMessage(_(msg))
            
        elif sizeKB > maxsize:
            if not context.portal_membership.checkPermission('Manage portal', context):
                msg = "Die Validierung schlug fehl. Die hochgeladene Datei ist zu gross: %iKB (maximal %iKB)." % (sizeKB, maxsize)
                return self.errorMessage(_(msg))
            
        
        # Get an unused filename without path
        id = self.cleanupFilename(id)

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id)
                if newid is None or newid == '':
                    newid = id
                break
            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(_("Bad filename, please rename."))
        else:
            return self.errorMessage(
                _("Not allowed to upload a file of this type to this folder"))

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses
        # a custom storage
        title = request['uploadtitle']
        description = request['uploaddescription']

        if title:
            try:
                obj.setTitle(title)
            except AttributeError:
                obj.title = title

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityItem(obj, uploadfile):
                return self.errorMessage(
                        _("The content-type '${type}' has no image- or file-field!",
                          mapping={'type': metatype}))
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, uploadfile)

        if not obj:
            return self.errorMessage(_("Could not upload the file"))

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return self.okMessage(path, folder)
Beispiel #14
0
    def getDetails(self):
        """Builds a JSON object based on the details
           of this object.
        """

        utility = getToolByName(aq_inner(self.context), 'portal_tinymce')
        anchor_portal_types = {}
        for apt in utility.containsanchors.splitlines():
            if apt and '|' in apt:
                type_, field = apt.split('|', 1)
            else:
                type_ = apt
                field = ''
            anchor_portal_types[type_] = field

        image_portal_types = utility.imageobjects.splitlines()

        results = {}
        results['title'] = self.context.title_or_id()
        results['url'] = self.context.absolute_url()
        results['description'] = self.context.Description()
        results['uid_relative_url'] = 'resolveuid/' + uuidFor(self.context)
        results['uid_url'] = self._getPloneUrl() + '/resolveuid/' + uuidFor(
            self.context)

        if self.context.portal_type in image_portal_types:
            images = self.context.restrictedTraverse('@@images')

            # TODO: support other contenttypes
            field_name = 'image'
            results['thumb'] = '%s/@@images/%s/%s' % (results['uid_url'],
                                                      field_name, 'thumb')
            sizes = images.getAvailableSizes(field_name)
            scales = [{
                'value': '@@images/%s/%s' % (field_name, key),
                'size': size,
                'title': key.capitalize()
            } for key, size in sizes.items()]
            scales.sort(key=lambda x: x['size'][0])
            original_size = images.getImageSize(field_name)
            if original_size[0] < 0 or original_size[1] < 0:
                original_size = (0, 0)
            scales.insert(0, {
                'value': '',
                'title': 'Original',
                'size': original_size
            })
            results['scales'] = scales
        else:
            results['thumb'] = ""

        if self.context.portal_type in anchor_portal_types:
            content_anchors = self.context.restrictedTraverse(
                '@@content_anchors')
            fieldname = anchor_portal_types[self.context.portal_type]
            results['anchors'] = content_anchors.listAnchorNames(fieldname)
        else:
            results['anchors'] = []
        results.update(self.additionalDetails())

        self.context.REQUEST.response.setHeader("Content-type",
                                                "application/json")
        return json.dumps(results)
Beispiel #15
0
id = cleanupFilename(id)

newid = context.invokeFactory(type_name=typename, id=id,
    title=node_prop_title,
    description=node_prop_desc,
    )

if newid is None or newid == '':
   newid = id 

obj = getattr(context,newid, None)
obj.setImage(node_prop_image)
    
if not obj:
   return Error("Could not create %s with %s as id and %s as title!", typename,newid, node_prop_title)

obj.reindexObject() 
uuid = uuidFor(obj)
if linkbyuid and uuid:
    url = base+'/resolveuid/%s' % uuid
else:
    url = obj.absolute_url()

print "Uploaded image"
# print "content_type", content_type
# print "typename", typename
# print "RESPONSE=", RESPONSE
return TEMPLATE % ('finishUpload', url, newline_to_br(html_quote(printed)))


Beispiel #16
0
    def upload(self):
        """Adds uploaded file.

        Required params: uploadfile, uploadtitle, uploaddescription
        """
        context = aq_inner(self.context)
        self.request = context.REQUEST
        if not IFolderish.providedBy(context):
            context = aq_parent(context)

        request = context.REQUEST
        utility = getToolByName(context, "portal_tinymce")

        id_ = request["uploadfile"].filename
        content_type = request["uploadfile"].headers["Content-Type"]
        # check if container is ready to store images
        if self.is_temporary(context):
            return self.errorMessage(
                translate(_("Please save the object first" " to enable image upload."), context=self.request)
            )

        # check mime type to make sure an image is uploaded
        if not is_image(content_type):
            return self.errorMessage(translate(_("Only image upload allowed."), context=self.request))

        # Permission checks based on code by Danny Bloemendaal

        # 1) check if the current user has permissions to add stuff
        if not context.portal_membership.checkPermission("Add portal content", context):
            return self.errorMessage("You do not have permission to upload files in this folder")

        # 2) check image types uploadable in folder.
        #    priority is to content_type_registry image type
        allowed_types = [t.id for t in context.getAllowedTypes()]
        tiny_image_types = utility.imageobjects.split("\n")
        uploadable_types = []
        for typename in tiny_image_types:
            if typename in allowed_types:
                uploadable_types.append(typename)

        # Get an unused filename without path
        id_ = self.cleanupFilename(id_)

        for metatype in uploadable_types:
            try:
                newid = context.invokeFactory(type_name=metatype, id=id_)
                if newid is None or newid == "":
                    newid = id_
                break
            except ValueError:
                continue
            except BadRequest:
                return self.errorMessage(translate(_("Bad filename, please rename."), context=self.request))
        else:
            return self.errorMessage(
                translate(_("Not allowed to upload a file of this type to this folder"), context=self.request)
            )

        obj = getattr(context, newid, None)

        # Set title + description.
        # Attempt to use Archetypes mutator if there is one, in case it uses
        # a custom storage
        title = request["uploadtitle"]
        description = request["uploaddescription"]

        if description:
            try:
                obj.setDescription(description)
            except AttributeError:
                obj.description = description

        if HAS_DEXTERITY and IDexterityContent.providedBy(obj):
            if not self.setDexterityImage(obj):
                return self.errorMessage(
                    translate(_("The content-type '%s' has no image-field!" % metatype), context=self.request)
                )
        else:
            # set primary field
            pf = obj.getPrimaryField()
            pf.set(obj, request["uploadfile"])

        if not obj:
            return self.errorMessage("Could not upload the file")

        if title and title is not "":
            obj.setTitle(title)
        else:
            obj.setTitle(obj.getFilename())

        obj.reindexObject()
        folder = obj.aq_parent.absolute_url()

        if utility.link_using_uids:
            path = "resolveuid/%s" % (uuidFor(obj))
        else:
            path = obj.absolute_url()
        return self.okMessage(path, folder)