Ejemplo n.º 1
0
def check_image(filename, context):
    if vfs.exists(filename) is False:
        print u"(WW) The filename '%s' doesn't exist" % filename
        filename = context.image_not_found_path
    im = None
    if filename.startswith('http://'):
        # Remote file
        # If the image is a remote file, we create a StringIO
        # object contains the image data to avoid reportlab problems ...
        data = vfs.open(filename).read()
        my_file = context.get_tmp_file()
        filename = my_file.name
        my_file.write(data)
        my_file.close()
        im = Image(string=data)
    if im is None:
        im = ro_database.get_handler(filename, Image)

    x, y = im.get_size()
    if not (x or y):
        print u'image not valid : %s' % filename
        filename = context.image_not_found_path
        im = ro_database.get_handler(filename, Image)
        x, y = im.get_size()

    return filename, (x, y)
Ejemplo n.º 2
0
    def get_template_from_skin_key(self, skin_key, web_path, warning):
        local_path = skin_key + web_path
        # 3. Get the handler
        handler = ro_database.get_handler(local_path, soft=True)
        if handler:
            if warning:
                print warning
            return handler

        # 4. Not an exact match: trigger language negotiation
        folder_path, name = local_path.rsplit('/', 1)
        name = name + '.'
        n = len(name)
        languages = []
        for x in lfs.get_names(folder_path):
            if x[:n] == name:
                language = x[n:]
                if has_language(language):
                    languages.append(language)
        if not languages:
            return None

        # 4.1 Get the best variant
        accept = self.accept_language
        language = accept.select_language(languages)
        # Print Warning
        if warning:
            print warning
        # 4.2 By default use whatever variant
        # (XXX we need a way to define the default)
        if language is None:
            language = languages[0]
        local_path = '%s.%s' % (local_path, language)
        return ro_database.get_handler(local_path)
Ejemplo n.º 3
0
def check_image(filename, context):
    if vfs.exists(filename) is False:
        print u"(WW) The filename '%s' doesn't exist" % filename
        filename = context.image_not_found_path
    im = None
    if filename.startswith('http://'):
        # Remote file
        # If the image is a remote file, we create a StringIO
        # object contains the image data to avoid reportlab problems ...
        data = vfs.open(filename).read()
        my_file = context.get_tmp_file()
        filename = my_file.name
        my_file.write(data)
        my_file.close()
        im = Image(string=data)
    if im is None:
        im = ro_database.get_handler(filename, Image)

    x, y = im.get_size()
    if not (x or y):
        print u'image not valid : %s' % filename
        filename = context.image_not_found_path
        im = ro_database.get_handler(filename, Image)
        x, y = im.get_size()

    return filename, (x, y)
Ejemplo n.º 4
0
    def get_template_from_skin_key(self, skin_key, web_path, warning):
        local_path = skin_key + web_path
        # 3. Get the handler
        handler = ro_database.get_handler(local_path, soft=True)
        if handler:
            if warning:
                print warning
            return handler

        # 4. Not an exact match: trigger language negotiation
        folder_path, name = local_path.rsplit('/', 1)
        name = name + '.'
        n = len(name)
        languages = []
        for x in lfs.get_names(folder_path):
            if x[:n] == name:
                language = x[n:]
                if has_language(language):
                    languages.append(language)
        if not languages:
            return None

        # 4.1 Get the best variant
        accept = self.accept_language
        language = accept.select_language(languages)
        # Print Warning
        if warning:
            print warning
        # 4.2 By default use whatever variant
        # (XXX we need a way to define the default)
        if language is None:
            language = languages[0]
        local_path = '%s.%s' % (local_path, language)
        return ro_database.get_handler(local_path)
Ejemplo n.º 5
0
def make_template(source, target):
    source_handler = ro_database.get_handler(source, XHTMLFile)

    language = target.rsplit('.', 1)[1]
    po = ro_database.get_handler('locale/%s.po' % language)
    data = source_handler.translate(po)
    with open(target, 'w') as f:
        f.write(data)
Ejemplo n.º 6
0
def make_template(source, target):
    source_handler = ro_database.get_handler(source, XHTMLFile)

    language = target.rsplit('.', 1)[1]
    po = ro_database.get_handler('locale/%s.po' % language)
    data = source_handler.translate(po)
    with open(target, 'w') as f:
        f.write(data)
