Beispiel #1
0
 def altera(self, obj=None, **attrs):
     try:
         evento = Evento.get(obj)
     except Exception:
         flash(_(u"ERRO: O evento que você está tentando alterar não existe."))
         raise redirect(url('/evento'))
     titulo = _(u"Altera evento")
     subtitulo = _(u"")
     form = EventoForm(submit_text=u"Salvar")
     if attrs:
         @validate(form)
         def get_errors(self, tg_errors=None, **data):
             return tg_errors, data
         tg_errors, data = get_errors(self, **attrs)
         if not tg_errors:
             try:
                 evento.set(
                     processoID = data['processoID'],
                     data = data['data'],
                     descricao = data['descricao'],
                     archive = data['archive'],
                     ownerID=identity.current.user.id,
                     )
                 flash(_(u"OK: Parte processo alterada."))
             except Exception:
                 flash(_(u"ERRO: Houve problemas ao alterar no banco de dados."))
             raise redirect(url('/evento'))
         else:
             flash(_("ATENÇÃO: Problemas no formulário, verifique as mensagens."))
     else:
         data = evento
     return dict(acoes=self._get_acoes(),titulo=titulo,subtitulo=subtitulo,select="Eventos",
                 form=form,data=data)
Beispiel #2
0
 def saveparticipant(self, new, eid, player, pseudonym="", id=0, submit=""):
     if (new):
         try:
             for q in Event.get(eid).participants:
                 if (q.player.user_name == player):
                     flash(
                         "Error: %s is already a participant in this event"
                         % player)
                     raise redirect(url("/editevent/" + str(eid)))
             p = Participant(event=Event.get(eid),
                             player=User.by_user_name(player),
                             pseudonym=Pseudonym.byName(player))
         except SQLObjectNotFound:
             flash(
                 "Error: Tried to add a participant to a nonexistent event")
             raise redirect(url("/news"))
     else:
         try:
             p = Participant.get(id)
         except SQLObjectNotFound:
             flash("Error: Tried to edit a nonexistent participant")
             raise redirect(url("/news"))
         try:
             p.player = User.by_user_name(player)
             p.pseudonym = Pseudonym.byName(pseudonym)
         except SQLObjectNotFound:
             flash(
                 "Error: Tried to change pseudonym to one that doesn't exist, or change pseudonym for a player that doesn't exist"
             )
             raise redirect(url("/news"))
     flash("Participant updated!")
     raise redirect(url("/editevent/" + str(eid)))
Beispiel #3
0
 def test_basic_urls(self):
     testutil.create_request("/")
     assert "/foo" == url("/foo")
     assert "foo/bar" == url(["foo", "bar"])
     assert url("/foo", bar=1, baz=2) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
Beispiel #4
0
    def size(self, width, id, tg_errors=None):
        if tg_errors:
            if "width" in tg_errors.keys():
                idx = tg_errors.keys().index("width")
                flash("Error: Invalid photo size: %s" % tg_errors.values()[idx])
            else:
                flash("Error: Invalid photo ID.")
            raise redirect(request.headers.get("Referer", url("/")))

        try:
            photo = Photo.get(id)
        except:
            # log.debug(traceback.format_exc())
            flash("Error: Photo %d does not exist." % id)
            raise redirect(request.headers.get("Referer", "/"))

        try:
            fullpath = os.path.join(self.photo_dir, photo.filename)
            img = IMG.open(fullpath)
            if img.size[0] > img.size[1]:
                height = int(img.size[1] * (float(float(width) / float(img.size[0]))))
            else:
                height = width
                width = int(img.size[0] * (float(float(height) / float(img.size[1]))))

            img = self._orient(img)
            out = img.resize((width, height), IMG.ANTIALIAS)
            return out.tostring("jpeg", "RGB")
        except:
            # log.debug(traceback.format_exc())
            flash("Error resizing photo, sending full photo.")
            raise redirect(url("/static/photos/%s" % photo.filename))
Beispiel #5
0
    def delete(self, id, tg_errors=None):
        if tg_errors:
            flash("Error: ID is not an integer.")
            raise redirect(request.headers.get("Referer", url("/")))

        try:
            album = Album.get(id)
        except:
            flash("Error: Album %d does not exist." % id)
            raise redirect(request.headers.get("Referer", url("/")))

        for photo in album.photos():
            fullname = os.path.join(config.get("photo_dir"), photo.filename)
            if os.path.exists(fullname):
                os.remove(fullname)

            try:
                photo.destroySelf()
            except:
                pass
                # log.debug(traceback.format_exc())

                # get rough page number to return to after delete.
        allalbums = list(Album.select(orderBy="-date"))
        idx = allalbums.index(album)
        page = (idx / 8) + 1

        album.destroySelf()
        flash("Album deleted successfully.")

        raise redirect(url("/?page=%d" % page))
Beispiel #6
0
    def delete(self, id, tg_errors=None):
        if tg_errors:
            flash("Error: ID is not an int.")
            return redirect(cherrypy.request.headers.get("Referer", url("/")))

        try:
            photo = Photo.get(id)
        except:
            flash("Error: Photo %d does not exist.")
            return redirect(cherrypy.request.headers.get("Referer", url("/")))

        albumid = photo.albumID

        fullname = os.path.join(self.photo_dir, photo.filename)
        if os.path.exists(fullname):
            os.remove(fullname)

        album = Album.get(albumid)
        idx = album.photos().index(photo)

        photo.destroySelf()

        page = (idx / 8) + 1

        raise redirect(url("/album/%d?page=%d" % (albumid, page)))
