示例#1
0
文件: base.py 项目: hforge/crm
    def get_links(self):
        links =  RoleAware.get_links(self) | TagsAware.get_links(self)
        base = self.get_canonical_path()

        # metadata
        schema = self.class_schema
        for key, datatype in schema.iteritems():
            if issubclass(datatype, PathDataType) is False:
                continue
            value = self.get_property(key)
            if not value:
                continue
            ref = get_reference(value)
            if ref.scheme:
                continue
            path, view = get_path_and_view(ref.path)
            links.add(str(base.resolve2(path)))

        # comments
        comments = self.metadata.get_property('comment') or []
        for comment in comments:
            # XXX hardcoded, not typed
            for key in ('attachment',):
                value = comment.get_parameter(key)
                if not value:
                    continue
                ref = get_reference(value)
                if ref.scheme:
                    continue
                path, view = get_path_and_view(ref.path)
                links.add(str(base.resolve2(path)))

        return links
示例#2
0
文件: shop_views.py 项目: hforge/shop
    def action(self, resource, context, form):
        email = form['username'].strip()
        password = form['password']

        # Check the user exists
        root = context.root
        user = root.get_user_from_login(email)
        if user is None:
            message = ERROR(u'The user "{username}" does not exist.',
                            username=email)
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check the password is right
        if not user.authenticate(password, clear=True):
            message = ERROR(u'The password is wrong.')
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check user is enabled
        ac = resource.get_access_control()
        if not user.get_property('is_enabled') and \
            not ac.is_admin(user, resource):
            message = ERROR(u"""Your account isn't validated,
                please contact the webmaster""")
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check user has confirm is registration
        if user.get_property('user_must_confirm'):
            message = ERROR(u"""Your account has not been confirmed.""")
            goto = '/users/%s/;confirm_registration' % user.name
            return context.come_back(message, goto)

        # We log authentification
        if resource != context.root:
            shop = get_shop(resource)
            if shop.get_property('log_authentification'):
                logs = shop.get_resource('customers/authentification_logs')
                logs.log_authentification(user.name)
                user.set_property('last_time', datetime.now())

        # Set cookie
        user.set_auth_cookie(context, password)

        # Set context
        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!"), goto)
示例#3
0
    def action(self, resource, context, form):
        email = form['username'].strip()
        password = form['password']

        # Check the user exists
        root = context.root
        user = root.get_user_from_login(email)
        if user is None:
            message = ERROR(u'The user "{username}" does not exist.',
                            username=email)
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check the password is right
        if not user.authenticate(password, clear=True):
            message = ERROR(u'The password is wrong.')
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check user is enabled
        ac = resource.get_access_control()
        if not user.get_property('is_enabled') and \
            not ac.is_admin(user, resource):
            message = ERROR(u"""Your account isn't validated,
                please contact the webmaster""")
            goto = context.get_referrer()
            return context.come_back(message, goto)

        # Check user has confirm is registration
        if user.get_property('user_must_confirm'):
            message = ERROR(u"""Your account has not been confirmed.""")
            goto = '/users/%s/;confirm_registration' % user.name
            return context.come_back(message, goto)

        # We log authentification
        if resource != context.root:
            shop = get_shop(resource)
            if shop.get_property('log_authentification'):
                logs = shop.get_resource('customers/authentification_logs')
                logs.log_authentification(user.name)
                user.set_property('last_time', datetime.now())

        # Set cookie
        user.set_auth_cookie(context, password)

        # Set context
        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!"), goto)
示例#4
0
文件: page_views.py 项目: hforge/wiki
def resolve_references(doctree, resource, context,
        reference_resolver=default_reference_resolver, **kw):
    """Translate resource path to accessible path in the output document.
    """
    for node in doctree.traverse(condition=nodes.reference):
        wiki_name = node.get('wiki_name')
        if wiki_name is False:
            # Broken link
            continue
        elif wiki_name:
            # Wiki link
            reference = get_reference(wiki_name)
            node['refuri'] = reference_resolver(resource, reference, context,
                    **kw)
        elif wiki_name is None:
            # Regular link: point back to the site
            refuri = node.get('refuri')
            if refuri is None:
                continue
            reference = get_reference(refuri.encode('utf_8'))
            if is_external(reference):
                # Keep the unicode version
                continue
            node['refuri'] = reference_resolver(resource, reference, context,
                    **kw)
示例#5
0
    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)
示例#6
0
文件: base.py 项目: hforge/crm
    def update_relative_links(self, source):
        Folder.update_relative_links(self, source)
        TagsAware.update_relative_links(self, source)

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

        # metadata
        schema = self.class_schema
        for key, datatype in schema.iteritems():
            if issubclass(datatype, PathDataType) is False:
                continue
            value = self.get_property(key)
            if not value:
                continue
            ref = get_reference(value)
            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 path with the right path
            # Absolute path allow to call get_pathto with the target
            new_path = str(target.get_pathto(new_abs_path)) + view
            # Update the property
            self.set_property(key, Path(new_path))

        # comments
        comments = self.metadata.get_property('comment') or []
        for comment in comments:
            # XXX hardcoded, not typed
            for key in ('attachment',):
                value = comment.get_parameter(key)
                if not value:
                    continue
                ref = get_reference(value)
                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 path with the right path
                # Absolute path allow to call get_pathto with the target
                new_path = str(target.get_pathto(new_abs_path)) + view
                # Update the record
                comment.set_parameter(key, new_path)

        self.set_property('comment', comments)
