def load(self, pfg):
     data = self.getContent()
     if IAdding.providedBy(pfg):
         return data
     data['title'] = safe_unicode(pfg.Title())
     data['description'] = safe_unicode(pfg.Description())
     data['intro'] = safe_unicode(pfg.getRawFormPrologue())
Esempio n. 2
0
    def __call__(self):
        context = aq_inner(self.context)
        request = self.request
        response_id = self.validate_response_id()
        file = None
        if response_id != -1:
            response = self.folder[response_id]
            file = response.attachment
            if file is None:
                status = IStatusMessage(request)
                msg = _(u"Response id ${response_id} has no attachment.",
                        mapping=dict(response_id=response_id))
                msg = translate(msg, 'Poi', context=context)
                status.addStatusMessage(msg, type='error')
        if file is None:
            request.response.redirect(context.absolute_url())

        # From now on file exists.
        # Code mostly taken from Archetypes/Field.py:FileField.download
        filename = getattr(file, 'filename', file.getId())
        if filename is not None:
            if FILE_NORMALIZER:
                filename = IUserPreferredFileNameNormalizer(request).normalize(
                    safe_unicode(filename, context.getCharset()))
            else:
                filename = safe_unicode(filename, context.getCharset())
            header_value = contentDispositionHeader(
                disposition='attachment',
                filename=filename)
            request.response.setHeader("Content-disposition", header_value)
        return file.index_html(request, request.response)
Esempio n. 3
0
 def get_vcard(self):
     vcard = get_vcard(self.context)
     vcard.add('fn')
     vcard.fn.value = safe_unicode(self.context.Title())
     vcard.add('n')
     vcard.n.value = vobject.vcard.Name(safe_unicode(self.context.Title()))
     return vcard
Esempio n. 4
0
 def _getLink(self):
     """Private method that does the link computation without the cachekey,
        this is done so it is possible to override the cachekey."""
     completeContent = safe_unicode(self.contentValue or self.context.Title())
     content = completeContent
     if self.maxLength:
         plone_view = self.context.restrictedTraverse('@@plone')
         ellipsis = self.kwargs.get('ellipsis', '...')
         content = plone_view.cropText(completeContent, self.maxLength, ellipsis)
     icons = self.showIcons and self._icons() or ''
     title = safe_unicode(self.tag_title or completeContent.replace("'", "'"))
     icons_tag = icons and u"<span class='pretty_link_icons'>{0}</span>".format(icons) or ""
     if self.isViewable:
         url = self._get_url()
         return u"<a class='{0}'{1} href='{2}' target='{3}'>{4}" \
                u"<span class='pretty_link_content'>{5}</span></a>" \
                .format(self.CSSClasses(),
                        self.display_tag_title and u" title='{0}'".format(title) or '',
                        url,
                        self.target,
                        icons_tag,
                        safe_unicode(content))
     else:
         # append the notViewableHelpMessage
         content = u"{0} {1}".format(content, self.notViewableHelpMessage)
         return self.link_pattern.format(
             self.CSSClasses(),
             self.display_tag_title and u" title='{0}'".format(title) or '',
             icons_tag,
             safe_unicode(content))
Esempio n. 5
0
    def get_files(self, path_prefix=u"", recursive=True, toplevel=True):
        """
        Returns a list of two-value-tuples having the following values:
        - a relative path under which the file should show up in the zip
        - the data as either a file or a stream
        """
        filename = '{0}.pdf'.format(self.context.getId())

        assembler = getMultiAdapter((self.context, self.request),
                                    IPDFAssembler)

        yield (u'{0}/{1}'.format(safe_unicode(path_prefix),
                                 safe_unicode(filename)),
               StringIO(assembler.build_pdf()))

        header = get_header(self.context)
        data = get_data(self.context)
        xlsx = create_xlsx(header, data)

        filename = translate(
            _(u'participants_export_filename', default=u'participants.xlsx'),
            context=self.request
        )

        yield (u'{0}/{1}'.format(safe_unicode(path_prefix),
                                 safe_unicode(filename)), xlsx)
        
        # Recursively export folder contents.
        folder_contents = super(WorkspaceZipRepresentation, self).get_files(
            path_prefix, recursive, toplevel)

        for item in folder_contents:
            yield item