Ejemplo n.º 7
0
    def init_resource(self, **kw):
        kw['website_is_open'] = 'extranet'
        # TODO allow to choose language at website creation
        default_language = 'en'
        # Initialize ikaaro website (Parent class)
        WebSite.init_resource(self, **kw)
        # Init bars
        Website_BarAware.init_resource(self, **kw)
        # Add a sitemap
        self.make_resource('sitemap.xml', self.sitemap_class)
        # Create Robots.txt
        self.make_resource('robots.txt', RobotsTxt)
        # Add an image folder
        self.make_resource('images', Folder)
        # Tags
        self.make_resource('tags', self.tagsfolder_class,
                           language=default_language)
        # Add default news folder
        self.make_resource('news', self.newsfolder_class)
        # About
        self.make_resource('about-itws', AboutITWS,
                       title={default_language: MSG(u'About ITWS').gettext()})

        # Add link to news in menu
        theme = self.get_resource('theme')
        menu = theme.get_resource('menu/menu')
        menu.add_new_record({'path': '/news/',
                             'title': Property(MSG(u'News').gettext(),
                                               language='en')})
        # Create a 'Welcome' html-content item in ws-data
        # Order this item in the contentbar
        path = get_abspath(self.first_contenbar)
        handler = ro_database.get_handler('%s.%s' % (path, default_language),
                                          XHTMLFile)
        ws_data = self.get_resource('ws-data')
        ws_data.make_resource('welcome', HTMLContent,
                  title={default_language: MSG(u'Welcome').gettext()},
                  state='public',
                  display_title=True,
                  body=handler.to_str(),
                  language=default_language)
        table = ws_data.get_resource('order-contentbar')
        table.add_new_record({'name': 'welcome'})

        # Create a 'Welcome' html-content item in repository
        # Order this item in the sidebar
        path = get_abspath(self.first_sidebar)
        handler = ro_database.get_handler('%s.%s' % (path, default_language),
                                          XHTMLFile)
        repository = self.get_resource('repository')
        repository.make_resource('first-sidebar', HTMLContent,
                  title={default_language: MSG(u'My first sidebar').gettext()},
                  state='public',
                  display_title=True,
                  body=handler.to_str(),
                  language=default_language)
        table = ws_data.get_resource('order-sidebar')
        table.add_new_record({'name': 'first-sidebar'})
Ejemplo n.º 8
0
def make_template(source, target):
    # Import some packages so we can compile templates
    from itools.html import XHTMLFile
    import itools.gettext
    import itools.stl
    import itools.pdf
    # Get file
    source_handler = ro_database.get_handler(source, XHTMLFile)
    language = target.rsplit('.', 1)[1]
    po = ro_database.get_handler('locale/%s.po' % language)
    data = source_handler.translate(po)
    with open(target, 'w') as f:
        f.write(data)
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
def register_shop(package, name):
    base_path = '../%s/%s' % (package, name)
    # Register shop
    shops.append(name)
    # Import project
    exec('import %s.%s' % (package, name))
    # Get config
    config_path = get_abspath('%s/setup.conf' % base_path)
    config = ro_database.get_handler(config_path, ITWSHOPConfig)
    # Register skin
    register_shop_skin(u'Skin %s' % name, package, '%s/ui/' % name, name, config)
    # Register domain for i18n
    register_domain(name, get_abspath('%s/locale' % base_path))
    # Register modules
    project_modules = []
    modules_path = get_abspath(join_paths(base_path, 'modules'))
    if exists(modules_path) or name == 'ecox':
        project_modules = [f for f in listdir(modules_path)
              if isdir(get_abspath('%s/%s' % (modules_path, f)))]
        for m in project_modules:
            exec('import %s.%s.modules.%s' % (package, name, m))
    # Print
    print 'Name: ',  name
    print 'URL: ', config.get_value('url')
    print 'Modules: [%s], %s' % (len(project_modules), project_modules)
Ejemplo n.º 11
0
def register_shop(package, name):
    base_path = '../%s/%s' % (package, name)
    # Register shop
    shops.append(name)
    # Import project
    exec('import %s.%s' % (package, name))
    # Get config
    config_path = get_abspath('%s/setup.conf' % base_path)
    config = ro_database.get_handler(config_path, ITWSHOPConfig)
    # Register skin
    register_shop_skin(u'Skin %s' % name, package, '%s/ui/' % name, name,
                       config)
    # Register domain for i18n
    register_domain(name, get_abspath('%s/locale' % base_path))
    # Register modules
    project_modules = []
    modules_path = get_abspath(join_paths(base_path, 'modules'))
    if exists(modules_path) or name == 'ecox':
        project_modules = [
            f for f in listdir(modules_path)
            if isdir(get_abspath('%s/%s' % (modules_path, f)))
        ]
        for m in project_modules:
            exec('import %s.%s.modules.%s' % (package, name, m))
    # Print
    print 'Name: ', name
    print 'URL: ', config.get_value('url')
    print 'Modules: [%s], %s' % (len(project_modules), project_modules)
