示例#1
0
    def default(self, obj):
        model = model_instance()
        if isinstance(obj, model.AuthenticatedUser):
            return {"uid": obj.uid, "username": obj.username, "email": obj.email}

        if isinstance(obj, model.Balance):
            return {
                "uid": obj.uid,
                "name": obj.name,
                "users": [{"user_uid": user.user_uid, "writable": user.writable} for user in obj.users],
            }

        if isinstance(obj, model.BalanceChange):
            return {
                "uid": obj.uid,
                "amount": obj.amount,
                "category_uid": obj.is_income and obj.income_category_uid or obj.expense_category_uid,
                "description": obj.description,
                "tags": obj.tags_as_string(),
            }

        if isinstance(obj, Decimal):
            return babel.numbers.format_decimal(obj, locale=get_lang()[0]).replace(
                babel.numbers.get_group_symbol(locale=get_lang()[0]), " "
            )

        if isinstance(obj, date) or isinstance(obj, datetime):
            return str(obj)
        return simplejson.JSONEncoder.default(self, obj)
示例#2
0
def repliesProxy(thread, controller):
    user = controller.userInst
    # flags = (isBoardView, showLongMessages)
    intFlags = (int(bool(c.board)) << 1) + int(not (user.hideLongComments) or
                                               (c.count == 1))
    tmplPrefix = (len(g.OPT.templates) > 1 and user.template) or ''
    keyPrefix = str('%s%d%s' % (tmplPrefix, intFlags, get_lang()[0]))
    postPairs = []
    for post in thread.Replies:
        postPairs.append((post.id, post))
        if c.userInst.hlOwnPosts and c.userInst.ownPost(
                post):  #post.uidNumber == c.userInst.uidNumber:
            c.userPostsToHighlight.append(post.id)
    postsDict = dict(postPairs)
    postsRender = g.mc.get_multi(postsDict.keys(), key_prefix=keyPrefix)
    absentPosts = list(set(postsDict.keys()) - set(postsRender.keys()))
    if absentPosts:
        absentPostsRender = dict([(post,
                                   doFastRender(postsDict[post], thread,
                                                controller))
                                  for post in absentPosts])
        g.mc.set_multi(absentPostsRender, key_prefix=keyPrefix)
        postsRender.update(absentPostsRender)
    sortedPostsRender = list(
        [postsRender[id] for id in sorted(postsRender.keys())])
    return ''.join(sortedPostsRender)
示例#3
0
    def getMenuItems(self, menuId):
        def itemsscmp(a, b):
            return cmp(a.weight, b.weight)

        langMenuId = menuId + get_lang()[0]
        mitems = self.menuCache.get(langMenuId, None)
        if not mitems:
            parentedItems = {}
            uniqueIds = []
            menuProviders = self.implementationsOf(AbstractMenuProvider)
            for plugin in menuProviders:
                items = plugin.menuItemsFor(menuId)
                if items:
                    for item in items:
                        id = item.id
                        if id in uniqueIds:
                            _log.error('Duplicated menu item Ids: %s' % id)
                        else:
                            uniqueIds.append(id)
                        parentid = item.parentId
                        item.plugin = plugin

                        if not parentid in parentedItems:
                            parentedItems[parentid] = []
                        parentedItems[parentid].append(item)

            for key in parentedItems.keys():
                parentedItems[key] = sorted(parentedItems[key], itemsscmp)
            self.menuCache[langMenuId] = parentedItems
            mitems = parentedItems
        return mitems
示例#4
0
def get_translator(lang=None):
    """
    return a GNUTranslations instance for `lang`::

        >>> translator = get_translator('fr')
        ... assert translator.gettext('Remove') == 'Supprimer'
        ... assert translator.gettext('month_01') == 'Janvier'
        >>> translator = get_translator('en')
        ... assert translator.gettext('Remove') == 'Remove'
        ... assert translator.gettext('month_01') == 'January'

    """
    # get possible fallback languages
    try:
        langs = get_lang() or []
    except TypeError:
        # this occurs when Pylons is available and we are not in a valid thread
        langs = []

    # insert lang if provided
    if lang and lang not in langs:
        langs.insert(0, lang)

    if not langs:
        langs = ['en']

    # get the first available catalog
    for lang in langs:
        filename = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
        if os.path.isfile(filename):
            translations_path = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
            return GNUTranslations(open(translations_path, 'rb'))

    # dummy translator
    return _Translator()
示例#5
0
def handle_request(request, tmpl_context):
    from pylons import session

    tmpl_context.language = locale = None
    if 'locale' in session:
        locale = Locale.parse(session.get('locale'))
    else:
        requested = [l.replace('-', '_') for l in request.languages]
        locale = Locale.parse(Locale.negotiate(get_available_languages(), requested))

    if locale is None:
        locale = get_default_locale()

    tmpl_context.locale = locale

    options = [str(locale), locale.language, str(get_default_locale()),
        get_default_locale().language]
    for language in options:
        try:
            set_lang(language)
            # Lose the territory part of the locale string
            tmpl_context.language = get_lang()[0].split('_')[0]
            break
        except:
            pass
示例#6
0
文件: js.py 项目: minrenmtv/reddit
    def use(self, **kwargs):
        from pylons.i18n import get_lang
        from r2.lib.template_helpers import static
        from r2.lib.filters import SC_OFF, SC_ON

        if g.uncompressedJS:
            if c.lang == "en" or c.lang not in g.all_languages:
                # in this case, the msgids *are* the translated strings and we
                # can save ourselves the pricey step of lexing the js source
                return Module.use(self, **kwargs)

            msgids = extract_javascript_msgids(Module.get_source(self))
            localized_appendices = self.localized_appendices + [
                StringsSource(msgids)
            ]

            lines = [Module.use(self, **kwargs)]
            for appendix in localized_appendices:
                line = SC_OFF + inline_script_tag.format(
                    content=appendix.get_localized_source(c.lang)) + SC_ON
                lines.append(line)
            return "\n".join(lines)
        else:
            langs = get_lang() or [g.lang]
            url = LocalizedModule.languagize_path(self.name, langs[0])
            return script_tag.format(src=static(url), **kwargs)