示例#7
0
文件: base.py 项目: hforge/crm
    def update_links(self, source, target):
        Folder.update_links(self, source, target)
        TagsAware.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)

        # metadata
        schema = self.class_schema
        for key, datatype in schema.iteritems():
            if issubclass(datatype, PathDataType) is False:
                continue
            value = self.get_property(key)
            if not value:
                continue
            ref = get_reference(value)
            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 path with the right path
                new_path = str(new_base.get_pathto(target)) + view
                self.set_property(key, Path(new_path))

        # comments
        comments = self.metadata.get_property('comment') or []
        for comment in comments:
            # XXX hardcoded, not typed
            for key in ('attachment',):
                value = comment.get_parameter(key)
                if not value:
                    continue
                ref = get_reference(value)
                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 path with the right path
                    new_path = str(new_base.get_pathto(target)) + view
                    comment.set_parameter(key, new_path)

        self.set_property('comment', comments)
示例#8
0
文件: images.py 项目: hforge/shop
    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)})
示例#9
0
 def action(self, resource, context, form):
     root = context.root
     to_addr = resource.get_property('to_addr')
     subject = MSG(u'Message from form: "%s"' %
                   resource.get_title()).gettext()
     text = []
     handler = resource.handler
     get_value = handler.get_record_value
     from_addr = to_addr
     for record in handler.get_records_in_order():
         name = get_value(record, 'name')
         datatype = get_value(record, 'datatype')
         value = form[name]
         # XXX Render on datatype ?
         if datatype == 'product':
             shop = get_shop(resource)
             site_root = resource.get_site_root()
             product = context.root.get_resource(value)
             base_uri = shop.get_property('shop_uri')
             end_uri = site_root.get_pathto(product)
             value = get_reference(base_uri).resolve(end_uri)
         elif datatype == 'email':
             # XXX Set from_addr
             from_addr = value
         title = get_value(record, 'title')
         text.append('*%s* \n\n %s' % (title, value))
     text = '\n\n\n'.join(text)
     root.send_email(to_addr,
                     subject,
                     from_addr=from_addr,
                     text=text,
                     subject_with_host=False)
     return resource.get_property('final_message')
示例#10
0
    def _propfind(cls, ref):
        ref, client = cls._get_client(ref)
        if ref in cls.response_cache:
            status, responses = cls.response_cache[ref]
            if cls.debug:
                dprint("response_cache hit: %s" % str(ref))
        else:
            if cls.debug:
                dprint("response_cache miss: %s" % str(ref))
            path = str(ref.path)
            responses = client.propfind(path, depth=1)
            if client.response.status == 301:
                # if cls.debug: dprint(client.response.status)
                # if cls.debug: dprint(pp.pformat(responses))
                # if cls.debug: dprint(client.response.body)
                match = cls.re301.search(client.response.body)
                if match:
                    newpath = match.group(1)
                    responses = client.propfind(newpath, depth=1)
                    cls.remap301[ref] = get_reference(newpath)
            status = client.response.status
            if cls.debug:
                dprint("response_cache miss: storing status=%s, response=%s" % (status, responses))
        if responses is not None:
            if cls.debug:
                dprint(ref)
            newref = cls._copy_reference_without_username(ref)
            cls.response_cache[newref] = (status, responses)

        return ref, status, responses
示例#11
0
文件: stl.py 项目: Nabellaleen/itools
def resolve_pointer(offset, reference, value):
    # FIXME Exception for STL
    if value[:2] == '${':
        return value

    # Absolute URI or path
    uri = get_reference(value)
    if uri.scheme or uri.authority:
        return value

    # Resolve Path
    if uri.path.is_absolute():
        if reference is None:
            return value
        # Do not call resolve with absolute path
        path = uri.path
    else:
        path = offset.resolve(uri.path)

    scheme = authority = ''
    if reference:
        scheme = reference.scheme
        authority = reference.authority
    value = Reference(scheme, authority, path, uri.query.copy(), uri.fragment)
    return str(value)
示例#12
0
        def my_func(value):
            # Skip empty links, external links and links to '/ui/'
            uri = get_reference(value)
            if uri.scheme or uri.authority or uri.path.is_absolute():
                return value
            path = uri.path
            if not path or path.is_absolute() and path[0] == 'ui':
                return value

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

            # Resolve Path
            # Calcul the old absolute path
            old_abs_path = source.resolve2(path)
            # Get the 'new' absolute parth
            new_abs_path = resources_old2new.get(old_abs_path, old_abs_path)

            path = str(target.get_pathto(new_abs_path)) + view
            value = Reference('', '', path, uri.query.copy(), uri.fragment)
            return str(value)