Ejemplo n.º 12
0
def build(parser):
    # Extract options and arguments
    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error('incorrect number of arguments')
    source, catalog_name = args

    # The SRX file
    if options.srx is not None:
        srx_handler = ro_database.get_handler(options.srx)
    else:
        srx_handler = None

    # Check for ODF files
    if is_zipfile(source) and options.output is None:
        parser.error('The option -o is needed\n')

    # Load the source handler (check the API)
    handler = ro_database.get_handler(source)
    try:
        translate = handler.translate
    except AttributeError:
        print 'Error: Unable to translate "%s", unsupported format.' % source
        return
    # Load the Catalog handler (check the API)
    catalog = ro_database.get_handler(catalog_name)
    try:
        catalog.gettext
    except AttributeError:
        print('Error: The file "%s" is not a supported '
              'catalog.') % catalog_name
        return
    # Translate
    data = translate(catalog, srx_handler=srx_handler)

    # Save
    if options.output is None:
        sys.stdout.write(data)
    else:
        output = open(options.output, 'w')
        try:
            output.write(data)
        finally:
            output.close()
Ejemplo n.º 13
0
    def get_template(self, web_path):
        web_path = normalize_path(web_path)

        # 1. Find local root
        web_roots = ui_registry.keys()
        web_roots.sort(reverse=True)
        for web_root in web_roots:
            if web_path.startswith(web_root):
                break
        else:
            raise ValueError, 'unexpected %s' % repr(web_path)

        # 2. Get the local path
        local_root = ui_registry[web_root]
        local_path = local_root + web_path[len(web_root):]

        # 3. Get the handler
        handler = ro_database.get_handler(local_path, soft=True)
        if handler:
            return handler

        # 4. Not an exact match: trigger language negotiation
        folder_path, name = local_path.rsplit('/', 1)
        name = name + '.'
        n = len(name)
        languages = []
        for x in lfs.get_names(folder_path):
            if x[:n] == name:
                language = x[n:]
                if has_language(language):
                    languages.append(language)
        if not languages:
            return None

        # 4.1 Get the best variant
        accept = self.accept_language
        language = accept.select_language(languages)

        # 4.2 By default use whatever variant
        # (XXX we need a way to define the default)
        if language is None:
            language = languages[0]
        local_path = '%s.%s' % (local_path, language)
        return ro_database.get_handler(local_path)
Ejemplo n.º 14
0
    def get_template(self, web_path):
        web_path = normalize_path(web_path)

        # 1. Find local root
        web_roots = ui_registry.keys()
        web_roots.sort(reverse=True)
        for web_root in web_roots:
            if web_path.startswith(web_root):
                break
        else:
            raise ValueError, 'unexpected %s' % repr(web_path)

        # 2. Get the local path
        local_root = ui_registry[web_root]
        local_path = local_root + web_path[len(web_root):]

        # 3. Get the handler
        handler = ro_database.get_handler(local_path, soft=True)
        if handler:
            return handler

        # 4. Not an exact match: trigger language negotiation
        folder_path, name = local_path.rsplit('/', 1)
        name = name + '.'
        n = len(name)
        languages = []
        for x in lfs.get_names(folder_path):
            if x[:n] == name:
                language = x[n:]
                if has_language(language):
                    languages.append(language)
        if not languages:
            return None

        # 4.1 Get the best variant
        accept = self.accept_language
        language = accept.select_language(languages)

        # 4.2 By default use whatever variant
        # (XXX we need a way to define the default)
        if language is None:
            language = languages[0]
        local_path = '%s.%s' % (local_path, language)
        return ro_database.get_handler(local_path)
Ejemplo n.º 15
0
def build(parser):
    # Extract options and arguments
    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error('incorrect number of arguments')
    source, catalog_name = args

    # The SRX file
    if options.srx is not None:
        srx_handler = ro_database.get_handler(options.srx)
    else:
        srx_handler = None

    # Check for ODF files
    if is_zipfile(source) and options.output is None:
        parser.error('The option -o is needed\n')

    # Load the source handler (check the API)
    handler = ro_database.get_handler(source)
    try:
        translate = handler.translate
    except AttributeError:
        print 'Error: Unable to translate "%s", unsupported format.' % source
        return
    # Load the Catalog handler (check the API)
    catalog = ro_database.get_handler(catalog_name)
    try:
        catalog.gettext
    except AttributeError:
        print ('Error: The file "%s" is not a supported '
              'catalog.') % catalog_name
        return
    # Translate
    data = translate(catalog, srx_handler=srx_handler)

    # Save
    if options.output is None:
        sys.stdout.write(data)
    else:
        output = open(options.output, 'w')
        try:
            output.write(data)
        finally:
            output.close()
Ejemplo n.º 16
0
 def test_parameters_save(self):
     table = Books(string=books_file)
     table.save_state_to('tests/books')
     # Load
     table = ro_database.get_handler('tests/books', Books)
     table.load_state()
     # Test
     record_0 = table.get_record(0)
     value = table.get_record_value(record_0, 'title', language='es')
     self.assertEqual(value, u'El Capital')
