Пример #1
0
    def update_links(self, source, target,
                     links_re = compile(r'(\.\. .*?: )(\S*)')):
        old_data = self.get_text()
        new_data = []

        not_uri = 0
        base = self.parent.abspath
        for segment in links_re.split(old_data):
            not_uri = (not_uri + 1) % 3
            if not not_uri:
                reference = get_reference(segment)
                # Skip external link
                if is_external(reference):
                    new_data.append(segment)
                    continue
                # Strip the view
                path = reference.path
                if path and path[-1] == ';download':
                    path = path[:-1]
                    view = '/;download'
                else:
                    view = ''
                # Resolve the path
                path = base.resolve(path)
                # Match ?
                if path == source:
                    segment = str(base.get_pathto(target)) + view
            new_data.append(segment)
        new_data = ''.join(new_data)
        self.get_value('data').load_state_from_string(new_data)
        get_context().database.change_resource(self)
Пример #2
0
    def update_links(self, source, target):
        super(FooterMenu, self).update_links(source, target)

        base = self.get_canonical_path()
        site_root = self.get_site_root()
        available_languages = site_root.get_property("website_languages")
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)
        handler = self.handler
        get_value = handler.get_record_value

        for record in handler.get_records_in_order():
            properties = []
            for language in available_languages:
                html_content = get_value(record, "html_content", language=language)
                if html_content is None:
                    continue
                events = _change_link(source, target, old_base, new_base, html_content)
                events = list(events)
                properties.append(Property(events, language=language))
            self.update_record(record.id, **{"html_content": properties})
        get_context().database.change_resource(self)
Пример #3
0
    def update_links(self, source, target):
        # FIXME BaseTheme does not take into account 'child'
        BaseTheme.update_links(self, source, target)
        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        # banner_path
        site_root = self.get_site_root()
        available_languages = site_root.get_property("website_languages")

        for language in available_languages:
            value = self.get_property("banner_path", language=language)
            if not value:
                continue
            path = old_base.resolve2(value)
            if path == source:
                # Hit the old name
                # Build the new reference with the right path
                self.set_property("banner_path", new_base.get_pathto(target), language=language)

        get_context().database.change_resource(self)
Пример #4
0
    def update_links(self, source, target):
        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        handler = self.handler
        get_value = handler.get_record_value

        for record in handler.get_records_in_order():
            path = get_value(record, 'name')
            if not path:
                continue
            ref = get_reference(path)
            if ref.scheme:
                continue
            # Strip the view
            path = ref.path
            name = path.get_name()
            if name and name[0] == ';':
                view = '/' + name
                path = path[:-1]
            else:
                view = ''
            path = str(old_base.resolve2(path))
            if path == source:
                # Hit the old name
                # Build the new reference with the right path
                new_ref = deepcopy(ref)
                new_ref.path = str(new_base.get_pathto(target)) + view
                handler.update_record(record.id, **{'name': str(new_ref)})

        get_context().server.change_resource(self)
Пример #5
0
    def update_links(self, source, target):
        super(TurningFooterTable, self).update_links(source, target)

        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        # languages
        site_root = self.get_site_root()
        available_languages = site_root.get_property('website_languages')

        # Append links contained in data
        handler = self.handler
        get_value = handler.get_record_value

        for record in handler.get_records_in_order():
            for language in available_languages:
                data = get_value(record, 'data', language=language)
                if data is None:
                    continue
                events = _change_link(source, target, old_base, new_base,
                                      data)
                events = list(events)
                p_events = Property(events, language=language)
                # TODO Update all language in one time
                self.update_record(record.id, **{'data': p_events})
        get_context().database.change_resource(self)
Пример #6
0
    def update_links(self, source, target):
        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        handler = self.handler
        get_value = handler.get_record_value

        for record in handler.get_records_in_order():
            path = get_value(record, 'name')
            if not path:
                continue
            ref = get_reference(path)
            if ref.scheme:
                continue
            # Strip the view
            path = ref.path
            name = path.get_name()
            if name and name[0] == ';':
                view = '/' + name
                path = path[:-1]
            else:
                view = ''
            path = str(old_base.resolve2(path))
            if path == source:
                # Hit the old name
                # Build the new reference with the right path
                new_ref = deepcopy(ref)
                new_ref.path = str(new_base.get_pathto(target)) + view
                handler.update_record(record.id, **{'name': str(new_ref)})

        get_context().server.change_resource(self)
Пример #7
0
    def update_links(self, source, target):
        WebPage.update_links(self, source, target)

        site_root = self.get_site_root()
        available_languages = site_root.get_property('website_languages')

        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        for lang in available_languages:
            path = self.get_property('thumbnail', language=lang)
            if not path:
                continue
            ref = get_reference(path)
            if ref.scheme:
                continue
            path, view = get_path_and_view(ref.path)
            path = str(old_base.resolve2(path))
            if path == source:
                # Hit the old name
                # Build the new reference with the right path
                new_ref = deepcopy(ref)
                new_ref.path = str(new_base.get_pathto(target)) + view
                self.set_property('thumbnail', str(new_ref), language=lang)

        get_context().database.change_resource(self)
