Esempio n. 1
0
    def renew(self, clear_session=False):

        if clear_session:
            self.clear()

        request = current.request
        response = current.response
        session = response.session
        masterapp = response.session_masterapp
        cookies = request.cookies

        if response.session_storage_type == 'cookie':
            return

        # if the session goes in file
        if response.session_storage_type == 'file':
            self._close(response)
            uuid = web2py_uuid()
            response.session_id = '%s-%s' % (response.session_client, uuid)
            separate = (lambda s: s[
                -2:]) if session and response.session_id[2:3] == "/" else None
            if separate:
                prefix = separate(response.session_id)
                response.session_id = '%s/%s' % \
                    (prefix, response.session_id)
            response.session_filename = \
                os.path.join(up(request.folder), masterapp,
                             'sessions', response.session_id)
            response.session_new = True

        # else the session goes in db
        elif response.session_storage_type == 'db':
            table = response.session_db_table

            # verify that session_id exists
            if response.session_file:
                self._close(response)
            if response.session_new:
                return
            # Get session data out of the database
            if response.session_id is None:
                return
            (record_id, sep, unique_key) = response.session_id.partition(':')

            if record_id.isdigit() and long(record_id) > 0:
                new_unique_key = web2py_uuid()
                row = table(record_id)
                if row and row.unique_key == unique_key:
                    table._db(table.id == record_id).update(
                        unique_key=new_unique_key)
                else:
                    record_id = None
            if record_id:
                response.session_id = '%s:%s' % (record_id, new_unique_key)
                response.session_db_record_id = record_id
                response.session_db_unique_key = new_unique_key
            else:
                response.session_new = True
Esempio n. 2
0
    def renew(self, clear_session=False):

        if clear_session:
            self.clear()

        request = current.request
        response = current.response
        session = response.session
        masterapp = response.session_masterapp
        cookies = request.cookies

        if response.session_storage_type == 'cookie':
            return

        # if the session goes in file
        if response.session_storage_type == 'file':
            self._close(response)
            uuid = web2py_uuid()
            response.session_id = '%s-%s' % (response.session_client, uuid)
            separate = (lambda s: s[-2:]) if session and response.session_id[2:3] == "/" else None
            if separate:
                prefix = separate(response.session_id)
                response.session_id = '%s/%s' % \
                    (prefix, response.session_id)
            response.session_filename = \
                os.path.join(up(request.folder), masterapp,
                             'sessions', response.session_id)
            response.session_new = True

        # else the session goes in db
        elif response.session_storage_type == 'db':
            table = response.session_db_table

            # verify that session_id exists
            if response.session_file:
                self._close(response)
            if response.session_new:
                return
            # Get session data out of the database
            if response.session_id is None:
                return
            (record_id, sep, unique_key) = response.session_id.partition(':')

            if record_id.isdigit() and long(record_id) > 0:
                new_unique_key = web2py_uuid()
                row = table(record_id)
                if row and row.unique_key == unique_key:
                    table._db(table.id == record_id).update(unique_key=new_unique_key)
                else:
                    record_id = None
            if record_id:
                response.session_id = '%s:%s' % (record_id, new_unique_key)
                response.session_db_record_id = record_id
                response.session_db_unique_key = new_unique_key
            else:
                response.session_new = True
Esempio n. 3
0
 def compute_uuid(self):
     self._uuid = '%s/%s.%s.%s' % (
         self.application,
         self.client.replace(':', '_'),
         self.now.strftime('%Y-%m-%d.%H-%M-%S'),
         web2py_uuid())
     return self._uuid
Esempio n. 4
0
def profile():

    if auth.user is None:
        my_username = ''
    else:
        my_username = auth.user.username
    user_name = request.args(0)
    #Note: Profile Details
    my_first = db(db.auth_user.username == user_name).select(db.auth_user.first_name)
    my_last = db(db.auth_user.username == user_name).select(db.auth_user.last_name)
    my_college = db(db.auth_user.username == user_name).select(db.auth_user.College)
    my_major = db(db.auth_user.username == user_name).select(db.auth_user.Major)
    my_gender = db(db.auth_user.username == user_name).select(db.auth_user.Gender)
    ##############################


    user_images = db(db.auth_user.username == user_name).select()
    for row in db().select(db.auth_user.ALL):
        if row.username == user_name:
            print "Name found"
            found = 1
            break
        else:
            print "No username found"
            found = 0
    if found == 1:
        print "print out form"
    else:
        print "no username founded, print out no such username try again"
    draft_id = gluon_utils.web2py_uuid()
    return dict(user_name=user_name, user_images=user_images, my_username=my_username,
                my_first=my_first, my_last=my_last, my_college=my_college, my_major=my_major,
                my_gender=my_gender, draft_id=draft_id)
Esempio n. 5
0
    def queue_task(self, function, pargs=[], pvars={}, **kwargs):
        """
        Queue tasks. This takes care of handling the validation of all
        values.
        :param function: the function (anything callable with a __name__)
        :param pargs: "raw" args to be passed to the function. Automatically
            jsonified.
        :param pvars: "raw" kwargs to be passed to the function. Automatically
            jsonified
        :param kwargs: all the scheduler_task columns. args and vars here should be
            in json format already, they will override pargs and pvars

        returns a dict just as a normal validate_and_insert, plus a uuid key holding
        the uuid of the queued task. If validation is not passed, both id and uuid
        will be None, and you'll get an "error" dict holding the errors found.
        """
        if hasattr(function, '__name__'):
            function = function.__name__
        targs = 'args' in kwargs and kwargs.pop('args') or dumps(pargs)
        tvars = 'vars' in kwargs and kwargs.pop('vars') or dumps(pvars)
        tuuid = 'uuid' in kwargs and kwargs.pop('uuid') or web2py_uuid()
        tname = 'task_name' in kwargs and kwargs.pop('task_name') or function
        rtn = self.db.scheduler_task.validate_and_insert(
            function_name=function,
            task_name=tname,
            args=targs,
            vars=tvars,
            uuid=tuuid,
            **kwargs)
        if not rtn.errors:
            rtn.uuid = tuuid
        else:
            rtn.uuid = None
        return rtn
Esempio n. 6
0
 def compute_uuid(self):
     self.uuid = '%s/%s.%s.%s' % (
         self.application,
         self.client.replace(':', '_'),
         self.now.strftime('%Y-%m-%d.%H-%M-%S'),
         web2py_uuid())
     return self.uuid
Esempio n. 7
0
    def __init__(self,db,tasks=None,migrate=True,
                 worker_name=None,group_names=None,heartbeat=HEARTBEAT,
                 max_empty_runs=0, discard_results=False):

        MetaScheduler.__init__(self)

        self.db = db
        self.db_thread = None
        self.tasks = tasks
        self.group_names = group_names or ['main']
        self.heartbeat = heartbeat
        self.worker_name = worker_name or socket.gethostname()+'#'+str(web2py_uuid())
        self.worker_status = RUNNING, 1 #tuple containing status as recorded in
                                        #the table, plus a boost parameter for
                                        #hibernation (i.e. when someone stop the
                                        #worker acting on the scheduler_worker table)
        self.max_empty_runs = max_empty_runs
        self.discard_results = discard_results
        self.is_a_ticker = False
        self.do_assign_tasks = False

        from gluon import current
        current._scheduler = self

        self.define_tables(db,migrate=migrate)
