Beispiel #1
0
def diff():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)
    archive = db.plugin_picture_info_archive(request.args(1))

    fields = []
    fields_archived = []
    fields_names = []

    for f in db.plugin_picture_info:
        # if values diff
        if content[f.name] != archive[f.name]:
            fields_names.append(f.name)
            f.comment = None
            fields.append(f)
            db.plugin_picture_info_archive[f.name].comment = None
            fields_archived.append(db.plugin_picture_info_archive[f.name])

    # build two readonly forms
    form_actual = SQLFORM.factory(
        *fields,
        record=content,
        readonly=True,
        showid=False,
        formstyle='divs'
        )
    form_archive = SQLFORM.factory(
        *fields,
        record=archive,
        readonly=True,
        showid=False,
        formstyle='divs')

    return locals()
Beispiel #2
0
def diff():
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)
    content = db.plugin_text_text(item_id=item.unique_id)
    archive = db.plugin_text_text_archive(request.args(1))

    fields = []
    fields_archived = []
    fields_names = []

    for f in db.plugin_text_text:
        # if values diff
        if content[f.name] != archive[f.name]:
            fields_names.append(f.name)
            f.comment = None
            fields.append(f)
            db.plugin_text_text_archive[f.name].comment = None
            fields_archived.append(db.plugin_text_text_archive[f.name])

    # build two readonly forms
    form_actual = SQLFORM.factory(*fields,
                                  record=content,
                                  readonly=True,
                                  showid=False,
                                  formstyle='divs')
    form_archive = SQLFORM.factory(*fields,
                                   record=archive,
                                   readonly=True,
                                   showid=False,
                                   formstyle='divs')

    return locals()
Beispiel #3
0
def contact():
    """
    Controller for a simple contact form.
    """
    mail = current.mail
    keydata = {}
    with open('applications/grammateus3/private/app.keys', 'r') as keyfile:
        for line in keyfile:
            k, v = line.split()
            keydata[k] = v

    form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()),
                           Field('message_title', requires=IS_NOT_EMPTY()),
                           Field('message', 'text', requires=IS_NOT_EMPTY()),
                           submit_button='Send message',
                           separator=' ')
    captcha = Recaptcha2(request, keydata['captcha_public_key'],
                         keydata['captcha_private_key'])
    form.element('table').insert(-1, TR('', captcha, ''))
    if form.process().accepted:
        if mail.send(to='*****@*****.**',
                     subject='OCP Contact: {}'.format(form.vars.message_title),
                     message=form.vars.message):
            response.flash = 'Thank you for your message.'
            response.js = "jQuery('#%s').hide()" % request.cid
        else:
            form.errors.your_email = "Sorry, we were unable to send the email"
    return dict(form=form)
Beispiel #4
0
def contact():
    """
    Controller for a simple contact form.
    """
    mail = current.mail
    keydata = {}
    with open('applications/grammateus3/private/app.keys', 'r') as keyfile:
        for line in keyfile:
            k, v = line.split()
            keydata[k] = v

    form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()),
                           Field('message_title', requires=IS_NOT_EMPTY()),
                           Field('message', 'text', requires=IS_NOT_EMPTY()),
                           submit_button='Send message',
                           separator=' ')
    captcha = Recaptcha2(request,
                         keydata['captcha_public_key'],
                         keydata['captcha_private_key'])
    form.element('table').insert(-1, TR('', captcha, ''))
    if form.process().accepted:
        if mail.send(to='*****@*****.**',
                     reply_to=form.vars.your_email_address,
                     subject='OCP Contact: {}'.format(form.vars.message_title),
                     message=form.vars.message):
            response.flash = 'Thank you for your message.'
            response.js = "jQuery('#%s').hide()" % request.cid
        else:
            form.errors.your_email = "Sorry, we were unable to send the email"
    return dict(form=form)
Beispiel #5
0
    def handle_upload(self):
        """
        Get an upload from CKEditor and returns the new filename.

        Get an upload from CKEditor and returns the new filename that
        can then be inserted into a database. Returns (new_filename,
        old_filename, length, mime_type)
        """
        upload = current.request.vars.upload
        path = os.path.join(current.request.folder, 'uploads')

        if upload is not None:
            if hasattr(upload, 'file'):
                form = SQLFORM.factory(
                    Field('upload', 'upload', requires=IS_NOT_EMPTY(),
                          uploadfs=self.settings.uploadfs,
                          uploadfolder=path),
                    table_name=self.settings.table_upload_name,

                )

                old_filename = upload.filename
                new_filename = form.table.upload.store(upload.file,
                                                       upload.filename)
                if self.settings.uploadfs:
                    length = self.settings.uploadfs.getsize(new_filename)
                else:
                    length = os.path.getsize(os.path.join(path, new_filename))
                mime_type = upload.headers['content-type']

                return (new_filename, old_filename, length, mime_type)
            else:
                raise HTTP(401, 'Upload is not proper type.')
        else:
            raise HTTP(401, 'Missing required upload.')
Beispiel #6
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()
Beispiel #7
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()
Beispiel #8
0
def bulk_update():
    """
    Controller function to perform a programmatic update to a field in one table.
    """
    response = current.response
    db = current.db
    myrecs = None
    form = SQLFORM.factory(
        Field('table', requires=IS_IN_SET(db.tables)),
        Field('field'),
        Field('query'),
        Field('new_value'))
    if form.process().accepted:
        query = eval(form.vars.query)
        try:
            recs = db(query)
            recs.update(**{form.vars.field: form.vars.new_value})
            myrecs = recs.select()
            response.flash = 'update succeeded'
        except Exception:
            print traceback.format_exc(5)
    elif form.errors:
        myrecs = BEAUTIFY(form.errors)
        response.flash = 'form has errors'

    return form, myrecs
def send_email():

    title = 'Contato'

    form = SQLFORM.factory(
        Field('name', requires=IS_NOT_EMPTY()),
        Field('email', requires =[ IS_EMAIL(error_message='invalid email!'), IS_NOT_EMPTY() ]),
        Field('subject', requires=IS_NOT_EMPTY()),
        Field('message', requires=IS_NOT_EMPTY(), type='text')
    )
    if form.process().accepted:
        session.name = form.vars.name
        session.email = form.vars.email
        session.subject = form.vars.subject
        session.message = form.vars.message

        x = mails.send(to=['*****@*****.**'],
            subject='loja de carros',
            message= "Olá esse é um email de teste da lja de carros.\nName:"+ session.name+" \nEmail : " + session.email +"\nSubject : "+session.subject +"\nMessage : "+session.message+ ".\n "
        )

        if x == True:
            response.flash = 'email sent sucessfully.'
        else:
            response.flash = 'fail to send email sorry!'

        #response.flash = 'form accepted.'
    elif form.errors:
        response.flash='form has errors.'

    form_carro = detalhes_geral(db2.carro, 2)

    (form_crud,table_crud) = pesquisa_geral(db2.carro)

    return locals()
Beispiel #10
0
def share():
    """
    Show the list of desk to with the item can be push
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    query = (db.desk.id != session.desk_id)
    query &= auth.accessible_query('push_items', db.desk)

    posible_desk = db(query).select()

    fld_to_desk = Field('to_desk', 'integer')
    fld_to_desk.label = T("Push to")
    fld_to_desk.comment = T("Select where to push the item")
    fld_to_desk.requires = IS_IN_SET([(desk.id, desk.name)
                                      for desk in posible_desk])
    form = SQLFORM.factory(fld_to_desk,
                           submit_button=T("Send"),
                           table_name='share')
    if form.process().accepted:
        # send the item to the selected desk
        ct = application.getContentType(item.item_type)
        ct.shareItem(item.unique_id, session.desk_id, form.vars.to_desk)
        response.js = "$('#metaModal').modal('hide');"

    return locals()
Beispiel #11
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}
Beispiel #12
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()
Beispiel #13
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()
Beispiel #14
0
def share():
    """
    Show the list of desk to with the item can be push
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    query = (db.desk.id != session.desk_id)
    query &= auth.accessible_query('push_items', db.desk)

    posible_desk = db(query).select()

    fld_to_desk = Field('to_desk', 'integer')
    fld_to_desk.label = T("Push to organization desk")
    fld_to_desk.comment = T("Select where to push the item")
    fld_to_desk.requires = IS_EMPTY_OR(
        IS_IN_SET([(desk.id, desk.name) for desk in posible_desk]))

    fld_personal_desk = Field('to_person_desk', 'integer')
    fld_personal_desk.label = T("Push to other person desk")
    fld_personal_desk.comment = T("Select a person from the list.")
    # list of person on orgs
    persons = []
    # search up all the persons
    orgs = db(db.organization.users.contains(auth.user.id)).select()
    for org in orgs:
        x = [db.auth_user(id=y) for y in org.users if y != auth.user.id]
        persons.extend(x)
    persons = list(set(persons))
    fld_personal_desk.requires = IS_EMPTY_OR(
        IS_IN_SET([(per.id, "{} {}".format(per.first_name, per.last_name))
                   for per in persons]))

    fld_cond = Field('cond', 'boolean', default=False)
    fld_cond.label = T('To other person?')

    form = SQLFORM.factory(fld_to_desk,
                           fld_personal_desk,
                           fld_cond,
                           submit_button=T("Send"),
                           table_name='share')
    if form.process().accepted:
        src = session.desk_id
        if form.vars.cond:
            # send the item to other user
            other_user = db.auth_user(form.vars.to_person_desk)
            target = application.getUserDesk(other_user).id
        else:
            # send the item to the selected desk
            target = form.vars.to_desk

        if target:
            ct = application.getContentType(item.item_type)
            ct.shareItem(item.unique_id, src, target)
        response.js = "$('#metaModal').modal('hide');"
        response.flash = None

    return locals()
Beispiel #15
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()
Beispiel #16
0
def diff():
    """
    Show the diff betwen the actual item and the archive one
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)
    item_archive = db.item_archive(request.args(1))
    if item_archive is None:
        raise HTTP(503)

    fields = []
    fields_archived = []

    # allow view of administrative metadata
    db.item.modified_by.readable = True
    db.item.modified_on.readable = True
    db.item_archive.modified_by.readable = True
    db.item_archive.modified_on.readable = True

    for f in db.item:
        if item[f.name] != item_archive[f.name]:
            f.comment = None
            fields.append(f)
            db.item_archive[f.name].comment = None
            fields_archived.append(db.item_archive[f.name])

    # build two readonly forms
    form_actual = SQLFORM.factory(
        *fields,
        record=item,
        readonly=True,
        showid=False,
        formstyle='divs'
        )
    form_archive = SQLFORM.factory(
        *fields_archived,
        record=item_archive,
        readonly=True,
        showid=False,
        formstyle='divs')

    return dict(item=item, form_actual=form_actual, form_archive=form_archive)
Beispiel #17
0
def editar_usuario():
    u"""Edição ou deleção de um usuário.

    Permite que um usuário com permissão de admin edite ou apague um usuário.
    Observação: Não é possível editar a senha de um usuário.
    """
    user_id = current.request.args(0, cast=int,
                                   otherwise=URL('default', 'index'))
    db = current.globalenv['db']
    query = db.auth_user.id == user_id
    query &= db.auth_user.id == db.auth_membership.user_id
    user_data = db(query).select(
        db.auth_user.first_name,
        db.auth_user.last_name,
        db.auth_user.email,
        db.auth_membership.group_id,
    ).first()

    for campo, valor in user_data.auth_user.items():
        db.auth_user[campo].default = valor
    for campo, valor in user_data.auth_membership.items():
        db.auth_membership[campo].default = valor
    db.auth_user.email.requires = IS_EMAIL(
        error_message=current.T('Email inválido!')
    )
    db.auth_user.password.writable = False
    db.auth_user.password.readable = False
    db.auth_membership.user_id.writable = False
    db.auth_membership.user_id.readable = False
    form_update = SQLFORM.factory(
        db.auth_user,
        db.auth_membership,
        Field('apagar', 'boolean', default=False, label='Marque para apagar'),
        submit_button="Enviar"
    )

    if form_update.process().accepted:
        if form_update.vars.apagar:
            db(db.auth_user.id == user_id).delete()
            db(db.auth_membership.user_id == user_id).delete()
            current.session.flash = current.T('Usuário apagado com sucesso!')
            redirect(URL('admin', 'listar_usuarios'))

        db(db.auth_user.id == user_id).update(
            **db.auth_user._filter_fields(form_update.vars)
        )
        db(db.auth_membership.user_id == user_id).update(
            **db.auth_membership._filter_fields(form_update.vars)
        )
        current.session.flash = current.T('Usuário editado com sucesso!')
        redirect(URL('admin', 'listar_usuarios'))

    return {'form_update': form_update}
Beispiel #18
0
def diff():
    """
    Show the diff betwen the actual item and the archive one
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)
    item_archive = db.item_archive(request.args(1))
    if item_archive is None:
        raise HTTP(503)

    fields = []
    fields_archived = []

    # allow view of administrative metadata
    db.item.modified_by.readable = True
    db.item.modified_on.readable = True
    db.item_archive.modified_by.readable = True
    db.item_archive.modified_on.readable = True

    for f in db.item:
        if item[f.name] != item_archive[f.name]:
            f.comment = None
            fields.append(f)
            db.item_archive[f.name].comment = None
            fields_archived.append(db.item_archive[f.name])

    # build two readonly forms
    form_actual = SQLFORM.factory(*fields,
                                  record=item,
                                  readonly=True,
                                  showid=False,
                                  formstyle='divs')
    form_archive = SQLFORM.factory(*fields_archived,
                                   record=item_archive,
                                   readonly=True,
                                   showid=False,
                                   formstyle='divs')

    return dict(item=item, form_actual=form_actual, form_archive=form_archive)
