Exemple #1
0
def index():
    """
    LOAD all components with ajax
    """
    user_desk = application.getUserDesk()
    redirect(URL('desk', 'index', args=[user_desk.id]))
    return locals()
Exemple #2
0
    def change(self, form):
        if not auth.user_authenticate(form.vars.oldpassword):
            form.errors.oldpassword = "******"
            return

        auth.set_password(form.vars.password)
        redirect(URL('user','index'))
Exemple #3
0
def create():
    fields = []

    fld_headline = db.item.headline
    fields.extend([fld_headline, db.item.keywords, db.item.genre])
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'photoset'

    form = SQLFORM.factory(
        *fields,
        table_name='plugin_photo_set'  # to allow the correct form name
    )

    if form.process(dbio=False).accepted:
        # item_id = CT_REG.photoset.create_item(form.vars)
        item_id = application.createItem('photoset', form.vars)
        form.vars.item_id = item_id
        if session.plugin_photoset:
            form.vars.photoset = session.plugin_photoset.photos
        else:
            form.vars.phoset = []
        db.plugin_photoset_content.insert(
            **db.plugin_photoset_content._filter_fields(
                form.vars
            )
        )
        application.indexItem(item_id)
        session.plugin_photoset = None
        redirect(URL('default', 'index.html'))

    return locals()
Exemple #4
0
 def edit(self):
     self.context.customfield = customfield
     self.get()
     self.db.article.thumbnail.compute = lambda r: THUMB2(r["picture"], gae=self.request.env.web2py_runtime_gae)
     self.db.article.medium_thumbnail.compute = lambda r: THUMB2(
         r["picture"], gae=self.request.env.web2py_runtime_gae, nx=400, ny=400, name="medium_thumb"
     )
     self.context.article_form = SQLFORM(self.db.article, self.context.article)
     content, article_data = self.get_content(
         self.context.article.content_type_id.classname, self.context.article.id
     )
     if self.context.article_form.process().accepted:
         article_data.update_record(**content.entity._filter_fields(self.request.vars))
         self.new_article_event(
             "update_article",
             data={
                 "event_link": "%s/%s"
                 % (self.context.article.id, IS_SLUG()(self.context.article_form.vars.title)[0]),
                 "event_text": self.context.article_form.vars.description,
                 "event_to": "%s (%s)" % (self.context.article.content_type_id.title, self.context.article.title),
                 "event_image": self.get_image(
                     self.context.article.thumbnail, self.context.article.content_type_id.identifier
                 ),
             },
         )
         self.session.flash = self.T("%s updated." % self.context.article.content_type_id.title)
         self.context.article.update_record(
             search_index="|".join(str(value) for value in self.request.vars.values())
         )
         redirect(
             self.CURL("article", "show", args=[self.context.article.id, IS_SLUG()(self.request.vars.title)[0]])
         )
     self.context.content_form = SQLFORM(content.entity, article_data)
Exemple #5
0
def produtos():
    u"""Exibe uma lista de produtos de forma paginada.

    Exibe uma lista de produtos, com 9 itens por página.
    """
    pagina = current.request.args(0, cast=int, default=1)
    itens_por_pagina = 9
    db = current.globalenv['db']
    total = db(db.produtos).count()
    if not total:
        current.session.flash = current.T(
            'Desculpe, não existem produtos cadastrados ainda'
        )
        redirect('/')
    paginas = total / itens_por_pagina
    if total % itens_por_pagina:
        paginas += 1
    limites = (itens_por_pagina * (pagina - 1), (itens_por_pagina * pagina))
    produtos = db(db.produtos).select(
        limitby=limites
    )
    return {
        'produtos': produtos,
        'pagina': pagina,
        'paginas': paginas
    }