Esempio n. 8
0
def saml2_handler(session, request, config_filename = None, entityid = None):
    config_filename = config_filename or os.path.join(request.folder,'private','sp_conf')
    client = Saml2Client(config_file = config_filename)
    if not entityid:
    	idps = client.metadata.with_descriptor("idpsso")
    	entityid = idps.keys()[0]
    bindings = [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]
    binding, destination = client.pick_binding(
        "single_sign_on_service", bindings, "idpsso", entity_id=entityid)
    if request.env.request_method == 'GET':
        binding = BINDING_HTTP_REDIRECT 
    elif request.env.request_method == 'POST':
        binding = BINDING_HTTP_POST
    if not request.vars.SAMLResponse:
        req_id, req = client.create_authn_request(destination, binding=binding)
        relay_state = web2py_uuid().replace('-','')
        session.saml_outstanding_queries = {req_id: request.url}	
        session.saml_req_id = req_id
        http_args = client.apply_binding(binding, str(req), destination,
                                         relay_state=relay_state)
        return {'url':dict(http_args["headers"])['Location']}
    else:
        relay_state = request.vars.RelayState
        req_id = session.saml_req_id
        unquoted_response = request.vars.SAMLResponse
        res =  {}
        try:
            data = client.parse_authn_request_response(
                unquoted_response, binding, session.saml_outstanding_queries)
            res['response'] = data if data else {}
        except Exception as e:
            import traceback
            res['error'] = traceback.format_exc()
        return res
Esempio n. 9
0
def mobile_login():
    # Verify email and password
    email, password = request.vars.email, request.vars.password
    if not email or not password:
        return dict(user_id=False, ticket=False)

    # user = db(db.user.email == email).select().first()
    # hashed_password = hash_password(password)
    # if not user or user.password != hashed_password: return dict(user_id=False, ticket=False)
    if not auth.login_bare(email, password):
        return dict(user_id=False, ticket=False)

    user = db(db.user.email == email).select().first()

    # Make new entry in auth_cas table
    web_auth_cas = db(db.web_auth_cas.user_id == user.id).select().first()
    if not web_auth_cas:
        ticket = "ST-" + web2py_uuid()
        db.web_auth_cas.update_or_insert(db.web_auth_cas.user_id == user.id, user_id=user.id, service='talent_mobile',
                                         ticket=ticket, renew='T')
    else:
        ticket = web_auth_cas.ticket

    # Set user's Get Started action for Mobile App Install
    set_get_started_action(user, GET_STARTED_ACTIONS['DOWNLOAD_MOBILE_APP'])

    # Return ticket of new entry
    return dict(user_id=user.id, ticket=ticket)
Esempio n. 10
0
def mobile_create():
    domain_id, email, password = request.vars.domain_id, request.vars.email, request.vars.password

    # Get and verify domain, email, and password
    if not domain_id or not email or not password:
        return dict(user_id=False)
    domain = db.domain(domain_id)
    if not domain:
        return dict(user_id=False)
    user = db(db.user.email == email).select().first()  # make sure user doesn't exist
    if user:
        return dict(user_id=False)

    # Make new entry in user table
    registration_key = web2py_uuid()
    hashed_password = hash_password(password)
    user_id = db.user.insert(email=email, password=hashed_password, registration_key=registration_key,
                             domainId=domain_id)

    db.commit()

    # TODO: Remove this functionality when we'll add UI for user scoped roles
    from TalentUsers import add_roles_to_user
    add_roles_to_user(user_id)
    
    # Make new widget_page if first user in domain
    get_or_create_widget_page(db.user(user_id))

    return dict(user_id=user_id, email=email, registration_key=registration_key)
Esempio n. 11
0
    def _(content):
        from gluon.utils import web2py_uuid
        uuid = web2py_uuid()
        if not content.gallery:
            current.response.write(XML('Gallery'), escape=False)
            return
        files = managed_html.db(managed_html.db.managed_html_file.id.belongs(content.gallery.split(','))).select()
        current.response.write(XML("""<div id='%s'>"""%uuid).xml(),escape=False)
        for file in files:
            current.response.write(XML("""<img file_id='%s' src='%s'/>"""%(file.id, URL('static', 'uploads/contents/%s'%file.name))).xml(),escape=False)
        current.response.write(XML("""
</div>
<script type="text/javascript" src="%s"></script>
<script type="text/javascript">
jQuery(function($) {
$('#%s').jqFancyTransitions({ width: %s, height: %s , effect: '%s', delay: %s});
});
</script>
"""%(URL(APP, 'static', 'plugin_managed_gallery/jqFancyTransitions.1.8.min.js'),
    uuid,
    content.width, 
    content.height, 
    content.effect,
    int(content.delay or 5) * 1000,
    )).xml(), 
    escape=False)
Esempio n. 12
0
def saml2_handler(session, request, config_filename = None):
    config_filename = config_filename or os.path.join(request.folder,'private','sp_conf')
    client = Saml2Client(config_file = config_filename)
    idps = client.metadata.with_descriptor("idpsso")
    entityid = idps.keys()[0]
    bindings = [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]
    binding, destination = client.pick_binding(
        "single_sign_on_service", bindings, "idpsso", entity_id=entityid)
    if request.env.request_method == 'GET':
        binding = BINDING_HTTP_REDIRECT 
    elif request.env.request_method == 'POST':
        binding = BINDING_HTTP_POST
    if not request.vars.SAMLResponse:
        req_id, req = client.create_authn_request(destination, binding=binding)
        relay_state = web2py_uuid().replace('-','')
        session.saml_outstanding_queries = {req_id: request.url}
        session.saml_req_id = req_id
        http_args = client.apply_binding(binding, str(req), destination,
                                         relay_state=relay_state)
        return {'url':dict(http_args["headers"])['Location']}
    else:
        relay_state = request.vars.RelayState
        req_id = session.saml_req_id
        unquoted_response = request.vars.SAMLResponse
        res =  {}
        try:
            data = client.parse_authn_request_response(
                unquoted_response, binding, session.saml_outstanding_queries)
            res['response'] = data if data else {}
        except Exception as e:
            import traceback
            res['error'] = traceback.format_exc()
        return res
Esempio n. 13
0
    def __call__(self, field, value, **attributes):
        if not self.settings.files:
            _files = [
                URL('static', 'css/jquery-te.css'),
                URL('static', 'js/jquery-te.js'),
            ]
        else:
            _files = self.settings.files
        _set_files(_files)

        from gluon.utils import web2py_uuid
        _id = '%s_%s_%s' % (field._tablename, field.name, web2py_uuid())
        attr = dict(_id=_id,
                    _name=field.name,
                    requires=field.requires,
                    _class='text')

        script = SCRIPT("""
    $('#%(id)s').jqte({
      title: %(title)s,
      source: %(source)s
    });
    """ % dict(id=_id, title=self.settings.title, source=self.settings.source))

        return SPAN(TEXTAREA((value != None and str(value)) or '', **attr),
                    script, **attributes)
Esempio n. 14
0
    def __init__(self,
                 db,
                 tasks={},
                 migrate=True,
                 worker_name=None,
                 group_names=None,
                 heartbeat=HEARTBEAT,
                 max_empty_runs=0):

        MetaScheduler.__init__(self)

        self.db = db
        self.db_thread = None
        self.tasks = tasks
        self.group_names = group_names or ['main']
        self.heartbeat = heartbeat
        self.worker_name = worker_name or socket.gethostname() + '#' + str(
            web2py_uuid())
        self.max_empty_runs = max_empty_runs
        self.is_a_ticker = False
        self.do_assign_tasks = False

        from gluon import current
        current._scheduler = self

        self.define_tables(db, migrate=migrate)
