def logged_in(self):
        # we need to set the language via a redirect
        lang = session.pop('lang', None)
        session.save()

        # we need to set the language explicitly here or the flash
        # messages will not be translated.
        i18n.set_lang(lang)

        if c.user:
            is_new = False
            is_sysadmin = new_authz.is_sysadmin(c.user)

            # Retrieve information about the current user
            context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': schema.user_new_form_schema()}
            data_dict = {'id': c.user}

            user_dict = get_action('user_show')(context, data_dict)

            # This check is not needed (or correct) for sys admins
            if not is_sysadmin:

                # Get all organizations and all groups the user belongs to
                orgs_q = model.Session.query(model.Group) \
                    .filter(model.Group.is_organization == True) \
                    .filter(model.Group.state == 'active')
                q = model.Session.query(model.Member) \
                    .filter(model.Member.table_name == 'user') \
                    .filter(model.Member.table_id == user_dict['id'])

                group_ids = []
                for row in q.all():
                    group_ids.append(row.group_id)

                if not group_ids:
                    is_new = True
                else:
                    orgs_q = orgs_q.filter(model.Group.id.in_(group_ids))

                    orgs_list = model_dictize.group_list_dictize(orgs_q.all(), context)

                    if len(orgs_list) == 0:
                        is_new = True

            h.flash_success(_("<p><strong>Note</strong></p>"
                "<p>%s is now logged in</p>") %
                user_dict['display_name'], allow_html=True)

            if is_new:
                return h.redirect_to(controller='ckanext.canada.controller:CanadaController',
                                         action='view_new_user', locale=lang)
            else:
                return h.redirect_to(controller='package',
                    action='search', locale=lang)
        else:
            h.flash_error(_('Login failed. Bad username or password.'))
            return h.redirect_to(controller='user',
                action='login', locale=lang)
Example #2
0
    def revoke(self, redirect_url=None):
        v_id = request.params.get('id', None)

        if v_id is None:
            abort(401, "id of velruse account not specified")

        v = Velruse.by_id(v_id)
        if v is None:
            self._failure(_("You are trying to disconnect from a provider"
                            " you are disconnected from already."))
            return None

        elif not (v.user == c.user or can.user.manage()):
            abort(403, _("You're not authorized to change %s's settings.")
                  % c.user.id)
        else:
            v.delete_forever()
            model.meta.Session.commit()

            h.flash(_("You successfully disconnected from %(provider)s.")
                    % {'provider': v.domain},
                    'success')

            if redirect_url is None:
                redirect(h.entity_url(c.user, member='settings/login'))
            else:
                redirect(redirect_url)
Example #3
0
    def GET_submit(self, url, title, then):
        """Submit form."""
        if url and not request.get.get('resubmit'):
            # check to see if the url has already been submitted
            links = link_from_url(url)
            if links and len(links) == 1:
                return self.redirect(links[0].already_submitted_link)
            elif links:
                infotext = (strings.multiple_submitted
                            % links[0].resubmit_link())
                res = BoringPage(_("seen it"),
                                 content = wrap_links(links),
                                 infotext = infotext).render()
                return res

        captcha = Captcha() if c.user.needs_captcha() else None
        sr_names = (Subreddit.submit_sr_names(c.user) or
                    Subreddit.submit_sr_names(None))

        return FormPage(_("submit"),
                        show_sidebar = True,
                        content=NewLink(url=url or '',
                                        title=title or '',
                                        subreddits = sr_names,
                                        captcha=captcha,
                                        then = then)).render()
Example #4
0
File: pages.py Project: vin/reddit
    def rightbox(self):
        """generates content in <div class="rightbox">"""
        
        ps = PaneStack(css_class='spacer')

        if self.searchbox:
            ps.append(SearchForm())

        if not c.user_is_loggedin and self.loginbox:
            ps.append(LoginFormWide())

        #don't show the subreddit info bar on cnames
        if not isinstance(c.site, FakeSubreddit) and not c.cname:
            ps.append(SubredditInfoBar())

        if self.submit_box:
            ps.append(SideBox(_('Submit a link'),
                              '/submit', 'submit',
                              sr_path = True,
                              subtitles = [_('to anything interesting: news article, blog entry, video, picture...')],
                              show_cover = True))
            
        if self.create_reddit_box:
           ps.append(SideBox(_('Create your own reddit'),
                              '/reddits/create', 'create',
                              subtitles = rand_strings.get("create_reddit", 2),
                              show_cover = True, nocname=True))
        return ps