Beispiel #7
0
    def save_upgrade_registration(self, **form_data):
        ERROR_CRED_INVALIDAS =_(u'No fue posible completar la operación. Revisar que el padrón y el password sean correctos.')
        ERROR_FORMAT =_(u'No fue posible completar la operación. El padrón se compone solamente de números.')

        curso = Curso.get(form_data['curso'])
        if not curso.inscripcion_abierta:
            flash('La inscripción al curso elegido se encuentra cerrada.')
            raise redirect(url('/'))

        try:
            if not form_data['padron'].isdigit():
                error_msg = ERROR_FORMAT
            else:
                alumno = Alumno.by_padron(form_data['padron'])
                if alumno.equals_password(form_data['password']):
                    if not curso in alumno.cursos:
                        curso.add_alumno(alumno)
                        flash(_(u'La inscripción ha sido exitosa.'))
                    else:
                        flash(_(u'¡Ya estabas inscripto a este curso!'))
                    raise redirect(url('/'))

                else:
                    error_msg = ERROR_CRED_INVALIDAS
        except SQLObjectNotFound:
            error_msg = ERROR_CRED_INVALIDAS
        except DuplicateEntryError, e:
	    error_msg = _(u'Ya estás registrado en el curso %s.' % curso)
Beispiel #8
0
    def save(self, task_rpm, *args, **kw):
        """
        TurboGears method to upload task rpm package
        """
        rpm_path = Task.get_rpm_path(task_rpm.filename)

        if not task_rpm.filename:
            flash(_(u'No task RPM specified'))
            redirect(url("./new"))

        # we do it here, since we do not want to proceed
        # any further
        if len(task_rpm.filename) > 255:
            flash(_(u"Task RPM name should be <= 255 characters"))
            redirect(url("./new"))

        if os.path.exists("%s" % rpm_path):
            flash(
                _(u'Failed to import because we already have %s' %
                  task_rpm.filename))
            redirect(url("./new"))

        try:

            def write_data(f):
                siphon(task_rpm.file, f)

            task = Task.update_task(task_rpm.filename, write_data)
        except Exception, err:
            session.rollback()
            log.exception('Failed to import %s', task_rpm.filename)
            flash(_(u'Failed to import task: %s' % err))
            redirect(url("./new"))
Beispiel #9
0
Datei: rss.py Projekt: tyll/bodhi
    def get_package_updates(self, package, release):
        entries = []
        pkg = Package.byName(package)
        base = config.get('base_address')
        for i, update in enumerate(pkg.updates()):
            delta = datetime.utcnow() - update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            if release and not update.release.name == release:
                continue

            entries.append({
                'id': base + url(update.get_url()),
                'summary': update.notes,
                'link': base + url(update.get_url()),
                'published': update.date_submitted,
                'updated': update.date_submitted,
                'title': update.title,
            })
        return dict(title='Latest Updates for %s' % package,
                    subtitle="",
                    link=config.get('base_address') + url('/'),
                    entries=entries)
Beispiel #10
0
Datei: rss.py Projekt: tyll/bodhi
    def get_latest_comments(self, user=None):
        entries = []
        if user:
            comments = Comment.select(Comment.q.author == user,
                                      orderBy=Comment.q.timestamp).reversed()
        else:
            comments = Comment.select(Comment.q.author != 'bodhi',
                                      orderBy=Comment.q.timestamp).reversed()
        for comment in comments:
            delta = datetime.utcnow() - comment.update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            entries.append({
                'id':
                config.get('base_address') + url(comment.update.get_url()),
                'summary':
                comment.text,
                'published':
                comment.timestamp,
                'link':
                config.get('base_address') + url(comment.update.get_url()),
                'title':
                "[%s] [%s] [%d]" %
                (comment.update.title, comment.author, comment.karma)
            })
        return dict(
            title='Latest Comments',
            subtitle="",
            link=config.get('base_address') + url('/'),
            entries=entries,
        )
Beispiel #11
0
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            if identity.in_group("issuer"):
                forward_url = url("issuer")
            elif identity.in_group("bidder"):
                forward_url = url("bidder")
            elif identity.in_group("admin"):
                forward_url = url("admin")
            raise redirect(forward_url)

        forward_url = None
        previous_url = request.path

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                    "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                    "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message=msg,
                    previous_url=previous_url,
                    logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)
    def desconfirmar(self, obj=None, **attrs):

        try:
            orcamento = Orcamento.get(obj)
        except AssertionError:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')
        except ValueError:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')
        except SQLObjectNotFound:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')

        if orcamento.data_confirmacao:
            for item in orcamento.itens:
                item.subgrupoequipamento.reservas -= item.quantidade
            orcamento.data_confirmacao = None
            orcamento.data_prev_pagamento = None
            orcamento.data_pago = None
            flash("Orçamento desconfirmado.")
            raise redirect(url('/orcamento/editar/%s' % orcamento.id))
        else:
            flash("Este orçamento ainda não foi confirmado.")
            raise redirect(url('/orcamento/editar/%s' % orcamento.id))
Beispiel #13
0
    def get_latest_comments(self, user=None):
        entries = []
        if user:
            comments = Comment.select(Comment.q.author == user,
                    orderBy=Comment.q.timestamp).reversed()
        else:
            comments = Comment.select(Comment.q.author != 'bodhi',
                    orderBy=Comment.q.timestamp).reversed()
        for comment in comments:
            delta = datetime.utcnow() - comment.update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            entries.append({
                'id'        : config.get('base_address') + \
                              url(comment.update.get_url()),
                'summary'   : comment.text,
                'published' : comment.timestamp,
                'link'      : config.get('base_address') + \
                              url(comment.update.get_url()),
                              'title'     : "[%s] [%s] [%d]" % (
                                  comment.update.title, comment.author,
                                  comment.karma)
            })
        return dict(
                title = 'Latest Comments',
                subtitle = "",
                link = config.get('base_address') + url('/'),
                entries = entries,
        )
Beispiel #14
0
    def get_package_updates(self, package, release):
        entries = []
        pkg = Package.byName(package)
        base = config.get('base_address')
        for i, update in enumerate(pkg.updates()):
            delta = datetime.utcnow() - update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            if release and not update.release.name == release:
                continue

            entries.append({
                'id'        : base + url(update.get_url()),
                'summary'   : update.notes,
                'link'      : base + url(update.get_url()),
                'published' : update.date_submitted,
                'updated'   : update.date_submitted,
                'title'     : update.title,
            })
        return dict(
                title = 'Latest Updates for %s' % package,
                subtitle = "",
                link = config.get('base_address') + url('/'),
                entries = entries
        )