Esempio n. 15
0
def export_file():
    cur_id = request.vars.flise_id
    import zipfile
    import StringIO
    import os.path
    output = StringIO.StringIO()
    archive = zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED)
    archive.write(os.path.join(request.folder, 'uploads', db.flise_file[cur_id].file), arcname="file.txt")
    archive.write(os.path.join(request.folder, 'uploads', db.flise_file[cur_id].rlvfile), arcname="file.rlv")
    archive.writestr("flise_file.csv", str(db(db.flise_file.id == cur_id).select()))
    archive.writestr("events.csv", str(db(db.event.flise_file_id == cur_id).select()))
    archive.writestr("subintervals.csv", str(db(db.subintervals.flise_file_id == cur_id).select()))
    archive.writestr("solutions.csv", str(db(db.solution.id == db.event.solution_id)(db.event.flise_file_id == cur_id).select(db.solution.id, db.solution.name, db.solution.components_name, db.solution.components_ratio, distinct=True)))
    archive.writestr("strains.csv", str(db(db.strain.id == db.flise_file.strain_id)(db.flise_file.id == cur_id).select(db.strain.id, db.strain.name, db.strain.identifier)|db(db.strain.id == db.subintervals.strain_id)(db.subintervals.flise_file_id == cur_id).select(db.strain.id, db.strain.name, db.strain.identifier, distinct=True)))
    archive.close()
    if request.extension == 'store_zip':
        from gluon.utils import web2py_uuid
        uufilename = web2py_uuid() + '.zip'
        if not os.path.exists(os.path.join(request.folder, 'static', 'tmp')):
            os.mkdir(os.path.join(request.folder, 'static', 'tmp'))
        open(os.path.join(request.folder, 'static', 'tmp',  uufilename), 'wb').write(output.getvalue())
        return URL(request.application, 'static/tmp', uufilename)
    import gluon.contenttype
    response.headers['Content-Type'] = gluon.contenttype.contenttype('.zip')
    response.headers['Content-disposition'] = 'attachment; filename=flise_file_%s.zip' % cur_id
    return output.getvalue()
Esempio n. 16
0
def create():
    title = request.vars.title or 'New Page'
    url = request.vars.url
    theme = request.vars.theme
    # if postback create a new page
    if request.env.request_method=='POST':
        # if no theme, download the page
        if title and not theme and url and url!='http://':
            theme = web2py_uuid().replace('-','')
            path = os.path.join(request.folder,'static','themes',theme)
            if not os.path.exists(path): os.makedirs(path)
            try:
                htmldownload(url,path,prefix='@{page.theme}/')
            except IOError:
                response.flash = 'Unable to download'
        # if downloaded or there is a theme create record
        if title and theme:
            path = os.path.join(request.folder,'static','themes',
                                theme,'theme.html')
            data = response.render(open(path,'rb'))
            id = db.page.insert(title=request.vars.title,theme=theme,
                                full_html = data,owner=auth.user.id)
            my_group = db.auth_group(role=auth.user.username).id
            # give author read and edit permission
            redirect(URL('edit',args=id))
    # if no postback, list of availbale themes
    filenames = glob.glob(os.path.join(
            request.folder,'static','themes','*','thumbnail.png'))    
    themes = [(f.split('/')[-2],URL('static','/'.join(f.split('/')[-3:]))) \
                  for f in filenames]
    return locals()
Esempio n. 17
0
def manage():
    """
    Controller for the procedure manager page. Parses the device ID and returns a list of procedures
    that are associated with the device ID.
    :return: procedure_list, uuid, and vars for URL
    """
    # Extract the device ID from the URL
    device_id = request.vars['device']

    # Go back if there's no device ID for some reason
    # TODO: Also ensure that the device ID is actually in the database.
    if device_id is None:
        session.flash = T('Device not found.')
        redirect(URL('default', 'index'))

    # Generate a UUID for user signature
    sign_uuid = gluon_utils.web2py_uuid()

    # Find all the procedures for this device
    procedure_list = db(db.procedures.device_id == device_id).select()

    # Return the procedure list, UUID, and device ID (as val) to be used in the page.
    return dict(procedures_list=procedure_list,
                sign_uuid=sign_uuid,
                val=device_id)
Esempio n. 18
0
def s3_dev_toolbar():
    """
        Developer Toolbar - ported from gluon.Response.toolbar()
        Shows useful stuff at the bottom of the page in Debug mode
    """
    from gluon.dal import thread
    from gluon.utils import web2py_uuid

    BUTTON = TAG.button

    if hasattr(thread, "instances"):
        dbstats = [TABLE(*[TR(PRE(row[0]),
                           "%.2fms" % (row[1]*1000)) \
                           for row in i.db._timings]) \
                         for i in thread.instances]
    else:
        dbstats = []  # if no db or on GAE
    u = web2py_uuid()
    return DIV(
        BUTTON("request", _onclick="$('#request-%s').slideToggle()" % u),
        DIV(BEAUTIFY(current.request),
            _class="dbg_hidden",
            _id="request-%s" % u),
        BUTTON("session", _onclick="$('#session-%s').slideToggle()" % u),
        DIV(BEAUTIFY(current.session),
            _class="dbg_hidden",
            _id="session-%s" % u),
        BUTTON("response", _onclick="$('#response-%s').slideToggle()" % u),
        DIV(BEAUTIFY(current.response),
            _class="dbg_hidden",
            _id="response-%s" % u),
        BUTTON("db stats", _onclick="$('#db-stats-%s').slideToggle()" % u),
        DIV(BEAUTIFY(dbstats), _class="dbg_hidden", _id="db-stats-%s" % u),
        SCRIPT("$('.dbg_hidden').hide()"))
Esempio n. 19
0
    def test_0_redis_session(self):
        """ Basic redis read-write """
        db = self.db
        response = self.current.response
        Field = db.Field
        db.define_table(
            self.tname,
            Field('locked', 'boolean', default=False),
            Field('client_ip', length=64),
            Field('created_datetime',
                  'datetime',
                  default=datetime.now().isoformat()),
            Field('modified_datetime', 'datetime'),
            Field('unique_key', length=64),
            Field('session_data', 'blob'),
        )
        table = db[self.tname]
        unique_key = web2py_uuid()
        dd = dict(locked=0,
                  client_ip=response.session_client,
                  modified_datetime=datetime.now().isoformat(),
                  unique_key=unique_key,
                  session_data=pickle.dumps({
                      'test': 123,
                      'me': 112312312
                  }, pickle.HIGHEST_PROTOCOL))
        record_id = table.insert(**dd)
        data_from_db = db(table.id == record_id).select()[0]
        self.assertDictEqual(Storage(dd), data_from_db, 'get inserted dict')

        dd['locked'] = 1
        table._db(table.id == record_id).update(**dd)
        data_from_db = db(table.id == record_id).select()[0]
        self.assertDictEqual(Storage(dd), data_from_db,
                             'get the updated value')
Esempio n. 20
0
    def _try_store_in_db(self, request, response):
        # don't save if file-based sessions,
        # no session id, or session being forgotten
        # or no changes to session (Unless the session is new)
        if not self._enabled: return False
            
        if not response.session_db_table or (self._unchanged(response) and not response.session_new):
            return False

        table = response.session_db_table
        record_id = response.session_db_record_id
        if response.session_new:
            unique_key = web2py_uuid()
        else:
            unique_key = response.session_db_unique_key

        session_pickled = response.session_pickled or pickle.dumps(self, pickle.HIGHEST_PROTOCOL)

        dd = dict(locked=False,
                  client_ip=response.session_client,
                  modified_datetime=request.now,
                  session_data=session_pickled,
                  unique_key=unique_key)
        if record_id:
            if not table._db(table.id == record_id).update(**dd):
                record_id = None
        if not record_id:
            record_id = table.insert(**dd)
            response.session_id = '%s:%s' % (record_id, unique_key)
            response.session_db_unique_key = unique_key
            response.session_db_record_id = record_id

        self.save_session_id_cookie()
        return True