def customers_vocab_for(user=None):
    """Customers vocabulary for given or currently authenticated user.
    """
    # XXX: expect context as argument
    context = getSite()
    order_uids = get_vendor_order_uids_for(context, user=user)
    res = set(get_order(context, uid).attrs['creator'] for uid in order_uids)
    vocab = []
    for creator in res:
        if not creator:
            # Development edge case: creator might be None
            continue
        customer = plone.api.user.get(userid=creator)

        email = None
        name = None
        if customer:
            # soft dep on bda.plone.shop
            first = safe_unicode(customer.getProperty('firstname', ''))
            last = safe_unicode(customer.getProperty('lastname', ''))
            email = safe_unicode(customer.getProperty('email', ''))
            # fallback
            full = safe_unicode(customer.getProperty('fullname', ''))
            name = u'{0}, {1}'.format(last, first) if (first or last) else full

        if email and name:
            title = u'{0} ({1}) - {2}'.format(name, creator, email)
        else:
            title = creator
        vocab.append((creator, title))

    # Sort the vocab by title, normalized like sortable_title
    vocab = sorted(vocab, key=lambda x: baseNormalize(x[1]).lower())

    return vocab
Esempio n. 7
0
    def Title(self):
        """The title of the comment.
        """

        if self.title:
            return self.title

        if not self.author_name:
            author_name = translate(
                Message(_(
                    u"label_anonymous",
                    default=u"Anonymous"
                ))
            )
        else:
            author_name = self.author_name

        # Fetch the content object (the parent of the comment is the
        # conversation, the parent of the conversation is the content object).
        content = aq_base(self.__parent__.__parent__)
        title = translate(
            Message(COMMENT_TITLE,
                    mapping={'author_name': safe_unicode(author_name),
                             'content': safe_unicode(content.Title())}))
        return title
def ticket_title_generator(obj):
    """Generate a title for the ticket, also using event information.
    """

    event = obj
    ret = {
        'title': obj.title, 'eventtitle': '', 'eventstart': '', 'eventend': ''
    }

    if ITicketOccurrence.providedBy(event):
        event = aq_parent(aq_parent(event))
        # Traverse to the Occurrence object
        if IATEvent.providedBy(event):
            # get the request out of thin air to be able to publishTraverse to
            # the transient Occurrence object.
            traverser = OccTravAT(event, getRequest())
        elif IDXEvent.providedBy(event):
            # TODO
            traverser = OccTravDX(event, getRequest())
        else:
            raise NotImplementedError(
                u"There is no event occurrence traverser implementation for "
                u"this kind of object."
            )
        try:
            event = traverser.publishTraverse(getRequest(), obj.id)
        except KeyError:
            # Maybe the ticket occurrence isn't valid anymore because the
            # event occurence doesn't exist anymore.
            # Just ignore that case.
            return ret

    elif ITicket.providedBy(event):
        event = aq_parent(event)

    if IEvent.providedBy(event) or IOccurrence.providedBy(event):
        acc = IEventAccessor(event)
        lstart = ulocalized_time(
            DT(acc.start),
            long_format=True,
            context=event
        )
        lend = ulocalized_time(
            DT(acc.start),
            long_format=True,
            context=event
        )
        # XXX: no unicode, store as utf-8 encoded string instead
        ret = dict(
            title=u'%s - %s (%s - %s)' % (
                safe_unicode(acc.title),
                safe_unicode(obj.title),
                lstart,
                lend,
            ),
            eventtitle=acc.title,
            eventstart=acc.start,
            eventend=acc.end,
        )
    return ret
Esempio n. 9
0
 def set_site_title_2(self, value):
     value = value or ''
     self.portal.title_2 = value.encode(self.encoding)
     title_1 = safe_unicode(self.portal.title_1)
     title_2 = safe_unicode(self.portal.title_2)
     title = u'%s %s' % (title_1, title_2)
     self.portal.title = title.encode(self.encoding)
Esempio n. 10
0
    def __call__(self):
        colorsDict = self.calendar.queryColors
        criterias = interfaces.IListBaseQueryCriteria(self.context)()
        css = ''
        if not colorsDict:
            return css

        for fieldid, selectedItems in [(a['i'], a.get('v')) for a in criterias]:
            if not colorsDict.has_key(fieldid):
                continue

            for i in range(len(selectedItems)):
                cValName = str(component.queryUtility(IURLNormalizer).normalize(safe_unicode(selectedItems[i])))

                color = None
                for k, v in colorsDict.get(fieldid, {}).items():
                    k = safe_unicode(k)
                    if k == cValName or str(component.queryUtility(IURLNormalizer).normalize(k)) == cValName:
                        color = v
                        break
                if color:
                    css += 'label.%scolorIndex-%s {\n' % (fieldid, str(i))
                    css += '    color: %s;\n' % (str(color))
                    css += '}\n\n'

        return css
Esempio n. 11
0
def getCookieItems(request, field, charset):
    items = request.form.get(field)
    if items:
        return items
    items = request.cookies.get(field)
    if not items:
        return None
    if isinstance(items, (str, unicode)):
        items = items.find('+') == -1 and items or items.split('+')
    final = []
    if isinstance(items, (list, tuple)):
        for item in items:
            try:
                item = item.decode('latin1')
            except:
                pass
            final.append(safe_unicode(item).encode(charset))
    else:
        try:
            items = items.decode('latin1')
        except:
            pass
        final = [safe_unicode(items).encode(charset)]

    return final