Beispiel #15
0
    def saveparticipant(self,new,eid,player,pseudonym="",id=0,submit=""):
         if(new):
	     try:
	         for q in Event.get(eid).participants:
	             if(q.player.user_name==player):
		         flash("Error: %s is already a participant in this event"%player)
		         raise redirect(url("/editevent/"+str(eid)))
	         p=Participant(event=Event.get(eid),player=User.by_user_name(player),pseudonym=Pseudonym.byName(player))
             except SQLObjectNotFound:
	         flash("Error: Tried to add a participant to a nonexistent event")
		 raise redirect(url("/news"))
	 else:
	     try:
	         p=Participant.get(id)
             except SQLObjectNotFound:
	         flash("Error: Tried to edit a nonexistent participant")
		 raise redirect(url("/news"))
	     try:
	         p.player=User.by_user_name(player)
  	         p.pseudonym=Pseudonym.byName(pseudonym)
	     except SQLObjectNotFound:
	         flash("Error: Tried to change pseudonym to one that doesn't exist, or change pseudonym for a player that doesn't exist")
		 raise redirect(url("/news"))
	 flash("Participant updated!")
	 raise redirect(url("/editevent/"+str(eid)))
Beispiel #16
0
    def save(self, task_rpm, *args, **kw):
        """
        TurboGears method to upload task rpm package
        """
        rpm_path = Task.get_rpm_path(task_rpm.filename)

        if not task_rpm.filename:
            flash(_(u'No task RPM specified'))
            redirect(url("./new"))

        # we do it here, since we do not want to proceed
        # any further
        if len(task_rpm.filename) > 255:
            flash(_(u"Task RPM name should be <= 255 characters"))
            redirect(url("./new"))

        if os.path.exists("%s" % rpm_path):
            flash(_(u'Failed to import because we already have %s' % 
                                                     task_rpm.filename ))
            redirect(url("./new"))

        try:
            def write_data(f):
                siphon(task_rpm.file, f)
            task = Task.update_task(task_rpm.filename, write_data)
        except Exception, err:
            session.rollback()
            log.exception('Failed to import %s', task_rpm.filename)
            flash(_(u'Failed to import task: %s' % err))
            redirect(url("./new"))
Beispiel #17
0
    def saveuser(self,oldname,name,address,college,water,notes,password,email,adjustment):
        if(oldname):
		try:
			u=User.by_user_name(oldname)
		except SQLObjectNotFound:
			flash("Error: Tried to edit a nonexistent player")
			raise redirect(url("/scoresname"))
		#u.user_name=name #don't give too much opportunity to break things
		u.address=address
		u.college=college
		u.water=water
		u.notes=notes
		if(password):
			u.password=password
		u.email_address=email
		if(adjustment!=u.adjustment and not identity.in_group('admin')):
			flash("Error: Tried to change a score adjustment while not umpire")
			raise redirect(url('/scoresname'))
		u.adjustment=adjustment
	else:
		u=User(user_name=name,address=address,college=college,water=water,notes=notes,password=password,email_address=email,score=0.0,adjustment=adjustment)
		p=Pseudonym(name=name,player=u)
	self.updatescores()
	flash("Player updated!")
	raise redirect(url("/scoresname"))
Beispiel #18
0
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            if identity.in_group("issuer"):
                forward_url= url("issuer")
            elif identity.in_group("bidder"):
                forward_url= url("bidder")
            elif identity.in_group("admin"):
                forward_url = url("admin")           
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")
            
        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)
Beispiel #19
0
 def savereport(self, new, eid, player, text, id=0):
     if (new):
         try:
             r = Report(speaker=User.by_user_name(player),
                        event=Event.get(eid),
                        content=text)
         except SQLObjectNotFound:
             flash(
                 "Error: Tried to add report by a nonexistent player, or to a nonexistent event"
             )
             raise redirect(url("/news"))
     else:
         try:
             r = Report.get(id)
             r.content = text
             #nothing else really should be being edited, but will update it all for future compatibility
             r.speaker = User.by_user_name(player)
             r.event = Event.get(eid)
         except SQLObjectNotFound:
             flash(
                 "Error: Tried to edit a nonexistent report, or a report for a nonexistent event, or write a report as a nonexistent player."
             )
             raise redirect(url("/news"))
     flash("Report updated!")
     raise redirect(url("/news"))
Beispiel #20
0
 def deleteevent(self, id):
     try:
         Event.delete(id)
         flash("Event deleted!")
         raise redirect(url("/news"))
     except SQLObjectNotFound:
         flash("Error: Tried to delete an event that doesn't exist")
         raise redirect(url("/news"))
Beispiel #21
0
    def deleteevent(self,id):
        try:
	    Event.delete(id)
	    flash("Event deleted!")
	    raise redirect(url("/news"))
        except SQLObjectNotFound:
	    flash("Error: Tried to delete an event that doesn't exist")
	    raise redirect(url("/news"))
 def test_basic_urls(self):
     self.app.get("/")
     assert "/foo" == url("/foo")
     assert "foo/bar" == url(["foo", "bar"])
     assert url("/foo", bar=1, baz=2) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
Beispiel #23
0
 def get_curso_actual(self):
     try:
         contexto = SessionHelper().get_contexto_usuario()
         return contexto.get_curso()
     except SinCursosDisponibles as e:
         if identity.has_permission(Permiso.admin):
             raise redirect(url('/curso/new'))
         else:
             raise redirect(url('/error/%s' % e))
Beispiel #24
0
 def test_approots(self):
     testutil.create_request("/subthing/")
     assert cherrypy.response.status.startswith("200")
     assert url("foo") == "foo"
     assert url("/foo") == "/subthing/foo"
     testutil.create_request("/nosubthing/")
     assert cherrypy.response.status.startswith("404")
     assert url("foo") == "foo"
     assert url("/foo") == "/foo"