Esempio n. 21
0
    def queue_task(self, function, pargs=[], pvars={}, **kwargs):
        """
        Queue tasks. This takes care of handling the validation of all
        values.
        :param function: the function (anything callable with a __name__)
        :param pargs: "raw" args to be passed to the function. Automatically
            jsonified.
        :param pvars: "raw" kwargs to be passed to the function. Automatically
            jsonified
        :param kwargs: all the scheduler_task columns. args and vars here should be
            in json format already, they will override pargs and pvars

        returns a dict just as a normal validate_and_insert, plus a uuid key holding
        the uuid of the queued task. If validation is not passed, both id and uuid
        will be None, and you'll get an "error" dict holding the errors found.
        """
        if hasattr(function, "__name__"):
            function = function.__name__
        targs = "args" in kwargs and kwargs.pop("args") or dumps(pargs)
        tvars = "vars" in kwargs and kwargs.pop("vars") or dumps(pvars)
        tuuid = "uuid" in kwargs and kwargs.pop("uuid") or web2py_uuid()
        tname = "task_name" in kwargs and kwargs.pop("task_name") or function
        immediate = "immediate" in kwargs and kwargs.pop("immediate") or None
        rtn = self.db.scheduler_task.validate_and_insert(
            function_name=function, task_name=tname, args=targs, vars=tvars, uuid=tuuid, **kwargs
        )
        if not rtn.errors:
            rtn.uuid = tuuid
            if immediate:
                self.db(self.db.scheduler_worker.is_ticker == True).update(status=PICK)
        else:
            rtn.uuid = None
        return rtn
Esempio n. 22
0
def create():
    title = request.vars.title or 'New Page'
    url = request.vars.url
    theme = request.vars.theme
    # if postback create a new page
    if request.env.request_method == 'POST':
        # if no theme, download the page
        if title and not theme and url and url != 'http://':
            theme = web2py_uuid().replace('-', '')
            path = os.path.join(request.folder, 'static', 'themes', theme)
            if not os.path.exists(path): os.makedirs(path)
            try:
                htmldownload(url, path, prefix='@{page.theme}/')
            except IOError:
                response.flash = 'Unable to download'
        # if downloaded or there is a theme create record
        if title and theme:
            path = os.path.join(request.folder, 'static', 'themes', theme,
                                'theme.html')
            data = response.render(open(path, 'rb'))
            id = db.page.insert(title=request.vars.title,
                                theme=theme,
                                full_html=data,
                                owner=auth.user.id)
            my_group = db.auth_group(role=auth.user.username).id
            # give author read and edit permission
            redirect(URL('edit', args=id))
    # if no postback, list of availbale themes
    filenames = glob.glob(
        os.path.join(request.folder, 'static', 'themes', '*', 'thumbnail.png'))
    themes = [(f.split('/')[-2],URL('static','/'.join(f.split('/')[-3:]))) \
                  for f in filenames]
    return locals()
def define_from_schema(db, tablename, schemas=None):
    from gluon.utils import web2py_uuid
    schemas = schemas or get_schemas()
    PROPERTIES = schemas['properties'] # label, comment, ranges
    TABLENAMES = schemas['types'].keys()    
    datatypes = {'DataType':('string',None), 
                 'Text':('string',None), 
                 'Float':('double',None), 
                 'Number':('double',None), 
                 'DateTime':('datetime',None), 
                 'URL':('string',None), 
                 'Boolean':('boolean',None), 
                 'Time':('time',None), 
                 'Date':('date',None), 
                 'Integer':('integer',None)}
    if tablename in schemas['types']:
        #print tablename, schemas['types'][tablename]['properties']
        properties = schemas['types'][tablename]['properties']
        fields = [Field('uuid','string',default=lambda:web2py_uuid(),writable=False)]
        for property in properties:
            info = PROPERTIES[property]
            label = info['label']
            comment = info['comment']
            ranges = info['ranges']
            if len(ranges)==1 and ranges[0] in datatypes:
                ftype = datatypes[ranges[0]][0]
            else:
                ftype = 'list:string'
            fields.append(Field('f'+property,ftype,label=label))
        table = db.define_table('t'+tablename,*fields)
        if db(table).isempty():
            from gluon.contrib.populate import populate
            populate(table,120)
        return table
    return None
Esempio n. 24
0
    def queue_task(self, function, pargs=[], pvars={}, **kwargs):
        """
        Queue tasks. This takes care of handling the validation of all
        values.
        :param function: the function (anything callable with a __name__)
        :param pargs: "raw" args to be passed to the function. Automatically
            jsonified.
        :param pvars: "raw" kwargs to be passed to the function. Automatically
            jsonified
        :param kwargs: all the scheduler_task columns. args and vars here should be
            in json format already, they will override pargs and pvars

        returns a dict just as a normal validate_and_insert, plus a uuid key holding
        the uuid of the queued task. If validation is not passed, both id and uuid
        will be None, and you'll get an "error" dict holding the errors found.
        """
        if hasattr(function, '__name__'):
            function = function.__name__
        targs = 'args' in kwargs and kwargs.pop('args') or dumps(pargs)
        tvars = 'vars' in kwargs and kwargs.pop('vars') or dumps(pvars)
        tuuid = 'uuid' in kwargs and kwargs.pop('uuid') or web2py_uuid()
        tname = 'task_name' in kwargs and kwargs.pop('task_name') or function
        rtn = self.db.scheduler_task.validate_and_insert(
            function_name=function,
            task_name=tname,
            args=targs,
            vars=tvars,
            uuid=tuuid,
            **kwargs)
        if not rtn.errors:
            rtn.uuid = tuuid
        else:
            rtn.uuid = None
        return rtn
Esempio n. 25
0
def s3_dev_toolbar():
    """
        Developer Toolbar - ported from gluon.Response.toolbar()
        Shows useful stuff at the bottom of the page in Debug mode
    """
    from gluon.dal import thread
    from gluon.utils import web2py_uuid

    BUTTON = TAG.button

    if hasattr(thread, "instances"):
        dbstats = [TABLE(*[TR(PRE(row[0]),
                           "%.2fms" % (row[1]*1000)) \
                           for row in i.db._timings]) \
                         for i in thread.instances]
    else:
        dbstats = [] # if no db or on GAE
    u = web2py_uuid()
    return DIV(
        BUTTON("request", _onclick="$('#request-%s').slideToggle()" % u),
        DIV(BEAUTIFY(current.request), _class="dbg_hidden", _id="request-%s" % u),
        BUTTON("session", _onclick="$('#session-%s').slideToggle()" % u),
        DIV(BEAUTIFY(current.session), _class="dbg_hidden", _id="session-%s" % u),
        # Disabled response as it breaks S3SearchLocationWidget
        #BUTTON("response", _onclick="$('#response-%s').slideToggle()" % u),
        #DIV(BEAUTIFY(current.response), _class="dbg_hidden", _id="response-%s" % u),
        BUTTON("db stats", _onclick="$('#db-stats-%s').slideToggle()" % u),
        DIV(BEAUTIFY(dbstats), _class="dbg_hidden", _id="db-stats-%s" % u),
        SCRIPT("$('.dbg_hidden').hide()")
        )
