예제 #1
0
class Roles(Specification):
    title = _("Uživatelské role")
    help = _(
        "Správa dostupných uživatelských rolí, které je možné přiřazovat uživatelům."
    )
    table = 'cms_roles'

    def fields(self):
        return (
            Field('role_id', default=nextval('cms_roles_role_id_seq')),
            Field('name', _("Title"), width=16),
            Field('system_role',
                  _("Systémová role"),
                  width=16,
                  type=pd.String(not_null=True)),
            Field('description', _("Description"), width=64),
        )

    layout = ('name', 'description')
    columns = ('name', 'description')
    condition = pd.EQ('system_role', pd.Value(pd.String(), None))

    def bindings(self):
        return (Binding('users', _("Uživatelé zařazení do této role"),
                        self._spec_name('RoleUsers'), 'role_id'), )

    cb = CodebookSpec(display='name')
예제 #2
0
 def _product_filter(self, row, marked, filter):
     condition = pd.WM('product', pd.WMValue(pd.String(), filter
                                             or '*'))
     if marked:
         value = pd.Value(pd.Boolean(), True)
         condition = pd.AND(condition, pd.EQ('marked', value))
     return condition
예제 #3
0
파일: spec.py 프로젝트: cerha/pytis
def cb2colvalue(value, column=None, transaction=None):
    """Převeď hodnotu políčka na hodnotu uvedeného sloupce navázaného číselníku.

    Argumenty:

      value -- Instance `Value', jejíž typ má definován enumerátor typu
        'pd.DataEnumerator'.
      column -- název sloupce číselníku poskytujícího výslednou hodnotu.
      transaction -- transakce pro předání datovým operacím.

    Pokud odpovídající řádek není nalezen, bude vrácena instance 'Value'
    stejného typu, jako je typ argumentu 'value' s hodnotou nastavenou na
    'None'.  Takováto hodnota nemusí být validní hodnotou typu, ale
    zjednodušuje se tím práce s výsledkem.  Pokud je zapotřebí korektnějšího
    chování, je doporučeno použít přímo metodu 'DataEnumerator.row()'
    (například voláním 'value.type().enumerator().row(value.value())'.

    """
    assert isinstance(value, pd.Value)
    assert value.type().enumerator() is not None
    if column is None:
        return value
    else:
        row = value.type().enumerator().row(value.value(),
                                            transaction=transaction)
        if row is not None:
            return row[column]
        else:
            return pd.Value(value.type(), None)
예제 #4
0
class SystemRoles(Roles):
    title = _("Systémové role")
    help = _("Systémové role jsou uživatelům přiřazeny automaticky.")
    layout = columns = ('name', 'system_role', 'description')
    condition = pd.NE('system_role', pd.Value(pd.String(), None))
    bindings = ()
    access_rights = pd.AccessRights((None, ('cms_admin', pd.Permission.ALL)),
                                    (None, ('cms_user', pd.Permission.VIEW)))
예제 #5
0
파일: test.py 프로젝트: cerha/pytis
 def test_original_row(self):
     r = pd.Row([(k, pd.Value(pd.Integer(), v))
                 for k, v in dict(a=None, b=6, c=None, d=3).items()])
     row = self._mega_row(new=True, row=r, b=22, c=33, d=44)
     r1 = row.original_row()
     self._check_values(r1, a=None, b=22, c=33, d=44)
     r2 = row.original_row(initialized=False)
     self._check_values(r2, a=None, b=6, c=None, d=3)
예제 #6
0
파일: web.py 프로젝트: cerha/pytis
 def _new_session(self, uid, session_key):
     data = self._data
     expiration = datetime.timedelta(hours=wiking.cfg.session_expiration)
     # Delete all expired records first (can't do in trigger due to the configuration option).
     data.delete_many(pd.LE('last_access',
                            pd.Value(pd.DateTime(),
                                     pd.DateTime.datetime(False) - expiration)))
     return data.insert(data.make_row(
         session_key=session_key,
         uid=uid,
         last_access=pd.DateTime.datetime(False))
     )[0]
예제 #7
0
파일: web.py 프로젝트: nicLucian/pytis
 def init(self, req, user, session_key):
     data = self._data
     # Delete all expired records first...
     now = pd.DateTime.datetime()
     expiration = datetime.timedelta(hours=wiking.cfg.session_expiration)
     data.delete_many(
         pd.LE('last_access', pd.Value(pd.DateTime(), now - expiration)))
     # Create new data row for this session.
     row, success = data.insert(
         data.make_row(uid=user.uid(),
                       session_key=session_key,
                       last_access=now))
     # Log session start for login history tracking.
     self._module('SessionLog').log(req, now, row['session_id'].value(),
                                    user.uid(), user.login())
예제 #8
0
파일: defs.py 프로젝트: cerha/pytis
    def __init__(self, spec_name_prefix=None):
        """
        Arguments:

          spec_name_prefix -- if not None then only specification with given
            prefix (basestring) are tested

        """
        import pytis.output
        self._output_resolver = pytis.output.OutputResolver(
            pytis.config.print_spec_dir, pytis.config.resolver)
        data = pd.dbtable('e_pytis_roles', ('name', 'purposeid'))
        condition = pd.NE('purposeid', pd.Value(pd.String(), 'user'))
        self._application_roles = [
            row[0].value()
            for row in data.select_map(identity, condition=condition)
        ]
        self._spec_name_prefix = spec_name_prefix
