def email_body(body):
    #body = str(body)
    #if type(body) == str:
    #    body = body.decode('utf8')
    body = body.replace('\r\n', '\n')
    # fix issue where quoted text immediately after quoted text at start of
    # quoting
    body = body.replace(':\n>', ':\n\n>')
    # in quoted sections seem to get line continuations with =
    body = body.replace('=\n', '')
    # incredibly ugly hack to deal with <*****@*****.**> in message body
    # (does not get handled by markdown for some reason ...)
    import re
    body = re.sub('<isitopen.okfn.org\s*>', '&lt;isitopen.okfn.org&gt;', body)
    # body = body.replace('<isitopen.okfn.org>', '&lt;isitopen.okfn.org&gt;')
    #return ""
    #return markdown(repr(type(body)).replace("<", "&lt;") + body[:10])
    # Todo: Fix this, it screws up when unicode is in the enquiry body.
    try:
        out = genshi.HTML(markdown(body))
    except:
        out = '<p><strong>We had problems prettifying the email you are trying to display -- probably due to broken HTML in it!</strong></p>\n\n'
        try:
            out += unicode(genshi.escape(body))
        except:
            pass
        out = genshi.HTML(out)
    return out
Example #2
0
def sanitize(html):
    """Removes unsafe tags and attributes from html and adds
    ``rel="nofollow"`` attribute to all external links.
    """

    # Can't sanitize unless genshi module is available
    if genshi is None:
        return html

    def get_nofollow(name, event):
        attrs = event[1][1]
        href = attrs.get('href', '')

        if href:
            # add rel=nofollow to all absolute links
            _, host, _, _, _ = urlparse.urlsplit(href)
            if host:
                return 'nofollow'

    try:
        html = genshi.HTML(html)
    except genshi.ParseError:
        if BeautifulSoup:
            # Bad html. Tidy it up using BeautifulSoup
            html = str(BeautifulSoup(html))
            html = genshi.HTML(html)
        else:
            raise

    stream = html \
        | genshi.filters.HTMLSanitizer() \
        | genshi.filters.Transformer("//a").attr("rel", get_nofollow)
    return stream.render()
    def _read(self, id, limit, dataset_type=None):
        ''' This is common code used by both read and bulk_process'''
        self.group_type = 'organization'
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'schema': self._db_to_form_schema(group_type=self.group_type),
            'for_view': True,
            'extras_as_string': True
        }

        q = c.q = request.params.get('q', '')
        # Search within group
        if c.group_dict.get('is_organization'):
            q += ' owner_org: "%s"' % c.group_dict.get('id')
        else:
            q += ' groups: "%s"' % c.group_dict.get('name')

        try:
            description_formatted = ckan.misc.MarkdownFormat().to_html(
                c.group_dict.get('description', ''))
            c.description_formatted = genshi.HTML(description_formatted)
        except Exception, e:
            error_msg = "<span class='inline-warning'>%s</span>" %\
                        p.toolkit._("Cannot render description")
            c.description_formatted = genshi.HTML(error_msg)
Example #4
0
    def read(self, id):
        from ckan.lib.search import SearchError
        group_type = self._get_group_type(id.split('@')[0])
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': self._db_to_form_schema(group_type=group_type),
                   'for_view': True, 'extras_as_string': True}
        data_dict = {'id': id}
        # unicode format (decoded from utf8)
        q = c.q = request.params.get('q', '')

        try:
            c.group_dict = get_action('group_show')(context, data_dict)
            c.group = context['group']
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % id)

        # Search within group
        q += ' groups: "%s"' % c.group_dict.get('name')

        try:
            description_formatted = ckan.misc.MarkdownFormat().to_html(
            c.group_dict.get('description', ''))
            c.description_formatted = genshi.HTML(description_formatted)
        except Exception, e:
            error_msg = "<span class='inline-warning'>%s</span>" %\
                        _("Cannot render description")
            c.description_formatted = genshi.HTML(error_msg)