Example #5
0
    def _connect(self, adhocracy_user, domain, domain_user,
                 provider_name,
                 velruse_email, email_verified=False,
                 redirect_url=None):
        """
        Connect existing adhocracy user to velruse.
        """

        if not Velruse.find(domain, domain_user):
            velruse_user = Velruse.connect(adhocracy_user, domain, domain_user,
                                           velruse_email, email_verified)

            model.meta.Session.commit()

            h.flash(_("You successfully connected to %s."
                      % provider_name.capitalize()),
                    'success')

            if redirect_url is None:
                redirect(h.user.post_login_url(adhocracy_user))
            else:
                redirect(redirect_url)
            return velruse_user

        else:
            h.flash(_("Your %s account is already connected."
                      % provider_name.capitalize()),
                    'error')

            redirect(h.user.post_login_url(adhocracy_user))
            return None
Example #6
0
 def register(self):
     require.account.create()
     errors, values = {}, None
     if request.method == 'POST':
         try:
             schema = AccountRegister()
             values = request.params
             data = schema.deserialize(values)
             if Account.by_name(data['name']):
                 raise colander.Invalid(
                     AccountRegister.name,
                     _("Login name already exists, please choose a "
                       "different one"))
             if not data['password1'] == data['password2']:
                 raise colander.Invalid(AccountRegister.password1, _("Passwords \
                     don't match!"))
             account = Account()
             account.name = data['name']
             account.fullname = data['fullname']
             account.email = data['email']
             account.password = generate_password_hash(data['password1'])
             db.session.add(account)
             db.session.commit()
             who_api = get_api(request.environ)
             authenticated, headers = who_api.login({
                 "login": account.name,
                 "password": data['password1']
             })
             response.headers.extend(headers)
             return redirect("/")
         except colander.Invalid, i:
             errors = i.asdict()
Example #7
0
 def after_login(self):
     if c.account is not None:
         h.flash_success(_("Welcome back, %s!") % c.account.name)
         redirect("/")
     else:
         h.flash_error(_("Incorrect user name or password!"))
         redirect("/login")
Example #8
0
def resource_update(context, data_dict):
    model = context['model']
    user = context['user']
    id = data_dict["id"]
    schema = context.get('schema') or ckan.logic.schema.default_update_resource_schema()
    model.Session.remove()

    resource = model.Resource.get(id)
    context["resource"] = resource

    if not resource:
        logging.error('Could not find resource ' + id)
        raise NotFound(_('Resource was not found.'))

    check_access('resource_update', context, data_dict)

    data, errors = validate(data_dict, schema, context)

    if errors:
        model.Session.rollback()
        raise ValidationError(errors, error_summary(errors))

    rev = model.repo.new_revision()
    rev.author = user
    if 'message' in context:
        rev.message = context['message']
    else:
        rev.message = _(u'REST API: Update object %s') % data.get("name", "")

    resource = model_save.resource_dict_save(data, context)
    if not context.get('defer_commit'):
        model.repo.commit()
    return model_dictize.resource_dictize(resource, context)
Example #9
0
def vocabulary_update(context, data_dict):
    model = context['model']

    vocab_id = data_dict.get('id')
    if not vocab_id:
        raise ValidationError({'id': _('id not in data')})

    vocab = model.vocabulary.Vocabulary.get(vocab_id)
    if vocab is None:
        raise NotFound(_('Could not find vocabulary "%s"') % vocab_id)

    data_dict['id'] = vocab.id
    if data_dict.has_key('name'):
        if data_dict['name'] == vocab.name:
            del data_dict['name']

    check_access('vocabulary_update', context, data_dict)

    schema = context.get('schema') or ckan.logic.schema.default_update_vocabulary_schema()
    data, errors = validate(data_dict, schema, context)

    if errors:
        model.Session.rollback()
        raise ValidationError(errors)

    updated_vocab = model_save.vocabulary_dict_update(data, context)

    if not context.get('defer_commit'):
        model.repo.commit()

    return model_dictize.vocabulary_dictize(updated_vocab, context)