示例#7
0
def handle_request(request, tmpl_context):
    from pylons import session

    tmpl_context.language = locale = None
    if 'locale' in session:
        locale = Locale.parse(session.get('locale'))
    else:
        requested = [l.replace('-', '_') for l in request.languages]
        locale = Locale.parse(
            Locale.negotiate(get_available_languages(), requested))

    if locale is None:
        locale = get_default_locale()

    tmpl_context.locale = locale

    options = [
        str(locale), locale.language,
        str(get_default_locale()),
        get_default_locale().language
    ]
    for language in options:
        try:
            set_lang(language)
            # Lose the territory part of the locale string
            tmpl_context.language = get_lang()[0].split('_')[0]
            break
        except:
            pass
    def _save_new(self, context, group_type=None):
        try:
            data_dict = clean_dict(dict_fns.unflatten(
                tuplize_dict(parse_params(request.params))))
            data_dict['type'] = group_type or 'group'
            context['message'] = data_dict.get('log_message', '')
            data_dict['users'] = [{'name': c.user, 'capacity': 'admin'}]
            group = self._action('group_create')(context, data_dict)

            log.info('::::: Persisting localised metadata locale :::::')
            lang = get_lang()[0]

            session = model.Session
            try:
                session.add_all([
                    GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='title', lang=lang, text=group.get('title')),
                    GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='description', lang=lang, text=group.get('description')),
                ])

                session.commit()
            except Exception, e:
                # on rollback, the same closure of state
                # as that of commit proceeds. 
                session.rollback()

                log.error('Exception occurred while persisting DB objects: %s', e)
                raise

            # Redirect to the appropriate _read route for the type of group
            h.redirect_to(group['type'] + '_read', id=group['name'])
    def _save_edit(self, id, context):
        try:
            data_dict = clean_dict(dict_fns.unflatten(
                tuplize_dict(parse_params(request.params))))
            context['message'] = data_dict.get('log_message', '')
            data_dict['id'] = id
            context['allow_partial_update'] = True
            group = self._action('group_update')(context, data_dict)
            if id != group['name']:
                self._force_reindex(group)

            log.info(':::::::::::: Saving the corresponding localized title and abstract :::::::::::::::')

            lang = get_lang()[0]

            q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == group.get('id')).all()

            create_new = False
            if q_results:
                available_db_lang = []

                for result in q_results:
                    if result.lang not in available_db_lang:
                        available_db_lang.append(result.lang)

                    # check if the group identifier name has been changed
                    if result.name != group.get('name'):
                        result.name = group.get('name')
                        result.save()

                if lang not in available_db_lang:
                    create_new = True
                else:
                    for result in q_results:
                        if result.lang == lang:
                            result.text = group.get(result.field)
                            result.save()
            else:
                create_new = True

            if create_new == True:
                log.info(':::::::::::: Localized fields are missing in package_multilang table, persisting defaults using values in the table group :::::::::::::::')
                session = model.Session
                try:
                    session.add_all([
                        GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='title', lang=lang, text=group.get('title')),
                        GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='description', lang=lang, text=group.get('description')),
                    ])

                    session.commit()
                except Exception, e:
                    # on rollback, the same closure of state
                    # as that of commit proceeds. 
                    session.rollback()

                    log.error('Exception occurred while persisting DB objects: %s', e)
                    raise

            h.redirect_to('%s_read' % group['type'], id=group['name'])
示例#10
0
 def login(self):
     """
     This is where the login form should be rendered.
     Without the login counter, we won't be able to tell if the user has
     tried to log in with wrong credentials
     """    
     came_from = request.params.get('came_from', None)
     identity = request.environ.get('repoze.who.identity')                
     if identity:                      
         return render(path.join(get_lang()[0],'derived/account/login.mako'))
     else:
         c.login_counter = request.environ['repoze.who.logins'] + 1                
         if came_from:
             session['came_from'] = came_from
             session.save()                
             return render(path.join(get_lang()[0],'derived/account/logindialog.mako'))
         return render(path.join(get_lang()[0],'derived/account/login.mako'))
示例#11
0
文件: i18n.py 项目: tbalaz/test
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    langs = i18n.get_lang()
    if langs:
        return langs[0]
    else:
        return 'hr'
示例#12
0
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    langs = i18n.get_lang()
    if langs:
        return langs[0]
    else:
        return 'en'
示例#13
0
def setLang(lang):
    oldLang = get_lang()
    if (lang and (len(lang) == 2)):
        set_lang(lang)
    else:
        langToSet = langForCurrentRequest()
        set_lang(langToSet)  # TODO: check
    return oldLang[0]
示例#14
0
def render_customer_form(
    menu_items, id, values=None, action=None, errors=None, add_number_of_addresses=0, add_number_of_phones=0
):
    c.number_of_addresses = number_of_addresses(values) + add_number_of_addresses
    c.number_of_phones = number_of_phones(values) + add_number_of_phones
    c.menu_items = h.top_menu(menu_items, _("Customers"))
    c.id = id
    html = render(path.join(get_lang()[0], "derived/user/customer/edit.mako"))
    return htmlfill.render(html, defaults=values, errors=errors)
示例#15
0
文件: js.py 项目: barneyfoxuk/reddit
 def use(self):
     from pylons.i18n import get_lang
     from r2.lib.template_helpers import static
     embed = Module.use(self)
     if g.uncompressedJS:
         return embed + StringsSource().use()
     else:
         url = LocalizedModule.languagize_path(self.name, get_lang()[0])
         return script_tag.format(src=static(url))
示例#16
0
文件: js.py 项目: LDot/reddit
 def use(self):
     from pylons.i18n import get_lang
     from r2.lib.template_helpers import static
     embed = Module.use(self)
     if g.uncompressedJS:
         return embed + StringsSource().use()
     else:
         url = LocalizedModule.languagize_path(self.name, get_lang()[0])
         return script_tag.format(src=static(url))
示例#17
0
 def menuItemsFor(self, menuId):
     ret = None
     id = menuId + get_lang()[0]
     if not getattr(self, "__pmenuItems", None): # we don't want to write constructor only for this variable
         self.__pmenuItems = {}
     ret = self.__pmenuItems.get(id, False)
     if not ret:
         ret = self.menuItems(menuId)
         self.__pmenuItems[id] = ret
     return ret
示例#18
0
文件: js.py 项目: DeanHyde/reddit
 def use(self):
     from pylons.i18n import get_lang
     from r2.lib.template_helpers import static
     embed = Module.use(self)
     if g.uncompressedJS:
         return embed + StringsSource().use()
     else:
         name, ext = os.path.splitext(self.name)
         url = os.path.join(g.static_path, name + "." + get_lang()[0] + ext)
         return script_tag.format(src=static(url))
示例#19
0
文件: i18n.py 项目: CIOIL/DataGovIL
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    if is_flask_request():
        from ckan.config.middleware.flask_app import get_locale
        return get_locale()
    else:
        langs = i18n.get_lang()
        if langs:
            return langs[0]
    return 'en'
示例#20
0
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    if is_flask_request():
        from ckan.config.middleware.flask_app import get_locale
        return get_locale()
    else:
        langs = i18n.get_lang()
        if langs:
            return langs[0]
    return 'en'
示例#21
0
文件: root.py 项目: vigilo/vigigraph
    def i18n(self):
        import gettext
        import pylons
        import os.path

        # Repris de pylons.i18n.translation:_get_translator.
        conf = pylons.config.current_conf()
        try:
            rootdir = conf['pylons.paths']['root']
        except KeyError:
            rootdir = conf['pylons.paths'].get('root_path')
        localedir = os.path.join(rootdir, 'i18n')

        lang = get_lang()

        # Localise le fichier *.mo actuellement chargé
        # et génère le chemin jusqu'au *.js correspondant.
        filename = gettext.find(conf['pylons.package'], localedir,
            languages=lang)
        js = filename[:-3] + '.js'
        # Récupère et envoie le contenu du fichier de traduction *.js.
        fhandle = open(js, 'r')
        translations = fhandle.read()
        fhandle.close()

        # Même chose pour les thèmes
        themes_filename = gettext.find(
            'vigilo-themes',
            resource_filename('vigilo.themes.i18n', ''),
            languages=lang)
        themes_js = themes_filename[:-3] + '.js'
        fhandle = open(themes_js, 'r')
        translations += fhandle.read()
        fhandle.close()

        # Extensions Enterprise
        try:
            ent_filename = gettext.find(
                'vigilo-vigigraph-enterprise',
                resource_filename('vigilo.vigigraph_enterprise.i18n', ''),
                languages=lang)
        except ImportError:
            pass
        else:
            # Le nom du fichier sera None s'il n'existe pas
            # de traductions dans la langue demandée.
            if ent_filename is not None:
                fhandle = open(ent_filename[:-3] + '.js', 'r')
                translations += fhandle.read()
                fhandle.close()

        return translations