Beispiel #25
0
 def test_basicurls(self):
     testutil.createRequest("/")
     self.failUnlessEqual("/foo", url("/foo"))
     self.failUnlessEqual("foo/bar", url(["foo", "bar"]))
     assert url("/foo", bar=1, baz=2) in \
             ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in \
             ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
Beispiel #26
0
 def test_basic_urls(self):
     testutil.create_request("/")
     assert "/foo" == url("/foo")
     assert "foo/bar" == url(["foo", "bar"])
     assert url("/foo", bar=1, baz=2) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
Beispiel #27
0
 def test_approots(self):
     testutil.create_request("/subthing/")
     assert cherrypy.response.status.startswith("200")
     assert url("foo") == "foo"
     assert url("/foo") == "/subthing/foo"
     testutil.create_request("/nosubthing/")
     assert cherrypy.response.status.startswith("404")
     assert url("foo") == "foo"
     assert url("/foo") == "/foo"
Beispiel #28
0
    def __init__(self, current_page, pages, page_count, input_values, limit,
                 order, ordering, row_count, var_name):

        self.var_name = var_name
        self.pages = pages
        self.limit = limit
        self.page_count = page_count
        self.current_page = current_page
        self.input_values = input_values
        self.order = order
        self.ordering = ordering
        self.row_count = row_count
        self.first_item = page_count and ((current_page - 1) * limit + 1) or 0
        self.last_item = min(current_page * limit, row_count)

        self.reversed = ordering and ordering[0][0] == '-'

        # If ordering is empty, don't add it.
        input_values = {var_name + '_tgp_limit': limit}
        if ordering:
            input_values[var_name + '_tgp_ordering'] = ','.join(ordering)
        self.input_values.update(input_values)

        if current_page < page_count:
            self.input_values.update({
                var_name + '_tgp_no': current_page + 1,
                var_name + '_tgp_limit': limit
            })
            self.href_next = turbogears.url(cherrypy.request.path_info,
                                            self.input_values)
            self.input_values.update({
                var_name + '_tgp_no': 'last',
                var_name + '_tgp_limit': limit
            })
            self.href_last = turbogears.url(cherrypy.request.path_info,
                                            self.input_values)
        else:
            self.href_next = None
            self.href_last = None

        if current_page > 1:
            self.input_values.update({
                var_name + '_tgp_no': current_page - 1,
                var_name + '_tgp_limit': limit
            })
            self.href_prev = turbogears.url(cherrypy.request.path_info,
                                            self.input_values)
            self.input_values.update({
                var_name + '_tgp_no': 1,
                var_name + '_tgp_limit': limit
            })
            self.href_first = turbogears.url(cherrypy.request.path_info,
                                             self.input_values)
        else:
            self.href_prev = None
            self.href_first = None
Beispiel #29
0
    def __init__(self, current_page, pages, page_count, input_values,
                 limit, order, ordering, row_count, var_name):

        self.var_name = var_name
        self.pages = pages
        self.limit = limit
        self.page_count = page_count
        self.current_page = current_page
        self.input_values = input_values
        self.order = order
        self.ordering = ordering
        self.row_count = row_count
        self.first_item = page_count and ((current_page - 1) * limit + 1) or 0
        self.last_item = min(current_page * limit, row_count)

        self.reversed = ordering and ordering[0][0] == '-'

        # If ordering is empty, don't add it.
        input_values = {var_name + '_tgp_limit': limit}
        if ordering:
            input_values[var_name + '_tgp_ordering'] = ','.join(ordering)
        self.input_values.update(input_values)

        if current_page < page_count:
            self.input_values.update({
                var_name + '_tgp_no': current_page + 1,
                var_name + '_tgp_limit': limit
            })
            self.href_next = turbogears.url(
                cherrypy.request.path_info, self.input_values)
            self.input_values.update({
                var_name + '_tgp_no': 'last',
                var_name + '_tgp_limit': limit
            })
            self.href_last = turbogears.url(
                cherrypy.request.path_info, self.input_values)
        else:
            self.href_next = None
            self.href_last = None

        if current_page > 1:
            self.input_values.update({
                var_name + '_tgp_no': current_page - 1,
                var_name + '_tgp_limit': limit
            })
            self.href_prev = turbogears.url(
                cherrypy.request.path_info, self.input_values)
            self.input_values.update({
                var_name + '_tgp_no': 1,
                var_name + '_tgp_limit': limit
            })
            self.href_first = turbogears.url(
                cherrypy.request.path_info, self.input_values)
        else:
            self.href_prev = None
            self.href_first = None
Beispiel #30
0
 def deletekill(self, kid):
     try:
         eid = Kill.get(kid).event.id
     except SQLObjectNotFound:
         flash("Error: you tried to delete a kill that doesn't exist!")
         raise redirect(url("/news"))
     Kill.delete(kid)
     self.updatescores()
     flash("Kill removed!")
     raise redirect(url("/editevent/" + str(eid)))
Beispiel #31
0
    def deleteinnocentkill(self,iid):
        try:
	    eid=InnocentKill.get(iid).event.id
	except SQLObjectNotFound:
	    flash("Error: you tried to delete an innocent kill that doesn't exist!")
	    raise redirect(url("/news"))
        InnocentKill.delete(iid)
	self.updatescores()
	flash("Innocent Kill removed!")
	raise redirect(url("/editevent/"+str(eid)))
 def default(self,*args):
     if len(args) != 1:
         raise cherrypy.HTTPRedirect(turbogears.url("/panels"))
     panelname=args[0]
     print "panel renderer: "+panelname+"\n"
     try:
         panelDef = readPanelDefinition("../resources/paneldef/",panelname)
     except PanelDefinitionException, e:
         turbogears.flash(str(e))
         raise cherrypy.HTTPRedirect(turbogears.url("/panels"))