Example #10
0
    def edit(self, id, data=None, errors=None, error_summary=None):
        package_type = self._get_package_type(id)
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'extras_as_string': True,
                   'save': 'save' in request.params,
                   'moderated': config.get('moderated'),
                   'pending': True,}

        if context['save'] and not data:
            return self._save_edit(id, context)
        try:
            old_data = get_action('package_show')(context, {'id':id})
            schema = self._db_to_form_schema(package_type=package_type)
            if schema and not data:
                old_data, errors = validate(old_data, schema, context=context)
            data = data or old_data
            # Merge all elements for the complete package dictionary
            c.pkg_dict = dict(old_data.items() + data.items())
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % '')
        except NotFound:
            abort(404, _('Dataset not found'))

        c.pkg = context.get("package")
        c.pkg_json = json.dumps(data)

        try:
            check_access('package_update',context)
        except NotAuthorized, e:
            abort(401, _('User %r not authorized to edit %s') % (c.user, id))
Example #11
0
    def history_ajax(self, id):

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'extras_as_string': True,}
        data_dict = {'id':id}
        try:
            pkg_revisions = get_action('package_revision_list')(context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % '')
        except NotFound:
            abort(404, _('Dataset not found'))


        data = []
        approved = False
        for num, revision in enumerate(pkg_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': revision['timestamp'],
                         '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)
Example #12
0
def package_name_validator(key, data, errors, context):
    model = context["model"]
    session = context["session"]
    package = context.get("package")

    query = session.query(model.Package.name).filter_by(name=data[key])
    if package:
        package_id = package.id
    else:
        package_id = data.get(key[:-1] + ("id",))
    if package_id and package_id is not missing:
        query = query.filter(model.Package.id <> package_id)
    result = query.first()
    if result:
        errors[key].append(_('That URL is already in use.'))

    value = data[key]
    if len(value) < PACKAGE_NAME_MIN_LENGTH:
        raise Invalid(
            _('Name "%s" length is less than minimum %s') % (value, PACKAGE_NAME_MIN_LENGTH)
        )
    if len(value) > PACKAGE_NAME_MAX_LENGTH:
        raise Invalid(
            _('Name "%s" length is more than maximum %s') % (value, PACKAGE_NAME_MAX_LENGTH)
        )
Example #13
0
def user_name_exists(user_name, context):
    model = context['model']
    session = context['session']
    result = session.query(model.User).filter_by(name=user_name).first()
    if not result:
        raise Invalid('%s: %s' % (_('Not found'), _('User')))
    return result.name
Example #14
0
def name_validator(val, field=None):
    # check basic textual rules
    min_length = 2
    if len(val) < min_length:
        raise formalchemy.ValidationError(_('Name must be at least %s characters long') % min_length)
    if not name_match.match(val):
        raise formalchemy.ValidationError(_('Name must be purely lowercase alphanumeric (ascii) characters and these symbols: -_'))
Example #15
0
    def make_tables(self):
        # overall promoted link traffic
        impressions = traffic.AdImpressionsByCodename.historical_totals("day")
        clicks = traffic.ClickthroughsByCodename.historical_totals("day")
        data = traffic.zip_timeseries(impressions, clicks)

        columns = [
            dict(color=COLORS.UPVOTE_ORANGE,
                 title=_("total impressions by day"),
                 shortname=_("impressions")),
            dict(color=COLORS.DOWNVOTE_BLUE,
                 title=_("total clicks by day"),
                 shortname=_("clicks")),
        ]

        self.totals = TimeSeriesChart("traffic-ad-totals",
                                      _("ad totals"),
                                      "day",
                                      columns,
                                      data,
                                      self.traffic_last_modified,
                                      classes=["traffic-table"])

        # get summary of top ads
        advert_summary = traffic.AdImpressionsByCodename.top_last_month()
        things = AdvertTrafficSummary.get_things(ad for ad, data
                                                 in advert_summary)
        self.advert_summary = []
        for id, data in advert_summary:
            name = AdvertTrafficSummary.get_ad_name(id, things=things)
            url = AdvertTrafficSummary.get_ad_url(id, things=things)
            self.advert_summary.append(((name, url), data))
Example #16
0
File: tag.py Project: whausen/part
    def show(self, id, format='html'):
        c.tag = get_entity_or_abort(model.Tag, id)
        require.tag.show(c.tag)
        require.proposal.index()
        require.page.index()

        if format == 'json':
            return render_json(c.tag)

        entities = libsearch.query.run(u'tag:' + c.tag.name,
                                       instance=c.instance)
        entities = [e for e in entities if (isinstance(e, model.Proposal) or
                                            isinstance(e, model.Page))]

        c.entities_pager = NamedPager(
            'entities', entities, tiles.dispatch_row,
            sorts={_("oldest"): sorting.entity_oldest,
                   _("newest"): sorting.entity_newest,
                   _("alphabetically"): sorting.delegateable_title,
                   _("relevance"): sorting.entity_stable},
            default_sort=sorting.entity_stable,
            q=c.query)

        tags = model.Tag.similar_tags(c.tag, limit=50)
        c.cloud_tags = sorted(text.tag_cloud_normalize(tags),
                              key=lambda (k, c, v): k.name)
        return render("/tag/show.html")
Example #17
0
    def build_toolbars(self):
        tabs = [
            NavButton(
                _("updates"),
                "/",
            ),
            NavButton(
                _("discussions"),
                "/discussions",
            ),
        ]

        if c.liveupdate_permissions:
            if (c.liveupdate_permissions.allow("settings") or
                    c.liveupdate_permissions.allow("close")):
                tabs.append(NavButton(
                    _("settings"),
                    "/edit",
                ))

            # all contributors should see this so they can leave if they want
            tabs.append(NavButton(
                _("contributors"),
                "/contributors",
            ))

        return [
            NavMenu(
                tabs,
                base_path="/live/" + c.liveupdate_event._id,
                type="tabmenu",
            ),
        ]
Example #18
0
    def all_karmas(self):
        """returns a list of tuples in the form (name, hover-text, link_karma,
        comment_karma)"""
        link_suffix = '_link_karma'
        comment_suffix = '_comment_karma'
        karmas = []
        sr_names = set()
        for k in self._t.keys():
            if k.endswith(link_suffix):
                sr_names.add(k[:-len(link_suffix)])
            elif k.endswith(comment_suffix):
                sr_names.add(k[:-len(comment_suffix)])
        for sr_name in sr_names:
            karmas.append((sr_name, None,
                           self._t.get(sr_name + link_suffix, 0),
                           self._t.get(sr_name + comment_suffix, 0)))

        karmas.sort(key = lambda x: abs(x[2] + x[3]), reverse=True)

        old_link_karma = self._t.get('link_karma', 0)
        old_comment_karma = self._t.get('comment_karma', 0)
        if old_link_karma or old_comment_karma:
            karmas.append((_('ancient history'),
                           _('really obscure karma from before it was cool to track per-subreddit'),
                           old_link_karma, old_comment_karma))

        return karmas
Example #19
0
    def as_csv(cls, thing):
        """Return the traffic data in CSV format for reports."""

        import csv
        import cStringIO

        start, end = promote.get_traffic_dates(thing)
        history = cls.get_traffic(thing, start, end)
        out = cStringIO.StringIO()
        writer = csv.writer(out)

        headers = [
            _("date and time (UTC)"),
            _("impressions"),
            _("clicks"),
            _("click-through rate (%)"),
        ]

        # peek at the first row's values tuple to see if we have spent
        first_row = history and history[0]
        has_spent = first_row and len(first_row[2]) == 4
        if has_spent:
            headers.insert(1, _("spent"))

        writer.writerow(headers)
        for date, datestr, values in history:
            # flatten (date, datestr, value-tuple) to (date, value1, value2...)
            writer.writerow((date,) + tuple(value for value, formated in values))

        return out.getvalue()
Example #20
0
def tag_delete(context, data_dict):
    '''Delete a tag.

    You must be a sysadmin to delete tags.

    :param id: the id or name of the tag
    :type id: string
    :param vocabulary_id: the id or name of the vocabulary that the tag belongs
        to (optional, default: None)
    :type vocabulary_id: string

    '''
    model = context['model']

    if not data_dict.has_key('id') or not data_dict['id']:
        raise ValidationError({'id': _('id not in data')})
    tag_id_or_name = _get_or_bust(data_dict, 'id')

    vocab_id_or_name = data_dict.get('vocabulary_id')

    tag_obj = model.tag.Tag.get(tag_id_or_name, vocab_id_or_name)

    if tag_obj is None:
        raise NotFound(_('Could not find tag "%s"') % tag_id_or_name)

    _check_access('tag_delete', context, data_dict)

    tag_obj.delete()
    model.repo.commit()
Example #21
0
def _unfollow(context, data_dict, schema, FollowerClass):
    validated_data_dict, errors = validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)

    model = context['model']

    if not context.has_key('user'):
        raise ckan.logic.NotAuthorized(
                _("You must be logged in to unfollow something."))
    userobj = model.User.get(context['user'])
    if not userobj:
        raise ckan.logic.NotAuthorized(
                _("You must be logged in to unfollow something."))
    follower_id = userobj.id

    object_id = validated_data_dict.get('id')

    follower_obj = FollowerClass.get(follower_id, object_id)
    if follower_obj is None:
        raise NotFound(
                _('You are not following {0}.').format(data_dict.get('id')))

    follower_obj.delete()
    model.repo.commit()