Пример #8
0
 def get_options(cls):
     if get_context().resource is None:
         return []
     shop = get_shop(get_context().resource)
     taxes = shop.get_resource('taxes').handler
     return [
         {'name': str(x.id),
          'value': taxes.get_record_value(x, 'value')}
         for x in taxes.get_records_in_order()]
Пример #9
0
 def get_options(cls):
     if get_context().resource is None:
         return []
     shop = get_shop(get_context().resource)
     taxes = shop.get_resource('taxes').handler
     return [{
         'name': str(x.id),
         'value': taxes.get_record_value(x, 'value')
     } for x in taxes.get_records_in_order()]
Пример #10
0
    def get_options(cls):
        context = get_context()
        site_root = context.site_root
        tags_folder = site_root.get_resource("tags", soft=True)
        if tags_folder is None:
            return []
        context = get_context()
        brains = tags_folder.get_tag_brains(context, states=cls.states)
        options = [{"name": brain.name, "value": brain.title or brain.name} for brain in brains]

        return options
Пример #11
0
    def get_options(cls):
        context = get_context()
        site_root = context.site_root
        tags_folder = site_root.get_resource('tags', soft=True)
        if tags_folder is None:
            return []
        context = get_context()
        options = [ {'name': brain.name,
                     'value': brain.title or brain.name}
                    for brain in tags_folder.get_tag_brains(context) ]

        return options
Пример #12
0
    def update_links(self, source, target):
        base = self.get_canonical_path()
        resources_new2old = get_context().database.resources_new2old
        base = str(base)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        site_root = self.get_site_root()
        languages = site_root.get_property('website_languages')
        links = []
        for key, datatype in self.get_metadata_schema().items():
            multilingual = getattr(datatype, 'multilingual', False)
            langs = languages if multilingual is True else [None]
            if issubclass(datatype, XHTMLBody):
                for lang in langs:
                    events = self.get_property(key, language=lang)
                    if not events:
                        continue
                    events = _change_link(source, target, old_base, new_base,
                                          events)
                    events = list(events)
                    self.set_property(key, events, language=lang)
            elif issubclass(datatype, PathDataType):
                # Relative path
                for lang in langs:
                    path = self.get_property(key, language=lang)
                    if path is None:
                        continue
                    path = str(old_base.resolve2(path))
                    if path == source:
                        # Hit the old name
                        new_path = str(new_base.get_pathto(target))
                        self.set_property(key, new_path, language=lang)
            elif issubclass(datatype, AbsolutePathDataTypeEnumerate):
                # Absolute path
                for lang in langs:
                    path = self.get_property(key, language=lang)
                    if path is None:
                        continue
                    path = str(path)
                    path = resources_new2old.get(path, path)
                    if path == source:
                        # Hit the old name
                        self.set_property(key, str(target), language=lang)
        # Tagaware ?
        if isinstance(self, TagsAware):
            TagsAware.update_links(self, source, target)

        # Change resource
        get_context().database.change_resource(self)
Пример #13
0
 def init_resource(self, *args, **kw):
     # Proxy
     proxy = super(Form, self)
     proxy.init_resource(*args, **kw)
     # init
     context = get_context()
     self.set_value('data', 'ctime:{0}'.format(context.timestamp))
Пример #14
0
 def set_user(self, email=None, password=None):
     context = get_context()
     shop = get_shop(context.resource)
     # Calculate the user id
     user_id = self.get_next_user_id()
     # Add the user
     cls = shop.user_class
     user = cls.make_resource(cls, self, user_id)
     # Set the email and paswword
     if email is not None:
         user.set_property('email', email)
     if password is not None:
         user.set_password(password)
     # Set default group
     root = context.root
     query = [
         PhraseQuery('format', 'user-group'),
         PhraseQuery('name', 'default')
     ]
     search = root.search(AndQuery(*query))
     documents = search.get_documents()
     group = documents[0]
     group = root.get_resource(group.abspath)
     user.set_property('user_group', str(group.get_abspath()))
     user_is_enabled = group.get_property('user_is_enabled_when_register')
     user.set_property('is_enabled', user_is_enabled)
     # Return the user
     return user
Пример #15
0
 def path(self):
     context = get_context()
     user = context.user
     if user:
         # here we want to add a Private Message functionality
         return '/users/%s' % user.name
     return '/'
