Esempio n. 1
0
    def output_relative_to(self, context):
        """Transforms the raw value to the output mimetype, within a specified context.

        If the value's mimetype is already the same as the output mimetype,
        no transformation is performed.

        The context parameter is relevant when the transformation is
        context-dependent. For example, Plone's resolveuid-and-caption
        transform converts relative links to absolute links using the context
        as a base.

        If a transformer cannot be found for the specified context, a
        transformer with the site as a context is used instead.
        """
        if self.mimeType == self.outputMimeType:
            if six.PY2:
                return self.raw_encoded
            else:
                return self.raw

        transformer = ITransformer(context, None)
        if transformer is None:
            site = getSite()
            transformer = ITransformer(site, None)
            if transformer is None:
                return None

        return transformer(self, self.outputMimeType)
Esempio n. 2
0
 def text_output(self):
     # XXX: a workaround for https://dev.plone.org/ticket/12442
     text = self.context.text
     site = getSite()
     if text.mimeType == text.outputMimeType:
         return text.raw_encoded
     else:
         transformer = ITransformer(site, None)
         if transformer is None:
             return None
         transformer.context = self.context  # set the transform context
         return transformer(text, text.outputMimeType)
 def getText(self):
     text = ''
     if self.data['text']:
         transformer = ITransformer(self.context, None)
         if transformer is not None:
             text = transformer(self.data['text'], 'text/x-html-safe')
     return text
Esempio n. 4
0
    def get_transformer(self, context=None):
        if not context:
            context = self

        transformer = ITransformer(context)

        return transformer
def searchable_text_indexer(obj):
    """SearchableText should contain id, title, description, body text,
    alternate text and keywords.
    """
    transformer = ITransformer(obj)

    try:
        text = transformer(obj.text, 'text/plain')
    except AttributeError:
        text = ''

    try:
        alternate_text = transformer(obj.alternate_content, 'text/plain')
    except AttributeError:
        alternate_text = ''

    keywords = u' '.join(safe_unicode(s) for s in obj.Subject())

    return u' '.join((
        safe_unicode(obj.id),
        safe_unicode(obj.title) or u'',
        safe_unicode(obj.description) or u'',
        safe_unicode(text),
        safe_unicode(alternate_text),
        safe_unicode(keywords),
    ))
Esempio n. 6
0
    def get_configured_fields(self):
        context = self.context
        tileType = queryUtility(ITileType, name=self.__name__)
        conf = self.get_tile_configuration()
        fields = getFieldsInOrder(tileType.schema)
        uuid = self.data.get('uuid', '')
        results = []
        for name, field in fields:
            image_field = INamedImageField.providedBy(field)
            data = self.data[name]
            if not ((image_field and (data or uuid)) or
                    (not image_field and data)):
                # If there's no data for this field, ignore it
                # special condition, if the field is an image field and
                # there is no uuid, then ignore it too
                continue

            if isinstance(data, RichTextValue):
                transformer = ITransformer(context, None)
                if transformer is not None:
                    content = transformer(data, 'text/x-html-safe')
            else:
                content = data

            field = {'id': name, 'content': content, 'title': field.title}

            if not self._include_updated_field(field, conf.get(name)):
                continue

            results.append(field)

        return results
 def text_output(self, fname='text'):
     text = ''
     if self.data[fname]:
         transformer = ITransformer(self.context, None)
         if transformer is not None:
             text = transformer(self.data[fname], 'text/x-html-safe')
     return text
Esempio n. 8
0
    def make_plain_text(self, item):
        text = item.get('text')
        if not text:
            return ''

        transformer = ITransformer(self.context)
        value = RichTextValue(text, mimeType=item.get('_text_mime_type', 'text/html'))
        return transformer(value, 'text/plain')
Esempio n. 9
0
 def strip_text(self, item, length=500):
     transformer = ITransformer(item)
     transformedValue = transformer(item.text, 'text/plain')
     striped_length = len(transformedValue)
     if striped_length > length:
         striped_length = transformedValue.rfind(' ', 0, length)
         transformedValue = transformedValue[:striped_length] + '...'
     return transformedValue