Example #22
0
    def view(self, dataset, dimension, format='html'):
        self._get_dataset(dataset)
        try:
            c.dimension = c.dataset[dimension]
        except KeyError:
            abort(404, _('This is not a dimension'))
        if not isinstance(c.dimension, model.Dimension):
            abort(404, _('This is not a dimension'))

        page = self._get_page('page')
        cache = AggregationCache(c.dataset)
        result = cache.aggregate(drilldowns=[dimension], page=page, 
                                 pagesize=PAGE_SIZE)
        items = result.get('drilldown', [])
        c.values = [(d.get(dimension), d.get('amount')) for d in items]

        if format == 'json':
            return to_jsonp({
                "values": c.values,
                "meta": c.dimension.as_dict()})

        c.page = Page(c.values, page=page,
                      item_count=result['summary']['num_drilldowns'],
                      items_per_page=PAGE_SIZE,
                      presliced_list=True)
        return render('dimension/view.html')
Example #23
0
 def pretty_name(self):
     if self.is_collection:
         return _("collection: %(name)s") % {'name': self.collection.name}
     elif self.subreddit_name == Frontpage.name:
         return _("frontpage")
     else:
         return "/r/%s" % self.subreddit_name
Example #24
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 #25
0
    def edit(self, id, data=None, errors=None, error_summary=None):
        group_type = self._get_group_type(id.split('@')[0])
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'extras_as_string': True,
                   'save': 'save' in request.params,
                   'for_edit': True,
                   'parent': request.params.get('parent', None)
                   }
        data_dict = {'id': id}

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

        try:
            old_data = get_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

        try:
            check_access('group_update', context)
        except NotAuthorized, e:
            abort(401, _('User %r not authorized to edit %s') % (c.user, id))