Ejemplo n.º 17
0
 def _make_resource(cls, folder, name, *args, **kw):
     OrderedTable._make_resource(cls, folder, name)
     table = BaseCountriesZones()
     zones = []
     csv = ro_database.get_handler(get_abspath('data/countries.csv'), CSVFile)
     for line in csv.get_rows():
         zone = unicode(line[1], 'utf-8')
         if zone not in zones:
             zones.append(zone)
             table.add_record({'title': Property(zone, language='fr')})
     folder.set_handler(name, table)
Ejemplo n.º 18
0
 def test_vtimezone(self):
     handler = ro_database.get_handler('tests/test_vtimezone.ics', iCalendar)
     tz = handler.get_components('VTIMEZONE')
     self.assertEqual(len(tz), 1)
     tz = tz[0]
     self.assertEqual(tz.__class__, VTimezone)
     self.assertTrue(isinstance(tz, tzinfo))
     for dt, (tzname, dst, utcoffset) in tz_file_test:
         dt = datetime(*dt, tzinfo=tz)
         self.assertEqual(tz.tzname(dt), tzname)
         self.assertEqual(tz.dst(dt), timedelta(*dst))
         self.assertEqual(tz.utcoffset(dt), timedelta(*utcoffset))
Ejemplo n.º 19
0
    def test_set_state_in_file_resource(self):
        handler = rw_database.get_handler('tests/test.csv', CSVFile)
        handler.add_row(['d1', 'e1', 'f1'])
        handler.save_state()

        handler2 = rw_database.get_handler('tests/test.csv', CSVFile)
        self.assertEqual(handler2.get_row(3), ['d1', 'e1', 'f1'])
        handler2.del_row(3)
        handler2.save_state()

        handler = ro_database.get_handler('tests/test.csv', CSVFile)
        self.assertEqual(handler.get_nrows(), 3)
Ejemplo n.º 20
0
 def _make_resource(cls, folder, name, *args, **kw):
     OrderedTable._make_resource(cls, folder, name)
     table = BaseCountriesZones()
     zones = []
     csv = ro_database.get_handler(get_abspath('data/countries.csv'),
                                   CSVFile)
     for line in csv.get_rows():
         zone = unicode(line[1], 'utf-8')
         if zone not in zones:
             zones.append(zone)
             table.add_record({'title': Property(zone, language='fr')})
     folder.set_handler(name, table)
Ejemplo n.º 21
0
 def test_vtimezone(self):
     handler = ro_database.get_handler('tests/test_vtimezone.ics',
                                       iCalendar)
     tz = handler.get_components('VTIMEZONE')
     self.assertEqual(len(tz), 1)
     tz = tz[0]
     self.assertEqual(tz.__class__, VTimezone)
     self.assertTrue(isinstance(tz, tzinfo))
     for dt, (tzname, dst, utcoffset) in tz_file_test:
         dt = datetime(*dt, tzinfo=tz)
         self.assertEqual(tz.tzname(dt), tzname)
         self.assertEqual(tz.dst(dt), timedelta(*dst))
         self.assertEqual(tz.utcoffset(dt), timedelta(*utcoffset))
Ejemplo n.º 22
0
 def _make_resource(cls, folder, name, *args, **kw):
     Table._make_resource(cls, folder, name)
     # Import CSV with list of countries
     zones = []
     table = BaseCountries()
     csv = ro_database.get_handler(get_abspath('data/countries.csv'), CSVFile)
     for line in csv.get_rows():
         country = unicode(line[0], 'utf-8')
         zone = unicode(line[1], 'utf-8')
         if zone not in zones:
             zones.append(zone)
         table.add_record({'title': Property(country, language='fr'),
                           'zone': str(zones.index(zone)),
                           'enabled': True})
     folder.set_handler(name, table)
Ejemplo n.º 23
0
    def view(self):
        # Load the STL template
        handler = ro_database.get_handler('TaskTracker_view.xml')

        # Build the namespace
        namespace = {}
        namespace['tasks'] = []
        for i, task in enumerate(self.tasks):
            namespace['tasks'].append({'id': i,
                                       'title': task.title,
                                       'description': task.description,
                                       'state': task.state,
                                       'is_open': task.state == 'open'})

        # Process the template and return the output
        return stl(handler, namespace, mode='xhtml')
Ejemplo n.º 24
0
 def test_save(self):
     agenda = Agenda(string=agenda_file)
     agenda.save_state_to('tests/agenda')
     # Change
     agenda = rw_database.get_handler('tests/agenda', Agenda)
     fake = agenda.add_record({'firstname': u'Toto', 'lastname': u'Fofo'})
     agenda.add_record({'firstname': u'Albert', 'lastname': u'Einstein'})
     agenda.del_record(fake.id)
     agenda.save_state()
     # Test
     agenda = ro_database.get_handler('tests/agenda', Agenda)
     ids = [ x.id for x in agenda.search(firstname=u'Toto') ]
     self.assertEqual(len(ids), 0)
     ids = [ x.id for x in agenda.search(firstname=u'Albert') ]
     self.assertEqual(len(ids), 1)
     # Clean
     lfs.remove('tests/agenda')