Beispiel #33
0
    def saveinnocentkill(self,eid,killer,licit):
      try:
        k=InnocentKill(event=Event.get(eid),killer=User.by_user_name(killer),licit=licit)
	self.updatescores()
	flash("Innocent Kill added!")
	for l in Kill.select():
	    if((l.victim == k.killer) and l.event.datetime < k.event.datetime and l.event.datetime >= (k.event.datetime - datetime.timedelta(0,14400))):
                flash("Warning: %s is listed as being killed in the event %s, which was less than four hours before this event."%(l.victim.user_name,str(l.event)))
	raise redirect(url("/editevent/"+str(eid)))
      except SQLObjectNotFound:
          flash("Error: Tried to add an innocent kill to a nonexistent event.")
	  raise redirect(url("/news"))
Beispiel #34
0
    def send_digest_mail(self):
        """
        Send digest mail to mailing lists
        """
        for prefix, content in self.testing_digest.items():
            log.debug("Sending digest for updates-testing %s" % prefix)
            maildata = u""
            try:
                security_updates = self.get_security_updates(prefix)
                if security_updates:
                    maildata += u"The following %s Security updates need testing:\n Age  URL\n" % prefix
                    for update in security_updates:
                        maildata += u" %3i  %s%s\n" % (
                            update.days_in_testing,
                            config.get("base_address"),
                            url(update.get_url()),
                        )
                    maildata += "\n\n"

                critpath_updates = self.get_unapproved_critpath_updates(prefix)
                if critpath_updates:
                    maildata += u"The following %s Critical Path updates have yet to be approved:\n Age URL\n" % prefix
                    for update in self.get_unapproved_critpath_updates(prefix):
                        maildata += u" %3i  %s%s\n" % (
                            update.days_in_testing,
                            config.get("base_address"),
                            url(update.get_url()),
                        )
                    maildata += "\n\n"
            except Exception, e:
                log.exception(e)

            maildata += u"The following builds have been pushed to %s updates-testing\n\n" % prefix
            # get a list af all nvr's
            updlist = content.keys()
            # sort the list
            updlist.sort()
            # Add the list of builds to the mail
            for pkg in updlist:
                maildata += u"    %s\n" % pkg
            # Add some space between the short list and the Details"
            maildata += u"\nDetails about builds:\n\n"
            # Add the detail of each build
            for nvr in updlist:
                maildata += u"\n" + self.testing_digest[prefix][nvr]
            release = Release.select(Release.q.long_name == prefix)[0]
            mail.send_mail(
                config.get("bodhi_email"),
                config.get("%s_test_announce_list" % release.id_prefix.lower().replace("-", "_")),
                "%s updates-testing report" % prefix,
                maildata,
            )
Beispiel #35
0
 def remove(self, obj=None):
     try:
         evento = Evento.get(obj)
     except Exception:
         flash(_(u"ERRO: O evento que você está tentando remover não existe."))
         raise redirect(url('/evento'))
     else:
         if evento.ownerID != identity.current.user.id:
             flash(_(u"ERRO: O evento que você está tentando remover não existe."))
             raise redirect(url('/evento'))
     evento.destroySelf()
     flash(_(u"OK: Evento removido."))
     raise redirect(url('/evento'))
Beispiel #36
0
 def baixa(self, obj=None):
     try:
         evento = Evento.get(obj)
     except Exception:
         flash(_(u"ERRO: O evento que você está tentando remover não existe."))
         raise redirect(url('/evento'))
     else:
         if evento.ownerID != identity.current.user.id:
             flash(_(u"ERRO: O evento que você está tentando remover não existe."))
             raise redirect(url('/evento'))
     evento.archive = True
     flash(_(u"OK: Evento arquivado."))
     raise redirect(url('/evento/inicio'))
Beispiel #37
0
    def __init__(self, current_page, pages, page_count, input_values, 
                 limit, order, ordering, row_count):
                 
        self.pages = pages
        self.limit = limit
        self.page_count = page_count
        self.current_page = current_page
        self.input_values = input_values
        self.order = order
        self.ordering = ordering
        self.row_count = row_count
        self.first_item = (current_page - 1) * limit + 1
        self.last_item = min(current_page * limit, row_count)
        self.reversed = False

        # Should reversed be true?
        for (field_name, ordering_values) in ordering.items():
            if ordering_values[0] == 0 and not ordering_values[1]:
                self.reversed = True

        # If ordering is empty, don't add it.
        input_values = dict(tg_paginate_limit=limit)
        if ordering:
            input_values['tg_paginate_ordering'] = ordering
        self.input_values.update(input_values)

        if current_page < page_count:
            self.input_values.update(dict(
                                tg_paginate_no=current_page+1,
                                tg_paginate_limit=limit))
            self.href_next = turbogears.url(cherrypy.request.path, input_values)
            self.input_values.update(dict(
                                tg_paginate_no=page_count,
                                tg_paginate_limit=limit))
            self.href_last = turbogears.url(cherrypy.request.path, input_values)
        else:
            self.href_next = None
            self.href_last = None
            
        if current_page > 1:
            self.input_values.update(dict(
                                tg_paginate_no=current_page-1,
                                tg_paginate_limit=limit))
            self.href_prev = turbogears.url(cherrypy.request.path, input_values)
            self.input_values.update(dict(
                                tg_paginate_no=1,
                                tg_paginate_limit=limit))
            self.href_first = turbogears.url(cherrypy.request.path, input_values)
        else:
            self.href_prev = None
            self.href_first = None
Beispiel #38
0
 def addinnocentkill(self, eid):
     try:
         return {'event': Event.get(eid)}
     except SQLObjectNotFound:
         flash(
             "Error: Tried to add an innocent kill to a nonexistent event.")
         raise redirect(url("/news"))
