Пример #1
0
 def _build_access_rights(self, object_name, connection_data):
     import pytis.data
     import config
     access_rights = []
     bindings = [
         pytis.data.DBColumnBinding(name, 'pytis.access_rights', name)
         for name in 'id', 'object', 'column_', 'group_', 'permission'
     ]
     key = bindings[0]
     data = pytis.data.DBDataDefault(bindings,
                                     key,
                                     connection_data=connection_data)
     try:
         data.select(condition=EQ('object', sval(object_name)))
         while True:
             row = data.fetchone()
             if row is None:
                 break
             access_rights.append(
                 (row['column_'].value(), (row['group_'].value(),
                                           row['permission'].value())))
     finally:
         try:
             data.close()
         except:
             pass
     return access_rights
Пример #2
0
def data_table(view, data, condition=None, sorting=None, transaction=None, **long_table_args):
    """Jednoduchý tisk tabulky dat.

    Zadaná tabulka bude jednoduchým způsobem zformátována na výstup.  Výběr dat
    je specifikován argumenty předanými konstruktoru použitého formátovače.
    Pro prezentační podobu tabulky jsou přiměřeně použity specifikace v jejím
    view.

    Argumenty:

      view -- presentation specification of the table;
        'pytis.presentation.Specification' instance
      data -- data object to use for querying the database; 'pytis.data.Data'
        instance
      condition -- podmínka výběru řádků tabulky ve formátu argumentu
        'condition' metody 'pytis.util.Data.select()'
      sorting -- specifikace třídění řádků tabulky ve formátu argumentu 'sort'
        metody 'pytis.util.Data.select()'
      transaction -- transaction object to use for database operations
      long_table_args -- dodatečné argumenty předané konstruktoru třídy
        'LongTable'
    
    """
    import pytis.data
    import pytis.form
    import pytis.presentation
    assert isinstance(view, pytis.presentation.ViewSpec), view
    assert isinstance(data, pytis.data.Data), data
    # Prezentace
    presented_row = pytis.presentation.PresentedRow(view.fields(), data, None, singleline=True)
    columns = []
    for cid in view.columns():
        f = view.field(cid)
        width = f.column_width()
        if width == 0:
            continue
        label = f.column_label()
        if isinstance(presented_row[cid].type(), pytis.data.Number):
            alignment = pytis.output.LongTable.Column.ALIGN_RIGHT
        else:
            alignment = pytis.output.LongTable.Column.ALIGN_LEFT
        tc = pytis.output.LongTable.Column(label, width, alignment=alignment)
        tc.id = cid # fuj, viz `table_row' níže
        columns.append(tc)
    # Data
    data.select(condition=condition, sort=sorting, transaction=transaction)
    # Formátování
    def table_row(*args, **kwargs):
        row = data.fetchone(transaction=transaction)
        if row is None:
            return None
        presented_row.set_row(row)
        return [presented_row.format(c.id, secure=True) for c in columns]
    long_table_args['separator_margin'] = \
        long_table_args['line_separator_margin'] = UFont(0.2)
    return pytis.output.LongTable(columns, table_row, **long_table_args)
Пример #3
0
        def delete_template(module, specification):
            def s(value):
                return pytis.data.Value(pytis.data.String(), value)

            data_spec = self.data_spec()
            view_spec = self.view_spec()
            import config
            data = data_spec.create(dbconnection_spec=config.dbconnection)
            condition = pytis.data.AND(
                pytis.data.EQ('module', s(module)),
                pytis.data.EQ('specification', s(specification)))
            if not data.select(condition):
                message = _("Tisková sestava neexistuje: ") + specification
                pytis.form.run_dialog(pytis.form.Error, message)
                return
            row = data.fetchone()
            if data.fetchone() is not None:
                message = _(
                    "Tisková sestava se vyskytuje ve více exemplářích: "
                ) + specification
                pytis.form.run_dialog(pytis.form.Error, message)
                return
            record = pytis.presentation.PresentedRow(view_spec.fields(), data,
                                                     row)
            if pytis.form.delete_record(view_spec, data, None, record):
                # To update the printing button of the current form
                pytis.form.refresh()