Ejemplo n.º 25
0
    def view(self):
        # Load the STL template
        handler = ro_database.get_handler('TaskTracker_view.xml')

        # Build the namespace
        namespace = {}
        namespace['tasks'] = []
        for i, task in enumerate(self.tasks):
            namespace['tasks'].append({
                'id': i,
                'title': task.title,
                'description': task.description,
                'state': task.state,
                'is_open': task.state == 'open'
            })

        # Process the template and return the output
        return stl(handler, namespace, mode='xhtml')
Ejemplo n.º 26
0
 def _make_resource(cls, folder, name, *args, **kw):
     Table._make_resource(cls, folder, name)
     # Import CSV with list of countries
     zones = []
     table = BaseCountries()
     csv = ro_database.get_handler(get_abspath('data/countries.csv'),
                                   CSVFile)
     for line in csv.get_rows():
         country = unicode(line[0], 'utf-8')
         zone = unicode(line[1], 'utf-8')
         if zone not in zones:
             zones.append(zone)
         table.add_record({
             'title': Property(country, language='fr'),
             'zone': str(zones.index(zone)),
             'enabled': True
         })
     folder.set_handler(name, table)
Ejemplo n.º 27
0
 def init_resource(self, **kw):
     # Init resource
     BaseTheme.init_resource(self, **kw)
     # Get language
     website = self.parent
     language = website.get_default_language()
     # Banner (background set with CSS)
     path = get_abspath("data/k2-banner-ties.jpg")
     image = ro_database.get_handler(path, FileHandler)
     self.make_resource(
         "banner-itws",
         Image,
         body=image.to_str(),
         extension="jpg",
         filename="banner-itws.jpg",
         format="image/jpeg",
         state="public",
     )
     # Set banner title
     vhosts = website.get_property("vhosts")
     if vhosts:
         banner_title = vhosts[0]
     else:
         banner_title = website.get_title()
     self.set_property("banner_title", banner_title, language=language)
     # CSS file
     # TODO Add an API in ikaaro that allow to easily change CSS...
     path = get_abspath("ui/themes/style.css")
     body = open(path).read()
     style = self.get_resource("style")
     style.handler.load_state_from_string(body)
     style.handler.set_changed()
     # Custom 404
     self.make_resource("404", NotFoundPage)
     # Add footer
     self.make_resource("footer", FooterFolder)
     menu = self.get_resource("footer/menu")
     title = Property(MSG(u"Powered by itws").gettext(), language=language)
     menu.add_new_record({"title": title, "path": "/about-itws"})
     title = Property(MSG(u"Contact us").gettext(), language=language)
     menu.add_new_record({"title": title, "path": "/;contact"})
     # Turning footer
     self.make_resource("turning-footer", TurningFooterFolder)
Ejemplo n.º 28
0
    def get_available_languages(self):
        """Returns the language codes for the user interface.
        """
        source = itools_source_language
        target = itools_target_languages
        # A package based on itools
        cls = self.__class__
        if cls is not Root:
            exec('import %s as pkg' % cls.__module__.split('.', 1)[0])
            config = Path(pkg.__path__[0]).resolve_name('setup.conf')
            config = ro_database.get_handler(str(config), ConfigFile)
            source = config.get_value('source_language', default=source)
            target = config.get_value('target_languages', default=target)

        target = target.split()
        if source in target:
            target.remove(source)

        target.insert(0, source)
        return target
Ejemplo n.º 29
0
Archivo: theme.py Proyecto: hforge/itws
 def init_resource(self, **kw):
     # Init resource
     BaseTheme.init_resource(self, **kw)
     # Get language
     website = self.parent
     language = website.get_default_language()
     # Banner (background set with CSS)
     path = get_abspath('data/k2-banner-ties.jpg')
     image = ro_database.get_handler(path, FileHandler)
     self.make_resource('banner-itws', Image, body=image.to_str(),
                        extension='jpg', filename='banner-itws.jpg',
                        format='image/jpeg', state='public')
     # Set banner title
     vhosts = website.get_property('vhosts')
     if vhosts:
         banner_title = vhosts[0]
     else:
         banner_title = website.get_title()
     self.set_property('banner_title', banner_title, language=language)
     # Drop logo property since itws uses banner_path property
     self.del_property('logo')
     # CSS file
     # TODO Add an API in ikaaro that allow to easily change CSS...
     path = get_abspath('ui/themes/style.css')
     body = open(path).read()
     style = self.get_resource('style')
     style.handler.load_state_from_string(body)
     style.handler.set_changed()
     # Custom 404
     self.make_resource('404', NotFoundPage)
     # Add footer
     self.make_resource('footer', FooterFolder)
     menu = self.get_resource('footer/menu')
     title = Property(MSG(u'Powered by itws').gettext(),
                      language=language)
     menu.add_new_record({'title': title, 'path': '/about-itws'})
     title = Property(MSG(u'Contact us').gettext(),
                      language=language)
     menu.add_new_record({'title': title, 'path': '/;contact'})
     # Turning footer
     self.make_resource('turning-footer', TurningFooterFolder)