示例#13
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
示例#14
0
        def my_func(value):
            # Skip empty links, external links and links to '/ui/'
            uri = get_reference(value)
            if uri.scheme or uri.authority or uri.path.is_absolute():
                return value
            path = uri.path
            if not path or path.is_absolute() and path[0] == 'ui':
                return value

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

            # Resolve Path
            # Calcul the old absolute path
            old_abs_path = source.resolve2(path)
            # Get the 'new' absolute parth
            new_abs_path = resources_old2new.get(old_abs_path, old_abs_path)

            path = str(target.get_pathto(new_abs_path)) + view
            value = Reference('', '', path, uri.query.copy(), uri.fragment)
            return str(value)
示例#15
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
示例#16
0
文件: images.py 项目: hforge/shop
    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)
示例#17
0
文件: page.py 项目: hforge/wiki
    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)
示例#18
0
文件: user.py 项目: hforge/shop
    def send_confirm_url(self, context, email, subject, text, view):
        # XXX We override send_confirm_url to send mail
        # without setting subject with host, to use shop_uri
        # and not backoffice_uri (Since webmaster click from backoffice uri)
        # and to use good from_addr

        # Set the confirmation key
        if self.has_property('user_must_confirm'):
            key = self.get_property('user_must_confirm')
        else:
            key = generate_password(30)
            self.set_property('user_must_confirm', key)

        # Build the confirmation link
        shop = get_shop(context.resource)
        base_uri = shop.get_property('shop_uri')
        confirm_url = get_reference(base_uri)
        path = '/users/%s/%s' % (self.name, view)
        confirm_url.path = Path(path)
        confirm_url.query = {'key': key, 'username': self.get_login_name()}
        confirm_url = str(confirm_url)
        text = text.gettext(uri=confirm_url, key=key)
        # Get from_addr
        site_root = context.site_root
        if site_root.get_property('emails_from_addr'):
            user_name = site_root.get_property('emails_from_addr')
            user = self.get_resource('/users/%s' % user_name)
            from_addr = user.get_title(), user.get_property('email')
        else:
            from_addr = context.server.smtp_from
        # Subject
        subject = u'[%s] %s' % (base_uri, subject.gettext())
        # Send email
        context.root.send_email(email, subject, from_addr=from_addr,
                                text=text, subject_with_host=False)
示例#19
0
 def action(self, resource, context, form):
     root = context.root
     to_addr = resource.get_property('to_addr')
     subject = MSG(u'Message from form: "%s"' % resource.get_title()).gettext()
     text = []
     handler = resource.handler
     get_value = handler.get_record_value
     from_addr = to_addr
     for record in handler.get_records_in_order():
         name = get_value(record, 'name')
         datatype = get_value(record, 'datatype')
         value = form[name]
         # XXX Render on datatype ?
         if datatype == 'product':
             shop = get_shop(resource)
             site_root = resource.get_site_root()
             product = context.root.get_resource(value)
             base_uri = shop.get_property('shop_uri')
             end_uri = site_root.get_pathto(product)
             value = get_reference(base_uri).resolve(end_uri)
         elif datatype == 'email':
             # XXX Set from_addr
             from_addr = value
         title = get_value(record, 'title')
         text.append('*%s* \n\n %s' % (title, value))
     text = '\n\n\n'.join(text)
     root.send_email(to_addr, subject, from_addr=from_addr, text=text,
                     subject_with_host=False)
     return resource.get_property('final_message')
示例#20
0
文件: webdav.py 项目: zendbit/peppy
    def _propfind(cls, ref):
        ref, client = cls._get_client(ref)
        if ref in cls.response_cache:
            status, responses = cls.response_cache[ref]
            if cls.debug: dprint("response_cache hit: %s" % str(ref))
        else:
            if cls.debug: dprint("response_cache miss: %s" % str(ref))
            path = str(ref.path)
            responses = client.propfind(path, depth=1)
            if client.response.status == 301:
                #if cls.debug: dprint(client.response.status)
                #if cls.debug: dprint(pp.pformat(responses))
                #if cls.debug: dprint(client.response.body)
                match = cls.re301.search(client.response.body)
                if match:
                    newpath = match.group(1)
                    responses = client.propfind(newpath, depth=1)
                    cls.remap301[ref] = get_reference(newpath)
            status = client.response.status
            if cls.debug:
                dprint("response_cache miss: storing status=%s, response=%s" %
                       (status, responses))
        if responses is not None:
            if cls.debug: dprint(ref)
            newref = cls._copy_reference_without_username(ref)
            cls.response_cache[newref] = (status, responses)

        return ref, status, responses