Esempio n. 10
0
 def eip_transform(self, value):
     """ Transform a RichTextValue to text/x-html-eip
     """
     site = getSite()
     transformer = ITransformer(site, None)
     if transformer is None:
         return None
     return transformer(value, 'text/x-html-eip')
Esempio n. 11
0
 def set_title(self, value):
     self._formatted_title = value
     transformer = ITransformer(self)
     if value:
         _title = transformer(value, "text/plain").strip()
         self.title = _title
     else:
         self.title = None
Esempio n. 12
0
 def getText(self):
     """ Return the rich text stored in the tile.
     """
     text = ''
     if self.data['text']:
         transformer = ITransformer(self.context, None)
         if transformer is not None:
             text = transformer(self.data['text'], 'text/x-html-safe')
     return text
Esempio n. 13
0
def strip_text(item, length=500, ellipsis='...', item_type='richtext'):
    if item_type == 'plain':
        striped_length = len(item)
        transformedValue = item

    else:  # item_type is 'richtext'
        transformer = ITransformer(item)
        transformedValue = transformer(item.text, 'text/plain')
        striped_length = len(transformedValue)

    if striped_length > length:
        striped_length = transformedValue.rfind(' ', 0, length)
        transformedValue = transformedValue[:striped_length] + ellipsis
    return transformedValue
Esempio n. 14
0
 def getText(self):
     """ Return the rich text stored in the tile.
     """
     text = ''
     if self.data['text']:
         text = self.data['text']
         # We expect that the text has a mimeType and an output
         # attribute, but someone may be using a different widget
         # returning a simple unicode, so check that.
         if not isinstance(text, basestring):
             transformer = ITransformer(self.context, None)
             if transformer is not None:
                 text = transformer(text, 'text/x-html-safe')
     return text
def get_content(context, default=EMPTY):
    """Return the content to be used in VLibras News API calls. As the
    API doesn't accept empty payload, we need to be sure all keys have
    a default value.
    """
    title = safe_unicode(context.Title()) or default
    description = safe_unicode(context.Description()) or default

    try:
        transformer = ITransformer(context)
        text = transformer(context.text, 'text/plain')
    except AttributeError:
        text = u''
    content = safe_unicode(text) or default

    return dict(title=title, description=description, content=content)
Esempio n. 16
0
    def get_configured_fields(self):
        context = self.context
        tileType = queryUtility(ITileType, name=self.__name__)
        conf = self.get_tile_configuration()
        fields = getFieldsInOrder(tileType.schema)
        uuid = self.data.get('uuid', '')
        results = []
        for name, field in fields:
            image_field = INamedImageField.providedBy(field)
            data = self.data[name]
            if not ((image_field and (data or uuid)) or
                    (not image_field and data)):
                # If there's no data for this field, ignore it
                # special condition, if the field is an image field and
                # there is no uuid, then ignore it too
                continue

            if isinstance(data, RichTextValue):
                transformer = ITransformer(context, None)
                if transformer is not None:
                    content = transformer(data, 'text/x-html-safe')
            else:
                content = data

            field = {'id': name, 'content': content, 'title': field.title}

            if name in conf:
                field_conf = conf[name]
                if (field_conf.get('visibility', '') == u'off'):
                    # If the field was configured to be invisible, then just
                    # ignore it
                    continue

                if 'htmltag' in field_conf:
                    # If this field has the capability to change its html tag
                    # render, save it here
                    field['htmltag'] = field_conf['htmltag']

                if 'imgsize' in field_conf:
                    field['scale'] = field_conf['imgsize'].split()[0]

                if 'position' in field_conf:
                    field['position'] = field_conf['position']

            results.append(field)

        return results
