def highlight_signature(text, attribute='style="color:#ccc"', tag="span", use_newline_to_br=False): text = text.replace('<p>--\n','<p>\n--\n') signature_regex = re.compile('(^--\s*(\n|<br\s*/>|<br>))', re.MULTILINE|re.I) found_signatures = signature_regex.findall(text) if found_signatures: whole, linebreak = found_signatures[-1] parts = text.split(whole) signature = parts[-1] if use_newline_to_br: whole = newline_to_br(whole) signature = newline_to_br(signature) double_endbreaks = re.compile(r'<br\s*/><br\s*/>$', re.M) whole = double_endbreaks.sub('<br />', whole) signature = double_endbreaks.sub('<br />', signature) whitespace = signature.replace(signature.strip(), '') signature = '%s<%s %s>%s%s</%s>'%(whitespace, tag, attribute, whole, signature.strip(), tag) return whole.join(parts[:-1])+signature else: signature_regex = re.compile('(^|<p>)(--\s*)', re.MULTILINE|re.I) splitted = signature_regex.split(text) if len(splitted)==4: part1, start, dashes, part2 = splitted part1 += start if start =='<p>': _p_splitted = part2.split('</p>') joined = '%s<%s %s>'%(part1, tag, attribute) joined += '%s%s</%s>%s</p>'%(dashes, _p_splitted[0], tag, _p_splitted[1]) else: joined = '%s<%s %s>%s%s</%s>'%(part1, tag, attribute, dashes, part2, tag) return joined return text
def _mergeBirthdaysIntoMessage(self, birthdays, uid): """ put all birthday messages into one """ all_lines = [] all_html_lines = [] all_best_names = [] for birthday in birthdays: lines = [_("Don't forget, it's")] html_lines = lines[:] if birthday.name and birthday.email: best_name = birthday.name name = u"%s's" % birthday.name _html = u'<a href="mailto:%s"><strong>%s\'s</strong></a>' html_name = _html % (birthday.email, birthday.name) elif birthday.email: best_name = name = birthday.email _html = '<a href="mailto:%s"><strong>%s\'s</strong></a>' html_name = _html % (birthday.email, birthday.email) else: name = best_name = "%s's" % birthday.name best_name = birthday.name html_name = '<strong>%s\'s</strong>' % birthday.name if birthday.birthday_today: lines.append('\t%s birthday today!' % name) html_lines.append(' '*4 + '%s birthday today!' % html_name) elif birthday.days_till == 1: lines.append('\t%s birthday in one day!' % name) html_lines.append(' '*4 + '%s birthday in one day!' % html_name) else: lines.append('\t%s birthday in %s days!' % (name, birthday.days_till)) html_lines.append(' '*4 + '%s birthday in %s days!' % \ (html_name, birthday.days_till)) all_best_names.append(best_name) all_lines.append('\n'.join(lines)) all_html_lines.append('\n'.join(html_lines)+'\n\n') rooturl = self.getRootURL() user = self._getUser(uid) plain_footer, html_footer = self._getSigntureWithOptout(rooturl, user.passkey) all_lines.append(plain_footer) all_html_lines.append(html_footer) msg = '\n\n'.join(all_lines) html_msg = '\n'.join(all_html_lines) html_msg = newline_to_br(html_msg) if len(all_best_names) == 1: subject = _("RememberYourFriends.com birthday reminder for") + \ ' %s' % all_best_names[0] else: subject = _("RememberYourFriends.com birthday reminder ") + \ DateTime().strftime('%d %B') return subject, msg, html_msg
def ShowText(text, display_format='', emaillinkfunction=None, urllinkfunction=None, allowhtml=False, # only applies to plaintext and structured_text paragraphtag=True, # only applies with plaintext ): """ Display text, using harmless HTML """ if not text: # blank or None return "" if display_format == 'structuredtext': #st=_replace_special_chars(text) st=text if not allowhtml: for k,v in {'<':'<', '>':'>'}.items(): st = st.replace(k, v) st = st.replace('[','|[|') st = html_entity_fixer(st, skipchars=('"',)) st = structured_text(st) if allowhtml: for k,v in {'<':'<', '>':'>'}.items(): st = st.replace(v, k) for k,v in {'&lt;':'<', '&gt;':'>', '|[|':'['}.items(): st = st.replace(k,v) st = addhrefs(st, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) st = st.rstrip() return st elif display_format == 'html': return text else: if paragraphtag: t = '<p>%s</p>'%safe_html_quote(text) else: t = safe_html_quote(text) t = t.replace('&lt;','<').replace('&gt;','>') t = addhrefs(t) t = newline_to_br(t) return t
def highlight_signature(text, attribute='style="color:#ccc"', tag="span", use_newline_to_br=False): text = text.replace('<p>--\n', '<p>\n--\n') signature_regex = re.compile('(^--\s*(\n|<br\s*/>|<br>))', re.MULTILINE | re.I) found_signatures = signature_regex.findall(text) if found_signatures: whole, linebreak = found_signatures[-1] parts = text.split(whole) signature = parts[-1] if use_newline_to_br: whole = newline_to_br(whole) signature = newline_to_br(signature) double_endbreaks = re.compile(r'<br\s*/><br\s*/>$', re.M) whole = double_endbreaks.sub('<br />', whole) signature = double_endbreaks.sub('<br />', signature) whitespace = signature.replace(signature.strip(), '') signature = '%s<%s %s>%s%s</%s>' % (whitespace, tag, attribute, whole, signature.strip(), tag) return whole.join(parts[:-1]) + signature else: signature_regex = re.compile('(^|<p>)(--\s*)', re.MULTILINE | re.I) splitted = signature_regex.split(text) if len(splitted) == 4: part1, start, dashes, part2 = splitted part1 += start if start == '<p>': _p_splitted = part2.split('</p>') joined = '%s<%s %s>' % (part1, tag, attribute) joined += '%s%s</%s>%s</p>' % (dashes, _p_splitted[0], tag, _p_splitted[1]) else: joined = '%s<%s %s>%s%s</%s>' % (part1, tag, attribute, dashes, part2, tag) return joined return text
def _sendnaggings(self, verbose=False): """ send out a reminder to those people who have signed up but haven't added any reminders. The 'max_send' parameter is ignored. """ sent_to = [] rooturl = self.getRootURL() reminderless_users = self._getReminderlessUsers() subject = _("Getting started with RememberYourFriends.com") for user in reminderless_users: html = bool(user.html_emails) lines = [] html_lines = [] add_date = user.add_date_formatted para1 = _("You signed up to RememberYourFriends.com on the")+\ " " + add_date + " " +\ _("but haven't set up any reminders yet.") lines.append(para1) html_lines.append(para1) add_reminders_url = '%s/_%s/add' % \ (rooturl, user.passkey) html_lines.append(_('To add some, <a href="%s">go to the <b>Add a new reminder</b> page</a>') %\ add_reminders_url) lines.append(_('To add some, go to the Add a new reminder page:')+\ '\n'+ add_reminders_url) lines.append('\n') html_lines.append('\n') plain, html_ = self._getSigntureWithOptout(rooturl, user.passkey) html_lines.append(html_) lines.append(plain) msg = '\n\n'.join(lines) html_msg = '\n'.join(html_lines) html_msg = newline_to_br(html_msg) if html: self._sendEmailWrapped(user.email, self.getWebmasterFromfield(), subject, msg, html_msg) else: self._sendEmailWrapped(user.email, self.getWebmasterFromfield(), subject, msg) sent_to.append(user.email) if sent_to: return "Sent to %s" % ', '.join(sent_to) else: return "Didn't send to anyone"
def _niceSourceFormat(self, code): if SC_XML is not None: generator = SC_XML.XMLHTMLGenerator() file = StringIO.StringIO() generator.generate_html(file, code) code = file.getvalue() file.close() del generator css = '<style type="text/css">%s</style>\n\n'%SC_stylesheet code = '<div class="code_default">%s</div>'%code return css + code else: code = html_quote(code) code = newline_to_br(code) code = code.replace('\t',' '*4) return "<code>%s</code>"%code
def ShowDescription(text, display_format=''): """ Display text, using harmless HTML """ if display_format == 'structuredtext': #st=_replace_special_chars(text) st=text for k,v in {'<':'<', '>':'>', '[':'|[|'}.items(): st = st.replace(k,v) st = html_entity_fixer(st, skipchars=('"',)) st = structured_text(st) for k,v in {'&lt;':'<', '&gt;':'>', '|[|':'['}.items(): st = st.replace(k,v) # BUG in structured_text in Zope 2.4.0 # it appends these annoying tags. #for tag in ['<html>','<body>','</body>','</html>']: # st = st.replace(tag, '') st = addhrefs(st) return st elif display_format == 'html': return text else: t = '<p>%s</p>'%html_quote(text) t = t.replace('&lt;','<').replace('&gt;','>') t = addhrefs(t) t = newline_to_br(t) return t
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
def Error(fmt, *args): msg = fmt % args script = TEMPLATE % ('cancelUpload', msg.replace("'", "\\'"), newline_to_br(html_quote(printed))) return script
# Get an unused filename without path 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) notifyobjectinitialization(obj) obj.reindexObject() if linkbyuid and hasattr(obj, 'UID'): url = base+'/resolveuid/%s' % obj.UID() 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)))
) document.share() report_item_list.append( (attachment.get('title', document.getStandardFilename(format=format)), document.getRelativeUrl())) # pre-convert document before sending notification if format: document.activate(tag=pre_convert_tag).convert(format=format) url_base = portal.ERP5Site_getAbsoluteUrl() attachment_link_list = [ { 'download_link': '%s/%s?format=%s' % (url_base , report_url, format), 'name': report_name } for (report_name, report_url) in report_item_list ] message_html = newline_to_br(html_quote(message)) message_text_format = "text/html" attachment_list = [] notification_message_reference = prefs.getPreferredDeferredReportNotificationMessageReference() if notification_message_reference: notification_message = portal.portal_notifications.getDocumentValue(reference=notification_message_reference) if notification_message is None: raise ValueError('Notification message not found by %r' % prefs.getPreferredDeferredReportNotificationMessageReference()) notification_mapping_dict = { 'report_link_list': portal.ERP5Site_viewReportCompleteNotificationMessage( attachment_link_list=attachment_link_list ), 'message': message_html } message = notification_message.asEntireHTML(
def Error(fmt, *args): msg = fmt % args script = TEMPLATE % ('cancelUpload', msg.replace( "'", "\\'"), newline_to_br(html_quote(printed))) return script
def ShowDescription(text, display_format='', emaillinkfunction=None, urllinkfunction=None): """ Display text, using harmless HTML """ if not text: # blank or None return "" if urllinkfunction is None: # add one that is able to truncate really long URLs def urllinkfunction(url, maxlength=70): if len(url) > maxlength: title = url[:42] + '...' + url[-25:] tooltip = 'Right click to copy the whole URL' return '<a href="%s" title="%s">%s</a>' % \ (improveURL(url), tooltip, title) else: return '<a href="%s">%s</a>' % (improveURL(url), url) if display_format == 'structuredtext': #st=_replace_special_chars(text) st=text # if the text is just a number (and a full stop), then # structured_text is going to make this the first of a numbered # HTML list. Prevent that with this "hack". found_only_number = re.compile('\d[\d \.]+').findall(st) if found_only_number: if found_only_number[0] == st: return st for k,v in {'<':'<', '>':'>', '[':'|[|'}.items(): st = st.replace(k,v) if isinstance(st, str): try: st = html_entity_fixer(st, skipchars=('"',)) except UnicodeDecodeError: # badly stored string. Legacy problem. pass st = structured_text(st) for k,v in {'&lt;':'<', '&gt;':'>', '|[|':'['}.items(): st = st.replace(k,v) st = addhrefs(st, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) return st elif display_format == 'markdown': if not markdown_converter: import warnings warnings.warn("Markdown is not installed") return text text = markdown_converter.convert(text) text = addhrefs(text, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) return text elif display_format == 'html': return text else: t = '<p>%s</p>'%safe_html_quote(text) t = t.replace('&lt;','<').replace('&gt;','>') t = addhrefs(t, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) t = newline_to_br(t) return t
def info(self, brain, allowLink=True): '''Get information from a brain''' __traceback_info__ = (brain, allowLink) id = brain.getId url = brain.getURL() portal_type = brain.portal_type collection = portal_type in self.coll_types tool = self.tool preview = tool.getPreviewUrl(portal_type, url) # Path for the uid catalog doesn't have the leading '/' path = brain.getPath() UID = None if path and self.uid_catalog: try: metadata = self.uid_catalog.getMetadataForUID( path[self.prefix_length:]) except KeyError: metadata = None if metadata: UID = metadata.get('UID', None) if UID: id = UID if collection and self.resource_type.allow_browse: src = brain.getURL() 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(brain, 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(brain) title = filterControlChars(brain.Title or brain.getId) description = newline_to_br(html_quote(brain.Description)) linkable = None if allowLink: linkable = True collection = False anchor = portal_type in self.anchor_types review_state, className = self.getState(brain.review_state) 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, }
def ar_results_pdf(self, info): settings = self.aq_parent.bika_setup max_batch = settings.getBatchEmail() laboratory = info['laboratory'] lab_address = laboratory.getPostalAddress() if not lab_address: lab_address = laboratory.getBillingAddress() if not lab_address: lab_address = laboratory.getPhysicalAddress() contact = info['contact'] client = contact.aq_parent contact_address = contact.getPostalAddress() if not contact_address: contact_address = client.getPostalAddress() if not contact_address: contact_address = client.getBillingAddress() if not contact_address: contact_address = contact.getPhysicalAddress() if not contact_address: contact_address = client.getPhysicalAddress() lab_accredited = laboratory.getLaboratoryAccredited() batch = info['analysis_requests'] invoice_exclude = False out_of_range = [] contact_stuff = contact.getFullname() + '\n' + client.Title() address = newline_to_br(contact_address.get('address', '')) contact_stuff = contact_stuff + '\n' + address location = contact_address.get('city', '') location = location + ', ' + contact_address.get('state', '') location = location + ', ' + contact_address.get('zip', '') location = location + ' ' + contact_address.get('country', '') contact_stuff = contact_stuff + '\n' + location lab_stuff = laboratory.Title() lab_title = laboratory.Title() address = newline_to_br(lab_address.get('address', '')) lab_stuff = lab_stuff + '\n' + address location = lab_address.get('city', '') location = location + ', ' + lab_address.get('state', '') location = location + ', ' + lab_address.get('zip', '') location = location + ' ' + lab_address.get('country', '') lab_stuff = lab_stuff + '\n' + location headings = [] headings.append((contact_stuff, lab_stuff)) all_first_heads = [] all_other_heads = [] all_results = [] all_cats = [] all_oor = [] all_attachments = [] all_remarks = [] all_disclaimers = [] all_ars = [] all_dries = [] ars = [] managers = {} batch_cnt = 0 for ar in info['analysis_requests']: responsible = ar.getManagers() for manager in responsible: if not managers.has_key(manager.getId()): managers[manager.getId()] = manager if batch_cnt == max_batch: (first_heads, other_heads, results, cats, out_of_range, dries, attachments, remarks, disclaimers) = self.process_batch(ars, lab_accredited, lab_title) all_first_heads.append(first_heads) all_other_heads.append(other_heads) all_results.append(results) all_cats.append(cats) all_oor.append(out_of_range) all_ars.append(batch_cnt) all_dries.append(dries) all_attachments.append(attachments) all_remarks.append(remarks) all_disclaimers.append(disclaimers) ars = [] batch_cnt = 0 ars.append(ar) batch_cnt += 1 if batch_cnt > 0: (first_heads, other_heads, results, cats, out_of_range, dries, attachments, remarks, disclaimers) = self.process_batch(ars, lab_accredited, lab_title) all_first_heads.append(first_heads) all_other_heads.append(other_heads) all_results.append(results) all_cats.append(cats) all_oor.append(out_of_range) all_attachments.append(attachments) all_remarks.append(remarks) all_disclaimers.append(disclaimers) all_ars.append(batch_cnt) all_dries.append(dries) all_managers = [] m_keys = managers.keys() for m_key in m_keys: all_managers.append(managers[m_key]) filename = "results.pdf" # tell the browser we send some PDF document # with the requested filename # get the document's content itself as a string of text file = self.MyPDFDoc(self, filename, headings, all_first_heads, all_other_heads, all_ars, all_results, all_cats, all_oor, all_dries, all_attachments, all_remarks, all_managers, all_disclaimers, lab_title) filecontent = file.report.getvalue() self.REQUEST.RESPONSE.setHeader('Content-Type', 'application/pdf') self.REQUEST.RESPONSE.setHeader('Content-Disposition', 'inline; filename=%s' % filename) file_data = {} file_data['file'] = filecontent file_data['file_name'] = filename return file_data
def ShowDescription(text, display_format='', emaillinkfunction=None, urllinkfunction=None): """ Display text, using harmless HTML """ if not text: # blank or None return "" if urllinkfunction is None: # add one that is able to truncate really long URLs def urllinkfunction(url, maxlength=70): if len(url) > maxlength: title = url[:42] + '...' + url[-25:] tooltip = 'Right click to copy the whole URL' return '<a href="%s" title="%s">%s</a>' % \ (improveURL(url), tooltip, title) else: return '<a href="%s">%s</a>' % (improveURL(url), url) if display_format == 'structuredtext': #st=_replace_special_chars(text) st = text # if the text is just a number (and a full stop), then # structured_text is going to make this the first of a numbered # HTML list. Prevent that with this "hack". found_only_number = re.compile('\d[\d \.]+').findall(st) if found_only_number: if found_only_number[0] == st: return st for k, v in {'<': '<', '>': '>', '[': '|[|'}.items(): st = st.replace(k, v) if isinstance(st, str): try: st = html_entity_fixer(st, skipchars=('"', )) except UnicodeDecodeError: # badly stored string. Legacy problem. pass st = structured_text(st) for k, v in { '&lt;': '<', '&gt;': '>', '|[|': '[' }.items(): st = st.replace(k, v) st = addhrefs(st, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) return st elif display_format == 'markdown': if not markdown_converter: import warnings warnings.warn("Markdown is not installed") return text text = markdown_converter.convert(text) text = addhrefs(text, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) return text elif display_format == 'html': return text else: t = '<p>%s</p>' % safe_html_quote(text) t = t.replace('&lt;', '<').replace('&gt;', '>') t = addhrefs(t, emaillinkfunction=emaillinkfunction, urllinkfunction=urllinkfunction) t = newline_to_br(t) return t
from Products.PythonScripts.standard import newline_to_br from Products.ERP5Type.Log import log log("Event_getTextContentCorrespondToFormat is deprecated, use Event_getEditorFieldTextContent instead", level=100) # WARNING content_type = context.getContentType() if content_type == 'text/html' and context.hasFile(): return context.asStrippedHTML() else: value = context.getTextContent() if editable: return value else: return newline_to_br(value or "")
def ShowDescription(text, display_format='', nofollow_rel=False): """ Display text, using harmless HTML """ text = SplitRegEx.sub('<!--split-->', text) codesyntax = '' if same_type(display_format, ()) or same_type(display_format, []): display_format, codesyntax = display_format if display_format == 'structuredtext': #st=_replace_special_chars(text) st=text for k,v in {#'<':'<', '>':'>', '[':'|[|'}.items(): st = st.replace(k,v) try: # my structured text st = nice_structured_text(st) except: st = structured_text(st) for k,v in {'&lt;':'<', '&gt;':'>', '|[|':'['}.items(): st = st.replace(k,v) # BUG in structured_text in Zope 2.4.0 # it appends these annoying tags. for tag in ['<html>','<body>','</body>','</html>']: st = st.replace(tag, '') pre_whole_tags = re.compile(r'<pre>.*?</pre>', re.I|re.DOTALL) pre_tags = pre_whole_tags.findall(st) mem = {} for pre_tag in pre_tags: randstr = '__%s__'%getRandomString() mem[randstr] = pre_tag st = st.replace(pre_tag, randstr) ### NEEDS TO BE FIXED! #st = addhrefs(st, urllinkfunction=mylinker) for key, tag in mem.items(): st = st.replace(key, tag) # preserve look of '<!--split-->' st = st.replace('<p><!--split--></p>','<!--split-->') # syntax highlighting of code if str(codesyntax).lower() in ['c++','cpp']: st = SyntaxHighlight(st, CPP_SYNTAX) elif str(codesyntax).lower() in ['py','python']: st = SyntaxHighlight(st, PYTHON_SYNTAX) elif str(codesyntax).lower() in ['sql']: st = SyntaxHighlight(st, SQL_SYNTAX) elif str(codesyntax).lower() in ['xml/html','xml','html']: st = SyntaxHighlight(st, XML_SYNTAX) elif str(codesyntax).lower() in ['css','stylesheet']: st = SyntaxHighlight(st, CSS_SYNTAX) st = sole_ampersand_regex.sub('&', st) return st elif display_format == 'html': return text elif display_format == 'texmix': texes = getTexes(text, 1) count = 1 for tagused, texstring in texes: imageid = 'texjpeg-%s.jpg'%count imagepath = 'texcache/%s'%imageid imagetag = '<img src="%s" alt="%s" '%(imagepath, "*generated jpeg*") if tagused.lower().find('inline') > -1: imagetag += 'class="texmix-inline"' else: imagetag += 'class="texmix"' imagetag += ' />' text = text.replace(texstring, imagetag) count += 1 text = text.replace('<texmix>','<span class="texmix">') text = text.replace('<texmix inline="1">','<span class="texmix-inline">') text = text.replace('</texmix>','</span>') format = 'structuredtext' if codesyntax: format = [format, codesyntax] return ShowDescription(text, format) else: t = html_quote(text) t = t.replace('&lt;','<').replace('&gt;','>') t = t.replace('<!--split-->', '<!--split-->') if nofollow_rel: def nofollower(url): template = '<a href="%s" rel="nofollow">%s</a>' return template % (url, url) t = addhrefs(t, urllinkfunction=nofollower) else: t = addhrefs(t) t = newline_to_br(t) return t
def sendUsersReminders(self, uid, reminders): """ if reminder.name and reminder.email: name = "%s (%s)" % (reminder.name, reminder.email) elif reminder.email: name = reminder.email else: name = reminder.name if reminder.snooze: msgs.append("Need to send snoozed reminder to %s" % name) else: msgs.append("Need to send reminder to %s" % name) """ if not reminders: return all_lines = [] all_html_lines = [] all_urls = {} all_names = [] user = self._getUser(uid, True) # prepare the extra text that we'll throw into the email nag = html_nag = '' if random.randint(1,3)==1 and not (\ user.first_name or \ user.last_name): # ok, this time we'll nag about getting them to enter their name html_nag = _("You still haven't completed your full name.\n") settings_url = '%s/_%s/settings' % (self.getRootURL(), user.passkey) nag = html_nag + _('Follow this link to change your settings: %s') % settings_url html_nag += _('Do that on the <a href="%s">your settings page</a>.') % settings_url elif random.randint(1,3) == 1 and len(reminders) == 1 and \ self._invitableReminder(reminders[0].rid, uid=uid): r = reminders[0] if r.name: name = r.name else: name = r.email name = unicodify(name, UNICODE_ENCODING) #LOG("RememberYourFriends.Cron", INFO, "name =%r" % name) html_nag = _(u"Do you want to invite %s to also use RememberYourFriends.com?") % name html_nag += ' ' nag = html_nag invite_url = '%s/_%s/r%s/send-invite' % (self.getRootURL(), user.passkey, r.rid) nag += _('If so, click this link: %s') % invite_url html_nag += _('If so, go to the <a href="%s">Send invite page</a>') % invite_url elif random.randint(1,4) == 1: send_invite_url = '%s/_%s/send-invite' % (self.getRootURL(), user.passkey) html_nag = _(u"You can invite more friends to RememberYourFriends.com") nag = html_nag + ' ' + _('on this page: %s') % send_invite_url html_nag += ' ' + _('on the <a href="%s">Send invite page</a>.') % send_invite_url elif random.randint(1,3) == 1: add_reminders_url = '%s/_%s/add' % \ (self.getRootURL(), user.passkey) html_nag = _(u"To add more reminders of other friends or change your current reminders") nag = html_nag + ' '+ _("go to this page: %s") % add_reminders_url html_nag += ' ' + _('go to the <a href="%s">Add a new reminder page</a>.') % add_reminders_url rooturl = self.getRootURL() for reminder in reminders: if reminder.paused: self._resetReminder(reminder.rid) continue lines = [_("You are being reminded to remember:")] html_lines = lines[:] if reminder.name and reminder.email: best_name = reminder.name name = "%s, %s" % (reminder.name, reminder.email) _html = '<a href="mailto:%s"><strong>%s</strong></a>' html_name = _html % (reminder.email, reminder.name) elif reminder.email: best_name = name = reminder.email _html = '<a href="mailto:%s"><strong>%s</strong></a>' html_name = _html % (reminder.email, reminder.email) else: name = best_name = reminder.name html_name = '<strong>%s</strong>' % reminder.name name = unicodify(name, UNICODE_ENCODING) html_name = unicodify(html_name, UNICODE_ENCODING) lines.append('\t%s\n' % name) html_lines.append(' '*4 + '%s\n' % html_name) all_names.append(name) count_sent_reminders = self._countSentRemindersByReminder(reminder.rid) if count_sent_reminders: rid = reminder.rid last_reminder = self._getSentRemindersByReminder(rid, limit=1, order='add_date', reverse=True)[0] if count_sent_reminders == 1: msg = _("One reminder sent before.") else: msg = _("%s reminders sent before.") % count_sent_reminders if last_reminder.snoozed: msg += " " + _("It was snoozed %s days") % last_reminder.snoozed lines.append(msg) html_lines.append(msg) lines.append(_("Snooze options:")) html_snooze_msg = _("Snooze this:") urls = [] _options = ('1 day', '2 days', '1 week','1 month') for e in _options: url = "%s/_%s/r%s/SNOOZE...%s" %(rooturl, user.passkey, reminder.rid, e.replace(' ','.')) all_urls[url] = e urls.append(url) html_snooze_msg += ' ' + ', '.join(urls) for url, label in all_urls.items(): html_snooze_msg = html_snooze_msg.replace(url, '<a href="%s">%s</a>' % (url, label)) lines.extend(urls) html_lines.append(html_snooze_msg) best_name = unicodify(best_name, UNICODE_ENCODING) if reminder.birthday and reminder.birthmonth: LOG("RememberYourFriends.Cron", INFO, "best_name =%r" % best_name) _edit_msg = _(u"Change settings for %s") % best_name _edit_href = '%s/_%s/edit?rid=%s&sbf=y' %\ (rooturl, user.passkey, reminder.rid) else: _edit_msg = _(u"Do you know %s's birthday?") % best_name _edit_href = '%s/_%s/edit?rid=%s' % (rooturl, user.passkey, reminder.rid) html_lines.append('<a href="%s" style="font-size:80%%">%s</a>' %\ (_edit_href, _edit_msg)) all_lines.append('\n'.join(lines)) LOG("RememberYourFriends.Cron", INFO, "html_lines =%s"%html_lines) all_html_lines.append('\n'.join(html_lines)+'\n\n') # remember that we sent something on this reminder self._logSentReminder(reminder.rid) # move the next_date forward and reset the snooze self._resetReminder(reminder.rid) if nag: all_lines.append(nag+'\n') if html_nag: all_html_lines.append(html_nag+'\n') plain_footer, html_footer = self._getSigntureWithOptout(rooturl, user.passkey) all_lines.append(plain_footer) all_html_lines.append(html_footer) msg = '\n\n'.join(all_lines) html_msg = '\n'.join(all_html_lines) html_msg = newline_to_br(html_msg) subject = _("RememberYourFriends.com reminder: ") + DateTime().strftime('%d %B') # Send it!! user = self._getUser(uid) if user.html_emails: self._sendEmailWrapped(user.email, self.getWebmasterFromfield(), subject, msg, html_msg) else: self._sendEmailWrapped(user.email, self.getWebmasterFromfield(), subject, msg)
def ShowDescription(text, display_format='', nofollow_rel=False): """ Display text, using harmless HTML """ text = SplitRegEx.sub('<!--split-->', text) codesyntax = '' if same_type(display_format, ()) or same_type(display_format, []): display_format, codesyntax = display_format if display_format == 'structuredtext': #st=_replace_special_chars(text) st = text for k, v in { #'<':'<', '>':'>', '[': '|[|' }.items(): st = st.replace(k, v) try: # my structured text st = nice_structured_text(st) except: st = structured_text(st) for k, v in { '&lt;': '<', '&gt;': '>', '|[|': '[' }.items(): st = st.replace(k, v) # BUG in structured_text in Zope 2.4.0 # it appends these annoying tags. for tag in ['<html>', '<body>', '</body>', '</html>']: st = st.replace(tag, '') pre_whole_tags = re.compile(r'<pre>.*?</pre>', re.I | re.DOTALL) pre_tags = pre_whole_tags.findall(st) mem = {} for pre_tag in pre_tags: randstr = '__%s__' % getRandomString() mem[randstr] = pre_tag st = st.replace(pre_tag, randstr) ### NEEDS TO BE FIXED! #st = addhrefs(st, urllinkfunction=mylinker) for key, tag in mem.items(): st = st.replace(key, tag) # preserve look of '<!--split-->' st = st.replace('<p><!--split--></p>', '<!--split-->') # syntax highlighting of code if str(codesyntax).lower() in ['c++', 'cpp']: st = SyntaxHighlight(st, CPP_SYNTAX) elif str(codesyntax).lower() in ['py', 'python']: st = SyntaxHighlight(st, PYTHON_SYNTAX) elif str(codesyntax).lower() in ['sql']: st = SyntaxHighlight(st, SQL_SYNTAX) elif str(codesyntax).lower() in ['xml/html', 'xml', 'html']: st = SyntaxHighlight(st, XML_SYNTAX) elif str(codesyntax).lower() in ['css', 'stylesheet']: st = SyntaxHighlight(st, CSS_SYNTAX) st = sole_ampersand_regex.sub('&', st) return st elif display_format == 'html': return text elif display_format == 'texmix': texes = getTexes(text, 1) count = 1 for tagused, texstring in texes: imageid = 'texjpeg-%s.jpg' % count imagepath = 'texcache/%s' % imageid imagetag = '<img src="%s" alt="%s" ' % (imagepath, "*generated jpeg*") if tagused.lower().find('inline') > -1: imagetag += 'class="texmix-inline"' else: imagetag += 'class="texmix"' imagetag += ' />' text = text.replace(texstring, imagetag) count += 1 text = text.replace('<texmix>', '<span class="texmix">') text = text.replace('<texmix inline="1">', '<span class="texmix-inline">') text = text.replace('</texmix>', '</span>') format = 'structuredtext' if codesyntax: format = [format, codesyntax] return ShowDescription(text, format) else: t = html_quote(text) t = t.replace('&lt;', '<').replace('&gt;', '>') t = t.replace('<!--split-->', '<!--split-->') if nofollow_rel: def nofollower(url): template = '<a href="%s" rel="nofollow">%s</a>' return template % (url, url) t = addhrefs(t, urllinkfunction=nofollower) else: t = addhrefs(t) t = newline_to_br(t) return t
def info(self, brain, allowLink=True): '''Get information from a brain''' __traceback_info__ = (brain, allowLink) id = brain.getId url = brain.getURL() portal_type = brain.portal_type collection = portal_type in self.coll_types tool = self.tool preview = tool.getPreviewUrl(portal_type, url) # Path for the uid catalog doesn't have the leading '/' path = brain.getPath() UID = None if path and self.portal_catalog: try: indexdata = self.portal_catalog.getIndexDataForUID(path) except KeyError: indexdata = None if indexdata: UID = indexdata.get('UID', None) if UID: id = UID if collection and self.resource_type.allow_browse: src = brain.getURL() 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(brain, 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(brain) title = filterControlChars(brain.Title or brain.getId) description = newline_to_br(html_quote(brain.Description)) linkable = None if allowLink: linkable = True collection = False anchor = portal_type in self.anchor_types review_state, className = self.getState(brain.review_state) 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, }
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: if self.portal_interface.objectImplements( obj, 'Products.Archetypes.interfaces.referenceable.IReferenceable' ): UID = getattr(obj.aq_explicit, 'UID', None) if UID: UID = UID() id = UID if not id: 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
report_item_list.append( (attachment.get('title', document.getStandardFilename(format=format)), document.getRelativeUrl())) # pre-convert document before sending notification if format: document.activate(tag=pre_convert_tag).convert(format=format) url_base = portal.ERP5Site_getAbsoluteUrl() attachment_link_list = [{ 'download_link': '%s/%s?format=%s' % (url_base, report_url, format), 'name': report_name } for (report_name, report_url) in report_item_list] message_html = newline_to_br(html_quote(message)) message_text_format = "text/html" attachment_list = [] notification_message_reference = prefs.getPreferredDeferredReportNotificationMessageReference( ) if notification_message_reference: notification_message = portal.portal_notifications.getDocumentValue( reference=notification_message_reference) if notification_message is None: raise ValueError( 'Notification message not found by %r' % prefs.getPreferredDeferredReportNotificationMessageReference()) notification_mapping_dict = { 'report_link_list': portal.ERP5Site_viewReportCompleteNotificationMessage(
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) notifyobjectinitialization(obj) obj.reindexObject() if linkbyuid and hasattr(obj, 'UID'): url = base + '/resolveuid/%s' % obj.UID() 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)))