示例#22
0
def _month_details(cls, stat_key=None):
    '''
    Returns a list of all the periods for which we have data and the date we've
    got data up to in the latest month.

    e.g. ([(u'2014-11', 'November 2014'),
           (u'2014-10', 'October 2014'),
           (u'2014-09', 'September 2014')],
           '27th')
       i.e. we have 3 months up to 27th November

    :param cls: GA_Stat or GA_Url

    unfortunately
    knows too much about the type of the cls being passed as GA_Url has a
    more complex query

    This may need extending if we add a period_name to the stats
    '''
    months = []
    day = None

    q = model.Session.query(cls.period_name, cls.period_complete_day)\
             .filter(cls.period_name!='All') \
             .distinct(cls.period_name)
    if stat_key:
        q = q.filter(cls.stat_name==stat_key)

    vals = q.order_by("period_name desc").all()

    lang = get_lang()
    #log.debug(lang)
    # If lang is None the actual language is english,
    # if lang is 'es' the actual language is spanish
    # otherwise the month is rendered in english language.
    if lang and lang[0] == 'es':
        # For the most recent month in spanish
        if vals and vals[0][1]:
            day = int(vals[0][1])
    else:
        # For the most recent month, add 'ordinal' to the day
        # e.g. '27' -> day='27th'
        if vals and vals[0][1]:
            day = int(vals[0][1])
            ordinal = 'th' if 11 <= day <= 13 \
                else {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
            day = "{day}{ordinal}".format(day=day, ordinal=ordinal)

    for m in vals:
        months.append((m[0], _get_month_name(m[0])))

    return months, day
示例#23
0
def fallback_trans(x):
    """For translating placeholder strings the user should never see
    in raw form, such as 'funny 500 message'.  If the string does not
    translate in the current language, falls back on the g.lang
    translation that we've hopefully already provided"""
    t = _(x)
    if t == x:
        l = get_lang()
        set_lang(g.lang, graceful_fail=True)
        t = _(x)
        if l and l[0] != g.lang:
            set_lang(l[0])
    return t
示例#24
0
def fallback_trans(x):
    """For translating placeholder strings the user should never see
    in raw form, such as 'funny 500 message'.  If the string does not
    translate in the current language, falls back on the g.lang
    translation that we've hopefully already provided"""
    t = _(x)
    if t == x:
        l = get_lang()
        set_lang(g.lang, graceful_fail = True)
        t = _(x)
        if l and l[0] != g.lang:
            set_lang(l[0])
    return t
示例#25
0
    def feed(self, filter=None, id=None):
        feed = feedgenerator.Rss201rev2Feed(
            title=_('%s packages' % config['debexpo.sitename']),
            link=config['debexpo.server'] + url('packages'),
            description=_('A feed of packages on %s' %
                          config['debexpo.sitename']),
            language=get_lang()[0])

        if filter == 'section':
            packages = self._get_packages(
                package_version_filter=(PackageVersion.section == id))

        elif filter == 'uploader':
            user = self._get_user(id)
            if user is not None:
                packages = self._get_packages(
                    package_filter=(Package.user_id == user.id))
            else:
                packages = []

        elif filter == 'maintainer':
            packages = self._get_packages(
                package_version_filter=(PackageVersion.maintainer == id))

        else:
            packages = self._get_packages()

        for item in packages:
            desc = _('Package %s uploaded by %s.' %
                     (item.name, item.user.name))

            desc += '<br/><br/>'

            if item.needs_sponsor:
                desc += _('Uploader is currently looking for a sponsor.')
            else:
                desc += _('Uploader is currently not looking for a sponsor.')

            desc += '<br/><br/>' + item.description.replace('\n', '<br/>')

            feed.add_item(title='%s %s' %
                          (item.name, item.package_versions[-1].version),
                          link=config['debexpo.server'] +
                          url('package', packagename=item.name),
                          description=desc,
                          unique_id=str(item.package_versions[-1].id))

        response.content_type = 'application/rss+xml'
        response.content_type_params = {'charset': 'utf8'}
        return feed.writeString('utf-8')
示例#26
0
 def document(self):
     """Render the error document"""
     request = self._py_object.request
     resp = request.environ.get('pylons.original_response')
     code = cgi.escape(request.GET.get('code', ''))
     content = cgi.escape(request.GET.get('message', ''))
     c.menu_items = h.top_menu(self.menu_items,_('Home')) 
     if resp:
         content = literal(resp.status)
         code = code or cgi.escape(str(resp.status_int))
     if not code:
         raise Exception("No Status code was found")
     c.code = code
     c.message = content
     return render(path.join(get_lang()[0],'derived/error/error.mako'))
示例#27
0
    def index(self, category="Main", page=1):
        c.lang = get_lang() 
        c.sites = []
        if not category:
            c.error = _("Sorry, there is no such category.")
            return redirect(url(controller="category", action="index"))

        c.category = CategoryModel.get_by_slug(category)
        c.site_name = str('name_'+c.lang[0])
        c.site_descr = str('description_'+c.lang[0])
        if c.category.id is None:
            c.error = _("Sorry, there is no such category.")
            c.category = CategoryModel.get_by_slug("Main")

        if int(c.category.is_leaf) == 1:
            c.sites = SiteModel.get_by_category(int(c.category.id),page,lang=c.lang)
            c.totals = CategoryModel().get_totals({'category_id':int(c.category.id)})
            c.pages = c.totals/20 + 1  if (c.totals/20) else c.totals/20
        c.cur_page = page
        c.slug = c.category.slug
        children = c.category.get_children()[1:]
        
        c.children = []
        for child in children:
            if re.search(u'[a-zA-Zа-яА-я]+', child[0].to_dict['title_'+c.lang[0]]):
                child[0].title = child[0].to_dict['title_'+c.lang[0]]
            if len(child)>0:
                for i in range(1,len(child)):
                    if re.search(u'[a-zA-Zа-яА-я]+', child[i][0].to_dict['title_'+c.lang[0]]):
                        child[i][0].title = child[i][0].to_dict['title_'+c.lang[0]]

            c.children.append(child)

        c.keywords = c.category.to_dict.get('keywords')
        c.description = c.category.to_dict.get('description')

        if re.search(u'[a-zA-Zа-яА-я]', c.category.to_dict['title_'+c.lang[0]]):
            c.category.title = c.category.to_dict['title_'+c.lang[0]]

        breadcrunchs = []
        if int(c.category.id) != 0:
            breadcrunchs =  CategoryModel.get_path(c.category)
        c.breadcrunchs = []
        for crunch in breadcrunchs:
            if re.search(u'[a-zA-Zа-яА-я]+', crunch.to_dict.get('title_'+c.lang[0],'')):
                crunch.title = crunch.to_dict['title_'+c.lang[0]]
            c.breadcrunchs.append(crunch)
        return render('/category/category.mako.html')
示例#28
0
    def index(self):
        group_type = self._guess_group_type()

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

        q = c.q = request.params.get('q', '')
        data_dict = {'all_fields': True, 'q': q, 'type': group_type or 'group'}
        sort_by = c.sort_by_selected = request.params.get('sort')
        if sort_by:
            data_dict['sort'] = sort_by
        try:
            self._check_access('site_read', context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        # pass user info to context as needed to view private datasets of
        # orgs correctly
        if c.userobj:
            context['user_id'] = c.userobj.id
            context['user_is_admin'] = c.userobj.sysadmin

        results = self._action('group_list')(context, data_dict)

        c.page = h.Page(
            collection=results,
            page = self._get_page_number(request.params),
            url=h.pager_url,
            items_per_page=21
        )

        log.info(':::::::::::: Retrieving the corresponding localized title and abstract :::::::::::::::')
        for item in c.page.items:   
            lang = get_lang()[0]
            
            q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == item.get('id'), GroupMultilang.lang == lang).all() 

            if q_results:
                for result in q_results:
                    item[result.field] = result.text
                    if result.field == 'title':
                        item['display_name'] = result.text


        return render(self._index_template(group_type),
                      extra_vars={'group_type': group_type})
示例#29
0
    def edit(self, id, data=None, errors=None, error_summary=None):
        group_type = self._ensure_controller_matches_group_type(
            id.split('@')[0])

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'save': 'save' in request.params,
                   'for_edit': True,
                   'parent': request.params.get('parent', None)
                   }
        data_dict = {'id': id, 'include_datasets': False}

        if context['save'] and not data:
            return self._save_edit(id, context)

        try:
            data_dict['include_datasets'] = False
            old_data = self._action('group_show')(context, data_dict)
            c.grouptitle = old_data.get('title')
            c.groupname = old_data.get('name')
            data = data or old_data
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % '')

        group = context.get("group")
        c.group = group
        c.group_dict = self._action('group_show')(context, data_dict)

        log.info(':::::::::::: Retrieving the corresponding localized title and abstract :::::::::::::::')

        lang = get_lang()[0]

        q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == data.get('id'), GroupMultilang.lang == lang).all()

        if q_results:
            for result in q_results:
                data[result.field] = result.text
                c.group_dict[result.field] = result.text
                if result.field == 'title':
                    c.group_dict['display_name'] = result.text

        try:
            self._check_access('group_update', context)
        except NotAuthorized, e:
            abort(401, _('User %r not authorized to edit %s') % (c.user, id))