예제 #9
0
파일: misc.py 프로젝트: cerha/pytis
 def _update_prices(self, row):
     # This serves for testing user transactions.
     true_value = pd.Value(pd.Boolean(), True)
     condition = pd.EQ('marked', true_value)
     transaction = pd.transaction()
     try:
         def process(row):
             return row['product_id']
         product_ids = row.data().select_map(process, condition=condition)
         for product_id in product_ids:
             if not pytis.form.run_form(pytis.form.PopupEditForm, 'misc.Products',
                                        select_row=product_id,
                                        transaction=transaction):
                 app.error("Transaction aborted")
                 transaction.rollback()
                 return
     except Exception:
         transaction.rollback()
         raise
     transaction.commit()
예제 #10
0
파일: test.py 프로젝트: cerha/pytis
 def test_key(self):
     row = self._row(
         (pp.Field('x', type=pd.Integer(not_null=True)), pp.Field('y')))
     assert row.key() == (pd.Value(pd.Integer(not_null=True), None), )
     row['x'] = 1
     assert row.key() == (pd.Value(pd.Integer(not_null=True), 1), )
예제 #11
0
파일: test.py 프로젝트: cerha/pytis
 def _data_row(self, row, **values):
     return pd.Row([(f.id(), pd.Value(f.type(), values.get(f.id())))
                    for f in row.fields() if not f.virtual()])
예제 #12
0
 def _action_filter(self, record, mod_id):
     return pd.OR(pd.EQ('mod_id', record['mod_id']),
                  pd.EQ('mod_id', pd.Value(pd.Integer(), None)))
예제 #13
0
class GenericActions(Actions):
    title = _("Akce společné pro všechny položky men")
    help = _("Výčet podporovaných akcí společných pro všechny položky menu.")
    condition = pd.EQ('mod_id', pd.Value(pd.Integer(), None))
    access_rights = pd.AccessRights((None, ('cms_admin', pd.Permission.ALL)),
                                    (None, ('cms_user', pd.Permission.VIEW)))
예제 #14
0
파일: _test.py 프로젝트: nicLucian/pytis
 def _value(self, key, value):
     col = find(key, self._columns, key=lambda c: c.id())
     return pd.Value(col.type(), value)
예제 #15
0
파일: _test.py 프로젝트: nicLucian/pytis
 def _data_row(self, **values):
     return pd.Row([(c.id(), pd.Value(c.type(), values.get(c.id())))
                    for c in self._columns])
예제 #16
0
def run():
    if '--help' in sys.argv:
        usage()
    try:
        pytis.config.add_command_line_options(sys.argv)
        if len(sys.argv) > 1:
            usage()
    except getopt.GetoptError as e:
        usage(e.msg)
    wiking.cfg.user_config_file = pytis.config.config_file
    pytis.config.dblisten = False
    pytis.config.log_exclude = [pytis.util.ACTION, pytis.util.EVENT,
                                pytis.util.DEBUG, pytis.util.OPERATIONAL]
    while True:
        try:
            data = pd.dbtable('cms_page_attachments',
                              ('attachment_id', 'filename', 'width', 'height',
                               'image', 'image_width', 'image_height', 'thumbnail',
                               'thumbnail_size', 'thumbnail_width', 'thumbnail_height'),
                              pytis.config.dbconnection)
        except pd.DBLoginException as e:
            if pytis.config.dbconnection.password() is None:
                import getpass
                login = pytis.config.dbuser
                password = getpass.getpass("Enter database password for %s: " % login)
                pytis.config.dbconnection.update_login_data(user=login, password=password)
        else:
            break
    image_screen_size = wiking.cms.cfg.image_screen_size
    image_thumbnail_sizes = wiking.cms.cfg.image_thumbnail_sizes
    transaction = pd.transaction()
    data.select(transaction=transaction)
    try:
        while True:
            row = data.fetchone()
            if row is None:
                break
            ext = os.path.splitext(row['filename'].value())[1].lower()
            path = os.path.join(wiking.cms.cfg.storage, pytis.config.dbname, 'attachments',
                                row['attachment_id'].export() + (ext or '.'))
            attachment = open(path, 'rb')
            try:
                image = PIL.Image.open(attachment)
            except IOError as e:
                continue
            sys.stderr.write("Resizing %s (%dx%d): " %
                             (row['filename'].value(), image.size[0], image.size[1]))
            thumbnail_size = row['thumbnail_size'].value()
            if thumbnail_size is None:
                thumbnail_value, real_thumbnail_size = None, (None, None)
            else:
                if thumbnail_size == 'small':
                    size = image_thumbnail_sizes[0]
                elif thumbnail_size == 'medium':
                    size = image_thumbnail_sizes[1]
                else:
                    size = image_thumbnail_sizes[2]
                thumbnail_value, real_thumbnail_size = resize(image, (size, size))
                sys.stderr.write("%dx%d, " % real_thumbnail_size)
            resized_image_value, resized_image_size = resize(image, image_screen_size)
            sys.stderr.write("%dx%d\n" % resized_image_size)
            values = dict(
                width=image.size[0],
                height=image.size[1],
                thumbnail=thumbnail_value,
                thumbnail_width=real_thumbnail_size[0],
                thumbnail_height=real_thumbnail_size[1],
                image=resized_image_value,
                image_width=resized_image_size[0],
                image_height=resized_image_size[1],
            )
            r = pd.Row([(key, pd.Value(row[key].type(), value)) for key, value in values.items()])
            data.update(row['attachment_id'], r, transaction=transaction)
    except Exception:
        try:
            transaction.rollback()
        except Exception:
            pass
        sys.stderr.write("Transaction rolled back.\n")
        raise
    else:
        sys.stderr.write("Transaction commited.\n")
        transaction.commit()
    transaction.close()