Esempio n. 12
0
    def get_author(self, data):
        context = aq_inner(self.context)
        # some attributes are not always set
        author_name = u''

        # Make sure author_name/ author_email is properly encoded
        if 'author_name' in data:
            author_name = safe_unicode(data['author_name'])
        if 'author_email' in data:
            author_email = safe_unicode(data['author_email'])

        # Set comment author properties for anonymous users or members
        portal_membership = getToolByName(context, 'portal_membership')
        anon = portal_membership.isAnonymousUser()
        if not anon and getSecurityManager().checkPermission(
                'Reply to item', context):
            # Member
            member = portal_membership.getAuthenticatedMember()
            email = safe_unicode(member.getProperty('email'))
            fullname = member.getProperty('fullname')
            if not fullname or fullname == '':
                fullname = member.getUserName()
            fullname = safe_unicode(fullname)
            author_name = fullname
            email = safe_unicode(email)
            # XXX: according to IComment interface author_email must not be  # noqa T000
            # set for logged in users, cite:
            # 'for anonymous comments only, set to None for logged in comments'
            author_email = email
            # /XXX  # noqa T000

        return author_name, author_email
Esempio n. 13
0
    def execute(self):

        portal_url = getToolByName(aq_inner(self.context), "portal_url")
        portal = portal_url.getPortalObject()
        self.mailhost = getToolByName(aq_inner(self.context), "MailHost")
        if not self.mailhost:
            raise ComponentLookupError, 'You must have a Mailhost utility to execute this action'

        # first construct all replacement variables
        values = Values()
        
        # the object
        values.set('title', safe_unicode(self.object.Title()))
        values.set('url', self.object.absolute_url())
                
        # user 
        try:
            user = self.context.portal_membership.getAuthenticatedMember()
            values.set('loggeduserid', user.getId())
            values.set('loggeduserfullname', safe_unicode(user.getProperty('fullname')))
            values.set('loggeduseremail', user.getProperty('email'))
        except AttributeError, e:
            logger.error("class %s" % user.__class__)
            logger.error(" %s" % dir(user) )
            raise e
 def getMaintenanceTypes(self):
     """ Return the current list of maintenance types
     """
     types = [('Preventive',safe_unicode(_('Preventive')).encode('utf-8')),
              ('Repair', safe_unicode(_('Repair')).encode('utf-8')),
              ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8'))]
     return DisplayList(types)
Esempio n. 15
0
    def getNewReviewSections(self):
        retval = ''
        results = []
        for result in self.context.new_issues.queryCatalog():
            volume = result.getObject().getParentNode()
            publication = volume.getParentNode()
            results.append((safe_unicode(publication.Title()),
                safe_unicode(volume.Title()),
                safe_unicode(result.Title)))

        def sort_method(a, b):
            result = cmp(a[0], b[0])
            for i in (1, 2):
                if not result:
                    result = cmp(a[i], b[i])
                else:
                    return result
            return result
        results.sort(sort_method)

        for pub, vol, issue in results:
            retval += u'<h3>%s: %s, %s</h3>\n' \
                % (pub,
                   vol,
                   issue)

        return retval
Esempio n. 16
0
 def __call__(self):
     ar = self.context
     workflow = getToolByName(ar, 'portal_workflow')
     # If is a retracted AR, show the link to child AR and show a warn msg
     if workflow.getInfoFor(ar, 'review_state') == 'invalid':
         childar = hasattr(ar, 'getChildAnalysisRequest') \
                     and ar.getChildAnalysisRequest() or None
         childid = childar and childar.getRequestID() or None
         message = _('This Analysis Request has been withdrawn and is shown '
                       'for trace-ability purposes only. Retest: '
                       '${retest_child_id}.',
                       mapping={'retest_child_id': safe_unicode(childid) or ''})
         self.context.plone_utils.addPortalMessage(message, 'warning')
     # If is an AR automatically generated due to a Retraction, show it's
     # parent AR information
     if hasattr(ar, 'getParentAnalysisRequest') \
         and ar.getParentAnalysisRequest():
         par = ar.getParentAnalysisRequest()
         message = _('This Analysis Request has been '
                     'generated automatically due to '
                     'the retraction of the Analysis '
                     'Request ${retracted_request_id}.',
                     mapping={'retracted_request_id': safe_unicode(par.getRequestID())})
         self.context.plone_utils.addPortalMessage(
             t(message), 'info')
     template = LogView.__call__(self)
     return template
Esempio n. 17
0
        def getProperty(id, default):
            for sheet in sheets:
                if sheet.hasProperty(id):
                    # Return the first one that has the property.
                    return safe_unicode(sheet.getProperty(id))

            return safe_unicode(default)
Esempio n. 18
0
 def _update_stored_categories(self, data):
     context = aq_inner(self.context)
     start = time.time()
     idx = int(self.getFieldname())
     new_value = data['content-editable-form-body']
     stored = self.stored_data()
     records = stored['items']
     record = records[idx]
     record['description'] = safe_unicode(new_value)
     records[idx] = record
     stored['items'] = records
     # store in registry here
     end = time.time()
     stored.update(dict(
         _runtime=str(end-start),
         timestamp=str(int(time.time())),
         updated=str(datetime.datetime.now())
     ))
     api.portal.set_registry_record(
         'meetshaus.blog.interfaces.IBlogToolSettings.blog_categories',
         safe_unicode(json.dumps(stored)))
     next_url = '{0}/@@manage-blog-categories'.format(
         context.absolute_url())
     api.portal.show_message(_(u"The item has successfully been updated"),
                             self.request,
                             type='info')
     return self.request.response.redirect(next_url)
Esempio n. 19
0
 def __call__(self):
     context = aq_inner(self.context)
     info = {'body': self.template()}
     info['title'] = safe_unicode(context.Title())
     info['desc'] = safe_unicode(context.Description())
     info['url'] = context.absolute_url()
     return self._macro % info
Esempio n. 20
0
def dbconfig(event):
    if conf is None:
        log.error('No product config found! Configuration will not be set')
        return
    db = Zope2.DB
    connection = db.open()
    root_folder = connection.root().get(ZopePublication.root_name, None)
    for portal_id in conf.get('portals', '').split(','):
        portal = root_folder.get(portal_id)
        if not portal:
            log.error('No such portal: ' + portal_id)
            continue
        url = conf.get('.'.join((portal_id, 'external_url')))
        if not url:
            log.error('No external_url provided for ' + portal_id)
            continue
        setSite(portal)
        registry = getUtility(IRegistry)
        try:
            recensio_settings = registry.forInterface(IRecensioSettings)
        except Exception as e:
            log.exception(e)
            log.error('Could not get recensio settings for ' + portal_id)
            continue
        if recensio_settings.external_portal_url != safe_unicode(url):
            recensio_settings.external_portal_url = safe_unicode(url)

    transaction.commit()
Esempio n. 21
0
    def write_results(self, results):
        self.write('''<ul class="LSTable">''')
        for result in results[:self.limit]:
            icon = self.getIcon(result)
            itemUrl = result.getURL()
            if result.portal_type in self.useViewAction:
                itemUrl += '/view'
            itemUrl = itemUrl + self.searchterm_query

            self.write('''<li class="LSRow">''')
            self.write(icon.html_tag() or '')
            full_title = safe_unicode(self.pretty_title_or_id(result))
            if len(full_title) > self.settings.max_title:
                display_title = ''.join((full_title[:self.settings.max_title], '...'))
            else:
                display_title = full_title
            full_title = full_title.replace('"', '&quot;')
            klass = 'contenttype-%s' % self.normalizeString(result.portal_type)
            self.write('''<a href="%s" title="%s" class="%s">%s</a>''' % (itemUrl, full_title, klass, display_title))
            display_description = safe_unicode(result.Description)
            if len(display_description) > self.settings.max_description:
                display_description = ''.join((display_description[:self.settings.max_description], '...'))
            # need to quote it, to avoid injection of html containing javascript and other evil stuff
            display_description = html_quote(display_description)
            self.write('''<div class="LSDescr">%s</div>''' % (display_description))
            self.write('''</li>''')
            full_title, display_title, display_description = None, None, None

        if len(results) > self.limit:
            # add a more... row
            self.write('''<li class="LSRow">''')
            self.write(self.get_show_more_link())
            self.write('''</li>''')
        self.write('''</ul>''')
Esempio n. 22
0
    def unSubscribe(self, subscriber_id, REQUEST=None):
        """The subscriber clicked the Unsubscribe button
        """
        subscriber = self.getSubscriberById(subscriber_id)
        if subscriber is not None:
            charset = self.ploneCharset()
            subscriber_email = subscriber.email.strip()

            # Make and send the unsubscribe mail
            mailMsg=email.Message.Message()
            mailMsg["To"]=subscriber_email
            mailMsg["From"]=self.authorEmail
            mailMsg["Subject"]=str(Header(safe_unicode(self.unsubscribeMailSubject), 'utf8'))
            mailMsg["Date"]=email.Utils.formatdate(localtime=1)
            mailMsg["Message-ID"]=email.Utils.make_msgid()
            mailMsg["Mime-version"]="1.0"

            bodyText = self.unsubscribeMailTemplate % {'email': subscriber_email}
            mailMsg["Content-type"]="text/plain"
            mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
            mailMsg.epilogue="\n" # To ensure that message ends with newline

            self.sendmail(self.authorEmail, (subscriber_email,), mailMsg, subject = mailMsg['subject'])

            parent = subscriber.aq_parent
            newSecurityManager(REQUEST, SpecialUsers.system)
            parent.manage_delObjects([subscriber_id,])

        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(self.absolute_url() + '/NewsletterTheme_unsubscribed')
        return
Esempio n. 23
0
def SearchableText_pinnwandfolder(obj):

    return u" ".join((
        safe_unicode(obj.id),
        safe_unicode(obj.title) or u"",
        safe_unicode(obj.description) or u"",
    ))
Esempio n. 24
0
    def render(self):
        context = aq_inner(self.context)
        wtool = getToolByName(context, 'portal_workflow')
        from logging import getLogger
        log = getLogger('Import Stories')
        for item in eval(main()):
            id = context.invokeFactory(
                id=item['id'],
                type_name='News Item',
                title=item['title']

                )
            newsitem = context.get(id)
            text = u' '.join(
                (safe_unicode(item['description'], 'latin-1'),
                 safe_unicode(item['body'], 'latin-1'))
            )
            text = text.replace(u'\x96', u'').replace(u'\x92', u'')\
                .replace(u'\x93', u'').replace(u'\x94', u'')
            newsitem.text = RichTextValue(text, 'text/html', 'text/html')
            newsitem.setModificationDate(item['last_modification'])
            newsitem.setEffectiveDate(item['releasedate'])
            newsitem.resourceurl = item.get('resourceurl', '')
            newsitem.source = item.get('source', '')
            if item.get('frontpicture', None):
                data = item.get('frontpicture')
                log.info('Image for %s' % id)
                newsitem.image = NamedBlobImage(data=data)
            wtool.doActionFor(newsitem, action='publish')
            log.info('Added: %s' % id)
            try:
                newsitem.reindexObject()
            except Exception, e:
                log.exception(e)
Esempio n. 25
0
    def tags(self):
        """ Get available tags, both from Plone's keyword index
            and the microblog utility

        Applies very basic text searching
        """
        catalog = api.portal.get_tool('portal_catalog')
        tags = set(catalog.uniqueValuesFor('Subject'))

        # TODO: Check if the user is actually allowed to view these tags
        tool = piapi.microblog.get_microblog()
        if tool:
            tags.update(tool._tag_mapping.keys())

        search_string = self.request.form.get('tagsearch')
        self.selected_tags = [
            safe_unicode(tag) for tag in self.request.form.get('tags', [])]
        tags.update(self.selected_tags)
        # It is mandatory that all tags are actually unicode. It might happen
        # that `tags` contains strings with non-ascii characters encoded with a
        # different encoding than utf-8. In this case sorted() will bail.
        tags = set([safe_unicode(x) for x in tags if x])
        tags = sorted(tags)
        if search_string:
            search_string = safe_unicode(search_string)
            lower_search_string = search_string.lower()
            tags = filter(lambda x: lower_search_string in x.lower(),
                          tags)
            if search_string not in tags:
                # add searched string as first item in list
                # if it doesn't exist
                tags = [search_string] + tags

        return tags
Esempio n. 26
0
    def __call__(self, context, query=None):
        root = api.portal.get()
        if 'fr' in root.objectIds():
            fr = getattr(root, 'fr')
            root = api.portal.get_navigation_root(fr)

        rootPath = '/'.join(root.getPhysicalPath())
        query = {}
        query['path'] = {'query': rootPath, 'depth': 1}
        query['portal_type'] = ['Folder']
        query['sort_on'] = 'sortable_title'
        query['is_default_page'] = False
        portal_catalog = api.portal.get_tool('portal_catalog')
        results = portal_catalog.searchResults(query)
        items = []
        for result in results:
            if not result.exclude_from_nav:
                continue
            items.append(
                SimpleTerm(
                    safe_unicode(result.id),
                    safe_unicode(result.id),
                    safe_unicode(result.Title),
                )
            )
        return SimpleVocabulary(items)
Esempio n. 27
0
    def __call__(self, context, query=None):
        site = api.portal.get()
        self.catalog = getToolByName(site, 'portal_catalog', None)
        if self.catalog is None:
            return SimpleVocabulary([])
        if self.indexName not in self.catalog._catalog.indexes.keys():
            return SimpleVocabulary([])
        index = self.catalog._catalog.getIndex(self.indexName)

        def safe_encode(term):
            if isinstance(term, unicode):
                # no need to use portal encoding for transitional encoding from
                # unicode to ascii. utf-8 should be fine.
                term = term.encode('utf-8')
            return term

        # Vocabulary term tokens *must* be 7 bit values, titles *must* be
        # unicode
        items = [
            SimpleTerm(safe_unicode(i), b2a_qp(
                safe_encode(i)), safe_unicode(i))
            for i in index._index
            if query is None or safe_encode(query) in safe_encode(i)
        ]
        return SimpleVocabulary(items)
Esempio n. 28
0
def SearchableText_pinnwandentry(obj):
    return u" ".join((
        safe_unicode(obj.id),
        safe_unicode(obj.title) or u"",
        safe_unicode(obj.description) or u"",
        safe_unicode(obj.text.output) or u"",
    ))
Esempio n. 29
0
def migrate_blobimagefield(src_obj, dst_obj, src_fieldname, dst_fieldname):
    """
    migrate an image field.
    Actually this field needs only to copy the existing NamedBlobImage instance
    to the new dst_obj, but we do some more in detail and create new fields.
    """
    old_image = getattr(src_obj, src_fieldname)
    if old_image == '':
        return
    filename = safe_unicode(old_image.filename)
    old_image_data = old_image.data
    if safe_hasattr(old_image_data, 'data'):
        old_image_data = old_image_data.data
    namedblobimage = NamedBlobImage(data=old_image_data,
                                    filename=filename)

    # set new field on destination object
    setattr(dst_obj, dst_fieldname, namedblobimage)

    # handle a possible image caption field
    field = '{0}_caption'.format(src_fieldname)
    old_image_caption = getattr(src_obj, field, None)
    if old_image_caption:
        setattr(dst_obj,
                ('{0}_caption'.format(dst_fieldname)),
                safe_unicode(old_image_caption))

    logger.info('Migrating image {0}'.format(filename))
Esempio n. 30
0
    def removeSubscriber(self, subscriber):
        charset = self.ploneCharset()
        subscriber_email = subscriber.email.strip()

        url_service = self.absolute_url()
        url_register = "%s/NewsletterTheme_subscribeForm" % url_service

        # Make and send the unsubscribe mail
        mailMsg=email.Message.Message()
        mailMsg["To"]=subscriber_email
        mailMsg["From"]=self.authorEmail
        mailMsg["Subject"]=str(Header(safe_unicode(self.removeNoticeMailSubject), 'utf8'))
        mailMsg["Date"]=email.Utils.formatdate(localtime=1)
        mailMsg["Message-ID"]=email.Utils.make_msgid()
        mailMsg["Mime-version"]="1.0"

        bodyText = self.removeNoticeTemplate % {'url_service': url_service,
                                                'url_register':url_register}
        mailMsg["Content-type"]="text/plain"
        mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
        mailMsg.epilogue="\n" # To ensure that message ends with newline

        try:
            self.sendmail(self.authorEmail, subscriber_email,
                                mailMsg, subject = mailMsg['subject'])
        except:
            log("Could not send a PloneGazzette unsubscribe message to %s, removing subscriber anyway." % subscriber_email)

        parent = aq_parent(subscriber)
        parent.manage_delObjects([subscriber.id])
Esempio n. 31
0
 def recurrence(self):
     return safe_unicode(self.context.getRecurrence())
Esempio n. 32
0
 def contact_email(self):
     return safe_unicode(self.context.contact_email())
Esempio n. 33
0
 def contact_name(self, value):
     self.context.setContactName(safe_unicode(value))
Esempio n. 34
0
 def contact_name(self):
     return safe_unicode(self.context.contact_name())
Esempio n. 35
0
 def location(self, value):
     self.context.setLocation(safe_unicode(value))
Esempio n. 36
0
 def location(self):
     return safe_unicode(self.context.getLocation())
Esempio n. 37
0
 def recurrence(self, value):
     self.context.setRecurrence(safe_unicode(value))
Esempio n. 38
0
 def timezone(self):
     return safe_unicode(self.context.getTimezone())
Esempio n. 39
0
 def description(self):
     return safe_unicode(self.context.Description())
Esempio n. 40
0
 def timezone(self, value):
     self.context.setTimezone(safe_unicode(value))
Esempio n. 41
0
 def title(self):
     return safe_unicode(getattr(self.context, 'title', None))
Esempio n. 42
0
 def description(self, value):
     self.context.setDescription(safe_unicode(value))
Esempio n. 43
0
 def Title(self):
     title = self.getName() and self.getName() or _("Laboratory")
     return safe_unicode(title).encode('utf-8')
Esempio n. 44
0
 def title(self, value):
     setattr(self.context, 'title', safe_unicode(value))
Esempio n. 45
0
 def Title(self):
     """ Return the Organisation's Name as its title """
     return safe_unicode(self.getField('Name').get(self)).encode('utf-8')
Esempio n. 46
0
 def url(self):
     return safe_unicode(self.context.absolute_url())
Esempio n. 47
0
 def Title(self):
     """ Return the Organisation's Name as its title """
     field = self.getField('Name')
     field = field and field.get(self) or ''
     return safe_unicode(field).encode('utf-8')
Esempio n. 48
0
    def reply(self):
        # Traverse to historical version
        if self.version:
            serializer = queryMultiAdapter(
                (self.context, self.request), ISerializeToJson
            )
            data = serializer(version=self.version)
            return data

        # Listing historical data
        content_history_viewlet = ContentHistoryViewlet(
            self.context, self.request, None, None
        )
        site_url = getSite().absolute_url()
        content_history_viewlet.navigation_root_url = site_url
        content_history_viewlet.site_url = site_url
        history = content_history_viewlet.fullHistory()
        if history is None:
            history = []

        unwanted_keys = [
            "diff_current_url",
            "diff_previous_url",
            "preview_url",
            "actor_home",
            "actorid",
            "revert_url",
            "version_id",
        ]

        for item in history:
            item["actor"] = {
                "@id": "{}/@users/{}".format(site_url, item["actorid"]),
                "id": item["actorid"],
                "fullname": item["actor"].get("fullname"),
                "username": item["actor"].get("username"),
            }

            if item["type"] == "versioning":
                item["version"] = item["version_id"]
                item["@id"] = "{}/@history/{}".format(
                    self.context.absolute_url(), item["version"]
                )

                # If a revert_url is present, then CMFEditions has checked our
                # permissions.
                item["may_revert"] = bool(item.get("revert_url"))

            # Versioning entries use a timestamp,
            # workflow ISO formatted string
            if not isinstance(item["time"], str):
                item["time"] = dt.fromtimestamp(item["time"]).isoformat()

            # The create event has an empty 'action', but we like it to say
            # 'Create', alike the transition_title
            if item["action"] is None:
                item["action"] = "Create"

            # We want action, state and transition names translated
            if "state_title" in item:
                item["state_title"] = self.context.translate(
                    safe_unicode(item["state_title"]), context=self.request
                )

            if "transition_title" in item:
                item["transition_title"] = self.context.translate(
                    safe_unicode(item["transition_title"]), context=self.request
                )

            if "action" in item:
                item["action"] = self.context.translate(
                    safe_unicode(item["action"]), context=self.request
                )

            # clean up
            for key in unwanted_keys:
                if key in item:
                    del item[key]

        return json_compatible(history)
Esempio n. 49
0
def to_unicode(text):
    if text is None:
        text = ''
    return safe_unicode(text)
Esempio n. 50
0
 def _get_title(self, doc_name, gen_context):
     splitted_name = doc_name.split('.')
     title = self.pod_template.title
     extension = splitted_name[-1]
     return safe_unicode(title), extension
Esempio n. 51
0
def write(s):
    output.append(safe_unicode(s))
Esempio n. 52
0
 if not request:
     return "!! request param cannot be empty"
 import re
 from Products.CMFPlone.utils import safe_unicode
 try:
     p_o = re.compile(toreplace)
 except Exception, msg:
     return "!! Cannot compile replace expression '%s': '%s'" % (toreplace,
                                                                 msg)
 try:
     dic = eval(request)
 except Exception, msg:
     return "!! Cannot eval request '%s': '%s'" % (request, msg)
 out = ['request= %s' % dic]
 for brain in self.portal_catalog(**dic):
     m_o = p_o.search(safe_unicode(brain.internal_reference_number))
     if not m_o:
         continue
     res = p_o.sub(safe_unicode(by),
                   safe_unicode(brain.internal_reference_number))
     out.append("'%s': '%s' => '%s'" %
                (brain.getPath(),
                 safe_unicode(brain.internal_reference_number), res))
     if change == '1':
         obj = brain.getObject()
         obj.internal_reference_no = res
         obj.reindexObject(idxs=[
             'internal_reference_number', 'sortable_title',
             'SearchableText', 'Title'
         ])
 return '\n'.join(out)
Esempio n. 53
0
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(self.request.form)
        plone.protect.PostOnly(self.request.form)
        uc = getToolByName(self.context, 'uid_catalog')
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        portal_catalog = getToolByName(self.context, 'portal_catalog')

        # Load the form data from request.state.  If anything goes wrong here,
        # put a bullet through the whole process.
        try:
            states = json.loads(form['state'])
        except Exception as e:
            message = t(_('Badly formed state: ${errmsg}',
                          mapping={'errmsg': e.message}))
            ajax_form_error(self.errors, message=message)
            return json.dumps({'errors': self.errors})

        # Validate incoming form data
        required = [field.getName() for field
                    in AnalysisRequestSchema.fields()
                    if field.required] + ["Analyses"]

        # First remove all states which are completely empty; if all
        # required fields are not present, we assume that the current
        # AR had no data entered, and can be ignored
        nonblank_states = {}
        for arnum, state in states.items():
            for key, val in state.items():
                if val \
                        and "%s_hidden" % key not in state \
                        and not key.endswith('hidden'):
                    nonblank_states[arnum] = state
                    break

        # in valid_states, all ars that pass validation will be stored
        valid_states = {}
        for arnum, state in nonblank_states.items():
            # Secondary ARs are a special case, these fields are not required
            if state.get('Sample', ''):
                if 'SamplingDate' in required:
                    required.remove('SamplingDate')
                if 'SampleType' in required:
                    required.remove('SampleType')
            # fields flagged as 'hidden' are not considered required because
            # they will already have default values inserted in them
            for fieldname in required:
                if fieldname + '_hidden' in state:
                    required.remove(fieldname)
            missing = [f for f in required if not state.get(f, '')]
            # If there are required fields missing, flag an error
            if missing:
                msg = t(_('Required fields have no values: '
                          '${field_names}',
                          mapping={'field_names': ', '.join(missing)}))
                ajax_form_error(self.errors, arnum=arnum, message=msg)
                continue
            # This ar is valid!
            valid_states[arnum] = state

        # - Expand lists of UIDs returned by multiValued reference widgets
        # - Transfer _uid values into their respective fields
        for arnum in valid_states.keys():
            for field, value in valid_states[arnum].items():
                if field.endswith('_uid') and ',' in value:
                    valid_states[arnum][field] = value.split(',')
                elif field.endswith('_uid'):
                    valid_states[arnum][field] = value

        if self.errors:
            return json.dumps({'errors': self.errors})

        # Now, we will create the specified ARs.
        ARs = []
        for arnum, state in valid_states.items():
            # Create the Analysis Request
            ar = create_analysisrequest(
                portal_catalog(UID=state['Client'])[0].getObject(),
                self.request,
                state
            )
            ARs.append(ar.Title())

        # Display the appropriate message after creation
        if len(ARs) > 1:
            message = _('Analysis requests ${ARs} were successfully created.',
                        mapping={'ARs': safe_unicode(', '.join(ARs))})
        else:
            message = _('Analysis request ${AR} was successfully created.',
                        mapping={'AR': safe_unicode(ARs[0])})
        self.context.plone_utils.addPortalMessage(message, 'info')
        # Automatic label printing won't print "register" labels for Secondary. ARs
        new_ars = [ar for ar in ARs if ar[-2:] == '01']
        if 'register' in self.context.bika_setup.getAutoPrintStickers() \
                and new_ars:
            return json.dumps({
                'success': message,
                'stickers': new_ars,
                'stickertemplate': self.context.bika_setup.getAutoStickerTemplate()
            })
        else:
            return json.dumps({'success': message})
Esempio n. 54
0
 def Title(self):
     """ Return the contact's Fullname as title """
     return safe_unicode(self.getFullname()).encode('utf-8')
Esempio n. 55
0
def string_converter(value):
    return safe_unicode(value, )
Esempio n. 56
0
        write(
            '<span style="color:red; font-weight:normal;">Alguns resultados não foram exibidos, refina melhor a sua busca.</span>'
        )
        write('''</li>''')

    for patient in pbrains[:limit]:

        #get patient
        icon = plone_view.getIcon(patient)
        itemUrl = patient.getURL()
        if patient.portal_type in useViewAction:
            itemUrl += '/view'

        write('''<li class="LSRow" style="width:425px;">''')
        write(icon.html_tag() or '')
        full_title = safe_unicode(pretty_title_or_id(patient))
        if len(full_title) > MAX_TITLE:
            display_title = ''.join((full_title[:MAX_TITLE], '...'))
        else:
            display_title = full_title
        full_title = full_title.replace('"', '&quot;')
        klass = 'contenttype-%s' % ploneUtils.normalizeString(
            patient.portal_type)

        # tratamento especial para o tipo patient
        # o primeiro if se refere ao Procurar do adicionar consulta1
        # o elif se refere a pesquisa da pasta Patients
        dt = patient.genericColumn1
        cf = patient.genericColumn2
        formatted_phone = "%s %s-%s" % (cf[:2], cf[2:6], cf[6:10])
        if selecting_patient_for_visit:
Esempio n. 57
0
def productId_indexer(obj):
    # index 傳進 unicode 會有 error,改傳 utf-8 正確,此法暫解
    string = safe_unicode(obj.productId).encode('utf-8')
    return string
Esempio n. 58
0
def _indent(text, ind=5, width=80):
    """helper indents text"""
    wrapped = textwrap.fill(safe_unicode(text),
                            width,
                            initial_indent=ind * u' ')
    return wrapped
Esempio n. 59
0
class ReCaptcha(object):
    captcha = safe_unicode('')

    def __init__(self, context):
        self.context = context
Esempio n. 60
0
def brand_indexer(obj):
    # index 傳進 unicode 會有 error,改傳 utf-8 正確,此法暫解
    string = safe_unicode(obj.brand).encode('utf-8')
    return string