Пример #4
0
 def _build_access_rights(self, object_name, connection_data):
     import pytis.data
     access_rights = []
     bindings = [pytis.data.DBColumnBinding(name, 'pytis.access_rights', name)
                 for name in 'id', 'object', 'column_', 'group_', 'permission']
     key = bindings[0]
     data = pytis.data.DBDataDefault(bindings, key,
                                     connection_data=connection_data)
     try:
         data.select(condition=EQ('object', sval(object_name)))
         while True:
             row = data.fetchone()
             if row is None:
                 break
             access_rights.append((row['column_'].value(),
                                   (row['group_'].value(),
                                    row['permission'].value())))
     finally:
         try:
             data.close()
         except:
             pass
     return access_rights
Пример #5
0
 def check_data(self, spec_name):
     errors = []
     resolver = self._resolver
     try:
         data_spec = resolver.get(spec_name, 'data_spec')
     except pytis.util.ResolverError as e:
         return errors + [str(e)]
     try:
         view_spec = resolver.get(spec_name, 'view_spec')
         fields = view_spec.fields()
         success, data = pytis.form.db_operation(data_spec.create,
                                                 dbconnection_spec=self._dbconn)
         if not success:
             return errors + ["Nepodařilo se vytvořit datový objekt."]
         try:
             data.select(limit=1)
             try:
                 row = data.fetchone()
             except AssertionError as e:
                 # Hack to avoid printing errors on non-existent image files
                 # referred from the database.
                 if ((len(e.args) == 3 and
                      isinstance(e.args[2], pytis.data.ValidationError) and
                      e.args[2][0] == u'Neplatný grafický formát')):
                     row = None
                 else:
                     raise
         finally:
             try:
                 data.close()
             except:
                 pass
         if row:
             pytis.presentation.PresentedRow(fields, data, row)
     except Exception as e:
         errors.append(str(e))
     return errors
Пример #6
0
 def check_data(self, spec_name):
     errors = []
     resolver = self._resolver
     try:
         data_spec = resolver.get(spec_name, 'data_spec')
     except pytis.util.ResolverError as e:
         return errors + [str(e)]
     try:
         view_spec = resolver.get(spec_name, 'view_spec')
         fields = view_spec.fields()
         success, data = pytis.form.db_operation(
             data_spec.create, dbconnection_spec=self._dbconn)
         if not success:
             return errors + ["Nepodařilo se vytvořit datový objekt."]
         try:
             data.select(limit=1)
             try:
                 row = data.fetchone()
             except AssertionError as e:
                 # Hack to avoid printing errors on non-existent image files
                 # referred from the database.
                 if ((len(e.args) == 3
                      and isinstance(e.args[2], pytis.data.ValidationError)
                      and e.args[2][0] == u'Neplatný grafický formát')):
                     row = None
                 else:
                     raise
         finally:
             try:
                 data.close()
             except:
                 pass
         if row:
             pytis.presentation.PresentedRow(fields, data, row)
     except Exception as e:
         errors.append(str(e))
     return errors
Пример #7
0
def dbselect(spec, condition=None, sort=(), transaction=None, arguments={}):
    """Vrať řádky dané db tabulky jako sekvenci.

    Argumenty:

      spec -- název specifikace datového objektu nebo přímo instance třídy
        'pytis.data.DataFactory'
      condition, sort, transaction -- argumenty volání
        'pytis.data.postgresql.select()'.

    Vrací všechny řádky vrácené z databáze jako list.

    """
    data = data_object(spec)
    data.select(condition=condition, sort=sort, transaction=transaction,
                arguments=arguments)
    result = []
    while True:
        row = data.fetchone()
        if row is None:
            data.close()
            break
        result.append(row)
    return result
