def show_conf(request): #route('/conf', 'GET') """Показывает список дизайнерских документов""" if get_const_value(request, 'is_admin') == "false" and not is_admin(request): return web.HTTPSeeOther('/') if not user_is_logged_in(request): return web.HTTPSeeOther('/login') all_docs = []; all_rbs = []; ss = []; all_menu = [] special = ['des:users', 'des:report_pe', 'des:conf', 'des:role'] # выводим справочники и документы из документа прослойки. for res in request.db.map.find({"conf.turn":"true", '$or':[{"conf.owner":None}, {"conf.owner":'_'}], "conf.is_doc":True} ): if user_has_permission(request, res['_id'], 'view'): all_docs.append(res) for res in request.db.map.find({"conf.turn":"true", '$or':[{"conf.owner":None}, {"conf.owner":'_'}], "conf.is_doc":False}): if not res['_id'] in special and user_has_permission(request, res['_id'], 'view'): all_rbs.append(res) # выводим настроечные кнопки которые справа. for res in get_ss(request): if user_has_permission(request, res['id'], 'view'): res['id'] = res['id'][:2]+'_'+res['id'][3:] ss.append(res) # выводим кнопки работы с меню. for res in request.db.tree.find({'sub_type':'menu'}): if user_has_permission(request, res['_id'], 'view'): all_menu.append(res) url = request.scheme + '://' + request.host # return templ('libs.admin:conf', request, dict(url = url, all_docs = all_docs, all_rbs = all_rbs, all_menu = all_menu, ss = ss) ) tree = [] for res in request.db.doc.find({"doc_type":"des:left_menu"}): tree.append(res) val_tree = form_tree_comm(request, tree) # print( request.__dict__) return templ('libs.admin:admin', request, dict(url = url, all_docs = all_docs, all_rbs = all_rbs, all_menu = all_menu, ss = ss, tree=val_tree) )
def conf_post(request): """show list design docs""" data = get_post(request) data = json.loads(data['data']) if not user_is_logged_in(request): return user_not_logged(request) if 'action' in request.POST: action = request.POST['action'] if action == 'create_rb': if not user_has_permission(request, 'ss:work_rb', 'view'): return 'You have no permission.' owner = data['rb_id'] return add_ref(data, owner) if action == 'del_rb': if not user_has_permission(request, 'ss:work_rb', 'view'): return 'You have no permission.' rb_id = data['rb_id'] is_del_doc = 'is_del_doc' in request.POST return del_ref(rb_id, is_del_doc) if action == 'create_role': if not user_has_permission(request, 'ss:work_rb', 'view'): return 'You have no permission.' return add_role(data) return 'action 404'
def save_tags(request, doc, tag_dict): """ разбиваем строчку тегов в масив и заносим в документ правильно разбитые теги call the function that fills in the tag cloud tag_dict - справочник из которого теги сохраняются вроде как удалено из текста 1) check that the document contains tags 2) разбиваем строку тегов на слова через запятую и запихиваем в словарь tags = {'tag1':1,'tag2':1} """ # TODO если теги пустые то мы их не стираем lang = cur_lang(request) if 'doc' in doc and doc['doc'] and 'tags' in doc['doc'] and doc['doc']['tags']: if lang in doc['doc']['tags']: if not doc['doc']['tags'][lang]: doc['doc']['tags'][lang] = '' t_old = doc['tags'][lang] if 'tags' in doc and lang in doc['tags'] else [] # разбиваем строку тегов на слова через и запихиваем в словарь tags = {'123':1, '456':1} tags = dict([(i.strip().lower(), 1) for i in doc['doc']['tags'][lang].split(',') if i.strip()]) if not 'tags' in doc: doc['tags'] = {} if not is_admin(request) and not user_has_permission(request, doc['doc_type'], 'edit_tag'): # наполняем в ифе tags теми перемеными которые не содержат звездочки. tags2 = tags; tags = {} for res in tags2: if not '*' in res: tags[res] = tags2[res] doc['tags'][lang] = tags if doc['doc_type'] in ['des:news', 'des:obj', 'des:banners', 'des:wiki']: if 'pub' in doc['doc'] and doc['doc']['pub'] == 'true': if 'accept' in doc['doc'] and doc['doc']['accept'] == 'true' or doc['doc_type'] in ['des:banners', 'des:wiki', 'des:news']: count_tags(request, tags, t_old, doc['doc_type']) elif doc['doc_type'] in ['des:ware']: count_tags(request, tags, t_old, doc['doc_type']) doc['doc']['tags'][lang] = ', '.join(tags) request.db.doc.save(doc)
async def del_comm_post(request): """ doc_id - id самого коментария """ data = await request.post() print(data) comm_id = data.get('comm_id') doc = get_doc(request, comm_id) if is_admin(request) or user_has_permission(request, 'des:obj', 'del_comm'): # добавление подсчета коментариев в отдельном документе request.db.doc.update({"_id": doc['doc']['owner']}, {"$inc": { "count_branch": -1 }}) if 'child' in doc: if len(doc['child']): request.db.doc.update({"_id": comm_id}, {"$set": { 'doc.is_del': 'true' }}) return response_json(request, { "result": "ok", "action": "del_dom", "id": comm_id }) else: del_row(request, 'des:comments', {comm_id: comm_id}) return response_json(request, {"result": "ok", "id": comm_id}) else: return response_json(request, { "result": "fail", "error": "error sequrity" })
def add_field(request, proc_id, data, field_id=None): #field_id=None индекс поля которое нужно поменять при редактировании if not user_has_permission(request, proc_id, 'create'): return response_json(request, {"result": "fail", "error": "You have no permission."}) print('data===================================================================================================') print('data', data) if 'relation' in data: relation = data['relation'] else: relation = '' if 'relation_field' in data: relation_field = data['relation_field'] else: relation_field = '' for i in data: tp = data['type'] if 'type' in data else 'string' field = { "hint": {"ru":data['hint_ru'], "en":data['hint_en']}, "title": {"ru":data['title_ru'],"en":data['title_en']}, "visible": data['visible'], "oncreate": data['oncreate'], "type": tp, "relation":relation, "relation_field":relation_field, "is_editable": data['is_editable'], "id": data['id'], "is_translate":data['is_translate']} doc = get_mt(request, proc_id) if not field_id: doc['doc'].append(field) else: for res in doc['doc']: if field_id == res['id']: cur = doc['doc'].index(res) doc['doc'].remove(res) doc['doc'].insert(cur, field) request.db.map.save(doc) return response_json(request, {"result":"ok"} )
async def edit_comm_post(request): if not user_has_permission(request, 'des:obj', 'add_com'): return {"result": "fail", "error": "no comment"} if not user_is_logged_in(request): return response_json(request, { "result": "fail", "error": "no comment" }) data = await request.post() comm_id = data.get('comm_id') body = data.get('body') user = data.get('user') if user == get_current_user(request) or is_admin(request): if 'child' in get_doc(request, comm_id) and not is_admin(request): return response_json(request, { "result": "fail", "error": "comment already answered" }) doc = request.db.doc.update( {'_id': comm_id}, {"$set": { "doc.body." + cur_lang(request): body }}) from core.union import invalidate_cache invalidate_cache('single_page') return response_json(request, {"result": "ok", "id": comm_id}) else: return response_json(request, { "result": "fail", "error": "access denied" })
def add_vote_comm_post(request): """Вычисляем данные в посте сколько проголосовало и тд.""" data = request.post() vote = data.get('vote') comm_id = data.get('comm_id') comm = get_doc(comm_id) # doc = db.tree.find_one({'owner':doc_id}) user = get_current_user(True) from libs.sites.sites import check_time # comm = doc['tree'][comm_id] if check_time( comm['doc']['date'], 'days', int( get_const_value(request, 'vote_timeout') ) ): return response_json(request, {"result":"fail", "error":"Голосование уже закончилось"}) if not 'vote' in comm : comm['vote'] = {"score":0,"votes_count":0, "votes_count_plus":0,"votes_count_minus":0, "voted":{}} if not user_has_permission(request, 'des:obj', 'vote_com'): return response_json(request, {"result":"fail","error":"Не имеете права голоса"}) if not is_admin(request) and user in comm['vote']['voted'] : return response_json(request, {"result":"fail","error":"Повторное голосование запрещено"}) if not is_admin(request) and user == 'user:'******'title']): return response_json(request, {"result":"fail","error":"Голосовать за себя запрещено"}) dt = datetime.today().strftime('%Y-%m-%d') user_f = get_doc(request, user) if not 'vote' in user_f : user_f['vote'] = {} if not dt in user_f['vote'] : user_f['vote'][dt] = {'up': 0, 'down': 0} if not is_admin(request) and int(user_f['vote'][dt]['up']) + int(user_f['vote'][dt]['down']) >= int(float(user_f['doc']['rate'])+1.25): return response_json(request, {"result":"fail","error":"Лимит голосов за сегодня исчерпан"}) user_f['vote'][dt][vote] += 1 request.db.doc.save(user_f) comm['vote']['voted'][user] = vote if vote == 'up': comm['vote']['score'] += 1 comm['vote']['votes_count_plus'] += 1 else: comm['vote']['score'] -= 1 comm['vote']['votes_count_minus'] += 1 comm['vote']['votes_count'] += 1 request.db.doc.save(comm) comm_vote = comm['vote'] # начисление балов пользователю # u_id = 'user:'******'title']) u_id = ct(request, comm['doc']['user'] ) u = get_doc(request, u_id) if u: if not 'rate' in u['doc']: u['doc']['rate'] = '0' request.db.doc.save(u) if float(u['doc']['rate']) >= 17: rate = float(u['doc']['rate']) + (0.02 if vote == 'up' else -0.1) else: rate = float(u['doc']['rate']) + (0.2 if vote == 'up' else -0.1) # rate =+ 1 if vote == 'up' else -1 update_cell(request, str(u_id), 'des:users', 'rate', str(rate) ) return response_json(request, {"result":"ok", "score":comm_vote["score"],"votes_count":comm_vote["score"],"charge_string":"","sign":"positive", "votes_count_plus":comm_vote["votes_count_plus"],"votes_count_minus":comm_vote["votes_count_minus"],"is_positive":True})
def table_update_cell_post(request): proc_id = request.match_info.get('proc_id') if not user_has_permission(request, proc_id, 'edit'): return {"result": "fail", "error": "You have no permission."} data = get_post(request) idd = data['id'] field = data['field'] value = unquote( data['value'] ) return response_json(request, update_cell(request, idd, proc_id, field, value) )
def tree_post(request, proc_id): if proc_id.startswith('tree:'): if not user_has_permission(request, proc_id[5:], 'view'): return response_json(request, {"result": "fail", "error": ct(request, "You have no permission.")}) return tree_data(request, proc_id, False) else: data = request.post() owner = data.get('owner', False) proc_id2 = data.get('proc_id', False) return tree_data(request, proc_id, owner) if owner else tree_data(request, proc_id2, False)
def edit_conf_post(request): """ Заносим видимость или невидимость кнопки тоесть модуля """ data = get_post(request) data = json.loads(data['data']) for res in request.db.map.find({'$or':[{"conf.owner":None}, {"conf.owner":'_'}]} ): if user_has_permission(request, res['_id'], 'view'): res['conf']['turn'] = 'true' if data[res['_id']] else 'false' request.db.map.save(res) return {"result":"ok"}
def transfer_doc(request, proc_id, ids, to): proc_id = get_post('proc_id') if not user_has_permission(request, proc_id, 'create'): return {"result": "fail", "error":"You have no permission."} ctr = 0 dat = get_post(request) data = json.loads(dat['ids']) for current_id in data: doc = get_doc(request, current_id) if doc is not None: doc['doc_type'] = dat['to'] request.db.doc.save(doc); ctr += 1 return response_json(request, {"result":"ok", "counter":ctr})
def edit_conf_post(request): """ Заносим видимость или невидимость кнопки тоесть модуля """ data = get_post(request) data = json.loads(data['data']) for res in request.db.map.find( {'$or': [{ "conf.owner": None }, { "conf.owner": '_' }]}): if user_has_permission(request, res['_id'], 'view'): res['conf']['turn'] = 'true' if data[res['_id']] else 'false' request.db.map.save(res) return {"result": "ok"}
def tree_post(request, proc_id): if proc_id.startswith('tree:'): if not user_has_permission(request, proc_id[5:], 'view'): return response_json( request, { "result": "fail", "error": ct(request, "You have no permission.") }) return tree_data(request, proc_id, False) else: data = request.post() owner = data.get('owner', False) proc_id2 = data.get('proc_id', False) return tree_data(request, proc_id, owner) if owner else tree_data( request, proc_id2, False)
def accept_comm_post(request): if not is_admin(request) and not user_has_permission(request, 'des:comments', 'edit'): return response_json(request, {"result":"fail", "error":"no has permission"}) data = get_post(request) doc_id = data.get('doc_id') doc = request.db.doc.find_one({'_id':doc_id}) doc['doc']['pre'] = 'false' request.db.doc.save(doc) owner = doc['doc']['doc_id'] comm_id = str(doc['doc']['comm_id']) tree = request.db.tree.find_one({'_id': owner}) # die(tree['tree'].keys()) tree['tree'][comm_id]['pre'] = 'false' request.db.tree.save(tree) return response_json(request, {"result":"ok"})
async def table_data_post(request): """ #page=текущая страница page ctr=кол-во pages=отрисованые ссылки на страницу навигация """ data = get_post(request) proc_id = data['proc_id'] if not user_has_permission(request, proc_id, 'view'): return {"result": "fail", "error": "You have no permission." } filtered = json.loads(data['filter']) doc_id = data['doc_id'] if 'doc_id' in data else '_' parent = data['parent'] if 'parent' in data else '_' id_next = None; id_prev = None if 'page' in filtered: page = filtered['page'] else: page = {'current':1} limit = int(get_const_value(request, 'doc_page_limit')) bdata, docs_table_count = table_data_post_(request, proc_id, filtered, doc_id, parent) otvet = {"result":"ok", "data":bdata, "pages":{"count":int(ceil(float(docs_table_count)/limit)), "current":page['current'], "next": id_next, "prev":id_prev} } return response_json(request, otvet)
async def table_update_row_post(request): proc_id = request.match_info.get('proc_id') force = request.match_info.get('force', False) if not force and not user_has_permission(request, proc_id, 'create'): return {"result": "fail", "error": "You have no permission."} data = get_post(request) row_id = data['row_id'] # print('parent', data['parent']) parent = data['parent'] if 'parent' in data else '_' data = json.loads(data['data']) print( 'data', data ) if 'rev' in data: del data['rev'] return response_json(request, update_row_(request, proc_id, row_id, data, parent = parent) )
async def edit_comm_post(request): if not user_has_permission(request, 'des:obj', 'add_com'): return {"result":"fail", "error":"no comment"} if not user_is_logged_in(request): return response_json(request, {"result":"fail", "error":"no comment"}) data = await request.post() comm_id = data.get('comm_id') body = data.get('body') user = data.get('user') if user == get_current_user(request) or is_admin(request): if 'child' in get_doc(request, comm_id) and not is_admin(request): return response_json(request, {"result":"fail", "error":"comment already answered"}) doc = request.db.doc.update({'_id': comm_id}, {"$set": {"doc.body." + cur_lang(request): body}}) from core.union import invalidate_cache invalidate_cache('single_page') return response_json(request, {"result":"ok", "id":comm_id}) else: return response_json(request, {"result":"fail", "error":"access denied"})
def table_add_row_post(request): data = get_post(request) proc_id = data['proc_id'] owner = data.get('owner', None) # defaults = json.loads(data['defaults'] if 'defaults' in data else {}) auto_fill = data.get('auto_fill', False) if not user_has_permission(request, proc_id, 'create'): return response_json(request, {"result": "fail", "error": "You have no permission."}) try: doc_id, updated = create_empty_row_(request, proc_id, owner, auto_fill) # update_row_(proc_id, doc_id, {}) if doc_id: return response_json(request, {"result":"ok", "id":doc_id, "updated": updated}) else: return response_json(request, {"result":"fail", "descr":"not doc_id", "error":json.dumps(updated)}) except Exception as e: return response_json(request, {"result":"fail", "descr":"exception", "error": e})
def accept_comm_post(request): if not is_admin(request) and not user_has_permission( request, 'des:comments', 'edit'): return response_json(request, { "result": "fail", "error": "no has permission" }) data = get_post(request) doc_id = data.get('doc_id') doc = request.db.doc.find_one({'_id': doc_id}) doc['doc']['pre'] = 'false' request.db.doc.save(doc) owner = doc['doc']['doc_id'] comm_id = str(doc['doc']['comm_id']) tree = request.db.tree.find_one({'_id': owner}) # die(tree['tree'].keys()) tree['tree'][comm_id]['pre'] = 'false' request.db.tree.save(tree) return response_json(request, {"result": "ok"})
async def del_comm_post(request): """ doc_id - id самого коментария """ data = await request.post() print(data) comm_id = data.get( 'comm_id') doc = get_doc(request, comm_id) if is_admin(request) or user_has_permission(request, 'des:obj', 'del_comm'): # добавление подсчета коментариев в отдельном документе request.db.doc.update({ "_id": doc['doc']['owner'] }, { "$inc": { "count_branch":-1 } } ) if 'child' in doc: if len(doc['child']): request.db.doc.update({"_id":comm_id}, {"$set":{'doc.is_del':'true'}}) return response_json(request, {"result":"ok", "action":"del_dom", "id":comm_id}) else: del_row(request, 'des:comments', { comm_id:comm_id }) return response_json(request, {"result":"ok", "id":comm_id}) else: return response_json(request, {"result":"fail", "error":"error sequrity"})
async def table_del_row_post(request): data = await request.post() # proc_id = data['proc_id'] if 'proc_id' in data else None proc_id = data.get('proc_id') force = data.get('force', False) ids = data.get('ids') ids = json.loads( ids ) idsn = data.get('idsn') idsn = json.loads(idsn) print( "4444", data['idsn']) for doc in request.db.doc.find({'_id': {'$in': idsn}}): final = False if not 'final' in doc: final = True # запрещаем не админу удалять документы созданые админом if not force and final and not user_has_permission(request, proc_id, 'delete') or not is_admin(request): return {"result": "fail", "error": "You have no permission."} return del_row(request, proc_id, ids)
async def add_comm_post(request): # return json.dumps(current_id, title, link, proc_id) """current_id это id ветки""" # ip = request.environ.get('REMOTE_ADDR') data = await request.post(); ip = None print('data->', data) #get ip address client peername = request.transport.get_extra_info('peername'); host=None if peername is not None: host, port = peername ip = host # print ('host, port->', host, port) user = get_current_user(request, True) if check_ban(request, host, user): return response_json(request, {"result":"fail", "error":"Ваш ip или аккаунт забанен на этом сайте, свяжитесь с администрацией"}) else: title = data.get('title') if not user_has_permission(request, 'des:obj', 'add_com') and not user_has_permission(request, 'des:obj', 'add_com_pre'): return response_json(request, {"result":"fail", "error":"no comment"}) if not check_user_rate(request, user): return response_json(request, {"result":"fail", "error":"Вы не можете оставлять сообщения слишком часто, из-за отрицательной кармы"}) doc_id = data.get('comm_id') id = data.get('id') if user_is_logged_in(request): title = get_current_user(request) # tle = get_doc(request, doc_id ) # print( doc_id ) # print( tle ) # tle = get_doc(request, doc_id )['doc']['title'] title_ = ct(request, title ) title = no_script( title ) if title else 'Аноним' parent = data.get('parent', "_") descr = data.get( 'descr') descr = no_script( descr ) descr = descr.replace('\n', '<br/>') # ретурн если нет и того и другого а если нет только одного то как раз проверим pre = 'true' if not user_has_permission(request, 'des:obj', 'add_com') else 'false' date = str( time.strftime("%Y-%m-%d %H:%M:%S") ) user_ = get_current_user_name(request, title ) or title our = "true" if user_is_logged_in(request) else "false" body = re.sub(r'(http?://([a-z0-9-]+([.][a-z0-9-]+)+)+(/([0-9a-z._%?#]+)+)*/?)', r'<a href="\1">\1</a>', descr) # добавление родителю ребенка request.db.doc.update({ "_id": parent }, { "$addToSet": { "child": doc_id } } ) # занесение коментов в справочник коментов doc_id_comm, updated = create_empty_row_(request, 'des:comments', parent, '', { "user":'******'+title }) data = {"id":doc_id_comm, "title":title_, "date":date, "body":body, "parent":parent, "owner":id, 'ip':ip, 'name':user_, "our":our, 'pre':pre } update_row_(request, 'des:comments', doc_id_comm, data, parent) if 'notify_user' in dir(settings) and settings.notify_user: # if 'notify_user' in settings and settings.notify_user: # link = make_link('show_object', {'doc_id':doc_id }, True)+'#comm_'+ str( id ) link = settings.domain+'/news/'+doc_id+'#comm_'+ str( id ) subject = 'User {} add comment'.format( title ) sub('user:'******'id1', id) id = get_doc(request, id)['_id'] print('id2', id) invalidate_cache('single_page', id=id) # rev = get_doc(request, doc_id)['doc']['rev'] # reset_cache(type="doc", doc_id=rev) # добавление подсчета коментариев в отдельном документе request.db.doc.update({ "_id": doc_id }, { "$inc": { "count_branch":1 } } ) # return json.dumps({"result":"ok", "content":data.update({"title":title}), "hash":""}) return response_json(request, {"result":"ok", "content":data, "hash":""})
def add_vote_comm_post(request): """Вычисляем данные в посте сколько проголосовало и тд.""" data = request.post() vote = data.get('vote') comm_id = data.get('comm_id') comm = get_doc(comm_id) # doc = db.tree.find_one({'owner':doc_id}) user = get_current_user(True) from libs.sites.sites import check_time # comm = doc['tree'][comm_id] if check_time(comm['doc']['date'], 'days', int(get_const_value(request, 'vote_timeout'))): return response_json(request, { "result": "fail", "error": "Голосование уже закончилось" }) if not 'vote' in comm: comm['vote'] = { "score": 0, "votes_count": 0, "votes_count_plus": 0, "votes_count_minus": 0, "voted": {} } if not user_has_permission(request, 'des:obj', 'vote_com'): return response_json(request, { "result": "fail", "error": "Не имеете права голоса" }) if not is_admin(request) and user in comm['vote']['voted']: return response_json(request, { "result": "fail", "error": "Повторное голосование запрещено" }) if not is_admin(request) and user == 'user:'******'title']): return response_json(request, { "result": "fail", "error": "Голосовать за себя запрещено" }) dt = datetime.today().strftime('%Y-%m-%d') user_f = get_doc(request, user) if not 'vote' in user_f: user_f['vote'] = {} if not dt in user_f['vote']: user_f['vote'][dt] = {'up': 0, 'down': 0} if not is_admin(request) and int(user_f['vote'][dt]['up']) + int( user_f['vote'][dt]['down']) >= int( float(user_f['doc']['rate']) + 1.25): return response_json(request, { "result": "fail", "error": "Лимит голосов за сегодня исчерпан" }) user_f['vote'][dt][vote] += 1 request.db.doc.save(user_f) comm['vote']['voted'][user] = vote if vote == 'up': comm['vote']['score'] += 1 comm['vote']['votes_count_plus'] += 1 else: comm['vote']['score'] -= 1 comm['vote']['votes_count_minus'] += 1 comm['vote']['votes_count'] += 1 request.db.doc.save(comm) comm_vote = comm['vote'] # начисление балов пользователю # u_id = 'user:'******'title']) u_id = ct(request, comm['doc']['user']) u = get_doc(request, u_id) if u: if not 'rate' in u['doc']: u['doc']['rate'] = '0' request.db.doc.save(u) if float(u['doc']['rate']) >= 17: rate = float(u['doc']['rate']) + (0.02 if vote == 'up' else -0.1) else: rate = float(u['doc']['rate']) + (0.2 if vote == 'up' else -0.1) # rate =+ 1 if vote == 'up' else -1 update_cell(request, str(u_id), 'des:users', 'rate', str(rate)) return response_json( request, { "result": "ok", "score": comm_vote["score"], "votes_count": comm_vote["score"], "charge_string": "", "sign": "positive", "votes_count_plus": comm_vote["votes_count_plus"], "votes_count_minus": comm_vote["votes_count_minus"], "is_positive": True })
async def add_comm_post(request): # return json.dumps(current_id, title, link, proc_id) """current_id это id ветки""" # ip = request.environ.get('REMOTE_ADDR') data = await request.post() ip = None print('data->', data) #get ip address client peername = request.transport.get_extra_info('peername') host = None if peername is not None: host, port = peername ip = host # print ('host, port->', host, port) user = get_current_user(request, True) if check_ban(request, host, user): return response_json( request, { "result": "fail", "error": "Ваш ip или аккаунт забанен на этом сайте, свяжитесь с администрацией" }) else: title = data.get('title') if not user_has_permission(request, 'des:obj', 'add_com') and not user_has_permission( request, 'des:obj', 'add_com_pre'): return response_json(request, { "result": "fail", "error": "no comment" }) if not check_user_rate(request, user): return response_json( request, { "result": "fail", "error": "Вы не можете оставлять сообщения слишком часто, из-за отрицательной кармы" }) doc_id = data.get('comm_id') id = data.get('id') if user_is_logged_in(request): title = get_current_user(request) # tle = get_doc(request, doc_id ) # print( doc_id ) # print( tle ) # tle = get_doc(request, doc_id )['doc']['title'] title_ = ct(request, title) title = no_script(title) if title else 'Аноним' parent = data.get('parent', "_") descr = data.get('descr') descr = no_script(descr) descr = descr.replace('\n', '<br/>') # ретурн если нет и того и другого а если нет только одного то как раз проверим pre = 'true' if not user_has_permission(request, 'des:obj', 'add_com') else 'false' date = str(time.strftime("%Y-%m-%d %H:%M:%S")) user_ = get_current_user_name(request, title) or title our = "true" if user_is_logged_in(request) else "false" body = re.sub( r'(http?://([a-z0-9-]+([.][a-z0-9-]+)+)+(/([0-9a-z._%?#]+)+)*/?)', r'<a href="\1">\1</a>', descr) # добавление родителю ребенка request.db.doc.update({"_id": parent}, {"$addToSet": {"child": doc_id}}) # занесение коментов в справочник коментов doc_id_comm, updated = create_empty_row_(request, 'des:comments', parent, '', {"user": '******' + title}) data = { "id": doc_id_comm, "title": title_, "date": date, "body": body, "parent": parent, "owner": id, 'ip': ip, 'name': user_, "our": our, 'pre': pre } update_row_(request, 'des:comments', doc_id_comm, data, parent) if 'notify_user' in dir(settings) and settings.notify_user: # if 'notify_user' in settings and settings.notify_user: # link = make_link('show_object', {'doc_id':doc_id }, True)+'#comm_'+ str( id ) link = settings.domain + '/news/' + doc_id + '#comm_' + str(id) subject = 'User {} add comment'.format(title) sub('user:'******'id1', id) id = get_doc(request, id)['_id'] print('id2', id) invalidate_cache('single_page', id=id) # rev = get_doc(request, doc_id)['doc']['rev'] # reset_cache(type="doc", doc_id=rev) # добавление подсчета коментариев в отдельном документе request.db.doc.update({"_id": doc_id}, {"$inc": {"count_branch": 1}}) # return json.dumps({"result":"ok", "content":data.update({"title":title}), "hash":""}) return response_json(request, { "result": "ok", "content": data, "hash": "" })
def show_conf(request): #route('/conf', 'GET') """Показывает список дизайнерских документов""" if get_const_value(request, 'is_admin') == "false" and not is_admin(request): return web.HTTPSeeOther('/') if not user_is_logged_in(request): return web.HTTPSeeOther('/login') all_docs = [] all_rbs = [] ss = [] all_menu = [] special = ['des:users', 'des:report_pe', 'des:conf', 'des:role'] # выводим справочники и документы из документа прослойки. for res in request.db.map.find({ "conf.turn": "true", '$or': [{ "conf.owner": None }, { "conf.owner": '_' }], "conf.is_doc": True }): if user_has_permission(request, res['_id'], 'view'): all_docs.append(res) for res in request.db.map.find({ "conf.turn": "true", '$or': [{ "conf.owner": None }, { "conf.owner": '_' }], "conf.is_doc": False }): if not res['_id'] in special and user_has_permission( request, res['_id'], 'view'): all_rbs.append(res) # выводим настроечные кнопки которые справа. for res in get_ss(request): if user_has_permission(request, res['id'], 'view'): res['id'] = res['id'][:2] + '_' + res['id'][3:] ss.append(res) # выводим кнопки работы с меню. for res in request.db.tree.find({'sub_type': 'menu'}): if user_has_permission(request, res['_id'], 'view'): all_menu.append(res) url = request.scheme + '://' + request.host # return templ('libs.admin:conf', request, dict(url = url, all_docs = all_docs, all_rbs = all_rbs, all_menu = all_menu, ss = ss) ) tree = [] for res in request.db.doc.find({"doc_type": "des:left_menu"}): tree.append(res) val_tree = form_tree_comm(request, tree) # print( request.__dict__) return templ( 'libs.admin:admin', request, dict(url=url, all_docs=all_docs, all_rbs=all_rbs, all_menu=all_menu, ss=ss, tree=val_tree))
def table_transfer_post(request): data = get_post(request) proc_id = data['proc_id'] if not user_has_permission(request, proc_id, 'create'): return {"result": "fail", "error": "You have no permission."} return transfer_doc(request, proc_id, json.loads(get_post('ids')), get_post('to'))
def check_map_perm(request, proc_id, meta_table, permission = 'view'): meta = [] for i in meta_table: if user_has_permission(request, proc_id, permission, i['id']): meta.append(i) return meta