示例#21
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)
示例#22
0
文件: diaporama.py 项目: hforge/itws
    def get_namespace(self, resource, context):
        width, height = 0, 0
        title = resource.get_property('display_title')
        if title:
            title = resource.get_title()
        namespace = {'title': title}
        user = context.user
        banners = []
        # Use to compute first image namespace
        first_banner_resource = None
        table = resource.get_resource(resource.order_path)
        handler = table.handler
        get_value = handler.get_record_value

        for record in handler.get_records_in_order():
            banner_ns = {}
            for key in ('title', 'description', 'target',):
                banner_ns[key] = get_value(record, key)
            # img path
            img_path = get_value(record, 'img_path')
            img_path_resource = table.get_resource(str(img_path), soft=True)
            if img_path_resource is None:
                # Skip broken image
                continue
            # ACL
            ac = img_path_resource.get_access_control()
            if ac.is_allowed_to_view(user, img_path_resource) is False:
                continue
            if first_banner_resource is None:
                first_banner_resource = img_path_resource
            img_path = '%s/;download' % context.get_link(img_path_resource)
            banner_ns['img_path'] = img_path
            # img link
            img_link = get_value(record, 'img_link')
            if img_link:
                reference = get_reference(img_link)
                if reference.scheme:
                    img_link = reference
                else:
                    item_link_resource = table.get_resource(reference.path,
                                                            soft=True)
                    if not item_link_resource:
                        img_link = reference
                    else:
                        img_link = context.get_link(item_link_resource)
            else:
                img_link = None
            banner_ns['img_link'] = img_link
            banners.append(banner_ns)

        # Compute first_img namespace
        first_img = {}
        if first_banner_resource:
            first_img = banners[0]
            width, height = first_banner_resource.handler.get_size()
        namespace['first_img'] = first_img
        namespace['banners'] = banners
        namespace['width'] = width
        namespace['height'] = height
        return namespace
示例#23
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)})
示例#24
0
文件: news.py 项目: nkhine/ztm-ikaaro
    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)
示例#25
0
文件: news.py 项目: nkhine/ztm-ikaaro
    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)
示例#26
0
文件: stl.py 项目: mmather02/itools
def resolve_pointer(offset, reference, value):
    # FIXME Exception for STL
    if value[:2] == '${':
        return value

    # Absolute URI or path
    uri = get_reference(value)
    if uri.scheme or uri.authority:
        return value

    # Resolve Path
    if uri.path.is_absolute():
        if reference is None:
            return value
        # Do not call resolve with absolute path
        path = uri.path
    else:
        path = offset.resolve(uri.path)

    scheme = authority = ''
    if reference:
        scheme = reference.scheme
        authority = reference.authority
    value = Reference(scheme, authority, path, uri.query.copy(), uri.fragment)
    return str(value)
示例#27
0
文件: page.py 项目: hforge/wiki
    def get_links(self):
        base = self.abspath

        try:
            doctree = self.get_doctree()
        except SystemMessage:
            # The doctree is in a incoherent state
            return set()

        # Links
        links = set()
        for node in doctree.traverse(condition=nodes.reference):
            refname = node.get('wiki_name')
            if refname is False:
                # Wiki link not found
                title = node['name']
                path = checkid(title) or title
                path = base.resolve(path)
            elif refname:
                # Wiki link found, "refname" is the path
                path = base.resolve2(refname)
            else:
                # Regular link, include internal ones
                refuri = node.get('refuri')
                if refuri is None:
                    continue
                reference = get_reference(refuri.encode('utf_8'))
                # Skip external
                if is_external(reference):
                    continue
                path = base.resolve2(reference.path)
            path = str(path)
            links.add(path)

        # Images
        for node in doctree.traverse(condition=nodes.image):
            reference = get_reference(node['uri'].encode('utf_8'))
            # Skip external image
            if is_external(reference):
                continue
            # Resolve the path
            path = base.resolve(reference.path)
            path = str(path)
            links.add(path)

        return links
示例#28
0
文件: tags.py 项目: hforge/itws
 def get_preview_thumbnail(self):
     path = self.get_property("thumbnail")
     if not path:
         return None
     ref = get_reference(path)
     if ref.scheme:
         return None
     return self.get_resource(path, soft=True)
示例#29
0
 def cover_uri(self):
     shop = get_shop(self)
     site_root = shop.get_site_root()
     cover = self.get_preview_thumbnail()
     if not cover:
         return None
     base_uri = shop.get_property('shop_uri')
     end_uri = site_root.get_pathto(cover)
     return str('%s/;download' % get_reference(base_uri).resolve(end_uri))
示例#30
0
文件: product.py 项目: hforge/shop
 def cover_uri(self):
     shop = get_shop(self)
     site_root = shop.get_site_root()
     cover = self.get_preview_thumbnail()
     if not cover:
         return None
     base_uri = shop.get_property('shop_uri')
     end_uri = site_root.get_pathto(cover)
     return str('%s/;download' % get_reference(base_uri).resolve(end_uri))
示例#31
0
    def GET(self, resource, context):
        if context.get_cookie('itws_fo_edit', Boolean):
            context.set_cookie('itws_fo_edit', '0')
        else:
            context.set_cookie('itws_fo_edit', '1')

        referer = context.get_referrer()
        if referer:
            ref = get_reference(referer)
            if ref.path == '/;fo_switch_mode':
                # Do no loop
                goto = '/'
            else:
                goto = referer
        else:
            goto = '/'

        return get_reference(goto)
示例#32
0
 def GET(self, resource, context):
     # We do a redirect permantent
     context.status = 301
     # Build goto
     query = context.uri.query
     specific_document = self.get_specific_document(resource, context)
     goto = '%s/%s' % (context.get_link(resource), specific_document)
     goto = get_reference(goto)
     goto.query = context.uri.query
     return goto
