def GET(self, resource, context): # Get the namespace namespace = self.get_namespace(resource, context) if isinstance(namespace, Reference): return namespace # STL template = self.get_template(resource, context) if isinstance(template, (GeneratorType, XMLParser)): return stl(events=template, namespace=namespace) return stl(template, namespace)
def GET(self, resource, context): # Get the namespace namespace = self.get_namespace(resource, context) if isinstance(namespace, Reference): return namespace # STL template = self.get_template(resource, context) if type(template) is list: return stl(None, namespace, events=template) return stl(template, namespace)
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_admin_bar(resource, buttons=[]): context = get_context() if is_navigation_mode(context): return ac = resource.get_access_control() if not ac.is_allowed_to_edit(context.user, resource): return events = admin_bar_template if not buttons else admin_bar_icon_template if hasattr(resource, 'get_admin_edit_link'): link = resource.get_admin_edit_link(context) else: link = '%s/;edit' % context.get_link(resource) use_fancybox = getattr(resource, 'use_fancybox', True) # workflow workflow = None if isinstance(resource, WorkflowAware): statename = resource.get_statename() state = resource.get_state() workflow = {'state': statename, 'title': state['title'].gettext().encode('utf-8')} title = MSG(u"Edit box '{title}'").gettext(title=resource.get_title()) namespace = {'link': link, 'rel': 'fancybox' if use_fancybox else None, 'buttons': buttons, 'class_title': resource.class_title, 'title': title, 'workflow': workflow} return stl(events=events, namespace=namespace)
def get_messages(self, context): """Return the message string of the last action. A list of messages is supported. """ # Text if context.message is not None: messages = context.message elif 'error' in context.uri.query: messages = ERROR(context.get_query_value('error', type=Unicode)) elif 'info' in context.uri.query: messages = INFO(context.get_query_value('info', type=Unicode)) # XXX For backwards compatibility elif 'message' in context.uri.query: messages = INFO(context.get_query_value('message', type=Unicode)) else: return None # Multiple messages: if not isinstance(messages, list): messages = [messages] messages_ns = [] for message in messages: css_class = getattr(message, 'css', 'info') messages_ns.append({'message': message, 'class': css_class}) namespace = {'messages': messages_ns} template = context.get_template('/ui/aruni/message.xml') return stl(template, namespace)
def GET(self, order, way, record, context): # Get the template template = self.get_template(order, context) # Get the namespace namespace = self.get_namespace(order, way, record, context) # Ok return stl(template, namespace)
def stl_to_odt(model_odt, namespace): # STL events = list(model_odt.get_events('content.xml')) xml_content = stl(namespace=namespace, events=events, mode='xml') modified_files = {'content.xml': xml_content} # Zip return zip_data(model_odt.data, modified_files)
def to_opml_stream(self, context): namespace = {} namespace['title'] = self.get_property('title') namespace['mtime'] = HTTPDate.encode(self.get_mtime()) revisions = self.get_revisions(context) name = email = None if revisions: root = context.root username = revisions[0]['username'] user = root.get_user(username) if user: name = user.get_title() email = user.get_property('email') owner = {'name': name, 'email': email} namespace['owner'] = owner # Feeds articles, errors = self.get_articles() feeds_cache = deepcopy(self.handler.feeds_summary) feeds = [] for uri, data in feeds_cache.iteritems(): feeds.append({'title': data['title'], 'nb_articles': data['nb_articles'], 'uri': uri, 'type': 'rss' # FIXME hardcoded }) namespace['feeds'] = feeds handler = self.get_resource('/ui/rssfeeds/RssFeeds_export_to_opml.xml') return stl(handler, namespace=namespace)
def get_icon_with_title(resource, context): path_to_icon = resource.get_resource_icon(16) if path_to_icon.startswith(';'): path_to_resource = context.get_link(resource) path_to_icon = path_to_resource.resolve(path_to_icon) title = resource.class_title.gettext() return stl(events=icon_with_title_template, namespace={'icon': path_to_icon, 'title': title})
def GET(self, resource, context): # Get the namespace namespace = self.get_namespace(resource, context) # Return xml context.set_content_type('text/xml') # Ok template = resource.get_resource(self.template) return stl(template, namespace, mode='xml')
def internal_server_error(self, context): # Send email (TODO Move this to the itools.log system) self.alert_on_internal_server_error(context) # Ok namespace = {'traceback': traceback.format_exc()} handler = context.get_template('/ui/ikaaro/root/internal_server_error.xml') return stl(handler, namespace, mode='html')
def GET(self, resource, context): # Get the namespace namespace = self.get_namespace(resource, context) if isinstance(namespace, Reference): return namespace # STL template = self.get_template(resource, context) return stl(template, namespace)
def GET(self, resource, context): # FIXME if context.message: return context.come_back(context.message) # Ok template = '/ui/hforge/subscribe_ok.xml' handler = resource.get_resource(template) return stl(handler)
def test_if_not(self): handler = XMLFile( string='<img xmlns:stl="http://www.hforge.org/xml-namespaces/stl"' ' stl:if="not img" />') namespace = {'img': True} stream = stl(handler, namespace) # Assert events = list(stream) self.assertEqual(events, [])
def test_attribute_accent(self): handler = XMLFile(string= '<input xmlns="http://www.w3.org/1999/xhtml" value="${name}" />') namespace = {'name': u'étoile'} stream = stl(handler, namespace) # Assert events = list(stream) value = events[0][1][2][(None, 'value')] self.assertEqual(value, 'étoile')
def test_attribute(self): handler = XMLFile(string= '<img xmlns="http://www.w3.org/1999/xhtml" alt="${alt}" />') namespace = {'alt': 'My title'} stream = stl(handler, namespace) # Assert events = list(stream) value = events[0][1][2][(None, 'alt')] self.assertEqual(value, 'My title')
def test_repeat(self): handler = XMLFile( string='<option xmlns:stl="http://www.hforge.org/xml-namespaces/stl"' ' stl:repeat="option options" />') namespace = {'options': []} stream = stl(handler, namespace) # Assert events = list(stream) self.assertEqual(events, [])
def test_if(self): handler = XMLFile(string= '<img xmlns:stl="http://www.hforge.org/xml-namespaces/stl"' ' stl:if="img" />') namespace = {'img': False} stream = stl(handler, namespace) # Assert events = list(stream) self.assertEqual(events, [])
def test_repeat(self): handler = XMLFile(string= '<option xmlns:stl="http://www.hforge.org/xml-namespaces/stl"' ' stl:repeat="option options" />') namespace = {'options': []} stream = stl(handler, namespace) # Assert events = list(stream) self.assertEqual(events, [])
def test_attribute(self): handler = XMLFile(string= '<img xmlns="http://www.w3.org/1999/xhtml" border="${border}" />') namespace = {'border': 5} stream = stl(handler, namespace) # Assert events = list(stream) value = events[0][1][2][(None, 'border')] self.assertEqual(value, '5')
def test_attribute(self): handler = XMLFile( string= '<img xmlns="http://www.w3.org/1999/xhtml" border="${border}" />') namespace = {'border': 5} stream = stl(handler, namespace) # Assert events = list(stream) value = events[0][1][2][(None, 'border')] self.assertEqual(value, '5')
def get_csv_namespace(self, resource, context): namespace = {} datatype = self.csv_schema['csv_format'] namespace['format'] = SelectWidget('csv_format', value=datatype.get_default(), datatype=datatype, has_empty_option=False) namespace['action'] = CSVExportButton(resource=resource, context=context, items=[0]) template = resource.get_resource(self.csv_template) return stl(template, namespace)
def get_namespace(self, resource, context): namespace = {'lines': []} # Search search_template = resource.get_resource(self.search_template) search_namespace = self.get_search_namespace(resource, context) namespace['search'] = stl(search_template, search_namespace) # Is a research ? if context.uri.query.has_key('search') is False: return namespace # Get all declinations (for optimization purpose) all_products = context.root.search(format='product') # Do products = {} items = self.get_items(resource, context) for i, brain in enumerate(items): # It's a product or a declination ? if brain.format == 'product': brain_product = brain brain_declination = None else: brain_declination = brain parent_path = '/'.join(brain_declination.abspath.split('/')[:-1]) brain_product = all_products.search(abspath=parent_path).get_documents()[0] # Get corresponding product if products.has_key(brain_product.reference): kw = products[brain_product.reference] else: nb_products = len(products) kw = {'id': nb_products + 1, 'reference': brain_product.reference, 'title': brain_product.title, 'href': '/' + '/'.join(brain_product.abspath.split('/')[2:]), # XXX Hack 'declinations': [], 'nb_declinations': 0, 'has_declination': False, 'stock_quantity': brain_product.stock_quantity} products[brain_product.reference] = kw # Get declination if brain_declination: nb_declinations = kw['nb_declinations'] d = {'id': nb_declinations + 1, 'name': brain_declination.name, 'title': brain_declination.declination_title, 'stock_quantity': brain_declination.stock_quantity} kw['has_declination'] = True kw['declinations'].append(d) kw['nb_declinations'] = nb_declinations + 1 products[brain_product.reference] = kw # Build namespace products = products.values() products.sort(key=itemgetter('id')) namespace['lines'] = products namespace['references_number'] = len(namespace['lines']) return namespace
def action(self, resource, context, form): # Get the user email = form['username'].strip() user = context.root.get_user_from_login(email) if form['no_password']: if not Email.is_valid(email): message = u'The given username is not an email address.' context.message = ERROR(message) return # Case 1: Register # check captcha first captcha = form['captcha'].strip() crypted = crypt_captcha(captcha) crypt_imgtext = form['crypt_imgtext'].strip() decrypt = Password.decode('%s' % crypt_imgtext) if crypted != decrypt: error = u"You typed an incorrect captcha string." context.message = ERROR(error) return # does the user exists? if user is None: if context.site_root.is_allowed_to_register(): return self._register(resource, context, email) # FIXME This message does not protect privacy error = u"You don't have an account, contact the site admin." context.message = ERROR(error) return # Case 2: Forgotten password email = user.get_property('email') user.send_forgotten_password(context, email) path = '/ui/website/forgotten_password.xml' handler = resource.get_resource(path) return stl(handler) # Case 3: Login password = form['password'] if user is None or not user.authenticate(password, clear=True): context.message = ERROR(u'The email or the password is incorrect.') return # Set cookie & context user.set_auth_cookie(context, password) context.user = user # Come back referrer = context.get_referrer() if referrer is None: goto = get_reference('./') else: path = get_uri_path(referrer) if path.endswith(';login'): goto = get_reference('./') else: goto = referrer return context.come_back(INFO(u"Welcome to the Phoenix Project!"), goto)
def get_namespace(self, resource, context): batch = None # Batch items = self.get_items(resource, context) if self.batch_template is not None: template = resource.get_resource(self.batch_template) namespace = self.get_batch_namespace(resource, context, items) batch = stl(template, namespace) items = self.sort_and_batch(resource, context, items) # Shop modules shop_module = ModuleLoader() shop_module.context = context shop_module.here = self # Lazy lazy = LazyDict() lazy.cache = {} lazy.context = context lazy.resource = resource lazy.s = self # Build namespace namespace = { 'batch': list(batch), 'title': resource.get_title(), 'breadcrumb_title': resource.get_property('breadcrumb_title'), 'lazy': lazy, 'module': shop_module, 'products': [], 'description': None} # Photo img = resource.get_property('image_category') if img: img = resource.get_resource(img, soft=True) if img: namespace['photo'] = context.get_link(img) else: namespace['photo'] = None # Get products view box for item_resource in items: # XXX Hack for cross selling # Cross selling return only resource not brain if type(item_resource) is tuple: item_brain, item_resource = item_resource viewbox = item_resource.viewbox namespace['products'].append({'name': item_resource.name, 'abspath': str(item_resource.get_abspath()), 'box': viewbox.GET(item_resource, context)}) # Categorie description (not for categories folder) namespace['description'] = resource.get_property('data') return namespace
def internal_server_error(self, context): # We send an email to administrators for email in self.get_property('administrators'): subject = MSG(u'Internal server error').gettext() headers = u'\n'.join([u'%s => %s' % (x, y) for x, y in context.get_headers()]) text = internal_error_body.gettext(uri=context.uri, error=traceback.format_exc(), headers=headers) self.send_email(email, subject, text=text) # We show a prerry error page database = context.database namespace = {'traceback': '', 'read_only': type(database) is ReadOnlyDatabase} handler = get_skin_template(context, 'internal_server_error.xml') return stl(handler, namespace, mode='html')
def get_introduction(self, resource, context): # Get payement way payment_way = resource.get_payment_way() if payment_way: payment_way = {'title': payment_way.get_title(), 'link': context.get_link(payment_way)} # Get order order = resource.get_order() if order: order = {'title': order.get_title(), 'link': context.get_link(order)} # Build namespace namespace = {'name': resource.name, 'order': order, 'payment_way': payment_way} template = resource.get_resource(self.introduction_template) return stl(template, namespace=namespace)
def view(self): # Load the STL template handler = ro_database.get_handler('TaskTracker_view.xml') # Build the namespace namespace = {} namespace['tasks'] = [] for i, task in enumerate(self.tasks): namespace['tasks'].append({'id': i, 'title': task.title, 'description': task.description, 'state': task.state, 'is_open': task.state == 'open'}) # Process the template and return the output return stl(handler, namespace, mode='xhtml')
def get_payment_way_description(self, context, total_amount): total_amount = total_amount['with_tax'] if not type(total_amount) is decimal: # XXX We don't need currency total_amount = decimal(total_amount.split(' ')[0]) amount_available = self.get_credit_available_for_user(context.user.name) remaining_amount = amount_available - total_amount if remaining_amount < decimal('0'): remaining_amount = decimal('0') namespace = {'amount_available': format_price(amount_available), 'has_to_complete_payment': amount_available < total_amount, 'amount_to_pay': format_price(total_amount-amount_available), 'remaining_amount': format_price(remaining_amount), 'total_amount': format_price(total_amount)} description_template = self.get_resource( '/ui/backoffice/payments/credit/description.xml') return stl(description_template, namespace=namespace)
def render(self, context): namespace = {'title': self.title, 'action': '.', 'description': self.description, 'css': self.css, 'advanced_title': self.advanced_title, 'actions': self.actions, 'has_required_widget': False, 'widgets': []} # If any widget advanced, activate advance mode advanced = False for widget in self.widgets: datatype = self.schema[widget.name] try: value = self.get_value_method(widget.name, type=datatype) except FormError: value = self.get_value_method(widget.name) error = MSG(u'Invalid value.') else: error = None if issubclass(datatype, Enumerate): value = datatype.get_namespace(value) elif datatype.multiple: value = value[0] widget.datatype = datatype widget.value = value w_advanced = getattr(widget, 'advanced', None) advanced = advanced or w_advanced namespace['widgets'].append( {'name': widget.name, 'id': widget.id, 'title': widget.title, 'multiple': getattr(datatype, 'multiple', False), 'tip': getattr(widget, 'tip', None), 'mandatory': getattr(datatype, 'mandatory', False), 'endline': getattr(widget, 'endline', None), 'class': None, 'advanced': w_advanced and 'advanced', 'suffix': widget.suffix, 'error': error, 'widget': widget}) if namespace['widgets']: namespace['first_widget'] = namespace['widgets'][0]['name'] namespace['advanced'] = advanced template = context.resource.get_resource(self.template) return stl(template, namespace)
def internal_server_error(self, context): # We send an email to administrators for email in self.get_property('administrators'): subject = MSG(u'Internal server error').gettext() headers = u'\n'.join( [u'%s => %s' % (x, y) for x, y in context.get_headers()]) text = internal_error_body.gettext(uri=context.uri, error=traceback.format_exc(), headers=headers) self.send_email(email, subject, text=text) # We show a prerry error page database = context.database namespace = { 'traceback': '', 'read_only': type(database) is ReadOnlyDatabase } handler = get_skin_template(context, 'internal_server_error.xml') return stl(handler, namespace, mode='html')
def view(self): # Load the STL template handler = ro_database.get_handler('TaskTracker_view.xml') # Build the namespace namespace = {} namespace['tasks'] = [] for i, task in enumerate(self.tasks): namespace['tasks'].append({ 'id': i, 'title': task.title, 'description': task.description, 'state': task.state, 'is_open': task.state == 'open' }) # Process the template and return the output return stl(handler, namespace, mode='xhtml')
def template(self, content): context = get_context() # Build the namespace namespace = self.build_namespace(context) namespace['body'] = content # Set the encoding to UTF-8 context.content_type = 'text/html; charset=UTF-8' # Load the template prefix, handler = self.get_template(context) # Build the output s = ['<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"\n' ' "http://www.w3.org/TR/html4/strict.dtd">'] # STL data = stl(handler, namespace, prefix=prefix, mode='html') s.append(data) return ''.join(s)
def get_item_value(self, resource, context, item, column): if column == 'links': brain, item_resource = item root = context.root path = str(item_resource.get_canonical_path()) results = root.search(links=path) if len(results) == 0: return 0 links = [] for index, doc in enumerate(results.get_documents()): links_resource = root.get_resource(doc.abspath) parent_resource = links_resource.parent # links_resource should be an ordered table links.append({'name': (index + 1), 'title': parent_resource.get_title(), 'path': context.get_link(links_resource)}) events = self.links_template return stl(events=events, namespace={'items': links}) return Folder_BrowseContent.get_item_value(self, resource, context, item, column)
def get_namespace(self, resource, context): batch = None table = None # Batch items = self.get_items(resource, context) if self.batch is not None: total = len(items) batch = self.batch(context=context, total=total).render() # Content items = self.sort_and_batch(resource, context, items) if self.table_template is not None: template = context.get_template(self.table_template) namespace = self.get_table_namespace(resource, context, items) table = stl(template, namespace) # The Search Form search = None if self.search_widgets: search = self.get_search_namespace(resource, context) return {'batch': batch, 'table': table, 'search': search}
def action(self, resource, context, form): # Get the user loginname = form['loginname'].strip() user = context.root.get_user_from_login(loginname) # Case 1: Forgotten password if form['no_password']: # 1.1 Send email if user: email = user.get_value('email') if user.get_value('user_state') == 'invalid': email_id = None # TODO else: user.update_pending_key() email_id = 'forgotten-password-ask-for-confirmation' else: email_id = None # TODO Which is the email address? if email_id: send_email(email_id, context, email, user=user) # 1.2 Show message (we show the same message even if the user # does not exist, because privacy wins over usability) path = '/ui/website/forgotten_password.xml' handler = context.get_template(path) return stl(handler) # Case 2: Login if user is None: context.message = MSG_LOGIN_WRONG_NAME_OR_PASSWORD return error = user._login(form['password'], context) if error: context.message = error return return self.get_goto(user)
def action(self, resource, context, form): # Get the user loginname = form['loginname'].strip() user = context.root.get_user_from_login(loginname) # Case 1: Forgotten password if form['no_password']: # 1.1 Send email if user: email = user.get_value('email') if user.get_value('user_state') == 'inactive': email_id = None # TODO else: user.update_pending_key() email_id = 'forgotten-password-ask-for-confirmation' else: email_id = None # TODO Which is the email address? if email_id: send_email(email_id, context, email, user=user) # 1.2 Show message (we show the same message even if the user # does not exist, because privacy wins over usability) path = '/ui/ikaaro/website/forgotten_password.xml' handler = context.get_template(path) return stl(handler) # Case 2: Login if user is None: context.message = MSG_LOGIN_WRONG_NAME_OR_PASSWORD return error = user._login(form['password'], context) if error: context.message = error return return self.get_goto(user)
def render(self): prefix = self.get_prefix() template = self.get_template() return stl(events=template, namespace=self, prefix=prefix)
def get_namespace(self, resource, context): namespace = super(AutoForm, self).get_namespace(resource, context) # Local Variables template = context.get_template(self.template_field) fields = self.get_schema(resource, context) languages = resource.get_edit_languages(context) # Build widgets namespace fields_list = [] fields_dict = {} first_widget = None onsubmit = None for widget in self.get_widgets(resource, context): widget_name = widget.name datatype = fields.get(widget.name, None) field_ns = namespace.get(widget.name, { 'name': widget.name, 'value': None, 'error': None }) field_ns['title'] = getattr(widget, 'title', None) field_ns['id'] = widget.id field_ns['mandatory'] = getattr(datatype, 'mandatory', False) field_ns['tip'] = widget.tip field_ns['endline'] = getattr(widget, 'endline', False) # onsubmit widget_onsubmit = getattr(widget, 'onsubmit', None) if widget_onsubmit is not None and onsubmit is not None: raise ValueError, "2 widgets want to change onsubmit" onsubmit = widget_onsubmit # Get value if self.method == 'get': value = context.get_query_value(widget.name, datatype) if issubclass(datatype, Enumerate): value = datatype.get_namespace(value) else: value = field_ns['value'] if is_prototype(datatype, DateTime) and len(value) <= 10: value_time = namespace.get('%s_time' % widget.name, {'value': None}) value_time = value_time['value'] if value_time: value += 'T%s' % value_time # multilingual or monolingual field_ns['widgets'] = widgets_html = [] if getattr(datatype, 'multilingual', False): for language in languages: language_title = get_language_msg(language) lwidget = widget(name='%s:%s' % (widget_name, language), field_name=widget_name, datatype=datatype, value=value[language], language_name=language, language=language_title) widgets_html.append(lwidget) if first_widget is None and lwidget.focus: first_widget = lwidget.id # fix label if widgets_html: field_ns['name'] = widgets_html[0].name else: widget = widget(field_name=widget_name, datatype=datatype, value=value) widgets_html.append(widget) if first_widget is None and widget.focus: first_widget = widget.id # Ok stream = stl(template, field_ns) fields_list.append(stream) fields_dict[widget_name] = stream # Enctype enctype = 'multipart/form-data' if self.method == 'post' else None # Get the actions actions = self._get_action_namespace(resource, context) # Before and after before = self.get_before_namespace(resource, context) after = self.get_after_namespace(resource, context) # Build namespace return { 'form_id': self.form_id, 'form_css': self.form_css, 'before': before, 'actions': actions, 'method': self.method, 'enctype': enctype, 'onsubmit': onsubmit, 'title': self.get_title(context), 'description': self.description, 'first_widget': first_widget, 'fields_list': fields_list, 'fields': fields_dict, 'after': after }
def get_namespace(self, resource, context): root = context.root here = context.resource site_root = here.get_site_root() site_root_abspath = site_root.get_abspath() shop = site_root.get_resource('shop') categories_abspath = str(site_root_abspath.resolve2('categories')) show_nb_products = resource.get_property('show_nb_products') show_first_category = resource.get_property('show_first_category') show_second_level = resource.get_property('show_second_level') here_abspath = here.get_abspath() here_real_abspath = str(here_abspath) here_parent_abspath = here_abspath.resolve2('..') current_level = here_real_abspath.count('/') if here.metadata.format == 'category': here_abspath = str(here.get_abspath()) # Max level deploy = count '/' + 1 # here_abspath at level 1 does not contain '/' here_abspath_level = here_abspath.count('/') max_level_deploy = here_abspath_level + 1 else: if here.metadata.format == 'product': # Special case for the product, here_* values are compute # with here = parent category parent_category = here.parent parent_category_abspath = parent_category.get_abspath() here_abspath = str(parent_category_abspath) here_abspath_level = here_abspath.count('/') max_level_deploy = here_abspath_level + 1 here_parent_abspath = parent_category_abspath.resolve2('..') else: # Tweak here_abspath here_abspath = categories_abspath here_abspath_level = here_abspath.count('/') max_level_deploy = categories_abspath.count('/') + 1 here_abspath_p = Path(here_abspath) # Get search with all publics products all_products = root.search( AndQuery(PhraseQuery('format', shop.product_class.class_id), PhraseQuery('workflow_state', 'public'))) # Get search with all categories all_categories = root.search( AndQuery(PhraseQuery('parent_paths', categories_abspath), PhraseQuery('format', 'category'))) # Build a dict with brains by level cat_per_level = {} for index, cat in enumerate( all_categories.get_documents(sort_by='abspath')): # Skip first category --> /categories if index == 0 and show_first_category is False: continue level = cat.abspath.count('/') # Skip second level (if we are not on level /categories/') if (show_second_level is False and current_level > 2 and level == 3 and not here_real_abspath == cat.abspath and not here_parent_abspath == cat.abspath): continue # Skip bad level if level > max_level_deploy: continue diff_level = here_abspath_level - level path_to_resolve = ['..' for x in range(diff_level)] path_to_resolve = '/'.join(path_to_resolve) # Path uses to compute the prefix with the current category here_prefix = here_abspath_p.resolve2(path_to_resolve) # Compute the prefix prefix = here_prefix.get_prefix(cat.abspath) if prefix == here_prefix: # special case when prefix equals here_prefix pass elif len(prefix) != level - 1: # bad, not in the same arborescence continue # Get the product number in the category sub_results = all_products.search( PhraseQuery('parent_paths', cat.abspath)) cats = cat_per_level.setdefault(level, []) cats.append({'doc': cat, 'nb_products': len(sub_results)}) # Build the tree starting with the higher level tree_template = resource.get_resource(self.tree_template) levels = sorted(cat_per_level.keys(), reverse=True) tree = None for level in levels: items = [] for data in cat_per_level[level]: doc = data['doc'] if here_abspath.startswith(doc.abspath): sub_tree = tree css = 'in-path ' else: sub_tree = None css = '' css = 'active ' if here_abspath == doc.abspath else css # Href (get_link emulation) href = str(site_root_abspath.get_pathto(doc.abspath)) css += checkid(href) css = css.replace('.', '-dot-') if resource.get_property('use_small_title'): title = doc.m_breadcrumb_title or doc.m_title or doc.name else: title = doc.m_title or doc.name d = { 'title': title, 'href': '/%s' % href, 'sub_tree': sub_tree, 'nb_products': data['nb_products'], 'css': css } items.append(d) tree = stl(tree_template, { 'items': items, 'show_nb_products': show_nb_products, 'css': None }) return {'title': resource.get_title(), 'tree': tree}
def get_namespace(self, resource, context): namespace = {'lines': []} # Search search_template = resource.get_resource(self.search_template) search_namespace = self.get_search_namespace(resource, context) namespace['search'] = stl(search_template, search_namespace) # Is a research ? if context.uri.query.has_key('search') is False: return namespace # Get all declinations (for optimization purpose) all_products = context.root.search(format='product') # Do products = {} items = self.get_items(resource, context) for i, brain in enumerate(items): # It's a product or a declination ? if brain.format == 'product': brain_product = brain brain_declination = None else: brain_declination = brain parent_path = '/'.join( brain_declination.abspath.split('/')[:-1]) brain_product = all_products.search( abspath=parent_path).get_documents()[0] # Get corresponding product if products.has_key(brain_product.reference): kw = products[brain_product.reference] else: nb_products = len(products) kw = { 'id': nb_products + 1, 'reference': brain_product.reference, 'title': brain_product.title, 'href': '/' + '/'.join(brain_product.abspath.split('/')[2:]), # XXX Hack 'declinations': [], 'nb_declinations': 0, 'has_declination': False, 'stock_quantity': brain_product.stock_quantity } products[brain_product.reference] = kw # Get declination if brain_declination: nb_declinations = kw['nb_declinations'] d = { 'id': nb_declinations + 1, 'name': brain_declination.name, 'title': brain_declination.declination_title, 'stock_quantity': brain_declination.stock_quantity } kw['has_declination'] = True kw['declinations'].append(d) kw['nb_declinations'] = nb_declinations + 1 products[brain_product.reference] = kw # Build namespace products = products.values() products.sort(key=itemgetter('id')) namespace['lines'] = products namespace['references_number'] = len(namespace['lines']) return namespace
def get_grid_data(data, grid, start_date=None, templates=(None, None), with_new_url=True, add_icon=None): """ Build final namespace from data and grid to be used in gridlayout templates. """ template, template_fd = templates if template is None: template = default_template if template_fd is None: template_fd = default_template_fd # Build grid with Time objects grid = [Time.decode(x) for x in grid] # Build.. headers, events_with_time, events_without_time = [], [], [] for column in data: time_grid = [] full_day = [] events = column['events'] # Build the time grid for event in events: start, end = event['start'], event['end'] # Put the event in the right place if not event['TIME']: event['ns'] = stl(template_fd, {'event': event}) full_day.append(event) else: start, end = Time.decode(start), Time.decode(end) insert_item(time_grid, start, end, event, event['cal']) # Fix grid if needed if start not in grid: grid.append(start) if end not in grid: grid.append(end) # Finalize headers.append(column.get('header')) events_with_time.append(time_grid) events_without_time.append(full_day) # Sort the grid grid.sort() ###################################################################### # Build_timegrids_collection with given data: # (events_with_time, headers, grid, events_without_time, # start_date=None) today = date.today() if start_date: current_date = start_date ns_full_day = None if filter(lambda x: x, events_without_time): ns_full_day = [] ns_headers = [] cols = [] for i in range(len(events_with_time)): table, ncols = render_namespace(events_with_time[i], grid, with_new_url) if headers is not None: if current_date == today: h_class = 'cal_day_selected' else: h_class = 'header' ns_headers.append({ 'header': headers[i], 'width': ncols, 'class': h_class }) if ns_full_day is not None: ns_full_day.append({ 'events': events_without_time[i], 'width': ncols }) # Add date to newurl for each cell having this parameter # Build namespace for the content of cells containing event (new) if start_date is not None: str_date = Date.encode(current_date) for column in table: for cell in column['cells']: if cell['newurl'] is not None: url = '%s&date=%s' % (cell['newurl'], str_date) cell['newurl'] = url if cell['new']: cell['ns'] = stl(template, { 'cell': cell, 'add_icon': add_icon }) current_date = current_date + timedelta(1) cols.append(table) body = [] for i in range(len(grid) - 1): body.append({ 'start': Time.encode(grid[i]), 'end': Time.encode(grid[i + 1]), 'items': [col[i] for col in cols] }) namespace = { 'headers': ns_headers, 'body': body, 'full_day_events': ns_full_day } return namespace
def get_calendar(self, resource, context): template = context.get_template(self.calendar_template) namespace = self.get_calendar_namespace(resource, context) return stl(template, namespace)