Esempio n. 17
0
def searchableText(obj):
    """Return searchable text to be used as indexer. Includes id, title,
    description and text from Rich Text tiles."""
    transformer = ITransformer(obj)
    tiles_text = ''
    for t in obj.list_tiles('collective.cover.richtext'):
        tile = obj.restrictedTraverse(
            '@@collective.cover.richtext/{0}'.format(str(t)))
        tiles_text += transformer(tile.data['text'], 'text/plain')

    searchable_text = [safe_unicode(entry) for entry in (
        obj.id,
        obj.Title(),
        obj.Description(),
        tiles_text,
    ) if entry]

    return u' '.join(searchable_text)
def handle_richtext_description(context, logger=None):
    """Convert old Program richtext description fields to regular text, and
    move their value to the new rich_description field"""
    if logger is None:
        # Called as upgrade step: define our own logger.
        logger = logging.getLogger('uwosh.oie.studyabroadstudent')
    catalog = api.portal.get_tool('portal_catalog')
    brains = catalog(portal_type='OIEStudyAbroadProgram')
    count = 0
    for brain in brains:
        obj = brain.getObject()
        description = obj.description, RichText
        if isinstance(description, RichTextValue):
            obj.rich_description = description
            transformer = ITransformer(obj)
            obj.description = transformer(obj.description, 'text/plain')
        logger.info('converted rich description for {0}'.format(obj.title))
        count += 1
    logger.info('{0} items migrated'.format(count))
Esempio n. 19
0
    def searched_text(self):
        """ The text searched
        """
        parts = [self.title, self.description]
        transformer = ITransformer(self)

        infocard_view = api.content.get_view("infocard_view", self,
                                             self.REQUEST)
        for x in infocard_view.allowed_infos:
            card = None
            if x.get("uid_card"):
                card = api.content.get(UID=x["uid_card"])
            if card and card.text:
                if isinstance(card.text, unicode):
                    parts.append(card.text)
                else:
                    parts.append(transformer(card.text, "text/plain"))

        return u" ".join(set(u" ".join(parts).lower().split()))
Esempio n. 20
0
    def __call__(self, value=None, fieldName=None, mimeType=None):
        context = aq_inner(self.context)

        if fieldName is None:
            fieldName = self.fieldName

        if value is None:
            value = getattr(context, fieldName)

        if mimeType is None:
            if not self.major or not self.minor:
                mimeType = value.outputMimeType
            else:
                mimeType = "%s/%s" % (
                    self.major,
                    self.minor,
                )

        transformer = ITransformer(context)
        return transformer(value, mimeType)
Esempio n. 21
0
def textIndexer(context):
    """SearchableText contains id, title, variants and definition
    text as plain text.
    """
    transformer = ITransformer(context)

    try:
        definition = transformer(context.definition, "text/plain")
    except AttributeError:
        definition = u""
    try:
        variants = u" ".join(context.variants)
    except TypeError:
        variants = u""

    return u" ".join((
        safe_unicode(context.id),
        safe_unicode(context.title) or u"",
        safe_unicode(variants),
        safe_unicode(definition),
    ))
Esempio n. 22
0
def update_to_33(context):
    """ Fix the value of the source field since we changed the field from
        richtext to textline
    """

    return
    catalog = portal.get_tool(name='portal_catalog')
    query = {
        'portal_type': [
            'eea.climateadapt.aceproject',
            'eea.climateadapt.adaptationoption',
            'eea.climateadapt.casestudy',
            'eea.climateadapt.guidancedocument',
            'eea.climateadapt.indicator',
            'eea.climateadapt.informationportal',
            'eea.climateadapt.mapgraphdataset',
            'eea.climateadapt.organisation',
            'eea.climateadapt.publicationreport',
            'eea.climateadapt.researchproject',
            'eea.climateadapt.tool',
        ]
    }
    results = catalog.searchResults(**query)

    for brain in results:
        try:
            obj = brain.getObject()
        except:
            logger.warn("SKIPPED %s", brain.getURL())

            continue

        if hasattr(obj, 'source'):
            if obj.source:
                bumblebee = ITransformer(obj)
                obj.source = bumblebee(obj.source, 'text/plain')
                logger.info("Migrated source field for %s", obj.absolute_url())
                obj._p_changed = True
                obj.reindexObject()