Пример #16
0
    def make_resource(self, name, cls, soft=False, **kw):
        # Automatic name
        if name is None:
            name = self.make_resource_name()

        # Make a resource somewhere else
        if '/' in name:
            path = dirname(name)
            name = basename(name)
            resource = self.get_resource(path)
            resource.make_resource(name, cls, soft=soft, **kw)
            return

        # Soft
        if soft is True:
            resource = self.get_resource(name, soft=True)
            if resource:
                return resource

        # Make the metadata
        metadata = Metadata(cls=cls)
        self.handler.set_handler('%s.metadata' % name, metadata)
        metadata.set_property('mtime', get_context().timestamp)
        # Initialize
        resource = self.get_resource(name)
        resource.init_resource(**kw)
        # Ok
        self.database.add_resource(resource)
        return resource
Пример #17
0
    def init_resource(self, **kw):
        """Return a Metadata object with sensible default values.
        """
        context = get_context()
        user = context.user
        now = context.fix_tzinfo(datetime.now())
        # UUID
        self.set_uuid()
        # Ctime
        if 'ctime' not in kw:
            self.set_value('ctime', now)
        # Mtime
        if 'mtime' not in kw:
            self.set_value('mtime', now)
        # Last author
        if 'last_author' not in kw and user:
            self.set_value('last_author', user.name)
        # Ownership
        owner = self.get_field('owner', soft=True)
        if owner and user:
            self.set_value('owner', str(user.abspath))

        # Keyword parameters
        for name, value in kw.items():
            field = self.get_field(name)
            if field is None:
                raise ValueError, 'undefined field "%s"' % name
            if type(value) is dict:
                for lang in value:
                    field._set_value(self, name, value[lang], lang)
            else:
                field._set_value(self, name, value)
Пример #18
0
 def get_model_schema(self):
     schema = {}
     context = get_context()
     ac = self.get_access_control()
     site_root = context.site_root
     is_admin = ac.is_admin(context.user, site_root)
     get_value = self.handler.get_record_value
     is_on_register_view = (hasattr(context, 'view') and issubclass(
         context.view.__class__, RegisterForm))
     for record in self.handler.get_records_in_order():
         name = get_value(record, 'name')
         title = get_value(record, 'title')
         show_on_register = get_value(record, 'show_on_register')
         show_on_register = get_value(record, 'show_on_register')
         if is_on_register_view is True and show_on_register is False:
             continue
         is_public = get_value(record, 'is_public')
         if not is_admin and is_public is False:
             continue
         datatype = get_real_datatype(self.handler, record)
         default = get_value(record, 'default')
         if default:
             datatype.default = datatype.decode(default)
         datatype.title = title
         schema[name] = datatype
     return schema
Пример #19
0
 def get_options(cls):
     context = get_context()
     root = context.root
     resources = [root.get_resource(brain.abspath)
                   for brain in root.search(format='tax').get_documents()]
     return [{'name': str(res.get_abspath()),
              'value': res.get_property('tax_value')} for res in resources]
Пример #20
0
def get_shop(resource):
    context = get_context()
    shop = getattr(context, '_shop', None)
    if shop is None:
        shop = resource.get_site_root().get_resource('shop')
        context._shop = shop
    return shop
Пример #21
0
 def get_namespace(self, datatype, value):
     # XXX Hack to get tax value (and keep it when submit form)
     context = get_context()
     submit = (context.method == 'POST')
     prefix = self.prefix
     if submit:
         tax_value = context.get_form_value('%stax' % prefix,
                                            type=TaxesEnumerate)
         has_reduction = context.get_form_value('%shas_reduction' % prefix,
                                                type=Boolean)
         reduce_pre_tax_price = context.get_form_value(
             '%sreduce-pre-tax-price' % prefix)
     else:
         tax_value = context.resource.get_property('%stax' % prefix)
         has_reduction = context.resource.get_property('%shas_reduction' %
                                                       prefix)
         reduce_pre_tax_price = context.resource.get_property(
             '%sreduce-pre-tax-price' % prefix)
     taxes = SelectWidget('%stax' % prefix,
                          css='tax-widget',
                          has_empty_option=False)
     # Devise
     shop = get_shop(context.resource)
     devise = shop.get_property('devise')
     symbol = Devises.get_symbol(devise)
     # Return namespace
     return {
         'widget_name': self.name,
         'pre-tax-price': value,
         'prefix': prefix,
         'devise': symbol,
         'reduce-pre-tax-price': reduce_pre_tax_price,
         'has_reduction': has_reduction,
         'taxes': taxes.to_html(TaxesEnumerate, tax_value)
     }
Пример #22
0
 def get_items(self, context):
     options = []
     root = get_context().root
     base_abspath = self.get_property('base_abspath')
     base_resource = root.get_resource(base_abspath)
     search = root.search(format='category', parent_paths=base_abspath)
     items_list = [base_resource]
     for brain in search.get_documents(sort_by='abspath'):
         items_list.append(root.get_resource(brain.abspath))
     for resource in items_list:
         abspath = str(resource.get_abspath())
         selected = context.resource.get_abspath() == abspath
         uri = get_reference(context.get_link(resource))
         uri.query = context.uri.query
         title = resource.get_title()
         if abspath == base_abspath:
             title = MSG(u'All')
         options.append({
             'name': abspath,
             'criterium': 'category',
             'query': PhraseQuery('parent_paths', abspath),
             'selected': selected,
             'uri': uri,
             'css': 'selected' if selected else None,
             'title': title
         })
     return options
