def rating(): user = request.user.get() if user: users = request.db().query(User).all() users.sort(key=lambda u: u.get_total_rating(), reverse=True) cities = request.db(Region).get_all() return template('rating', {'page': 'rating', 'user': user, 'members': users, 'cities': cities}) redirect("/")
def save_object(): if not request.user.role('admin'): return False data = request.forms photos = request.files.getall('file') v = Validator(data) v.fields("file.id").integer(nullable=True) v.fields("file.visible").boolean() v.fields("file.order").integer() if v.is_valid(): data = v.valid_data about = request.db(Content).get_by_alias('about') if not about: about = Content() about.con_alias = 'about' about.con_name = 'about' about.con_text = data.get("text") request.db.add(about) request.db.commit() action = data.getall('file.action') visible = data.getall('file.visible') order = data.getall('file.order') for i, id in enumerate(data.getall('file.id')): if action[i]: if action[i] == 'new': file = request.db(File).create('photo.jpg', module=module.name, entity=about) file.create_dir() file.update_uniq_id() photo = photos.pop(0) image_resize(photo).convert('RGB').save(file.get_fullpath()) else: file = request.db(File).get_by_id(id) file.visible = visible[i] file.order = order[i] if action[i] == 'delete': file.remove_files() request.db.delete(file) else: request.db.add(file) request.db.commit() return {"status": "ok", "reload": 'true'} else: return {"status": "fail", "errors": v.errors}
def news(id=None): user = request.user.get() if user: load_month() news = request.db(News).get_by_id(id) return {'news': news, 'page': 'news'} redirect("/")
def all(): user = request.user.get() if user: load_month() news = request.db(News).get_visible() return {'news': news, 'page': 'news'} redirect("/")
def save(): if not request.user.role('admin'): return False data = request.forms v = Validator(data) v.field("id").integer(nullable=True) v.field("title").required() v.field("text").required() v.field("datetime").datetime(format='%d.%m.%Y %H:%M') if v.is_valid(): data = v.valid_data news = request.db(News).get_by_id(data.get("id")) or News() news.title = data.get("title") news.text = data.get("text") news.datetime = data.get("datetime") request.db.add(news) request.db.commit() return {"status": "ok", "redirect": '/admin/news'} else: return {"status": "fail", "errors": v.errors}
def login_fb(): user = None data = json.loads(request.forms.data) try: response = urllib2.urlopen("https://graph.facebook.com/me?fields=first_name,last_name,picture,email&access_token="+data['authResponse']['accessToken']) response = json.loads(response.read()) if response is not None and 'id' in response: fb_id = response['id'] uc = request.db().query(UserCommunity).join(Community)\ .filter(Community.alias == 'fb', UserCommunity.external_id == fb_id).first() user = uc.user if uc is not None else None if user is None: email = response['email'] user = request.db.query(User).filter_by(email=email).first() if user is None: user = User(first_name=response['first_name'], last_name=response['last_name'], email=response['email'], photo='https://graph.facebook.com/'+fb_id+'/picture?type=large', photo_s='https://graph.facebook.com/'+fb_id+'/picture?type=square') community = request.db.query(Community).filter_by(alias='fb').first() if community is None: community = Community(alias='fb', name='Facebook') uc = UserCommunity(user=user, community=community, external_id=fb_id) request.db.add(uc) request.db.commit() except HTTPError: pass return auth(user)
def send(): data = request.forms v = Validator(data) v.field("name").required() v.field("email_phone").required() v.field("reason").integer() receivers = [c.cnt_value for c in request.db(Contacts).list_by_type('feedback')] if v.is_valid(): data = v.valid_data reason = translate('site.contacts.reason'+str(data.get("reason")), language=get_default_language().lng_code) text = """\ Контактное лицо: %s <br/> Email или телефон: %s <br/> Причина: %s <br/> <br/> %s """ % (data.get('name'), data.get('email_phone'), reason, data.get('text')) msg = MIMEText(text.encode('utf-8'), 'html') sender = data.get('email') receiver = ', '.join(receivers) msg['Subject'] = 'Письмо от пользователя %s' % data.get('name') msg['From'] = 'Обратная связь' msg['To'] = receiver s = smtplib.SMTP('localhost') s.sendmail(sender, receiver, msg.as_string()) s.quit() return {"status": "ok", "message": translate('site.feedback.message_sent', default="Повiдомлення вiдправленно.")} else: return {"status": "fail", "errors": translate('site.feedback.fill_all_fields', default="Заповнiть, будь ласка, усi поля.")}
def change_default(): if not request.user.role('admin'): return False id = request.forms.id default = request.forms.is_default == 'true' lang = request.db(Language).get_by_id(id) all = request.db(Language).list_all() if lang is not None: for lng in all: lng.lng_default = False request.db.add(lng) lang.lng_default = default request.db.add(lang) request.db.commit() kernel.translator.default_language = lang return {"status": "ok", "is_default": lang.lng_default} else: return {"status": "fail"}
def delete_seo(id=None): if not request.user.role('admin'): return False seo = request.db(SEOUrl).get_by_id(id) if seo is not None: request.db.delete(seo) request.db.commit() return {"status": "ok"} else: return {"status": "fail"}
def get_translation_language(): s = request.session lang = None lang_code = request.forms['__translation__'] if '__translation__' in request.forms else '' if lang_code != '': lang = request.db(Language).get_by_code(lang_code) if not lang and 'language' in s and 'translation' in s['language']: lang = s['language']['translation'] if not lang: lang = get_default_language() return lang
def delete(): if not request.user.role('admin'): return False id = request.forms.id entity = request.db(News).get_by_id(id) if entity is not None: request.db.delete(entity) request.db.commit() return {"status": "ok"} else: return {"status": "fail"}
def after_insert_listener(mapper, connection, target): lang = request.forms.get('translation_language') if not lang: lang = get_translation_language().lng_code db = request.db() for c in target.__table__.columns: if c.name in target.translatable_fields: translation = Translation() translation.trl_code = get_entity_code(target, c.name) translation.lng_code = lang translation.trl_text = getattr(target, c.name) db.add(translation) db.commit()
def change_visibility(): if not request.user.role('admin'): return False id = request.forms.id visible = request.forms.visible == 'true' lang = request.db(Language).get_by_id(id) if lang is not None: lang.lng_active = visible request.db.add(lang) request.db.commit() return {"status": "ok", "visible": lang.lng_active} else: return {"status": "fail"}
def change_visibility(): if not request.user.role('admin'): return False id = request.forms.id visible = request.forms.visible == 'true' entity = request.db(News).get_by_id(id) if entity is not None: entity.visible = visible request.db.add(entity) request.db.commit() return {"status": "ok", "visible": entity.visible} else: return {"status": "fail"}
def seo_save(): if not request.user.role('admin'): return False data = request.forms v = Validator(data) v.field("seou_url").required() v.field("seou_id").integer(nullable=True) v.fields("seot_id").integer(nullable=True) seo = request.db(SEOUrl).get_by_url(v.valid_data.get("seou_url").strip()) if seo is not None and seo.seou_id != v.valid_data.seou_id: v.add_error("seou_url", "Такая ссылка уже существует") if v.is_valid(): seo = request.db(SEOUrl).get_by_id(data.seou_id) if seo is None: seo = SEOUrl() seo.seou_url = data.get('seou_url').strip() tag_ids = data.getall('seot_id') tag_text = data.getall('seot_text') request.db.add(seo) request.db.commit() for i, text in enumerate(tag_text): text = text.strip() id = tag_ids[i] tag = request.db(SEOUrl).get_by_id(id) if tag is None: tag = SEOTag() tag.seou_id = seo.seou_id if text == '': if id is not None: request.db.delete(tag) else: tag.seot_text = text request.db.add(tag) request.db.commit() return {"status": "ok"} else: return {"status": "fail", "errors": v.errors}
def registrate(): data = request.forms data['photo'] = request.files.get('photo') v = Validator(data) v.field("first_name").required() v.field("last_name").required() v.field("email").required().email() v.field("password").required().length(min=5, message="Длина пароля не менее %(min)d символов") v.field("photo").image() if data.get("password") != data.get("repassword"): v.add_error('password', 'Пароли не совпадают', 'wrong_repassword') if(v.is_valid()): data = v.valid_data password_hash = hash_password(data.get('password')) user = request.db(User).get_by_email(data['email']) if user: v.add_error('email', 'Электронный адрес уже используется.', 'email_is_used_already') else: user = User() user.email = data['email'] user.first_name = data['first_name'] user.last_name = data['last_name'] user.password = password_hash request.db.add(user) request.db.commit() img = data.get("photo") if img is not None: path = profile_path.format(id=user.id) photo_name = 'photo_'+str(user.id)+"_"+str(uuid.uuid4())+".png" thumbnail_name = photo_name.rstrip(".png")+".thumbnail.png" if not os.path.exists(path): os.makedirs(path) remove_similar(path, photo_name) image_path = os.path.join(path, photo_name) thumbnail_path = os.path.join(path, thumbnail_name) photo = image_thumbnail(img, width=200, height=200, fill='cover') photo.save(image_path) img.file.seek(0) thumbnail = image_thumbnail(img, width=50, height=50, fill='cover') thumbnail.save(thumbnail_path) user.photo = "/file"+image_path.replace(files_dir, '').replace("\\", '/') user.photo_s = "/file"+thumbnail_path.replace(files_dir, '').replace("\\", '/') request.db.commit() auth(user) return {"status": "ok", "reload": True} return {"status": "fail", "errors": v.errors}
def login_native(): data = request.forms v = Validator(data) v.field("email").required() v.field("password").required() if v.is_valid(): data = v.valid_data user = request.db().query(User).filter(User.email == data.get('email')).first() if not user or not verify_password(data.get('password'), user.password): v.add_error('email', 'Неправильный email или пароль', 'wrong_login') else: auth(user) return {"status": "ok", "reload": True} return {"status": "fail", "errors": v.errors}
def delete(): if not request.user.role('admin'): return False id = request.forms.id lang = request.db(Language).get_by_id(id) if lang is not None: def_language = get_default_language() trans_language = get_translation_language() if trans_language.lng_id == lang.lng_id: set_translation_language(def_language.lng_code) request.db.delete(lang) request.db.commit() return {"status": "ok"} else: return {"status": "fail"}
def save(): if not request.user.role('admin'): return False data = request.forms v = Validator(data) data['lng_code'] = data['lng_code'].upper() v.field("lng_id").integer(nullable=True) v.field("lng_code").required() v.field("lng_name").required() lang = request.db(Language).get_by_code(data.get("lng_code")) if lang is not None and lang.lng_id != data['lng_id']: v.add_error('lng_name', 'Язык с таким кодом уже существует', 'language.exists') if v.is_valid(): data = v.valid_data lang = request.db(Language).get_by_id(data.get("lng_id")) if lang is None: lang = Language() lang.lng_code = data.get("lng_code") lang.lng_name = data.get("lng_name") request.db.add(lang) request.db.commit() return {"status": "ok", "language": lang.as_dict(translated=True)} else: return {"status": "fail", "errors": v.errors}
def save_contacts(ids, values, type): if not request.user.role('admin'): return False for i, id in enumerate(ids): if id != '': contact = request.db(Contacts).get_by_id(id) else: contact = Contacts() contact.cnt_type = type contact.cnt_value = values[i] if contact.cnt_value == '<delete>': if contact.cnt_id is not None: request.db.delete(contact) else: request.db.add(contact)
def seo_widget(): seos = request.db(SEOUrl).list_all_ordered() result = '' found = False for seo in seos: req = request.urlparts url = request.url re_url = seo.seou_url.replace('.', '\\.').replace('*', '.*') if re_url[0] == '/': re_url = req.scheme + '://' + req.netloc + seo.seou_url.replace('.', '\\.').replace('*', '.*') if re.match('^'+re_url+'$', url): found = True for tag in seo.tags: result = result + tag.seot_text + '\n' if found: break return result
def save(): if not request.user.role('admin'): return False data = request.forms v = Validator(data) v.field("id").required().integer() if v.is_valid(): data = v.valid_data dictionary = request.db(Dictionary).get_by_id(data.get("id")) dictionary.text = data.get("text") request.db.add(dictionary) request.db.flush() request.db.commit() update_translation(dictionary) return {"status": "ok", "dictionary": dictionary.as_dict(translated=True)} else: return {"status": "fail", "errors": v.errors}
def save_content(): if not request.user.role('admin'): return False data = request.forms v = Validator(data) v.field("text").required() v.field("id").integer(nullable=True).required() if v.is_valid(): data = v.valid_data content = request.db(Content).get_by_id(data.get("id")) content.text = data.get("text") request.db.add(content) request.db.commit() return {"status": "ok", "redirect": '/admin/content'} else: return {"status": "fail", "errors": v.errors}
def login_vk(): user = None data = json.loads(request.forms.data) params = "expire="+str(data['expire']) \ + "mid="+str(data['mid'])\ + "secret="+str(data['secret'])\ + "sid="+str(data['sid'])\ + str(config['sn']['vk']['app_secret']) md5 = hashlib.md5() md5.update(params) sig = md5.hexdigest() if sig == data['sig']: try: response = urllib2.urlopen("https://api.vk.com/method/getProfiles?uid="+data['mid']+"&fields=uid,photo,photo_big,photo_medium") response = json.loads(response.read()) if response is not None: response = response['response'][0] vk_id = response['uid'] uc = request.db().query(UserCommunity).join(Community)\ .filter(Community.alias == 'vk', UserCommunity.external_id == vk_id).first() user = uc.user if uc is not None else None if user is None: user = User(first_name=response['first_name'], last_name=response['last_name'], photo=response['photo_big'], photo_s=response['photo']) community = request.db.query(Community).filter_by(alias='vk').first() if community is None: community = Community(alias='vk', name='VKontakte') uc = UserCommunity(user=user, community=community, external_id=vk_id) request.db.add(uc) request.db.commit() except KeyError, HTTPError: pass
def index(): urls = request.db(SEOUrl).list_all() return {"urls": urls}
def content_widget(alias): content = request.db(Content).get_by_alias(alias) return content.text if content.text else ''
def rules(): user = request.user.get() if user: rules = request.db(Content).get_by_alias('rules') return template('rules', {'page': 'rules', 'rules': rules}) redirect("/")
def edit_route(id=None): news = request.db(News).get_by_id(id) or News() return template("admin/news/form", {'news': news})
def all(): news = request.db(News).get_all() return {'news': news}
def seo_form(id=None): seo = request.db(SEOUrl).get_by_id(id) return {"seo": seo}