示例#33
0
 def action_diff(self, resource, context, form):
     # Take newer and older revisions, even if many selected
     ids = sorted(form['ids'])
     # Each item is a (index, revision) tuple
     revision = ids.pop()[1]
     to = ids.pop(0)[1] if ids else 'HEAD'
     # FIXME same hack than rename to call a GET from a POST
     query = encode_query({'revision': revision, 'to': to})
     uri = '%s/;changes?%s' % (context.get_link(resource), query)
     return get_reference(uri)
示例#34
0
 def _get_box_goto(self, child, context):
     link_child = '%s/;edit' % context.get_link(child)
     goto = get_reference(link_child)
     # Is admin popup ?
     if ('is_admin_popup' in context.get_referrer() and
         getattr(child, 'use_fancybox', True) is True):
         goto.query['is_admin_popup'] = '1'
     else:
         goto = None
     return goto
示例#35
0
文件: html.py 项目: nkhine/ztm-ikaaro
 def get_links(self):
     links = WebPage.get_links(self)
     base = self.get_canonical_path()
     path = self.get_property('title_link')
     if path:
         ref = get_reference(path)
         if not ref.scheme:
             path, view = get_path_and_view(ref.path)
             links.add(str(base.resolve2(path)))
     return links
示例#36
0
 def action_diff(self, resource, context, form):
     # Take newer and older revisions, even if many selected
     ids = sorted(form['ids'])
     # Each item is a (index, revision) tuple
     revision = ids.pop()[1]
     to = ids.pop(0)[1] if ids else 'HEAD'
     # FIXME same hack than rename to call a GET from a POST
     query = encode_query({'revision': revision, 'to': to})
     uri = '%s/;changes?%s' % (context.get_link(resource), query)
     return get_reference(uri)
示例#37
0
def close_fancybox(context, default=None):
    # Case 1: fancybox
    fancybox = context.get_query_value('fancybox')
    if fancybox:
        context.set_content_type('text/html')
        return _close_fancybox

    # Case 2: normal
    goto = context.get_form_value('referrer') or default
    return get_reference(goto) if type(goto) is str else goto
示例#38
0
def close_fancybox(context, default=None):
    # Case 1: fancybox
    fancybox = context.get_query_value('fancybox')
    if fancybox:
        context.set_content_type('text/html')
        return _close_fancybox

    # Case 2: normal
    goto = context.get_form_value('referrer') or default
    return get_reference(goto) if type(goto) is str else goto
示例#39
0
 def GET(self, resource, context):
     # We do a redirect permantent
     context.status = 301
     # Build goto
     query = context.uri.query
     specific_document = self.get_specific_document(resource, context)
     goto = "%s/%s" % (context.get_link(resource), specific_document)
     goto = get_reference(goto)
     goto.query = context.uri.query
     return goto
示例#40
0
文件: datatypes.py 项目: hforge/itws
 def is_valid(value):
     here = get_context().resource
     try:
         ref = get_reference(value)
         if not ref.scheme:
             resource = here.get_resource(ref.path, soft=True)
             if resource and isinstance(resource, Image):
                 return True
     except Exception:
         return False
     return False
示例#41
0
 def rewrite(value):
     if value[0] == '#':
         return value
     ref = get_reference(value)
     if ref.scheme:
         return value
     name = ref.path.get_name()
     name, extension, langage = FileName.decode(name)
     if extension in ('png', 'pdf'):
         name = '%s/;download' % name
     ref.path[-1] = name
     return '../%s' % ref
示例#42
0
文件: page_views.py 项目: hforge/wiki
def resolve_images(doctree, resource, context):
    """Translate image path to handler key to load them from filesystem.
    """
    fs = resource.metadata.database.fs
    for node in doctree.traverse(condition=nodes.image):
        reference = get_reference(node['uri'].encode('utf8'))
        if is_external(reference):
            continue
        name = str(reference.path)
        image = resource.get_resource(name, soft=True)
        if image is not None:
            node['uri'] = fs.get_absolute_path(image.handler.key)
示例#43
0
文件: text.py 项目: hforge/ikaaro
def css_get_reference(uri):
    # FIXME Not compliant with
    # http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
    value = uri.strip()
    # remove optional " or '
    if value and value[0] in ("'", '"'):
        value = value[1:]
    # remove optional " or '
    if value and value[-1] in ("'", '"'):
        value = value[:-1]

    return get_reference(value)
示例#44
0
def css_get_reference(uri):
    # FIXME Not compliant with
    # http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
    value = uri.strip()
    # remove optional " or '
    if value and value[0] in ("'", '"'):
        value = value[1:]
    # remove optional " or '
    if value and value[-1] in ("'", '"'):
        value = value[:-1]

    return get_reference(value)
示例#45
0
    def get_goto(self, user):
        context = self.context

        # Check if user account is completed
        for name, field in user.get_fields():
            if field.required and user.get_value(name) is None:
                msg = MSG(u'You must complete your account informations')
                goto = '/users/%s/;edit_account' % user.name
                return context.come_back(msg, goto)

        # Come back
        referrer = context.get_referrer()
        if referrer is None:
            goto = get_reference('./')
        else:
            path = get_uri_path(referrer)
            if path.endswith(';login') or path.endswith(';register'):
                goto = get_reference('./')
            else:
                goto = referrer

        return context.come_back(INFO(u"Welcome!"), goto)