Пример #8
0
 def delete_template(module, specification):
     def s(value):
         return pytis.data.Value(pytis.data.String(), value)
     data_spec = self.data_spec()
     view_spec = self.view_spec()
     import config
     data = data_spec.create(dbconnection_spec=config.dbconnection)
     condition = pytis.data.AND(pytis.data.EQ('module', s(module)),
                                pytis.data.EQ('specification', s(specification)))
     if not data.select(condition):
         message = _("Tisková sestava neexistuje: ") + specification
         pytis.form.run_dialog(pytis.form.Error, message)
         return
     row = data.fetchone()
     if data.fetchone() is not None:
         message = _("Tisková sestava se vyskytuje ve více exemplářích: ") + specification
         pytis.form.run_dialog(pytis.form.Error, message)
         return
     record = pytis.presentation.PresentedRow(view_spec.fields(), data, row)
     if pytis.form.delete_record(view_spec, data, None, record):
         # To update the printing button of the current form
         pytis.form.refresh()
Пример #9
0
def crypto_admin_key(area, admin_user, connection_data):
    """Return crypto admin key for the given user and area.

    The return value is a pair (KEY_ID, KEY) where KEY_ID is the database
    record key and KEY is the actual key.

    Arguments:

      area -- name of the crypto area; basestring
      admin_user -- login name of the crypto area administrator; basestring
      connection_data -- database connection data; 'pytis.data.DBConnection'
        instance

    """
    data = crypto_key_table(connection_data)
    condition = pytis.data.AND(
        pytis.data.EQ('username', pytis.data.sval(admin_user)),
        pytis.data.EQ('name', pytis.data.sval(area)))
    if not data.select(condition):
        return None, None
    row = data.fetchone()
    return row['key_id'], row['key']
Пример #10
0
def data_table(view,
               data,
               condition=None,
               sorting=None,
               transaction=None,
               **long_table_args):
    """Jednoduchý tisk tabulky dat.

    Zadaná tabulka bude jednoduchým způsobem zformátována na výstup.  Výběr dat
    je specifikován argumenty předanými konstruktoru použitého formátovače.
    Pro prezentační podobu tabulky jsou přiměřeně použity specifikace v jejím
    view.

    Argumenty:

      view -- presentation specification of the table;
        'pytis.presentation.Specification' instance
      data -- data object to use for querying the database; 'pytis.data.Data'
        instance
      condition -- podmínka výběru řádků tabulky ve formátu argumentu
        'condition' metody 'pytis.util.Data.select()'
      sorting -- specifikace třídění řádků tabulky ve formátu argumentu 'sort'
        metody 'pytis.util.Data.select()'
      transaction -- transaction object to use for database operations
      long_table_args -- dodatečné argumenty předané konstruktoru třídy
        'LongTable'
    
    """
    import pytis.data
    import pytis.form
    import pytis.presentation
    assert isinstance(view, pytis.presentation.ViewSpec), view
    assert isinstance(data, pytis.data.Data), data
    # Prezentace
    presented_row = pytis.presentation.PresentedRow(view.fields(),
                                                    data,
                                                    None,
                                                    singleline=True)
    columns = []
    for cid in view.columns():
        f = view.field(cid)
        width = f.column_width()
        if width == 0:
            continue
        label = f.column_label()
        if isinstance(presented_row[cid].type(), pytis.data.Number):
            alignment = pytis.output.LongTable.Column.ALIGN_RIGHT
        else:
            alignment = pytis.output.LongTable.Column.ALIGN_LEFT
        tc = pytis.output.LongTable.Column(label, width, alignment=alignment)
        tc.id = cid  # fuj, viz `table_row' níže
        columns.append(tc)
    # Data
    data.select(condition=condition, sort=sorting, transaction=transaction)

    # Formátování
    def table_row(*args, **kwargs):
        row = data.fetchone(transaction=transaction)
        if row is None:
            return None
        presented_row.set_row(row)
        return [presented_row.format(c.id, secure=True) for c in columns]
    long_table_args['separator_margin'] = \
        long_table_args['line_separator_margin'] = UFont(0.2)
    return pytis.output.LongTable(columns, table_row, **long_table_args)