Example #5
0
 def render_package(cls, pkg, context):
     '''Prepares for rendering a package. Takes a Package object and
     formats it for the various context variables required to call
     render. 
     Note that the actual calling of render('package/read') is left
     to the caller.'''
     try:
         notes_formatted = ckan.misc.MarkdownFormat().to_html(
             pkg.get('notes', ''))
         c.pkg_notes_formatted = genshi.HTML(notes_formatted)
     except Exception, e:
         error_msg = "<span class='inline-warning'>%s</span>" % _(
             "Cannot render package description")
         c.pkg_notes_formatted = genshi.HTML(error_msg)
Example #6
0
File: macro.py Project: weese/seqan
    def format_doc_link(self, formatter, ns, target, label):
        """Function to perform formatting for seqan:XYZ links.

        This roughly follows [1].

        [1] http://trac.edgewall.org/wiki/TracDev/IWikiSyntaxProviderExample
        """
        add_stylesheet(formatter.req, 'doc_links/css/doc_links.css')
        # The following is a heuristic for "no alternative label".
        if ns in label and target in label:
            if '.' in target:
                category, item = tuple(target.split('.', 1))
                label = item
                # Strip everything before and including the first hash.
                if '#' in label:
                    label = label.split('#', 1)[1]
            else:
                label = target
        # Ignore if the target does not contain a dot.
        if not '.' in target:
            return target
        # Now, use dddoc's logic to generate the appropriate file name for
        file_name = getFilename(*target.split('.', 1))
        span = [gb.tag.span(genshi.HTML('&nbsp;'), class_='icon'), label]
        title = ' "%s" in SeqAn documentation.' % target
        return gb.tag.a(span,
                        class_='doc-link',
                        href=self.base_url + file_name,
                        title=title)
Example #7
0
 def _format_about(self, about):
     about_formatted = ckan.misc.MarkdownFormat().to_html(about)
     try:
         html = genshi.HTML(about_formatted)
     except genshi.ParseError, e:
         log.error('Could not print "about" field Field: %r Error: %r', about, e)
         html = _('Error: Could not parse About text')
Example #8
0
 def chart(self, id=None):
     self._get_data(id)
     if c.error:
         return self.help()
     c.html_table = genshi.XML(self.get_html_table(self.tabular))
     c.chart_code = genshi.HTML(self._get_chart_code(self.tabular))
     return render('plot/chart', strip_whitespace=False)
Example #9
0
    def table(self, id=None):
        if id is None:
            abort(404)
        c.table = self.dbmod.PesaTable.query.get(int(id))
        if c.table is None:
            abort(404)
        c.expenditures = self.dbmod.Expenditure.query.\
                filter_by(pesatable=c.table).\
                order_by(self.dbmod.Expenditure.title).\
                order_by(self.dbmod.Expenditure.date).all()
        # from formalchemy import FieldSet, Field, Grid
        # c.grid = Grid(self.dbmod.Expenditure, c.expenditures).render()
        # c.grid = genshi.HTML(c.grid)
        # fs = FieldSet(c.table)
        td = swiss.tabular.TabularData()
        td.header = ['Year', 'Title', 'Amount']
        td.data = [[e.date, e.title, e.amount] for e in c.expenditures]
        tdout = swiss.tabular.pivot(td, 'Year', 'Title', 'Amount')
        # tdouttable = swiss.tabular.pivot(td,'Title','Year','Amount')

        plotctr = econ.www.controllers.plot.PlotController()
        c.html_table = genshi.XML(plotctr.get_html_table(tdout))
        c.chart_code = genshi.HTML(plotctr._get_chart_code(tdout))

        return render('wdmmg/table')
