def schema(self): return schema.Schema( "ShopOrderCostFilter", members=[ schema.String( "operator", required=True, default="eq", enumeration=self.operators, text_search=False, translate_value=lambda value, language=None, **kwargs: "" if not value else translations( "cocktail.html.UserFilterEntry operator " + value, language, **kwargs)), schema.Boolean("include_shipping", default=False), schema.Boolean("include_taxes", default=False), schema.Boolean("include_discounts", default=False), schema.Decimal("value", required=True) ])
def _create_asset(self, cls, id, **values): """Convenience method for creating content when installing an extension. """ asset = cls() asset.qname = qname = self.full_name.rsplit(".", 1)[0] + "." + id if values: for key, value in values.iteritems(): if value is extension_translations: for language in Configuration.instance.languages: value = translations(qname + "." + key, language) if value: asset.set(key, value, language) else: asset.set(key, value) asset.insert() return asset
def _get_publication_parameters(self, publishable): og = OpenGraphExtension.instance og_properties = og.get_properties(publishable) post_data = { "access_token": self.auth_token, "name": og_properties.get("og:title") or translations(publishable), "link": og_properties.get("og:url") } # Disregard any default image; only show an image if the published # content defines one if "og:image" not in og_properties: post_data["picture"] = "" if self.targeting: context = { "language": get_language(), "og_properties": og_properties, "publishable": publishable, "locales": facebook_locales, "include_locales": (lambda included: [facebook_locales[loc_name] for loc_name in included]), "exclude_locales": (lambda excluded: [ loc_id for loc_name, loc_id in facebook_locales.iteritems() if loc_name not in excluded ]) } targeting_code = self.targeting.replace("\r\n", "\n") exec targeting_code in context targeting = context.get("targeting") if targeting: post_data["feed_targeting"] = dumps(targeting) return post_data
def create_button(self, name): button = Element("a") button.add_class("button") button.add_class(name) button.icon = Element("img", src="/resources/images/%s.png" % name, alt=translations( "cocktail.html.Pager.%s_button" % name)) button.icon["title"] = button.icon["alt"] @when(button.icon.ready_stage) def set_button_style(e): if self.button_style == "characters": button.icon.tag = "span" button.icon["src"] = None button.icon["alt"] = None button.icon.append(self.button_characters[name]) button.append(button.icon) return button
def create_member_entry(self, member): value = member.schema.full_name + "." + member.name entry = Element() entry.check = CheckBox() entry.check["name"] = self.name entry.check.require_id() entry.check.value = value in self.value entry.check["value"] = value entry.append(entry.check) entry.label = Element("label") entry.label["for"] = entry.check["id"] entry.label.append(translations(member.schema.name + "." + member.name)) entry.append(entry.label) return entry
def form_schema(self): return schema.Schema( "FacebookAlbumsForm", members=[ schema.String("album_title", required=True), schema.String("album_description", edit_control="cocktail.html.TextArea"), schema.Collection( "subset", items=schema.Reference( type=File, relation_constraints=[ File.resource_type.equal("image") ], required=True, enumeration=lambda ctx: self.selection), min=1, default=schema.DynamicDefault(lambda: self.selection)), schema.Collection( "photo_languages", min=1, items=schema.String(required=True, enumeration=lambda ctx: Configuration. instance.languages, translate_value=lambda value, language= None, **kwargs: "" if not value else translations( value, language, **kwargs)), default=schema.DynamicDefault( lambda: Configuration.instance.languages)), schema.Boolean("generate_story", required=True, default=True), schema.Collection( "publication_targets", items=schema.Reference(type=FacebookPublicationTarget, required=True, enumeration=lambda ctx: self. allowed_publication_targets), min=1, default=schema.DynamicDefault( lambda: self.allowed_publication_targets)) ])
def test_item_selector(self): from woost.models import Publishable, Template template = list(Template.select())[0] browser.open( "/en/cms/content/?content_view=flat&type=woost.models.publishable.Publishable&search_expanded=true" ) admin_login() browser.fire_event("css=.new_filter_selector", "click") browser.fire_event("css=.new_filter-member-template", "click") assert not browser.is_element_present("css=.filters .value_field .new") assert not browser.is_element_present( "css=.filters .value_field .edit") assert not browser.is_element_present( "css=.filters .value_field .delete") assert not browser.is_element_present( "css=.filters .value_field .unlink") browser.click("css=.filters .value_field .select") browser.select_frame( "dom=selenium.browserbot.getCurrentWindow().frames[0]") browser.wait_for_element_present("css=.collection_display", 10000) assert not browser.is_element_present("css=.new_action") browser.click("css=.collection_display #%d" % template.id) browser.click("css=.select_action") browser.select_frame("relative=parent") browser.wait_for_element_present("css=.collection_display", 10000) assert translations(template, "en") \ in browser.jquery_html(".filters .value_field") assert browser.get_value("filter_value0") == str(template.id) browser.click("css=.filters .search_button") browser.wait_for_page_to_load(10000) rows_count = browser.jquery_count(".collection_display .item_row") assert rows_count == len(template.items)
def translate_file_type(self, language=None): trans = "" mime_type = self.mime_type if mime_type: trans = translations("mime " + mime_type, language=language) if not trans: res_type = self.resource_type if res_type: trans = self.__class__.resource_type.translate_value( res_type, language=language) if trans and res_type != "other": ext = self.file_extension if ext: trans += " " + ext.upper().lstrip(".") return trans
def _get_publishable_properties(self): properties = { "og:title": translations(self), "og:type": self.open_graph_type.code, "og:url": self.get_uri(host=".") } image = self.get_open_graph_image() if image: if isinstance(image, Publishable): image = image.get_image_uri("facebook", host=".") properties["og:image"] = image video = self.get_open_graph_video() if video: if isinstance(video, Publishable): video = video.get_uri(host=".") properties["og:video"] = video return properties
def get_payment(self, payment_id): order = shoporder.ShopOrder.get_instance(int(payment_id)) if order is None: raise PaymentNotFoundError(payment_id) payment = Payment() payment.id = order.id payment.amount = order.cost payment.shop_order = order payment.currency = Currency(payments_ext.payment_gateway.currency) for entry in order.entries: payment.add( PaymentItem(reference=str(entry.product.id), description=translations(entry.product), units=entry.quantity, price=entry.cost)) return payment
def create_empty_option(self): entry = Element("li") entry.control = Element("input", type=self._control_type, name=self.name, value="", checked=self.value is None) bind_member(self, entry.control) entry.append(entry.control) entry.label = Element("label") entry.label.add_class("entry_label") entry.label.add_class("empty_option") entry.label.append( translations("woost.views.ContentTypePicker.empty_label")) entry.append(entry.label) entry.label["for"] = entry.control.require_id() return entry
def create_icon(self): img = Element("img") img.add_class("icon") img["title"] = translations(self.item.__class__.__name__) get_image_uri = getattr(self.item, "get_image_uri", None) if get_image_uri: img["src"] = get_image_uri(self.image_factory) else: image_factory = self.image_factory or "default" if "." not in image_factory: from woost.models.rendering.formats import ( extensions_by_format, default_format ) extension = extensions_by_format[default_format] image_factory += "." + extension img["src"] = context["cms"].image_uri(self.item, image_factory) return img
def _synchronize(self): cmp = self.comparision get_param = cherrypy.request.params.get file_downloads = set() selection = self.sync_selection with changeset_context(get_current_user()): for obj in cmp["incomming"]: if obj.global_id in selection: obj.insert() if isinstance(obj, File): file_downloads.add(obj) for global_id, change in cmp["modified"].iteritems(): if global_id in selection: local = change["local"] remote = change["remote"] for member, lang in change["diff"]: value = schema.get(remote, member, language=lang) local.set(member, value, lang) if member in (File.file_hash, File.file_size): file_downloads.add(local) # Download files from the remote copy for file in file_downloads: self.synchronization.download_file(file) # Find importable content again self.comparision = self.synchronization.compare_content() notify_user( translations( "woost.controllers.InstallationSyncController.success"), "success")
def translate_member(self): from cocktail import schema path = list(self.context.path()) desc = [] for i, context in enumerate(path): if isinstance(context.member, schema.Schema) and ( (i == 0 and len(path) > 1) or (context.parent_context and isinstance( context.parent_context.member, schema.RelationMember))): continue label = decapitalize(translations(context.member)) if context.collection_index is not None: if isinstance(context.collection_index, int): label += " %d" % (context.collection_index + 1) elif (context.parent_context and isinstance( context.parent_context.member, schema.Mapping) and context.parent_context.member.keys): key_label = context.parent_context.member.keys.translate_value( context.collection_index) if label: if key_label: label = "%s: %s" % (key_label, label) else: label = key_label else: label = "%s: %s" % (context.collection_index, label) if self.language: label += " (%s)" % translate_locale(self.language) desc.append(label.strip()) return " » ".join(desc)
def create_translated_values(self, member): cell = Element("td") table = Element("table") table.add_class("translated_values") cell.append(table) for language in (self.translations or (get_language(), )): language_row = Element("tr") language_row.add_class(language) table.append(language_row) language_label = Element("th") language_label.append(translations(language)) language_row.append(language_label) with language_context(language): language_value_cell = self.create_value(member) language_row.append(language_value_cell) return cell
class DummyPaymentGateway(CMSPaymentGateway, PaymentGateway): """A simulated payment gateway, useful for testing purposes.""" instantiable = True payment_gateway_controller_class = ( "woost.extensions.payments.dummypaymentgatewaycontroller." "DummyPaymentGatewayController") members_order = [ "payment_status", "payment_successful_page", "payment_failed_page" ] payment_status = schema.String( required=True, enumeration=("accepted", "failed"), default="accepted", translate_value=lambda value, language=None, **kwargs: u"" if not value else translations( "woost.extensions.payments." "DummyPaymentGateway.payment_status " + value, language, **kwargs), text_search=False) payment_successful_page = schema.Reference(type=Document, related_end=schema.Reference()) payment_failed_page = schema.Reference(type=Document, related_end=schema.Reference()) def get_payment_form_data(self, payment_id, language=None): return (self.get_payment_url("simulate_transaction"), (("payment_id", payment_id), )) def process_notification(self, parameters): payment_id = parameters["payment_id"] payment = self.get_payment(payment_id) payment.status = self.payment_status return payment
def get_body(self, controller, publishable, url): return translations( "woost.extensions.googleanalytics.eventredirection.body", url=url)
def translate_value(self, value, language=None, **kwargs): if value is None: return "" else: return translations(value, language, **kwargs)
def _load(self): extension = self from woost.extensions.ecommerce import ( strings, ecommerceproduct, ecommerceorder, ecommercepurchase, ecommercebillingconcept, ecommerceordercompletedtrigger ) from woost.extensions.ecommerce.ecommerceorder import ECommerceOrder # Add the necessary members to define pricing policies ECommerceExtension.members_order = [ "payment_types", "pricing", "shipping_costs", "taxes", "order_steps" ] available_payment_types = ("payment_gateway", "transfer", "cash_on_delivery") ECommerceOrder.payment_type.enumeration = available_payment_types ECommerceExtension.add_member( schema.Collection( "payment_types", items = schema.String( enumeration = available_payment_types, translate_value = lambda value, language = None, **kwargs: translations( "ECommerceExtension.payment_types-%s" % value, language = language ), ), min = 1 ) ) ECommerceExtension.add_member( schema.Collection("pricing", items = schema.Reference( type = ecommercebillingconcept.ECommerceBillingConcept ), bidirectional = True, related_end = schema.Collection(), integral = True ) ) ECommerceExtension.add_member( schema.Collection("shipping_costs", items = schema.Reference( type = ecommercebillingconcept.ECommerceBillingConcept ), bidirectional = True, related_end = schema.Collection(), integral = True ) ) ECommerceExtension.add_member( schema.Collection("taxes", items = schema.Reference( type = ecommercebillingconcept.ECommerceBillingConcept ), bidirectional = True, related_end = schema.Collection(), integral = True ) ) ECommerceExtension.add_member( schema.Collection("order_steps", items = schema.Reference(type = Publishable), related_end = schema.Collection() ) ) # If the payments extension is enabled, setup the payment gateway for # the shop from woost.extensions.payments import PaymentsExtension payments_ext = PaymentsExtension.instance if payments_ext.enabled: extension._setup_payment_gateway() # Create the pages for the shop the first time the extension runs self.install()
def __translate_field(self, obj, key): for language in translations: with language_context(language): value = translations("%s.%s" % (obj.qname, key)) if value: obj.set(key, value)
def __translate__(self, language, **kwargs): return translations( "woost.models.changesets.Change description", action=self.action, target=self.target) or PersistentObject.__translate__( self, language, **kwargs)
class Location(Item): members_order = [ "location_name", "location_type", "code", "parent", "locations" ] location_name = schema.String( translated = True, descriptive = True, required = True, indexed = True, normalized_index = True, full_text_indexed = True ) location_type = schema.String( required = True, indexed = True, enumeration = [ "continent", "country", "autonomous_community", "province", "town" ], text_search = False, translate_value = lambda value, language = None, **kwargs: "" if not value else translations( "woost.extensions.locations.location_types." + value, language, **kwargs ), edit_control = "cocktail.html.DropdownSelector" ) code = schema.String( required = True, indexed = True, text_search = False ) parent = schema.Reference( type = "woost.extensions.locations.location.Location", bidirectional = True, cycles_allowed = False ) locations = schema.Collection( items = "woost.extensions.locations.location.Location", bidirectional = True, cascade_delete = True ) def ascend(self, include_self = False): """Iterate over the location's ancestors. :param include_self: Indicates if the location itself should be included in the iteration. :type include_self: bool :return: An iterable sequence of locations. :rtype: `Location` """ ascendant = self if include_self else self.parent while ascendant is not None: yield ascendant ascendant = ascendant.parent def descend(self, include_self = False): """Iterates over the location's descendants. :param include_self: If set to True, the location itself is yielded as the first element in the iteration. :type include_self: bool :return: An iterable sequence containing the location's flattened tree. :rtype: `Location` """ if include_self: yield self for location in self.locations: for descendant in location.descend(True): yield descendant def descends_from(self, ascendant): """Indicates if the location descends from a given location. :param ascendant: The hypothetical container of the location. :type ascendant: `Location` :return: True if the location is, or is contained within the given location or one of its descendants, False otherwise. :rtype: bool """ location = self while location is not None: if location is ascendant: return True else: location = location.parent return False def get_child_location(self, code): """Retrieves the contained location that matches the indicated code. :param code: The code of the location to retrieve. :type code: str :return: The specified location, or None if it wasn't found. :rtype: `Location` """ for child in self.locations: if child.code == code: return child for descendant in child.locations: match = descendant.get_child_location(code) if match: return match @classmethod def by_code(cls, *code): if not code or not code[0]: raise ValueError( "Location.by_code() requires one or more location codes" ) location = first(cls.select([Location.code.equal(code[0])])) for x in code[1:]: if location is None: return None location = location.get_child_location(x) return location def list_level(self, depth): if depth == 1: return self.locations else: descendants = [] for location in self.locations: descendants.extend(location.list_level(depth - 1)) return descendants
def finish_record(): if current_record: current_record["language_count"] = translations( "woost.extensions.staticpub.publicationcontroller." "PublicationController.language_count", count=len(current_record["languages"]))
translations.define("woost.extensions.mailer.SendEmailView continue", ca=u"Continuar", es=u"Continuar", en=u"Continue") translations.define("woost.extensions.mailer.SendEmailView send", ca=u"Enviar", es=u"Enviar", en=u"Send") translations.define( "woost.extensions.mailer.SendEmailView confirmation text", ca=lambda mailing: u"S'enviarà el document <strong>%s</strong> en <strong>%s</strong> " u"als següents usuaris:" % (translations(mailing.document), translations(mailing.language)), es=lambda mailing: u"Se enviará el documento <strong>%s</strong> en " u"</strong>%s</strong> a los siguientes usuarios:" % (translations(mailing.document), translations(mailing.language)), en=lambda mailing: u"You are about to send the document <strong>%s</strong> " u"in <strong>%s</strong> to the following users:" % (translations(mailing.document), translations(mailing.language))) translations.define("woost.extensions.mailer.SendEmailView total", ca=u"Total:", es=u"Total:", en=u"Total:") translations.define( "woost.extensions.mailer.SendEmailView accessibility warning",
def __translate__(self, language, **kwargs): return "%s (%d)" % ( translations(self.product, language), self.quantity )
def __translate__(self, language, **kwargs): return translations(self.__class__.full_name + "-instance", language, instance=self, **kwargs) or Item.__translate__( self, language, **kwargs)
required=True, default=True, indexed=True, member_group="sitemap", listed_by_default=False), append=True) URI.default_sitemap_indexable = False Publishable.add_member(schema.String( "sitemap_change_frequency", enumeration=[ "always", "hourly", "daily", "weekly", "monthly", "yearly", "never" ], translate_value=lambda value, language=None, **kwargs: "" if not value else translations( "woost.extensions.sitemap.change_frequency " + value, language, ** kwargs), member_group="sitemap", text_search=False, listed_by_default=False), append=True) Publishable.add_member(schema.Decimal("sitemap_priority", default=Decimal("0.5"), min=0, max=1, listed_by_default=False, member_group="sitemap"), append=True)
def _handle_user_action_error(self, action, selection, error): if isinstance(error, tuple(self._graceful_user_action_errors)): notify_user(translations(error), "error") self.go_back() else: raise error
def get_title(self, controller, publishable): return translations( "woost.extensions.googleanalytics.eventredirection.title")
def get_translation_inheritance_remark(self, source_locale): return translations( "cocktail.html.TranslationDisplay.translation_inheritance_remark", source_locale=source_locale)