Пример #11
0
def add_crypto_user(area,
                    user,
                    admin_user,
                    admin_password,
                    admin_address,
                    connection_data,
                    transaction=None,
                    user_password=None):
    """Add new crypto user for the given area.

    If the action succeeds, return 'None'.  Otherwise return an error
    description (basestring).

    Arguments:

      area -- name of the crypto area; basestring
      user -- login name of the user to get the access to the area; basestring
      admin_user -- login name of the crypto area administrator; basestring
      admin_password -- password to the admin key; basestring
      admin_address -- e-mail address of the admin user, to be used as the
        sender of the notification e-mail; basestring
      connection_data -- database connection data; 'pytis.data.DBConnection'
        instance
      transaction -- transaction to use
      user_password -- string to use as the password for given login name; in such a case
        password will not be sent by email.

    """
    key_id, key = crypto_admin_key(area, admin_user, connection_data)
    if key_id is None:
        return "admin key not found for the area: %s" % (area, )
    try:
        transaction_ = transaction
        if transaction_ is None:
            transaction_ = pytis.data.DBTransactionDefault(connection_data)
        condition = pytis.data.AND(
            pytis.data.EQ('name', pytis.data.sval(area)),
            pytis.data.EQ('username', pytis.data.sval(user)))
        data = pytis.data.dbtable('e_pytis_crypto_keys', (
            'name',
            'username',
        ), connection_data)
        if data.select(condition) > 0:
            return "key already exists for the given user and area: %s %s" % (
                user,
                area,
            )
        data.close()
        if user_password is None:
            function = pytis.data.DBFunctionDefault(
                'pytis_crypto_user_contact', connection_data)
            row = pytis.data.Row(((
                'username',
                pytis.data.sval(user),
            ), ))
            result = function.call(row, transaction=transaction_)[0]
            email, gpg_key = [v.value() for v in result]
            if gpg_key is None:
                return "crypto contact not found for user: %s" % (user, )
            characters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789_-=$#%!'
            user_password = ''.join(
                [characters[ord(c) % 64] for c in os.urandom(32)])
            send_password = True
        else:
            send_password = False
        if not check_crypto_password(key, admin_password, connection_data):
            return "invalid password"
        function = pytis.data.DBFunctionDefault('pytis_crypto_copy_key',
                                                connection_data)
        row = pytis.data.Row((
            (
                'name_',
                pytis.data.sval(area),
            ),
            (
                'from_user',
                pytis.data.sval(admin_user),
            ),
            (
                'to_user',
                pytis.data.sval(user),
            ),
            (
                'from_psw',
                pytis.data.sval(admin_password),
            ),
            (
                'to_psw',
                pytis.data.sval(user_password),
            ),
        ))
        if not function.call(row, transaction=transaction_)[0][0]:
            return "user key installation failed"
        if send_password:
            subject = u"Vaše heslo pro šifrovanou oblast %s" % (area, )
            text = u"Vaše heslo pro šifrovanou aplikační oblast %s je:\n%s\n" % (
                area, user_password)
            error = send_mail(email, admin_address, subject, text, key=gpg_key)
            if error:
                return "failure when sending mail to the user: %s" % (error, )
        else:
            data = pytis.data.dbtable('e_pytis_crypto_keys',
                                      ('key_id', 'name', 'username', 'fresh'),
                                      connection_data)
            row = pytis.data.Row(((
                'fresh',
                pytis.data.bval(True),
            ), ))
            condition = pytis.data.AND(
                pytis.data.EQ('name', pytis.data.sval(area)),
                pytis.data.EQ('username', pytis.data.sval(user)))
            result = data.update_many(condition, row, transaction=transaction_)
            if result != 1:
                return "couldn't update fresh column for the new user key"
            data.close()
        if transaction is None:
            transaction_.commit()
        transaction_ = None
    finally:
        if transaction is None and transaction_ is not None:
            transaction_.rollback()
Пример #12
0
 def lfunction():
     data.select(transaction=transaction)
     self._row = data.fetchone()
     data.close()