Esempio n. 26
0
    def queue_task(self, function, pargs=[], pvars={}, **kwargs):
        """
        FIXME: immediate should put item in queue. The hard part is
        that currently there are no hooks happening at post-commit time
        Queue tasks. This takes care of handling the validation of all
        parameters

        Args:
            function: the function (anything callable with a __name__)
            pargs: "raw" args to be passed to the function. Automatically
                jsonified.
            pvars: "raw" kwargs to be passed to the function. Automatically
                jsonified
            kwargs: all the parameters available (basically, every
                `scheduler_task` column). If args and vars are here, they should
                be jsonified already, and they will override pargs and pvars

        Returns:
            a dict just as a normal validate_and_insert(), plus a uuid key
            holding the uuid of the queued task. If validation is not passed
            ( i.e. some parameters are invalid) both id and uuid will be None,
            and you'll get an "error" dict holding the errors found.
        """
        if hasattr(function, '__name__'):
            function = function.__name__
        targs = 'args' in kwargs and kwargs.pop('args') or dumps(pargs)
        tvars = 'vars' in kwargs and kwargs.pop('vars') or dumps(pvars)
        tuuid = 'uuid' in kwargs and kwargs.pop('uuid') or web2py_uuid()
        tname = 'task_name' in kwargs and kwargs.pop('task_name') or function
        immediate = 'immediate' in kwargs and kwargs.pop('immediate') or None
        rtn = self.db.scheduler_task.validate_and_insert(
            function_name=function,
            task_name=tname,
            args=targs,
            vars=tvars,
            uuid=tuuid,
            **kwargs)
        if not rtn.errors:
            rtn.uuid = tuuid
            if immediate:
                r_server = self.r_server
                ticker = self.get_workers(only_ticker=True)
                if ticker.keys():
                    ticker = ticker.keys()[0]
                    with r_server.pipeline() as pipe:
                        while True:
                            try:
                                pipe.watch('SET_WORKER_STATUS')
                                worker_key = self._nkey('worker_status:%s' %
                                                        ticker)
                                pipe.hset(worker_key, 'status', 'PICK')
                                pipe.execute()
                                break
                            except RWatchError:
                                time.sleep(0.1)
                                continue
        else:
            rtn.uuid = None
        return rtn
Esempio n. 27
0
class DAL(pyDAL):
    serializers = w2p_serializers
    validators_method = _default_validators
    uuid = lambda x: web2py_uuid()
    representers = {
        'rows_render': sqlhtml.represent,
        'rows_xml': sqlhtml.SQLTABLE
    }
Esempio n. 28
0
def create_order():
    """Creates an order (AJAX function)"""
    cart = request.vars.cart
    # Stores the cart, and creates an order number.
    # It would be better to randomize the order number, but here for simplicity we don't.
    order_key = web2py_uuid()
    order_id = db.product_order.insert(cart=cart, order_key=order_key)
    return response.json(dict(order_id=order_id, order_key=order_key))
Esempio n. 29
0
 def compute_uuid(self):
     self.uuid = "%s/%s.%s.%s" % (
         self.application,
         self.client.replace(":", "_"),
         self.now.strftime("%Y-%m-%d.%H-%M-%S"),
         web2py_uuid(),
     )
     return self.uuid
def show_comments():
    draft_id = gluon_utils.web2py_uuid()
    disc_id = request.args(0)
    user_id = auth.user_id
    rows = db(db.discs.disc_id == disc_id).select(db.discs.ALL)
    first_disc = rows.first()
    disc_name = first_disc.disc_name
    return dict(draft_id=draft_id, disc_name=disc_name, disc_id=disc_id, user_id=user_id)
def boards():
    """Returns the boards name, id and a unique post id for when the board is clicked on"""
    board_id = request.args(0)
    board = db(db.boards.board_id == board_id).select(db.boards.board_content)
    for row in board:
        board_name = row.board_content
    post_id = gluon_utils.web2py_uuid()
    return dict(board_id=board_id, post_id=post_id, board_name=board_name)
def index():
    draft_id = gluon_utils.web2py_uuid()
    """Fetch the Game of the Year Category as the default active Category"""
    rows = db(db.cats.cat_name == "Game of the Year").select(db.cats.ALL)
    first_cat = rows.first()
    active_cat_id = first_cat.cat_id
    active_cat_name = first_cat.cat_name
    return dict(draft_id=draft_id, active_cat_id=active_cat_id, active_cat_name=active_cat_name)
Esempio n. 33
0
    def queue_task(self, function, pargs=[], pvars={}, **kwargs):
        """
        FIXME: immediate should put item in queue. The hard part is
        that currently there are no hooks happening at post-commit time
        Queue tasks. This takes care of handling the validation of all
        parameters

        Args:
            function: the function (anything callable with a __name__)
            pargs: "raw" args to be passed to the function. Automatically
                jsonified.
            pvars: "raw" kwargs to be passed to the function. Automatically
                jsonified
            kwargs: all the parameters available (basically, every
                `scheduler_task` column). If args and vars are here, they should
                be jsonified already, and they will override pargs and pvars

        Returns:
            a dict just as a normal validate_and_insert(), plus a uuid key
            holding the uuid of the queued task. If validation is not passed
            ( i.e. some parameters are invalid) both id and uuid will be None,
            and you'll get an "error" dict holding the errors found.
        """
        if hasattr(function, '__name__'):
            function = function.__name__
        targs = 'args' in kwargs and kwargs.pop('args') or dumps(pargs)
        tvars = 'vars' in kwargs and kwargs.pop('vars') or dumps(pvars)
        tuuid = 'uuid' in kwargs and kwargs.pop('uuid') or web2py_uuid()
        tname = 'task_name' in kwargs and kwargs.pop('task_name') or function
        immediate = 'immediate' in kwargs and kwargs.pop('immediate') or None
        rtn = self.db.scheduler_task.validate_and_insert(
            function_name=function,
            task_name=tname,
            args=targs,
            vars=tvars,
            uuid=tuuid,
            **kwargs)
        if not rtn.errors:
            rtn.uuid = tuuid
            if immediate:
                r_server = self.r_server
                ticker = self.get_workers(only_ticker=True)
                if ticker.keys():
                    ticker = ticker.keys()[0]
                    with r_server.pipeline() as pipe:
                        while True:
                            try:
                                pipe.watch('SET_WORKER_STATUS')
                                worker_key = self._nkey('worker_status:%s' % ticker)
                                pipe.hset(worker_key, 'status', 'PICK')
                                pipe.execute()
                                break
                            except RWatchError:
                                time.sleep(0.1)
                                continue
        else:
            rtn.uuid = None
        return rtn
Esempio n. 34
0
        def verify_email(form):
            from gluon.utils import web2py_uuid
            if str2bool(self.config.take('auth_local.admin_registration_requires_verification')):
                d = dict(form.vars)
                key = web2py_uuid()
                link = URL('default', 'user', args=('verify_email', key), scheme=True)
                d = dict(form.vars)
                plain_password = web2py_uuid().split('-')[0]
                md5_password = self.db.auth_user.password.validate(plain_password)[0]
                d.update(dict(registration_key=key, password=md5_password))
                self.db(self.db['auth_user']._id==form.vars.id).update(**d)

                from myapp import Mailer
                notification = Mailer()
                if notification.send_email(form.vars.email, 'VERIFY YOUR EMAIL', 'verify_email', link=link, password=plain_password):
                    self.session.flash = "Email sent to the user for verification"
                else:
                    self.session.flash = "Email unsent, uppss there is a error"