示例#46
0
    def init_context(self):
        soup_message = self.soup_message
        path = self.path

        # The request method
        self.method = soup_message.get_method()
        # The query
        query = soup_message.get_query()
        self.query = decode_query(query)

        # The URI as it was typed by the client
        xfp = soup_message.get_header('X_FORWARDED_PROTO')
        src_scheme = xfp or 'http'
        xff = soup_message.get_header('X-Forwarded-Host')
        if xff:
            xff = xff.split(',', 1)[0].strip()
        hostname = soup_message.get_host()
        src_host = xff or soup_message.get_header('Host') or hostname
        if query:
            uri = '%s://%s%s?%s' % (src_scheme, src_host, path, query)
        else:
            uri = '%s://%s%s' % (src_scheme, src_host, path)
        self.uri = get_reference(uri)

        # Split the path into path and method ("a/b/c/;view")
        path = path if type(path) is Path else Path(path)
        name = path.get_name()
        if name and name[0] == ';':
            self.path = path[:-1]
            self.view_name = name[1:]
        else:
            self.path = path
            self.view_name = None

        # Cookies
        self.cookies = {}

        # Media files (CSS, javascript)
        # Set the list of needed resources. The method we are going to
        # call may need external resources to be rendered properly, for
        # example it could need an style sheet or a javascript file to
        # be included in the html head (which it can not control). This
        # attribute lets the interface to add those resources.
        self.styles = []
        self.scripts = []

        # The authenticated user
        self.authenticate()
        # The Site Root
        self.find_site_root()
        self.site_root.before_traverse(self)  # Hook
示例#47
0
文件: stl.py 项目: pombredanne/itools
def resolve_pointer(offset, value):
    # FIXME Exception for STL
    if value[:2] == '${':
        return value

    # Absolute URI or path
    uri = get_reference(value)
    if uri.scheme or uri.authority or uri.path.is_absolute():
        return value

    # Resolve Path
    path = offset.resolve(uri.path)
    value = Reference('', '', path, uri.query.copy(), uri.fragment)
    return str(value)
示例#48
0
    def action_batch_edition(self, resource, context, form):
        ids = form['ids']
        # Check input data
        if not ids:
            context.message = messages.MSG_NONE_SELECTED
            return

        # FIXME Hack to get rename working. The current user interface forces
        # the rename_form to be called as a form action, hence with the POST
        # method, but it should be a GET method. Maybe it will be solved after
        # the needed folder browse overhaul.
        ids_list = '&'.join([ 'ids=%s' % x for x in ids])
        uri = '%s/;batch_edition?%s' % (context.get_link(resource), ids_list)
        return get_reference(uri)
示例#49
0
    def GET(self, resource, context):
        specific_document = self.get_specific_document(resource, context)
        specific_view = self.get_specific_view(resource, context)
        goto = '%s/%s' % (context.get_link(resource), specific_document)
        if specific_view:
            goto = '%s/;%s' % (goto, specific_view)
        goto = get_reference(goto)

        # Keep the message
        message = context.get_form_value('message')
        if message:
            goto = goto.replace(message=message)

        return goto
示例#50
0
    def come_back(self, message, goto=None, keep=freeze([]), **kw):
        """This is a handy method that builds a resource URI from some
        parameters.  It exists to make short some common patterns.
        """
        # By default we come back to the referrer
        if goto is None:
            goto = self.get_referrer()
            # Replace goto if no referrer
            if goto is None:
                goto = str(self.uri)
                if '/;' in goto:
                    goto = goto.split('/;')[0]

        if type(goto) is str:
            goto = get_reference(goto)

        # Preserve some form values
        form = {}
        for key, value in self.get_form().items():
            # Be robust
            if not key:
                continue
            # Omit methods
            if key[0] == ';':
                continue
            # Omit files
            if isinstance(value, tuple) and len(value) == 3:
                continue
            # Keep form field
            if (keep is True) or (key in keep):
                form[key] = value
        if form:
            goto = goto.replace(**form)
        # Translate the source message
        if message:
            text = message.gettext(**kw)
            if is_prototype(message, ERROR):
                goto = goto.replace(error=text)
            else:
                goto = goto.replace(info=text)
        # Keep fancybox
        if 'fancybox' in self.uri.query:
            goto.query['fancybox'] = '1'
        # Ok
        return goto
示例#51
0
    def get_links(self, links, resource, field_name, languages):
        base = resource.abspath
        for language in languages:
            handler = self.get_value(resource, field_name, language)
            if not handler:
                continue
            for event, value, line in handler.events:
                if event != START_ELEMENT:
                    continue
                tag_uri, tag_name, attributes = value
                if tag_uri != xhtml_uri:
                    continue

                # Get the attribute name and value
                attr_name = map.get(tag_name)
                if attr_name is None:
                    continue

                attr_name = (None, attr_name)
                value = attributes.get(attr_name)
                if value is None:
                    continue

                reference = get_reference(value)

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

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

                uri = base.resolve2(path)
                uri = str(uri)
                links.add(uri)