Пример #23
0
 def get_options(cls):
     shop = get_shop(get_context().resource)
     enumerates_folder = shop.get_resource("enumerates")
     return [
         {"name": res.name, "value": res.get_property("title")}
         for res in enumerates_folder.search_resources(cls=EnumerateTable)
     ]
Пример #24
0
 def get_namespace(self, datatype, value):
     # XXX Hack to get tax value (and keep it when submit form)
     context = get_context()
     submit = (context.method == 'POST')
     prefix = self.prefix
     if submit:
         tax_value = context.get_form_value('%stax' % prefix, type=TaxesEnumerate)
         has_reduction = context.get_form_value('%shas_reduction' % prefix, type=Boolean)
         reduce_pre_tax_price = context.get_form_value('%sreduce-pre-tax-price' % prefix)
     else:
         tax_value = context.resource.get_property('%stax' % prefix)
         has_reduction = context.resource.get_property('%shas_reduction' % prefix)
         reduce_pre_tax_price = context.resource.get_property('%sreduce-pre-tax-price' % prefix)
     taxes = SelectWidget('%stax' % prefix, css='tax-widget', has_empty_option=False)
     # Devise
     shop = get_shop(context.resource)
     devise = shop.get_property('devise')
     symbol = Devises.get_symbol(devise)
     # Return namespace
     return {'widget_name': self.name,
             'pre-tax-price': value,
             'prefix': prefix,
             'devise': symbol,
             'reduce-pre-tax-price': reduce_pre_tax_price,
             'has_reduction': has_reduction,
             'taxes': taxes.to_html(TaxesEnumerate, tax_value)}
Пример #25
0
 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)}
Пример #26
0
 def get_model_namespace(self, resource):
     context = get_context()
     specific_model_is = SpecificModelIs()
     specific_model_is.model_name = self.name
     namespace = {
         'specific_model_is': specific_model_is,
         'specific_dict': {},
         'specific_list': [],
         'specific_list_complete': []
     }
     dynamic_schema = self.get_model_schema()
     schema_handler = self.get_resource('schema').handler
     get_value = schema_handler.get_record_value
     for record in schema_handler.get_records_in_order():
         name = get_value(record, 'name')
         value = real_value = resource.get_dynamic_property(
             name, dynamic_schema)
         # Real value is used to keep the enumerate value
         # corresponding to the options[{'name': xxx}]
         datatype = dynamic_schema[name]
         if value and hasattr(datatype, 'render'):
             value = datatype.render(value, context)
         # Build kw
         kw = {'value': value, 'real_value': real_value}
         for key in ['name', 'title', 'multiple', 'visible']:
             kw[key] = get_value(record, key)
         # Add to namespace
         namespace['specific_dict'][name] = kw
         namespace['specific_list_complete'].append(kw)
         if kw['visible'] and kw['value']:
             namespace['specific_list'].append(kw)
     return namespace
Пример #27
0
def format_price(price):
    context = get_context()
    shop = get_shop(context.resource)
    devise = shop.get_property('devise')
    symbol = Devises.get_symbol(devise)
    price = get_arrondi(price)
    return u'%s %s' % (price, symbol)
Пример #28
0
def format_price(price, symbol=None):
    if symbol is None:
        context = get_context()
        shop = get_shop(context.resource)
        devise = shop.get_property('devise')
        symbol = Devises.symbols[devise]
    return u'%s %s' % (price, symbol)
Пример #29
0
    def get_options(self):
        context = get_context()
        resource = context.resource
        view = context.view
        # 1. Build the query of all objects to search
        query = get_base_path_query(resource.abspath)
        if view.search_content_only(resource, context) is True:
            content_query = PhraseQuery('is_content', True)
            query = AndQuery(query, content_query)

        # 2. Compute children_formats
        children_formats = set()
        for child in context.search(query).get_documents():
            children_formats.add(child.format)

        # 3. Do not show two options with the same title
        formats = {}
        for type in children_formats:
            cls = context.database.get_resource_class(type)
            title = cls.class_title.gettext()
            formats.setdefault(title, []).append(type)

        # 4. Build the namespace
        types = []
        for title, type in formats.items():
            type = ','.join(type)
            types.append({'name': type, 'value': title})
        types.sort(key=lambda x: x['value'].lower())

        return types