示例#30
0
 def search(self):
     identity = request.environ.get("repoze.who.identity")
     c.menu_items = h.top_menu(self.menu_items, _("Customers"))
     c.tags = Session.query(UserTag.tag).all()
     action = request.params.getone("action")
     values = dict(request.params)
     del values["action"]
     schema = UserSearch()
     try:
         result = schema.to_python(values)
     except Invalid, e:
         html = render(path.join(get_lang()[0], "/derived/user/staff/index.html"))
         return htmlfill.render(
             html,
             defaults=values,
             errors=variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False),
         )
示例#31
0
文件: js.py 项目: songv/reddit
    def use(self):
        from pylons.i18n import get_lang
        from r2.lib.template_helpers import static

        if g.uncompressedJS:
            if c.lang == "en":
                # in this case, the msgids *are* the translated strings and we
                # can save ourselves the pricey step of lexing the js source
                return Module.use(self)

            msgids = extract_javascript_msgids(Module.get_source(self))
            strings = StringsSource(c.lang, msgids)
            return "\n".join(
                (Module.use(self), inline_script_tag.format(content=strings.get_plural_forms()), strings.use())
            )
        else:
            langs = get_lang() or [g.lang]
            url = LocalizedModule.languagize_path(self.name, langs[0])
            return script_tag.format(src=static(url))
示例#32
0
    def feed(self, filter=None, id=None):
        feed = feedgenerator.Rss201rev2Feed(
            title=_('%s packages' % config['debexpo.sitename']),
            link=config['debexpo.server'] + url('packages'),
            description=_('A feed of packages on %s' % config['debexpo.sitename']),
            language=get_lang()[0])

        if filter == 'section':
            packages = self._get_packages(package_version_filter=(PackageVersion.section == id))

        elif filter == 'uploader':
            user = self._get_user(id)
            if user is not None:
                packages = self._get_packages(package_filter=(Package.user_id == user.id))
            else:
                packages = []

        elif filter == 'maintainer':
            packages = self._get_packages(package_version_filter=(PackageVersion.maintainer == id))

        else:
            packages = self._get_packages()

        for item in packages:
            desc = _('Package %s uploaded by %s.' % (item.name, item.user.name))

            desc += '<br/><br/>'

            if item.needs_sponsor:
                desc += _('Uploader is currently looking for a sponsor.')
            else:
                desc += _('Uploader is currently not looking for a sponsor.')

            desc += '<br/><br/>' + item.description.replace('\n', '<br/>')

            feed.add_item(title='%s %s' % (item.name, item.package_versions[-1].version),
                link=config['debexpo.server'] + url('package', packagename=item.name),
                description=desc, unique_id=str(item.package_versions[-1].id))

        response.content_type = 'application/rss+xml'
        response.content_type_params = {'charset': 'utf8'}
        return feed.writeString('utf-8')
示例#33
0
    def get_content(self):
        from pylons.i18n import get_lang
        from r2.lib import strings, translation

        if self.lang:
            old_lang = get_lang()
            translation.set_lang(self.lang)

        data = {}
        if self.keys is not None:
            for key in self.keys:
                data[key] = strings.strings[key]
                self._check_formatting_specifiers(key, data[key])
        else:
            data = dict(strings.strings)

        if self.lang:
            translation.set_lang(old_lang)

        return data
示例#34
0
文件: js.py 项目: 99plus2/reddit
    def get_content(self):
        from pylons.i18n import get_lang
        from r2.lib import strings, translation

        if self.lang:
            old_lang = get_lang()
            translation.set_lang(self.lang)

        data = {}
        if self.keys is not None:
            for key in self.keys:
                data[key] = strings.strings[key]
                self._check_formatting_specifiers(key, data[key])
        else:
            data = dict(strings.strings)

        if self.lang:
            translation.set_lang(old_lang)

        return data
示例#35
0
 def load(self):
     query = Base().query()
     if ((self.controller != None) and (self.name == None)):
         q = 'select * from project where controller = "%s"'%(self.controller)
     elif ((self.controller == None) and (self.name != None)):
         q = 'select * from project where name = "%s"'%(self.name)
     else:
         q = 'select * from project where controller = "%s"'%('main')
     query.query(q)
     row = query.record[0]
     self.id = int(row['id'])
     self.controller = str(row['controller'])
     self.name = str(row['name'])
     if (self.lang ==None):
         q = 'select id from lang where lang = "%s"'%(get_lang()[0])
     else:
         q = 'select id from lang where lang = "%s"'%(self.lang)
     query.query(q)
     row = query.record[0]
     self.langId = int(row['id'])
示例#36
0
def render_form(
    menu_items,
    values=None,
    action="submit",
    id=-1,
    errors=None,
    add_number_of_addresses=0,
    add_number_of_emails=0,
    add_number_of_phones=0,
):
    c.number_of_addresses = number_of_addresses(values) + add_number_of_addresses
    c.number_of_emails = number_of_emails(values) + add_number_of_emails
    c.number_of_phones = number_of_phones(values) + add_number_of_phones
    c.menu_items = h.top_menu(menu_items, _("Customers"))
    # c.roles = ['test1','test2']
    c.roles = Session.query(Group).all()
    c.tags = Session.query(UserTag).all()
    c.action = action
    c.id = id
    html = render(path.join(get_lang()[0], "derived/user/staff/new.mako"))
    return htmlfill.render(html, defaults=values, errors=errors)
示例#37
0
文件: js.py 项目: tomrh/reddit
    def use(self):
        from pylons.i18n import get_lang
        from r2.lib.template_helpers import static

        if g.uncompressedJS:
            if c.lang == "en":
                # in this case, the msgids *are* the translated strings and we
                # can save ourselves the pricey step of lexing the js source
                return Module.use(self)

            msgids = extract_javascript_msgids(Module.get_source(self))
            strings = StringsSource(c.lang, msgids)
            return "\n".join((
                Module.use(self),
                inline_script_tag.format(content=strings.get_plural_forms()),
                strings.use(),
            ))
        else:
            langs = get_lang() or [g.lang]
            url = LocalizedModule.languagize_path(self.name, langs[0])
            return script_tag.format(src=static(url))
示例#38
0
文件: js.py 项目: LDot/reddit
    def get_source(self):
        from pylons.i18n import get_lang
        from r2.lib import strings, translation

        if self.lang:
            old_lang = get_lang()
            translation.set_lang(self.lang)

        data = {}
        if self.keys is not None:
            for key in self.keys:
                data[key] = strings.strings[key]
        else:
            data = dict(strings.strings)
        
        output = self.prepend + json.dumps(data) + "\n"

        if self.lang:
            translation.set_lang(old_lang)

        return output