Esempio n. 35
0
def app_create(app, request, force=False, key=None, info=False):
    """Create a copy of welcome.w2p (scaffolding) app

    Args:
        app(str): application name
        request: the global request object

    """
    path = apath(app, request)
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except:
            if info:
                return False, traceback.format_exc(sys.exc_info)
            else:
                return False
    elif not force:
        if info:
            return False, "Application exists"
        else:
            return False
    try:
        w2p_unpack("welcome.w2p", path)
        for subfolder in [
            "models",
            "views",
            "controllers",
            "databases",
            "modules",
            "cron",
            "errors",
            "sessions",
            "cache",
            "languages",
            "static",
            "private",
            "uploads",
        ]:
            subpath = os.path.join(path, subfolder)
            if not os.path.exists(subpath):
                os.mkdir(subpath)
        db = os.path.join(path, "models", "db.py")
        if os.path.exists(db):
            data = read_file(db)
            data = data.replace("<your secret key>", "sha512:" + (key or web2py_uuid()))
            write_file(db, data)
        if info:
            return True, None
        else:
            return True
    except:
        rmtree(path)
        if info:
            return False, traceback.format_exc(sys.exc_info)
        else:
            return False
def show_cat():
    draft_id = gluon_utils.web2py_uuid()
    cat_id = request.args(0)
    rows = db(db.cats.cat_id == cat_id).select(db.cats.ALL)
    first_cat = rows.first()
    cat_name = first_cat.cat_name
    user_id = auth.user_id
    response.flash = T(cat_name)
    return dict(draft_id=draft_id, cat_name=cat_name, cat_id=cat_id, user_id=user_id)
Esempio n. 37
0
def create_survey():
    def f(form):
        form.vars.results = [0]*len(request.vars.choices)
    from gluon.utils import web2py_uuid
    db.survey.uuid.default = uuid = web2py_uuid()
    form = SQLFORM(db.survey).process(onvalidation=f)
    if form.accepted:
        redirect(URL('take_survey',args=uuid))
    return locals()
Esempio n. 38
0
    def __call__(self, field, value, **attributes):
        if not self.settings.files:
            _files = [
                URL(APP, "static", "plugin_elrte_widget/css/elrte.min.css"),
                URL(APP, "static", "plugin_elrte_widget/css/elrte-inner.css"),
                URL(APP, "static", "plugin_elrte_widget/css/smoothness/jquery-ui-1.8.13.custom.css"),
                URL(APP, "static", "plugin_elrte_widget/js/jquery-ui-1.8.16.custom.min.js"),
                URL(APP, "static", "plugin_elrte_widget/js/elrte.min.js"),
            ]
            if self.settings.lang:
                _files.append(URL(APP, "static", "plugin_elrte_widget/js/i18n/elrte.%s.js" % self.settings.lang))
        else:
            _files = self.settings.files
        _set_files(_files)

        from gluon.utils import web2py_uuid

        _id = "%s_%s_%s" % (field._tablename, field.name, web2py_uuid())
        attr = dict(_id=_id, _name=field.name, requires=field.requires, _class="text")

        script = SCRIPT(
            """
jQuery(function() { var t = 10; (function run() {if ((function() {
    if (typeof elRTE === 'undefined') { return true; }
    var opts = elRTE.prototype.options;
    opts.panels.default_1 = ['pastetext', 'pasteformattext', 'removeformat', 'undo', 'redo'];
    opts.panels.default_2 = ['formatblock', 'fontsize', 'fontname'];
    opts.panels.default_3 = ['bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript'];
    opts.panels.default_4 = ['forecolor', 'hilitecolor', 'justifyleft', 'justifyright',
                      'justifycenter', 'justifyfull', 'outdent', 'indent'];
    opts.panels.default_5 = ['link', 'unlink', 'image', 'elfinder','insertorderedlist', 'insertunorderedlist',
                      'horizontalrule', 'blockquote', 'div', 'stopfloat', 'css', 'nbsp'];
    opts.toolbars = {'default': ['default_1', 'default_2', 'default_3', 'default_4', 'default_5', 'tables']};

    if(typeof String.prototype.trim !== 'function') {
      String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, '');}
    }
    var el = $('#%(id)s');
    if(!$.support.opacity){if (el.text() == '') { el.text('<p>&nbsp;</p>')}}

    el.elrte({cssClass: 'el-rte', lang: '%(lang)s',
              toolbar: '%(toolbar)s',
              fmOpen : %(fm_open)s,
              cssfiles: %(cssfiles)s});
})()) {setTimeout(run, t); t = 2*t;}})();});

"""
            % dict(
                id=_id,
                lang=self.settings.lang or "",
                toolbar=self.settings.toolbar,
                fm_open=self.settings.fm_open,
                cssfiles=json.dumps(self.settings.cssfiles),
            )
        )

        return SPAN(script, TEXTAREA(value or "", **attr), **attributes)
Esempio n. 39
0
def index():
    #Determining if user is logged in
    count = 1
    if auth.user_id is None:
        count = 0
    #creating a unique board
    draft_id = gluon_utils.web2py_uuid()
    board_id = id
    return dict(draft_id=draft_id, count = count, board_id= board_id)
Esempio n. 40
0
def create_match():
    def f(form):
        form.vars.results = [0]*2
    from gluon.utils import web2py_uuid
    db.knockout_match.uuid.default = uuid = web2py_uuid()
    form = SQLFORM(db.knockout_match).process( onvalidation=f)
    if form.accepted:
        redirect(URL('index',args=uuid))
    return locals()
Esempio n. 41
0
def get_random_word(length=6):
    """Produces a random word"""
    # We initialize the random number generator in a safe way, to guarantee random sequences
    # even in the cloud on cloned hosts.
    r = random.Random(web2py_uuid())
    s = ''
    for j in range(length / 2):
        s += r.choice(CONSONANTS) + r.choice(VOWELS)
    return s
Esempio n. 42
0
def index():
    draft_id = gluon_utils.web2py_uuid()
    """Fetch the Game of the Year Category as the default active Category"""
    rows = db(db.cats.cat_name == "Game of the Year").select(db.cats.ALL)
    first_cat = rows.first()
    active_cat_id = first_cat.cat_id
    active_cat_name = first_cat.cat_name
    return dict(draft_id=draft_id,
                active_cat_id=active_cat_id,
                active_cat_name=active_cat_name)
Esempio n. 43
0
def create_survey():
    def f(form):
        form.vars.results = [0] * len(request.vars.choices)

    from gluon.utils import web2py_uuid
    db.survey.uuid.default = uuid = web2py_uuid()
    form = SQLFORM(db.survey).process(onvalidation=f)
    if form.accepted:
        redirect(URL('take_survey', args=uuid))
    return locals()
Esempio n. 44
0
def issues():
    project = db.project(request.args(0)) or redirect(URL('projects'))
    status = request.args(2)
    #TODO- show issues of the subprojects
    query = (db.issue.project == project.id) & (db.issue.is_last == True)
    if (request.args(1)):
        query = query & (db.issue.super_issue == request.args(1))
    if not status or status == 'Open':
        query = query & (db.issue.status.belongs(
            ['New', 'Assigned', 'Accepted', 'Started']))
    elif status == 'Closed':
        query = query & (db.issue.status.belongs(
            ['Fixed', 'Verified', 'Invalid', 'Duplicate', 'WontFix', 'Done']))
    elif status != 'All':
        query = query & (db.issue.status == status)
    """comment"""
    from gluon.utils import web2py_uuid
    db.issue.project.default = project.id
    db.issue.uuid.default = web2py_uuid()
    db.issue.is_last.default = True
    db.issue.owner.default = project.created_by.email
    db.issue.description.default = DESCRIPTION
    db.issue.labels.represent = lambda v, r: ', '.join(v or [])
    if not auth.user or not (
        auth.user.id == project.created_by or \
            auth.user.email in (project.members_email or [])):
        db.issue.owner.writable = False
        db.issue.status.writable = False
    FIELDS = (
        db.issue.id,
        db.issue.uuid,
        db.issue.status,
        db.issue.summary,
        db.issue.created_on,
        db.issue.author,
        db.issue.labels,
    )
    LINKS = [
        lambda row: A('Details', _href=URL('issue', args=row.uuid)),
        lambda row: A('Sub-issues',
                      _href=URL('issues', args=[project.id, row.id])),
        lambda row2: A('Assignment', _href=URL('assign', args=row2.id)),
        lambda row3: A('Escalate', _href=URL('escalate', args=row3.id))
    ]
    grid = SQLFORM.grid(
        query,
        fields=FIELDS,
        links=LINKS,
        details=False,
        editable=False,
        deletable=project.created_on == auth.user_id,
        create=auth.user_id,
        args=[project.id],
        oncreate=lambda form: do_mail([db.issue(form.vars.id)]))
    return dict(grid=grid, project=project)