Пример #30
0
 def onenter_open(self):
     context = get_context()
     shop = get_shop(self)
     root = context.root
     # Remove product from stock
     order_products = self.get_resource('products')
     get_value = order_products.handler.get_record_value
     for record in order_products.handler.get_records():
         name = get_value(record, 'name')
         product_resource = context.root.get_resource(name, soft=True)
         if product_resource is None:
             continue
         quantity = get_value(record, 'quantity')
         id_declination = get_value(record, 'declination')
         product_resource.remove_from_stock(quantity, id_declination)
     # E-Mail confirmation / notification -> Order creation
     customer_email = self.get_customer_email(context)
     # Build email informations
     kw = {'order_name': self.name}
     # Send confirmation to client
     kw['order_uri'] = self.get_frontoffice_uri()
     subject = mail_confirmation_title.gettext()
     body = mail_confirmation_body.gettext(**kw)
     root.send_email(customer_email, subject, text=body)
     # Send confirmation to the shop
     subject = mail_notification_title.gettext()
     kw['order_uri'] = self.get_backoffice_uri()
     body = mail_notification_body.gettext(**kw)
     for to_addr in shop.get_property('order_notification_mails'):
         root.send_email(to_addr, subject, text=body)
Пример #31
0
 def get_items(self, context):
     options = []
     root = get_context().root
     base_abspath = self.get_property("base_abspath")
     base_resource = root.get_resource(base_abspath)
     search = root.search(format="category", parent_paths=base_abspath)
     items_list = [base_resource]
     for brain in search.get_documents(sort_by="abspath"):
         items_list.append(root.get_resource(brain.abspath))
     for resource in items_list:
         abspath = str(resource.get_abspath())
         selected = context.resource.get_abspath() == abspath
         uri = get_reference(context.get_link(resource))
         uri.query = context.uri.query
         title = resource.get_title()
         if abspath == base_abspath:
             title = MSG(u"All")
         options.append(
             {
                 "name": abspath,
                 "criterium": "category",
                 "query": PhraseQuery("parent_paths", abspath),
                 "selected": selected,
                 "uri": uri,
                 "css": "selected" if selected else None,
                 "title": title,
             }
         )
     return options
Пример #32
0
 def is_valid(cls, value):
     context = get_context()
     if getattr(context, 'recaptcha_return_code', None) == 'true':
         return True
     # Get remote ip
     remote_ip = context.get_remote_ip() or '127.0.0.1'
     # Get Captcha fields
     recaptcha_challenge_field = context.get_form_value(
         'recaptcha_challenge_field', type=String)
     recaptcha_response_field = context.get_form_value(
         'recaptcha_response_field', type=String)
     # Test if captcha value is valid
     params = urllib.urlencode ({
             'privatekey': cls.private_key,
             'remoteip' :  remote_ip,
             'challenge':  recaptcha_challenge_field,
             'response' :  recaptcha_response_field,
             })
     request = urllib2.Request (
         url = "http://api-verify.recaptcha.net/verify",
         data = params,
         headers = {
             "Content-type": "application/x-www-form-urlencoded",
             "User-agent": "reCAPTCHA Python"
             }
         )
     httpresp = urllib2.urlopen (request)
     return_values = httpresp.read ().splitlines ();
     httpresp.close();
     context.recaptcha_return_code = return_code = return_values[0]
     return return_code == 'true'
Пример #33
0
 def class_views(self):
     context = get_context()
     # Back-Office
     hostname = context.uri.authority
     if hostname[:6] == 'admin.':
         return ['edit'] + self.default_class_views
     return ['view', 'edit'] + self.default_class_views
Пример #34
0
 def get_views(self):
     context = get_context()
     for name in self.class_views:
         view_name = name.split('?')[0]
         view = self.get_view(view_name)
         if context.is_access_allowed(self, view):
             yield name, view
Пример #35
0
    def update_20101015(self):
        """Fix TagsAware pub_datetime
        Add tzinfo"""
        from pytz import timezone
        from itools.core import fixed_offset

        # Current server timezone
        paris = timezone('Europe/Paris')

        utc = fixed_offset(0)
        database = get_context().database
        for resource in self.traverse_resources():
            if isinstance(resource, TagsAware):
                pub_datetime = resource.get_property('pub_datetime')
                if pub_datetime is None:
                    continue
                if pub_datetime.tzinfo:
                    return
                # localize date
                local_datetime = paris.localize(pub_datetime)
                utc_datetime = local_datetime - local_datetime.utcoffset()
                utc_datetime = utc_datetime.replace(tzinfo=utc)
                # Call metadata.set_property directly to avoid
                # comparison error 'TypeError'
                # -> can't compare offset-naive and offset-aware datetimes
                database.change_resource(resource)
                resource.metadata.set_property('pub_datetime', utc_datetime)
Пример #36
0
 def class_views(self):
     context = get_context()
     # Back-Office
     hostname = context.uri.authority
     if hostname[:6] == 'admin.' :
         return ['search']
     return ['addresses_book']