Example #26
0
File: view.py Project: tbalaz/test
    def edit(self, id, data = None,errors = None, error_summary = None):

        if ('save' in request.params) and not data:
            return self._save_edit(id)

        try:
            context = {'model':model, 'user':c.user, 'include_status':False}

            old_data = p.toolkit.get_action('harvest_source_show')(context, {'id':id})
        except p.toolkit.ObjectNotFound:
            abort(404, _('Harvest Source not found'))
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)
        try:
            p.toolkit.check_access('harvest_source_update', context)
        except p.toolkit.NotAuthorized:
            abort(401, _('Unauthorized to update the harvest source'))

        data = data or old_data
        errors = errors or {}
        error_summary = error_summary or {}
        try:
            context = {'model': model, 'user': c.user}
            harvesters_info = p.toolkit.get_action('harvesters_info_show')(context, {})
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)

        vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'harvesters': harvesters_info}

        c.source_title = old_data.get('title') if old_data else ''
        c.source_id = id
        c.groups = self._get_publishers()
        c.form = render('source/new_source_form.html', extra_vars=vars)
        return render('source/edit.html')
    def nuevo(self, id_fase, **kw):
        """Despliega el formulario para añadir una linea base a la fase"""
	fase=DBSession.query(Fase).get(id_fase)
	#Comprobación de si el estado de la fase se encuentra en Con Lineas Bases
	if fase.relacion_estado_fase.nombre_estado=='Con Lineas Bases':
		flash(_("Todos los items de esta fase ya se encuentran en una Linea Base Aprobada"), 'warning')
                redirect("/admin/linea_base/listado_linea_bases",id_proyecto=fase.id_proyecto, id_fase=id_fase)	    
	tipo_items=DBSession.query(TipoItem).filter_by(id_fase=id_fase)
	itemsDeFaseActual = []
	for tipo_item in tipo_items:
		itemsTipoItem = DBSession.query(Item).filter_by(id_tipo_item=tipo_item.id_tipo_item).filter_by(vivo=True)
		for itemTipoItem in itemsTipoItem:
			itemsDeFaseActual.append(itemTipoItem)
	contador_items_en_fase_actual = 0
	for item in itemsDeFaseActual:
		contador_items_en_fase_actual = contador_items_en_fase_actual + 1
	#Comprobación de si existen items cargados para la fase actual
	if contador_items_en_fase_actual == 0:
		flash(_("Aun no existen items cargados para esta fase"), 'warning')
                redirect("/admin/linea_base/listado_linea_bases",id_proyecto=fase.id_proyecto, id_fase=id_fase)		
        kw['id_estado']= 'Desarrollo'
        kw['id_fase']= id_fase
	kw['version']= '1'
	tmpl_context.form = crear_linea_base_form
        return dict(nombre_modelo='LineaBase', id_proyecto=fase.id_proyecto, id_fase=id_fase, page='nuevo', value=kw)