Beispiel #39
0
def add_system():
    # We accept JSON or form-encoded for convenience
    if request.json:
        if 'fqdn' not in request.json:
            raise BadRequest400('Missing fqdn key')
        new_fqdn = request.json['fqdn']
    elif request.form:
        if 'fqdn' not in request.form:
            raise BadRequest400('Missing fqdn parameter')
        new_fqdn = request.form['fqdn']
    else:
        raise UnsupportedMediaType415
    with convert_internal_errors():
        if System.query.filter(System.fqdn == new_fqdn).count() != 0:
            raise Conflict409('System with fqdn %r already exists' % new_fqdn)
        system = System(fqdn=new_fqdn, owner=identity.current.user)
        session.add(system)
        # new systems are visible to everybody by default
        system.custom_access_policy = SystemAccessPolicy()
        system.custom_access_policy.add_rule(SystemPermission.view,
                                             everybody=True)
    # XXX this should be 201 with Location: /systems/FQDN/ but 302 is more
    # convenient because it lets us use a traditional browser form without AJAX
    # handling, and for now we're redirecting to /view/FQDN until that is moved
    # to /systems/FQDN/
    return flask_redirect(url(u'/view/%s#essentials' % system.fqdn))
Beispiel #40
0
 def url(self, url):
     """
     Returns the absolute path for the given url.
     """
     prefix = self.request_local.environ['toscawidgets.prefix']
     
     return '/' + turbogears.url(prefix+url).lstrip('/')
Beispiel #41
0
    def __init__(self, *args, **kw):
        kw['search_url'] = url("/powertypes/by_name?anywhere=1"),
        kw['search_name'] = 'power'
        super(PowerTypes, self).__init__(*args, **kw)

        self.search_col = PowerType.name
        self.search_mapper = PowerType
Beispiel #42
0
class TaskActionWidget(RPC):
    template = 'bkr.server.templates.task_action'
    params = ['redirect_to']
    action = url('/tasks/disable_from_ui')
    javascript = [LocalJSLink('bkr', '/static/javascript/task_disable.js')]

    def __init__(self, *args, **kw):
        super(TaskActionWidget, self).__init__(*args, **kw)

    def display(self, task, action=None, **params):
        id = task.id
        task_details={'id': 'disable_%s' % id,
            't_id' : id}
        params['task_details'] = task_details
        if action:
            params['action'] = action
        return super(TaskActionWidget, self).display(task, **params)

    def update_params(self, d):
        super(TaskActionWidget, self).update_params(d)
        d['task_details']['onclick'] = "TaskDisable('%s',%s, %s); return false;" % (
            d.get('action'),
            jsonify_for_html({'t_id': d['task_details'].get('t_id')}),
            jsonify_for_html(self.get_options(d)),
            )
Beispiel #43
0
 def index(self, pagename="FrontPage" ):
   box = hub.getConnection()
   player_fields = {
     Player : [
       ('Name', 'name'),
       ('Birth Date', 'birthdate'),
       #('Team', 'team'),
       ('Points', 'points'),
     ],
     Team : [
       ('City', 'city'),
       ('NickName', 'nickname'),
     ],
   }
   team_fields = [
     ('City', 'city'),
     ('NickName', 'nickname'),
   ]
   page = box.Page(pagename=pagename)
   if page == None:
     raise turbogears.redirect("notfound", pagename = pagename)
   content = publish_parts(page.data, writer_name="html")['html_body']
   root = str(turbogears.url('/'))
   content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content)
   return dict(
     data=content,
     page=page,
     players=box.recall(Team + Player),
     teams=box.recall(Team),
     players_widget=DataGrid(fields=player_fields),
     teams_widget=DataGrid(fields=team_fields),
   )
Beispiel #44
0
def absolute_url(tgpath,
                 tgparams=None,
                 scheme=None,
                 labdomain=False,
                 webpath=True,
                 **kw):
    """
    Like turbogears.url, but makes the URL absolute (with scheme, hostname, 
    and port from the tg.url_scheme and tg.url_domain configuration 
    directives).
    If labdomain is True we serve an alternate tg.proxy_domain if defined
    in server.cfg.  This is to support multi-home systems which have
    different external vs internal names.
    """
    order = []
    if labdomain:
        order.append(config.get('tg.lab_domain'))
    order.extend([
        config.get('tg.url_domain'),
        config.get('servername'),
        socket.getfqdn()
    ])

    # TODO support relative paths
    if webpath:
        theurl = url(tgpath, tgparams, **kw)
    else:
        theurl = url_no_webpath(tgpath, tgparams, **kw)
    assert theurl.startswith('/')
    scheme = scheme or config.get('tg.url_scheme', 'http')
    host_port = filter(None, order)[0]
    return '%s://%s%s' % (scheme, host_port, theurl)
Beispiel #45
0
    def index(self, *args, **kw):
        tasks = Task.query
        # FIXME What we really want is some default search options
        # For now we won't show deleted/invalid tasks in the grid
        # but for data integrity reasons we will allow you to view
        # the task directly.  Ideally we would have a default search
        # option of valid=True which the user could change to false
        # to see all "deleted" tasks
        tasks = tasks.filter(Task.valid == True)

        tasks_return = self._tasks(tasks, **kw)
        searchvalue = None
        search_options = {}
        if tasks_return:
            if 'tasks_found' in tasks_return:
                tasks = tasks_return['tasks_found']
            if 'searchvalue' in tasks_return:
                searchvalue = tasks_return['searchvalue']
            if 'simplesearch' in tasks_return:
                search_options['simplesearch'] = tasks_return['simplesearch']

        tasks_grid = myPaginateDataGrid(fields=[
            widgets.PaginateDataGrid.Column(
                name='name',
                getter=lambda x: make_link("./%s" % x.id, x.name),
                title='Name',
                options=dict(sortable=True)),
            widgets.PaginateDataGrid.Column(name='description',
                                            getter=lambda x: x.description,
                                            title='Description',
                                            options=dict(sortable=True)),
            widgets.PaginateDataGrid.Column(name='version',
                                            getter=lambda x: x.version,
                                            title='Version',
                                            options=dict(sortable=True)),
            widgets.PaginateDataGrid.Column(
                name='action',
                getter=lambda x: self.task_list_action_widget.display(
                    task=x,
                    type_='tasklist',
                    title='Action',
                    options=dict(sortable=False))),
        ])

        search_bar = SearchBar(
            name='tasksearch',
            label=_(u'Task Search'),
            table=search_utility.Task.search.create_complete_search_table(),
            search_controller=url("/get_search_options_task"),
        )
        return dict(
            title="Task Library",
            grid=tasks_grid,
            list=tasks,
            search_bar=search_bar,
            action='.',
            action_widget=self.
            task_list_action_widget,  #Hack,inserts JS for us.
            options=search_options,
            searchvalue=searchvalue)