Esempio n. 23
0
    def options(self):
        mapping = super(NewIssueMail, self).options()
        context = aq_inner(self.context)
        portal = getSite()
        portal_membership = getToolByName(portal, 'portal_membership')
        issueCreator = context.Creator()
        issueCreatorInfo = portal_membership.getMemberInfo(issueCreator)
        issueAuthor = issueCreator
        if issueCreatorInfo:
            issueAuthor = issueCreatorInfo['fullname'] or issueCreator

        issueText = context.details.output
        paras = issueText.splitlines()
        issueDetails = '\n'.join([wrapper.fill(p) for p in paras])
        transformer = ITransformer(context)
        issuePlainText = transformer(context.details, 'text/plain')
        issuePlainDetails = '\n'.join([wrapper.fill(p) for p in paras])
        paras = issuePlainText.splitlines()
        mapping['issue_author'] = su(issueAuthor)
        mapping['issue_details'] = su(issueDetails)
        mapping['issue_plain_details'] = su(issuePlainDetails)
        return mapping
Esempio n. 24
0
def textIndexer(obj):
    """SearchableText contains id, title, subtitle, abstract, author and body
    text as plain text.
    """
    transformer = ITransformer(obj)
    text = obj.text
    if text:
        text = transformer(obj.text, 'text/plain')

    searchable_text = [
        safe_unicode(entry) for entry in (
            obj.id,
            obj.Title(),
            obj.subtitle,
            obj.Description(),
            obj.byline,
            text,
            obj.location,
        ) if entry
    ]

    return u' '.join(searchable_text)
Esempio n. 25
0
    def get_configured_fields(self):
        tileType = queryUtility(ITileType, name=self.__name__)
        conf = self.get_tile_configuration()

        fields = getFieldsInOrder(tileType.schema)

        results = []
        for name, obj in fields:
            if not self.data[name]:
                # If there's no data for this field, ignore it
                continue

            if isinstance(self.data[name], RichTextValue):
                transformer = ITransformer(self.context, None)
                if transformer is not None:
                    content = transformer(self.data[name], 'text/x-html-safe')
            else:
                content = self.data[name]

            field = {'id': name, 'content': content, 'title': obj.title}
            if name in conf:
                field_conf = conf[name]
                if ('visibility' in field_conf
                        and field_conf['visibility'] == u'off'):
                    # If the field was configured to be invisible, then just
                    # ignore it
                    continue

                if 'htmltag' in field_conf:
                    # If this field has the capability to change its html tag
                    # render, save it here
                    field['htmltag'] = field_conf['htmltag']

            results.append(field)

        return results
Esempio n. 26
0
def _strip_text(item, length=500, ellipsis='...'):
    transformer = ITransformer(item)
    transformedValue = transformer(item.text, 'text/plain')
    return Plone.cropText(transformedValue, length=length, ellipsis=ellipsis)
