def publictimeline(self): self.response.meta.title = "%s | %s" % ( self.db.T("Public timeline"), self.db.config.meta.title, ) query = (self.db.UserTimeLine.user_id == self.db.auth_user.id) & (self.db.auth_user.privacy == 1) #### pagination self.context.paginate_selector = PaginateSelector(paginates=(10, 25, 50, 100)) self.context.paginator = Paginator( paginate=self.context.paginate_selector.paginate) self.context.paginator.records = self.db(query).count() self.context.paginate_info = PaginateInfo( self.context.paginator.page, self.context.paginator.paginate, self.context.paginator.records) limitby = self.context.paginator.limitby() #### /pagination if 'limitby' in self.request.vars: limitby = [ int(item) for item in self.request.vars.limitby.split(',') ] self.get_timeline(query, limitby=limitby, public=True) #self.context.paginator.records = self.context.paginate_info.records = len(self.context.events) if self.db.request.args(0) == "sidebar": self.context.TIMELINEFUNCTIONS = '%s/app/person/sidebar_publictimeline_events.html' % self.context.theme_name else: self.context.TIMELINEFUNCTIONS = '%s/app/person/publictimeline_events.html' % self.context.theme_name
def most_popular(): paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) sounds = db(active_sounds).select(orderby=~Sounds.play_count, limitby=paginator.limitby()) paginator.records = len(sounds) return locals()
def search(self, q): self.response.meta.title = "%s | %s" % ( self.db.T("Search in members"), self.db.config.meta.title, ) self.contacts() self.context.results = [] if q: words = q.split() queries = [] for word in words: queries.append( self.db.auth_user.first_name.like("%" + word + "%")) queries.append( self.db.auth_user.last_name.like("%" + word + "%")) queries.append(self.db.auth_user.email.like("%" + word + "%")) queries.append( self.db.auth_user.nickname.like("%" + word + "%")) queries.append(self.db.auth_user.about.like("%" + word + "%")) queries.append(self.db.auth_user.tagline.like("%" + word + "%")) query = reduce(lambda a, b: (a | b), queries) finalquery = query & (self.db.auth_user.id != self.session.auth.user.id) & ( self.db.auth_user.is_active == True) #### pagination self.context.paginate_selector = PaginateSelector(paginates=(26, 50, 100)) self.context.paginator = Paginator( paginate=self.context.paginate_selector.paginate) self.context.paginator.records = self.db(finalquery).count() self.context.paginate_info = PaginateInfo( self.context.paginator.page, self.context.paginator.paginate, self.context.paginator.records) limitby = self.context.paginator.limitby() #### /pagination self.context.results = self.db(finalquery).select( orderby=~self.db.auth_user.id, limitby=limitby) from helpers.person import contact_box self.context.contact_box = contact_box qdefault = q if q and q != '@' else '' self.context.form = SQLFORM.factory(Field( 'q', default=qdefault, label=self.T("Search Term"), comment=self.T("In name, email, nickname, about")), formstyle='divs', _method="GET")
def playlist(): p = db(Profiles.user == auth.user_id).select().first() sounds = db(active_sounds & Sounds.id.belongs(p.playlist)).select() if p and p.playlist else [] paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) paginator.records = len(sounds) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) return locals()
def by_language(): paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) count = Sounds.id.count() sounds = db(active_sounds).select(Sounds.created_by, Sounds.download_server, Sounds.download_key, Sounds.language, count, orderby=~count, groupby=Sounds.language, limitby=paginator.limitby()) paginator.records = len(sounds) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) return locals()
def search(): paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) details_form=SQLFORM.factory( Field('category', requires=IS_EMPTY_OR(IS_IN_SET(categories))), Field('language', requires=IS_EMPTY_OR(IS_IN_SET(languages))), Field('keywords'), _name="detail-search", _class="form-horizontal" ) sounds = None if details_form.process(formname='detail-search', message_onsuccess="").accepted: query = active_sounds if details_form.vars.language: query &= Sounds.language==details_form.vars.language if details_form.vars.category: query &= Sounds.category==details_form.vars.category if details_form.vars.keywords: values = details_form.vars.keywords.split(" ") query &= Sounds.keywords.contains(values, all=False) sounds = db(query).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) paginator.records = len(sounds) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) return locals() if search_form.process(session=None, formname="master-search", message_onsuccess="").accepted and search_form.vars.query: values = search_form.vars.query.split(",") sounds = db(active_sounds & ( Sounds.title.contains(values, all=False) | Sounds.description.contains(values, all=False) | Sounds.keywords.contains(values, all=False))).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) else: if request.vars.user: sounds = db(active_sounds & (Sounds.created_by==request.vars.user)).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) elif request.vars.language: sounds = db(active_sounds & (Sounds.language==request.vars.language)).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) # display nothing if no search criteria (client's request) #else: # sounds = db(active_sounds).select(orderby=~Sounds.created_on, # limitby=paginator.limitby()) if not sounds: sounds = [] paginator.records = len(sounds) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) return locals()
def details(): detail_sound = Sounds(a0) or redirect(URL('index')) if not detail_sound.is_active: raise HTTP(404) query = active_sounds & (Sounds.created_by==detail_sound.created_by) detail_sound.update_record(play_count=(detail_sound.play_count or 0) + 1) paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) sounds = db(query).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) paginator.records = len(sounds) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) return locals()
def list(): """List all commands.""" # querying the database current_user_entities = [ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ] if 'request' in request.vars and request.vars['request'] == 'all': _query = db.command.entity.belongs(current_user_entities) elif 'request' in request.vars and request.vars['request'] == 'mine': _query = db.command.submitter == auth.user.id elif 'request' in request.vars and request.vars['request'] == 'new': status_id = db(db.command_status.label == 'New').select( db.command_status.id) _query = db.command.status.belongs( status_id) & db.command.entity.belongs(current_user_entities) elif 'request' in request.vars and request.vars['request'] == 'accepted': status_id = db(db.command_status.label == 'Accepted').select( db.command_status.id) _query = db.command.status.belongs( status_id) & db.command.entity.belongs(current_user_entities) else: status_id = db(db.command_status.state == 0).select( db.command_status.id) _query = db.command.status.belongs( status_id) & db.command.entity.belongs(current_user_entities) # pagination stuff paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=False) paginator.records = db(_query).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # querying the database _orderby = ~db.command.modification_datetime rows = db(_query).select(limitby=paginator.limitby(), orderby=_orderby) return dict(commands=rows, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def details(): detail_sound = Sounds(a0) or redirect(URL('index')) query = active_sounds & (Sounds.created_by == detail_sound.created_by) new_count = detail_sound.play_count or 0 + 1 detail_sound.update_record(play_count=new_count) paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=True) paginator.records = db(query).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) sounds = db(query).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) return locals()
def list(): ''' lists entities of the authenticated user ''' mylogger.debug(message='request.vars:%s' % request.vars) entity_mapper = ENTITY_MAPPER() person_mapper = PERSON_MAPPER() # getting the authenticated user auth_user = person_mapper.find(person_id=auth.user.id)[0] # pagination stuff paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=False) paginator.records = entity_mapper.count_all() if auth_user.is_all_entity() \ else auth_user.compute_nb_entities() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # if the authenticated user is in all entities (ie. 'all_entity' entity) # retrieving the whole entitities if auth_user.is_all_entity(): auth_user_entitites = entity_mapper.find(limitby=paginator.limitby()) # else getting the authenticated user entitities else: auth_user_entitites = entity_mapper.find(person_id=auth.user.id, limitby=paginator.limitby()) # adding the all_entity entity for the whole users auth_user_entitites.insert(0, entity_mapper.find(role='all_entity')[0]) mylogger.debug(message='auth_user_entitites:%s' % auth_user_entitites) # putting 'all_entity' at the top of the list auth_user_entitites = sorted( auth_user_entitites, key=lambda k: k.role if k.role != 'all_entity' else '0_%s' % k.role) return dict(entities=auth_user_entitites, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def usertimeline(self): if self.request.args(0): try: user = self.db.auth_user[int(self.request.args(0))] except Exception: user = self.db.auth_user(nickname=self.request.args(0)) else: user = self.db.auth_user[self.db.auth.user_id] self.context.user = user if self.request.extension == "html": if user: self.show(user.id) else: redirect(self.CURL('home', 'index')) if user: query = self.db.UserTimeLine.user_id == user.id #### pagination self.context.paginate_selector = PaginateSelector(paginates=(10, 25, 50, 100)) self.context.paginator = Paginator( paginate=self.context.paginate_selector.paginate) self.context.paginator.records = self.db(query).count() self.context.paginate_info = PaginateInfo( self.context.paginator.page, self.context.paginator.paginate, self.context.paginator.records) limitby = self.context.paginator.limitby() #### /pagination if 'limitby' in self.request.vars: limitby = [ int(item) for item in self.request.vars.limitby.split(',') ] self.get_timeline(query, limitby=limitby, public=user.privacy == 1) #self.context.paginator.records = self.context.paginate_info.records = len(self.context.events) self.response.meta.title = "%s | %s" % ( self.db.T("%s's timeline", user.nickname.title() or user.first_name.title()), self.db.config.meta.title, ) self.context.TIMELINEFUNCTIONS = '%s/app/person/usertimeline_events.html' % self.context.theme_name
def list(): # building the query _query = db.class_of_compounds _orderby = db.class_of_compounds.label # pagination stuff paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=False) paginator.records = db(_query).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # querying the database rows = db(_query).select(limitby=paginator.limitby(), orderby=_orderby) return dict(rows=rows, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def index_real(): paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=True) paginator.records = db(active_sounds).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) form = SQLFORM.factory(Field('query', default=T('Search'))) sounds = None if form.process(message_onsuccess="").accepted and form.vars.query: values = form.vars.query sounds = db(active_sounds).select(orderby=~Sounds.created_on, limitby=paginator.limitby()).find(lambda s: values.lower() in s.title.lower() or \ values.lower() in s.description.lower() or values.lower() in s.keywords.lower()) else: sounds = db(active_sounds).select(orderby=~Sounds.created_on, limitby=paginator.limitby()) return locals()
def index(): query = db.product.id > 0 ################################ The core ###################################### paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=True) paginator.records = db(query).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) rows = db(query).select(limitby=paginator.limitby()) ################################################################################ table = SOLIDTABLE(rows, renderstyle=True) return dict(table=table, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def privatetimeline(self): try: self.board(self.db.auth.user_id) except: redirect(self.CURL('home', 'index')) self.contacts() allowed = list(self.context.following_list) + list( self.context.contacts_list) allowed.append(self.session.auth.user.id) query = self.db.UserTimeLine.created_by.belongs(allowed) #### pagination self.context.paginate_selector = PaginateSelector(paginates=(10, 25, 50, 100)) self.context.paginator = Paginator( paginate=self.context.paginate_selector.paginate) self.context.paginator.records = self.db(query).count() self.context.paginate_info = PaginateInfo( self.context.paginator.page, self.context.paginator.paginate, self.context.paginator.records) limitby = self.context.paginator.limitby() #### /pagination if 'limitby' in self.request.vars: limitby = [ int(item) for item in self.request.vars.limitby.split(',') ] self.get_private_timeline(query, limitby=limitby) #self.context.paginator.records = self.context.paginate_info.records = len(self.context.events) if self.db.request.args(0) == "sidebar": self.context.TIMELINEFUNCTIONS = '%s/app/person/sidebar_privatetimeline_events.html' % self.context.theme_name else: self.context.TIMELINEFUNCTIONS = '%s/app/person/privatetimeline_events.html' % self.context.theme_name self.response.meta.title = "%s | %s" % ( self.db.T( "%s's private timeline", self.context.user.nickname.title() or self.context.user.first_name.title()), self.db.config.meta.title, )
def list(): ''' lists users that belongs to the same ENTITY as the authenticated user ''' mylogger.debug(message='request.vars:%s' %request.vars) person_mapper = PERSON_MAPPER() _person_id = auth.user.id # pagination stuff paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v': 1}, anchor='main', renderstyle=False) paginator.records = person_mapper.count_in_same_entity(person_id=_person_id) paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # getting the ENTITY PERSONs _persons = person_mapper.find_in_same_entity(person_id=_person_id, limitby=paginator.limitby()) return dict(persons=_persons, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def search(): mylogger.debug(message='request.vars:%s' % str(request.vars)) mylogger.debug(message='request.args:%s' % str(request.args)) # some init query_list = [] rows = None persons = None entities = None paginator = '' paginate_selector = '' paginate_info = '' nb_entries = 1 # number of results label = '' # request title, ie. "products in the Chemical Lab. page = int(request.vars['page']) if 'page' in request.vars else 0 result_per_page = int(request.vars['result_per_page'] ) if 'result_per_page' in request.vars else 10 connected_user_entity_ids = db( db.entity.id.belongs([ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ])).select(cacheable=True) # no way to pass the "keep_last_search" variable while clicking on a "x results per page" link if 'paginate' in request.vars: request.vars['keep_last_search'] = True # # restoring session vars if keep_last_search # if 'keep_last_search' in request.vars: if session.search_display_by: request.vars['display_by'] = session.search_display_by if session.search_person_id: request.vars['member'] = session.search_member if session.search_role: request.vars['role'] = session.search_role del request.vars['keep_last_search'] # # and then cleaning up request vars # for key in ['search_display_by', 'search_member', 'search_role']: if session.has_key(key): mylogger.debug(message='key:%s' % str(key)) mylogger.debug(message='session[key]:%s' % str(session[key])) del session[key] mylogger.debug(message='request.vars:%s' % str(request.vars)) # # display by entity or person # if 'display_by' in request.vars and request.vars['display_by'] == 'person': session.search_display_by = 'person' display_by_person = True else: display_by_person = False session.search_result_per_page = result_per_page session.search_page = page # # building the request # if 'member' in request.vars and request.vars['member'] != '': mylogger.debug(message='case 1') session.search_member = request.vars['member'] _person_entity_ids = db( db.entity.id.belongs([ _entity.id for _entity in ENTITY_MAPPER().find( person_id=request.vars['member']) ])).select(cacheable=True) _common_entity_ids = [ _id for _id in _person_entity_ids if _id in connected_user_entity_ids ] if len(_common_entity_ids) > 0: if display_by_person: query_list.append(db.person.id == request.vars['member']) else: query_list.append(db.entity.id.belongs(_common_entity_ids)) elif 'role' in request.vars and request.vars['role'] != '': mylogger.debug(message='case 2') session.search_role = request.vars['role'] if display_by_person: query_list.append( (db.entity.role.like('%s%%' % request.vars['role'].strip())) | (db.entity.role.like('%%%s%%' % request.vars['role'].strip()))) query_list.append( db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.group_id == db.entity.id) query_list.append(db.membership.user_id == db.person.id) else: query_list.append( (db.entity.role.like('%s%%' % request.vars['role'].strip())) | (db.entity.role.like('%%%s%%' % request.vars['role'].strip()))) query_list.append( db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.group_id == db.entity.id) else: mylogger.debug(message='case 3') if display_by_person: # Need to get users without entities #query_list.append(db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.user_id == db.person.id) else: query_list.append(db.entity.id.belongs(connected_user_entity_ids)) #request.vars['member'] = auth.user.id if len(query_list) != 0: finalQuery = query_list[0] for query in query_list[1:]: mylogger.debug(message='query:%s' % str(query)) finalQuery = finalQuery.__and__(query) mylogger.debug(message='finalQuery:%s' % str(finalQuery)) if display_by_person: _distinct = db.person.id else: _distinct = db.entity.id # # pagination # range_min = page * result_per_page range_max = range_min + result_per_page mylogger.debug(message='page:%s' % page) mylogger.debug(message='result_per_page:%s' % result_per_page) mylogger.debug(message='range_min:%s' % range_min) mylogger.debug(message='range_min:%s' % range_max) theset = db(finalQuery) nb_entries = theset.count(distinct=_distinct) mylogger.debug(message='nb_entries:%i' % nb_entries) paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'keep_last_search': True}, anchor='main', renderstyle=False) paginator.records = nb_entries paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # # executing the query # _limitby = paginator.limitby() if display_by_person: _orderby = db.person.email select_fields = [db.person.ALL] else: _orderby = db.entity.role select_fields = [db.entity.ALL] allrows = theset.select(*select_fields, orderby=_orderby, distinct=True, limitby=_limitby, cacheable=True) rows = allrows mylogger.debug(message='len(rows):%s' % len(rows)) for row in rows: mylogger.debug(message='row:%s' % row) if len(rows) > 0: if not display_by_person: entities = ENTITY_MAPPER().find( entity_id=[row.id for row in rows], orderby=_orderby) mylogger.debug(message='len(entities):%s' % len(entities)) else: persons = PERSON_MAPPER().find( person_id=[row.id for row in rows], orderby=_orderby) mylogger.debug(message='len(persons):%s' % len(persons)) # # building the search form # db.entity.role.widget = SQLFORM.widgets.string.widget #db.person.email.widget=CHIMITHEQUE_MULTIPLE_widget(db.person.email, configuration={'*': {'disable_validate': True}}) # prepopulating form values + default values in the following form declaration db.entity.role.default = request.vars['role'] #db.person.email.default = request.vars['member'] db.entity.role.label = cc.get_string('SEARCH_ENTITY_NAME') #db.person.email.label = cc.get_string('SEARCH_PERSON_EMAIL') form = SQLFORM.factory( db.entity.role, Field('member', 'reference person', default=request.vars['member'], label=cc.get_string('SEARCH_ENTITY_MEMBER'), widget=CHIMITHEQUE_MULTIPLE_widget( db.person.email, configuration={'*': { 'disable_validate': True }})), _action='/%s/%s/search' % (request.application, request.controller), submit_button=cc.get_string("SEARCH")) return dict(form=form, persons=persons, entities=entities, nb_entries=nb_entries, label=label, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def board(self, uid, post_id=None): self.context.extrajs = "" if self.request.vars.reply: try: self.context.reply = self.db.UserBoard[self.request.vars.reply] self.db.UserBoard.parent_id.default = self.context.reply.id except Exception: self.context.reply = [] else: self.context.reply = [] if self.request.extension == 'html': self.show(uid) T = self.T try: user = self.db.auth_user[int(uid)] except Exception: user = self.db.auth_user(nickname=uid) self.context.user = user if user: self.response.meta.title = "%s | %s" % ( self.db.T("%s's board", user.nickname.title() or user.first_name.title()), self.db.config.meta.title, ) self.db.UserBoard.user_id.default = user.id self.db.UserBoard.writer.default = self.session.auth.user.id if self.session.auth else 0 relation = self.db.UserContact._relation( self.session.auth.user.id if self.session.auth else 0, user.id) self.context.relation = relation if relation == "yourself": board_text_label = T("Whats up?") elif relation in ["contacts", "follower"]: board_text_label = T("Write something on %s's board", user.nickname) if relation in ['contacts', 'yourself', 'follower']: #self.db.UserBoard.board_text.label = CAT(board_text_label, A(T(" add photo "), _onclick="alert('Sorry, Photo upload is under development!');")) self.db.UserBoard.board_text.label = board_text_label self.context.form = SQLFORM(self.db.UserBoard, formstyle='divs', submit_button=T('Post'), separator='')\ .process(onsuccess=lambda form: self.board_posted(form, user, relation)) else: self.context.form = '' self.db.UserBoard.replies = Field.Lazy(lambda row: self.db( self.db.UserBoard.parent_id == row.user_board.id).select( orderby=~self.db.UserBoard.created_on, limitby=(0, 10))) query = (self.db.UserBoard.user_id == user.id) & (self.db.UserBoard.parent_id == 0) if post_id: query = query & (self.db.UserBoard.id == post_id) self.context.form = self.context.paginate_selector = \ self.context.paginator = self.context.paginate_info = "" limitby = None else: #### pagination self.context.paginate_selector = PaginateSelector(paginates=(10, 25, 50, 100)) self.context.paginator = Paginator( paginate=self.context.paginate_selector.paginate) self.context.paginator.records = self.db(query).count() self.context.paginate_info = PaginateInfo( self.context.paginator.page, self.context.paginator.paginate, self.context.paginator.records) limitby = self.context.paginator.limitby() #### /pagination if 'limitby' in self.request.vars: limitby = [ int(item) for item in self.request.vars.limitby.split(',') ] if self.context.user.privacy != 1 and \ relation not in ['contacts', 'follower', 'yourself'] and \ not self.db.auth.has_membership("admin", self.db.auth.user_id): self.view = 'app/person/board_private' self.context.board = [] else: self.view = 'app/person/board' self.context.board = self.db(query).select( orderby=~self.db.UserBoard.created_on, limitby=limitby)
def __call__( self, query, fields=None, field_id=None, left=None, headers={}, columns=None, orderby=None, # EXTENDED for permutation searchable=True, # EXTENDED ex) [table.id, table.name, ...] sortable=True, # EXTENDED ex) [table.id, table.name, ...] paginate=(10, 25, 50, 100), # EXTENDED deletable=True, editable=True, # EXTENDED ex) [['id', 'name'], 'profile', ...] details=True, # EXTENDED ex) [['id', 'name'], 'profile', ...] selectable=None, # TODO create=True, # EXTENDED ex) [['id', 'name'], 'profile', ...] csv=True, links=None, upload='<default>', args=[], user_signature=True, maxtextlengths={}, # NOT WORK maxtextlength=20, onvalidation=None, oncreate=None, onupdate=None, ondelete=None, sorter_icons=('[^]', '[v]'), # NOT WORK ui='ui', # ONLY WORK FOR "ui" showbuttontext=True, _class="web2py_grid", formname='web2py_grid', search_widget='default', # NOT WORK extracolumns=None, # CUSTOM (same as in SQLTABLE) search_queries={}, # CUSTOM showid=True, # CUSTOM onpermute=None, # CUSTOM virtualtable=None, # CUSTOM virtualrecord=None, # CUSTOM virtualset=None, # CUSTOM hmac_key=None, # CUSTOM scope=None, #CUSTOM scope_default=None, #CUSTOM groupby=None, #CUSTOM ): from gluon.dal import SQLALL from plugin_solidform import SOLIDFORM from plugin_solidtable import SOLIDTABLE, OrderbySelector from plugin_paginator import Paginator, PaginateSelector, PaginateInfo gridbutton = self.gridbutton recordbutton = self.recordbutton request, session, T = current.request, current.session, current.T def __oncreate(form): session.flash = T('Created') def __onupdate(form): session.flash = T('Updated') def __ondelete(table, tablename, ret): session.flash = T('Deleted') def __onpermute(table, tablename, ret): session.flash = T('Permuted') def redirect_patch(): onupdate oncreate = oncreate or __oncreate onupdate = onupdate or __onupdate ondelete = ondelete or __ondelete onpermute = onpermute or __onpermute if ui == 'ui': ui = dict( widget='', header='', content='', default='', cornerall='', cornertop='', cornerbottom='', button='', buttontext='', buttonadd='ui-icon-plusthick', buttonback='ui-icon-arrowreturnthick-1-w', buttonexport='', buttondelete='ui-icon-close', buttonedit='ui-icon-pencil', buttontable='', buttonview='ui-icon-zoomin', ) elif not isinstance(ui, dict): raise RuntimeError, 'SQLFORM.grid ui argument must be a dictionary' wenabled = (not user_signature or (session.auth and session.auth.user)) deletable = wenabled and deletable # if search_widget=='default': # search_widget = SQLFORM.search_menu url = self.url_factory(args, user_signature, hmac_key) db = query._db dbset = db(query) tables = [ db[tablename] for tablename in db._adapter.tables(dbset.query) ] if not fields: fields = reduce(lambda a, b: a + b, [[field for field in table] for table in tables]) new_fields = [] for item in fields: if isinstance(item, SQLALL): new_fields += item.table else: new_fields.append(item) fields = new_fields main_table = tables[0] if not field_id: field_id = main_table._id table = field_id.table tablename = table._tablename referrer = session.get('_web2py_grid_referrer_' + formname, url()) def __from_process_redirect_patch(func): def wrapper(form): func(form) redirect(referrer) return wrapper oncreate = __from_process_redirect_patch(oncreate) onupdate = __from_process_redirect_patch(onupdate) def check_authorization(): if user_signature or hmac_key: if not URL.verify(request, user_signature=user_signature, hmac_key=hmac_key): session.flash = T('not authorized') redirect(referrer) if upload == '<default>': upload = lambda filename: url(args=['download', filename]) if len(request.args) > 1 and request.args[-2] == 'download': check_authorization() stream = response.download(request, db) raise HTTP(200, stream, **response.headers) gridbuttons = [gridbutton('%(buttonback)s' % ui, T('Back'), referrer)] if create and len(request.args) > 1 and request.args[-2] == 'new': check_authorization() table = db[request.args[-1]] self.mark_not_empty(virtualtable or table) if orderby: inverted = (orderby.op == orderby.db._adapter.INVERT) field = orderby.first if inverted else orderby last = dbset.select( field_id, field, limitby=(0, 1), orderby=orderby.first if inverted else ~orderby).first() last_value = (last[field] or 0) if last else 0 table[field.name].default = (-1 if inverted else 1) + last_value create_form = SOLIDFORM( virtualtable or table, fields=create if type(create) in (list, tuple) else None, showid=showid, _class='web2py_form', submit_button=T('Create'), ).process( # next=referrer, for web2py-bug onvalidation=onvalidation, onsuccess=oncreate, formname=formname) self.unmark_not_empty(table) res = DIV(create_form, _class=_class) res.create_form = create_form res.gridbuttons = gridbuttons return res elif details and len(request.args) > 2 and request.args[-3] == 'view': check_authorization() table = db[request.args[-2]] record = table(request.args[-1]) or redirect(URL('error')) form = SOLIDFORM(virtualtable or table, virtualrecord or record, fields=details if type(details) in (list, tuple) else create if type(create) in (list, tuple) else None, upload=upload, readonly=True, showid=showid, _class='web2py_form') res = DIV(form, _class=_class) res.record = record # CUSTOM res.view_form = form # CUSTOM if editable: gridbuttons.append( gridbutton('%(buttonedit)s' % ui, T('Edit'), url(args=['edit', tablename, record.id]))) res.gridbuttons = gridbuttons return res elif editable and len(request.args) > 2 and request.args[-3] == 'edit': check_authorization() table = db[request.args[-2]] record = table(request.args[-1]) or redirect(URL('error')) self.mark_not_empty(virtualtable or table) edit_form = SOLIDFORM( virtualtable or table, virtualrecord or record, fields=editable if type(editable) in (list, tuple) else create if type(create) in (list, tuple) else None, upload=upload, deletable=deletable, showid=showid, delete_label=T('Check to delete:'), submit_button=T('Update'), _class='web2py_form') self.unmark_not_empty(table) edit_form.process( formname=formname, onvalidation=onvalidation, onsuccess=onupdate, # #next=referrer, for web2py-bug ) res = DIV(edit_form, _class=_class) res.record = record # CUSTOM res.edit_form = edit_form if details: gridbuttons.append( gridbutton('%(buttonview)s' % ui, T('View'), url(args=['view', tablename, record.id]))) res.gridbuttons = gridbuttons return res elif deletable and len( request.args) > 2 and request.args[-3] == 'delete': check_authorization() table = db[request.args[-2]] ret = db(table.id == request.args[-1]).delete() if ondelete: ondelete(table, request.args[-1], ret) redirect(url()) elif csv and len(request.args) > 0 and request.args[-1] == 'csv': check_authorization() return dict() elif request.vars.records and not isinstance(request.vars.records, list): request.vars.records = [request.vars.records] elif not request.vars.records: request.vars.records = [] session['_web2py_grid_referrer_' + formname] = URL( r=request, args=request.args, vars=request.vars, user_signature=user_signature, hmac_key=hmac_key) error = None search_form = None table_el_id = formname + '_maintable' columns = columns or [ str(f) for f in fields if f.table == main_table and f.readable and (showid or f.type != 'id') ] if searchable: field_sep = '___' if searchable is True: _exclude_types = ('upload', 'text') if showid else ('id', 'upload', 'text') searchable = [ f for f in fields if f.table == main_table and f.type not in _exclude_types and f.readable ] _search_fields = [] _from_tos = [] for f in searchable: _requires = [] if f.requires and type(f.requires) not in (list, tuple): if isinstance(f.requires, IS_EMPTY_OR): _requires = [f.requires.other] else: _requires = [f.requires] _requires = [ r for r in _requires if not isinstance(r, IS_NOT_IN_DB) ] if _requires: if len(_requires) == 1: _requires = _requires[0] _requires = IS_EMPTY_OR(_requires) else: _requires = None _type = 'string' if f.type == 'text' else 'integer' if f.type == 'id' else f.type if (f.type in ('double', 'decimal', 'date', 'datetime') or (f.type == 'integer' and _requires and isinstance(_requires.other, (IS_INT_IN_RANGE)))): _from_to = [ Field(str(f).replace('.', field_sep) + field_sep + 'from', type=_type, requires=_requires, label=f.label, widget=f.widget), Field(str(f).replace('.', field_sep) + field_sep + 'to', type=_type, requires=_requires, label=f.label, widget=f.widget) ] _from_tos.append(_from_to) _search_fields += _from_to elif hasattr(f, 'table'): _search_fields.append( Field(str(f).replace('.', field_sep), type=_type, requires=_requires, label=f.label, widget=f.widget)) else: _search_fields.append(f) search_form = SQLFORM.factory(formstyle='divs', submit_button=T('Search'), _class='search_form', *_search_fields) for _from_to in _from_tos: self.inline(search_form, 'no_table', [f.name for f in _from_to], LABEL(_from_to[0].label), SPAN(' - ')) subquery = self.build_query_by_form(db, search_form, queries=search_queries, field_sep=field_sep, formname='search_%s' % formname) else: subquery = None if subquery: dbset = dbset(subquery) if scope: from plugin_tablescope import TableScope scope_el = TableScope(dbset, scope, default=scope_default) dbset = scope_el.scoped_dataset if sortable is True: sortable = [ ~f if f.type in ('id', 'date', 'datetime') else f for f in fields if f.table == main_table and f.type not in ('text', 'upload') ] if not sortable: sortable = [] if orderby: sortable.insert(0, orderby) orderby_selector = OrderbySelector(sortable) current_orderby = orderby_selector.orderby() permutable = (orderby and (not subquery) and sortable and current_orderby is sortable[0]) extracolumns = extracolumns or [] if permutable: if len(request.args) > 2 and request.args[-3] in ('up', 'down'): check_authorization() table = db[request.args[-2]] record = table(request.args[-1]) or redirect(URL('error')) inverted = (orderby.op == orderby.db._adapter.INVERT) field = orderby.first if inverted else orderby current_value = record[field] if current_value is None: first = dbset.select(field_id, limitby=(0, 1), orderby=orderby).first() current_value = (1 if inverted else -1) + (first.id if first else 0) if (request.args[-3] == ('down' if inverted else 'up')): target = dbset(field < current_value).select( field_id, field, limitby=(0, 1), orderby=orderby if inverted else ~orderby).first() elif (request.args[-3] == ('up' if inverted else 'down')): target = dbset(field > current_value).select( field_id, field, limitby=(0, 1), orderby=orderby.first if inverted else orderby).first() else: raise NotImplementedError if not target: last = dbset.select(field_id, limitby=(0, 1), orderby=orderby.first if orderby.first else ~orderby).first() target_value = (-1 if inverted else 1) + (last.id if last else 0) else: target_value = target[field] db(table.id == record[field_id]).update( **{field.name: target_value}) if target: db(table.id == target[field_id]).update( **{field.name: current_value}) if onpermute: onpermute(table, request.args[-2], (record, target)) redirect(url()) first = dbset.select(field_id, limitby=(0, 1), orderby=orderby).first() first_id = first.id if first else 0 last = dbset.select( field_id, limitby=(0, 1), orderby=orderby.first if orderby.first else ~orderby).first() last_id = last.id if last else 0 extracolumns.append({ 'label': DIV(T('Move'), _style='text-align:center;'), 'width': '150px' if showbuttontext else '65px', 'content': lambda row, rc: DIV( recordbutton('ui-icon-triangle-1-n', T('Up'), url(args=['up', tablename, row[field_id]]), showbuttontext) if row[field_id] != first_id else '', recordbutton('ui-icon-triangle-1-s', T('Down'), url(args=['down', tablename, row[field_id]]), showbuttontext) if row[field_id] != last_id else '', _style='text-align:center;') }) _size = 80 if showbuttontext else 25 _size = _size * (int(bool(details)) + int(bool(editable)) + int(bool(deletable))) if _size: extracolumns.append({ 'label': '', 'width': '%spx' % (_size + 12), 'content': lambda row, rc: DIV( recordbutton('%(buttonview)s' % ui, T('View'), url(args=['view', tablename, row[field_id]]), showbuttontext) if details else '', recordbutton('%(buttonedit)s' % ui, T('Edit'), url(args=['edit', tablename, row[field_id]]), showbuttontext) if editable else '', recordbutton( '%(buttondelete)s' % ui, T('Delete'), url(args=['delete', tablename, row[field_id]]), showbuttontext, _onclick=""" if(confirm("%s")){return true;} else {jQuery(this).unbind('click').fadeOut();return false;}""" % T('Sure you want to delete them?'), ) if deletable else '') }) if paginate: paginate_selector = PaginateSelector(paginate if type(paginate) in (list, tuple) else [paginate]) current_paginate = paginate_selector.paginate paginator = Paginator(paginate=current_paginate) # TODO for groupby paginator.records = virtualset( dbset.query).count() if virtualset else dbset.count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) limitby = paginator.limitby() else: limitby = None current_paginate = None # TODO # if paginator.records == 0: # error = 'Not Found' if virtualset: records = virtualset(dbset.query).select(left=left, limitby=limitby, orderby=current_orderby, groupby=groupby, *fields) records.db = virtualtable._db else: records = dbset.select(left=left, limitby=limitby, orderby=current_orderby, groupby=groupby, *fields) table = SOLIDTABLE( records, columns=columns, headers=headers, orderby=orderby_selector, truncate=maxtextlength, #TODO replace extracolumns=extracolumns, upload=upload) table.attributes['_class'] = 'solidtable' table.attributes['_id'] = table_el_id inner = [] if scope: inner.append(scope_el) if current_paginate: inner.append(DIV(paginate_info, _class='pagination_information')) inner.append(table) if current_paginate and paginator.records > current_paginate: inner.append( DIV(paginate_selector, paginator, _class='index_footer')) res = DIV(_class=_class, *inner) res.records = records res.search_form = search_form res.error = error res.gridbuttons = [] if create: res.gridbuttons.append( gridbutton('%(buttonadd)s' % ui, T('Add'), url(args=['new', tablename]))) return res