Пример #37
0
 def get_price_prefix(self):
     shop = get_shop(self)
     context = get_context()
     group_name = get_group_name(shop, context)
     if get_uri_name(group_name) == 'pro':
         return 'pro-'
     return ''
Пример #38
0
 def items(self):
     context = get_context()
     resource = context.resource
     items = []
     if resource.class_id in ('contact', 'mission'):
         todo = []
         if resource.class_id == 'contact':
             p_company = resource.get_property('crm_p_company')
             if p_company:
                 todo.append(p_company)
         elif resource.class_id == 'mission':
             contacts = resource.get_resource('../../contacts')
             for m_contact in resource.get_property('crm_m_contact'):
                 contact = contacts.get_resource(m_contact)
                 p_company = contact.get_property('crm_p_company')
                 if p_company not in todo:
                     todo.append(p_company)
         companies = resource.get_resource('../../companies')
         for p_company in todo:
             company = companies.get_resource(p_company)
             items.append(item(
                 title=company.get_property('title'),
                 icon=Icon('crm16-company'),
                 href=context.get_link(company),
                 selected=True))
     items.append(item(
         title=MSG(u"New Company"),
         icon=Icon('crm16-company-add'),
         href=context.get_link(companies),
         selected=False))
     return items
Пример #39
0
    def init_resource(self, **kw):
        """Return a Metadata object with sensible default values.
        """
        context = get_context()
        user = context.user
        now = context.fix_tzinfo(datetime.now())
        # UUID
        self.set_uuid()
        # Ctime
        if 'ctime' not in kw:
            self.set_value('ctime', now)
        # Mtime
        if 'mtime' not in kw:
            self.set_value('mtime', now)
        # Last author
        if 'last_author' not in kw and user:
            self.set_value('last_author', user.name)
        # Ownership
        owner = self.get_field('owner', soft=True)
        if owner and user:
            self.set_value('owner', str(user.abspath))

        # Keyword parameters
        for name, value in kw.items():
            field = self.get_field(name)
            if field is None:
                raise ValueError, 'undefined field "%s"' % name
            if type(value) is dict:
                for lang in value:
                    field._set_value(self, name, value[lang], lang)
            else:
                field._set_value(self, name, value)
Пример #40
0
 def __init__(self, cls, database, user=None, username=None, email=None, commit_at_exit=True):
     # Check if context is not already locked
     if get_context() != None:
         raise ValueError('Cannot acquire context. Already locked.')
     # Acquire lock on database
     DBSEM.acquire()
     from server import get_server
     self.context = cls()
     self.context.database = database
     self.context.server = get_server()
     self.commit_at_exit = commit_at_exit
     # Set context
     set_context(self.context)
     # Get user by user
     if email:
         query = AndQuery(
             PhraseQuery('format', 'user'),
             PhraseQuery('email', email),
         )
         search = database.search(query)
         if search:
             user = search.get_resources(size=1).next()
     # Get user by username
     if username:
         user = self.context.root.get_user(username)
     # Log user
     if user:
         self.context.login(user)
Пример #41
0
    def get_options(self):
        context = get_context()
        resource = context.resource
        view = context.view
        # 1. Build the query of all objects to search
        query = get_base_path_query(resource.abspath)
        if view.search_content_only(resource, context) is True:
            content_query = PhraseQuery('is_content', True)
            query = AndQuery(query, content_query)

        # 2. Compute children_formats
        children_formats = set()
        for child in context.search(query).get_documents():
            children_formats.add(child.format)

        # 3. Do not show two options with the same title
        formats = {}
        for type in children_formats:
            cls = context.database.get_resource_class(type)
            title = cls.class_title.gettext()
            formats.setdefault(title, []).append(type)

        # 4. Build the namespace
        types = []
        for title, type in formats.items():
            type = ','.join(type)
            types.append({'name': type, 'value': title})
        types.sort(key=lambda x: x['value'].lower())

        return types
Пример #42
0
 def get_options(cls):
     shop = get_shop(get_context().resource)
     enumerates_folder = shop.get_resource('enumerates')
     return [{
         'name': res.name,
         'value': res.get_property('title')
     } for res in enumerates_folder.search_resources(cls=EnumerateTable)]
Пример #43
0
 def preview(self):
     context = get_context()
     handler = context.resource.get_value(self.field_name,
                                          language=self.language_name)
     if handler is None:
         return None
     # Params
     params = 'name={field_name}'
     if self.language_name:
         params += '&language={language_name}'
     # Download link
     kw = {
         'field_name': self.field_name,
         'width': self.width,
         'height': self.height,
         'language_name': self.language_name
     }
     link = ';get_file?' + params.format(**kw)
     # Image link
     image = None
     if isinstance(handler, Image):
         image = ';get_image?width={width}&height={height}&' + params
         image = image.format(**kw)
     # Ok
     return {'link': link, 'image': image}