Beispiel #46
0
def doit():
    distro_trees = []
    for id in request.form.getlist('distro_tree_id'):
        try:
            distro_trees.append(DistroTree.by_id(id))
        except NoResultFound:
            raise BadRequest400('Distro tree %r does not exist' % id)
    job_details = {}
    job_details['pick'] = request.form.get('pick') or 'auto'
    if job_details['pick'] == 'fqdn':
        try:
            job_details['system'] = System.by_fqdn(request.form.get('system'),
                                                   identity.current.user)
        except NoResultFound:
            raise BadRequest400('System %s not found' %
                                request.form.get('system'))
    elif job_details['pick'] == 'lab':
        try:
            job_details['lab'] = LabController.by_name(request.form.get('lab'))
        except NoResultFound:
            raise BadRequest400('Lab controller %s not found' %
                                request.form.get('lab'))
    days = int(request.form.get('reserve_days') or DEFAULT_RESERVE_DAYS)
    days = min(days, MAX_DAYS_PROVISION)
    job_details['reservetime'] = days * 24 * 60 * 60
    job_details['whiteboard'] = request.form.get('whiteboard')
    job_details['ks_meta'] = request.form.get('ks_meta')
    job_details['koptions'] = request.form.get('koptions')
    job_details['koptions_post'] = request.form.get('koptions_post')
    with convert_internal_errors():
        job = Job.provision_system_job(distro_trees, **job_details)
    return 'Created %s' % job.t_id, 201, [('Location',
                                           url('/jobs/%s' % job.id))]
Beispiel #47
0
class CaptchaInputField(FormField):
    """Basic captcha widget.
    
    This widget doesn't do any validation, and should only be used if you 
    want to do your own validation.
    """
    enable = tg.config.get('tgcaptcha.audio', True)
    sound = ""
    if enable:
        sound = """
        <a href="${controller}/sound/${payload}">
            <img src="${tg.url('/static/theme/fas/images/gnome_audio_volume_medium.png')}"
            alt="Audio file" />
        </a>
        """
    template = """
    <span xmlns:py="http://purl.org/kid/ns#">
        <img id="${field_id}_img" 
            src="${controller}/image/${payload}" 
            alt="${alt}"/>
        %s
        <input 
            type="text"
            name="${name}"
            class="${field_class}"
            id="${field_id}"
            py:attrs="attrs"/> 
    </span>
    """ % sound
    params = ['controller', 'payload', 'alt', "attrs"]
    controller = tg.url(tg.config.get("tgcaptcha.controller", "/captcha"))
    alt = _('obfuscated letters')
    attrs = {}
Beispiel #48
0
def absolute_url(tgpath, tgparams=None, scheme=None, 
                 labdomain=False, webpath=True, **kw):
    """
    Like turbogears.url, but makes the URL absolute (with scheme, hostname, 
    and port from the tg.url_scheme and tg.url_domain configuration 
    directives).
    If labdomain is True we serve an alternate tg.proxy_domain if defined
    in server.cfg.  This is to support multi-home systems which have
    different external vs internal names.
    """
    if labdomain and config.get('tg.lab_domain'):
        host_port = config.get('tg.lab_domain')
    elif config.get('tg.url_domain'):
        host_port = config.get('tg.url_domain')
    elif config.get('servername'): # deprecated
        host_port = config.get('servername')
    else:
        # System hostname is cheap to look up (no DNS calls) but there is no 
        # requirement that it be fully qualified.
        kernel_hostname = socket.gethostname()
        if '.' in kernel_hostname:
            host_port = kernel_hostname
        else:
            # Last resort, let glibc do a DNS lookup through search domains etc.
            host_port = socket.getfqdn()

    # TODO support relative paths
    theurl = url(tgpath, tgparams, **kw)
    if not webpath:
        theurl = strip_webpath(theurl)
    assert theurl.startswith('/')
    scheme = scheme or config.get('tg.url_scheme', 'http')
    return '%s://%s%s' % (scheme, host_port, theurl)
Beispiel #49
0
 def savepseudonym(self, new, name, playerid, id=0, submit=""):
     if (new):
         try:
             p = Pseudonym(player=User.get(playerid), name=name)
         except SQLObjectNotFound:
             flash("Error: Tried to add a pseudonym to a nonexistent user")
             raise redirect(url("/scoresname"))
     else:
         try:
             p = Pseudonym.get(id)
         except SQLObjectNotFound:
             flash("Error: Tried to edit a nonexistent pseudonym")
             raise redirect(url("/scoresname"))
         p.name = name
     flash("Pseudonym updated!")
     raise redirect(url("/edituser/" + p.player.user_name))
Beispiel #50
0
def make_link(url, text, **kwargs):
    # make an <a> element
    a = Element('a', href=turbogears.url(url))
    a.text = text
    if kwargs.get('elem_class', None):
        a.attrib['class']=kwargs.get('elem_class')
    return a
Beispiel #51
0
    def __init__(self, *args, **kw):
        kw['search_url'] = url("/configuration/by_name?anywhere=1"),
        kw['search_name'] = 'name'
        super(Configuration, self).__init__(*args, **kw)

        self.search_col = ConfigItem.name
        self.search_mapper = ConfigItem
Beispiel #52
0
    def __init__(self,*args,**kw):
        kw['search_url'] = url("/configuration/by_name?anywhere=1"),
        kw['search_name'] = 'name'
        super(Configuration, self).__init__(*args, **kw)

        self.search_col = ConfigItem.name
        self.search_mapper = ConfigItem