Esempio n. 45
0
def show_comments():
    draft_id = gluon_utils.web2py_uuid()
    disc_id = request.args(0)
    user_id = auth.user_id
    rows = db(db.discs.disc_id == disc_id).select(db.discs.ALL)
    first_disc = rows.first()
    disc_name = first_disc.disc_name
    return dict(draft_id=draft_id,
                disc_name=disc_name,
                disc_id=disc_id,
                user_id=user_id)
Esempio n. 46
0
def create_survey3():
    def f(form):
        #form.vars.results = [0]*len(request.vars.choices)
        form.vars.results = request.vars.choices
    from gluon.utils import web2py_uuid,time
    db.survey.uuid.default = uuid = web2py_uuid()
    form = SQLFORM(db.survey).process(session=None, formname='test',onvalidation=f)
    if form.accepted:
        time.sleep(5)
        redirect(URL('thank_you',args=uuid))
    return locals()
Esempio n. 47
0
def index():
    """
    Description: Controller for the home page.
    Returns: a redirect to the splash page if not logged in or a list of the devices + UUID to index.html if you are.
    """
    if auth.user_id is None:
        redirect(URL('default', 'login.html'))
        return dict(message=T('Please sign in!'))
    else:
        sign_uuid = gluon_utils.web2py_uuid()
        device_list = db().select(db.device.ALL)
        return dict(device_list=device_list, sign_uuid=sign_uuid)
Esempio n. 48
0
    def __init__(self, **kwargs):

        self.__id = kwargs.get('id') if 'id' in kwargs else web2py_uuid(
        )  # uid to debug instance creation - not commited in DB
        self.__creation_datetime = kwargs.get('creation_datetime')
        self.__product = kwargs.get('product')
        self.__kind_of_work = kwargs.get('kind_of_work')
        self.__cpe = kwargs.get('cpe')
        self.__ppe = kwargs.get('ppe')
        self.__nb_exposure = kwargs.get('nb_exposure')
        self.__exposure_time = kwargs.get('exposure_time')
        self.__simultaneous_risk = kwargs.get('simultaneous_risk')
Esempio n. 49
0
def show_cat():
    draft_id = gluon_utils.web2py_uuid()
    cat_id = request.args(0)
    rows = db(db.cats.cat_id == cat_id).select(db.cats.ALL)
    first_cat = rows.first()
    cat_name = first_cat.cat_name
    user_id = auth.user_id
    response.flash = T(cat_name)
    return dict(draft_id=draft_id,
                cat_name=cat_name,
                cat_id=cat_id,
                user_id=user_id)
Esempio n. 50
0
def app_create(app, request, force=False, key=None, info=False):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    path = apath(app, request)
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except:
            if info:
                return False, traceback.format_exc(sys.exc_info)
            else:
                return False
    elif not force:
        if info:
            return False, "Application exists"
        else:
            return False
    try:
        w2p_unpack('welcome.w2p', path)
        for subfolder in [
                'models', 'views', 'controllers', 'databases', 'modules',
                'cron', 'errors', 'sessions', 'cache', 'languages', 'static',
                'private', 'uploads'
        ]:
            subpath = os.path.join(path, subfolder)
            if not os.path.exists(subpath):
                os.mkdir(subpath)
        db = os.path.join(path, 'models', 'db.py')
        if os.path.exists(db):
            data = read_file(db)
            data = data.replace('<your secret key>',
                                'sha512:' + (key or web2py_uuid()))
            write_file(db, data)
        if info:
            return True, None
        else:
            return True
    except:
        rmtree(path)
        if info:
            return False, traceback.format_exc(sys.exc_info)
        else:
            return False
Esempio n. 51
0
def app_create(app, request, force=False, key=None, info=False):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    path = apath(app, request)
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except:
            if info:
                return False, traceback.format_exc(sys.exc_info)
            else:
                return False
    elif not force:
        if info:
            return False, "Application exists"
        else:
            return False
    try:
        w2p_unpack('welcome.w2p', path)
        for subfolder in [
            'models', 'views', 'controllers', 'databases',
            'modules', 'cron', 'errors', 'sessions', 'cache',
            'languages', 'static', 'private', 'uploads']:
            subpath = os.path.join(path, subfolder)
            if not os.path.exists(subpath):
                os.mkdir(subpath)
        db = os.path.join(path, 'models', 'db.py')
        if os.path.exists(db):
            data = read_file(db)
            data = data.replace('<your secret key>',
                                'sha512:' + (key or web2py_uuid()))
            write_file(db, data)
        if info:
            return True, None
        else:
            return True
    except:
        rmtree(path)
        if info:
            return False, traceback.format_exc(sys.exc_info)
        else:
            return False
Esempio n. 52
0
    def __init__(self, id=None, new_person=True, **kwargs):

        self.__uuid = web2py_uuid(
        )  # uid to debug instance creation - not present in DB
        self.__new_person = new_person  # flag to help user creation/update - not present in DB
        self.__id = id  # id not inserted in DB in the commit method
        self.__first_name = kwargs.get('first_name')
        self.__last_name = kwargs.get('last_name')
        self.__email = kwargs.get('email')
        self.__contact = kwargs.get('contact')
        self.__password = str(int(
            time())) + '-' + web2py_uuid()  # generating a random password
        self.__password_key = str(int(
            time())) + '-' + web2py_uuid()  # generating a random password key
        self.__registration_key = kwargs.get(
            'registration_key') if 'registration_key' in kwargs else ''
        self.__creation_date = datetime.now()
        self.__virtual = kwargs.get(
            'virtual') if 'virtual' in kwargs else False
        self.__archive = False  # a user is never deleted but archived
        self.__creator = kwargs.get(
            'creator'
        )  # lambda that returns a PERSON instance - see the get_creator method
        self.__permissions = kwargs.get(
            'permissions') if 'permissions' in kwargs else [
            ]  # lambda that returns a [ PERMISSIONS ]
        self.__entities = kwargs.get('entities') if 'entities' in kwargs else [
        ]  # lambda that returns a [ ENTITIES ]
        self.__exposure_cards = kwargs.get(
            'exposure_cards') if 'exposure_cards' in kwargs else [
            ]  # lambda that returns a [ EXPOSURE_CARD ]
        self.__has_product_in_active_exposure_card = kwargs.get(
            'has_product_in_active_exposure_card')

        self.__compute_nb_storage_card = kwargs.get(
            'compute_nb_storage_card')  # lambda that returns a int
        self.__compute_nb_archived_storage_card = kwargs.get(
            'compute_nb_archived_storage_card')  # lambda that returns a int