Пример #44
0
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)
Пример #45
0
 def onenter_open(self):
     context = get_context()
     shop = get_shop(self)
     root = context.root
     # Remove product from stock
     order_products = self.get_resource('products')
     get_value = order_products.handler.get_record_value
     for record in order_products.handler.get_records():
         name = get_value(record, 'name')
         product_resource = context.root.get_resource(name, soft=True)
         if product_resource is None:
             continue
         quantity = get_value(record, 'quantity')
         id_declination = get_value(record, 'declination')
         product_resource.remove_from_stock(quantity, id_declination)
     # E-Mail confirmation / notification -> Order creation
     customer_email = self.get_customer_email(context)
     # Build email informations
     kw = {'order_name': self.name}
     # Send confirmation to client
     kw['order_uri'] = self.get_frontoffice_uri()
     subject = mail_confirmation_title.gettext()
     body = mail_confirmation_body.gettext(**kw)
     root.send_email(customer_email, subject, text=body)
     # Send confirmation to the shop
     subject = mail_notification_title.gettext()
     kw['order_uri'] = self.get_backoffice_uri()
     body = mail_notification_body.gettext(**kw)
     for to_addr in shop.get_property('order_notification_mails'):
         root.send_email(to_addr, subject, text=body)
Пример #46
0
 def get_options(cls):
     options = []
     root = get_context().root
     search = root.search(format="category")
     for brain in search.get_documents(sort_by="abspath"):
         options.append({"name": brain.abspath, "value": brain.abspath})
     return options
Пример #47
0
    def update_relative_links(self, source):
        WebPage.update_relative_links(self, source)

        site_root = self.get_site_root()
        available_languages = site_root.get_property('website_languages')

        target = self.get_canonical_path()
        resources_old2new = get_context().database.resources_old2new

        for lang in available_languages:
            path = self.get_property('thumbnail', language=lang)
            if not path:
                continue
            ref = get_reference(path)
            if ref.scheme:
                continue
            path, view = get_path_and_view(ref.path)
            # Calcul the old absolute path
            old_abs_path = source.resolve2(path)
            # Check if the target path has not been moved
            new_abs_path = resources_old2new.get(old_abs_path, old_abs_path)
            # Build the new reference with the right path
            # Absolute path allow to call get_pathto with the target
            new_ref = deepcopy(ref)
            new_ref.path = str(target.get_pathto(new_abs_path)) + view
            self.set_property('thumbnail', str(new_ref), language=lang)
Пример #48
0
 def _make_resource(cls, folder, name, *args, **kw):
     ShopFolder._make_resource(cls, folder, name, *args, **kw)
     # Image
     body = lfs.open(get_abspath(cls.img)).read()
     img = Image._make_resource(Image, folder,
                                '%s/logo.png' % name, body=body,
                                **{'state': 'public'})
     # Load zones
     shop = get_context().resource.parent
     zones = []
     handler = shop.get_resource('countries-zones').handler
     for record in handler.get_records():
         zones.append(handler.get_record_value(record, 'title'))
     # Create history
     cls.shipping_history_cls._make_resource(cls.shipping_history_cls,
                           folder, '%s/history' % name)
     # Import CSV with prices
     ShippingPrices._make_resource(ShippingPrices, folder,
                                   '%s/prices' % name)
     if getattr(cls, 'csv', None):
         table = ShippingPricesTable()
         csv = ro_database.get_handler(get_abspath(cls.csv), ShippingPricesCSV)
         for row in csv.get_rows():
             table.add_record(
               {'zone': str(zones.index(row.get_value('zone'))),
                'max-weight': row.get_value('max-weight'),
                'price': row.get_value('price')})
         folder.set_handler('%s/prices' % name, table)
Пример #49
0
    def update_relative_links(self, source):
        site_root = self.get_site_root()
        target = self.get_canonical_path()
        resources_old2new = get_context().database.resources_old2new

        handler = self.handler
        get_value = handler.get_record_value
        for record in handler.get_records():
            path = get_value(record, 'name')
            if not path:
                continue
            ref = get_reference(str(path))
            if ref.scheme:
                continue
            # Strip the view
            path = ref.path
            name = path.get_name()
            if name and name[0] == ';':
                view = '/' + name
                path = path[:-1]
            else:
                view = ''
            path = str(path)
            # Calcul the old absolute path
            old_abs_path = source.resolve2(path)
            # Check if the target path has not been moved
            new_abs_path = resources_old2new.get(old_abs_path, old_abs_path)
            # Build the new reference with the right path
            # Absolute path allow to call get_pathto with the target
            new_ref = deepcopy(ref)
            new_ref.path = str(target.get_pathto(new_abs_path)) + view
            # Update the record
            handler.update_record(record.id, **{'name': str(new_ref)})