示例#39
0
    def history_ajax(self, id):

        pkg = model.Package.get(id)
        data = []
        approved = False
        for num, (revision, revision_obj) in enumerate(pkg.all_related_revisions):
            if not approved and revision.approved_timestamp:
                current_approved, approved = True, True
            else:
                current_approved = False
            
            data.append({'revision_id': revision.id,
                         'message': revision.message,
                         'timestamp': format_datetime(revision.timestamp, 
                                                      locale=(get_lang() or ['en'])[0]),
                         'author': revision.author,
                         'approved': bool(revision.approved_timestamp),
                         'current_approved': current_approved})
                
        response.headers['Content-Type'] = 'application/json;charset=utf-8'
        return json.dumps(data)
示例#40
0
文件: js.py 项目: barneyfoxuk/reddit
    def get_source(self):
        from pylons.i18n import get_lang
        from r2.lib import strings, translation

        if self.lang:
            old_lang = get_lang()
            translation.set_lang(self.lang)

        data = {}
        if self.keys is not None:
            for key in self.keys:
                data[key] = strings.strings[key]
        else:
            data = dict(strings.strings)

        output = self.prepend + json.dumps(data) + "\n"

        if self.lang:
            translation.set_lang(old_lang)

        return output
示例#41
0
    def search(self,page=1):
        c.lang = get_lang() 
        c.site_name = str('name_'+c.lang[0])
        c.site_descr = str('description_'+c.lang[0])

        page = int(page) if int(page) > 0 else 1
        
        client = Base.sphinx_client

        client.SetMatchMode(sphinxapi.SPH_MATCH_EXTENDED2)
        client.SetLimits((page-1)*20,20)

        query = request.GET.get("q", "")
        result = client.Query(query, index='catalog')
        c.query = request.GET['q']

        if result is not None:
            if 'matches' not in result or not len(result['matches']):
                return render('/category/not_found.mako.html')

            c.cur_page = page
            
            temp = [item['id'] for item in result['matches']]
            c.matches = result['total']
            c.pages = c.matches/20 + 1  if c.matches % 20 else c.matches/20
            c.sites = SiteModel.get_by_id(temp)

            c.script = h.HTML.literal("<script type=\"text/javascript\"><!--\nyottos_advertise = \"6aafe89a-98ec-11e0-bbc7-00163e0300c1\";\n//--></script><script type=\"text/javascript\" src=\"http://cdn.yottos.com/getmyad/_a.js\"></script>")
            
            for site in c.sites:
                site.name_en = unicode(client.BuildExcerpts([site.name_en, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
                site.name_uk = unicode(client.BuildExcerpts([site.name_uk, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
                site.name_ru = unicode(client.BuildExcerpts([site.name_ru, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
                site.description_en = unicode(client.BuildExcerpts([site.description_en, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
                site.description_uk = unicode(client.BuildExcerpts([site.description_uk, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
                site.description_ru = unicode(client.BuildExcerpts([site.description_ru, ], 'catalog', query, opts={'allow_empty':False, 'limit':1024})[0], 'utf-8')
        else: 
            return render('/category/not_found.mako.html')
        return render('/category/search.mako.html')
示例#42
0
 def post_login(self):         
     identity = request.environ.get('repoze.who.identity')
     if not identity:
         session['failedlogin'] +=1
         session.save()
         #h.flash(_("Incorrect User name or Password"))
         if session['failedlogin']>3:    
             session['failedlogin'] = 0
             session.save()
             #return "To many login atempts!"
         return HTTPForbidden(request=request,body="Incorrect User name or Password")            
     if identity['user'].pending:
         session['failedlogin'] = 0 
         session.save()
         h.flash(_('Your account is still pending. Check your email for activation link'))
         #return redirect logout
         return redirect(url(controller="account",action="logout"))
         #return render(path.join(get_lang()[0],'derived/account/login.mako'))
     if identity['user'].deleted:
         session['failedlogin'] = 0 
         session.save()        
         h.flash(_('Your account has been deleted!'))
         return redirect(url(controller="account",action="logout"))
         #return render(path.join(get_lang()[0],'derived/account/login.mako'))
     
     session['user'] = identity['user'].id
    
     if is_met(not_anonymous()):
         session['failedlogin'] = 0            
         session['user_selection']={}
         session['product_selection']={}
         session['invoice_selection']={}        
     session.save()
     if 'came_from' in session:
         came_from = session['came_from']
         del session['came_from']
         session.save()
         return redirect(came_from)
     return render(path.join(get_lang()[0],'derived/account/login.mako'))        
示例#43
0
文件: js.py 项目: GreatChenR/reddit
    def use(self):
        from pylons.i18n import get_lang
        from r2.lib.template_helpers import static
        from r2.lib.filters import SC_OFF, SC_ON

        if g.uncompressedJS:
            if c.lang == "en" or c.lang not in g.all_languages:
                # in this case, the msgids *are* the translated strings and we
                # can save ourselves the pricey step of lexing the js source
                return Module.use(self)

            msgids = extract_javascript_msgids(Module.get_source(self))
            localized_appendices = self.localized_appendices + [StringsSource(msgids)]

            lines = [Module.use(self)]
            for appendix in localized_appendices:
                line = SC_OFF + inline_script_tag.format(content=appendix.get_localized_source(c.lang)) + SC_ON
                lines.append(line)
            return "\n".join(lines)
        else:
            langs = get_lang() or [g.lang]
            url = LocalizedModule.languagize_path(self.name, langs[0])
            return script_tag.format(src=static(url))
示例#44
0
    def about(self, id):
        group_type = self._ensure_controller_matches_group_type(id)
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author}
        c.group_dict = self._get_group_dict(id)

        log.info(':::::::::::: Retrieving the corresponding localized title and abstract :::::::::::::::')

        # Localizing Organizations in about page
        lang = get_lang()[0]

        q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == c.group_dict.get('id'), GroupMultilang.lang == lang).all() 

        if q_results:
            for result in q_results:
                c.group_dict[result.field] = result.text
                if result.field == 'title':
                    c.group_dict['display_name'] = result.text

        group_type = c.group_dict['type']
        self._setup_template_variables(context, {'id': id},
                                       group_type=group_type)
        return render(self._about_template(group_type),
                      extra_vars={'group_type': group_type})
示例#45
0
                401,
                _('User %r not authorized to edit %r') %
                (c.user.encode('ascii', 'ignore'), id))

        format = request.params.get('format', '')
        if format == 'atom':
            # Generate and return Atom 1.0 document.
            from webhelpers.feedgenerator import Atom1Feed
            feed = Atom1Feed(
                title=_(u'CKAN Group Revision History'),
                link=self._url_for(controller='group',
                                   action='read',
                                   id=c.group_dict['name']),
                description=_(u'Recent changes to CKAN Group: ') +
                c.group_dict['display_name'],
                language=unicode(get_lang()),
            )
            for revision_dict in c.group_revisions:
                revision_date = h.date_str_to_datetime(
                    revision_dict['timestamp'])
                try:
                    dayHorizon = int(request.params.get('days'))
                except:
                    dayHorizon = 30
                dayAge = (datetime.datetime.now() - revision_date).days
                if dayAge >= dayHorizon:
                    break
                if revision_dict['message']:
                    item_title = u'%s' % revision_dict['message'].\
                        split('\n')[0]
                else:
示例#46
0
    def history(self, id):
        group_type = self._ensure_controller_matches_group_type(id)
        if 'diff' in request.params or 'selected1' in request.params:
            try:
                params = {
                    'id': request.params.getone('group_name'),
                    'diff': request.params.getone('selected1'),
                    'oldid': request.params.getone('selected2'),
                }
            except KeyError:
                if 'group_name' in dict(request.params):
                    id = request.params.getone('group_name')
                c.error = \
                    _('Select two revisions before doing the comparison.')
            else:
                params['diff_entity'] = 'group'
                h.redirect_to(controller='revision', action='diff', **params)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user,
            'schema': self._db_to_form_schema()
        }
        data_dict = {'id': id}
        try:
            c.group_dict = self._action('group_show')(context, data_dict)
            c.group_revisions = self._action('group_revision_list')(context,
                                                                    data_dict)
            #TODO: remove
            # Still necessary for the authz check in group/layout.html
            c.group = context['group']
        except (NotFound, NotAuthorized):
            abort(404, _('Group not found'))

        format = request.params.get('format', '')
        if format == 'atom':
            # Generate and return Atom 1.0 document.
            from webhelpers.feedgenerator import Atom1Feed
            feed = Atom1Feed(
                title=_(u'CKAN Group Revision History'),
                link=self._url_for_this_controller(action='read',
                                                   id=c.group_dict['name']),
                description=_(u'Recent changes to CKAN Group: ') +
                c.group_dict['display_name'],
                language=unicode(get_lang()),
            )
            for revision_dict in c.group_revisions:
                revision_date = h.date_str_to_datetime(
                    revision_dict['timestamp'])
                try:
                    dayHorizon = int(request.params.get('days'))
                except:
                    dayHorizon = 30
                dayAge = (datetime.datetime.now() - revision_date).days
                if dayAge >= dayHorizon:
                    break
                if revision_dict['message']:
                    item_title = u'%s' % revision_dict['message'].\
                        split('\n')[0]
                else:
                    item_title = u'%s' % revision_dict['id']
                item_link = h.url_for(controller='revision',
                                      action='read',
                                      id=revision_dict['id'])
                item_description = _('Log message: ')
                item_description += '%s' % (revision_dict['message'] or '')
                item_author_name = revision_dict['author']
                item_pubdate = revision_date
                feed.add_item(
                    title=item_title,
                    link=item_link,
                    description=item_description,
                    author_name=item_author_name,
                    pubdate=item_pubdate,
                )
            feed.content_type = 'application/atom+xml'
            return feed.writeString('utf-8')
        return render(self._history_template(group_type),
                      extra_vars={'group_type': group_type})
示例#47
0
class feedGroupController(GroupController):

    def history(self, id):
        if 'diff' in request.params or 'selected1' in request.params:
            try:
                params = {'id':request.params.getone('group_name'),
                          'diff':request.params.getone('selected1'),
                          'oldid':request.params.getone('selected2'),
                          }
            except KeyError, e:
                if dict(request.params).has_key('group_name'):
                    id = request.params.getone('group_name')
                c.error = _('Select two revisions before doing the comparison.')
            else:
                params['diff_entity'] = 'group'
                h.redirect_to(controller='revision', action='diff', **params)

        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_revisions = get_action('group_revision_list')(context, data_dict)
            c.group = context['group']
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('User %r not authorized to edit %r') % (c.user, id))

        onlycreated = request.params.get('created', '')
        feed_title=u'RSS-Feed - Geänderte Datensätze - %s - data.gv.at' % c.group_dict['display_name']
        feed_description=_(u'Letzte Änderungen: ') + c.group_dict['display_name']
        if onlycreated == '1':
            feed_title=u'RSS-Feed - Neue Datensätze - %s - data.gv.at' % c.group_dict['display_name']
            feed_description=_(u'Neue Datensätze: ') + c.group_dict['display_name']
        format = request.params.get('format', '')
        if format == 'atom':
            # Generate and return Atom 1.0 document.
            from webhelpers.feedgenerator import Atom1Feed
            feed = Atom1Feed(
                title=_(u'CKAN Group Revision History'),
                link=h.url_for(controller='group', action='read', id=c.group_dict['name']),
                description=_(u'Recent changes to CKAN Group: ') +
                    c.group_dict['display_name'],
                language=unicode(get_lang()),
            )
            for revision_dict in c.group_revisions:
                revision_date = h.date_str_to_datetime(revision_dict['timestamp'])
                try:
                    dayHorizon = int(request.params.get('days'))
                except:
                    dayHorizon = 30
                dayAge = (datetime.datetime.now() - revision_date).days
                if dayAge >= dayHorizon:
                    break
                if revision_dict['message']:
                    item_title = u'%s' % revision_dict['message'].split('\n')[0]
                else:
                    item_title = u'%s' % revision_dict['id']
                item_link = h.url_for(controller='revision', action='read', id=revision_dict['id'])
                item_description = _('Log message: ')
                item_description += '%s' % (revision_dict['message'] or '')
                item_author_name = revision_dict['author']
                item_pubdate = revision_date
                feed.add_item(
                    title=item_title,
                    link=item_link,
                    description=item_description,
                    author_name=item_author_name,
                    pubdate=item_pubdate,
                )
            feed.content_type = 'application/atom+xml'
            return feed.writeString('utf-8')
        return render( self._history_template(c.group_dict['type']) )    
示例#48
0
 def list(self):
     format = request.params.get('format', '')
     onlycreated = request.params.get('created', '')
     organization = request.params.get('organization', '')
     feed_title=u'RSS-Feed - Geänderte Datensätze - data.gv.at'
     feed_description=_(u'Letzte Änderungen: ')
     if onlycreated == '1':
         feed_title=u'RSS-Feed - Neue Datensätze - data.gv.at'
         feed_description=_(u'Neue Datensätze: ')
     log.debug("organization selected: %s" % organization)        
     if format == 'atom':
         # Generate and return Atom 1.0 document.
         from webhelpers.feedgenerator import Atom1Feed
         feed = Atom1Feed(
             title=feed_title,
             link=h.url_for(controller='revision', action='list', id=''),
             description=feed_description,
             language=unicode(get_lang()),
         )
         # TODO: make this configurable?
         # we do not want the system to fall over!
         maxresults = 200
         maxfeedresults = 10
         try:
             dayHorizon = int(request.params.get('days', 30))
         except:
             dayHorizon = 30
         ourtimedelta = timedelta(days=-dayHorizon)
         since_when = datetime.now() + ourtimedelta
         querycounter = 0
         while querycounter <= 2:
             revision_query = model.repo.history()
             revision_query = revision_query.filter(
                     model.Revision.timestamp>=since_when).filter(
                     model.Revision.id!=None)
             revision_query = revision_query.slice(maxresults*querycounter, maxresults*querycounter+maxresults)
             for revision in revision_query:
                 if(feed.num_items()>=maxfeedresults):
                        break
                 package_indications = []
                 revision_changes = model.repo.list_changes(revision)
                 resource_revisions = revision_changes[model.Resource]
                 resource_group_revisions = revision_changes[model.ResourceGroup]
                 package_extra_revisions = revision_changes[model.PackageExtra]
                 for package in revision.packages:
                     number = len(package.all_revisions)
                     package_revision = None
                     count = 0
                     for pr in package.all_revisions:
                         count += 1
                         if pr.revision.id == revision.id:
                             package_revision = pr
                             break
                     if package_revision and package_revision.state == model.State.DELETED:
                         transition = 'deleted'
                     elif package_revision and count == number:
                         transition = 'created'
                     else:
                         transition = 'updated'
                         for resource_revision in resource_revisions:
                             if resource_revision.continuity.resource_group.package_id == package.id:
                                 transition += ':resources'
                                 break
                         for resource_group_revision in resource_group_revisions:
                             if resource_group_revision.package_id == package.id:
                                 transition += ':resource_group'
                                 break
                         for package_extra_revision in package_extra_revisions:
                             if package_extra_revision.package_id == package.id:
                                 if package_extra_revision.key == 'date_updated':
                                     transition += ':date_updated'
                                     break
                     indication = "%s:%s" % (package.name, transition)
                     package_indications.append(indication)
                     packName = package.name
                     packId = package.id
 #                    packTitle = package.title
 #                    maintainer = package.maintainer
 #                    package_indications.append(indication)
 #                    package = model.Package.get(packId)
 #                    packDict = model.Package.as_dict(package)
                 if (onlycreated == '1') and not(transition.startswith('created')):
                     log.fatal("show only created")
                     log.fatal("transition: %s" % transition)
                     continue
                 
 #                log.debug('group found: %s / group wanted: %s' % (packDict.get('groups'), organization))                   
 #                if (organization != ''):
 #                    if not(organization in packDict.get('groups')):
 #                        continue
 #                log.critical('CORRECT GROUP FOUND!!')                    
                 pkgs = u'[%s]' % ' '.join(package_indications)
                 item_title = u'r%s ' % (revision.id)
                 item_title += pkgs
                 if revision.message:
                     item_title += ': %s' % (revision.message or '')
                 item_link = "/sucheDetail/?id=%s" % packId
                 item_description = _('Datasets affected: %s.\n') % pkgs
                 item_description += '%s' % (revision.message or '')
                 item_author_name = revision.author
                 item_pubdate = revision.timestamp
                 feed.add_item(
                     title=item_title,
                     link=item_link,
                     description=item_description,
                     author_name=item_author_name,
                     pubdate=item_pubdate,
                 )
             querycounter += 1
         feed.content_type = 'application/atom+xml'
         return feed.writeString('utf-8')
     else:
         query = model.Session.query(model.Revision)
         c.page = Page(
             collection=query,
             page=request.params.get('page', 1),
             url=h.pager_url,
             items_per_page=20
         )
         return render('revision/list.html')
示例#49
0
def get_translator(lang=None, request=None):
    """
    return a GNUTranslations instance for `lang`::

        >>> translate = get_translator('fr')
        >>> assert translate('Remove') == 'Supprimer'
        >>> assert translate('month_01') == 'Janvier'
        >>> translate = get_translator('en')
        >>> assert translate('Remove') == 'Remove'
        >>> assert translate('month_01') == 'January'

    The correct gettext method is stored in request if possible::

        >>> from webob import Request
        >>> req = Request.blank('/')
        >>> translate = get_translator('fr', request=req)
        >>> assert translate('Remove') == 'Supprimer'
        >>> translate = get_translator('en', request=req)
        >>> assert translate('Remove') == 'Supprimer'

    """
    if request is not None:
        translate = request.environ.get('fa.translate')
        if translate:
            return translate

        if HAS_PYRAMID:
            translate = get_localizer(request).translate
            request.environ['fa.translate'] = translate
            return translate

    # get possible fallback languages
    try:
        langs = get_lang() or []
    except TypeError:
        # this occurs when Pylons is available and we are not in a valid thread
        langs = []

    # insert lang if provided
    if lang and lang not in langs:
        langs.insert(0, lang)

    if not langs:
        langs = ['en']

    # get the first available catalog
    for lang in langs:
        filename = os.path.join(i18n_path, lang, 'LC_MESSAGES',
                                'formalchemy.mo')
        if os.path.isfile(filename):
            translations_path = os.path.join(i18n_path, lang, 'LC_MESSAGES',
                                             'formalchemy.mo')
            tr = GNUTranslations(open(translations_path, 'rb')).gettext

            def translate(value):
                value = tr(value)
                if isinstance(value, six.binary_type):
                    value = six.text_type(value, 'utf-8')
                return value

            if request is not None:
                request.environ['fa.translate'] = translate
            return translate

    # dummy translator
    if request is not None:
        request.environ['fa.translate'] = _translator.gettext
    return _translator.gettext
示例#50
0
文件: i18nc.py 项目: bluker/pylons
 def langs(self):
     locale_list = request.languages
     set_lang(request.languages)
     return str(get_lang())
示例#51
0
文件: group.py 项目: nushkovg/ckan
def history(id, group_type, is_organization):
    u''' Do we need this? '''
    extra_vars = {}
    set_org(is_organization)
    if u'diff' in request.params or u'selected1' in request.params:
        try:
            params = {
                u'id': request.params.getone(u'group_name'),
                u'diff': request.params.getone(u'selected1'),
                u'oldid': request.params.getone(u'selected2'),
            }
        except KeyError:
            if u'group_name' in dict(request.params):
                id = request.params.getone(u'group_name')
            error = \
                _(u'Select two revisions before doing the comparison.')
            # TODO: Remove
            g.error = error
        else:
            params[u'diff_entity'] = u'group'
            return h.redirect_to(controller=u'revision',
                                 action=u'diff',
                                 **params)

    context = {
        u'model': model,
        u'session': model.Session,
        u'user': g.user,
        u'schema': _db_to_form_schema()
    }
    data_dict = {u'id': id}
    try:
        group_dict = _action(u'group_show')(context, data_dict)
        group_revisions = _action(u'group_revision_list')(context, data_dict)
        # TODO: remove
        # Still necessary for the authz check in group/layout.html
        group = context['group']
    except (NotFound, NotAuthorized):
        base.abort(404, _(u'Group not found'))

    format = request.params.get(u'format', u'')
    if format == u'atom':
        # Generate and return Atom 1.0 document.
        from webhelpers.feedgenerator import Atom1Feed
        feed = Atom1Feed(
            title=_(u'CKAN Group Revision History'),
            link=h.url_for(group_type + u'.read', id=group_dict[u'name']),
            description=_(u'Recent changes to CKAN Group: ') +
            group_dict['display_name'],
            language=text_type(get_lang()),
        )
        for revision_dict in group_revisions:
            revision_date = h.date_str_to_datetime(revision_dict[u'timestamp'])
            try:
                dayHorizon = int(request.params.get(u'days'))
            except Exception:
                dayHorizon = 30
            dayAge = (datetime.datetime.now() - revision_date).days
            if dayAge >= dayHorizon:
                break
            if revision_dict['message']:
                item_title = u'%s' % revision_dict['message'].\
                    split(u'\n')[0]
            else:
                item_title = u'%s' % revision_dict['id']
            item_link = h.url_for(controller=u'revision',
                                  action=u'read',
                                  id=revision_dict['id'])
            item_description = _(u'Log message: ')
            item_description += u'%s' % (revision_dict['message'] or u'')
            item_author_name = revision_dict['author']
            item_pubdate = revision_date
            feed.add_item(
                title=item_title,
                link=item_link,
                description=item_description,
                author_name=item_author_name,
                pubdate=item_pubdate,
            )
        feed.content_type = u'application/atom+xml'
        return feed.writeString(u'utf-8')

    # TODO: Remove
    g.group_dict = group_dict
    g.group_revisions = group_revisions
    g.group = group
    extra_vars = {
        u"group_dict": group_dict,
        u"group_revisions": group_revisions,
        u"group": group,
        u"group_type": group_type
    }
    return base.render(_history_template(group_type), extra_vars)
 def list(self):
     format = request.params.get('format', '')
     if format == 'atom':
         # Generate and return Atom 1.0 document.
         from webhelpers.feedgenerator import Atom1Feed
         feed = Atom1Feed(
             title=_(u'CKAN Repository Revision History'),
             link=h.url_for(controller='revision', action='list', id=''),
             description=_(u'Recent changes to the CKAN repository.'),
             language=unicode(get_lang()),
         )
         # TODO: make this configurable?
         # we do not want the system to fall over!
         maxresults = 200
         try:
             dayHorizon = int(request.params.get('days', 5))
         except:
             dayHorizon = 5
         ourtimedelta = timedelta(days=-dayHorizon)
         since_when = datetime.now() + ourtimedelta
         revision_query = model.repo.history()
         revision_query = revision_query.filter(
             model.Revision.timestamp >= since_when).filter(
                 model.Revision.id != None)
         revision_query = revision_query.limit(maxresults)
         for revision in revision_query:
             package_indications = []
             revision_changes = model.repo.list_changes(revision)
             resource_revisions = revision_changes[model.Resource]
             resource_group_revisions = \
                 revision_changes[model.ResourceGroup]
             package_extra_revisions = revision_changes[model.PackageExtra]
             for package in revision.packages:
                 if not package:
                     # package is None sometimes - I don't know why,
                     # but in the meantime while that is fixed,
                     # avoid an exception here
                     continue
                 if package.private:
                     continue
                 number = len(package.all_revisions)
                 package_revision = None
                 count = 0
                 for pr in package.all_revisions:
                     count += 1
                     if pr.revision.id == revision.id:
                         package_revision = pr
                         break
                 if package_revision and package_revision.state == \
                         model.State.DELETED:
                     transition = 'deleted'
                 elif package_revision and count == number:
                     transition = 'created'
                 else:
                     transition = 'updated'
                     for resource_revision in resource_revisions:
                         if resource_revision.continuity.resource_group.\
                                 package_id == package.id:
                             transition += ':resources'
                             break
                     for resource_group_revision in \
                             resource_group_revisions:
                         if resource_group_revision.package_id == \
                                 package.id:
                             transition += ':resource_group'
                             break
                     for package_extra_revision in package_extra_revisions:
                         if package_extra_revision.package_id == \
                                 package.id:
                             if package_extra_revision.key == \
                                     'date_updated':
                                 transition += ':date_updated'
                                 break
                 indication = "%s:%s" % (package.name, transition)
                 package_indications.append(indication)
             pkgs = u'[%s]' % ' '.join(package_indications)
             item_title = u'r%s ' % (revision.id)
             item_title += pkgs
             if revision.message:
                 item_title += ': %s' % (revision.message or '')
             item_link = h.url_for(controller='revision',
                                   action='read',
                                   id=revision.id)
             item_description = _('Datasets affected: %s.\n') % pkgs
             item_description += '%s' % (revision.message or '')
             item_author_name = revision.author
             item_pubdate = revision.timestamp
             feed.add_item(
                 title=item_title,
                 link=item_link,
                 description=item_description,
                 author_name=item_author_name,
                 pubdate=item_pubdate,
             )
         feed.content_type = 'application/atom+xml'
         return feed.writeString('utf-8')
     else:
         query = model.Session.query(model.Revision)
         c.page = h.Page(collection=query,
                         page=request.params.get('page', 1),
                         url=h.pager_url,
                         items_per_page=20)
         return base.render('revision/list.html')
示例#53
0
    def old_list(self):
           format = request.params.get('format', '')
           onlycreated = request.params.get('created', '')
           organization = request.params.get('organization', '')
           feed_title=u'RSS-Feed - Geänderte Datensätze - data.gv.at'
           feed_description=_(u'Letzte Änderungen: ')
           if onlycreated == '1':
               feed_title=u'RSS-Feed - Neue Datensätze - data.gv.at'
               feed_description=_(u'Neue Datensätze: ')
           log.debug("organization selected: %s" % organization)
           lang = get_lang()
           if lang[0]:
               lang = lang[0]
           if format == 'atom':
               feed = Atom1Feed(
                  title=_(feed_title),
                  link=h.url_for(controller='revision', action='list', id=''),
                  description=feed_description,
                  language=unicode(lang),
               )
               maxresults = 10
               #revision_query = model.repo.history()
               #revision_query = revision_query.limit(maxresults)
               revision_query = model.repo.history()
               revision_query = revision_query.order_by(model.Revision.timestamp.desc())
               revision_query = revision_query.filter(model.Revision.id!=None)
               #revision_query = revision_query.filter(model.Member.group_id=='4a766e5e-89a3-4a16-addd-05fa0b5953c3')
               #revision_query = revision_query.limit(maxresults)
               maintainer = 'default'
               for revision in revision_query:
                   if(feed.num_items()>=maxresults):
                       break
                   transition = ""
                   packName= ""
                   package_indications = []
                   revision_changes = model.repo.list_changes(revision)
                   resource_revisions = revision_changes[model.Resource]
                   #package_revisions = revision_changes[model.Package]
                   resource_group_revisions = revision_changes[model.ResourceGroup]
                   package_extra_revisions = revision_changes[model.PackageExtra]
                   group_revisions = revision_changes[model.Group]
                   tag_revisions = revision_changes[model.PackageTag]
                   member_revisions = revision_changes[model.Member]
                   
                   #Skip groups
                   if (len(group_revisions)>0):
                     continue       
                   #if (len(member_revisions)>0):
                     #continue   
                   if len(revision.packages)==0:
                     continue
                   if (len(resource_group_revisions) + len(tag_revisions) +len(package_extra_revisions) +len(resource_revisions))==0:
                     continue       
                   for package in revision.packages:
                       number = len(package.all_revisions)
                       package_revision = None
                       count = 0
                       
                       for pr in package.all_revisions:
                           count += 1
                           if pr.revision.id == revision.id:
                               package_revision = pr
                               break
                       if package_revision and package_revision.state == model.State.DELETED:
                            transition = 'deleted'
                       elif package_revision and count == number:
                            transition = 'created'
                       else:
                            transition = 'updated'
                            for resource_revision in resource_revisions:
                                if resource_revision.continuity.resource_group.package_id == package.id:
                                    transition += ': Ressourcen'
                                    break
                            for resource_group_revision in resource_group_revisions:
                                if resource_group_revision.package_id == package.id:
                                    transition += ' resource_group'
                                    break
                            for package_extra_revision in package_extra_revisions:
                                if package_extra_revision.package_id == package.id:
                                    #if package_extra_revision.key == 'date_updated':
                                    transition += ''
                                    break
                       indication = "%s" % ( transition)
                       packName = package.name
                       packId = package.id
                       packTitle = package.title
                       maintainer = package.maintainer
                       package_indications.append(indication)
                       package = model.Package.get(packId)
                       packDict = model.Package.as_dict(package)
                   if (onlycreated == '1') and not(transition.startswith('created')):
                       continue

                   log.debug('group found: %s / group wanted: %s' % (packDict.get('groups'), organization))                   
                   if (organization != ''):
                       if not(organization in packDict.get('groups')):
                           continue
                   log.critical('CORRECT GROUP FOUND!!')
                   #if len(package_indications[0]) < 3:
                   #    revision_changes.xxx()
                       
                   pkgs = u'%s' % ' '.join(package_indications)
                   #item_title = u'%s ' % (revision.id)
                   item_title = packTitle
                   #if revision.message:
                   #    item_title += ': %s' % (revision.message or '')    
                   item_link = '/sucheDetail/?id=' + packId
                   item_description = indication
                   #item_description = _('Datasets affected: %s.\n') % pkgs
                   #item_description += '%s' % (revision.message or '')
                   #item_author_name = Authorization Group !
                   item_author_name =  maintainer
                   item_pubdate = revision.timestamp
                   
                   feed.add_item(
                     title=item_title,
                     link=item_link,
                     description=item_description,
                     author_name=item_author_name,
                     pubdate=item_pubdate,
                   )
                   log.fatal("feedlength: " + feed.num_items())
               feed.content_type = 'application/atom+xml'
               return feed.writeString('utf-8')
           else:
               return RevisionController.list(self);