Example #1
0
    def __init__(self, id, **options):
        # store options if not already stored by a sub-class
        self.store_options(options)

        # field integer options
        self.size = KIntValue(value=self.get_option("size"), allow_none=True).value

        # Min and max length of text
        self.min_length = KIntValue(value=self.get_option("min_length"), allow_none=True).value
        self.max_length = KIntValue(value=self.get_option("max_length"), allow_none=True).value

        # If set: checks if the same value as the field referenced
        # Mostly used for password verification
        self.verification_field_id = KValue(value=self.get_option("verification_field_id"), allow_none=True).value

        # super!
        super(TextField, self).__init__(id, **options)

        kdebug.debug(1, "allow none: %s, required: %s" % ( str((not self.required)), str(self.required) ), "kweb_forms" )

        self._data = KStringValue(value=self.get_option("value"),
                                    allow_none=(not self.required), raise_on_exception=False,
                                    min_length=self.min_length, max_length=self.max_length,
                                    pre_filter_callables=[filter_none_to_empty_str] + self.pre_filter_callables,
                                    post_filter_callables=self.post_filter_callables)
Example #2
0
    def filter(self, value):
        kdebug.debug(
            1, "KStringValue.filter: value='%s', type='%s'" %
            (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if not isinstance(value, basestring):
            fresult.validation_exceptions.append(
                ValidationTypeException(expected_type=str(str),
                                        type=str(type(value))))
        else:
            if self._min_length and self._min_length and len(
                    value) < self._min_length:
                fresult.validation_exceptions.append(
                    ValidationStringTooShortException(
                        min_length=self._min_length, length=len(value)))
            if self._max_length and self._max_length and len(
                    value) > self._max_length:
                fresult.validation_exceptions.append(
                    ValidationStringTooLongException(
                        max_length=self._max_length, length=len(value)))

        kdebug.debug(
            2, "KStringValue.filter: filter_result='%s'" % (str(fresult)),
            "kvalues")

        return fresult
Example #3
0
    def get_value(self):
        # output debug info
        kdebug.debug(3, "_get_value: value='%s'" % (str(self._value)),
                     "kvalues")

        # return current value
        return self._value
Example #4
0
    def filter_choices(self, value):
        kdebug.debug(4, "filter_choices: input value='%s'" % ( str(value) ), "kweb_forms" )

        if not value in self.choices.keys():
            return FilterResult(value=value, validation_exceptions=[ValidationInvalidChoiceException()], continue_filtering=False)

        return FilterResult(value=value)
def get_html_escaped_string(strings,
                            key,
                            app=None,
                            none_if_missing=False,
                            allow_basic_html=False):
    kdebug.debug(1, "set_strings(key='%s', app='%s', none_if_missing='%s', allow_basic_html='%s'" % \
        ( key, str(app), str(none_if_missing), str(allow_basic_html) ), "kweb_getstrings" )

    # get the string
    tmpstr = kgetstrings.get_string(strings,
                                    key,
                                    app=app,
                                    none_if_missing=none_if_missing)
    if not tmpstr:
        return None

    # escape basic forbidden html characters (not entities)
    tmpstr = kweb_lib.html_text_escape(tmpstr)

    if allow_basic_html:
        # unescape some html tags that we allow in strings
        tmpstr = re.sub(
            '&lt;nbsp&gt;', "&nbsp;", tmpstr
        )  # special case -- convert <nbsp> (not a real tag) to &nbsp;
        tmpstr = re.sub(
            '&lt;(\/?)(p|b|i)&gt;', "<\\1\\2>",
            tmpstr)  # convert back <p>, </p>, <b>, </b>,  <i>, </i>

    return tmpstr
Example #6
0
    def filter(self, value):
        kdebug.debug(
            1, "KIntValue.filter: value='%s', type='%s'" %
            (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if type(value) != int:
            fresult.validation_exceptions.append(
                ValidationTypeException(expected_type=str(int),
                                        type=str(type(value))))
        else:
            if self._min_value and int(value) < int(self._min_value):
                fresult.validation_exceptions.append(
                    ValidationIntTooLowException(min_value=self._min_value,
                                                 value=value))
            if self._max_value and int(value) > int(self._max_value):
                fresult.validation_exceptions.append(
                    ValidationIntTooHighException(max_value=self._max_value,
                                                  value=value))

        kdebug.debug(2,
                     "KIntValue.filter: filter_result='%s'" % (str(fresult)),
                     "kvalues")

        return fresult
Example #7
0
    def filter(self, value):
        kdebug.debug(
            1, "KStringListValue.filter: value='%s', type='%s'" %
            (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if type(value) != dict:
            fresult.validation_exceptions.append(
                ValidationTypeException(expected_type="string dict",
                                        type=str(type(value))))
        else:
            for k, v in value.items():
                if not isinstance(type(k), basestring) or not isinstance(
                        type(v), basestring):
                    fresult.validation_exceptions.append(
                        ValidationTypeException(expected_type="string dict",
                                                type=str(type(value))))
                    break

        kdebug.debug(
            2, "KStringListValue.filter: filter_result='%s'" % (str(fresult)),
            "kvalues")

        return fresult
Example #8
0
def authenticate():
    global server_sid

    kdebug.debug(
        3, "Authenticating with user '%s', password '%s'." %
        (server_login, server_password))
    server_sid = server.session_login(server_login, server_password)
    kdebug.debug(2, "Session ID: %s" % (server_sid))
Example #9
0
 def get_db_conn(self):
     kdebug.debug(2, "Connecting to %s:%i, database %s, user %s, pass %s" % \
         ( self.db_host, self.db_port, self.db_database, self.db_user, self.db_pass ) )
     conn = PgSQL.connect(host=self.db_host, port=self.db_port, database=self.db_database,
         user=self.db_user, password=self.db_pass)
     kdebug.debug(1, "Connecting to %s:%i, database %s, user %s, pass %s" % \
         ( self.db_host, self.db_port, self.db_database, self.db_user, self.db_pass ) )
     return conn
Example #10
0
def test_keys():
    main_key_id = server.get_main_key_id(server_sid)
    assert str(main_key_id).isdigit()
    kdebug.debug(3, "Main key ID: %s" % (main_key_id))

    key_id = server.get_key_id(server_sid)
    assert str(key_id).isdigit()
    kdebug.debug(3, "Key ID: %s" % (key_id))
def test_keys():
    main_key_id = server.get_main_key_id(server_sid)
    assert str(main_key_id).isdigit()
    kdebug.debug(3, "Main key ID: %s" % ( main_key_id ))

    key_id = server.get_key_id(server_sid)
    assert str(key_id).isdigit()
    kdebug.debug(3, "Key ID: %s" % ( key_id ))
Example #12
0
    def filter_choices(self, value):
        kdebug.debug(4, "filter_choices: input value='%s'" % (str(value)),
                     "kweb_forms")

        if not value in self.choices.keys():
            return FilterResult(
                value=value,
                validation_exceptions=[ValidationInvalidChoiceException()],
                continue_filtering=False)

        return FilterResult(value=value)
Example #13
0
def get_string(strings, key, app=None, none_if_missing=False):
    kdebug.debug(1, "set_strings(key='%s', app='%s', none_if_missing='%s'" % \
        ( key, str(app), str(none_if_missing) ), "kgetstrings" )

    if strings and strings.has_key(app) and strings[app].has_key(key):
        return strings[app][key]

    if none_if_missing == True:
        return None

    return "MISSING:" + key
Example #14
0
def get_string(strings, key, app=None, none_if_missing=False):
    kdebug.debug(1, "set_strings(key='%s', app='%s', none_if_missing='%s'" % \
        ( key, str(app), str(none_if_missing) ), "kgetstrings" )

    if strings and strings.has_key(app) and strings[app].has_key(key):
        return strings[app][key]
        
    if none_if_missing == True:
        return None

    return "MISSING:"+key
Example #15
0
 def get_db_conn(self):
     kdebug.debug(2, "Connecting to %s:%i, database %s, user %s, pass %s" % \
         ( self.db_host, self.db_port, self.db_database, self.db_user, self.db_pass ) )
     conn = PgSQL.connect(host=self.db_host,
                          port=self.db_port,
                          database=self.db_database,
                          user=self.db_user,
                          password=self.db_pass)
     kdebug.debug(1, "Connecting to %s:%i, database %s, user %s, pass %s" % \
         ( self.db_host, self.db_port, self.db_database, self.db_user, self.db_pass ) )
     return conn
Example #16
0
    def html_output(self):
       s = '<select id=%s name=%s%s>\n' % \
                ( html_attribute_escape(self.fid_html), html_attribute_escape(self.id), self._attributes_string() )
       for k, v in self.choices.items():
           kdebug.debug(1, "DEBUG: '%s' -- '%s'" % ( str(self._data.value), str(k) ), "kweb_forms" )
           if str(self._data.value) == str(k):
               s += '<option value=%s selected>%s</option>\n' % ( html_attribute_escape(k), html_text_escape(v) )
           else:
               s += '<option value=%s>%s</option>\n' % ( html_attribute_escape(k), html_text_escape(v) )

       s += "</option>\n"
       return s
Example #17
0
    def __init__(self, id, **options):
        self.hidden = False
        self.filled = False
        self.validation_exceptions = []

        # store options if not already stored by a sub-class
        self.store_options(options)

        # Field ID - string list
        self.id = KStringValue(value=id, allow_none=False).value
        #self.id_str = recursive_string_list_to_string(self.id)

        # needed for debug (__str__)
        self._data = None

        kdebug.debug(3, "New instance of class '%s'" % ( str(self.__class__.__name__) ), "kweb_forms" )

        # FIXME - choose a better name, ...
        # Form.each_field behaves differently if counts is true or false
        self.counts = True

        # store options temporarily
        self.options = options

        # form id
        self.form_id = KStringValue(value=self.get_option("form_id", default_value="")).value

        # filters
        self.pre_filter_callables = self.get_option("pre_filter_callables", default_value=[])
        self.post_filter_callables = self.get_option("post_filter_callables", default_value=[])

        # field boolean options
        self.required = KBoolValue(value=self.get_option("required", default_value=False)).value
        self.force_value = KBoolValue(value=self.get_option("force_value", default_value=False)).value
        self.enabled = KBoolValue(value=self.get_option("enabled", default_value=True)).value
        self.autofocus = KBoolValue(value=self.get_option("autofocus", default_value=False)).value

        # Field reference (any type) - reference to anything
        self.reference = KStringValue(value=self.get_option("reference"), allow_none=False).value

        # Field classe(s) (string or list of strings)
        self.classes = KStringListValue(value=self.get_option("classes"), allow_none=True).value
        
        # Field tags (ordered dict of key/values)
        self.other_attributes = KStringDictValue(value=self.get_option("other_attributes"), allow_none=True).value

        self._data = KValue(value=self.get_option("value"),
                                    allow_none=(not self.required), raise_on_exception=False,
                                    pre_filter_callables=self.pre_filter_callables,
                                    post_filter_callables=self.post_filter_callables)
Example #18
0
def connect(url):
    global server

    try:
        kdebug.debug(2, "Connecting to url '%s'." % (url))
        server = xmlrpclib.ServerProxy(url)
        kdebug.debug(1, "Connected to url '%s'." % (url))

    except xmlrpclib.ProtocolError, e:
        print "A protocol error occurred:"
        print "URL: %s" % e.url
        print "HTTP/HTTPS headers: %s" % e.headers
        print "Error code: %d" % e.errcode
        print "Error message: %s" % e.errmsg
        sys.exit(1)
def connect(url):
    global server

    try:
        kdebug.debug(2, "Connecting to url '%s'." % ( url ) )
        server = xmlrpclib.ServerProxy(url)
        kdebug.debug(1, "Connected to url '%s'." % ( url ) )
        
    except xmlrpclib.ProtocolError, e:
        print "A protocol error occurred:"
        print "URL: %s" % e.url
        print "HTTP/HTTPS headers: %s" % e.headers
        print "Error code: %d" % e.errcode
        print "Error message: %s" % e.errmsg
        sys.exit(1)
Example #20
0
    def html_output(self):
        s = '<select id=%s name=%s%s>\n' % \
                 ( html_attribute_escape(self.fid_html), html_attribute_escape(self.id), self._attributes_string() )
        for k, v in self.choices.items():
            kdebug.debug(
                1, "DEBUG: '%s' -- '%s'" % (str(self._data.value), str(k)),
                "kweb_forms")
            if str(self._data.value) == str(k):
                s += '<option value=%s selected>%s</option>\n' % (
                    html_attribute_escape(k), html_text_escape(v))
            else:
                s += '<option value=%s>%s</option>\n' % (
                    html_attribute_escape(k), html_text_escape(v))

        s += "</option>\n"
        return s
Example #21
0
    def handle_reinvite(self, opts, args):
        # Arguments
        email = args[0]

        # Options
        dry_run_flag = 0
        for opt, value in opts:
            if opt == "-d" or opt == "--dry-run": dry_run_flag = 1

        # Connect to the KCD database.
        self.conn = self.get_db_conn()

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object())
        c.connect()
        c.select_role(kanp.KANP_KCD_ROLE_WORKSPACE)
        kdebug.debug(1, "Instantiated a KCD client.")

        # Get the list of workspaces.
        kws_list = []
        query = (
            "SELECT kws_id FROM kcd_kws_users WHERE lower(email)=lower(%s) AND (bool(flags & %i = 0)) "
            "ORDER BY kws_id") % (escape_pg_string(email),
                                  kanp.KANP_USER_FLAG_BAN)
        cur = exec_pg_query(self.conn, query)
        for row in cur.fetchall():
            kws_list.append(row[0])
        cur.close()

        # Invite the user.
        for kws_id in kws_list:
            self.stdout.write("Reinviting user %s to workspace %i.\n" %
                              (email, kws_id))
            if dry_run_flag: continue

            # Log in the workspace.
            c.connect_workspace(workspace_id=kws_id,
                                email_id="kwmo",
                                password=c.conf.kcd_passwd)

            # Send the invitation.
            msg = "This email was sent automatically to give you access to your Teambox.\n"
            wi = WorkspaceInvitee(email_address=email, send_mail=1)
            c.send_invitation(kws_id, msg, [wi])
            if wi.error != "": raise Exception(wi.error)
def get_html_escaped_string(strings, key, app=None, none_if_missing=False, allow_basic_html=False):
    kdebug.debug(1, "set_strings(key='%s', app='%s', none_if_missing='%s', allow_basic_html='%s'" % \
        ( key, str(app), str(none_if_missing), str(allow_basic_html) ), "kweb_getstrings" )

    # get the string
    tmpstr = kgetstrings.get_string(strings, key, app=app, none_if_missing=none_if_missing)
    if not tmpstr:
        return None

    # escape basic forbidden html characters (not entities)
    tmpstr = kweb_lib.html_text_escape(tmpstr)

    if allow_basic_html:
        # unescape some html tags that we allow in strings
        tmpstr = re.sub('&lt;nbsp&gt;', "&nbsp;", tmpstr) # special case -- convert <nbsp> (not a real tag) to &nbsp;
        tmpstr = re.sub('&lt;(\/?)(p|b|i)&gt;', "<\\1\\2>", tmpstr) # convert back <p>, </p>, <b>, </b>,  <i>, </i>

    return tmpstr
Example #23
0
    def handle_rm(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.inode_id = long(args[1])
        self.commit_id = long(args[2])

        # Options
        self.type = 'f'
        self.user_id = 1
        self.share_id = 0
        self.email_id = 0
        for opt, value in opts:
            if opt == "-t" or opt == "--type":
                self.type = value
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-e" or opt == "--email_id":
                self.email_id = value

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object())
        kdebug.debug(1, "Instantiated a KCD client.")

        # Build list of entries (only one entry supported for now).
        entries_list = []
        if self.type == 'd':
            entry = kfs_lib.KFSOpDirDelete(self.inode_id, self.commit_id)
        elif self.type == 'f':
            entry = kfs_lib.KFSOpFileDelete(self.inode_id, self.commit_id)
        else:
            raise Exception("Bad entry type.")
        entries_list = [entry]

        # Delete entries.
        c.kfs_delete_entries(self.kws_id, self.share_id, self.user_id,
                             self.email_id, entries_list)
Example #24
0
    def filter(self, value):
        kdebug.debug(1, "KStringListValue.filter: value='%s', type='%s'" % (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if type(value) != dict:
            fresult.validation_exceptions.append(
                ValidationTypeException(expected_type="string dict", type=str(type(value)))
            )
        else:
            for k, v in value.items():
                if not isinstance(type(k), basestring) or not isinstance(type(v), basestring):
                    fresult.validation_exceptions.append(
                        ValidationTypeException(expected_type="string dict", type=str(type(value)))
                    )
                    break

        kdebug.debug(2, "KStringListValue.filter: filter_result='%s'" % (str(fresult)), "kvalues")

        return fresult
Example #25
0
    def filter(self, value):
        kdebug.debug(1, "KIntValue.filter: value='%s', type='%s'" % (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if type(value) != int:
            fresult.validation_exceptions.append(ValidationTypeException(expected_type=str(int), type=str(type(value))))
        else:
            if self._min_value and int(value) < int(self._min_value):
                fresult.validation_exceptions.append(
                    ValidationIntTooLowException(min_value=self._min_value, value=value)
                )
            if self._max_value and int(value) > int(self._max_value):
                fresult.validation_exceptions.append(
                    ValidationIntTooHighException(max_value=self._max_value, value=value)
                )

        kdebug.debug(2, "KIntValue.filter: filter_result='%s'" % (str(fresult)), "kvalues")

        return fresult
Example #26
0
    def filter(self, value):
        kdebug.debug(1, "KStringValue.filter: value='%s', type='%s'" % (str(value), type(value)), "kvalues")

        fresult = kfilter.FilterResult(value=value)

        if not isinstance(value, basestring):
            fresult.validation_exceptions.append(ValidationTypeException(expected_type=str(str), type=str(type(value))))
        else:
            if self._min_length and self._min_length and len(value) < self._min_length:
                fresult.validation_exceptions.append(
                    ValidationStringTooShortException(min_length=self._min_length, length=len(value))
                )
            if self._max_length and self._max_length and len(value) > self._max_length:
                fresult.validation_exceptions.append(
                    ValidationStringTooLongException(max_length=self._max_length, length=len(value))
                )

        kdebug.debug(2, "KStringValue.filter: filter_result='%s'" % (str(fresult)), "kvalues")

        return fresult
Example #27
0
    def handle_rm(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.inode_id = long(args[1])
        self.commit_id = long(args[2])
        
        # Options
    	self.type = 'f'
        self.user_id = 1
        self.share_id = 0
        self.email_id = 0
        for opt, value in opts:
            if opt == "-t" or opt == "--type":
                self.type = value
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-e" or opt == "--email_id":
                self.email_id = value
 
        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object())
        kdebug.debug(1, "Instantiated a KCD client.")

        # Build list of entries (only one entry supported for now).
        entries_list = []
        if self.type == 'd':
            entry = kfs_lib.KFSOpDirDelete(self.inode_id, self.commit_id)
        elif self.type == 'f':
            entry = kfs_lib.KFSOpFileDelete(self.inode_id, self.commit_id)
        else:
            raise Exception("Bad entry type.")
        entries_list = [entry]

        # Delete entries.
        c.kfs_delete_entries(self.kws_id, self.share_id, self.user_id, self.email_id, entries_list)  
Example #28
0
    def handle_reinvite(self, opts, args):
        # Arguments
        email = args[0]
        
        # Options
        dry_run_flag = 0
        for opt, value in opts:
            if opt == "-d" or opt == "--dry-run": dry_run_flag = 1
 
        # Connect to the KCD database.
        self.conn = self.get_db_conn()
        
        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object())
        c.connect()
        c.select_role(kanp.KANP_KCD_ROLE_WORKSPACE)
        kdebug.debug(1, "Instantiated a KCD client.")
        
        # Get the list of workspaces.
        kws_list = []
        query = ("SELECT kws_id FROM kcd_kws_users WHERE lower(email)=lower(%s) AND (bool(flags & %i = 0)) "
                 "ORDER BY kws_id") % (escape_pg_string(email), kanp.KANP_USER_FLAG_BAN)
        cur = exec_pg_query(self.conn, query)
        for row in cur.fetchall(): kws_list.append(row[0])
        cur.close()
        
        # Invite the user.
        for kws_id in kws_list:
            self.stdout.write("Reinviting user %s to workspace %i.\n" % (email, kws_id))
            if dry_run_flag: continue
            
            # Log in the workspace.
            c.connect_workspace(workspace_id=kws_id, email_id="kwmo", password=c.conf.kcd_passwd)
            
            # Send the invitation.
            msg = "This email was sent automatically to give you access to your Teambox.\n"
            wi = WorkspaceInvitee(email_address=email, send_mail=1)
            c.send_invitation(kws_id, msg, [ wi ])
            if wi.error != "": raise Exception(wi.error)
Example #29
0
    def fill(self, input_values):
        self.filled = True
        for field in self.fields.values():
            if isinstance(field, RadioButtonField):
                kdebug.debug(
                    4, "Filling RadioButtonField field '%s' with values '%s'" %
                    (field.id, input_values), "kweb_forms")
                field.fill(input_values)
            else:
                if input_values.has_key(field.reference):
                    kdebug.debug(
                        4, "Filling field '%s' with value '%s'" %
                        (field.id, input_values[field.reference]),
                        "kweb_forms")
                    field.fill(input_values[field.reference])
                else:
                    kdebug.debug(
                        4, "Filling field '%s' with None (not sent)." %
                        (field.id), "kweb_forms")
                    field.fill(None)

            if isinstance(field, TextField) and field.verification_field_id:
                if self.fields[
                        field.verification_field_id].value != field.value:
                    field.add_validation_exception(
                        ValidationVerificationFieldException())
Example #30
0
def ksession_get_session(db_name, db_host, db_port, db_user, db_pwd,
                         sid=None, create_as_needed=1):

    # Open the session connection if required.
    ksession_open_pg_conn(db_name = db_name, db_host = db_host,
                          db_port = db_port, db_user = db_user,
                          db_pwd = db_pwd)
    
    # Create the session object.
    s = KSession(ksession_pg_conn)
    
    # The session possibly exists. Try to load it.
    if sid != None:
        if s.load(sid):
            kdebug.debug(2, "Session with ID %s loaded successfully." % (sid), "ksession")
            return s
            
        else:
            kdebug.debug(2, "Session with ID %s was not found in database." % (sid), "ksession")
     
    # We would have to create a new session, but we're not allowed to.
    if not create_as_needed: raise Exception("the user session does not exist")
    
    # Save and return the session.
    s.save()
    kdebug.debug(2, "Created new session with ID %s." % (s.sid), "ksession")
    return s
Example #31
0
    def set_value(self, value):
        # output debug info
        kdebug.debug(3, "_set_value: value='%s'" % (str(value)), "kvalues")

        # Unmodified value
        self.raw_value = value
        self.validation_exceptions = []

        # Make filters list
        filters = []

        if self._pre_filter_callables:
            # Custom pre-filters
            filters += self._pre_filter_callables

        if self._allow_none == True and value == None:
            # None value allowed... value is None... bypass other filters
            pass

        else:
            if self._allow_none == False:
                # None value not allowed... use a special filter for that
                filters += [kfilter.filter_not_none]

            # Class filter
            filters += [self.filter]

            if self._post_filter_callables:
                # Custom post-filters
                filters += self._post_filter_callables

        kdebug.debug(4, "_set_value: filters='%s'" % (str(filters)), "kvalues")

        # Run filters
        kdebug.debug(4, "_set_value: calling run_filters", "kvalues")
        fresult = kfilter.run_filters(value, filters)
        kdebug.debug(4, "_set_value: filter_result='%s'" % (str(fresult)),
                     "kvalues")

        # raise the first exception if exceptions and raise_on_exception
        if self._raise_on_exception != False:
            if len(fresult.validation_exceptions):
                raise fresult.validation_exceptions[0]

        # Final value assignment
        self._value = fresult.value
        self.validation_exceptions = list(
            fresult.validation_exceptions
        )  # TEST - make a copy instead of assigning
Example #32
0
 def localize_validation_exceptions(self, d):
     kdebug.debug(5, "Localizing messages for validation exceptions.", "kweb_forms" )
     for e in self.validation_exceptions:
         if d.has_key(e.classname()):
             e.message = d[e.classname()]
             kdebug.debug(6, "Found message id for for exception class '%s: '%s'." % ( e.classname(), d[e.classname()] ), "kweb_forms" )
         else:
             kdebug.debug(6, "Could not find local message for exception class '%s'." % ( e.classname() ), "kweb_forms" )
Example #33
0
    def __init__(self, id, **options):
        # store options if not already stored by a sub-class
        self.store_options(options)

        # field integer options
        self.size = KIntValue(value=self.get_option("size"),
                              allow_none=True).value

        # Min and max length of text
        self.min_length = KIntValue(value=self.get_option("min_length"),
                                    allow_none=True).value
        self.max_length = KIntValue(value=self.get_option("max_length"),
                                    allow_none=True).value

        # If set: checks if the same value as the field referenced
        # Mostly used for password verification
        self.verification_field_id = KValue(
            value=self.get_option("verification_field_id"),
            allow_none=True).value

        # super!
        super(TextField, self).__init__(id, **options)

        kdebug.debug(
            1, "allow none: %s, required: %s" % (str(
                (not self.required)), str(self.required)), "kweb_forms")

        self._data = KStringValue(
            value=self.get_option("value"),
            allow_none=(not self.required),
            raise_on_exception=False,
            min_length=self.min_length,
            max_length=self.max_length,
            pre_filter_callables=[filter_none_to_empty_str] +
            self.pre_filter_callables,
            post_filter_callables=self.post_filter_callables)
Example #34
0
    def set_value(self, value):
        # output debug info
        kdebug.debug(3, "_set_value: value='%s'" % (str(value)), "kvalues")

        # Unmodified value
        self.raw_value = value
        self.validation_exceptions = []

        # Make filters list
        filters = []

        if self._pre_filter_callables:
            # Custom pre-filters
            filters += self._pre_filter_callables

        if self._allow_none == True and value == None:
            # None value allowed... value is None... bypass other filters
            pass

        else:
            if self._allow_none == False:
                # None value not allowed... use a special filter for that
                filters += [kfilter.filter_not_none]

            # Class filter
            filters += [self.filter]

            if self._post_filter_callables:
                # Custom post-filters
                filters += self._post_filter_callables

        kdebug.debug(4, "_set_value: filters='%s'" % (str(filters)), "kvalues")

        # Run filters
        kdebug.debug(4, "_set_value: calling run_filters", "kvalues")
        fresult = kfilter.run_filters(value, filters)
        kdebug.debug(4, "_set_value: filter_result='%s'" % (str(fresult)), "kvalues")

        # raise the first exception if exceptions and raise_on_exception
        if self._raise_on_exception != False:
            if len(fresult.validation_exceptions):
                raise fresult.validation_exceptions[0]

        # Final value assignment
        self._value = fresult.value
        self.validation_exceptions = list(fresult.validation_exceptions)  # TEST - make a copy instead of assigning
Example #35
0
 def localize_validation_exceptions(self, d):
     kdebug.debug(5, "Localizing messages for validation exceptions.",
                  "kweb_forms")
     for e in self.validation_exceptions:
         if d.has_key(e.classname()):
             e.message = d[e.classname()]
             kdebug.debug(
                 6, "Found message id for for exception class '%s: '%s'." %
                 (e.classname(), d[e.classname()]), "kweb_forms")
         else:
             kdebug.debug(
                 6,
                 "Could not find local message for exception class '%s'." %
                 (e.classname()), "kweb_forms")
Example #36
0
def ksession_open_pg_conn(db_name, db_host, db_port, db_user, db_pwd):
    global ksession_pg_conn
    
    # There is a cached connection open. Test if it works.
    if ksession_pg_conn != None:
        try:
            if ksession_pg_conn.inTransaction:
                kdebug.debug(1, "Cached session connection not clean... rolling previous transaction back.", "ksession")
                ksession_pg_conn.rollback()
            exec_pg_query_rb_on_except(ksession_pg_conn, "SELECT 1")
            ksession_pg_conn.rollback()
            kdebug.debug(2, "Cached session connection operational.", "ksession")
            return
        except Exception, e:
            kdebug.debug(2, "Cached session connection does not work, reopening.", "ksession")
            ksession_pg_conn = None
Example #37
0
    def fill(self, input_values):
        self.filled = True
        for field in self.fields.values():
            if isinstance(field, RadioButtonField):
                kdebug.debug(4, "Filling RadioButtonField field '%s' with values '%s'" % ( field.id, input_values ), 
		    "kweb_forms" )
                field.fill(input_values)
            else:
                if input_values.has_key(field.reference):
                    kdebug.debug(4, "Filling field '%s' with value '%s'" % ( field.id, input_values[field.reference] ), 
			"kweb_forms" )
                    field.fill(input_values[field.reference])
                else:
                    kdebug.debug(4, "Filling field '%s' with None (not sent)." % ( field.id ), "kweb_forms" )
                    field.fill(None)

            if isinstance(field, TextField) and field.verification_field_id:
                if self.fields[field.verification_field_id].value != field.value:
                    field.add_validation_exception(
			ValidationVerificationFieldException())
Example #38
0
def ksession_open_pg_conn(db_name, db_host, db_port, db_user, db_pwd):
    global ksession_pg_conn

    # There is a cached connection open. Test if it works.
    if ksession_pg_conn != None:
        try:
            if ksession_pg_conn.inTransaction:
                kdebug.debug(
                    1,
                    "Cached session connection not clean... rolling previous transaction back.",
                    "ksession")
                ksession_pg_conn.rollback()
            exec_pg_query_rb_on_except(ksession_pg_conn, "SELECT 1")
            ksession_pg_conn.rollback()
            kdebug.debug(2, "Cached session connection operational.",
                         "ksession")
            return
        except Exception, e:
            kdebug.debug(
                2, "Cached session connection does not work, reopening.",
                "ksession")
            ksession_pg_conn = None
Example #39
0
def ksession_get_session(db_name,
                         db_host,
                         db_port,
                         db_user,
                         db_pwd,
                         sid=None,
                         create_as_needed=1):

    # Open the session connection if required.
    ksession_open_pg_conn(db_name=db_name,
                          db_host=db_host,
                          db_port=db_port,
                          db_user=db_user,
                          db_pwd=db_pwd)

    # Create the session object.
    s = KSession(ksession_pg_conn)

    # The session possibly exists. Try to load it.
    if sid != None:
        if s.load(sid):
            kdebug.debug(2, "Session with ID %s loaded successfully." % (sid),
                         "ksession")
            return s

        else:
            kdebug.debug(
                2, "Session with ID %s was not found in database." % (sid),
                "ksession")

    # We would have to create a new session, but we're not allowed to.
    if not create_as_needed: raise Exception("the user session does not exist")

    # Save and return the session.
    s.save()
    kdebug.debug(2, "Created new session with ID %s." % (s.sid), "ksession")
    return s
def authenticate():
    global server_sid

    kdebug.debug(3, "Authenticating with user '%s', password '%s'." % ( server_login, server_password ) )
    server_sid = server.session_login(server_login, server_password)
    kdebug.debug(2, "Session ID: %s" % ( server_sid ))
Example #41
0
    def handle_upload(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.file = args[1]
        
        # Options
        self.user_id = 1
        self.share_id = 0
        self.upload_file_as = os.path.basename(self.file)
        for opt, value in opts:
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-a" or opt == "--upload_file_as":
                self.upload_file_as = value
 
        # Connect to the KCD database.
        self.conn = self.get_db_conn()

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object(), db_conn=self.conn)
        kdebug.debug(1, "Instantiated a KCD client.")

        # Prepare file list.       
        files = []
        file = kfs_lib.KFSUploadFile()
        file.kfs_op = kanp.KANP_KFS_OP_CREATE_FILE
        file.parent_inode = 0
        file.parent_commit_id = 0
        file.name = self.upload_file_as
        fd = os.open(self.file, os.O_RDONLY)
        file.set_from_fd(fd)
        files.append(file)

        # Connecting to KCD.
        kdebug.debug(2, "Connecting to KCD.")
        c.connect()
        kdebug.debug(1, "Connected to KCD.")

        # Selecting KFS role.
        kdebug.debug(2, "Selecting KFS role.")
        c.select_role(kanp.KANP_KCD_ROLE_FILE_XFER)
        kdebug.debug(1, "Selected KFS role.")

        # Uploading file(s).
        kdebug.debug(2, "Uploading file(s) to kcd %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )
        c.kfs_upload(self.kws_id, self.share_id, self.user_id, files)
        kdebug.debug(1, "Uploaded file(s) to kcd %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )

        # Errors?
        i = -1
        for file in files:
            i += 1
            if file.kfs_error:
                print "File %i could not be uploaded: '%s'." % ( i, file.kfs_error )

        # Close  KCD connection.
        c.close()
def assert_fault_xmlrpc(func_name, fault_codes, *params):
    try:
        value = getattr(server, func_name)(*params)
        raise ExceptionReturn(value,
            "ERROR: func: '%s', params:'%s': succeded.. shoud have failed with code(s) %s" % \
            ( str(func_name), str(*params), str(fault_codes) ) )

    except xmlrpclib.Fault, e:
        if (len(fault_codes) == 1 and fault_codes != e.faultCode) or not e.faultCode in fault_codes:
            raise Exception(
                "ERROR: func: '%s', params: '%s': expected fault(s) '%s', got fault %i, string '%s'." % \
                ( str(func_name), str(params), str(fault_codes), e.faultCode, e.faultString) )

    kdebug.debug(1, 
        "Suceeded: func '%s', params '%s': failed like expected with one of code(s) '%s'." \
            % ( str(func_name), str(params), str(fault_codes) ) )

def connect(url):
    global server

    try:
        kdebug.debug(2, "Connecting to url '%s'." % ( url ) )
        server = xmlrpclib.ServerProxy(url)
        kdebug.debug(1, "Connected to url '%s'." % ( url ) )
        
    except xmlrpclib.ProtocolError, e:
        print "A protocol error occurred:"
        print "URL: %s" % e.url
        print "HTTP/HTTPS headers: %s" % e.headers
        print "Error code: %d" % e.errcode
Example #43
0
    def handle_download(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.file = args[1]
        
        # Options
        self.user_id = 1
        self.share_id = 0
        self.download_file_as = self.file
        for opt, value in opts:
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-a" or opt == "--download_file_as":
                self.download_file_as = value
            if opt == "-p" or opt == "--parent_id":
                self.parent_id = value
 
        # Connect to the KCD database.
        self.conn = self.get_db_conn()

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object(), db_conn=self.conn)
        kdebug.debug(1, "Instantiated a KCD client.")

        # Get the entry details.
        entry = kfs_lib.kfs_kas_view_lookup_file(self.conn, self.kws_id, self.share_id, self.file, self.parent_inode)
        if not isinstance(entry, kfs_lib.KFSFile): raise Exception("This entry is not a file.")

        # Prepare file list.
        files = []
        file = kfs_lib.KFSDownloadFile()
        file.inode = entry.inode
        file.commit_id = entry.commit_id
        file.size = entry.size
        file.comm = kfs_lib.KFSFileWriter(self.download_file_as)
        files.append(file)

        # Connecting to KCD.
        kdebug.debug(2, "Connecting to KCD.")
        c.connect()
        kdebug.debug(1, "Connected to KCD.")

        # Selecting KFS role.
        kdebug.debug(2, "Selecting KFS role.")
        c.select_role(kanp.KANP_KCD_ROLE_FILE_XFER)
        kdebug.debug(1, "Selected KFS role.")

        # Uploading file(s).
        kdebug.debug(2, "Downloading file(s) from kcd: kws_id %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )
        c.kfs_download(self.kws_id, self.share_id, self.user_id, files)
        kdebug.debug(1, "Downloaded file(s) from kcd: kws_id %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )

        # Errors?
        i = -1
        for file in files:
            i += 1
            if file.kfs_error:
                print "File %i could not be downloaded: '%s'." % ( i, file.kfs_error )

        # Close  KCD connection.
        c.close()
Example #44
0
    def handle_upload(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.file = args[1]

        # Options
        self.user_id = 1
        self.share_id = 0
        self.upload_file_as = os.path.basename(self.file)
        for opt, value in opts:
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-a" or opt == "--upload_file_as":
                self.upload_file_as = value

        # Connect to the KCD database.
        self.conn = self.get_db_conn()

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object(), db_conn=self.conn)
        kdebug.debug(1, "Instantiated a KCD client.")

        # Prepare file list.
        files = []
        file = kfs_lib.KFSUploadFile()
        file.kfs_op = kanp.KANP_KFS_OP_CREATE_FILE
        file.parent_inode = 0
        file.parent_commit_id = 0
        file.name = self.upload_file_as
        fd = os.open(self.file, os.O_RDONLY)
        file.set_from_fd(fd)
        files.append(file)

        # Connecting to KCD.
        kdebug.debug(2, "Connecting to KCD.")
        c.connect()
        kdebug.debug(1, "Connected to KCD.")

        # Selecting KFS role.
        kdebug.debug(2, "Selecting KFS role.")
        c.select_role(kanp.KANP_KCD_ROLE_FILE_XFER)
        kdebug.debug(1, "Selected KFS role.")

        # Uploading file(s).
        kdebug.debug(2, "Uploading file(s) to kcd %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )
        c.kfs_upload(self.kws_id, self.share_id, self.user_id, files)
        kdebug.debug(1, "Uploaded file(s) to kcd %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )

        # Errors?
        i = -1
        for file in files:
            i += 1
            if file.kfs_error:
                print "File %i could not be uploaded: '%s'." % (i,
                                                                file.kfs_error)

        # Close  KCD connection.
        c.close()
Example #45
0
def assert_fault_xmlrpc(func_name, fault_codes, *params):
    try:
        value = getattr(server, func_name)(*params)
        raise ExceptionReturn(value,
            "ERROR: func: '%s', params:'%s': succeded.. shoud have failed with code(s) %s" % \
            ( str(func_name), str(*params), str(fault_codes) ) )

    except xmlrpclib.Fault, e:
        if (type(fault_codes) == int and fault_codes != e.faultCode) or \
                (type(fault_codes) != int and not e.faultCode in fault_codes):
            raise Exception(
                "ERROR: func: '%s', params: '%s': expected fault(s) '%s', got fault %i, string '%s'." % \
                ( str(func_name), str(params), str(fault_codes), e.faultCode, e.faultString) )

    kdebug.debug(1,
        "Suceeded: func '%s', params '%s': failed like expected with one of code(s) '%s'." \
            % ( str(func_name), str(params), str(fault_codes) ) )


def connect(url):
    global server

    try:
        kdebug.debug(2, "Connecting to url '%s'." % (url))
        server = xmlrpclib.ServerProxy(url)
        kdebug.debug(1, "Connected to url '%s'." % (url))

    except xmlrpclib.ProtocolError, e:
        print "A protocol error occurred:"
        print "URL: %s" % e.url
        print "HTTP/HTTPS headers: %s" % e.headers
Example #46
0
    def get_value(self):
        # output debug info
        kdebug.debug(3, "_get_value: value='%s'" % (str(self._value)), "kvalues")

        # return current value
        return self._value
Example #47
0
    def handle_download(self, opts, args):
        # KDebug parameters
        self.set_debug_levels(opts)

        # Arguments
        self.kws_id = int(args[0])
        self.file = args[1]

        # Options
        self.user_id = 1
        self.share_id = 0
        self.download_file_as = self.file
        for opt, value in opts:
            if opt == "-u" or opt == "--user_id":
                self.user_id = value
            if opt == "-s" or opt == "--share_id":
                self.share_id = value
            if opt == "-a" or opt == "--download_file_as":
                self.download_file_as = value
            if opt == "-p" or opt == "--parent_id":
                self.parent_id = value

        # Connect to the KCD database.
        self.conn = self.get_db_conn()

        # Connect to KCD
        kdebug.debug(2, "Instantiating a KCD client.")
        c = BaseKcdClient(get_kcd_external_conf_object(), db_conn=self.conn)
        kdebug.debug(1, "Instantiated a KCD client.")

        # Get the entry details.
        entry = kfs_lib.kfs_kas_view_lookup_file(self.conn, self.kws_id,
                                                 self.share_id, self.file,
                                                 self.parent_inode)
        if not isinstance(entry, kfs_lib.KFSFile):
            raise Exception("This entry is not a file.")

        # Prepare file list.
        files = []
        file = kfs_lib.KFSDownloadFile()
        file.inode = entry.inode
        file.commit_id = entry.commit_id
        file.size = entry.size
        file.comm = kfs_lib.KFSFileWriter(self.download_file_as)
        files.append(file)

        # Connecting to KCD.
        kdebug.debug(2, "Connecting to KCD.")
        c.connect()
        kdebug.debug(1, "Connected to KCD.")

        # Selecting KFS role.
        kdebug.debug(2, "Selecting KFS role.")
        c.select_role(kanp.KANP_KCD_ROLE_FILE_XFER)
        kdebug.debug(1, "Selected KFS role.")

        # Uploading file(s).
        kdebug.debug(2, "Downloading file(s) from kcd: kws_id %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )
        c.kfs_download(self.kws_id, self.share_id, self.user_id, files)
        kdebug.debug(1, "Downloaded file(s) from kcd: kws_id %i, share %i, user %i." % \
            ( self.kws_id, self.share_id, self.user_id ) )

        # Errors?
        i = -1
        for file in files:
            i += 1
            if file.kfs_error:
                print "File %i could not be downloaded: '%s'." % (
                    i, file.kfs_error)

        # Close  KCD connection.
        c.close()
def test_org():
    global server_org_id

    org_id = server.get_security_context_org_id(server_sid)
    assert str(org_id).isdigit()
    kdebug.debug(2, "Bound to organization ID: %s" % ( str(org_id) ))
Example #49
0
    if ksession_pg_conn != None:
        try:
            if ksession_pg_conn.inTransaction:
                kdebug.debug(1, "Cached session connection not clean... rolling previous transaction back.", "ksession")
                ksession_pg_conn.rollback()
            exec_pg_query_rb_on_except(ksession_pg_conn, "SELECT 1")
            ksession_pg_conn.rollback()
            kdebug.debug(2, "Cached session connection operational.", "ksession")
            return
        except Exception, e:
            kdebug.debug(2, "Cached session connection does not work, reopening.", "ksession")
            ksession_pg_conn = None

    # There is no current connection. Open a new one.
    else:
        kdebug.debug(2, "No session connection open, opening new one.", "ksession")
        
    try:
        ksession_pg_conn = open_pg_conn(database = db_name, 
                                        host = db_host,
                                        port = db_port,
                                        user = db_user,
                                        password = db_pwd)
    except:
        ksession_pg_conn = None
        raise

# This function loads and creates session objects. If a session ID is specified,
# the function attempts to load this session. On failure, or if no session ID is
# specified, the function attempts to create a new session. If create_as_needed
# is false, however, the function throws an exception instead of creating a new
Example #50
0
                    "ksession")
                ksession_pg_conn.rollback()
            exec_pg_query_rb_on_except(ksession_pg_conn, "SELECT 1")
            ksession_pg_conn.rollback()
            kdebug.debug(2, "Cached session connection operational.",
                         "ksession")
            return
        except Exception, e:
            kdebug.debug(
                2, "Cached session connection does not work, reopening.",
                "ksession")
            ksession_pg_conn = None

    # There is no current connection. Open a new one.
    else:
        kdebug.debug(2, "No session connection open, opening new one.",
                     "ksession")

    try:
        ksession_pg_conn = open_pg_conn(database=db_name,
                                        host=db_host,
                                        port=db_port,
                                        user=db_user,
                                        password=db_pwd)
    except:
        ksession_pg_conn = None
        raise


# This function loads and creates session objects. If a session ID is specified,
# the function attempts to load this session. On failure, or if no session ID is
# specified, the function attempts to create a new session. If create_as_needed
Example #51
0
    def __init__(self, id, **options):
        self.hidden = False
        self.filled = False
        self.validation_exceptions = []

        # store options if not already stored by a sub-class
        self.store_options(options)

        # Field ID - string list
        self.id = KStringValue(value=id, allow_none=False).value
        #self.id_str = recursive_string_list_to_string(self.id)

        # needed for debug (__str__)
        self._data = None

        kdebug.debug(
            3, "New instance of class '%s'" % (str(self.__class__.__name__)),
            "kweb_forms")

        # FIXME - choose a better name, ...
        # Form.each_field behaves differently if counts is true or false
        self.counts = True

        # store options temporarily
        self.options = options

        # form id
        self.form_id = KStringValue(
            value=self.get_option("form_id", default_value="")).value

        # filters
        self.pre_filter_callables = self.get_option("pre_filter_callables",
                                                    default_value=[])
        self.post_filter_callables = self.get_option("post_filter_callables",
                                                     default_value=[])

        # field boolean options
        self.required = KBoolValue(
            value=self.get_option("required", default_value=False)).value
        self.force_value = KBoolValue(
            value=self.get_option("force_value", default_value=False)).value
        self.enabled = KBoolValue(
            value=self.get_option("enabled", default_value=True)).value
        self.autofocus = KBoolValue(
            value=self.get_option("autofocus", default_value=False)).value

        # Field reference (any type) - reference to anything
        self.reference = KStringValue(value=self.get_option("reference"),
                                      allow_none=False).value

        # Field classe(s) (string or list of strings)
        self.classes = KStringListValue(value=self.get_option("classes"),
                                        allow_none=True).value

        # Field tags (ordered dict of key/values)
        self.other_attributes = KStringDictValue(
            value=self.get_option("other_attributes"), allow_none=True).value

        self._data = KValue(value=self.get_option("value"),
                            allow_none=(not self.required),
                            raise_on_exception=False,
                            pre_filter_callables=self.pre_filter_callables,
                            post_filter_callables=self.post_filter_callables)
Example #52
0
def test_org():
    global server_org_id

    server_org_id = server.get_security_context_org_id(server_sid)
    assert str(server_org_id).isdigit()
    kdebug.debug(2, "Bound to organization ID: %s" % (str(server_org_id)))