Esempio n. 53
0
 def _add_content(self, name, target_el):
     T = current.T
     form = SQLFORM.factory(
         Field('content_type',
               requires=IS_IN_SET(self.settings.content_types.keys(), zero=None)),
         submit_button=T('Submit'),
     )
     from gluon.utils import web2py_uuid
     form.components += [INPUT(_type='hidden', _name=self.keyword, _value=name),
                INPUT(_type='hidden', _name='_action', _value='show_add_content'),
                INPUT(_type='hidden', _name='_target_el', _value=target_el),
                INPUT(_type='hidden', _name='_name', _value=web2py_uuid()),
                ]
     return form
Esempio n. 54
0
    def app_with_logging(environ, responder):
        """
        a wsgi app that does logging and profiling and calls wsgibase
        """
        status_headers = []

        def responder2(s, h):
            """
            wsgi responder app
            """
            status_headers.append(s)
            status_headers.append(h)
            return responder(s, h)

        time_in = time.time()
        ret = [0]
        if not profiler_dir:
            ret[0] = wsgiapp(environ, responder2)
        else:
            import cProfile
            prof = cProfile.Profile()
            prof.enable()
            ret[0] = wsgiapp(environ, responder2)
            prof.disable()
            destfile = pjoin(profiler_dir, "req_%s.prof" % web2py_uuid())
            prof.dump_stats(destfile)

        try:
            today = datetime.datetime.today()
            line = '%s, %s, %s, %s, %s, %s, %f\n' % (
                environ['REMOTE_ADDR'],
                '%s.%03d' % (today.strftime('%Y-%m-%d %H:%M:%S'),
                             int(today.microsecond / 1000)),
                environ['REQUEST_METHOD'],
                '%s://%s:%s%s' %
                (environ['wsgi.url_scheme'], environ['HTTP_HOST'],
                 environ['SERVER_PORT'], environ['REQUEST_URI']),
                environ['SERVER_PROTOCOL'],
                (status_headers[0])[:3],
                time.time() - time_in,
            )
            if not logfilename:
                sys.stdout.write(line)
            elif isinstance(logfilename, str):
                write_file(logfilename, line, 'a')
            else:
                logfilename.write(line)
        except:
            pass
        return ret[0]
Esempio n. 55
0
def create_survey3():
    def f(form):
        #form.vars.results = [0]*len(request.vars.choices)
        form.vars.results = request.vars.choices

    from gluon.utils import web2py_uuid, time
    db.survey.uuid.default = uuid = web2py_uuid()
    form = SQLFORM(db.survey).process(session=None,
                                      formname='test',
                                      onvalidation=f)
    if form.accepted:
        time.sleep(5)
        redirect(URL('thank_you', args=uuid))
    return locals()
Esempio n. 56
0
def copy_model():
    model_id = request.vars.model_id
    m_list = db(db.model.model_id == request.vars.model_id).select()
    m = m_list.__getitem__(0)

    db.model.insert(name=m.name,
                    description=m.description,
                    tag_list=m.tag_list,
                    mesh_list=m.mesh_list,
                    thumbnail_image=m.thumbnail_image,
                    last_edited=datetime.utcnow(),
                    model_id=gluon_utils.web2py_uuid())

    response.flash=T('Model "' + m.name + '" has been saved to your profile.')
Esempio n. 57
0
def view_listing():
    if auth.user is None:
        my_username = ''
    else:
        my_username = auth.user.username

    q = db.bboard

    def generate_del_button(row):
        # If the record is ours, we can delete it.
        b = ''
        if auth.user_id == row.user_id:
            b = A('Delete', _class='btn', _href=URL('default', 'delete', args=[row.id]))
        return b

    def generate_edit_button(row):
        # If the record is ours, we can delete it.
        b = ''
        if auth.user_id == row.user_id:
            b = A('Edit', _class='btn', _href=URL('default', 'edit', args=[row.id]))
        return b

    def shorten_post(row):
        return row.bbmessage[:50] + '...'

    # Creates extra buttons.

    links = [
        dict(header='', body = generate_del_button),
        dict(header='', body = generate_edit_button),
        ]

    if len(request.args) == 0:
        # We are in the main index.
        links.append(dict(header='Post', body = shorten_post))
        db.bboard.bbmessage.readable = False

    form = SQLFORM.grid(q,
        fields=[db.bboard.user_id, db.bboard.date_posted,
                db.bboard.category, db.bboard.title,
                db.bboard.bbmessage],
        editable=False, deletable=False,
        links=links,
        paginate=5,
        csv=False,
        create=False
        )
    draft_id = gluon_utils.web2py_uuid()
    return dict(my_username=my_username,form=form,draft_id=draft_id)
Esempio n. 58
0
def export():
    out = ''
    if not request.vars.format:
        return ''
    import os
    if app_config.get('export', 'tool') == 'inkscape':
        if request.vars.format in 'png pdf'.split():
            from gluon.tools import web2py_uuid
            import subprocess
            tmp_file = os.path.join(request.folder, 'static', web2py_uuid())
            open(tmp_file + '.svg', 'w').write(request.vars.svg_data)
            format_switch = '-A' if request.vars.format == 'pdf' else '-e'
            command = [
                app_config.get('inkscape', 'path'), "-f ", tmp_file + ".svg",
                format_switch, tmp_file + request.vars.format
            ]
            result = subprocess.call(command)
            if result == 1:  # stderr
                raise HTTP('inkscape call failed')
            out = open(tmp_file + request.vars.format, 'rb').read()
            os.unlink(tmp_file + '.svg')
            os.unlink(tmp_file + request.vars.format)
        else:
            raise HTTP(500, 'File Format Not Supported')

    elif app_config.get('export', 'tool') == 'java':
        if request.vars.format in 'png jpeg pdf tiff'.split():
            from subprocess import Popen, PIPE
            from shlex import split
            jar = os.path.join(request.folder, "static", "svg-export-0.2.jar")
            applet = app_config.get(
                'java',
                'path') + " -jar " + jar + " -si -so -f " + request.vars.format
            result = Popen(split(applet), stdin=PIPE, stdout=PIPE).communicate(
                request.vars.svg_data)  # call Ben's Java Exporter Applet
            out = result[0]  # stdout
            if result[1]:
                raise Exception(result[1])
            # print "image export errors: ", result[1]  # stderr
        else:
            raise HTTP(500, 'File Format Not Supported')

    import gluon.contenttype
    response.headers['Content-Type'] = gluon.contenttype.contenttype(
        "%s" % request.vars.format)
    filename = "%s.%s" % ('graph', request.vars.format)
    response.headers[
        'Content-disposition'] = "attachment; filename=\"%s\"" % filename
    return out
Esempio n. 59
0
 def _update_session_user(self, user):
     if global_settings.web2py_runtime_gae:
         user = Row(self.table_user()._filter_fields(user, id=True))
         delattr(user, self.settings.password_field)
     else:
         user = Row(user)
         for key in list(user.keys()):
             value = user[key]
             if callable(value) or key == self.settings.password_field:
                 delattr(user, key)
     current.session.auth = Storage(user=user,
                                    last_visit=current.request.now,
                                    expiration=self.settings.expiration,
                                    hmac_key=web2py_uuid())
     return user
Esempio n. 60
0
def login():
    response.headers['Access-Control-Allow-Origin'] = '*'
    username = request.vars.username
    h = hashlib.sha256(SECRET_KEY)
    h.update(request.vars.password)
    r = db((db.myuser.username == username)
           & (db.myuser.password == h.hexdigest())).select().first()
    if r is None:
        return response.json(dict(result='fail'))
    #Creates a new token
    if r.token is None:
        token = web2py_uuid()
        r.update_record(token=token)

    return response.json(dict(result='logged in', token=token))