Example #28
0
    def _try_sign_in(self, username, password, location=None, remember=False):
        # user may have registered in several Ututi
        # networks using same username
        locations = [user.location for user in User.get_all(username)]
        if len(locations) == 0:
            return {'username': _('Incorrect username.')}

        if len(locations) > 1:
            # if there is more than one location,
            # we will want to show it in the form
            c.locations = [(loc.id, loc.title) for loc in locations]
            c.selected_location = location

        if location is None and len(locations) == 1:
            location = locations[0].id

        if location is None:
            # still none! that means that location is not
            # unique and user did not specify it.
            return {'location': _('Please select your network.')}

        user = User.authenticate(location, username, password)
        if user is None:
            return {'password': _('Incorrect password.')}

        sign_in_user(user, long_session=remember)
Example #29
0
def milestones(milestones, default_sort=None, **kwargs):
    if default_sort is None:
        default_sort = sorting.milestone_time
    sorts = {_("by date"): sorting.milestone_time,
             _("alphabetically"): sorting.delegateable_title}
    return NamedPager('milestones', milestones, tiles.milestone.row,
                      sorts=sorts, default_sort=default_sort, **kwargs)
Example #30
0
    def menus(self):
        res = []
        if (self.where in ('overview', 'submitted', 'comments')):
            res.append(ProfileSortMenu(default = self.sort))
            if self.sort not in ("hot", "new"):
                res.append(TimeMenu(default = self.time))
        if self.where == 'saved' and c.user.gold:
            srnames = LinkSavesBySubreddit.get_saved_subreddits(self.vuser)
            srnames += CommentSavesBySubreddit.get_saved_subreddits(self.vuser)
            srs = Subreddit._by_name(srnames)
            srnames = [name for name, sr in srs.iteritems()
                            if sr.can_view(c.user)]
            srnames = sorted(list(set(srnames)), key=lambda name: name.lower())
            if len(srnames) > 1:
                sr_buttons = [NavButton(_('all'), None, opt='sr',
                                        css_class='primary')]
                for srname in srnames:
                    sr_buttons.append(NavButton(srname, srname, opt='sr'))
                base_path = request.path
                sr_menu = NavMenu(sr_buttons, base_path=base_path,
                                  title=_('filter by subreddit'),
                                  type='lightdrop')
                res.append(sr_menu)
        elif (self.where == 'gilded' and
                (c.user == self.vuser or c.user_is_admin)):
            path = '/user/%s/gilded/' % self.vuser.name
            buttons = [NavButton(_("my posts"), dest='/'),
                       NavButton(_("posts gilded by me"), dest='/given')]
            res.append(NavMenu(buttons, base_path=path, type='flatlist'))

        return res