예제 #17
0
    def _reload_actions(self, record):
        import wiking

        def action_descr(module, action):
            if issubclass(module, wiking.PytisModule):
                for a in module.Spec.actions:
                    if a.name() == action:
                        return a.descr() or a.title()
            try:
                return dict(self._DEFAULT_ACTIONS)[action]
            except KeyError:
                method = getattr(module, 'action_' + action)
                docstring = method.__doc__
                return docstring and docstring.splitlines()[0] or _(
                    "Neuvedeno")

        module = self._module(record['modname'].value())
        if module:
            from pytis.form import run_dialog, CheckListDialog, create_data_object
            data = create_data_object(self._spec_name('Actions'))
            data.select(condition=pd.EQ('mod_id', record['mod_id']))
            existing_actions = {}
            while True:
                row = data.fetchone()
                if row is None:
                    break
                else:
                    existing_actions[row['name'].value()] = row['action_id']
            data.close()
            actions = [
                attr[7:] for attr in dir(module) if attr.startswith('action_')
                and isinstance(getattr(module, attr), collections.Callable)
            ]
            default_actions = [a[0] for a in self._DEFAULT_ACTIONS]
            # Order default actions first and in the order of self._DEFAULT_ACTIONS.
            order = lambda a: a in default_actions and (default_actions.index(
                a) + 1) or a
            actions.sort(lambda a, b: cmp(order(a), order(b)))
            descriptions = [action_descr(module, action) for action in actions]
            result = run_dialog(
                CheckListDialog,
                title=_("Nalezené akce"),
                message=_("Zaškrtněte akce, které chcete zpřístupnit webovým "
                          "uživatelům:"),
                items=zip([a in existing_actions for a in actions], actions,
                          descriptions),
                columns=(_("Action"), _("Description")))
            if result is not None:
                # TODO: Use a transaction.  Respect existing actions.
                for i, action in enumerate(actions):
                    if result[i]:
                        description_value = pd.Value(pd.String(),
                                                     descriptions[i] or None)
                        try:
                            key = existing_actions[action]
                        except KeyError:
                            rowdata = [('mod_id', record['mod_id']),
                                       ('name', pd.Value(pd.String(), action)),
                                       ('description', description_value)]
                            data.insert(pd.Row(rowdata))
                        else:
                            data.update(
                                (key, ),
                                pd.Row((('description', description_value), )))
예제 #18
0
 def _values(self, data, **kwargs):
     return [(k, pd.Value(data.find_column(k).type(), v)) for k, v in kwargs.items()]
예제 #19
0
파일: misc.py 프로젝트: cerha/pytis
 def _country_filter(self, row, filter, switch):
     """Return the validity condition as pd.Operator instance."""
     cond = pd.WM('name', pd.WMValue(pd.String(), filter or '*'))
     if switch:
         cond = pd.AND(cond, pd.EQ('continent', pd.Value(pd.String(), 'EU')))
     return cond
예제 #20
0
파일: test.py 프로젝트: cerha/pytis
def test_hidden(row, field, context, value, exported):
    row[field.id] = pd.Value(field.type, value)
    result = context.localize(field.hidden(context))
    expected = ''.join('<input name="{}" type="hidden" value={}/>'.format(
        field.id, saxutils.quoteattr(v)) for v in pytis.util.xtuple(exported))
    assert result == expected
예제 #21
0
파일: web.py 프로젝트: nicLucian/pytis
 def close(self, req, user, session_key):
     # This deletion will lead to end_time in cms_session_log_data being set to last_access
     # value of the deleted row.  Use delete_many() because we don't know session_id.
     self._data.delete_many(
         pd.AND(pd.EQ('uid', pd.Value(pd.Integer(), user.uid())),
                pd.EQ('session_key', pd.Value(pd.DateTime(), session_key))))
예제 #22
0
 def _parent_filter(self, record, lang):
     return pd.EQ('lang', pd.Value(pd.String(), lang))
예제 #23
0
 def _country_filter(self, row, continent):
     if continent:
         return pd.EQ('continent',
                      pd.Value(pd.String(), continent.upper()))
     else:
         return None