Example #10
0
    def _get_package(self, id):
        """
        Given an ID use the logic layer to fetch the Package and a
        dict representation of it as well as adding formatted notes
        and the publisher to the template context (c).
        """
        import ckan.misc
        import genshi

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'extras_as_string': True,
            'for_view': True
        }

        try:
            c.pkg_dict = get_action('package_show')(context, {'id': id})
            c.pkg = context['package']
        except ObjectNotFound:
            abort(404, _('Dataset not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % id)

        groups = c.pkg.get_groups('publisher')
        if groups:
            c.publisher = groups[0]
        else:
            log.warning("Package {0} is not a member of any group!".format(id))

        # Try and render the notes as markdown for display on the page.  Most
        # unpublished items *won't* be markdown if they've come directly from the
        # CSV - unless they've been edited.
        try:
            notes_formatted = ckan.misc.MarkdownFormat().to_html(c.pkg.notes)
            c.pkg_notes_formatted = genshi.HTML(notes_formatted)
            c.release_notes_formatted = None

            notes = unpublished_release_notes(c.pkg_dict)
            if notes and notes.strip():
                c.release_notes_formatted = genshi.HTML(
                    ckan.misc.MarkdownFormat().to_html(notes))
        except Exception:
            c.pkg_notes_formatted = c.pkg.notes
Example #11
0
 def read(self, id):
     context = {'model': model, 'session': model.Session,
                'user': c.user or c.author,
                'schema': self._form_to_db_schema()}
     data_dict = {'id': id}
     try:
         c.group_dict = get_action('group_show')(context, data_dict)
         c.group = context['group']
     except NotFound:
         abort(404, _('Group not found'))
     except NotAuthorized:
         abort(401, _('Unauthorized to read group %s') % id)
     try:
         description_formatted = ckan.misc.MarkdownFormat().to_html(c.group.get('description',''))
         c.description_formatted = genshi.HTML(description_formatted)
     except Exception, e:
         error_msg = "<span class='inline-warning'>%s</span>" % _("Cannot render description")
         c.description_formatted = genshi.HTML(error_msg)
Example #12
0
def sanitize(html, encoding='utf8'):
    """Removes unsafe tags and attributes from html and adds
    ``rel="nofollow"`` attribute to all external links.
    Using encoding=None if passing Unicode strings.
    encoding="utf8" matches default format for earlier versions of Genshi
    https://genshi.readthedocs.io/en/latest/upgrade/#upgrading-from-genshi-0-6-x-to-the-development-version
    """

    # Can't sanitize unless genshi module is available
    if genshi is None:
        return html

    def get_nofollow(name, event):
        attrs = event[1][1]
        href = attrs.get('href', '')

        if href:
            # add rel=nofollow to all absolute links
            _, host, _, _, _ = urlsplit(href)
            if host:
                return 'nofollow'

    try:
        html = genshi.HTML(html, encoding=encoding)

    # except (genshi.ParseError, UnicodeDecodeError, UnicodeError) as e:
    # don't catch Unicode errors so we can tell if we're getting bytes
    except genshi.ParseError:
        if BeautifulSoup:
            # Bad html. Tidy it up using BeautifulSoup
            html = str(BeautifulSoup(html, "lxml"))
            try:
                html = genshi.HTML(html)
            except Exception:
                # Failed to sanitize.
                # We can't do any better than returning the original HTML, without sanitizing.
                return html
        else:
            raise

    stream = (html
              | genshi.filters.HTMLSanitizer()
              | genshi.filters.Transformer("//a").attr("rel", get_nofollow))
    return stream.render()
Example #13
0
 def view(self, id):
     res = model.Resource.query.get(id)
     if not res:
         abort(404)
     if res.material:
         c.title = res.material.title
     else:
         c.title = ''
     c.work = res.material.work
     c.texthtml = genshi.HTML(render_resource(res))
     # strip_whitespace does not work with pylons 0.9.7
     return render('text/view.html')
Example #14
0
    def view(self, id=None):
        c.work = model.Work.by_name(id)
        if c.work is None:
            abort(404)

        c.annotator_enabled = True
        # should be guaranteed not to be a pdf ...
        material = c.work.default_material
        resource = c.work.default_resource

        c.title = material.title
        c.content = genshi.HTML(render_resource(resource))
        return render('work/view.html')
Example #15
0
    def read(self, id):
        from ckan.lib.search import SearchError
        import genshi

        group_type = self._get_group_type(id.split('@')[0])
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': self._form_to_db_schema(group_type=type)}
        data_dict = {'id': id}
        q = c.q = request.params.get('q', '') # unicode format (decoded from utf8)
        fq = ''
        c.is_sysadmin = Authorizer().is_sysadmin(c.user)

        # TODO: Deduplicate this code copied from index()
        # TODO: Fix this up, we only really need to do this when we are
        # showing the hierarchy (and then we should load on demand really).
        c.all_groups = model.Session.query(model.Group).\
                       filter(model.Group.type == 'publisher').\
                       filter(model.Group.state == 'active').\
                       order_by('title')

        try:
            c.group_dict = get_action('group_show')(context, data_dict)
            c.group = context['group']
        except ObjectNotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % id)

        # Search within group
        fq += ' parent_publishers: "%s"' % c.group_dict.get('name')

        description = c.group_dict.get('description','').replace('&amp;', '&')
        try:
            description_formatted = ckan.misc.MarkdownFormat().to_html(description)
            c.description_formatted = genshi.HTML(description_formatted)
        except Exception, e:
            error_msg = "<span class='inline-warning'>%s</span>" % _("Cannot render description")
            c.description_formatted = genshi.HTML(error_msg)
Example #16
0
def sanitize(html):
    """Removes unsafe tags and attributes from html and adds
    ``rel="nofollow"`` attribute to all external links.
    """

    # Can't sanitize unless genshi module is available
    if genshi is None:
        return html

    def get_nofollow(name, event):
        attrs = event[1][1]
        href = attrs.get('href', '')

        if href:
            # add rel=nofollow to all absolute links
            _, host, _, _, _ = urlparse.urlsplit(href)
            if host:
                return 'nofollow'

    try:
        html = genshi.HTML(html)
    except (genshi.ParseError, UnicodeDecodeError, UnicodeError):
        if BeautifulSoup:
            # Bad html. Tidy it up using BeautifulSoup
            html = str(BeautifulSoup(html, "lxml"))
            try:
                html = genshi.HTML(html)
            except Exception:
                # Failed to sanitize.
                # We can't do any better than returning the original HTML, without sanitizing.
                return html
        else:
            raise

    stream = html \
        | genshi.filters.HTMLSanitizer() \
        | genshi.filters.Transformer("//a").attr("rel", get_nofollow)
    return stream.render()
Example #17
0
 def download_adder(stream):
     download_html = '''<span class="downloads-count">
     [downloaded %s times]</span>'''
     count = None
     for mark, (kind, data, pos) in stream:
         if mark and kind == genshi.core.START:
             href = data[1].get('href')
             if href:
                 count = dbutil.get_resource_visits_for_url(href)
         if count and mark is genshi.filters.transform.EXIT:
             # emit count
             yield genshi.filters.transform.INSIDE, (
                 genshi.core.TEXT,
                 genshi.HTML(download_html % count), pos)
         yield mark, (kind, data, pos)
Example #18
0
    def spend(self):
        a = d.Analyzer()
        entries, years = a.extract_simple()
        expenditure = entries['Public sector current expenditure']
        td = swiss.tabular.TabularData(header=['Year'], data=[years])
        for k, v in entries.items():
            td.header.append(k)
            td.data.append(v)
        td.data = swiss.tabular.transpose(td.data)

        import econ.www.controllers.plot
        plotctr = econ.www.controllers.plot.PlotController()
        c.html_table = genshi.XML(plotctr.get_html_table(td))
        c.chart_code = genshi.HTML(plotctr._get_chart_code(td))
        c.fig_title = u'UK Government Expenditure (Millions)'
        return render('wdmmg/spend')
Example #19
0
 def read(self, id):
     c.group = model.Group.get(id)
     if c.group is None:
         abort(404)
     auth_for_read = self.authorizer.am_authorized(c, model.Action.READ, c.group)
     if not auth_for_read:
         abort(401, _('Not authorized to read %s') % id.encode('utf8'))
     
     import ckan.misc
     format = ckan.misc.MarkdownFormat()
     desc_formatted = format.to_html(c.group.description)
     try: 
         desc_formatted = genshi.HTML(desc_formatted)
     except genshi.ParseError, e:
         log.error('Could not print group description: %r Error: %r', c.group.description, e)
         desc_formatted = 'Error: Could not parse group description'
Example #20
0
 def view(self, id):
     c.pkg = self._get_package(id)
     c.metadata_keys = [
         k for k in c.pkg.metadata.key_list if getattr(c.pkg, k)
     ]
     # limit to a maximum to avoid problems with huge datasets
     c.data_limit = 1000
     c.plot_data_url = h.url_for(controller='plot',
                                 action='chart',
                                 id=id,
                                 limit='[:%s]' % c.data_limit)
     import econ.www.controllers.plot
     plotctr = econ.www.controllers.plot.PlotController()
     plotctr._get_data(id, limit='[:%s]' % c.data_limit)
     try:
         c.html_table = genshi.XML(plotctr.get_html_table(plotctr.tabular))
         c.chart_code = genshi.HTML(plotctr._get_chart_code(
             plotctr.tabular))
     except Exception, inst:
         c.error = 'Problem displaying graph or table for data'
Example #21
0
    def view(self, id=None):
        countries = request.params.getall('countries')
        series = request.params.get('series')
        try:
            c.series = self.dbmod.Series.query.get(series)
        except:
            h.redirect_to(controller='mdg', action='index', id=None)
        c.values = self.dbmod.Value.query.filter(
            self.dbmod.Value.country_code.in_(countries)).filter_by(
                series_code=series).all()
        c.countries = [
            self.dbmod.Country.query.get(ctry) for ctry in countries
        ]
        td = self._cvt_values_to_tabular(c.values)

        import econ.www.controllers.plot
        plotctr = econ.www.controllers.plot.PlotController()
        c.html_table = genshi.XML(plotctr.get_html_table(td))
        c.chart_code = genshi.HTML(plotctr._get_chart_code(td))
        # return render('plot/chart', strip_whitespace=False)
        return render('mdg/view')
Example #22
0
    def myseries(self, id=None):
        # overloading one url to be both add and view ...
        self._handle_series_changes()
        # now do display
        # from pylons import session
        c.programmes = []
        for seriesid in session['datasets']:
            dataset_code, id = seriesid.split('---')
            if dataset_code == 'cra':
                prg = self.dbmodcra.Area.query.get(id)
                c.programmes.append(prg)

        td = swiss.tabular.TabularData()
        td.header = ['Year', 'Title', 'Amount']
        for prg in c.programmes:
            td.data += [[e.year, prg.title + '-' + prg.region, e.amount]
                        for e in prg.expenditures]
        tdout = swiss.tabular.pivot(td, 'Year', 'Title', 'Amount')
        plotctr = econ.www.controllers.plot.PlotController()
        c.html_table = genshi.XML(plotctr.get_html_table(tdout))
        c.chart_code = genshi.HTML(plotctr._get_chart_code(tdout))
        return render('wdmmg/myseries')
Example #23
0
    def view(self, id=None):
        format = request.params.get('format', 'plain')
        text1 = request.params.get('text_1', None)
        text2 = request.params.get('text_2', None)
        if not text1 or not text2:
            c.error = 'Texts incorrectly specified'
            return render('multi/view.html')

        namelist = [text1, text2]
        numtexts = len(namelist)
        textlist = [model.Material.by_name(tname) for tname in namelist]
        texthtml = {}
        for item in textlist:
            tfileobj = item.get_text()
            # TODO: check format
            ttext = shakespeare.format.format_text(tfileobj, format)
            texthtml[item.name] = genshi.HTML(ttext)
        c.frame_width = 100.0 / numtexts - 4.0
        c.textlist = textlist
        c.texthtml = texthtml
        # set to not strip whitespace as o/w whitespace in pre tag gets removed
        # strip_whitespace does not work with pylons 0.9.7
        # return render('multi/view.html', strip_whitespace=False)
        return render('multi/view.html')
Example #24
0
    def config(self,
               config_timestamp=0,
               load_defaults=False,
               cancel=False,
               apply=False,
               export_config=False,
               new_config=None,
               import_config=False,
               **data):
        error = None
        values = None

        if cancel:
            raise cherrypy.HTTPRedirect('/')
        elif export_config:
            # use cherrypy utility to push the file for download. This also
            # means that we don't have to move the config file into the
            # web-accessible filesystem hierarchy
            return cherrypy.lib.static.serve_file(
                os.path.realpath(self._config.filename),
                "application/x-download", "attachment",
                os.path.basename(self._config.filename))
        elif apply:
            # if someone else has modified the config, then warn the user
            # before saving their changes (overwriting the other's changes)
            if int(config_timestamp) == self._config.getTimestamp():
                self.updateConfigFromPostData(self._config, data)

                # update file
                try:
                    self._config.saveToFile()
                    self._config.exportForShell(self._config.filename + ".sh")
                    # bounce back to homepage
                    raise cherrypy.HTTPRedirect('/')
                except IOError as e:
                    # if save failed, put up error message and stay on the page
                    error = 'Error saving: %s' % e
            else:
                error = genshi.HTML('''WARNING:
                        Configuration has been changed externally.<br />
                        If you wish to keep your changes and lose the external
                        changes, then click on 'Apply' again. <br />
                        To lose your changes and preserve the external changes,
                        click 'Cancel'.''')
                # load the post data into a temporary configparser to preserve
                # the user's changes when the page is loaded again. This means
                # we don't have to duplicate the horrible POST-to-config code
                temp_conf = ConfigParser()
                self.updateConfigFromPostData(temp_conf, data)
                values = temp_conf.getValues()
                # the page loading below will send the new config timestamp so
                # we don't have to anything else here.

        if load_defaults:
            values = self._config.getDefaultValues()
        elif import_config:
            if new_config.filename:
                try:
                    values = self._config.parseFile(new_config.file)
                except Exception as e:
                    values = None
                    error = 'Unable to parse config file: "%s"' % e
            else:
                error = 'No filename provided for config import'

        if not values:
            values = self._config.getValues()
        return template.render(station=self.getStationName(),
                               config_timestamp=self._config.getTimestamp(),
                               error=error,
                               using_defaults=load_defaults,
                               values=values,
                               file=self._config.filename,
                               defaults_file=self._config.defaults_filename)
Example #25
0
    def filter(self, stream):
        '''Insert Google Analytics code into legacy Genshi templates.

        This is called by CKAN whenever any page is rendered, _if_ using old
        CKAN 1.x legacy templates. If using new CKAN 2.0 Jinja templates, the
        template helper methods below are used instead.

        See IGenshiStreamFilter.

        '''
        log.info("Inserting Google Analytics code into template")

        # Add the Google Analytics tracking code into the page header.
        header_code = genshi.HTML(
            gasnippet.header_code %
            (self.googleanalytics_id, self.googleanalytics_domain))
        stream = stream | genshi.filters.Transformer('head').append(
            header_code)

        # Add the Google Analytics Event Tracking script into the page footer.
        if self.track_events:
            footer_code = genshi.HTML(gasnippet.footer_code %
                                      self.googleanalytics_javascript_url)
            stream = stream | genshi.filters.Transformer(
                'body/div[@id="scripts"]').append(footer_code)

        routes = pylons.request.environ.get('pylons.routes_dict')
        action = routes.get('action')
        controller = routes.get('controller')

        if ((controller == 'package'
             and action in ['search', 'read', 'resource_read'])
                or (controller == 'group' and action == 'read')):

            log.info("Tracking of resource downloads")

            # add download tracking link
            def js_attr(name, event):
                attrs = event[1][1]
                href = attrs.get('href').encode('utf-8')
                link = '%s%s' % (self.googleanalytics_resource_prefix,
                                 urllib.quote(href))
                js = "javascript: _gaq.push(['_trackPageview', '%s']);" % link
                return js

            # add some stats
            def download_adder(stream):
                download_html = '''<span class="downloads-count">
                [downloaded %s times]</span>'''
                count = None
                for mark, (kind, data, pos) in stream:
                    if mark and kind == genshi.core.START:
                        href = data[1].get('href')
                        if href:
                            count = dbutil.get_resource_visits_for_url(href)
                    if count and mark is genshi.filters.transform.EXIT:
                        # emit count
                        yield genshi.filters.transform.INSIDE, (
                            genshi.core.TEXT,
                            genshi.HTML(download_html % count), pos)
                    yield mark, (kind, data, pos)

            # perform the stream transform
            stream = stream | genshi.filters.Transformer(
                '//a[contains(@class, "resource-url-analytics")]').attr(
                    'onclick', js_attr)

            if (self.show_downloads and action == 'read'
                    and controller == 'package'):
                stream = stream | genshi.filters.Transformer(
                    '//a[contains(@class, "resource-url-analytics")]').apply(
                        download_adder)
                stream = stream | genshi.filters.Transformer('//head').append(
                    genshi.HTML(gasnippet.download_style))

        return stream
Example #26
0
class GroupController(BaseController):

    ## hooks for subclasses
    group_form = 'group/new_group_form.html'

    def _form_to_db_schema(self):
        return group_form_schema()

    def _db_to_form_schema(self):
        '''This is an interface to manipulate data from the database
        into a format suitable for the form (optional)'''

    def _setup_template_variables(self, context):
        c.is_sysadmin = Authorizer().is_sysadmin(c.user)

        ## This is messy as auths take domain object not data_dict
        context_group = context.get('group', None)
        group = context_group or c.group
        if group:
            try:
                if not context_group:
                    context['group'] = group
                check_access('group_change_state', context)
                c.auth_for_change_state = True
            except NotAuthorized:
                c.auth_for_change_state = False

    ## end hooks

    def index(self):

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author
        }

        data_dict = {'all_fields': True}

        try:
            check_access('site_read', context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        results = get_action('group_list')(context, data_dict)

        c.page = Page(collection=results,
                      page=request.params.get('page', 1),
                      url=h.pager_url,
                      items_per_page=20)
        return render('group/index.html')

    def read(self, id):
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'schema': self._form_to_db_schema()
        }
        data_dict = {'id': id}
        try:
            c.group_dict = get_action('group_show')(context, data_dict)
            c.group = context['group']
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % id)
        try:
            description_formatted = ckan.misc.MarkdownFormat().to_html(
                c.group.get('description', ''))
            c.description_formatted = genshi.HTML(description_formatted)
        except Exception, e:
            error_msg = "<span class='inline-warning'>%s</span>" % _(
                "Cannot render description")
            c.description_formatted = genshi.HTML(error_msg)

        try:
            desc_formatted = ckan.misc.MarkdownFormat().to_html(
                c.group.description)
            desc_formatted = genshi.HTML(desc_formatted)
        except genshi.ParseError, e:
            desc_formatted = 'Error: Could not parse group description'
Example #27
0
                                              filter_finish, selected_date,
                                              selected_recording).showMonth()
        else:
            calendar = ('<h2>Unimplemented</h2>'
                        'That calendar format is not supported')

        return template.render(is_proxy=True,
                               station=station,
                               errors=errors,
                               station_names=station_names,
                               schedule_titles=schedule_titles,
                               filter_station=filter_station,
                               filter_title=filter_title,
                               filter_start=formatDateUI(filter_start),
                               filter_finish=formatDateUI(filter_finish),
                               calendar=genshi.HTML(calendar),
                               selected_date=selected_date,
                               selected_recording=selected_recording,
                               selected_recordings=selected_recordings,
                               selected_action_mode=selected_action_mode,
                               selected_action_size=selected_action_size,
                               transfer_queue_ids=transfer_queue_ids)

    @cherrypy.expose
    @template.output('export.html')
    def export(self,
               filter_start=None,
               filter_finish=None,
               filter_station=None,
               export_partial=None,
               start_type=None,