Example #31
0
def activity_stream_string_added_tag():
    return _("{actor} added the tag {tag} to the dataset {dataset}")
Example #32
0
def activity_stream_string_deleted_group():
    return _("{actor} deleted the group {group}")
Example #33
0
def activity_stream_string_changed_user():
    return _("{actor} updated their profile")
Example #34
0
def activity_stream_string_changed_resource():
    return _(
        "{actor} updated the resource {resource} in the dataset {dataset}")
Example #35
0
def activity_stream_string_changed_package_extra():
    return _("{actor} changed the extra {extra} of the dataset {dataset}")
Example #36
0
def activity_stream_string_changed_package():
    return _("{actor} updated the dataset {dataset}")
Example #37
0
def activity_stream_string_changed_group():
    return _("{actor} updated the group {group}")
Example #38
0
def activity_stream_string_follow_group():
    return _("{actor} started following {group}")
Example #39
0
def activity_stream_string_follow_dataset():
    return _("{actor} started following {dataset}")
Example #40
0
def activity_stream_string_new_related_item():
    return _(
        "{actor} created the link to related {related_type} {related_item}")
Example #41
0
def activity_stream_string_removed_tag():
    return _("{actor} removed the tag {tag} from the dataset {dataset}")
Example #42
0
def activity_stream_string_follow_user():
    return _("{actor} started following {user}")
Example #43
0
def activity_stream_string_new_resource():
    return _("{actor} added the resource {resource} to the dataset {dataset}")
Example #44
0
def activity_stream_string_deleted_related_item():
    return _("{actor} deleted the related item {related_item}")
Example #45
0
def activity_stream_string_new_package():
    return _("{actor} created the dataset {dataset}")
Example #46
0
def activity_stream_string_new_user():
    return _("{actor} signed up")
Example #47
0
def activity_stream_string_deleted_resource():
    return _(
        "{actor} deleted the resource {resource} from the dataset {dataset}")
Example #48
0
def activity_stream_string_new_package_extra():
    return _("{actor} added the extra {extra} to the dataset {dataset}")
Example #49
0
 def send403(self):
     c.response.status_code = 403
     c.site = Default
     res = pages.RedditError(_("forbidden (%(domain)s)") %
                             dict(domain=g.domain))
     return res.render()
Example #50
0
def activity_stream_string_new_group():
    return _("{actor} created the group {group}")
Example #51
0
def js_config(extra_config=None):
    logged = c.user_is_loggedin and c.user.name
    gold = bool(logged and c.user.gold)

    controller_name = request.environ['pylons.routes_dict']['controller']
    action_name = request.environ['pylons.routes_dict']['action']
    mac = hmac.new(g.secrets["action_name"],
                   controller_name + '.' + action_name, hashlib.sha1)
    verification = mac.hexdigest()

    config = {
        # is the user logged in?
        "logged":
        logged,
        # the subreddit's name (for posts)
        "post_site":
        c.site.name if not c.default_sr else "",
        # the user's voting hash
        "modhash":
        c.modhash or False,
        # the current rendering style
        "renderstyle":
        c.render_style,

        # they're welcome to try to override this in the DOM because we just
        # disable the features server-side if applicable
        'store_visits':
        gold and c.user.pref_store_visits,

        # current domain
        "cur_domain":
        get_domain(cname=c.frameless_cname, subreddit=False, no_www=True),
        # where do ajax requests go?
        "ajax_domain":
        get_domain(cname=c.authorized_cname, subreddit=False),
        "extension":
        c.extension,
        "https_endpoint":
        is_subdomain(request.host, g.domain) and g.https_endpoint,
        # does the client only want to communicate over HTTPS?
        "https_forced":
        c.user.https_forced,
        # debugging?
        "debug":
        g.debug,
        "send_logs":
        g.live_config["frontend_logging"],
        "server_time":
        math.floor(time.time()),
        "status_msg": {
            "fetching": _("fetching title..."),
            "submitting": _("submitting..."),
            "loading": _("loading...")
        },
        "is_fake":
        isinstance(c.site, FakeSubreddit),
        "fetch_trackers_url":
        g.fetch_trackers_url,
        "adtracker_url":
        g.adtracker_url,
        "clicktracker_url":
        g.clicktracker_url,
        "uitracker_url":
        g.uitracker_url,
        "static_root":
        static(''),
        "over_18":
        bool(c.over18),
        "new_window":
        bool(c.user.pref_newwindow),
        "vote_hash":
        c.vote_hash,
        "gold":
        gold,
        "has_subscribed":
        logged and c.user.has_subscribed,
        "pageInfo": {
            "verification": verification,
            "actionName": controller_name + '.' + action_name,
        },
    }

    if g.uncompressedJS:
        config["uncompressedJS"] = True

    if extra_config:
        config.update(extra_config)

    hooks.get_hook("js_config").call(config=config)

    return config