Пример #50
0
    def get_namespace(self, datatype, value):
        from declination import Declination
        context = get_context()
        here = context.resource
        # BooleanRadio for handled
        stock_handled = here.get_property('stock-handled')
        handled_widget = BooleanRadio('stock-handled', css='stock-handled')

        # SelectRadio for option
        stock_option_value = here.get_property('stock-option')
        options_widget = SelectRadio('stock-option',
                                     css='stock-option',
                                     has_empty_option=False)
        stock_quantity = here.get_property('stock-quantity')
        # Has declination
        has_declination = len(list(here.search_resources(cls=Declination))) > 0
        return {
            'stock-handled':
            handled_widget.to_html(Boolean, stock_handled),
            'has_declination':
            has_declination,
            'stock-quantity':
            stock_quantity,
            'stock-option':
            options_widget.to_html(StockOptions, stock_option_value)
        }
Пример #51
0
    def folderX(self, x):
        """ folders -> folder courant
            folder  -> folder complet
            value   -> folder fils sélectionné
        """
        if self.folder is None:
            return None
        name = 'folder%s' % x
        folder_path = self.folder.abspath
        value = quote(str(folder_path[:x + 1]))

        if len(folder_path) < x:
            return None
        base_folder = folder_path[:x]
        base_folder = get_context().database.get_resource(base_folder)

        # On affiche la liste si elle contient des items
        if list(base_folder.search_resources(format='folder')):
            return FolderWidget(
                name,
                datatype=FoldersEnumerate(base_folder=base_folder),
                value=value,
                lower=x + 1,
                level=x).render()
        return None
Пример #52
0
 def get_views(self):
     context = get_context()
     for name in self.class_views:
         view_name = name.split('?')[0]
         view = self.get_view(view_name)
         if context.is_access_allowed(self, view):
             yield name, view
Пример #53
0
 def get_value(cls, name, default=None):
     if name is None:
         return
     context = get_context()
     path = '%s/%s' % (cls.path, name)
     resource = context.site_root.get_resource(path)
     return resource.get_title()
Пример #54
0
    def make_resource(self, name, cls, soft=False, **kw):
        # Automatic name
        if name is None:
            name = self.make_resource_name()

        # Make a resource somewhere else
        if '/' in name:
            path = dirname(name)
            name = basename(name)
            resource = self.get_resource(path)
            resource.make_resource(name, cls, soft=soft, **kw)
            return

        # Soft
        if soft is True:
            resource = self.get_resource(name, soft=True)
            if resource:
                return resource

        # Make the metadata
        metadata = Metadata(cls=cls)
        self.handler.set_handler('%s.metadata' % name, metadata)
        metadata.set_property('mtime', get_context().timestamp)
        # Initialize
        resource = self.get_resource(name)
        self.database.add_resource(resource)
        resource.init_resource(**kw)
        # Ok
        return resource
Пример #55
0
 def get_options(cls):
     context = get_context()
     root = context.root
     resources = [root.get_resource(brain.abspath)
                   for brain in root.search(format='user').get_documents()]
     return [{'name': res.name, 'value': res.get_title()}
                for res in resources]
Пример #56
0
 def class_views(self):
     context = get_context()
     # Back-Office
     hostname = context.uri.authority
     if hostname[:6] == 'admin.':
         return ['search']
     return ['addresses_book']
Пример #57
0
    def update_links(self, source, target):
        super(CSS, self).update_links(source, target)
        resources_new2old = get_context().database.resources_new2old
        base = str(self.abspath)
        old_base = resources_new2old.get(base, base)
        old_base = Path(old_base)
        new_base = Path(base)

        def my_func(matchobj):
            uri = matchobj.group(1)
            reference = css_get_reference(uri)

            # Skip empty links, external links and links to '/ui/'
            if reference.scheme or reference.authority:
                return matchobj.group(0)
            path = reference.path
            if not path or path[0] == 'ui':
                return matchobj.group(0)

            # Strip the view
            name = path.get_name()
            if name and name[0] == ';':
                view = '/' + name
                path = path[:-1]
            else:
                view = ''

            # Resolve the path
            # Absolute path are relative to site root
            if not path.is_absolute():
                path = old_base.resolve2(path)

            # Match ?
            if path == source:
                path = str(new_base.get_pathto(target)) + view
                new_path = Reference('', '', path, reference.query.copy(),
                                     reference.fragment)
                return "url('%s')" % new_path

            return matchobj.group(0)

        data = self.to_text().encode('utf-8')
        new_data = css_uri_expr.sub(my_func, data)
        self.handler.load_state_from_string(new_data)

        get_context().database.change_resource(self)
Пример #58
0
 def _set_addresses(self, delivery_address, bill_address):
     if delivery_address==None:
         delivery_address = ''
     if bill_address==None:
         bill_address = ''
     value = Password.encode('%s|%s' % (delivery_address, bill_address))
     context = get_context()
     context.set_cookie('addresses', value)