Beispiel #53
0
def absolute_url(tgpath, tgparams=None, scheme=None, 
                 labdomain=False, webpath=True, **kw):
    """
    Like turbogears.url, but makes the URL absolute (with scheme, hostname, 
    and port from the tg.url_scheme and tg.url_domain configuration 
    directives).
    If labdomain is True we serve an alternate tg.proxy_domain if defined
    in server.cfg.  This is to support multi-home systems which have
    different external vs internal names.
    """
    order = []
    if labdomain:
        order.append(config.get('tg.lab_domain'))
    order.extend([config.get('tg.url_domain'),
                  config.get('servername'),
                  socket.getfqdn()])

    # TODO support relative paths
    if webpath:
        theurl = url(tgpath, tgparams, **kw)
    else:
        theurl = url_no_webpath(tgpath, tgparams, **kw)
    assert theurl.startswith('/')
    scheme = scheme or config.get('tg.url_scheme', 'http')
    host_port = filter(None, order)[0]
    return '%s://%s%s' % (scheme, host_port, theurl)
Beispiel #54
0
    def __init__(self,*args,**kw):
        kw['search_url'] =  url("/keytypes/by_name?anywhere=1"),
        kw['search_name'] = 'key'
        super(KeyTypes,self).__init__(*args,**kw)

        self.search_col = Key.key_name
        self.search_mapper = Key
Beispiel #55
0
 def remove(self, obj=None):
     try:
         adversa = Adversa.get(obj)
     except Exception:
         flash(_(u"ERRO: A parte adversa que você está tentando remover não existe."))
         raise redirect(url('/adversa'))
     else:
         if adversa.ownerID != identity.current.user.id:
             flash(_(u"ERRO: A parte adversa que você está tentando remover não existe."))
             raise redirect(url('/adversa'))
     if adversa.processos:
         flash(_(u"ERRO: Existe vínculos de processos a esta parte, não é possível remover."))
     else:
         cliente.destroySelf()
         flash(_(u"OK: Parte removida."))
     raise redirect(url('/adversa'))
Beispiel #56
0
 def po_upload(self, myFile, code):
     path = os.path.join(self.locales_directory(),
             code, 'LC_MESSAGES', 'messages.po')
     f = codecs.open(path, 'wb', 'utf-8')
     f.write(unicode(myFile.file.read(), 'utf-8', errors='replace'))
     f.close()
     raise cherrypy.HTTPRedirect(turbogears.url('language', code=code))
Beispiel #57
0
 def save_state(self, state):
     """Pickle the state."""
     try:
         pickle.dump(state, open(self.state_path(), 'wb'), True)
     except pickle.PicklingError, e:
         msg = 'Fail to store pickled session file %s' % e
         raise cherrypy.HTTPRedirect(turbogears.url('error', msg=msg))
Beispiel #58
0
    def __init__(self, *args, **kw):
        kw['search_url'] = url("/users/by_name?anywhere=1&ldap=0")
        kw['search_name'] = 'user'
        super(Users, self).__init__(*args, **kw)

        self.search_col = User.user_name
        self.search_mapper = User
Beispiel #59
0
    def send_digest_mail(self):
        '''
        Send digest mail to mailing lists
        '''
        for prefix, content in self.testing_digest.items():
            log.debug("Sending digest for updates-testing %s" % prefix)
            maildata = u''
            try:
                security_updates = self.get_security_updates(prefix)
                if security_updates:
                    maildata += u'The following %s Security updates need testing:\n Age  URL\n' % prefix
                    for update in security_updates:
                        maildata += u' %3i  %s%s\n' % (
                            update.days_in_testing, config.get('base_address'),
                            url(update.get_url()))
                    maildata += '\n\n'

                critpath_updates = self.get_unapproved_critpath_updates(prefix)
                if critpath_updates:
                    maildata += u'The following %s Critical Path updates have yet to be approved:\n Age URL\n' % prefix
                    for update in self.get_unapproved_critpath_updates(prefix):
                        maildata += u' %3i  %s%s\n' % (
                            update.days_in_testing, config.get('base_address'),
                            url(update.get_url()))
                    maildata += '\n\n'
            except Exception, e:
                log.exception(e)

            maildata += u'The following builds have been pushed to %s updates-testing\n\n' % prefix
            # get a list af all nvr's
            updlist = content.keys()
            # sort the list
            updlist.sort()
            # Add the list of builds to the mail
            for pkg in updlist:
                maildata += u'    %s\n' % pkg
            # Add some space between the short list and the Details"
            maildata += u'\nDetails about builds:\n\n'
            # Add the detail of each build
            for nvr in updlist:
                maildata += u"\n" + self.testing_digest[prefix][nvr]
            release = Release.select(Release.q.long_name == prefix)[0]
            mail.send_mail(
                config.get('bodhi_email'),
                config.get('%s_test_announce_list' %
                           release.id_prefix.lower().replace('-', '_')),
                '%s updates-testing report' % prefix, maildata)
Beispiel #60
0
Datei: rss.py Projekt: tyll/bodhi
    def get_critpath_updates(self, release=None, unapproved=None):
        i = 0
        entries = []
        base = config.get('base_address')
        title = 'Latest Critical Path Updates'
        query = [PackageUpdate.q.status != 'obsolete']
        if release:
            try:
                release = Release.byName(release)
            except SQLObjectNotFound:
                return dict(title='%s release not found' % release, entries=[])
            releases = [release]
            title = title + ' for %s' % release.long_name
        else:
            releases = Release.select()
        if unapproved:
            query.append(PackageUpdate.q.status != 'stable')
        for update in PackageUpdate.select(
                AND(
                    OR(*[
                        PackageUpdate.q.releaseID == release.id
                        for release in releases
                    ]), *query),
                orderBy=PackageUpdate.q.date_submitted).reversed():

            delta = datetime.utcnow() - update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            if update.critpath:
                if unapproved:
                    if update.critpath_approved:
                        continue
                entries.append({
                    'id': base + url(update.get_url()),
                    'summary': update.notes,
                    'link': base + url(update.get_url()),
                    'published': update.date_submitted,
                    'updated': update.date_submitted,
                    'title': update.title,
                })
                i += 1
        return dict(title=title,
                    subtitle="",
                    link=config.get('base_address') + url('/'),
                    entries=entries)