Esempio n. 27
0
    def __call__(self):

        path = '/'.join(__file__.split('/')[:-1])
        path = path + "/VVT-Vorlage.docx"

        doc = DocxTemplate(path)

        personenlist = list()
        personen = self.context.beteiligte_personen_und_ihre_rollen
        if personen:
            for i in range(len(personen)):
                key = 'person%s' % str(i + 1)
                personenlist.append((key, personen[i]))

        transformer = ITransformer(self.context)
        transformedValue = u''
        if self.context.beschreibung_massnahmen:
            transformedValue = transformer(
                self.context.beschreibung_massnahmen, 'text/plain')

        anmerkung = self.context.anmerkung_zum_status
        if not anmerkung:
            anmerkung = u''

        begruendung = self.context.begruendung
        if not begruendung:
            begruendung = u''

        erlaeuterung = self.context.datenschutz_erlaeuterung
        if not erlaeuterung:
            erlaeuterung = u''

        aktenzeichen = self.context.aktenzeichen
        if not aktenzeichen:
            aktenzeichen = u''

        datum = self.context.datumsangabe
        if datum:
            datum = datum.strftime('%d.%m.%Y')

        pruefdatum = self.context.pruefung_bis_wann
        if pruefdatum:
            pruefdatum = pruefdatum.strftime('%d.%m.%Y')

        context = {
            'title': self.context.title,
            'document_id': self.context.dokument_id,
            'aktenzeichen': aktenzeichen,
            'verantwortlicher': self.context.verantwortlicher,
            'angaben_zu_verantwortlichen':
            self.context.angaben_zu_verantwortlichen,
            'status': self.context.status,
            'anmerkung_zum_status': anmerkung,
            'datenschutzbeauftragter': self.context.datenschutzbeauftragter,
            'zwecke': self.context.zwecke,
            'rechtsgrundlagen_befugnis':
            self.context.rechtsgrundlagen_befugnis,
            'dienststelle_sachgebiet_abteilung':
            self.context.dienststelle_sachgebiet_abteilung,
            'datumsangabe': datum,
            'datenschutz_folgenabschatzung_erforderlich':
            self.context.datenschutz_folgenabschatzung_erforderlich,
            'pruefung_bis_wann': pruefdatum,
            'begruendung': begruendung,
            'vorliegen_stellungnahme': self.context.vorliegen_stellungnahme,
            'datenschutz_erlaeuterung': erlaeuterung,
            'beschreibung_massnahmen': transformedValue,
        }

        for i in personenlist:
            context[i[0]] = i[1]

        count = 0
        for i in self.context.kategorien_personen:
            key = 'kategorien_personen%s' % count
            context[key] = i['bezeichnung']
            count += 1

        count = 0
        for i in self.context.kategorien_daten:
            key = 'kategorien_daten%s' % count
            context[key] = i['bezeichnung']
            count += 1

        count = 0
        for i in self.context.kategorien_empfaenger:
            key1 = 'kategorien_empfaenger_emp%s' % count
            key2 = 'kategorien_empfaenger_offen%s' % count
            context[key1] = i['bezeichnung']
            context[key2] = i['anmerkung']
            count += 1

        count = 0
        for i in reversed(self.context.internationale_organisationen):
            key1 = 'uebermittlung_drittland%s' % count
            key2 = 'uebermittlung_garantien%s' % count
            context[key1] = i['bezeichnung']
            context[key2] = i['anmerkung']
            count += 1

        count = 0
        for i in self.context.loeschfristen:
            key = 'loeschung%s' % count
            context[key] = i['bezeichnung']
            count += 1

        count = 0
        for i in reversed(self.context.anlagen_beschreibung):
            key1 = 'anlagen_bezeichnung%s' % count
            key2 = 'anlagen_anmerkung%s' % count
            if not i.get('link'):
                context[key1] = i['bezeichnung']
            else:
                context[key1] = "%s (%s)" % (i['bezeichnung'], i['link'])
            context[key2] = i['anmerkung']
            count += 1

        count = 0
        for i in self.context.aenderungen:
            key1 = 'aenderungen_wann%s' % count
            key2 = 'aenderungen_wer%s' % count
            key3 = 'aenderungen_was%s' % count
            context[key1] = i['wann'].strftime("%d.%m.%Y")
            context[key2] = i['wer']
            context[key3] = i['was']
            count += 1

        doc.render(context)

        savepath = '/tmp/changed'
        doc.save(savepath)

        file = open(savepath, 'rb')
        file.seek(0)

        RESPONSE = self.request.response
        RESPONSE.setHeader(
            'content-type',
            'application/application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )
        RESPONSE.setHeader(
            'content-disposition',
            'attachment; filename=verarbeitungstaetigkeit.docx')
        return file.read()