def get_item_value(self, resource, context, item, column): gallery = resource.parent if column in ['image', 'title', 'edit']: image = resource.get_resource(item.name, soft=True) if image is None: # XXX Why ? image = gallery.get_resource(item.name, soft=True) if image is None: return None link = context.get_link(image) if column == 'image': src = '%s/;thumb?width=%s&height=%s' % (link, 250, 250) preview = '<img src="%s"/>' % src return XMLParser(preview.encode('utf-8')) elif column == 'title': return image.get_title() elif column == 'edit': edit = (""" <a href="%s/;edit" title="Edit image"> <img src="/ui/icons/16x16/edit.png"/> </a> """ % link) return XMLParser(edit) return OrderedTable_View.get_item_value(self, resource, context, item, column)
def get_item_value(self, resource, context, item, column): item_brain, item_resource = item if column == 'barcode': reference = item_resource.get_property('reference') if reference is None: return None link = context.get_link(item_resource) return XMLParser('<img src="%s/barcode/;download"/>' % link) elif column == 'cover': cover = item_resource.get_cover_namespace(context) if cover: uri = cover['href'] return XMLParser(""" <div class="thumb-products"> <a href="%s/;download" rel="fancybox"> <img src="%s/;thumb?width=48&height=48"/> </a> </div> """% (uri, uri)) return XMLParser('<div class="thumb-products"/>') elif column == 'stored_price': price = item_resource.get_price_with_tax(pretty=True) if item_resource.get_property('has_reduction'): price = price.encode('utf-8') return XMLParser('<span style="color:red">%s</span>'% price) return price # Super proxy = super(Products_View, self) return proxy.get_item_value(resource, context, item, column)
def get_namespace(self, resource, context): proxy = super(Shop_UserSendConfirmation, self) namespace = proxy.get_namespace(resource, context) confirm_msg = MSG(u"""Fill this form to receive a mail with the link to activate your account""") namespace['required_msg'] = (list(XMLParser(confirm_msg.gettext().encode('utf8'))) + list(XMLParser('<br/>')) + list(namespace['required_msg'])) return namespace
def _format(self, message, **kw): if self.format == 'replace': return msg_formatter.vformat(message, [], (self, kw)) elif self.format == 'none': return message elif self.format == 'html': data = message.encode('utf_8') return XMLParser(data, namespaces=xhtml_namespaces) elif self.format == 'replace_html': message = msg_formatter.vformat(message, [], (self, kw)) data = message.encode('utf_8') return XMLParser(data, namespaces=xhtml_namespaces) raise ValueError, 'unexpected format "{0}"'.format(self.format)
def get_namespace(self, resource, context): # Render txt version as webmail txt_data = resource.get_email_text(context) txt_data = XMLContent.encode(txt_data) txt_data = re.sub(r'(\A|\s)(http://(\w|\.|/|:|;|\?|=|%|&|-)+)', r'\1<a href="\2" target="_blank"> \2</a>', txt_data) txt_data = XMLParser(txt_data.replace('\n', '<br/>')) # Return namespace return {'title': resource.get_title(), 'email_subject': resource.get_email_subject(context), 'spool_size': context.server.get_spool_size(), 'nb_users': resource.parent.get_subscripters_nb(), 'is_sent': resource.get_property('is_sent'), 'number': resource.get_property('number'), 'txt_data': txt_data}
def decode(cls, data): events = XMLParser(data, namespaces=xhtml_namespaces, doctype=xhtml_doctype) if cls.sanitize_html is True: events = sanitize_stream(events) return list(events)
class SelectRadioImages(SelectRadio): template = list( XMLParser( """ <ul style="list-style-type:none;margin:0;padding:0;"> <li stl:if="has_empty_option" style="width:110px;height=110px;float:left;"> <input id="${id}" type="radio" name="${name}" value="" checked="checked" stl:if="none_selected"/> <input id="${id}" type="radio" name="${name}" value="" stl:if="not none_selected"/> <label for="${id}" style="width:60px;height:60px;display:block;border:1px dashed gray; padding:20px;"> No picture </label> </li> <li style="float:left;width:110px;height=110px;" stl:repeat="option options"> <input type="radio" id="${id}-${option/name}" name="${name}" value="${option/name}" checked="checked" stl:if="option/selected"/> <input type="radio" id="${id}-${option/name}" name="${name}" value="${option/name}" stl:if="not option/selected"/> <label for="${id}-${option/name}"> <img src="${option/link}/;thumb?width=100&height=100" title=" ${option/value}"/> </label> </li> </ul> """, stl_namespaces))
class BirthdayWidget(Widget): template = list( XMLParser( """ ${day} ${month} ${year} <input type="hidden" name="${name}" value="1"/> """, stl_namespaces)) def get_namespace(self, datatype, value): namespace = Widget.get_namespace(self, datatype, value) context = get_context() if value and value != '1': try: day, month, year = value.split('/') day = int(day) month = int(month) year = int(year) except: day = month = year = None else: day = context.get_form_value('day', type=Integer) month = context.get_form_value('month', type=Integer) year = context.get_form_value('year', type=Integer) namespace['day'] = SelectWidget('day').to_html(Days, day) namespace['month'] = SelectWidget('month').to_html(Months, month) namespace['year'] = SelectWidget('year').to_html(Years, year) return namespace
class RangeSlider(Widget): template = list( XMLParser( """ <input type="text" id="${id}-amount" style="border:0; color:#f6931f; font-weight:bold;" /> <div id="${id}"/> <script type="text/javascript" src="/ui/shop/js/jquery.slider.js"/> <script type="text/javascript"> $(function() { $("#${id}").slider({ range: true, min: 0, max: 5000, values: [0, 10], slide: function(event, ui) { $("#${id}-amount").val(ui.values[0] + ' - ' + ui.values[1]); } }); }); </script> """, stl_namespaces)) def get_namespace(self, datatype, value): namespace = Widget.get_namespace(self, datatype, value) namespace['title'] = self.title return namespace
def get_events(self, filename): content = self.get_file(filename) for event in XMLParser(content): if event == XML_DECL: pass else: yield event
def get_before_namespace(self, resource, context): # Set organizer infos in ${before} owner = resource.get_owner() owner = resource.get_resource(owner).get_title() owner_msg = MSG(u'<p id="event-owner">Created by <em>{owner}</em></p>') owner_msg = owner_msg.gettext(owner=owner).encode('utf-8') return XMLParser(owner_msg)
def _load_state_from_file(self, file): # FIXME The XML parser does not support reading from a StringIO if type(file) is InputType: file = file.read() stream = XMLParser(file) self.events = list(stream)
def _format(self, message, **kw): if self.format == 'stl': events = XMLParser(message.encode('utf_8'), namespaces=stl_namespaces) return stl(events=events, namespace=self) return super(INFO, self)._format(message, **kw)
def get_rss_news(self, context): url = getattr(context.site_root, 'backoffice_rss_news_uri', None) if url is None: return [] # Flux de news RSS try: f = urlopen(url) except Exception: return [] try: feed = RSSFile(string=f.read()) except (XMLError, IndexError): return [] rss_news = [] for item in feed.items[:5]: item['ago'] = datetime_to_ago(item['pubDate']) if item.get('pubDate'): item['pubDate'] = format_date(item['pubDate'], context.accept_language) else: item['pubDate'] = None item['description'] = XMLParser( item['description'].encode('utf-8')) rss_news.append(item) return rss_news
def get_namespace(self, context): # Build namespace namespace = { 'author': self.get_namespace_author(context), 'href': context.get_link(self), 'images': self.get_images(context) } for key in ['title', 'note', 'advantages', 'disadvantages']: namespace[key] = self.get_property(key) # Add informations about product product = self.parent.parent namespace['product'] = { 'link': context.get_link(product), 'title': product.get_title() } # Context here = context.resource namespace['is_on_user_view'] = here.class_id == 'user' namespace['is_on_product_view'] = here.class_id == 'product' # Description description = self.get_property('description').encode('utf-8') description = XMLContent.encode(description) namespace['description'] = XMLParser(description.replace( '\n', '<br/>')) # ctime ctime = self.get_property('ctime') accept = context.accept_language namespace['ctime'] = format_datetime(ctime, accept) # Recommendation recommended = self.get_property('recommended') or 0 namespace['recommendation'] = bool(int(recommended)) return namespace
def test_stream_to_html_escape(self): parser = XMLParser('<p xmlns="http://www.w3.org/1999/xhtml"></p>') events = list(parser) events.insert(1, (xml_TEXT, '<br/>', 0)) self.assertEqual( stream_to_html(events), '<p xmlns="http://www.w3.org/1999/xhtml"><br/></p>')
def test_html(self): parser = XMLParser( '<p xmlns="http://www.w3.org/1999/xhtml">Bed&Breakfast</p>') out = stream_to_html(parser) # Assert self.assertEqual( out, '<p xmlns="http://www.w3.org/1999/xhtml">Bed&Breakfast</p>')
def get_item_value(self, resource, context, item, column): brain, item_resource = item if column == 'name': link = '%s/%s' % (resource.get_property('shop_uri'), brain.name) return XMLParser("<a href='%s' target='_blank'>%s</a>" % (link, brain.name)) return Folder_BrowseContent.get_item_value(self, resource, context, item, column)
def _load_state_from_file(self, file): text = None self.header = {} messages = {} self.header_notes = {} for event, value, line_number in XMLParser(file.read()): if event == START_ELEMENT: namespace, local_name, attributes = value # Attributes, get rid of the namespace uri (XXX bad) aux = {} for attr_key in attributes: attr_name = attr_key[1] aux[attr_name] = attributes[attr_key] attributes = aux if local_name == 'tmx': self.version = attributes['version'] elif local_name == 'header': self.header = attributes default_srclang = attributes['srclang'] notes = [] elif local_name == 'note': note = TMXNote(attributes=attributes) elif local_name == 'tu': tu = TMXUnit(attributes) notes = [] elif local_name == 'tuv': tuv = Sentence(attributes) notes = [] segment = None elif event == END_ELEMENT: namespace, local_name = value if local_name == 'header': self.header_notes = notes elif local_name == 'note': note.text = text notes.append(note) elif local_name == 'tu': tu.notes = notes srclang = tu.attributes.get('srclang', default_srclang) if srclang == '*all*': raise NotImplementedError, \ 'no support for "*all*" in srclang attribute.' msgid = tu.msgstr[srclang].text messages[msgid] = tu elif local_name == 'tuv': if segment is not None: tuv.notes = notes tuv.text = segment tu.msgstr[tuv.attributes['lang']] = tuv elif local_name == 'seg': segment = text elif event == COMMENT: pass elif event == TEXT: text = unicode(value, 'UTF-8') self.messages = messages
def test_3(self): doctype = DocType(PubidLiteral='-//W3C//DTD XHTML 1.0 Strict//EN', SystemLiteral= 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', intSubset='\n<!ENTITY entity_test "TEST">\n') data = '<html>À &entity_test;</html>' # No raise list(XMLParser(data, doctype=doctype))
def test_3(self): data = ('<?xml version="1.0"?>\n' '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' '<html>« ƒ Ξ ψ ‰ ℜ ∞ ' '∴ ♣</html>\n') expected = '« ƒ Ξ ψ ‰ ℜ ∞ ∴ ♣' parser = XMLParser(data) self.assertEqual(list(parser)[5][1], expected)
def get_item_value(self, resource, context, item, column): if column == 'numero': state = item.workflow_state href = './;order_view?id=%s' % item.name name = item.get_reference() return XMLParser(numero_template % (states_color[state], href, name)) elif column == 'state': state = item.workflow_state state_title = states[state].gettext().encode('utf-8') href = './;order_view?id=%s' % item.name return XMLParser(numero_template % (states_color[state], href, state_title)) elif column == 'total_price': price = item.get_property(column) return format_price(price) elif column == 'creation_datetime': value = item.get_property(column) accept = context.accept_language return format_datetime(value, accept=accept) return BrowseForm.get_item_value(self, resource, context, item, column)
def get_namespace(self, resource, context): namespace = RegisterForm.get_namespace(self, resource, context) # Add register body group = self.get_group(context) register_body = group.get_property('register_body') if register_body is not None: namespace['required_msg'] = (register_body + list(XMLParser('<br/><br/>')) + list(namespace['required_msg'])) return namespace
class FilesWidget(Widget): template = list( XMLParser( """ <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> """, stl_namespaces))
def get_namespace(self, resource, context): proxy = super(Shop_UserConfirmRegistration, self) namespace = proxy.get_namespace(resource, context) confirm_msg = MSG(u""" You have not yet confirmed your registration.<br/> To confirm it, please click on the confirmation link included on the registration confirmation email.<br/> You can also fill your email address and your activation key (received on the mail) in the following form.<br/> If you havn't received your registration key, <a href=";send_confirmation_view"> you can receive it again by clicking here. </a> """) namespace['required_msg'] = (list(XMLParser(confirm_msg.gettext().encode('utf8'))) + list(XMLParser('<br/>')) + list(namespace['required_msg'])) return namespace
def test_serialize(self): data = self.rss.to_str() # Testing the hand-written XML is well-formed events = list(XMLParser(data)) # Testing the XML processing instruction event, value, line_number = events[0] self.assertEqual(event, XML_DECL) version, encoding, standalone = value self.assertEqual(version, '1.0') self.assertEqual(encoding, 'UTF-8')
class SIRETWidget(Widget): template = list( XMLParser( """ <input type="text" id="${id}" name="${name}" value="${value}"/> <script type="text/javascript" src="/ui/shop/js/jquery.maskedinput-1.2.2.min.js"/> <script type="text/javascript"> $("#${id}").mask("999 999 999 99999"); </script> """, stl_namespaces))
def get_options(cls): from products.enumerate import CategoriesEnumerate datatype = CategoriesEnumerate context = get_context() value = context.resource.get_property('specific_category') html = SelectWidget('specific_category').to_html(datatype, value) opt = [{ 'name': 'one_category', 'value': list(XMLParser('Only this category')) + list(html) }] return cls.base_options + opt
def get_announce(self, context): url = getattr(context.site_root, 'backoffice_announce_uri', None) if url is None: return None try: f = urlopen(url) data = XMLParser(f.read()) except Exception: return None if f.code == 404: return None return data
class MiniProductWidget(Widget): template = list( XMLParser("""${viewbox}<div class="clear"/>""", stl_namespaces)) def get_namespace(self, datatype, value): context = get_context() product = context.resource while product.class_id != 'product': product = product.parent viewbox = product.viewbox return {'viewbox': viewbox.GET(product, context)}
def test_1(self): dtd = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" ' '[\n' '<!ENTITY entity_test "TEST">\n' ']>') data = '<?xml version="1.0"?>\n'+dtd parser = XMLParser(data) name, doctype = list(parser)[2][1] self.assertEqual(get_doctype(name, doctype), dtd)
def test_formatting(self): context = Context() data = '<p>TXT <i>TEXT<u>TEXT</u></i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para>TXT <i>TEXT<u>TEXT</u></i></para>') data = '<p>TXT <i>TEXT<u>TEXT</u>TEXT</i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] goodanswer = '<para>TXT <i>TEXT<u>TEXT</u>TEXT</i></para>' self.assertEqual(para.text, goodanswer) data = '<p>TXT <i>TEXT<u>TEXT</u></i>TEXT</p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] goodanswer = '<para>TXT <i>TEXT<u>TEXT</u></i>TEXT</para>' self.assertEqual(para.text, goodanswer) data = '<p>TXT <i>TEXT<u>TEXT</u>TEXT</i>TEXT</p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] goodanswer = '<para>TXT <i>TEXT<u>TEXT</u>TEXT</i>TEXT</para>' self.assertEqual(para.text, goodanswer) data = '<p>TXT <i><u>TXT</u></i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para>TXT <i><u>TXT</u></i></para>') data = '<p><i>TEXT<u>TEXT</u></i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para><i>TEXT<u>TEXT</u></i></para>') data = '<p><i>TEXT<u>TEXT</u>TEXT</i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para><i>TEXT<u>TEXT</u>TEXT</i></para>') data = '<p><i>TEXT<u>TEXT</u></i>TEXT</p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para><i>TEXT<u>TEXT</u></i>TEXT</para>') data = '<p><i>TEXT<u>TEXT</u>TEXT</i>TEXT</p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] goodanswer = '<para><i>TEXT<u>TEXT</u>TEXT</i>TEXT</para>' self.assertEqual(para.text, goodanswer) data = '<p><i><u>TXT</u></i></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para><i><u>TXT</u></i></para>') data = '<p>TEXT<sup>TEXT</sup></p>' stream = XMLParser(data, NAMESPACES) stream.next() context.path_on_start_event('p', {}) para = paragraph_stream(stream, 'p', {}, context)[0] self.assertEqual(para.text, '<para>TEXT<super><font fontSize="7.2">TEXT</font></super></para>')