Ejemplo n.º 30
0
 def test_load_file(self):
     handler = ro_database.get_handler('tests/hello.txt')
     self.assertEqual(handler.data, u'hello world\n')
Ejemplo n.º 31
0
from config import Configuration
from config_register import RegisterForm, TermsOfService_View
from context import CMSContext
from fields import Char_Field
from folder import Folder
from resource_views import LoginView
from skins import skin_registry
from root_views import PoweredBy, ContactForm
from root_views import NotFoundView, ForbiddenView, NotAllowedView
from root_views import UploadStatsView, UpdateDocs, UnavailableView
from update import UpdateInstanceView


# itools source and target languages
config = get_abspath('setup.conf')
config = ro_database.get_handler(config,  ConfigFile)
itools_source_language = config.get_value('source_language')
itools_target_languages = config.get_value('target_languages')


# Force email to send UTF-8 mails in plain text
add_charset('utf-8', QP, None, 'utf-8')
add_codec('utf-8', 'utf_8')



class CtrlView(BaseView):

    access = True

    def GET(self, resource, context):
Ejemplo n.º 32
0
def get_config():
    return ro_database.get_handler('setup.conf', SetupConf)
Ejemplo n.º 33
0
def get_config(target):
    return ro_database.get_handler('%s/config.conf' % target, ServerConfig)
Ejemplo n.º 34
0
 def get_template(self, resource, context):
     path = get_abspath('twitter.stl')
     return ro_database.get_handler(path, XMLFile)
Ejemplo n.º 35
0
    (style_uri, 'default-page-layout'),
    (style_uri, 'list-level-label-alignment'),
    ]

###########################################################################
# Make the namespaces
###########################################################################
def duplicate_ns(namespaces, first_uri, second_uri):
    ns = copy(namespaces[first_uri])
    ns.uri = second_uri
    ns.prefix = None
    namespaces[second_uri] = ns

# Read the Relax NG schema
rng_file = get_abspath('OpenDocument-strict-schema-v1.1.rng')
rng_file = ro_database.get_handler(rng_file, RelaxNGFile)
namespaces = rng_file.get_namespaces()

# Apply the metadata
for uri, element_name in inline_elements:
    element = namespaces[uri].get_element_schema(element_name)
    element.is_inline = True
for uri, element_name in skip_content_elements:
    element = namespaces[uri].get_element_schema(element_name)
    element.skip_content = True
for uri, element_name in unknown_elements:
    elements = namespaces[uri].elements
    if element_name in elements:
        raise ValueError, 'element "%s" is defined twice' % element_name
    elements[element_name] = ElementSchema(element_name,
                                           default_datatype=String)
Ejemplo n.º 36
0
def get_config():
    return ro_database.get_handler('setup.conf', SetupConf)
Ejemplo n.º 37
0
 def get_template(self, resource, context):
     style = resource.get_property('style')
     path = get_abspath('addthis_%s.stl' % style)
     return ro_database.get_handler(path, XMLFile)
Ejemplo n.º 38
0

    #########################################################################
    # Web Interface
    #########################################################################
    def view(self):
        # Load the STL template
        handler = ro_database.get_handler('TaskTracker_view.xml')

        # Build the namespace
        namespace = {}
        namespace['tasks'] = []
        for i, task in enumerate(self.tasks):
            namespace['tasks'].append({'id': i,
                                       'title': task.title,
                                       'description': task.description,
                                       'state': task.state,
                                       'is_open': task.state == 'open'})

        # Process the template and return the output
        return stl(handler, namespace, mode='xhtml')


register_handler_class(TaskTracker)



if __name__ == '__main__':
    task_tracker = ro_database.get_handler('itools.tt')
    print task_tracker.view()