Beispiel #19
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()
Beispiel #20
0
def gather_from_field(tablename,
                      fieldname,
                      regex_str,
                      exclude,
                      filter_func=None,
                      unique=True):
    """
    Return a list of all strings satisfying the supplied regex.

    The fieldnames argument should be a list, so that multiple target fields
    can be searched at once.

    The optional 'unique' keyword argument determines whether duplicates will
    be removed from the list. (Defaults to True.)

    The optional 'filterfunc' keyword argument allows a function to be passed
    which which will be used to alter the gathered strings. This alteration will
    happen before duplicate values are removed. So, for example, the strings
    can be normalized for case or accent characters if those variations are
    not significant.
    """

    db = current.db
    form = SQLFORM.factory(Field('target_field'), Field('target_table'),
                           Field('filter_func'), Field('trans_func'),
                           Field('write_table'), Field('write_field'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        filter_func = eval(vv.filter_func) if vv.filter_func else None
        trans_func = eval(vv.trans_func) if vv.trans_func else None

        items = []
        rows = db(db[vv.target_table].id > 0).select()
        for r in rows:
            items.append(r['target_field'])

        if filter_func:
            items = filter(filter_func, items)
        if trans_func:
            items = [trans_func(i) for i in items]
        if vv.unique:
            items = list(set(items))
        items = [i for i in items if i not in exclude]

    elif form.errors:
        items = BEAUTIFY(form.errors)

    return form, items
Beispiel #21
0
    def new(self):
        if not self.session.auth:
            redirect(self.CURL('default', 'user', args='login', vars=dict(_next=self.CURL('article', 'new', args=self.request.args))))
        arg = self.request.args(0)
        query = self.db.content_type.identifier == arg
        content_type = self.db(query).select().first() or redirect(self.CURL('home', 'index'))
        self.context.viewname = content_type.viewname
        content = self.define_content_type(content_type.classname)
        path = os.path.join(self.request.folder, 'uploads/')
        if not self.request.env.web2py_runtime_gae:
            self.db.article.picture.uploadfolder = path
            self.db.article.thumbnail.uploadfolder = path
        else:
            self.db.article.picture.uploadfield = "picture_blob"
            self.db.article.thumbnail.uploadfield = "thumbnail_blob"
        self.db.article.author.default = self.session.auth.user.id
        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.db.article.content_type_id.default = content_type.id
        category_set = self.db(self.db.Category.content_type == content_type.id)
        self.db.article.category_id.requires = IS_IN_DB(category_set, self.db.Category.id, "%(name)s")
        self.context.form = SQLFORM.factory(self.db.article, content.entity, table_name="article", formstyle='divs', separator='')
        self.context.customfield = customfield
        if self.context.form.process().accepted:
            try:
                article_id = self.db.article.insert(**self.db.article._filter_fields(self.context.form.vars))
                self.context.form.vars.article_id = article_id
                self.context.form.vars.type_id = content_type.id
                content_id = content.entity.insert(**content.entity._filter_fields(self.context.form.vars))
                if not content_id:
                    raise Exception("Content not added")
            except Exception:
                self.db.rollback()
                self.response.flash = self.T("error including %s." % content_type.title)
            else:
                self.db.commit()
                self.session.flash = self.T("%s included." % content_type.title)
                self.context.article = self.db.article[article_id]
                self.context.article.update_record(search_index="|".join(str(value) for value in self.context.form.vars.values()))

                if not self.context.article.draft:
                    self.new_article_event('new_article')
                    count = int(self.context.article.author.articles) + 1
                    self.context.article.author.update_record(articles=count)
                else:
                    count = int(self.context.article.author.draft_articles) + 1
                    self.context.article.author.update_record(draft_articles=count)

                redirect(self.CURL('article', 'show', args=[article_id, IS_SLUG()(self.context.form.vars.title)[0]]))
Beispiel #22
0
def gather_from_field(tablename, fieldname, regex_str, exclude,
                      filter_func=None, unique=True):
    """
    Return a list of all strings satisfying the supplied regex.

    The fieldnames argument should be a list, so that multiple target fields
    can be searched at once.

    The optional 'unique' keyword argument determines whether duplicates will
    be removed from the list. (Defaults to True.)

    The optional 'filterfunc' keyword argument allows a function to be passed
    which which will be used to alter the gathered strings. This alteration will
    happen before duplicate values are removed. So, for example, the strings
    can be normalized for case or accent characters if those variations are
    not significant.
    """

    db = current.db
    form = SQLFORM.factory(Field('target_field'),
                           Field('target_table'),
                           Field('filter_func'),
                           Field('trans_func'),
                           Field('write_table'),
                           Field('write_field'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        filter_func = eval(vv.filter_func) if vv.filter_func else None
        trans_func = eval(vv.trans_func) if vv.trans_func else None

        items = []
        rows = db(db[vv.target_table].id > 0).select()
        for r in rows:
            items.append(r['target_field'])

        if filter_func:
            items = filter(filter_func, items)
        if trans_func:
            items = [trans_func(i) for i in items]
        if vv.unique:
            items = list(set(items))
        items = [i for i in items if i not in exclude]

    elif form.errors:
        items = BEAUTIFY(form.errors)

    return form, items
Beispiel #23
0
def create():
    """
    Create a Item of a given content type
    """
    item_type = request.args(0)
    ct = application.getContentType(item_type)
    if ct is None:
        raise HTTP(404)

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

    # aks for preconditions:
    cond, values = ct.check_create_conditions()

    if cond is False:
        user_desk = application.getUserDesk()
        if 'message' in values.keys():
            message = values['message']
        else:
            message = T('Some conditions for the item creation are not met.')
        session.flash = message
        redirect(URL('desk', 'index.html', args=[user_desk.id]))

    else:
        # get the proposed values and initialize the form
        if 'headline' in values.keys():
            db.item.headline.default = values['headline']
        if 'keywords' in values.keys():
            db.item.keywords.default = values['keywords']
        if 'genre' in values.keys():
            db.item.genre.default = values['genre']

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

    if form.process(dbio=False).accepted:
        item_id = application.createItem(item_type, form.vars)
        application.indexItem(item_id)
        redirect(application.getItemURL(item_id))

    return locals()
Beispiel #24
0
def create():
    """
    Create a Item of a given content type
    """
    item_type = request.args(0)
    ct = application.getContentType(item_type)
    if ct is None:
        raise HTTP(404)

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

    # aks for preconditions:
    cond, values = ct.check_create_conditions()

    if cond is False:
        user_desk = application.getUserDesk()
        if 'message' in values.keys():
            message = values['message']
        else:
            message = T('Some conditions for the item creation are not met.')
        session.flash = message
        redirect(URL('desk', 'index.html', args=[user_desk.id]))

    else:
        # get the proposed values and initialize the form
        if 'headline' in values.keys():
            db.item.headline.default = values['headline']
        if 'keywords' in values.keys():
            db.item.keywords.default = values['keywords']
        if 'genre' in values.keys():
            db.item.genre.default = values['genre']

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

    if form.process(dbio=False).accepted:
        item_id = application.createItem(item_type, form.vars)
        application.indexItem(item_id)
        redirect(application.getItemURL(item_id))

    return locals()
Beispiel #25
0
def share():
    """
    Show the user's who has access to this item
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    fld_email = Field('email', 'string', default='')
    fld_perms = Field('perms', 'string', default='owner')
    fld_email.requires = IS_EMAIL()
    form = SQLFORM.factory(
        fld_email,
        fld_perms,
        formstyle='bootstrap3_inline',
        submit_button=T("Share this item"),
        table_name='share')
    if form.process().accepted:
        # search a user by his email addr
        u = db.auth_user(email=form.vars.email)
        if u is not None:
            # create new share
            ct = application.getContentType(item.item_type)
            ct.shareItem(item.unique_id, u, perms=form.vars.perms)
            # notify users
            subject = T("Share of %s", (item.headline,))
            message = response.render(
                'share_email.txt',
                dict(
                    item=item,
                    user=auth.user,
                    t_user=db.auth_user(email=form.vars.email)
                )
            )
            application.notifyCollaborators(
                item.unique_id,
                subject,
                message
            )
            # --
            # close the dialog
            response.js = "$('#metaModal').modal('hide');"
        else:
            # no user with that email
            response.flash = T("The user don't exists on this system")
            form.errors.email = T("The user don't exists on this system")

    return locals()
Beispiel #26
0
def create():
    if session.dashboard is None:
        session.flash = T('You must activate some dashboard first')
        redirect(URL('default', 'index'))

    dash = db.dashboard(session.dashboard)
    if not dash.item_list:
        session.flash = T('The current dashboard is empty')
        redirect(URL('default', 'index'))

    # get the headline form the first item in the list
    # first_item = application.getItemByUUID(dash.item_list[0])

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fdl_keywords = db.item.keywords
    keywords_list = []
    for item_id in dash.item_list:
        _item = application.getItemByUUID(item_id)
        keywords_list.extend(_item.keywords)
    keywords_list = list(set(keywords_list))  # remove any dup
    fdl_keywords.default = keywords_list
    fields.append(fdl_keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'package'
    fields.append(db.plugin_package_content.description)

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

    if form.process(dbio=False).accepted:
        form.vars.item_id = application.createItem('package', form.vars)
        form.vars.item_list = dash.item_list
        db.plugin_package_content.insert(
            **db.plugin_package_content._filter_fields(form.vars)
        )
        application.indexItem(form.vars.item_id)
        redirect(URL('default', 'index'))

    return locals()
Beispiel #27
0
def make_rows_from_field():
    """
    Use values from one table to create new records in another.

    The strings provided for

    The values for source_fields, target_fields, filter_funcs, and
    transform_funcs will be aligned by index.
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('target_table'),
                           Field('source_table'),
                           Field('source_fields', 'list:string'),
                           Field('target_fields', 'list:string'),
                           Field('filter_funcs', 'list:string'),
                           Field('trans_funcs', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        sourcerows = db(db[vv.target_table].id > 0).select()
        out = []
        for srow in sourcerows:
            trow = []
            for idx, f in enumerate(vv.source_fields):
                tval = vv.trans_funcs[idx](srow[f]) \
                    if len(vv.trans_funcs) > idx else srow[f]
                if len(vv.filter_funcs) > idx:
                    if not vv.filter_funcs[idx](tval):
                        tval = None
                if tval:
                    trow[vv.target_fields[idx]] = tval
            out.append(trow)

        if vv.unique:
            out = list(set(out))
        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #28
0
def test_step_regex():
    """
    Return a form that handles regex testing for individual steps.
    """
    db = current.db
    result = None
    form = SQLFORM.factory(Field('step_number', 'integer',
                                 requires=IS_IN_DB(db, 'steps.id')))

    if form.process(dbio=False, keepvalues=True).accepted:
        sid = form.vars.step_number
        row = db.steps(sid)
        result = check_regex(row.response1, row.readable_response.split('|'))
        result = BEAUTIFY(result)
    elif form.errors:
        result = BEAUTIFY(form.errors)

    return form, result
Beispiel #29
0
def make_rows_from_field():
    """
    Use values from one table to create new records in another.

    The strings provided for

    The values for source_fields, target_fields, filter_funcs, and
    transform_funcs will be aligned by index.
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('target_table'), Field('source_table'),
                           Field('source_fields', 'list:string'),
                           Field('target_fields', 'list:string'),
                           Field('filter_funcs', 'list:string'),
                           Field('trans_funcs', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        sourcerows = db(db[vv.target_table].id > 0).select()
        out = []
        for srow in sourcerows:
            trow = []
            for idx, f in enumerate(vv.source_fields):
                tval = vv.trans_funcs[idx](srow[f]) \
                    if len(vv.trans_funcs) > idx else srow[f]
                if len(vv.filter_funcs) > idx:
                    if not vv.filter_funcs[idx](tval):
                        tval = None
                if tval:
                    trow[vv.target_fields[idx]] = tval
            out.append(trow)

        if vv.unique:
            out = list(set(out))
        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #30
0
def make_rows_from_filenames():
    """
    TODO: unfinished
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('folder_path'),
                           Field('target_field'),
                           Field('target_table'),
                           Field('filter_func'),
                           Field('extra_fields', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        mypath = vv.folder_path
        fullpath = os.path.join()
        dirpath, dirnames, filenames = os.walk(mypath).next()
        xfield, xfunc = tuple([(x[0].strip(), x[1].strip()) for x in vv.extra_fields.split(',')])
        if xfunc:
            xfunc = eval(xfunc)
        filter_func = eval(vv.filter_func)

        out = []
        for f in filenames:
            kwargs = {}
            kwargs[vv.target_field] = f
            if xfunc:
                kwargs[xfield] = xfunc(f)
            if filter_func and not filter_func(f):
                kwargs = None
            if kwargs:
                out.append(kwargs)

        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #31
0
def create():
    fld_name = db.dashboard.name
    fld_name.requires = IS_NOT_EMPTY()
    fld_activate = Field(
        'activate',
        'boolean',
        default=True,
        label=T('Activate?'))

    form = SQLFORM.factory(fld_name, fld_activate)

    if form.process().accepted:
        d_id = db.dashboard.insert(
            name=form.vars.name,
            item_list=[]
        )
        auth.add_permission(0, 'owner', db.dashboard, d_id)
        session.dashboard = d_id
        redirect(URL('default', 'index'))
    return dict(form=form)
Beispiel #32
0
def print_rows_as_dicts():
    """docstring for print_select"""
    db = current.db
    message = 'Click to display the query result as a list of dictionaries.'
    form = SQLFORM.factory(Field('table', 'str'),
                           Field('field', 'str'),
                           Field('value', 'str'),
                           Submit='Evaluate')
    if form.process().accepted:
        tbl = form.vars.table
        fld = form.vars.field
        val = literal_eval(form.vars.value)
        rows = db(db[tbl][fld] == val).select().as_list()
        if not rows:
            rows = db(db[tbl][fld] == int(val)).select().as_list()
        message = rows
    elif form.errors:
        message = BEAUTIFY(form.errors)
    print message
    return form, message
Beispiel #33
0
def print_rows_as_dicts():
    """docstring for print_select"""
    db = current.db
    message = 'Click to display the query result as a list of dictionaries.'
    form = SQLFORM.factory(Field('table', 'str'),
                           Field('field', 'str'),
                           Field('value', 'str'),
                           Submit='Evaluate')
    if form.process().accepted:
        tbl = form.vars.table
        fld = form.vars.field
        val = literal_eval(form.vars.value)
        rows = db(db[tbl][fld] == val).select().as_list()
        if not rows:
            rows = db(db[tbl][fld] == int(val)).select().as_list()
        message = rows
    elif form.errors:
        message = BEAUTIFY(form.errors)
    print message
    return form, message
Beispiel #34
0
def make_rows_from_filenames():
    """
    TODO: unfinished
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('folder_path'), Field('target_field'),
                           Field('target_table'), Field('filter_func'),
                           Field('extra_fields', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        mypath = vv.folder_path
        fullpath = os.path.join()
        dirpath, dirnames, filenames = os.walk(mypath).next()
        xfield, xfunc = tuple([(x[0].strip(), x[1].strip())
                               for x in vv.extra_fields.split(',')])
        if xfunc:
            xfunc = eval(xfunc)
        filter_func = eval(vv.filter_func)

        out = []
        for f in filenames:
            kwargs = {}
            kwargs[vv.target_field] = f
            if xfunc:
                kwargs[xfield] = xfunc(f)
            if filter_func and not filter_func(f):
                kwargs = None
            if kwargs:
                out.append(kwargs)

        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #35
0
def create():
    if not session.marked_items:
        session.flash = T('You must mark some items first')
        redirect(URL('default', 'index'))

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fdl_keywords = db.item.keywords
    keywords_list = []
    for item_id in session.marked_items:
        _item = application.getItemByUUID(item_id)
        keywords_list.extend(_item.keywords)
    keywords_list = list(set(keywords_list))  # remove any dup
    fdl_keywords.default = keywords_list
    fields.append(fdl_keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'package'
    fields.append(db.plugin_package_content.description)

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

    if form.process(dbio=False).accepted:
        form.vars.item_id = application.createItem('package', form.vars)
        form.vars.item_list = session.marked_items
        db.plugin_package_content.insert(
            **db.plugin_package_content._filter_fields(form.vars)
        )
        application.indexItem(form.vars.item_id)
        session.marked_items = []
        redirect(URL('default', 'index'))

    return locals()
Beispiel #36
0
def replace_in_field():
    """
    Make a systematic set of string replacements for all values of one
    db field.
    """

    db = current.db
    form = SQLFORM.factory(Field('target_field'),
                           Field('target_table'),
                           Field('filter_func'),
                           Field('replacement_pairs', 'list:string'),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        reps = vv.replacement_pairs
        myreps = []
        for r in reps:
            pieces = r.split(',')
            myset = (pieces[0].strip(), pieces[1].strip())
            myreps.append(myset)

        myrows = db(db[vv.target_table].id > 0).select()
        count = 0
        pairs = {}
        for m in myrows:
            startval = m[vv.target_field]
            endval = multiple_replace(startval, myreps)
            if not vv.testing:
                m.update_record(**{vv.target_field: endval})
            pairs[startval] = endval
            count += 1

        out = {'records_updated': count,
               'pairs': pairs}

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #37
0
def tag_counts():
    '''
    Return a dictionary of data on user activity around tag categories.

    '''
    nowdate = datetime.datetime.combine(datetime.date.today(),
                                        datetime.time(0, 0, 0, 0))

    if 'start_date' in list(request.vars.keys()):
        sdt = parse(request.vars['start_date'])
        startdate = datetime.datetime.combine(sdt, datetime.time(0, 0, 0, 0))
    else:
        startdate = nowdate - datetime.timedelta(days=2)
    print('startdate', startdate)

    if 'end_date' in list(request.vars.keys()):
        edt = parse(request.vars['end_date'])
        enddate = datetime.datetime.combine(edt, datetime.time(0, 0, 0, 0))
    else:
        enddate = nowdate
    print('enddate', enddate)

    uid = request.vars['user_id'] if 'user_id' in list(request.vars.keys()) else None

    tagdata = Stats(uid).get_tag_counts_over_time(start=startdate,
                                                  end=enddate,
                                                  uid=uid)

    form = SQLFORM.factory(Field('start_date', 'date', default=startdate.date()),
                           Field('end_date', 'date', default=enddate.date()),
                           Field('user_id', 'list:reference auth_user',
                                 default=uid, readable=False, writable=False),
                           _name='tag_counts_form',
                           _id='tag_counts_form'
                           )
    requires = IS_DATE(format='%Y-%m-%d', error_message='must be YYYY-MM-DD!')

    return {'tagdata': tagdata,
            'form': form}
Beispiel #38
0
def create():
    if not session.marked_items:
        session.flash = T('You must mark some items first')
        redirect(URL('default', 'index'))

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fdl_keywords = db.item.keywords
    keywords_list = []
    for item_id in session.marked_items:
        _item = application.getItemByUUID(item_id)
        keywords_list.extend(_item.keywords)
    keywords_list = list(set(keywords_list))  # remove any dup
    fdl_keywords.default = keywords_list
    fields.append(fdl_keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'package'
    fields.append(db.plugin_package_content.description)

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

    if form.process(dbio=False).accepted:
        form.vars.item_id = application.createItem('package', form.vars)
        form.vars.item_list = session.marked_items
        db.plugin_package_content.insert(
            **db.plugin_package_content._filter_fields(form.vars))
        application.indexItem(form.vars.item_id)
        session.marked_items = []
        redirect(URL('default', 'index'))

    return locals()
Beispiel #39
0
def sale_sqlform_factory():
    """
    Create a custom form using SQLFORM.factory and custom widgets.

    This action creates a form based on the sale table but it also includes a
    wrapper field which can hold one of the following:
        A link to a grid that allows the user to select accessories to include in the sale.
        A grid holding the selected accessories.

    The ids of the selected accessories are passed in the request.
    """

    accessory_wrapper_field = Field('IncludedAccessories',widget=custom_accessory_widget, type='boolean')
    sale_sqlform_factory    = SQLFORM.factory(db.sale, accessory_wrapper_field)

    if sale_sqlform_factory.process().accepted:
        sale_id = db.sale.insert(**db.sale._filter_fields(sale_sqlform_factory.vars))
        insert_accessories(sale_id, request.vars.id)
	#TODO request.clear()
        response.flash = 'Record inserted'

    return locals()
Beispiel #40
0
def replace_in_field():
    """
    Make a systematic set of string replacements for all values of one
    db field.
    """

    db = current.db
    form = SQLFORM.factory(Field('target_field'), Field('target_table'),
                           Field('filter_func'),
                           Field('replacement_pairs', 'list:string'),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        reps = vv.replacement_pairs
        myreps = []
        for r in reps:
            pieces = r.split(',')
            myset = (pieces[0].strip(), pieces[1].strip())
            myreps.append(myset)

        myrows = db(db[vv.target_table].id > 0).select()
        count = 0
        pairs = {}
        for m in myrows:
            startval = m[vv.target_field]
            endval = multiple_replace(startval, myreps)
            if not vv.testing:
                m.update_record(**{vv.target_field: endval})
            pairs[startval] = endval
            count += 1

        out = {'records_updated': count, 'pairs': pairs}

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
Beispiel #41
0
def bulk_update():
    """
    Controller function to perform a programmatic update to a field in one table.
    """
    response = current.response
    db = current.db
    myrecs = None
    form = SQLFORM.factory(Field('table', requires=IS_IN_SET(db.tables)),
                           Field('field'), Field('query'), Field('new_value'))
    if form.process().accepted:
        query = eval(form.vars.query)
        try:
            recs = db(query)
            recs.update(**{form.vars.field: form.vars.new_value})
            myrecs = recs.select()
            response.flash = 'update succeeded'
        except Exception:
            print traceback.format_exc(5)
    elif form.errors:
        myrecs = BEAUTIFY(form.errors)
        response.flash = 'form has errors'

    return form, myrecs
Beispiel #42
0
def register():
    u"""Permite que um usuário com permissão de admin registre novos usuários.

    Usuários podem ter permissão de admin ou de editor.
    """
    db = current.globalenv['db']
    db.auth_membership.user_id.writable = False
    db.auth_membership.user_id.readable = False
    form_register = SQLFORM.factory(
        db.auth_user,
        db.auth_membership,
        submit_button="Enviar"
    )

    if form_register.process().accepted:
        form_register.vars.user_id = db.auth_user.insert(
            **db.auth_user._filter_fields(form_register.vars)
        )
        db.auth_membership.insert(
            **db.auth_membership._filter_fields(form_register.vars)
        )
        current.response.flash = current.T('Usuário cadastrado com sucesso!')

    return {'form_register': form_register}
Beispiel #43
0
    def subscription_status(self, r, **attr):
        """
            Default page for the subscriber (!) to view and manage their
            subscription

            - standard CRUD methods are for the merchant
            - can be replaced in template to include further fulfillment
              details / management options: customise_fin_subscription_resource()
              to override the "status" method with a custom REST method handler
        """

        T = current.T
        settings = current.deployment_settings

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

        output = {"title": T("Subscription Status")}

        # Subscription/fulfillment details to be shown to the subscriber
        # TODO show current status
        formfields = [
            Field(
                "plan",
                label=T("Subscription Plan"),
                writable=False,
            ),
            Field(
                "subscriber",
                label=T("Subscriber"),
                writable=False,
            ),
            Field(
                "date",
                label=T("Created on"),
                writable=False,
            ),
        ]

        table = r.table
        data = {
            "id": "",
            "plan": table.plan_id.represent(record.plan_id),
            "subscriber": table.pe_id.represent(record.pe_id),
            "date": S3DateTime.datetime_represent(record.created_on),
        }

        # Subscriber actions
        status = record.status
        if status == "NEW":
            buttons = [
                A(
                    T("Approve"),
                    _href=r.url(
                        method="approve",
                        vars={"subscription_id": record.refno},
                    ),
                    _class="action-btn",
                ),
            ]
        elif status == "APPROVED":
            buttons = [
                A(
                    T("Activate"),
                    _href=r.url(
                        method="confirm",
                        vars={"subscription_id": record.refno},
                    ),
                    _class="action-btn",
                ),
            ]
        elif status == "ACTIVE":
            buttons = [
                A(
                    T("Cancel"),
                    _href=r.url(
                        method="cancel",
                        vars={"subscription_id": record.refno},
                    ),
                    _class="action-btn",
                ),
            ]
        else:
            buttons = []

        resourcename = r.resource.name

        # Generate the form and add it to the output
        formstyle = settings.get_ui_formstyle()
        form = SQLFORM.factory(
            record=data,
            showid=False,
            formstyle=formstyle,
            table_name=resourcename,
            buttons=buttons,
            #hidden = hidden,
            #_id = widget_id,
            *formfields)

        output["item"] = form

        current.response.view = self._view(r, "display.html")

        return output
Beispiel #44
0
    def cancel_subscription(self, r, **attr):
        """
            Cancel a subscription and trigger automated cancelation actions

            - interactive user confirmation is required
            - URL query must include the reference number ("subscription_id")

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

        T = current.T
        settings = current.deployment_settings

        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)

        output = {"title": T("Cancel subscription")}

        # Dialog to confirm cancellation
        CONFIRM = T("Please check this box to confirm")
        formfields = [
            Field(
                "plan",
                label=T("Subscription Plan"),
                writable=False,
            ),
            Field(
                "subscriber",
                label=T("Subscriber"),
                writable=False,
            ),
            Field(
                "date",
                label=T("Created on"),
                writable=False,
            ),
            Field("cancel",
                  "boolean",
                  label=T("Yes, cancel this subscription"),
                  default=False,
                  requires=lambda cb, record_id=None:
                  (cb, (CONFIRM if not cb else None))),
        ]

        table = r.table
        data = {
            "id": "",
            "plan": table.plan_id.represent(record.plan_id),
            "subscriber": table.pe_id.represent(record.pe_id),
            "date": S3DateTime.datetime_represent(record.created_on),
            "cancel": False,
        }

        buttons = [
            INPUT(
                _class="tiny primary button submit-btn",
                _name="submit",
                _type="submit",
                _value=T("Cancel Subscription"),
            ),
            A(
                T("Return"),
                _href=r.url(method="status"),
                _class="cancel-action action-lnk",
            ),
        ]

        resourcename = r.resource.name

        # Generate the form and add it to the output
        formstyle = settings.get_ui_formstyle()
        form = SQLFORM.factory(
            record=data,
            showid=False,
            formstyle=formstyle,
            table_name=resourcename,
            buttons=buttons,
            #hidden = hidden,
            #_id = widget_id,
            *formfields)
        output["form"] = form

        # Process the form
        formname = "%s/cancel" % resourcename
        if form.accepts(
                r.post_vars,
                current.session,
                formname=formname,
                keepvalues=False,
                hideerror=False,
        ):

            if adapter.cancel_subscription(record.id):
                current.response.confirmation = T("Subscription cancelled")
            else:
                current.response.error = T("Cancellation failed")
            self.next = r.url(method="status")

        current.response.view = self._view(r, "update.html")
        return output
Beispiel #45
0
def walk():
    """
    Present the various stages of the game ui and handle user responses.

    This is the main function for presenting various states of the game
    user interface. These states are determined by the first url argument.
    The states are:

    - map (default; present navigation map)
    - step (Present prompt to begin a step OR evaluate user response and
        present the appropriate feedback and further navigation options.)
    - error

    The 'step' state elicits two different behaviours from the
    paideia module, depending on whether the web2py request object includes a
    submitted user response.
    - no: begin a step (choose appropriate path/step and retrieve prompt)
    - yes: evaluate the user's reply to the previous step prompt

    This function is intended to be accessed only via ajax, so its only view
    is exploring/walk.load. This view should be presented in the #page
    element of exploring/index.html.
    """

    request = current.request

    print "\n\nstarting walk controller========================================"
    rvars = request.vars
    rargs = request.args
    #print "in controller.walk:"
    #print "args:", request.args
    #print "vars:", request.vars
    #simple_obj_print(request.body.read(), "request body:")
    #simple_obj_print(request, "request:")
    #simple_obj_print(request.vars, "request.vars:")
    #simple_obj_print(request.args, "request.args:")

    # form for testing paths; returned and embedded in view
    testform = SQLFORM.factory(Field('path', 'integer'),
                               Field('location', 'reference locations'),
                               Field('blocks'),
                               Field('new_user', 'boolean'),
                               )
    if testform.process().accepted:
        redirect(URL('exploring', 'walk.load', args=['ask'], vars=request.vars))
    elif testform.errors:
        response.flash = 'Form had errors'
        print testform.errors

    print "controller.walk: Auth.user_id is", auth.user_id
    print "controller.walk: first_name is", db.auth_user(auth.user_id).first_name
    # When user begins exploring (also default) present map
    if (not rargs) or (rargs[0] == 'map'):
        print "controller.walk: getting map"
        return {'map': Map().show(),
                'form': testform}
    elif rargs[0] == 'repeat' and 'response' not in rvars.keys():
        print "controller.walk: setting repeat signal"
        stepargs = {'repeat': True}
    else:
        print "controller.walk: setting response string", rvars['response']
        stepargs = {}
        # if condition prevents submission of blank response
        stepargs['response_string'] = rvars['response'] if \
            ('response' in rvars and 'response' not in [' ', None]) else None
    if session.set_review:
        stepargs['set_review'] = session.set_review

    # pass along test settings to Walk.ask()
    print '----------------args & vars------------'
    print 'vars:'
    for x in rvars: print {x: rvars[x]}
    print 'args:'
    for x in rargs: print x
    # print 'cookies'
    # for x in request.cookies: print {x : request.cookies[x].value}
    print '------------end args & vars------------'
    if ('blocks' in rvars) and not (rvars['blocks'] in ['', None, 'undefined']):
        stepargs['set_blocks'] = literal_eval(rvars['blocks'])
        #debug
        print {'----------blocks passed------------': rvars['blocks']}
    if 'path' in rvars and not (rvars['path'] in ['', None, 'undefined']):
        stepargs['path'] = rvars['path']
    #JOB ... oct 18, 2014 ... bug step id
    if 'pre_bug_step_id' in rvars and not (rvars['pre_bug_step_id'] in ['', None, 'undefined']):
        stepargs['pre_bug_step_id'] = rvars['pre_bug_step_id']

    if not request.vars.loc:  # TODO: Does this do anything?
        request.vars.loc = None

    # variables for Walk init
    new_user = False
    if 'new_user' in request.vars and request.vars.new_user == 'on':
        print 'forcing new user'
        new_user is True

    resp = Walk(new_user=new_user).start(request.vars.loc,
                                         **stepargs)
    if 'bmodal' not in resp.keys():
        resp['bmodal'] = ''
    resp['form'] = testform

    return resp
Beispiel #46
0
def users():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    org = db.organization(session.org_id)

    if request.args(1):
        my_user = db.auth_user(request.args(1))

        fld_read_desk = Field('read_desk', 'boolean')
        fld_read_desk.label = T("Read '%s' content", (desk.name, ))
        fld_read_desk.comment = T(
            "Allow the user read only access to the desk item list.")
        fld_read_desk.default = auth.has_permission('read', db.desk, desk.id,
                                                    my_user.id)

        fld_update_items = Field('update_items', 'boolean')
        fld_update_items.label = T("Read/Update items in '%s'", (desk.name, ))
        fld_update_items.comment = T(
            "Allow the user make modifications to the items in the desk.")
        fld_update_items.default = auth.has_permission('update_items', db.desk,
                                                       desk.id, my_user.id)

        fld_push_items = Field('push_items', 'boolean')
        fld_push_items.label = T("Push items into '%s'", (desk.name, ))
        fld_push_items.comment = T(
            """Allow the user move items into the desk.""")
        fld_push_items.default = auth.has_permission('push_items', db.desk,
                                                     desk.id, my_user.id)

        fld_update_desk = Field('update_desk', 'boolean')
        fld_update_desk.label = T("Update/Manage '%s'", (desk.name, ))
        fld_update_desk.comment = T("""
            Allow the user to manage/administrate this desk. Use with caution.
            """)
        fld_update_desk.default = auth.has_permission('update', db.desk,
                                                      desk.id, my_user.id)

        form = SQLFORM.factory(fld_read_desk,
                               fld_update_items,
                               fld_push_items,
                               fld_update_desk,
                               table_name='desk_perms')

        if form.process().accepted:
            if form.vars.read_desk:
                # give perm
                auth.add_permission(auth.user_group(my_user.id), 'read',
                                    db.desk, desk.id)
            else:
                auth.del_permission(auth.user_group(my_user.id), 'read',
                                    db.desk, desk.id)

            if form.vars.update_items:
                # give perm
                auth.add_permission(auth.user_group(my_user.id),
                                    'update_items', db.desk, desk.id)
            else:
                auth.del_permission(auth.user_group(my_user.id),
                                    'update_items', db.desk, desk.id)

            if form.vars.push_items:
                # give perm
                auth.add_permission(auth.user_group(my_user.id), 'push_items',
                                    db.desk, desk.id)
            else:
                auth.del_permission(auth.user_group(my_user.id), 'push_items',
                                    db.desk, desk.id)

            if form.vars.update_desk:
                # give perm
                auth.add_permission(auth.user_group(my_user.id), 'update_desk',
                                    db.desk, desk.id)
            else:
                auth.del_permission(auth.user_group(my_user.id), 'update_desk',
                                    db.desk, desk.id)

            redirect(URL('desk', 'users', args=[desk.id]))

        response.view = "desk/user_perms.html"
    else:
        # select user view
        query = (db.auth_user.id > 0)
        query &= (db.auth_user.id.belongs(org.users))

        my_users = db(query).select()

    return locals()
Beispiel #47
0
def share():
    """
    Show the list of desk to with the item can be push
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    query = (db.desk.id != session.desk_id)
    query &= auth.accessible_query('push_items', db.desk)

    posible_desk = db(query).select()

    fld_to_desk = Field('to_desk', 'integer')
    fld_to_desk.label = T("Push to organization desk")
    fld_to_desk.comment = T("Select where to push the item")
    fld_to_desk.requires = IS_EMPTY_OR(IS_IN_SET(
        [(desk.id, desk.name) for desk in posible_desk]
    ))

    fld_personal_desk = Field('to_person_desk', 'integer')
    fld_personal_desk.label = T("Push to other person desk")
    fld_personal_desk.comment = T("Select a person from the list.")
    # list of person on orgs
    persons = []
    # search up all the persons
    orgs = db(db.organization.users.contains(auth.user.id)).select()
    for org in orgs:
        x = [db.auth_user(id=y) for y in org.users if y != auth.user.id]
        persons.extend(x)
    persons = list(set(persons))
    fld_personal_desk.requires = IS_EMPTY_OR(IS_IN_SET(
        [(per.id, "{} {}".format(per.first_name, per.last_name)) for per in persons]
    ))

    fld_cond = Field('cond', 'boolean', default=False)
    fld_cond.label = T('To other person?')

    form = SQLFORM.factory(
        fld_to_desk,
        fld_personal_desk,
        fld_cond,
        submit_button=T("Send"),
        table_name='share')
    if form.process().accepted:
        src = session.desk_id
        if form.vars.cond:
            # send the item to other user
            other_user = db.auth_user(form.vars.to_person_desk)
            target = application.getUserDesk(other_user).id
        else:
            # send the item to the selected desk
            target = form.vars.to_desk

        if target:
            ct = application.getContentType(item.item_type)
            ct.shareItem(item.unique_id, src, target)
        response.js = "$('#metaModal').modal('hide');"
        response.flash = None

    return locals()
Beispiel #48
0
def create():

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fields.append(db.item.keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'picture'

    # and the image for the first redition
    fld_redition = db.plugin_picture_rendition.picture
    fld_redition.uploadfolder = os.path.join(request.folder, 'uploads')
    fld_redition.label = T('Select the first rendition of the picture')
    fld_redition.comment = T("""
    Normally the raw version of the image. You may add other renditions as
    needed after form submition..
    """)
    fld_redition.requires = IS_IMAGE()
    fields.append(fld_redition)

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

    if form.process(dbio=False).accepted:
        # create the item
        item_id = application.createItem('picture', form.vars)
        # first rendition
        rend_id = db.plugin_picture_rendition.insert(
            **db.plugin_picture_rendition._filter_fields(form.vars)
        )
        form.vars.renditions = [rend_id]
        # generate the thumbnail
        rend = db.plugin_picture_rendition(rend_id)
        (filename, stream) = db.plugin_picture_rendition.picture.retrieve(
            rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.width, rend.height = im.size
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # --------------------------------
        size = (500, 500)
        im.thumbnail(size)
        fl = NamedTemporaryFile(suffix=".jpg", delete=True)
        fl.close()
        im.save(fl.name, "JPEG")
        form.vars.thumbnail = db.plugin_picture_info.thumbnail.store(
            open(fl.name, 'rb'), fl.name)
        os.unlink(fl.name)  # cleanup
        # create the picture main content
        form.vars.item_id = item_id
        info_id = db.plugin_picture_info.insert(
            **db.plugin_picture_info._filter_fields(form.vars)
        )
        # register document for search
        application.indexItem(item_id)
        # --
        # redirect to the item
        redirect(URL('default', 'index'))

    return locals()
Beispiel #49
0
    def invite(self, r, **attr):
        """
            Prepare and process invitation form

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

        T = current.T

        db = current.db
        s3db = current.s3db

        response = current.response
        request = current.request
        session = current.session

        settings = current.deployment_settings
        auth = current.auth
        auth_settings = auth.settings
        auth_messages = auth.messages

        output = {
            "title": T("Invite Organisation"),
        }

        # Get all accounts that are linked to this org
        utable = auth_settings.table_user
        oltable = s3db.org_organisation_user
        pltable = s3db.pr_person_user

        organisation_id = r.record.id
        join = oltable.on((oltable.user_id == utable.id) & \
                          (oltable.deleted == False))
        left = pltable.on((pltable.user_id == utable.id) & \
                          (pltable.deleted == False))
        query = (oltable.organisation_id == organisation_id)
        rows = db(query).select(
            utable.id,
            utable.first_name,
            utable.last_name,
            utable.email,
            utable.registration_key,
            pltable.pe_id,
            join=join,
            left=left,
        )

        active, disabled, invited = [], [], []
        for row in rows:
            user = row[utable]
            person_link = row.pr_person_user
            if person_link.pe_id:
                if user.registration_key:
                    disabled.append(user)
                else:
                    active.append(user)
            else:
                invited.append(user)

        if active or disabled:
            response.error = T(
                "There are already user accounts registered for this organization"
            )

            from gluon import UL, LI, H4, DIV
            from s3 import s3_format_fullname

            fullname = lambda user: s3_format_fullname(
                fname=user.first_name,
                lname=user.last_name,
                truncate=False,
            )
            account_list = DIV(_class="org-account-list")
            if active:
                account_list.append(H4(T("Active Accounts")))
                accounts = UL()
                for user in active:
                    accounts.append(
                        LI("%s <%s>" % (fullname(user), user.email)))
                account_list.append(accounts)
            if disabled:
                account_list.append(H4(T("Disabled Accounts")))
                accounts = UL()
                for user in disabled:
                    accounts.append(
                        LI("%s <%s>" % (fullname(user), user.email)))
                account_list.append(accounts)

            output["item"] = account_list
            response.view = self._view(r, "display.html")
            return output

        account = invited[0] if invited else None

        # Look up existing invite-account
        email = None
        if account:
            email = account.email
        else:
            ctable = s3db.pr_contact
            query = (ctable.pe_id == r.record.pe_id) & \
                    (ctable.contact_method == "EMAIL") & \
                    (ctable.deleted == False)
            contact = db(query).select(
                ctable.value,
                orderby=ctable.priority,
                limitby=(0, 1),
            ).first()
            if contact:
                email = contact.value

        # Form Fields
        dbset = db(utable.id != account.id) if account else db
        formfields = [
            Field("email",
                  default=email,
                  requires=[
                      IS_EMAIL(error_message=auth_messages.invalid_email),
                      IS_LOWER(),
                      IS_NOT_IN_DB(
                          dbset,
                          "%s.email" % utable._tablename,
                          error_message=auth_messages.duplicate_email,
                      ),
                  ]),
        ]

        # Generate labels (and mark required fields in the process)
        labels, has_required = s3_mark_required(formfields, )
        response.s3.has_required = has_required

        # Form buttons
        SEND_INVITATION = T("Send New Invitation") if account else T(
            "Send Invitation")
        buttons = [
            INPUT(
                _type="submit",
                _value=SEND_INVITATION,
            ),
            # TODO cancel-button?
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(
            table_name="invite",
            record=None,
            hidden={"_next": request.vars._next},
            labels=labels,
            separator="",
            showid=False,
            submit_button=SEND_INVITATION,
            #delete_label = auth_messages.delete_label,
            formstyle=settings.get_ui_formstyle(),
            buttons=buttons,
            *formfields)

        # Identify form for CSS & JS Validation
        form.add_class("send_invitation")

        if form.accepts(
                request.vars,
                session,
                formname="invite",
                #onvalidation = auth_settings.register_onvalidation,
        ):

            error = self.invite_account(r.record,
                                        form.vars.email,
                                        account=account)
            if error:
                response.error = T(
                    "Could not send invitation (%(reason)s)") % {
                        "reason": error
                    }
            else:
                response.confirmation = T("Invitation sent")
        else:
            if account:
                response.warning = T(
                    "This organisation has been invited before!")

        output["form"] = form

        response.view = self._view(r, "update.html")

        return output
Beispiel #50
0
    def __call__(self, field, value, **attributes):
        """
            Widget renderer for the input field; to be set as widget=self
            for the field returned by the resolve()-method.

            @param field: the input field
            @param value: the value to populate the widget
            @param attributes: attributes for the widget
            @return: the widget for this form element as HTML helper
        """

        T = current.T
        settings = current.deployment_settings

        # Check current value
        if isinstance(value, str):
            try:
                value = json.loads(value) if value else {}
            except JSONERRORS:
                value = {}
        elif not value:
            value = {}
        delegation_id = value.get("delegationID") if value else None

        # Form name and widget ID
        formname = self._formname()
        widget_id = attributes.get("_id")
        if not widget_id:
            widget_id = str(field).replace(".", "_")

        # Ajax parameters
        if delegation_id:
            ajax_args = [delegation_id, "notifications.json"]
            ajax_vars = {}
        else:
            ajax_args = ["notifications.json"]
            dtable = current.s3db.hrm_delegation
            person_id = dtable.person_id.default
            ajax_vars = {
                "viewing": "pr_person.%s" % person_id
            } if person_id else {}

        # Sender and recipient types
        sender = self.options.get("sender")
        if sender:
            ajax_vars["sender"] = sender
        notifications = DeploymentNotifications(delegation_id, sender=sender)
        recipients = list(notifications.recipients.keys())

        # Selectable organisations
        organisations = self.options.get("organisations")

        # Inject script
        options = {
            "ajaxURL":
            URL(
                c="hrm",
                f="delegation",
                args=ajax_args,
                vars=ajax_vars,
            ),
            "formName":
            formname,
            "recipients":
            recipients,
            "organisations":
            organisations,
        }
        self.inject_js(widget_id, options)

        # The widget
        widget = DIV(
            INPUT(
                _type="hidden",
                _name=field.name,
                _value=json.dumps(value),
                _class="notification-data",
            ),
            _id=widget_id,
        )

        # Add field set per recipient type
        labels = {
            "organisation": T("Requesting Organisation"),
            "volunteer": T("Volunteer"),
            "office": T("Office##gov"),
        }
        formstyle = settings.get_ui_formstyle()
        for recipient in recipients:
            input_name = "%s_%s" % (formname, recipient)
            formfields = [
                Field(
                    "%s_email" % input_name,
                    label=T("Email"),
                ),
                Field(
                    "%s_subject" % input_name,
                    label=T("Subject"),
                    widget=self.subject_widget,
                ),
                Field(
                    "%s_message" % input_name,
                    "text",
                    label=T("Message"),
                    widget=self.message_widget,
                ),
            ]
            form = SQLFORM.factory(record=None,
                                   showid=False,
                                   formstyle=formstyle,
                                   buttons=[],
                                   table_name="sub",
                                   *formfields)
            toggle_name = "%s_notify_%s" % (formname, recipient)

            toggle_edit = DIV(
                A(
                    T("Preview"),
                    _class="preview-toggle action-lnk",
                    _style="display:none",
                ),
                A(
                    T("Edit"),
                    _class="preview-toggle action-lnk",
                ),
                _class="preview-toggles",
            )
            subform = DIV(
                FIELDSET(
                    LEGEND(
                        LABEL(
                            INPUT(
                                _type="checkbox",
                                _class="notify-toggle",
                                value=True,
                                _name=toggle_name,
                                _id=toggle_name,
                            ),
                            labels.get(recipient, "?"),
                        ), ),
                    form[0],
                    toggle_edit,
                ),
                _class="notification",
            )
            widget.append(subform)

        return widget
Beispiel #51
0
    def new(self):
        if not self.session.auth:
            redirect(
                self.CURL('default',
                          'user',
                          args='login',
                          vars=dict(_next=self.CURL(
                              'article', 'new', args=self.request.args))))
        arg = self.request.args(0)
        query = self.db.content_type.identifier == arg
        content_type = self.db(query).select().first() or redirect(
            self.CURL('home', 'index'))
        self.context.viewname = content_type.viewname
        content = self.define_content_type(content_type.classname)
        path = os.path.join(self.request.folder, 'uploads/')
        if not self.request.env.web2py_runtime_gae:
            self.db.article.picture.uploadfolder = path
            self.db.article.thumbnail.uploadfolder = path
        else:
            self.db.article.picture.uploadfield = "picture_blob"
            self.db.article.thumbnail.uploadfield = "thumbnail_blob"
        self.db.article.author.default = self.session.auth.user.id
        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.db.article.content_type_id.default = content_type.id
        self.context.form = SQLFORM.factory(self.db.article,
                                            content.entity,
                                            table_name="article",
                                            formstyle='divs',
                                            separator='')
        self.context.customfield = customfield
        if self.context.form.process().accepted:
            try:
                article_id = self.db.article.insert(
                    **self.db.article._filter_fields(self.context.form.vars))
                self.context.form.vars.article_id = article_id
                self.context.form.vars.type_id = content_type.id
                content_id = content.entity.insert(
                    **content.entity._filter_fields(self.context.form.vars))
                if not content_id:
                    raise Exception("Content not added")
            except Exception:
                self.db.rollback()
                self.response.flash = self.T("error including %s." %
                                             content_type.title)
            else:
                self.db.commit()
                self.session.flash = self.T("%s included." %
                                            content_type.title)
                self.context.article = self.db.article[article_id]
                self.context.article.update_record(search_index="|".join(
                    str(value) for value in self.context.form.vars.values()))

                if not self.context.article.draft:
                    self.new_article_event('new_article')
                    count = int(self.context.article.author.articles) + 1
                    self.context.article.author.update_record(articles=count)
                else:
                    count = int(self.context.article.author.draft_articles) + 1
                    self.context.article.author.update_record(
                        draft_articles=count)

                redirect(
                    self.CURL('article',
                              'show',
                              args=[
                                  article_id,
                                  IS_SLUG()(self.context.form.vars.title)[0]
                              ]))
Beispiel #52
0
def gather_word_forms():
    """
    Return a list of all strings satisfying the supplied regex.

    The fieldnames argument should be a list, so that multiple target fields
    can be searched at once.

    The optional 'unique' keyword argument determines whether duplicates will
    be removed from the list. (Defaults to True.)

    The optional 'filterfunc' keyword argument allows a function to be passed
    which which will be used to alter the gathered strings. This alteration will
    happen before duplicate values are removed. So, for example, the strings
    can be normalized for case or accent characters if those variations are
    not significant.
    """

    items = []
    db = current.db
    x = ['πιλ', 'βοδυ', 'μειδ', 'νηλ', 'ἰλ', 'σαγγ', 'ἁμ', 'ἱτ', 'ἑλπ', 'ἑλω', 'ο',
         'βοτ', 'ὁλ', 'ὁγ', 'παθ', 'τιψ', 'β', 'σωλ', 'κορπ', 'ὡλ', 'κατς', 'γγς',
         'μωλτεγγ', 'δεκ', 'φιξ', 'βαλ', 'διλ', 'δαξ', 'δρομα', 'δακ', 'δαγ', 'ἁγ',
         'λοξ', 'δυδ', 'βωθ', 'ὐψ', 'καν', 'καβ', 'ὀτ', 'βαδ', 'μωστ', 'μοισδ',
         'μιλ', 'βελ', 'ἑδ', 'θοτ', 'κιλ', 'κρω', 'βοχ', 'ω', 'μεντ', 'ἁτ', 'νεατ',
         'σπηρ', 'βοδι', 'πιτ', 'βονδ', 'ἁρδ', 'δοκς', 'μελτ', 'βεδ', 'μαλ', 'δατς',
         'σωπ', 'α', 'πενσιλ', 'κς', 'δεκς', 'αριας', 'βαγγ', 'σετ', 'βρουμ', 'ἀδ',
         'πωλ', 'δατ', 'ἁγγ', 'πραυδ', 'αὐτης', 'νειλ', 'σογγ', 'ζαπ', 'κλαδ',
         'νιτ', 'φαξ', 'βολ', 'κεπτ', 'μοιστ', 'ἁμερ', 'τουνα', 'προγγ', 'τ',
         'κλυν', 'λοβ', 'πλειαρ', 'κροπ', 'βανδ', 'μωλτεν', 'υτ', 'κοτ', 'κοπ',
         'ἀτ', 'φυξ', 'ὡλι', 'μυτ', 'θατ', 'δοτ', 'βικς', 'ἁμαρ', 'λωφερ', 'δοκ',
         'ταπ', 'ἀβωδ', 'ὑτος', 'λωφρ', 'ἁμρ', 'ροκ', 'πς', 'βαδυ', 'οὐψ', 'πραγγ',
         'σπειρ', 'ἀγγλ', 'σλαψ', 'πλαυ', 'δραμα', 'φοξ', 'ἱτεδ', 'ὁτ', 'δογ',
         'δολ', 'ρω', 'δοξ', 'ὗτος', 'μιτ', 'αὑ', 'ἱτς', 'μωλτ', 'βατ', 'βαχ',
         'βικ', 'μιαλ', 'μολ', 'μιελ', 'κον', 'μωισδ', 'κραπ', 'καπ', 'ὑπ', 'ἀγκλ',
         'λιξ', 'ρωλ', 'λαβ', 'ὀδ', 'λαξ', 'δοτς', 'ἀνκλ', 'ρακ', 'πεγ', 'τυνα',
         'βρυμ', 'καρπ', 'βρεδ', 'κιπ', 'μηδ', 'δαλ', 'βετ', 'διπ', 'κλιν', 'πετ',
         'βαδι', 'λικς', 'δακς', 'πς', 'ὑπ', 'κς', 'α', 'ος', 'μιτ', 'βρεδ', 'ί',
         'ο', 'νεατ', 'δι', 'Ω', 'τ', 'υτ', 'η', 'ον', 'β', 'α', 'δεξ', 'παι']
    x = [makeutf8(word) for word in x]

    form = SQLFORM.factory(Field('search_table', default='steps',
                                 writable=False),
                           Field('search_field',
                                 requires=IS_IN_SET(['prompt',
                                                     'readable_response'])),
                           Field('write_table', default='word_forms',
                                 writable=False),
                           Field('write_field', default='word_form',
                                 writable=False),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True),
                           Field('new', 'boolean', default=True))
    form.vars.search_table = 'steps'
    form.vars.write_table = 'word_forms'
    form.vars.write_field = 'word_form'

    if form.process().accepted:
        vv = form.vars
        filter_func = eval(vv.filter_func) if vv.filter_func else None
        trans_func = eval(vv.trans_func) if vv.trans_func else None

        rows = db(db[vv.search_table].id > 0).select()
        for r in rows:
            items.append(r[vv['search_field']])

        ptrn = re.compile(u'[\u0370-\u03FF\u1F00-\u1FFF]+', flags=re.U)
        items = flatten([re.findall(ptrn, makeutf8(i)) for i in items])
        normalizer = GreekNormalizer()
        items = [normalizer.normalize(i) for i in items]
        if vv.unique:
            items = list(set(items))
        items = [i.lower() for i in items if i not in x]

        if vv.new:
            existing = [makeutf8(r['word_form']) for r in
                        db(db.word_forms.id > 0).select(db.word_forms.word_form)]
            items = [i for i in items if i not in existing
                     and i.capitalize() not in existing
                     and i.lower() not in existing]
        if vv.testing:
            pass
            response.flash = 'Success, but nothing written to database.'
        else:
            newdata = [{'word_form': item} for item in items]
            rowcount = db.word_forms.bulk_insert(newdata)
            response.flash = 'Success. Added', len(rowcount), 'new word forms.'

    elif form.errors:
        items = BEAUTIFY(form.errors)

    return {'form': form, 'items': items}
Beispiel #53
0
def add_new_property():
    form = SQLFORM.factory(db.address)

    return dict(form=form)
Beispiel #54
0
def create():

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fields.append(db.item.keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'picture'

    # and the image for the first redition
    fld_redition = db.plugin_picture_rendition.picture
    fld_redition.uploadfolder = os.path.join(request.folder, 'uploads')
    fld_redition.label = T('Select the first rendition of the picture')
    fld_redition.comment = T("""
    Normally the raw version of the image. You may add other renditions as
    needed after form submition..
    """)
    fld_redition.requires = IS_IMAGE()
    fields.append(fld_redition)

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

    if form.process(dbio=False).accepted:
        # create the item
        item_id = application.createItem('picture', form.vars)
        # first rendition
        rend_id = db.plugin_picture_rendition.insert(
            **db.plugin_picture_rendition._filter_fields(form.vars)
        )
        form.vars.renditions = [rend_id]
        # generate the thumbnail
        rend = db.plugin_picture_rendition(rend_id)
        (filename, stream) = db.plugin_picture_rendition.picture.retrieve(
            rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.width, rend.height = im.size
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # --------------------------------
        size = (500, 500)
        im.thumbnail(size)
        fl = NamedTemporaryFile(suffix=".jpg", delete=True)
        fl.close()
        im.save(fl.name, "JPEG")
        form.vars.thumbnail = db.plugin_picture_info.thumbnail.store(
            open(fl.name, 'rb'), fl.name)
        os.unlink(fl.name)  # cleanup
        # create the picture main content
        form.vars.item_id = item_id
        info_id = db.plugin_picture_info.insert(
            **db.plugin_picture_info._filter_fields(form.vars)
        )
        # register document for search
        application.indexItem(item_id)
        # --
        # redirect to the item
        redirect(URL('default', 'index'))

    return locals()
Beispiel #55
0
    def __call__(self):

        output = {}

        T = current.T
        request = current.request
        response = current.response
        s3 = response.s3

        # Check logged in and permissions
        auth = current.auth
        settings = current.deployment_settings
        roles = current.session.s3.roles
        system_roles = auth.get_system_roles()
        AUTHENTICATED = system_roles.AUTHENTICATED

        # Login/Registration forms
        self_registration = settings.get_security_registration_visible()
        registered = False
        login_form = None
        login_div = None
        register_form = None
        register_div = None

        # Project Links
        project_links = DIV(_class="title-links hide-for-small")
        project_description = settings.get_frontpage("project_description")
        if project_description:
            project_links.append(
                A(
                    ICON("link"),
                    T("Project Description"),
                    _class="action-lnk",
                    _href=project_description,
                    _target="_blank",
                ))
        project_links.append(
            A(
                ICON("link"),
                T("User Manual"),
                _class="action-lnk",
                _href=URL(
                    c="default",
                    f="index",
                    args=["docs"],
                    vars={"name": "UserManual"},
                ),
                _target="_blank",
            ))
        mailing_list = settings.get_frontpage("mailing_list")
        if mailing_list:
            project_links.append(
                A(
                    ICON("link"),
                    T("Mailing List"),
                    _class="action-lnk",
                    _href=mailing_list,
                    _target="_blank",
                ))

        # Contact Form
        request_email = settings.get_frontpage("request_email")
        if request_email:
            from gluon import IS_NOT_EMPTY, SQLFORM
            from s3dal import Field
            fields = [
                Field(
                    "name",
                    label="Your name",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "address",
                    label="Your e-mail address",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "subject",
                    label="Subject",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "message",
                    "text",
                    label="Message",
                    requires=IS_NOT_EMPTY(),
                ),
            ]
            from s3 import s3_mark_required
            labels, required = s3_mark_required(fields)
            s3.has_required = required

            response.form_label_separator = ""
            contact_form = SQLFORM.factory(
                formstyle=settings.get_ui_formstyle(),
                submit_button=T("Submit"),
                labels=labels,
                separator="",
                table_name="contact",  # Dummy table name
                _id="mailform",
                *fields)

            if contact_form.accepts(request.post_vars,
                                    current.session,
                                    formname="contact_form",
                                    keepvalues=False,
                                    hideerror=False):
                # Processs Contact Form
                form_vars = contact_form.vars
                sender = "%s <%s>" % (form_vars.name, form_vars.address)
                result = current.msg.send_email(
                    to=request_email,
                    sender=sender,
                    subject=form_vars.subject,
                    message=form_vars.message,
                    reply_to=form_vars.address,
                )
                if result:
                    response.confirmation = "Thank you for your message - we'll be in touch shortly"
            if s3.cdn:
                if s3.debug:
                    s3.scripts.append(
                        "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"
                    )
                else:
                    s3.scripts.append(
                        "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"
                    )
            else:
                if s3.debug:
                    s3.scripts.append("/%s/static/scripts/jquery.validate.js" %
                                      request.application)
                else:
                    s3.scripts.append(
                        "/%s/static/scripts/jquery.validate.min.js" %
                        request.application)
            validation_script = '''
$('#mailform').validate({
 errorClass:'req',
 rules:{
  name:{
   required:true
  },
  address: {
   required:true,
   email:true
  },
  subject:{
   required:true
  },
  message:{
   required:true
  }
 },
 messages:{
  name:"Enter your name",
  subject:"Enter a subject",
  message:"Enter a message",
  address:{
   required:"Please enter a valid email address",
   email:"Please enter a valid email address"
  }
 },
 errorPlacement:function(error,element){
  error.appendTo(element.parents('div.controls'))
 },
 submitHandler:function(form){
  form.submit()
 }
})'''
            s3.jquery_ready.append(validation_script)

        else:
            contact_form = ""

        if AUTHENTICATED not in roles:

            login_buttons = DIV(A(T("Login"),
                                  _id="show-login",
                                  _class="tiny secondary button"),
                                _id="login-buttons")
            script = '''
$('#show-mailform').click(function(e){
 e.preventDefault()
 $('#login_box').fadeOut(function(){$('#intro').fadeIn()})
})
$('#show-login').click(function(e){
 e.preventDefault()
 $('#login_form').show()
 $('#register_form').hide()
 $('#intro').fadeOut(function(){$('#login_box').fadeIn()})
})'''
            s3.jquery_ready.append(script)

            # This user isn't yet logged-in
            if request.cookies.has_key("registered"):
                # This browser has logged-in before
                registered = True

            if self_registration is True:
                # Provide a Registration box on front page
                login_buttons.append(
                    A(T("Register"),
                      _id="show-register",
                      _class="tiny secondary button",
                      _style="margin-left:5px"))
                script = '''
$('#show-register').click(function(e){
 e.preventDefault()
 $('#login_form').hide()
 $('#register_form').show()
 $('#intro').fadeOut(function(){$('#login_box').fadeIn()})
})'''
                s3.jquery_ready.append(script)

                register_form = auth.register()
                register_div = DIV(H3(T("Register")),
                                   P(XML(T("If you would like to help, then please %(sign_up_now)s") % \
                                            dict(sign_up_now=B(T("sign-up now"))))))

                register_script = '''
$('#register-btn').click(function(e){
 e.preventDefault()
 $('#login_form').fadeOut(function(){$('#register_form').fadeIn()})
})
$('#login-btn').click(function(e){
 e.preventDefault()
 $('#register_form').fadeOut(function(){$('#login_form').fadeIn()})
})'''
                s3.jquery_ready.append(register_script)

            # Provide a login box on front page
            auth.messages.submit_button = T("Login")
            login_form = auth.login(inline=True)
            login_div = DIV(H3(T("Login")),
                            P(XML(T("Registered users can %(login)s to access the system") % \
                                  dict(login=B(T("login"))))))

        else:
            login_buttons = ""

        # Create output dict
        output = {
            "login_buttons": login_buttons,
            "self_registration": self_registration,
            "registered": registered,
            "login_div": login_div,
            "login_form": login_form,
            "register_div": register_div,
            "register_form": register_form,
            "contact_form": contact_form,
            "project_links": project_links,
        }

        # Count records (@todo: provide total/updated counters?)
        s3db = current.s3db
        db = current.db

        # Organisations
        table = s3db.org_organisation
        query = (table.deleted != True)
        count = table.id.count()
        row = db(query).select(count).first()
        output["total_organisations"] = row[count]

        # Service Locations (@todo)
        #table = s3db.org_service_location
        #query = (table.deleted != True)
        #count = table.id.count()
        #row = db(query).select(count).first()
        output["total_services"] = 0  #row[count]

        # Needs lists
        table = s3db.req_organisation_needs
        query = (table.deleted != True)
        count = table.id.count()
        row = db(query).select(count).first()
        output["total_needs"] = row[count]

        # Frontpage Feed Control
        if settings.frontpage.rss:
            s3.external_stylesheets.append(
                "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css"
            )
            s3.scripts.append(
                "http://www.google.com/jsapi?key=notsupplied-wizard")
            s3.scripts.append(
                "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js"
            )
            counter = 0
            feeds = ""
            for feed in settings.frontpage.rss:
                counter += 1
                feeds = "".join((feeds, "{title:'%s',\n" % feed["title"],
                                 "url:'%s'}" % feed["url"]))
                # Don't add a trailing comma for old IEs
                if counter != len(settings.frontpage.rss):
                    feeds += ",\n"
            # feedCycleTime: milliseconds before feed is reloaded (5 minutes)
            feed_control = "".join(('''
function LoadDynamicFeedControl(){
 var feeds=[
  ''', feeds, '''
 ]
 var options={
  feedCycleTime:300000,
  numResults:5,
  stacked:true,
  horizontal:false,
  title:"''', str(T("News")), '''"
 }
 new GFdynamicFeedControl(feeds,'feed-control',options)
}
google.load('feeds','1')
google.setOnLoadCallback(LoadDynamicFeedControl)'''))

        s3.js_global.append(feed_control)
        s3.stylesheets.append("../themes/RW/homepage.css")

        self._view(THEME, "index.html")
        return output
    def __call__(self):

        T = current.T

        request = current.request
        response = current.response
        session = current.session

        settings = current.deployment_settings

        # Get the registration key
        if request.env.request_method == "POST":
            key = request.post_vars.registration_key
        elif len(request.args) > 1:
            key = request.args[-1]
        else:
            key = None
        if not key:
            session.error = T("Missing registration key")
            redirect(URL(c="default", f="index"))

        formfields = [
            Field(
                "activation_code",
                label=T("Please enter your Activation Code"),
                requires=IS_NOT_EMPTY(),
            ),
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(
            table_name="auth_user",
            record=None,
            hidden={
                "_next": request.vars._next,
                "registration_key": key,
            },
            separator=":",
            showid=False,
            submit_button=T("Submit"),
            formstyle=settings.get_ui_formstyle(),
            #buttons = buttons,
            *formfields)

        if form.accepts(
                request.vars,
                session,
                formname="register_confirm",
        ):

            db = current.db
            s3db = current.s3db

            auth = current.auth
            auth_settings = auth.settings
            register.customise_auth_messages()

            # Get registration key from URL
            code = form.vars.activation_code

            # Find the pending user account
            utable = auth_settings.table_user
            query = (utable.registration_key == register.keyhash(key, code))
            user = db(query).select(limitby=(0, 1), ).first()
            if not user:
                session.error = T("Registration not found")
                redirect(auth_settings.verify_email_next)

            # Configure callback to process custom fields
            s3db.configure(
                "auth_user",
                register_onaccept=register.register_onaccept,
            )

            # Approve and link user
            auth.s3_approve_user(user)

            # Send welcome email (custom)
            self.send_welcome_email(user)

            # Log them in
            user = Storage(utable._filter_fields(user, id=True))
            auth.login_user(user)

            auth_messages = auth.messages
            auth.log_event(auth_messages.verify_email_log, user)

            session = current.session
            session.confirmation = auth_messages.email_verified
            session.flash = auth_messages.registration_successful

            redirect(URL(c="default", f="person"))

        self._view(THEME, "register.html")

        return {
            "title": T("Confirm Registration"),
            "form": form,
        }
Beispiel #57
0
    def __call__(self):

        request = current.request
        response = current.response

        from gluon import Field, SQLFORM, IS_NOT_EMPTY, IS_EMAIL, IS_IN_SET, IS_EMPTY_OR
        from s3 import s3_mark_required, S3StringWidget

        T = current.T
        formstyle = current.deployment_settings.get_ui_formstyle()

        fields = [Field("address",
                        label = T("Your e-mail address"),
                        requires = IS_EMAIL(),
                        widget = lambda *args, **kwargs: \
                                 S3StringWidget(placeholder="*****@*****.**")(_type="email", *args, **kwargs),
                        ),
                  Field("subject",
                        label = T("Subject"),
                        requires = IS_EMPTY_OR(IS_IN_SET(("Solution Development",
                                                          "Workshop / Training",
                                                          "SAHANA Deployment / Support",
                                                          "Other / General Inquiry",
                                                          ),
                                                         zero = "What can we do for you?",
                                                         sort = False,
                                                         )),
                        ),
                  Field("message", "text",
                        label = T("Message"),
                        requires = IS_NOT_EMPTY(),
                        ),
                  ]

        labels, required = s3_mark_required(fields)
        response.form_label_separator = ""
        form = SQLFORM.factory(
            formstyle=formstyle,
            labels=labels,
            submit_button=T("Send Message"),
            _id="mailform",
            *fields,
        )

        if form.accepts(
                request.post_vars,
                current.session,
                formname="default/index/contact",
                #onvalidation = onvalidation,
                keepvalues=False,
                hideerror=False,
        ):

            form_vars = form.vars
            subject = "Request on AidIQ website"
            if form_vars.subject:
                subject = "%s: %s" % (subject, form_vars.subject)

            result = current.msg.send_email(
                to=current.deployment_settings.get_mail_approver(),
                subject=form_vars.subject,
                message=form_vars.message,
                reply_to=form_vars.address,
            )
            if result:
                response.confirmation = "Thank you for your message - we'll be in touch shortly"

        appname = request.application
        s3 = response.s3
        sappend = s3.scripts.append
        if s3.cdn:
            if s3.debug:
                sappend(
                    "//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"
                )
            else:
                sappend(
                    "//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
                )

        else:
            if s3.debug:
                sappend("/%s/static/scripts/jquery.validate.js" % appname)
            else:
                sappend("/%s/static/scripts/jquery.validate.min.js" % appname)
        sappend("/%s/static/themes/AidIQ/js/contact.js" % appname)

        response.title = "Contact Us | AidIQ.com"

        self._view(THEME, "contact.html")

        return {
            "form": DIV(form, _class="form-container"),
        }
    def __call__(self):

        auth = current.auth

        # Redirect if already logged-in
        if auth.s3_logged_in():
            redirect(URL(c="default", f="index"))

        auth_settings = auth.settings
        auth_messages = auth.messages
        self.customise_auth_messages()

        T = current.T
        db = current.db
        s3db = current.s3db

        request = current.request
        response = current.response
        session = current.session
        settings = current.deployment_settings

        utable = auth_settings.table_user

        # Page title and intro text
        title = T("Volunteer Registration")

        # Form Fields
        formfields, required_fields, subheadings = self.formfields()

        # Generate labels (and mark required fields in the process)
        labels, has_required = s3_mark_required(
            formfields,
            mark_required=required_fields,
        )
        response.s3.has_required = has_required
        labels["skill_id"] = DIV(
            labels["skill_id"],
            DIV(
                "(%s)" % T("Select all that apply"),
                _class="sub-label",
            ),
        )

        # Form buttons
        REGISTER = T("Register")
        buttons = [
            INPUT(
                _type="submit",
                _value=REGISTER,
            ),
            # TODO cancel-button?
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(table_name=utable._tablename,
                               record=None,
                               hidden={"_next": request.vars._next},
                               labels=labels,
                               separator="",
                               showid=False,
                               submit_button=REGISTER,
                               delete_label=auth_messages.delete_label,
                               formstyle=settings.get_ui_formstyle(),
                               buttons=buttons,
                               *formfields)

        # Identify form for CSS & JS Validation
        form.add_class("auth_register")

        # Add Subheadings
        if subheadings:
            for pos, heading in subheadings[::-1]:
                form[0].insert(pos, DIV(heading, _class="subheading"))

        # Inject client-side Validation
        auth.s3_register_validation()

        # Set default registration key, so new users are prevented
        # from logging in until approved
        key = str(uuid4())
        code = uuid4().hex[-6:].upper()
        utable.registration_key.default = self.keyhash(key, code)

        if form.accepts(
                request.vars,
                session,
                formname="register",
                onvalidation=auth_settings.register_onvalidation,
        ):

            formvars = form.vars

            # Add default organisation
            organisation_id = formvars.get("organisation_id")
            if not organisation_id:
                formvars[
                    "organisation_id"] = settings.get_org_default_organisation

            # Add HR type
            link_user_to = formvars.get("link_user_to")
            if link_user_to is None:
                formvars["link_user_to"] = ["volunteer"]

            # Create the user record
            user_id = utable.insert(
                **utable._filter_fields(formvars, id=False))
            formvars.id = user_id

            # Save temporary user fields in s3db.auth_user_temp
            temptable = s3db.auth_user_temp
            record = {"user_id": user_id}

            mobile = formvars.mobile_phone
            if mobile:
                record["mobile"] = mobile

            record["consent"] = formvars.consent

            # Store Custom fields
            custom = {#"date_of_birth": formvars.date_of_birth,
                      "home_phone": formvars.home_phone,
                      #"office_phone": formvars.office_phone,
                      "location_id": formvars.location_id,
                      "addr_street": formvars.addr_street,
                      "addr_postcode": formvars.addr_postcode,
                      "occupation_type_ids": formvars.occupation_type_ids,
                      "occupation": formvars.occupation,
                      #"start_date": formvars.start_date,
                      #"end_date": formvars.end_date,
                      "hours_per_week": formvars.hours_per_week,
                      "schedule": formvars.schedule,
                      "skill_id": formvars.skill_id,
                      "comments": formvars.comments,
                      }
            for datefield in ("date_of_birth", "start_date", "end_date"):
                value = formvars.get(datefield)
                if value:
                    value = value.isoformat()
                    custom[datefield] = value
            record["custom"] = json.dumps(custom)

            temptable.insert(**record)

            # Post-process the new user record
            users = db(utable.id > 0).select(utable.id, limitby=(0, 2))
            if len(users) == 1:
                # 1st user to register doesn't need verification/approval
                auth.s3_approve_user(form.vars)
                session.confirmation = auth_messages.registration_successful

                # 1st user gets Admin rights
                admin_group_id = 1
                auth.add_membership(admin_group_id, users.first().id)

                # Log them in
                if "language" not in form.vars:
                    # Was missing from login form
                    form.vars.language = T.accepted_language
                user = Storage(utable._filter_fields(form.vars, id=True))
                auth.login_user(user)

                # Send welcome email
                auth.s3_send_welcome_email(form.vars)

                # Where to go next?
                register_next = request.vars._next or auth_settings.register_next

            else:
                # Request User Verify their Email
                # System Details for Verification Email
                verify_url = URL(
                    c="default",
                    f="index",
                    args=["verify_email", key],
                    scheme="https" if request.is_https else "http",
                )
                system = {
                    "system_name": settings.get_system_name(),
                    "url": verify_url,
                    #"url": "%s/default/index/verify_email/%s" % (response.s3.base_url, key),
                    "code": code,
                }

                # Try to send the Verification Email
                if not auth_settings.mailer or \
                   not auth_settings.mailer.settings.server or \
                   not auth_settings.mailer.send(to = form.vars.email,
                                                 subject = auth_messages.verify_email_subject % system,
                                                 message = auth_messages.verify_email % system,
                                                 ):
                    response.error = auth_messages.email_verification_failed

                    # Custom View
                    self._view(THEME, "register.html")

                    return {
                        "title": title,
                        "form": form,
                    }

                # Redirect to Verification Info page
                register_next = URL(
                    c="default",
                    f="message",
                    args=["verify_email_sent"],
                    vars={"email": form.vars.email},
                )

            # Log action
            auth.log_event(auth_messages.register_log, form.vars)

            # Redirect
            redirect(register_next)

        elif form.errors:
            response.error = T(
                "There are errors in the form, please check your input")

        # Custom View
        self._view(THEME, "register.html")

        return {
            "title": title,
            "form": form,
        }
Beispiel #59
0
    def __call__(self):

        request = current.request
        response = current.response

        if request.env.request_method == "POST":
            # Processs Form
            vars = request.post_vars
            result = current.msg.send_email(
                to=current.deployment_settings.get_mail_approver(),
                subject=vars.subject,
                message=vars.message,
                reply_to=vars.address,
            )
            if result:
                response.confirmation = "Thankyou for your message - we'll be in touch shortly"

        from gluon import Field, SQLFORM
        from s3 import s3_mark_required, S3StringWidget

        T = current.T
        formstyle = current.deployment_settings.get_ui_formstyle()

        fields = [
            Field(
                "name",
                label=T("Your name"),
                required=True,
            ),
            Field(
                "address",
                label=T("Your e-mail address"),
                required=True,
                #widget = S3StringWidget(placeholder="*****@*****.**"),
            ),
            Field(
                "subject",
                label=T("Subject"),
                required=True,
            ),
            Field(
                "message",
                "text",
                label=T("Message"),
                required=True,
            ),
        ]

        labels, required = s3_mark_required(fields)
        response.form_label_separator = ""
        form = SQLFORM.factory(formstyle=formstyle,
                               labels=labels,
                               submit_button=T("Send Message"),
                               *fields)
        form["_id"] = "mailform"
        form = DIV(
            H4("Contact Us",
               _style="background-color:#f7f8f9;padding:0.1rem 0.3rem"),
            P("You can leave a message using the contact form below."),
            form,
            _class="form-container",
        )

        appname = request.application
        s3 = response.s3
        sappend = s3.scripts.append
        if s3.cdn:
            if s3.debug:
                sappend(
                    "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"
                )
            else:
                sappend(
                    "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
                )

        else:
            if s3.debug:
                sappend("/%s/static/scripts/jquery.validate.js" % appname)
            else:
                sappend("/%s/static/scripts/jquery.validate.min.js" % appname)
        if s3.debug:
            sappend("/%s/static/themes/AidIQ/js/contact.js" % appname)
        else:
            sappend("/%s/static/themes/AidIQ/js/contact.min.js" % appname)

        response.title = "Contact | AidIQ.com"

        self._view(THEME, "contact.html")
        return dict(form=form)
Beispiel #60
0
    def register(self, r, **attr):
        """
            Register a test result

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

        if r.http not in ("GET", "POST"):
            r.error(405, current.ERROR.BAD_METHOD)
        if not r.interactive:
            r.error(415, current.ERROR.BAD_FORMAT)

        T = current.T
        db = current.db
        s3db = current.s3db
        auth = current.auth

        request = current.request
        response = current.response
        s3 = response.s3

        settings = current.deployment_settings

        # Page title and intro text
        title = T("Register Test Result")

        # Get intro text from CMS
        ctable = s3db.cms_post
        ltable = s3db.cms_post_module
        join = ltable.on((ltable.post_id == ctable.id) & \
                         (ltable.module == "disease") & \
                         (ltable.resource == "case_diagnostics") & \
                         (ltable.deleted == False))

        query = (ctable.name == "TestResultRegistrationIntro") & \
                (ctable.deleted == False)
        row = db(query).select(
            ctable.body,
            join=join,
            cache=s3db.cache,
            limitby=(0, 1),
        ).first()
        intro = row.body if row else None

        # Instantiate Consent Tracker
        consent = s3db.auth_Consent(
            processing_types=["CWA_ANONYMOUS", "CWA_PERSONAL"])

        table = s3db.disease_case_diagnostics

        # Configure disease_id
        field = table.disease_id
        if field.writable:
            default_disease = None
            offset = 1
        else:
            default_disease = field.default
            field.readable = False
            offset = 0

        # Probe date is mandatory
        field = table.probe_date
        requires = field.requires
        if isinstance(requires, IS_EMPTY_OR):
            field.requires = requires.other

        # Configure device_id
        field = table.device_id
        field.readable = field.writable = True

        dtable = s3db.disease_testing_device
        query = (dtable.device_class == "RAT") & \
                (dtable.approved == True) & \
                (dtable.available == True)
        if default_disease:
            query = (dtable.disease_id == default_disease) & query
        field.requires = IS_ONE_OF(
            db(query),
            "disease_testing_device.id",
            field.represent,
        )

        cwa_options = (
            ("NO", T("Do not report")),
            ("ANONYMOUS", T("Issue anonymous contact tracing code")),
            ("PERSONAL", T("Issue personal test certificate")),
        )
        formfields = [  # -- Test Result --
            table.site_id,
            table.disease_id,
            table.probe_date,
            table.device_id,
            table.result,

            # -- Report to CWA --
            Field(
                "report_to_cwa",
                "string",
                requires=IS_IN_SET(cwa_options, sort=False, zero=""),
                default="NO",
                label=T("Report test result to %(system)s") % CWA,
            ),
            Field(
                "last_name",
                label=T("Last Name"),
            ),
            Field(
                "first_name",
                label=T("First Name"),
            ),
            s3_date(
                "date_of_birth",
                label=T("Date of Birth"),
                month_selector=True,
            ),
            Field(
                "dcc_option",
                "boolean",
                default=False,
                label=T("Provide Digital %(title)s Certificate") %
                {"title": "COVID-19 Test"},
            ),
            Field(
                "consent",
                label="",
                widget=consent.widget,
            ),
        ]

        # Required fields
        required_fields = []

        # Subheadings
        subheadings = (
            (0, T("Test Result")),
            (4 + offset, CWA["system"]),
        )

        # Generate labels (and mark required fields in the process)
        labels, has_required = s3_mark_required(
            formfields,
            mark_required=required_fields,
        )
        s3.has_required = has_required

        # Form buttons
        REGISTER = T("Submit")
        buttons = [
            INPUT(
                _type="submit",
                _value=REGISTER,
            ),
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(table_name="test_result",
                               record=None,
                               hidden={"_next": request.vars._next},
                               labels=labels,
                               separator="",
                               showid=False,
                               submit_button=REGISTER,
                               delete_label=auth.messages.delete_label,
                               formstyle=settings.get_ui_formstyle(),
                               buttons=buttons,
                               *formfields)

        # Identify form for CSS & JS Validation
        form.add_class("result-register")

        # Add Subheadings
        if subheadings:
            for pos, heading in subheadings[::-1]:
                form[0].insert(pos, DIV(heading, _class="subheading"))

        # Inject scripts
        script = "/%s/static/themes/RLP/js/testresult.js" % r.application
        if script not in s3.scripts:
            s3.scripts.append(script)
        s3.jquery_ready.append("S3EnableNavigateAwayConfirm()")

        if form.accepts(
                request.vars,
                current.session,
                formname="register",
                onvalidation=self.validate,
        ):

            formvars = form.vars

            # Create disease_case_diagnostics record
            testresult = {
                "result": formvars.get("result"),
            }
            if "site_id" in formvars:
                testresult["site_id"] = formvars["site_id"]
            if "disease_id" in formvars:
                testresult["disease_id"] = formvars["disease_id"]
            if "probe_date" in formvars:
                testresult["probe_date"] = formvars["probe_date"]
            if "device_id" in formvars:
                testresult["device_id"] = formvars["device_id"]

            record_id = table.insert(**testresult)
            if not record_id:
                raise RuntimeError("Could not create testresult record")

            testresult["id"] = record_id
            # Set record owner
            auth = current.auth
            auth.s3_set_record_owner(table, record_id)
            auth.s3_make_session_owner(table, record_id)
            # Onaccept
            s3db.onaccept(table, testresult, method="create")
            response.confirmation = T("Test Result registered")

            report_to_cwa = formvars.get("report_to_cwa")
            if report_to_cwa == "NO":
                # Do not report to CWA, just forward to read view
                self.next = r.url(id=record_id, method="read")
            else:
                # Report to CWA and show test certificate
                dcc_option = False
                if report_to_cwa == "ANONYMOUS":
                    processing_type = "CWA_ANONYMOUS"
                    cwa_report = CWAReport(record_id)
                elif report_to_cwa == "PERSONAL":
                    dcc_option = formvars.get("dcc_option")
                    processing_type = "CWA_PERSONAL"
                    cwa_report = CWAReport(
                        record_id,
                        anonymous=False,
                        first_name=formvars.get("first_name"),
                        last_name=formvars.get("last_name"),
                        dob=formvars.get("date_of_birth"),
                        dcc=dcc_option,
                    )
                else:
                    processing_type = cwa_report = None

                if cwa_report:
                    # Register consent
                    if processing_type:
                        cwa_report.register_consent(
                            processing_type,
                            formvars.get("consent"),
                        )
                    # Send to CWA
                    success = cwa_report.send()
                    if success:
                        response.information = T(
                            "Result reported to %(system)s") % CWA
                        retry = False
                    else:
                        response.error = T("Report to %(system)s failed") % CWA
                        retry = True

                    # Store DCC data
                    if dcc_option:
                        cwa_data = cwa_report.data
                        from .dcc import DCC
                        try:
                            hcert = DCC.from_result(
                                cwa_data.get("hash"),
                                record_id,
                                cwa_data.get("fn"),
                                cwa_data.get("ln"),
                                cwa_data.get("dob"),
                            )
                        except ValueError as e:
                            hcert = None
                            response.warning = str(e)
                        if hcert:
                            hcert.save()
                        else:
                            # Remove DCC flag if hcert could not be generated
                            cwa_report.dcc = False

                    S3CustomController._view("RLPPTM", "certificate.html")

                    # Title
                    field = table.disease_id
                    if cwa_report.disease_id and field.represent:
                        disease = field.represent(cwa_report.disease_id)
                        title = "%s %s" % (disease, T("Test Result"))
                    else:
                        title = T("Test Result")

                    return {
                        "title": title,
                        "intro": None,  # TODO
                        "form": cwa_report.formatted(retry=retry),
                    }
                else:
                    response.information = T(
                        "Result not reported to %(system)s") % CWA
                    self.next = r.url(id=record_id, method="read")

            return None

        elif form.errors:
            current.response.error = T(
                "There are errors in the form, please check your input")

        # Custom View
        S3CustomController._view("RLPPTM", "testresult.html")

        return {
            "title": title,
            "intro": intro,
            "form": form,
        }