Example #52
0
def activity_stream_string_deleted_package_extra():
    return _("{actor} deleted the extra {extra} from the dataset {dataset}")
Example #53
0
def gettext(params):
    """Grabs a gettext string."""
    params['string'] = _(params['string'])
    return params
Example #54
0
def add_attr(attrs, kind, label=None, link=None, cssclass=None, symbol=None):
    from r2.lib.template_helpers import static

    symbol = symbol or kind

    if kind == 'F':
        priority = 1
        cssclass = 'friend'
        if not label:
            label = _('friend')
        if not link:
            link = '/prefs/friends'
    elif kind == 'S':
        priority = 2
        cssclass = 'submitter'
        if not label:
            label = _('submitter')
        if not link:
            raise ValueError("Need a link")
    elif kind == 'M':
        priority = 3
        cssclass = 'moderator'
        if not label:
            raise ValueError("Need a label")
        if not link:
            raise ValueError("Need a link")
    elif kind == 'A':
        priority = 4
        cssclass = 'admin'
        if not label:
            label = _('reddit admin, speaking officially')
        if not link:
            link = '/about/team'
    elif kind in ('X', '@'):
        priority = 5
        cssclass = 'gray'
        if not label:
            raise ValueError("Need a label")
    elif kind == 'V':
        priority = 6
        cssclass = 'green'
        if not label:
            raise ValueError("Need a label")
    elif kind == 'B':
        priority = 7
        cssclass = 'wrong'
        if not label:
            raise ValueError("Need a label")
    elif kind == 'special':
        priority = 98
    elif kind == "cake":
        priority = 99
        cssclass = "cakeday"
        symbol = "&#x1F370;"
        if not label:
            raise ValueError("Need a label")
        if not link:
            raise ValueError("Need a link")
    else:
        raise ValueError("Got weird kind [%s]" % kind)

    attrs.append((priority, symbol, cssclass, label, link))
Example #55
0
 def title(self):
     return _('messages') + ': ' + _(self.where)
Example #56
0
    ExploreSettings,
)

from pylons import app_globals as g
from pylons.i18n import _

# recommendation sources
SRC_MULTIREDDITS = 'mr'
SRC_EXPLORE = 'e'  # favors lesser known srs
SRC_CORRELATION = 'c'

ALL_RECOMMENDATION_SOURCES = set(
    [SRC_MULTIREDDITS, SRC_EXPLORE, SRC_CORRELATION])

# explore item types
TYPE_RISING = _("rising")
TYPE_DISCOVERY = _("discovery")
TYPE_HOT = _("hot")
TYPE_COMMENT = _("comment")


def get_recommendations(srs,
                        count=10,
                        source=SRC_MULTIREDDITS,
                        to_omit=None,
                        match_set=True,
                        over18=False):
    """Return subreddits recommended if you like the given subreddits.

    Args:
    - srs is one Subreddit object or a list of Subreddits
Example #57
0
 def title(self):
     return _('subreddits: ') + self.where
Example #58
0
 def title(self):
     return _('subreddits')
 def __init__(self, **kwargs):
     BoringPage.__init__(self,
                         pagename=_("reddit meetups"),
                         show_sidebar=False,
                         **kwargs)
Example #60
0
 def title(self):
     """Page <title>"""
     return _(self.title_text) + " : " + c.site.name