示例#52
0
 def _show_payment_form(self, context, payment):
     kw = {
         'amout': '25',
         'currency': '978',  # Euros,
         'capture_delay': '3',
         'ctx_mode': 'TEST',
         'payment_cards': 'AMEX;CB;MASTERCARD;VISA',
         'payment_config': 'SINGLE',
         'site_id': '12345678',
         'trans_date': '20100303105332',
         'url_return': 'http://shop:8080',
         'trans_id': '1',
         'validation_mode': '0',  #Validation automatique
         'version': 'V1'
     }
     # Get signature
     kw['signature'] = self.get_signature(kw)
     # Return URI
     uri = get_reference(self.uri)
     uri.query = kw
     print '======>', uri
     return context.uri.resolve(uri)
示例#53
0
文件: user.py 项目: nicolasderam/shop
    def send_confirm_url(self, context, email, subject, text, view):
        # XXX We override send_confirm_url to send mail
        # without setting subject with host, to use shop_uri
        # and not backoffice_uri (Since webmaster click from backoffice uri)
        # and to use good from_addr

        # Set the confirmation key
        if self.has_property('user_must_confirm'):
            key = self.get_property('user_must_confirm')
        else:
            key = generate_password(30)
            self.set_property('user_must_confirm', key)

        # Build the confirmation link
        shop = get_shop(context.resource)
        base_uri = shop.get_property('shop_uri')
        confirm_url = get_reference(base_uri)
        path = '/users/%s/%s' % (self.name, view)
        confirm_url.path = Path(path)
        confirm_url.query = {'key': key, 'username': self.get_login_name()}
        confirm_url = str(confirm_url)
        text = text.gettext(uri=confirm_url, key=key)
        # Get from_addr
        site_root = context.site_root
        if site_root.get_property('emails_from_addr'):
            user_name = site_root.get_property('emails_from_addr')
            user = self.get_resource('/users/%s' % user_name)
            from_addr = user.get_title(), user.get_property('email')
        else:
            from_addr = context.server.smtp_from
        # Subject
        subject = u'[%s] %s' % (base_uri, subject.gettext())
        # Send email
        context.root.send_email(email,
                                subject,
                                from_addr=from_addr,
                                text=text,
                                subject_with_host=False)
示例#54
0
def split_reference(ref):
    """Return the reference associated to the path, the path and the optional
    view without query/fragment.
    ref: Reference
    path: Path
    view: string
    """
    # XXX specific case for the menu
    # Be robust if the path is multilingual
    type_ref = type(ref)
    if type_ref is unicode:
        ref = Unicode.encode(ref)
    if type_ref is not Reference:
        ref = get_reference(ref)
    # Split path and view
    path = ref.path
    view = ''
    name = path.get_name()
    # Strip the view
    if name and name[0] == ';':
        view = '/' + name
        path = path[:-1]
    return ref, path, view
示例#55
0
    def action_rename(self, resource, context, form):
        ids = form['ids']
        # Filter names which the authenticated user is not allowed to move
        root = context.root
        user = context.user
        # Check if file to rename exists & user is allowed to move
        paths = []
        for x in ids:
            r_to_rename = resource.get_resource(x, soft=True)
            if r_to_rename and root.is_allowed_to_move(user, r_to_rename):
                paths.append(x)

        # Check input data
        if not paths:
            context.message = messages.MSG_NONE_SELECTED
            return

        # FIXME Hack to get rename working. The current user interface forces
        # the rename_form to be called as a form action, hence with the POST
        # method, but it should be a GET method. Maybe it will be solved after
        # the needed folder browse overhaul.
        ids_list = '&'.join(['ids=%s' % x for x in paths])
        uri = '%s/;rename?%s' % (context.get_link(resource), ids_list)
        return get_reference(uri)