Exemple #6
0
def add_rendition():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(db.plugin_picture_rendition)

    if form.process().accepted:
        r_id = form.vars.id
        rend = db.plugin_picture_rendition(r_id)
        (filename,
         stream) = db.plugin_picture_rendition.picture.retrieve(rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.height = im.height
        rend.width = im.width
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # append this rendition to the item content
        content.renditions.append(r_id)
        content.update_record()
        redirect(application.getItemURL(item.unique_id))

    return locals()
Exemple #7
0
def membros():
    u"""Retorna a lista de membros cadastrados no formato de uma matriz.

    Retorna a lista de membros cadastrados sob formato de matriz
    de dimensões N x 3.
    """
    db = current.globalenv['db']
    membros = db(db.membros).select().as_list()
    if not membros:
        current.session.flash = current.T(
            'Desculpe, não existem membros cadastrados ainda'
        )
        redirect('/')
    linhas = (len(membros) // 3) + 1
    matriz = []
    for _ in range(linhas):
        aux = []
        cont = 0
        while cont < 3 and membros:
            aux.append(membros.pop(0))
            cont += 1
        matriz.append(aux)
    return {
        'matriz': matriz
    }
Exemple #8
0
def create():
    org = db.organization(session.org_id)
    tbl = db.desk
    tbl.item_list.readable = False
    tbl.item_list.writable = False
    tbl.name.requires = IS_NOT_EMPTY()

    form = SQLFORM(db.desk)
    form.add_button(T('Cancel'), URL('org', 'view', args=[org.id]))

    if form.process().accepted:
        # add the new desk to the org list
        desk_id = form.vars.id
        # add current users as the one with permission to update manage
        # this desk
        auth.add_permission(
            auth.user_group(auth.user.id),
            'update',
            db.desk,
            desk_id)
        desk_list = org.desks
        desk_list.insert(0, desk_id)
        org.update_record(desks=desk_list)
        # return to the org desk list
        redirect(URL('org', 'view', args=[org.id]))

    return locals()
Exemple #9
0
def delete():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    db.desk.item_list.readable = False
    db.desk.item_list.writable = False
    form = SQLFORM.confirm(
        T("Are you sure?"),
        {T('Cancel'): URL('index', args=[desk.id])})

    if form.accepted:
        # empty move all the items in the desk to the owners desk
        for item_id in desk.item_list:
            item = db.item(item_id)
            owner = db.auth_user(item.created_by)
            owner_desk = application.getUserDesk(user=owner)
            owner_desk_items = owner_desk.item_list
            owner_desk_items.append(item_id)
            owner_desk.update_record(item_list=owner_desk_items)

        # remove desk from org
        org = db(
            db.organization.desks.contains(desk.id)
        ).select().first()
        desk_list = org.desks
        desk_list.remove(desk.id)
        org.update_record(desks=desk_list)
        # delete the desk from db.
        del db.desk[desk.id]
        # cleanup context
        session.desk_id = None
        # go to org view
        redirect(URL('org','view', args=[org.id]))

    return locals()
Exemple #10
0
    def reportcontent(self):
        if not self.db.auth.user:
            vrs = {
                "_next":
                self.CURL('page', 'reportcontent', args=self.db.request.args)
            }
            redirect(self.CURL('person', 'account', args=['login'], vars=vrs))

        self.response.meta.title = "%s | %s" % (
            self.db.T("Report content"),
            self.db.config.meta.title,
        )

        self.db.Report.content_type.default = self.db.T(
            self.db.request.args(0))
        self.db.Report.item_id.default = int(self.db.request.args(1))
        self.db.Report.slug.default = self.db.request.args(2)

        self.db.Report.content_type.writable = \
        self.db.Report.item_id.writable = \
        self.db.Report.slug.writable = False

        self.context.form = SQLFORM(self.db.Report, formstyle='divs')
        self.context.form.insert(0, H1(self.db.T("Report content or user")))

        if self.context.form.process().accepted:
            self.db.response.flash = self.db.T(
                "Thank you for reporting this content")
Exemple #11
0
 def edit(self):
     self.get()
     self.context.form = SQLFORM(self.db.Page,
                                 self.context.page,
                                 formstyle='divs')
     if self.context.form.process().accepted:
         redirect(self.CURL("show", args=self.context.form.vars.id))
Exemple #12
0
    def approve_subscription(self, r, **attr):
        """
            Approve a pending subscription; as subscriber-action on status page
        """

        record = r.record
        if not record or not record.service_id:
            r.error(405, "Invalid record")

        onerror = r.url(method="status")

        try:
            adapter = S3PaymentService.adapter(record.service_id)
        except (KeyError, ValueError):
            r.error(405, "Invalid payment service", next=onerror)
        if not adapter.verify_reference(r):
            r.error(405, "Invalid reference", next=onerror)

        if record.status == "NEW":
            approval_url = record.approval_url
            if approval_url:
                redirect(approval_url)
            else:
                r.error(405, "Missing link for approval", next=onerror)
        else:
            r.error(405,
                    "Invalid subscription status for approval",
                    next=onerror)

        return {}
def select_store(only_auto_select=False):
    """ Goes to store selection screen if there are multiple stores, and
        auto selects the only store in other case, use only_auto_select
        to avoid going to store_selection page and just auto select when only
        one store is available
    """

    auth = current.auth
    session = current.session
    request = current.request
    db = current.db

    if not auth.user or auth.user.is_client or session.store:
        return

    q = (db.store.id < 0)
    store_memberships = db(
        (db.auth_membership.group_id == db.auth_group.id) &
        (db.auth_membership.user_id == auth.user.id) &
        (db.auth_group.role.like('Store %'))
    ).iterselect(db.auth_group.role)
    for store_membership in store_memberships:
        store_id = int(store_membership.role.split(' ')[1])
        q |= db.store.id == store_id
    stores = db((q) & (db.store.is_active == True)).select()

    if len(stores) == 1:
        session.store = stores.first().id
    elif not only_auto_select:
        redirect(URL('user', 'store_selection', vars=dict(_next=URL(request.controller, request.function, args=request.args or [], vars=request.vars or {})))
        )

    return
Exemple #14
0
def getEditgameUpdateForm(game):
    """
	Gets an update for the edit game page.

	Keyword Arguments:
	game -- row representing the current game

	Return Values:
	formUpdate -- web2py form
	"""

    from gluon import current, redirect, URL, SQLFORM
    db = current.db

    #Hide some fields of the form
    hideFields(db.game, ['id', 'host_id', 'game_status', 'password'])

    formUpdate = SQLFORM(db.game, game.id)
    formUpdate.add_class('assassins-form')

    if formUpdate.process().accepted:
        resizeImage(db.game, game.id)
        redirect(getUrl('edit', game.id))

    return formUpdate
Exemple #15
0
def create():
    fields = []

    fld_headline = db.item.headline
    fields.extend([fld_headline, db.item.keywords, db.item.genre])
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'photoset'

    form = SQLFORM.factory(
        *fields,
        table_name='plugin_photo_set'  # to allow the correct form name
    )

    if form.process(dbio=False).accepted:
        # item_id = CT_REG.photoset.create_item(form.vars)
        item_id = application.createItem('photoset', form.vars)
        form.vars.item_id = item_id
        if session.plugin_photoset:
            form.vars.photoset = session.plugin_photoset.photos
        else:
            form.vars.phoset = []
        db.plugin_photoset_content.insert(
            **db.plugin_photoset_content._filter_fields(
                form.vars
            )
        )
        application.indexItem(item_id)
        session.plugin_photoset = None
        redirect(URL('default', 'index.html'))

    return locals()
def getEditgameBtn (game, user):
	"""
	Gets a dictionary of buttons that do stuff for the edit game page.

	Keyword Arguments:
	game -- row representing the current game
	user -- row representing the current user

	Return Values:
	btn -- dictionary of web2py forms
	        -- 'back'   Back To Game
	        -- 'delete' Delete Game
	"""

	from gluon import URL, INPUT, FORM, A, redirect

	btn = {'back':'back', 'delete':'delete'}

	link = A('Back to Game', _class='btn btn-large btn-inverse btn-block', _href=URL('default', 'game', args=game.id))
	btn['back'] = link

	button = INPUT(_type='submit', _value='(Host) Delete Game', _class='btn btn-small btn-block abtn-small', _onclick='return confirm(\'Are you sure you want to delete this game?\');')
	formDelete = FORM(button)
	btn['delete'] = formDelete

	if btn['delete'].process().accepted:
		deleteGame(game.id, user)
		redirect(URL('default', 'current'))

	return btn
Exemple #17
0
def create():
    """Create a new organization"""
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [
        IS_NOT_EMPTY(error_message=T("Cannot be empty")),
        IS_NOT_IN_DB(
            db,
            'organization.name',
            error_message=T(
                "An Organization witch that name is allready in nStock"))
    ]

    form = SQLFORM(tbl)
    form.add_button(T('Cancel'), URL('index'))

    if form.process().accepted:
        # add the new organization
        g_id = auth.user_group(auth.user.id)
        # give the user all perms over this org
        auth.add_permission(g_id, 'update', tbl, form.vars.id)
        auth.add_permission(g_id, 'read', tbl, form.vars.id)
        auth.add_permission(g_id, 'delete', tbl, form.vars.id)
        redirect(URL('index'))

    return locals()
Exemple #18
0
def add_rendition():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(db.plugin_picture_rendition)

    if form.process().accepted:
        r_id = form.vars.id
        rend = db.plugin_picture_rendition(r_id)
        (filename, stream) = db.plugin_picture_rendition.picture.retrieve(
            rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.height = im.height
        rend.width = im.width
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # append this rendition to the item content
        content.renditions.append(r_id)
        content.update_record()
        redirect(application.getItemURL(item.unique_id))

    return locals()
Exemple #19
0
 def __init__(
         self,
         pk,
         sk,
         amount,  # in cents
         description,
         currency='usd',
         currency_symbol='$',
         security_notice=True,
         disclosure_notice=True,
         template=None):
     from gluon import current, redirect, URL
     if not (current.request.is_local or current.request.is_https):
         redirect(URL(args=current.request.args, scheme='https'))
     self.pk = pk
     self.sk = sk
     self.amount = amount
     self.description = description
     self.currency = currency
     self.currency_symbol = currency_symbol
     self.security_notice = security_notice
     self.disclosure_notice = disclosure_notice
     self.template = template or TEMPLATE
     self.accepted = None
     self.errors = None
     self.signature = sha1(repr(
         (self.amount, self.description))).hexdigest()
Exemple #20
0
 def start(self):
     from movuca import DataBase, User
     from datamodel.content import report
     from datamodel.article import ContentType, Category, Article
     self.db = DataBase([User, Page, Category, ContentType, Article])
     if self.db.request.function != "show" and not self.db.auth.has_membership("admin"):
         redirect(self.db.CURL("home", "index"))
Exemple #21
0
def delete():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    db.desk.item_list.readable = False
    db.desk.item_list.writable = False
    form = SQLFORM.confirm(T("Are you sure?"),
                           {T('Cancel'): URL('index', args=[desk.id])})

    if form.accepted:
        # empty move all the items in the desk to the owners desk
        for item_id in desk.item_list:
            item = db.item(item_id)
            owner = db.auth_user(item.created_by)
            owner_desk = application.getUserDesk(user=owner)
            owner_desk_items = owner_desk.item_list
            owner_desk_items.append(item_id)
            owner_desk.update_record(item_list=owner_desk_items)

        # remove desk from org
        org = db(db.organization.desks.contains(desk.id)).select().first()
        desk_list = org.desks
        desk_list.remove(desk.id)
        org.update_record(desks=desk_list)
        # delete the desk from db.
        del db.desk[desk.id]
        # cleanup context
        session.desk_id = None
        # go to org view
        redirect(URL('org', 'view', args=[org.id]))

    return locals()
Exemple #22
0
def getEditgameUpdateForm (game):
	"""
	Gets an update for the edit game page.

	Keyword Arguments:
	game -- row representing the current game

	Return Values:
	formUpdate -- web2py form
	"""

	from gluon import current, redirect, URL, SQLFORM
	db = current.db

	#Hide some fields of the form
	hideFields (db.game, ['id', 'host_id', 'game_status', 'password'])

	formUpdate = SQLFORM(db.game, game.id)
	formUpdate.add_class('assassins-form')

	if formUpdate.process().accepted:
		resizeImage(db.game, game.id)
		redirect(getUrl('edit', game.id))

	return formUpdate
Exemple #23
0
def projeto():
    u"""Editar informações sobre o projeto marolo.

    Permite que um usuário com permissão de admin edite as informações sobre
    o projeto.
    """
    path = os.path.dirname(os.path.abspath(__file__))
    with open(path + '/../views/default/sobre_projeto.html', 'r') as arq:
        sobre_projeto = arq.read()
    ckeditor = current.globalenv['ckeditor']
    form = SQLFORM.factory(
        Field(
            'texto',
            'text',
            widget=ckeditor.widget,
            default=sobre_projeto,
            requires=IS_NOT_EMPTY()
        ),
        hideerror=True,
        message_onfailure=current.T('O conteúdo não pode ser vazio.')
    )
    form.elements('label', replace=None)
    if form.process().accepted:
        with open(path + '/../views/default/sobre_projeto.html',
                  'w') as arq:
            arq.write(form.vars.texto)
        current.session.flash = current.T(
            'Sobre o projeto editado com sucesso!'
        )
        redirect(URL('admin', 'listar', args='noticias'))
    return {'form': form}
Exemple #24
0
def create():
    """
    Show the creation form of the text item.
    """

    fields = [
        db.item.headline,
        db.item.keywords,
        db.item.genre,
        db.item.item_type,
        # db.plugin_text_text.body
    ]
    db.item.item_type.default = 'text'
    db.item.item_type.writable = False
    db.item.item_type.readable = False

    form = SQLFORM.factory(*fields, submit_button=T("Next"))

    if form.process().accepted:
        item_id = application.createItem('text', form.vars)
        form.vars.item_id = item_id
        db.plugin_text_text.insert(
            **db.plugin_text_text._filter_fields(form.vars))
        application.indexItem(item_id)
        redirect(URL('index.html', args=[item_id]))

    return locals()
Exemple #25
0
def listar():
    u"""Lista registros em ordem decrescente.

    Um registro pode ser:
        - Uma notícia;
        - Um evento;
        - Um produto;
        - Um membro;
        - Um apoiador.
    Observação: Somente usuários com permissão de admin podem listar membros e
    apoiadores.
    """
    argumento = current.request.args(0) or redirect(URL('default', 'index'))
    lista_tabelas = ['noticias', 'eventos', 'produtos']
    auth = current.globalenv['auth']
    db = current.globalenv['db']
    if auth.has_membership('admin'):
        lista_tabelas.extend(['membros', 'apoiadores'])
    if argumento not in lista_tabelas:
        current.response.flash = current.T(
            'Operação não permitida a seu usuário.'
        )
        redirect(URL('admin', 'listar', args='noticias'))
    lista = db(db[argumento]).select(orderby=~db[argumento].id)
    return {'argumento': argumento, 'lista': lista}
Exemple #26
0
def inserir():
    u"""Permite inserir um novo registro.

    Um registro pode ser:
        - Uma notícia;
        - Um evento;
        - Um produto;
        - Um membro;
        - Um apoiador.
    Observação: Somente usuários com permissão de admin podem inserir novos
    membros e apoiadores.
    """
    argumento = current.request.args(0) or redirect(URL('default', 'index'))
    lista_tabelas = ['noticias', 'eventos', 'produtos']
    auth = current.globalenv['auth']
    db = current.globalenv['db']
    if auth.has_membership('admin'):
        lista_tabelas.extend(['membros', 'apoiadores'])
    if argumento not in lista_tabelas:
        current.session.flash = current.T(
            'Operação não permitida a seu usuário.'
        )
        redirect(URL('admin', 'listar', args='noticias'))
    form = SQLFORM(
        db[argumento], submit_button="Enviar",
        formstyle='bootstrap3_stacked')
    if form.process().accepted:
        current.response.flash = 'Registro inserido com sucesso!'
    elif form.errors:
        current.response.flash = 'Formulário contem erros'
    return {'argumento': argumento, 'form': form}
Exemple #27
0
 def start(self):
     from movuca import DataBase, User
     from datamodel.page import Page, Report
     from datamodel.article import ContentType, Category, Article
     self.db = DataBase([User, Page, Report, Category, ContentType, Article])
     if self.db.request.function not in ["show", "reportcontent"] and not self.db.auth.has_membership("admin"):
         redirect(self.db.CURL("home", "index"))
Exemple #28
0
    def apply_method(self, r, **attr):
        """
            API entry point

            @param r: the S3Request instance
            @param attr: controller attributes for the request
        """

        if r.http in ("GET", "POST", "DELETE"):
            if r.record:
                # Initialize CRUD form
                self.settings = current.response.s3.crud
                self.sqlform = sqlform = self._config("crud_form")
                if not sqlform:
                    from s3forms import S3SQLDefaultForm
                    self.sqlform = S3SQLDefaultForm()

                # Render page
                output = self.profile(r, **attr)
                return output

            elif r.representation not in ("dl", "aadata"):
                # Redirect to the List View
                redirect(r.url(method=""))

            else:
                # No point redirecting
                r.error(404, current.ERROR.BAD_RECORD)
        else:
            r.error(405, current.ERROR.BAD_METHOD)
Exemple #29
0
 def _CAS_logout(self):
     """
     exposed CAS.logout()
     redirects to the CAS logout page
     """
     import urllib
     redirect("%s?service=%s" % (self.cas_logout_url, self.cas_my_url))
Exemple #30
0
    def apply_method(self, r, **attr):
        """
            API entry point

            @param r: the S3Request instance
            @param attr: controller attributes for the request
        """

        if r.http in ("GET", "POST", "DELETE"):
            if r.record:
                # Initialize CRUD form
                self.settings = current.response.s3.crud
                self.sqlform = sqlform = self._config("crud_form")
                if not sqlform:
                    from .s3forms import S3SQLDefaultForm
                    self.sqlform = S3SQLDefaultForm()

                # Render page
                output = self.profile(r, **attr)
                return output

            elif r.representation not in ("dl", "aadata"):
                # Redirect to the List View
                redirect(r.url(method=""))

            else:
                # No point redirecting
                r.error(404, current.ERROR.BAD_RECORD)
        else:
            r.error(405, current.ERROR.BAD_METHOD)
Exemple #31
0
def create():
    """Create a new organization"""
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [
        IS_NOT_EMPTY(
            error_message=T("Cannot be empty")
        ),
        IS_NOT_IN_DB(
            db,
            'organization.name',
            error_message=T(
                "An Organization witch that name is allready in nStock"))]

    form = SQLFORM(tbl)
    form.add_button(T('Cancel'), URL('index'))

    if form.process().accepted:
        # add the new organization
        g_id = auth.user_group(auth.user.id)
        # give the user all perms over this org
        auth.add_permission(g_id, 'update', tbl, form.vars.id)
        auth.add_permission(g_id, 'read', tbl, form.vars.id)
        auth.add_permission(g_id, 'delete', tbl, form.vars.id)
        redirect(URL('index'))

    return locals()
Exemple #32
0
def create():
    """
    Show the creation form of the text item.
    """

    fields = [
        db.item.headline,
        db.item.keywords,
        db.item.genre,
        db.item.item_type,
        db.plugin_text_text.body
    ]
    db.item.item_type.default = 'text'
    db.item.item_type.writable = False
    db.item.item_type.readable = False

    form = SQLFORM.factory(*fields)

    if form.process().accepted:
        item_id = application.createItem('text', form.vars)
        form.vars.item_id = item_id
        db.plugin_text_text.insert(
            **db.plugin_text_text._filter_fields(form.vars))
        application.indexItem(item_id)
        redirect(URL('default', 'index.html'))

    return locals()
Exemple #33
0
def delete():
    dash = db.dashboard(request.args(0))

    db(db.dashboard.id == dash.id).delete()
    session.dashboard = None

    redirect(URL('default', 'index'))
    return CAT()
Exemple #34
0
def create_draft_intro():
    """
    Controller to create a new draft doc intro and redirect to draft_intro
    controller.
    """
    filename = get_truename(request.args[0])
    published_intro = db(db.docs.filename == filename).select().first()
    if published_intro:
        db['draftdocs'].insert(**published_intro.as_dict())
        db.commit()
    else:
        default_vals = {'filename': filename,
                        'name': 'Document title here',
                        'introduction': 'Provide a brief overview of the document\'s nature '
                                        'and importance.',
                        'provenance': 'Discuss the date, geographical location, and cultural '
                                    'situation of composition. This is also the '
                                    'place to discuss translation history and the '
                                    'relationship between various text types.',
                        'themes': 'Discuss the document\'s major themes.',
                        'status': 'Discuss the current status of the OCP edition of '
                                'the text. You should point out whether, e.g., a '
                                'better eclectic text exists elsewhere, or whether '
                                'there are manuscripts or text types that are not '
                                'included here.',
                        'manuscripts': 'Provide a list of all extant manuscripts, '
                                    'including their official designations, their '
                                    'current location (the institution where they '
                                    'are held), their date of copying, and any print '
                                    'editions of the manuscript in running form. If some '
                                    'mss do not contain the full document, specify '
                                    'which parts of the document are contained in each. '
                                    'Note that this list will be converted to a table '
                                    'by the OCP general editors.',
                        'bibliography': 'Provide a bibliography of all published '
                                        'editions of the text. It would be helpful '
                                        'to annotate the list, indicating the quality '
                                        'and distinctive features of each edition. '
                                        'If multiple text types or language traditions '
                                        'have different publication histories, provide '
                                        'a heading and separate bibliography for each.',
                        'corrections': 'If you have found errors in existing print '
                                    'editions these can be presented here in a list.',
                        'sigla': 'List here each symbol used in the text along with '
                                'a brief description of its meaning. Standard punctuation '
                                'need not be listed, but even common text-critical '
                                'symbols (like square brackets, ellipses, or '
                                'circles/dots above a character) should be included.',
                        'copyright': 'Explain here, as best you understand it, the '
                                    'copyright status of each text type included in '
                                    'the OCP edition of your text. If you have '
                                    'question about copyright issues, feel free to '
                                    'ask the OCP general editors.',
                        'version': '0.1'
                        }
        db['draftdocs'].insert(**default_vals)
        db.commit()
    redirect(URL('draft_intro', args=[filename]))
Exemple #35
0
def create_draft_intro():
    """
    Controller to create a new draft doc intro and redirect to draft_intro
    controller.
    """
    filename = request.args[0]
    published_intro = db(db.docs.filename == filename).select().first()
    if published_intro:
        db['draftdocs'].insert(**published_intro.as_dict())
        db.commit()
    else:
        default_vals = {'filename': filename,
                        'name': 'Document title here',
                        'introduction': 'Provide a brief overview of the document\'s nature '
                                        'and importance.',
                        'provenance': 'Discuss the date, geographical location, and cultural '
                                    'situation of composition. This is also the '
                                    'place to discuss translation history and the '
                                    'relationship between various text types.',
                        'themes': 'Discuss the document\'s major themes.',
                        'status': 'Discuss the current status of the OCP edition of '
                                'the text. You should point out whether, e.g., a '
                                'better eclectic text exists elsewhere, or whether '
                                'there are manuscripts or text types that are not '
                                'included here.',
                        'manuscripts': 'Provide a list of all extant manuscripts, '
                                    'including their official designations, their '
                                    'current location (the institution where they '
                                    'are held), their date of copying, and any print '
                                    'editions of the manuscript in running form. If some '
                                    'mss do not contain the full document, specify '
                                    'which parts of the document are contained in each. '
                                    'Note that this list will be converted to a table '
                                    'by the OCP general editors.',
                        'bibliography': 'Provide a bibliography of all published '
                                        'editions of the text. It would be helpful '
                                        'to annotate the list, indicating the quality '
                                        'and distinctive features of each edition. '
                                        'If multiple text types or language traditions '
                                        'have different publication histories, provide '
                                        'a heading and separate bibliography for each.',
                        'corrections': 'If you have found errors in existing print '
                                    'editions these can be presented here in a list.',
                        'sigla': 'List here each symbol used in the text along with '
                                'a brief description of its meaning. Standard punctuation '
                                'need not be listed, but even common text-critical '
                                'symbols (like square brackets, ellipses, or '
                                'circles/dots above a character) should be included.',
                        'copyright': 'Explain here, as best you understand it, the '
                                    'copyright status of each text type included in '
                                    'the OCP edition of your text. If you have '
                                    'question about copyright issues, feel free to '
                                    'ask the OCP general editors.',
                        'version': '0.1'
                        }
        db['draftdocs'].insert(**default_vals)
        db.commit()
    redirect(URL('draft_intro', args=[filename]))
Exemple #36
0
def members():
    org = db.organization(request.args(0))

    if not request.args(1):
        fld_email = Field('email', 'string', label=T("Email"))
        fld_email.requires = IS_EMAIL()

        form = SQLFORM.factory(
            fld_email,
            formstyle='bootstrap3_inline',
            submit_button=T("Add user"),
            table_name='members')

        if form.process().accepted:
            u = db.auth_user(email=form.vars.email)
            if u is not None:
                # create new share
                if u.id in org.users:
                    form.errors.email = T(
                        "The user is already in the organization")
                else:
                    user_list = org.users
                    user_list.insert(0, u.id)
                    org.update_record(users=user_list)
                    g_id = auth.user_group(u.id)
                    auth.add_permission(g_id, 'read', db.organization, org.id)
            else:
                # no user with that email
                response.flash = ""
                form.errors.email = T("The user don't exists on this system")
    elif request.args(1) == 'delete':
        # remove the user on args(2) from the org members list
        # TODO: remove else any perms on the org desks
        user_to_remove = db.auth_user(request.args(2))
        if user_to_remove is not None:
            user_list = org.users
            user_list.remove(user_to_remove.id)
            org.update_record(users=user_list)
            # remove perms over the org
            auth.del_permission(
                auth.user_group(user_to_remove.id),
                'read',
                db.organization,
                org.id)
            # remove, also, all rights over the desks in the org.
            desk_perms = [
                'read_desk', 'update_items', 'push_items', 'update_desk']
            for desk_id in org.desks:
                for perm in desk_perms:
                    auth.del_permission(
                        auth.user_group(user_to_remove.id),
                        perm,
                        db.desk,
                        desk_id
                    )
        redirect(URL('org', 'members', args=[org.id]))

    return locals()
 def edit_post(self, post_id):
     post = self.db.Post[post_id]
     # permission is checked here
     if not post or post.author != self.auth.user_id:
         redirect(URL("post", "index"))
     self.context.form = SQLFORM(
         self.db.Post, post.id,
         formstyle='divs').process(onsuccess=lambda form: redirect(
             URL('show', args=form.vars.id)))
Exemple #38
0
    def register(self, form):
        computedate(form)

        if len(form.vars.addressid) is 0:
            form.vars.addressid = current.db.address.insert(**current.db.address._filter_fields(form.vars))

        form.vars.userid = auth.user_id
        current.db.card.insert(**current.db.card._filter_fields(form.vars))
        redirect(self.redirect_url)
Exemple #39
0
def exception_handler():
    import sys, traceback
    etype, value, tb = sys.exc_info()
    error = ''
    msg = ''.join(traceback.format_exception(etype, value, tb, 10))           
    if is_moderator():
        error = msg
    logger.error(msg)                 
    redirect(URL(c='default', f='error',vars={'error':error}))    
Exemple #40
0
    def apply_method(self, r, **attr):
        """
            Entry point for REST API

            @param r: the S3Request instance
            @param attr: controller parameters

            @return: output data (JSON)
        """

        resource = self.resource
        rules = resource.get_config("anonymize")
        if not rules:
            r.error(405, "Anonymizing not configured for resource")

        record_ids = current.session.s3.get("anonymize_record_ids")
        if not record_ids:
            r.error(400, "No target record(s) specified")

        table = resource.table

        # Check permission for each record
        has_permission = current.auth.s3_has_permission
        for record_id in record_ids:
            if not has_permission("update", table, record_id=record_id) or \
               not has_permission("delete", table, record_id=record_id):
                r.unauthorised()

        output = {}

        if r.representation == "html":
            if r.http == "GET":
                # Show form
                anonymise_btn = S3AnonymizeBulkWidget.widget(
                    r,
                    record_ids=record_ids,
                    _class="action-btn anonymize-btn",
                )
                current.response.view = "simple.html"
                output = {
                    "item": anonymise_btn,
                    "title": current.T("Anonymize Records"),
                }
            elif r.http == "POST":
                # Process form
                output = self.anonymize(r, table, record_ids)
                del current.session.s3["anonymize_record_ids"]
                next_url = resource.get_config("anonymize_next")
                if next_url:
                    redirect(next_url)
            else:
                r.error(405, current.ERROR.BAD_METHOD)
        else:
            r.error(415, current.ERROR.BAD_FORMAT)

        return output
Exemple #41
0
 def get(self, redir=True):
     article_id = self.request.args(0)
     article_slug = self.request.args(1)
     queries = [self.db.article.id == article_id]
     if article_slug:
         queries.append(self.db.article.slug == article_slug)
     query = reduce(lambda a, b: (a & b), queries)
     self.context.article = self.db(query).select().first()
     if not self.context.article and redir:
         redirect(self.CURL('home', 'index'))
Exemple #42
0
    def force_integrity(self):
        if self.user_id >0:
            if current.request.controller not in ['address','card','user']:
                addresses = current.db(current.db.address.userid==self.user_id).count()
                if addresses == 0:
                    redirect(URL("address","create", args=['register']))

                cards = current.db(current.db.card.userid==self.user_id).count()
                if cards == 0:
                    redirect(URL("card","register"))
Exemple #43
0
 def get(self, redir=True):
     article_id = self.request.args(0)
     article_slug = self.request.args(1)
     queries = [self.db.article.id == article_id]
     if article_slug:
         queries.append(self.db.article.slug == article_slug)
     query = reduce(lambda a, b: (a & b), queries)
     self.context.article = self.db(query).select().first()
     if not self.context.article and redir:
         redirect(self.CURL('home', 'index'))
def expiration_redirect():
    """ Redirect if the user try to access paid contente with an expired service """

    session = current.session
    T = current.T
    exp_days = current.EXPIRATION_DAYS
    if exp_days > 0:
        return
    session.info = T('Your service has expired, please renew.')
    redirect(URL('default', 'index'))
 def requires_edicao(self):
     """
     Usado para verificar se o usuário selecionou uma edição
     """
     if current.session.edicao:
         return True
     else:
         redirect(
             URL('default', 'edicoes', vars=dict(_next=URL(current.request.controller, current.request.function,
                                                           vars=current.request.vars))))
def getGameFormBtn (game, user, gameStats):
	"""
	Gets a dictionary of form buttons that do stuff for the game page.

	Keyword Arguments:
	game    -- row representing the current game
	user    -- row representing the current user

	Return Values:
	formBtn -- dictionary of web2py forms
	        -- 'start'  Start Game button
	        -- 'join'   Join Game button
	        -- 'leave'  Leave Game button
	        -- 'target' Target Eliminated button
	        -- 'dead'   I have been eliminated button
	"""

	from gluon import current, INPUT, FORM, redirect, URL, BUTTON
	db = current.db

	formBtn = {'start':'start', 'join':'join', 'leave':'leave', 'target':'target', 'dead':'dead'}

	if gameStats['players'] > 1:
		formBtn['start']  = FORM(INPUT(_type='submit', _value='(Host) Start Game', _class='btn btn-large btn-block btn-inverse abtn-large', _onclick='return confirm(\'Are you sure you want to start this game?\');'))
	else:
		formBtn['start']  = BUTTON('(Host) Start Game', _class='btn btn-large btn-block btn-inverse abtn-large', _onclick='alert(\'You need at least 2 players to start a game?\');')

	formBtn['join']   = FORM(INPUT(_type='submit', _value='Join Game', _class='btn btn-large btn-block btn-inverse abtn-large'))
	formBtn['leave']  = FORM(INPUT(_type='submit', _value='Leave Game', _class='btn btn-block abtn-small', _onclick='return confirm(\'Are you sure you want to leave this game?\');'))
	formBtn['target'] = FORM(INPUT(_type='submit', _value='Target Eliminated', _class='btn btn-large btn-block btn-inverse abtn-large'))
	formBtn['dead']   = FORM(INPUT(_type='submit', _value='I am dead.', _class='btn btn-block abtn-small', _onclick='return confirm(\'Are you sure you want to eliminate yourself?\');'))

	if gameStats['players'] > 1 and formBtn['start'].process(formname='formBtnStart').accepted:
		startGameAssassins(game.id, user)
		redirect(URL('default', 'game', args=game.id))

	if formBtn['join'].process(formname='formBtnJoin').accepted:
		joinGame(game.id, user)
		redirect(URL('default', 'game', args=game.id))

	if formBtn['leave'].process(formname='formBtnLeave').accepted:
		leaveGame(game.id, user)
		redirect(URL('default', 'game', args=game.id))

	if formBtn['target'].process(formname='formBtnTarget').accepted:
		killCompletedAssassins(game.id, user.id)
		redirect(URL('default', 'game', args=game.id))

	if formBtn['dead'].process(formname='formBtnDead').accepted:
		query = db( (db.player.game_id==game.id) & (db.player.player_id==user.id) ).select(db.player.id)[0]
		killPlayer(game.id, user.id)
		#wasKilledAssassins()
		redirect(URL('default', 'game', args=game.id))

	return formBtn
Exemple #47
0
    def get_user(self):
        """ Returns the user info """

        token = self.accessToken()
        if not token:
            return None

        session = current.session
        user = None
        try:
            user = self.call_api(token)
        except Exception:
            session.token = None

        user_dict = None
        if user:
            #if "email" not in user:
            #    # Non-standard key for "email" claim
            #    email = user.get("mail")
            #else:
            email = user.get("email")
            if not email:
                msg = "OpenID Connect: unidentifiable user %s" % user.get(
                    "sub")
                current.session.warning = msg
                current.log.warning(msg)
                redirect(URL(c="default", f="user", args=["login"]))

            # Check if a user with this email has already registered
            table = current.auth.settings.table_user
            query = (table.email == email)
            existing = current.db(query).select(table.id,
                                                table.password,
                                                limitby=(0, 1)).first()

            if existing:
                user_dict = {"email": email, "password": existing.password}
            else:
                first_name = user.get("given_name", "")
                last_name = user.get("family_name", "")
                if not first_name and not last_name and "name" in user:
                    # Try to parse the combined 'name' field
                    from nameparser import HumanName
                    name = HumanName(user.get("name", ""))
                    first_name = name.first
                    last_name = name.last
                user_dict = {
                    "first_name": first_name,
                    "last_name": last_name,
                    "email": email,
                }

        return user_dict
Exemple #48
0
def informe_mes_empleado():
    empleados = db(db.empleado.is_active is True).select(db.empleado.ALL)
    fempl = ([" "] +
             [f"{p.user_code} {p.nombre} {p.apellido}" for p in empleados])
    form = FORM(
        CENTER(
            H4('Marcadas del personal'),
            TABLE(
                TR(
                    TAG('<label class "control-label">Persona</label>'),
                    SELECT(fempl,
                           _name='fempleado',
                           _type='text',
                           _id="persona",
                           _class="form-control string")),
                TR(
                    TAG('<label class "control-label">Periodo desde</label>'),
                    INPUT(_name='fdesde',
                          _type='date',
                          _id="mesanio",
                          _class="form-control string",
                          requires=IS_NOT_EMPTY())),
                TR(
                    TAG('<label class "control-label">Periodo hasta</label>'),
                    INPUT(
                        _name='fhasta',
                        _type='date',
                        _id="mesanio",
                        _class="form-control string",
                    ))), BR(),
            INPUT(_type="submit",
                  _class="btn btn-primary btn-medium",
                  _value='Continuar')))
    if form.accepts(request, session):
        session.empleado = request.vars['fempleado']
        session.user_code = request.vars['fempleado'].split()[0]
        session.fdesde = request.vars['fdesde']
        session.fhasta = request.vars['fhasta']
        log(f"seleccionado {session.empleado}")
        log(f"desde: {session.fdesde} hasta {session.fhasta}")
        # selector = (db.empleado.user_code == user_code)
        # usuario = db(selector).select().first().as_dict()
        session.tdesde = datetime.datetime.strptime(session.fdesde, '%Y-%m-%d')
        session.thasta = datetime.datetime.strptime(session.fhasta, '%Y-%m-%d')
        lista = aplico_politica(session.user_code, session.fdesde,
                                session.fhasta)
        nombre_archivo = f'''{session.empleado}
        -{session.fdesde}-{session.fhasta}'''
        session.table = list_dict_to_table_sortable(lista, nombre_archivo)
        redirect(URL('informe'))
    else:
        log(f'acceso {request.function}')
    return dict(form=form)
Exemple #49
0
def edit():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    db.desk.item_list.readable = False
    db.desk.item_list.writable = False
    form = SQLFORM(db.desk, record=desk, showid=False)

    if form.process().accepted:
        redirect(URL('index', args=[desk.id]))

    return locals()
Exemple #50
0
    def __call__(self):

        auth = current.auth
        ADMIN = auth.get_system_roles().ADMIN

        if auth.s3_has_role(ADMIN):

            T = current.T

            form = FORM(
                H3(T("Check transferability for all current cases")),
                INPUT(
                    _class="tiny primary button",
                    _type="submit",
                    _value=T("Update now"),
                ),
                P("(%s)" % T("This process can take a couple of minutes")),
            )

            if form.accepts(current.request.post_vars, current.session):

                # Get default site
                default_site = current.deployment_settings.get_org_default_site(
                )

                # Update transferability
                result = update_transferability(site_id=default_site)
                if result:
                    msg = current.T("%(number)s transferable cases found") % {
                        "number": result
                    }
                    current.session.confirmation = msg
                else:
                    msg = current.T("No transferable cases found")
                    current.session.warning = msg

                # Forward to list of transferable cases
                redirect(
                    URL(
                        c="dvr",
                        f="person",
                        vars={
                            "closed": "0",
                            "dvr_case.transferable__belongs": "True",
                            "show_family_transferable": "1",
                        },
                    ))

            self._view(THEME, "transferability.html")
            return {"form": form}

        else:
            auth.permission.fail()
Exemple #51
0
    def get(self):
        try:
            self.context.page = self.db.Page[int(self.request.args(0))]
        except Exception:
            self.context.page = self.db(self.db.Page.slug == self.request.args(0)).select().first()

        if not self.context.page:
            redirect(self.CURL('home', 'index'))

        self.response.meta.title = "%s | %s" % (
                                             self.context.page.title,
                                             self.db.config.meta.title,
                                            )
Exemple #52
0
    def load_user_metrics(self, username):
        self.username = username

        if not self.course:
            rslogger.debug("ERROR - NO COURSE course_id = {}".format(
                self.course_id))

        base_course = self.course.base_course

        self.chapters = current.db(
            current.db.chapters.course_id == base_course).select(
                orderby=current.db.chapters.chapter_num)

        self.user = (current.db(
            (current.db.auth_user.username == username)
            & (current.db.user_courses.user_id == current.db.auth_user.id)
            & (current.db.user_courses.course_id == self.course_id)).select(
                current.db.auth_user.id,
                current.db.auth_user.first_name,
                current.db.auth_user.last_name,
                current.db.auth_user.email,
                current.db.auth_user.username,
            ).first())
        if not self.user:
            rslogger.debug("ERROR - NO USER username={} course_id={}".format(
                username, self.course_id))
            current.session.flash = "Please make sure you are in the correct course"
            redirect(URL("default", "courses"))
            # TODO: calling redirect here is kind of a hacky way to handle this.

        self.db_chapter_progress = current.db(
            (current.db.user_sub_chapter_progress.user_id == self.user.id)
            & (current.db.user_sub_chapter_progress.course_name ==
               self.course.course_name)
            & (current.db.user_sub_chapter_progress.sub_chapter_id ==
               current.db.sub_chapters.sub_chapter_label)
            & (current.db.sub_chapters.chapter_id == current.db.chapters.id)
            & (current.db.chapters.course_id == base_course)
            & (current.db.chapters.chapter_label ==
               current.db.user_sub_chapter_progress.chapter_id)).select(
                   current.db.user_sub_chapter_progress.chapter_id,
                   current.db.user_sub_chapter_progress.sub_chapter_id,
                   current.db.user_sub_chapter_progress.status,
                   orderby=[
                       current.db.chapters.chapter_num,
                       current.db.sub_chapters.sub_chapter_num,
                   ],
               )
        self.formatted_activity = self.load_recent_activity()
        self.chapter_progress = UserActivityChapterProgress(
            self.chapters, self.db_chapter_progress)
Exemple #53
0
def members():
    org = db.organization(request.args(0))

    if not request.args(1):
        fld_email = Field('email', 'string', label=T("Email"))
        fld_email.requires = IS_EMAIL()

        form = SQLFORM.factory(fld_email,
                               formstyle='bootstrap3_inline',
                               submit_button=T("Add user"),
                               table_name='members')

        if form.process().accepted:
            u = db.auth_user(email=form.vars.email)
            if u is not None:
                # create new share
                if u.id in org.users:
                    form.errors.email = T(
                        "The user is already in the organization")
                else:
                    user_list = org.users
                    user_list.insert(0, u.id)
                    org.update_record(users=user_list)
                    g_id = auth.user_group(u.id)
                    auth.add_permission(g_id, 'read', db.organization, org.id)
            else:
                # no user with that email
                response.flash = ""
                form.errors.email = T("The user don't exists on this system")
    elif request.args(1) == 'delete':
        # remove the user on args(2) from the org members list
        # TODO: remove else any perms on the org desks
        user_to_remove = db.auth_user(request.args(2))
        if user_to_remove is not None:
            user_list = org.users
            user_list.remove(user_to_remove.id)
            org.update_record(users=user_list)
            # remove perms over the org
            auth.del_permission(auth.user_group(user_to_remove.id), 'read',
                                db.organization, org.id)
            # remove, also, all rights over the desks in the org.
            desk_perms = [
                'read_desk', 'update_items', 'push_items', 'update_desk'
            ]
            for desk_id in org.desks:
                for perm in desk_perms:
                    auth.del_permission(auth.user_group(user_to_remove.id),
                                        perm, db.desk, desk_id)
        redirect(URL('org', 'members', args=[org.id]))

    return locals()
Exemple #54
0
def index():
    """
    Edit/Show package content
    """
    pkg_item = application.getItemByUUID(request.args(0))
    content = db.plugin_package_content(item_id=pkg_item.unique_id)

    form = SQLFORM(db.plugin_package_content, record=content, showid=False)

    if form.process().accepted:
        application.indexItem(pkg_item.unique_id)
        redirect(URL('default', 'index'))

    return locals()
Exemple #55
0
    def customise_dc_template_controller(**attr):

        s3db = current.s3db

        target_id = current.request.get_vars.get("target_id")
        if target_id:
            # Find the Template for this Target
            ttable = s3db.dc_target
            target = current.db(ttable.id == target_id).select(
                ttable.template_id,
                limitby=(0, 1),
            ).first()
            if target:
                from gluon import redirect, URL
                redirect(
                    URL(c="dc",
                        f="template",
                        args=[target.template_id, "editor"]))

        # Custom Methods
        from templates.UCCE.controllers import dc_TemplateEditor
        from templates.UCCE.controllers import dc_TemplateExportL10n
        from templates.UCCE.controllers import dc_TemplateImportL10n
        from templates.UCCE.controllers import dc_TemplateSave

        set_method = s3db.set_method
        set_method("dc",
                   "template",
                   method="editor",
                   action=dc_TemplateEditor())

        set_method("dc",
                   "template",
                   method="export_l10n",
                   action=dc_TemplateExportL10n())

        set_method("dc",
                   "template",
                   method="upload_l10n",
                   action=dc_TemplateImportL10n())

        set_method("dc",
                   "template",
                   method="update_json",
                   action=dc_TemplateSave())

        attr["rheader"] = ucce_rheader

        return attr
Exemple #56
0
 def _CAS_login(self):
     """
     exposed as CAS.login(request)
     returns a token on success, None on failed authentication
     """
     import urllib
     self.ticket = current.request.vars.ticket
     if not current.request.vars.ticket:
         redirect("%s?service=%s" % (self.cas_login_url,
                                     self.cas_my_url))
     else:
         url = "%s?service=%s&ticket=%s" % (self.cas_check_url,
                                            self.cas_my_url,
                                            self.ticket)
         data = urllib.urlopen(url).read()
         if data.startswith('yes') or data.startswith('no'):
             data = data.split('\n')
             if data[0] == 'yes':
                 if ':' in data[1]:  # for Compatibility with Custom CAS
                     items = data[1].split(':')
                     a = items[0]
                     b = len(items) > 1 and items[1] or a
                     c = len(items) > 2 and items[2] or b
                 else:
                     a = b = c = data[1]
                 return dict(user=a, email=b, username=c)
             return None
         import xml.dom.minidom as dom
         import xml.parsers.expat as expat
         try:
             dxml = dom.parseString(data)
             envelop = dxml.getElementsByTagName(
                 "cas:authenticationSuccess")
             if len(envelop) > 0:
                 res = dict()
                 for x in envelop[0].childNodes:
                     if x.nodeName.startswith('cas:') and len(x.childNodes):
                         key = x.nodeName[4:].encode('utf8')
                         value = x.childNodes[0].nodeValue.encode('utf8')
                         if not key in res:
                             res[key] = value
                         else:
                             if not isinstance(res[key], list):
                                 res[key] = [res[key]]
                             res[key].append(value)
                 return res
         except expat.ExpatError:
             pass
         return None  # fallback