Ejemplo n.º 39
0
    # Format
    if options.format == 'po':
        cls = POFile
    elif options.format == 'tmx':
        cls = TMXFile
    elif options.format == 'xliff':
        cls = XLFFile
    else:
        parser.error(
            "available output formats are 'po' (default), 'tmx' and 'xliff'.")

    # The SRX file
    if options.srx is None:
        srx_handler = None
    else:
        srx_handler = ro_database.get_handler(options.srx)

    # Make the output handler
    out_handler = cls()
    for filename in args:
        handler = ro_database.get_handler(filename)
        try:
            get_units = handler.get_units
        except AttributeError:
            message = 'ERROR: The file "%s" could not be processed\n'
            sys.stderr.write(message % filename)
            continue
        # Extract the messages
        for source, context, line in get_units(srx_handler=srx_handler):
            out_handler.add_unit(filename, source, context, line)
    data = out_handler.to_str()
Ejemplo n.º 40
0
    def test_wrapped_quote_value(self):
        # Init data
        value = "\"HELLO, WORLD!\""
        self._init_test(value)

        # Write data
        config = rw_database.get_handler(self.config_path, ConfigFile)
        try:
            config.set_value("test", value)
        except SyntaxError, e:
            self.fail(e)
        config.save_state()

        # Read data
        config2 = ro_database.get_handler(self.config_path, ConfigFile)
        try:
            config2_value = config2.get_value("test")
        except SyntaxError, e:
            self.fail(e)
        finally:
            lfs.remove(self.config_path)

        # Test data
        self.assertEqual(config2_value, value)


###########################################################################
# Archive files
###########################################################################
class ArchiveTestCase(TestCase):
Ejemplo n.º 41
0
    # Read configuration for languages
    config = get_config()
    src_language = config.get_value('source_language', default='en')

    # Get local folder
    package_root = config.get_value('package_root')
    if lfs.exists(package_root):
        locale_folder_path = Path('{0}/locale'.format(package_root))
    else:
        locale_folder_path = Path('locale/')
    locale_folder = lfs.open(locale_folder_path)

    # The SRX file
    if options.srx is not None:
        srx_handler = ro_database.get_handler(options.srx)
    else:
        srx_handler = None

    # Initialize message catalog
    po = POFile()
    lines = []
    for line in open('MANIFEST').readlines():
        line = line.strip()
        if line.split(sep)[0] not in ('archive', 'docs', 'skeleton', 'test'):
            lines.append(line)

    # Process Python and HTML files
    write('* Extract text strings')
    extensions = ['.py', '.xhtml.%s' % src_language, '.xml.%s' % src_language]
Ejemplo n.º 42
0
        for lang in (source_language, ) + target_languages:
            print lang,
            stdout.flush()
            call(
                ['msgfmt',
                 'locale/%s.po' % lang, '-o',
                 'locale/%s.mo' % lang])
            # Add to the manifest
            manifest.append('locale/%s.mo' % lang)
        print

        # Load message catalogs
        message_catalogs = {}
        for lang in target_languages:
            path = 'locale/%s.po' % lang
            handler = ro_database.get_handler(path)
            message_catalogs[lang] = (handler, lfs.get_mtime(path))

        # Build the templates in the target languages
        good_files = compile('.*\\.x.*ml.%s$' % source_language)
        exclude = frozenset(['.git', 'build', 'dist'])
        lines = get_files(exclude, filter=lambda x: good_files.match(x))
        lines = list(lines)
        if lines:
            print '* Build XHTML files',
            stdout.flush()
            for path in lines:
                # Load the handler
                src_mtime = lfs.get_mtime(path)
                src = ro_database.get_handler(path, XHTMLFile)
                done = False
Ejemplo n.º 43
0
 def setUp(self):
     self.rss = ro_database.get_handler('tests/sample-rss-2.xml', RSSFile)
Ejemplo n.º 44
0
    version = 'itools %s' % itools.__version__
    description = (
        'Anonymizes and ODF file, replacing text by latin boilerplate and '
        'images by other dumb images.')
    parser = OptionParser(usage, version=version, description=description)
    parser.add_option('-o', '--output', help='The output will be written to'
        ' the given file, instead of printed to the standard output.')

    # Parse the command line
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    # Load the ODF handler
    filename = args[0]
    handler = ro_database.get_handler(filename)
    if not isinstance(handler, ODFFile):
        parser.error('the given file is not an ODF file')

    # Anonymize
    data = handler.greek()

    # Save
    if options.output is None:
        stdout.write(data)
    else:
        file_out = open(options.output, 'w')
        try:
            file_out.write(data)
        finally:
            file_out.close()
Ejemplo n.º 45
0
 def setUp(self):
     self.doc = ro_database.get_handler('odf/Document.odp', ODPFile)
Ejemplo n.º 46
0
 def get_template(self, resource, context):
     path = get_abspath('google_analytics.stl')
     return ro_database.get_handler(path, XMLFile)
Ejemplo n.º 47
0
 def test_input(self):
     """Test input.
     """
     xliff = ro_database.get_handler('tests/gettext_en_es.xlf', XLFFile)
     xliff.to_str()