示例#56
0
    def __init__(self, target, read_only=False, cache_size=None,
                 profile_space=False):
        target = lfs.get_absolute_path(target)
        self.target = target
        self.read_only = read_only
        # Set timestamp
        self.timestamp = str(int(time() / 2))
        # Load the config
        config = get_config(target)
        self.config = config
        load_modules(config)
        self.modules = config.get_value('modules')

        # Contact Email
        self.smtp_from = config.get_value('smtp-from')

        # Full-text indexing
        self.index_text =  config.get_value('index-text', type=Boolean,
                                            default=True)
        # Accept cors
        self.accept_cors = config.get_value(
            'accept-cors', type=Boolean, default=False)

        # Profile Memory
        if profile_space is True:
            import guppy.heapy.RM

        # The database
        if cache_size is None:
            cache_size = config.get_value('database-size')
        if ':' in cache_size:
            size_min, size_max = cache_size.split(':')
        else:
            size_min = size_max = cache_size
        size_min, size_max = int(size_min), int(size_max)
        read_only = read_only or config.get_value('database-readonly')
        database = get_database(target, size_min, size_max, read_only)
        self.database = database

        # Find out the root class
        root = get_root(database)

        # Load environment file
        root_file_path = inspect.getfile(root.__class__)
        environement_path = str(get_reference(root_file_path).resolve('environment.json'))
        if vfs.exists(environement_path):
            with open(environement_path, 'r') as f:
                data = f.read()
                self.environment = json.loads(data)

        # Init fake context
        context = get_fake_context(database, root.context_cls)
        context.server = self

        # Initialize
        access_log = '%s/log/access' % target
        super(Server, self).__init__(root, access_log=access_log)

        # Email service
        self.spool = lfs.resolve2(self.target, 'spool')
        spool_failed = '%s/failed' % self.spool
        if not lfs.exists(spool_failed):
            lfs.make_folder(spool_failed)
        # Configuration variables
        get_value = config.get_value
        self.smtp_host = get_value('smtp-host')
        self.smtp_login = get_value('smtp-login', default='').strip()
        self.smtp_password = get_value('smtp-password', default='').strip()
        # Email is sent asynchronously
        self.flush_spool()

        # Logging
        log_file = '%s/log/events' % target
        log_level = config.get_value('log-level')
        if log_level not in log_levels:
            msg = 'configuraion error, unexpected "%s" value for log-level'
            raise ValueError, msg % log_level
        log_level = log_levels[log_level]
        logger = Logger(log_file, log_level, rotate=timedelta(weeks=3))
        register_logger(logger, None)
        logger = WebLogger(log_file, log_level)
        register_logger(logger, 'itools.web')
        # Session timeout
        self.session_timeout = get_value('session-timeout')
        # Register routes
        self.register_dispatch_routes()
示例#57
0
def read_file(context, uri, file):
    uri = get_reference(uri)

    # Shortcuts
    elements = context['elements']
    references = context['references']

    # XML stream
    stream = XMLParser(file.read())

    # Parse !
    stack = []
    for type, value, line in stream:
        # Set the good encoding
        if type == XML_DECL:
            context['encoding'] = value[1]

        elif type == START_ELEMENT:
            tag_uri, tag_name, attrs = value

            # Set your context variable
            read_common_attrs(tag_uri, attrs, context)

            # Only RNG !
            if tag_uri == rng_uri:

                # <element>
                if tag_name == 'element':
                    # Create a new element
                    qnames = read_qnames(attrs, context, stream)
                    element = {
                        'qnames': qnames,
                        'attributes': [],
                        'data': None,
                        'is_empty': True,
                        'refs': []
                    }

                    # My father has at least a child,  me!
                    if stack:
                        stack[-1]['is_empty'] = False

                    # And push it
                    elements.append(element)
                    stack.append(element)

                # <attribute>
                elif tag_name == 'attribute':
                    # Create a new attribute
                    qnames = read_qnames(attrs, context, stream)
                    attribute = {'qnames': qnames, 'data': None, 'refs': []}

                    # And push it
                    stack[-1]['attributes'].append(attribute)
                    stack.append(attribute)

                # <data>
                elif tag_name == 'data':
                    type = attrs[None, 'type']

                    last = stack[-1]
                    if last['data'] is not None:
                        last['data'] = ''
                    else:
                        last['data'] = type

                # <ref>
                elif tag_name == 'ref':
                    name = attrs[None, 'name']

                    if stack:
                        stack[-1]['refs'].append(name)

                # <define>
                elif tag_name == 'define':
                    name = attrs[None, 'name']

                    # New or merge ?
                    if name in references and (None, 'combine') in attrs:
                        ref = references[name]
                    else:
                        ref = {
                            'attributes': [],
                            'data': None,
                            'is_empty': True,
                            'refs': []
                        }
                        references[name] = ref

                    stack.append(ref)

                # <text>
                elif tag_name == 'text':
                    last = stack[-1]
                    if last['data'] is not None:
                        last['data'] = ''
                    else:
                        last['data'] = 'string'

                # <value>
                elif tag_name == 'value':
                    stack[-1]['data'] = ''

                # <include>
                elif tag_name == 'include':
                    href = attrs[None, 'href']
                    include_uri = uri.resolve(href)
                    include_uri = str(include_uri)
                    include_file = vfs.open(include_uri)
                    read_file(context, include_uri, include_file)

                # Ignored tags
                elif tag_name in [
                        'grammar', 'start', 'choice', 'optional', 'zeroOrMore',
                        'oneOrMore', 'group', 'empty', 'interleave', 'param',
                        'list', 'mixed'
                ]:
                    continue

                # Tags not implemented
                else:
                    raise NotImplementedError, ('relax NG: <%s> not '
                                                'implemented') % tag_name
        elif type == END_ELEMENT:
            tag_uri, tag_name = value
            if (tag_uri == rng_uri
                    and tag_name in ['element', 'attribute', 'define']):
                stack.pop()
示例#58
0
 def test_ftp(self):
     """references with unknow scheme are generic."""
     ref = get_reference('http://hforge.org')
     self.assert_(isinstance(ref, Reference))
示例#59
0
 def test_no_scheme(self):
     """references with no scheme are generic."""
     ref = get_reference('logo.png')
     self.assert_(isinstance(ref, Reference))
示例#60
0
 def is_valid(value):
     try:
         get_reference(value)
     except Exception:
         return False
     return True