Ejemplo n.º 48
0
 def get_template(self):
     path = get_abspath('google_analytics_graph.stl')
     return ro_database.get_handler(path, XMLFile)
Ejemplo n.º 49
0
    description = (
        'Anonymizes and ODF file, replacing text by latin boilerplate and '
        'images by other dumb images.')
    parser = OptionParser(usage, version=version, description=description)
    parser.add_option(
        '-o',
        '--output',
        help='The output will be written to'
        ' the given file, instead of printed to the standard output.')

    # Parse the command line
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    # Load the ODF handler
    filename = args[0]
    handler = ro_database.get_handler(filename)
    if not isinstance(handler, ODFFile):
        parser.error('the given file is not an ODF file')

    # Anonymize
    data = handler.greek()

    # Save
    if options.output is None:
        stdout.write(data)
    else:
        with open(options.output, 'w') as file_out:
            file_out.write(data)
Ejemplo n.º 50
0
    while center:
        if (center[0][0] == START_FORMAT and center[-1][0] == END_FORMAT and
            center[0][1][1] == center[-1][1][1]):
            left.append(center.pop(0))
            right.insert(0, center.pop())
        else:
            break

    # (4) Remove the spaces
    left, center, right = _remove_spaces(left, center, right, keep_spaces)

    return left, center, right


default_srx_handler = get_abspath('srx/default.srx', 'itools')
default_srx_handler = ro_database.get_handler(default_srx_handler, SRXFile)
def _split_message(message, srx_handler=None):
    # Concatenation!
    concat_text = []
    for type, value, line in message:
        if type == TEXT:
            concat_text.append(value[0])
    concat_text = u''.join(concat_text)

    # Get the rules
    if srx_handler is None:
        srx_handler = default_srx_handler
    # XXX we must handle the language here!
    rules = srx_handler.get_compiled_rules('en')

    # Get the breaks
Ejemplo n.º 51
0
 def test_input(self):
     """Test input.
     """
     tmx = ro_database.get_handler('tests/localizermsgs.tmx', TMXFile)
     tmx.to_str()
Ejemplo n.º 52
0
    # Format
    if options.format == 'po':
        cls = POFile
    elif options.format == 'tmx':
        cls = TMXFile
    elif options.format == 'xliff':
        cls = XLFFile
    else:
        parser.error(
            "available output formats are 'po' (default), 'tmx' and 'xliff'.")

    # The SRX file
    if options.srx is None:
        srx_handler = None
    else:
        srx_handler = ro_database.get_handler(options.srx)

    # Make the output handler
    out_handler = cls()
    for filename in args:
        handler = ro_database.get_handler(filename)
        try:
            get_units = handler.get_units
        except AttributeError:
            message = 'ERROR: The file "%s" could not be processed\n'
            sys.stderr.write(message % filename)
            continue
        # Extract the messages
        for source, context, line in get_units(srx_handler=srx_handler):
            out_handler.add_unit(filename, source, context, line)
    data = out_handler.to_str()
Ejemplo n.º 53
0
 def test_table(self):
     handler = ro_database.get_handler('pml/table.xml', XMLFile)
     story, stylesheet = stl_pmltopdf_test(handler, path='pml/table.xml')
     self.assertEqual(len(story), 1)
Ejemplo n.º 54
0
 def test_table(self):
     handler = ro_database.get_handler('pml/table.xml', XMLFile)
     story, stylesheet = stl_pmltopdf_test(handler, path='pml/table.xml')
     self.assertEqual(len(story), 1)
Ejemplo n.º 55
0
]


###########################################################################
# Make the namespaces
###########################################################################
def duplicate_ns(namespaces, first_uri, second_uri):
    ns = copy(namespaces[first_uri])
    ns.uri = second_uri
    ns.prefix = None
    namespaces[second_uri] = ns


# Read the Relax NG schema
rng_file = get_abspath('OpenDocument-strict-schema-v1.1.rng')
rng_file = ro_database.get_handler(rng_file, RelaxNGFile)
namespaces = rng_file.get_namespaces()

# Apply the metadata
for uri, element_name in inline_elements:
    element = namespaces[uri].get_element_schema(element_name)
    element.is_inline = True
for uri, element_name in skip_content_elements:
    element = namespaces[uri].get_element_schema(element_name)
    element.skip_content = True
for uri, element_name in unknown_elements:
    elements = namespaces[uri].elements
    if element_name in elements:
        raise ValueError, 'element "%s" is defined twice' % element_name
    elements[element_name] = ElementSchema(element_name,
                                           default_datatype=String)
Ejemplo n.º 56
0
    def test_get_handler(self):
        cls = ro_database.get_handler_class('handlers/test.tar.gz')
        self.assertEqual(cls, TGZFile)

        file = ro_database.get_handler('handlers/test.tar.gz')
        self.assertEqual(file.__class__, TGZFile)