Ejemplo n.º 1
0
    def get(self):
        self.checkSession(self.request.headers.get('Cookie'), True)
        self.insertMenu()
        
        news = db.GqlQuery("select * from DBNews order by date desc LIMIT 15")
        news = [new for new in news if new.hiden != True][:5]
        self.insertContent("<div style='padding: 10px;'>")
#        if news.count() == 0:
#            self.insertContent("Сейчас нет ни одной новости.")
        for piece_of_news in news:
            u_class = DBUser()
            login = u_class.get_login_by_id(piece_of_news.userid)
            self.insertContent('<table width=100% style="border-width: 1px; border-style: dashed;"><tr><td><li>' + str(piece_of_news.date) +
                               ' | <a href="/news/' + 
                               str(piece_of_news.key().id()) + '">' + 
                               piece_of_news.cap.encode("utf8") + '</a>'+
                               '<font size=1> размещено '+
                               '<a href="/users/'+login+'">'+login+'</a>'+
                               '</font><hr><font size=2>'+
                               piece_of_news.preview.encode("utf8") +
                               '</font><br><br></li></td></tr></table><br>')
        self.insertContent("</div>")
        
        self.insertContent("<div style='padding: 10px;'><a href='/news_all/'>Архив новостей</a></div>")
        
        self.drawPage("Новости")
Ejemplo n.º 2
0
    def get(self):
        self.checkSession(self.request.headers.get('Cookie'), True)
        self.insertMenu()

        news = db.GqlQuery("select * from DBNews order by date desc LIMIT 15")
        news = [new for new in news if new.hiden != True][:5]
        self.insertContent("<div style='padding: 10px;'>")
        #        if news.count() == 0:
        #            self.insertContent("Сейчас нет ни одной новости.")
        for piece_of_news in news:
            u_class = DBUser()
            login = u_class.get_login_by_id(piece_of_news.userid)
            self.insertContent(
                '<table width=100% style="border-width: 1px; border-style: dashed;"><tr><td><li>'
                + str(piece_of_news.date) + ' | <a href="/news/' +
                str(piece_of_news.key().id()) + '">' +
                piece_of_news.cap.encode("utf8") + '</a>' +
                '<font size=1> размещено ' + '<a href="/users/' + login +
                '">' + login + '</a>' + '</font><hr><font size=2>' +
                piece_of_news.preview.encode("utf8") +
                '</font><br><br></li></td></tr></table><br>')
        self.insertContent("</div>")

        self.insertContent(
            "<div style='padding: 10px;'><a href='/news_all/'>Архив новостей</a></div>"
        )

        self.drawPage("Новости")
Ejemplo n.º 3
0
    def get_news(self):
        spe_news = memcache.get("news4main")
        if not spe_news:
#            try:
                spe_news = ''
                news = db.GqlQuery("select * from DBNews order by date desc LIMIT 15")
                news = [new for new in news if new.hiden != True][:5]
                spe_news+=("<div style='padding: 5px; margin-bottom: 50px;'>")
     
                banner = BannerHandler().next_banner()
     
                for news_position, piece_of_news in enumerate(news):
                    if news_position == 4:
                        spe_news += """
                        <div style="text-align: center;">
                            <a href="%s" target=”_blank”>
                                <img src="/banner/show/%s" style="align: center;" />
                            </a>
                        </div>
                        <div style="text-align: right; font-size: 12px;">
                            <a href="/advertising">Реклама на портале</a>
                        </div>
                        """ % (banner['link'].encode("utf-8"), banner['key']) if banner else ""
                    u_class = DBUser()
                    login = u_class.get_login_by_id(piece_of_news.userid)
                    spe_news+=("""
                                <div style="float: left; width: 100%; border: 1px solid #fd9446; margin-bottom: 5px; margin-top: 5px; background-color: white;">
                                    <div style="padding: 4px;">
                                        <a href="/news/""" + str(piece_of_news.key().id()) + """\">
                                            """ +  piece_of_news.cap.encode("utf8") + """
                                        </a>
                                        <br>
                                        <font style="font-size: 10px; color: #333333;">
                                            Добавлена """ + str(piece_of_news.date.strftime("%d.%m.%Y")) + 
                                            """, <a href=\"/users/""" + login + """\">""" +
                                            login +      
                                            """</a>
                                        </font>
                                    </div>
                                    <div style="padding: 4px;">
                                        <font size=2>
                                            """ + piece_of_news.preview.encode("utf8") +   
                                            """
                                        </font>
                                        <br>
                                        <div style="text-align: right; margin-top: 8px;">
                                            <a style="font-size: 10px;" href="/news/""" + str(piece_of_news.key().id()) + """\">
                                                читать далее
                                            </a>
                                        </div>
                                    </div>
                                </div>
                               """)
                spe_news+=("</div>")
                memcache.add("news4main", spe_news, 3600)
#            except: pass
        return spe_news
Ejemplo n.º 4
0
    def get(self):
        
        self.checkSession(self.request.headers.get('Cookie'), False)

        name = self.get_url_part(1)
        
        conf = 0

#        conf = DBConf()
#        conf.name = "arhimir"
#        conf.cap = "title"
#        conf.rules = "rules"
#        conf.about = "about"
#        conf.userid = 2
#        conf.put()
        
        try:
            conf = DBConf.gql("where name = :name", name = name)[0]
        except:
            self.showMessage("К сожалению, такой конференции не найдено!")
            return

        owner = False
        if int(conf.userid) == self.Session['userid']:
            owner = True
        _questions = db.GqlQuery("SELECT * FROM DBConfQuestion WHERE moderated=True") 
        
        
        #DBConfQuestion.gql("where answer != :some", some = None)#.filter("confid = ", conf.key().id())
        questions = []
        for q in _questions:
            user = DBUser()
            questions.append(
                             {
                              'id' : q.key().id(),
                              'cap' : q.cap,
                              'text' : q.text,
                              'user' : user.get_login_by_id(q.userid),
                              'answer' : q.answer,
                              'date' : q.date,
                             }
                             )
        questions.reverse()   
        self.insertTemplate("conf/tpl_conf.html", {
                                              'name' : name,
                                              'cap' : conf.cap,
                                              'questions' : questions,
                                              'owner' : owner,
                                              })
        self.drawPage("Конференция :: "+str(conf.name))
Ejemplo n.º 5
0
    def get(self):

        self.checkSession(self.request.headers.get('Cookie'), False)

        name = self.get_url_part(1)

        conf = 0

        #        conf = DBConf()
        #        conf.name = "arhimir"
        #        conf.cap = "title"
        #        conf.rules = "rules"
        #        conf.about = "about"
        #        conf.userid = 2
        #        conf.put()

        try:
            conf = DBConf.gql("where name = :name", name=name)[0]
        except:
            self.showMessage("К сожалению, такой конференции не найдено!")
            return

        owner = False
        if int(conf.userid) == self.Session['userid']:
            owner = True
        _questions = db.GqlQuery(
            "SELECT * FROM DBConfQuestion WHERE moderated=True")

        #DBConfQuestion.gql("where answer != :some", some = None)#.filter("confid = ", conf.key().id())
        questions = []
        for q in _questions:
            user = DBUser()
            questions.append({
                'id': q.key().id(),
                'cap': q.cap,
                'text': q.text,
                'user': user.get_login_by_id(q.userid),
                'answer': q.answer,
                'date': q.date,
            })
        questions.reverse()
        self.insertTemplate(
            "conf/tpl_conf.html", {
                'name': name,
                'cap': conf.cap,
                'questions': questions,
                'owner': owner,
            })
        self.drawPage("Конференция :: " + str(conf.name))
Ejemplo n.º 6
0
 def get(self):
     self.checkSession(self.request.headers.get('Cookie'), False)
     self.insertMenu()
     anketaid = self.request.uri.split('/')[-1]
     useranketa = DBEventAnketa.get_by_id(int(anketaid))
     user = DBUser.get_by_id(int(useranketa.userid))
     #        payway = {  0   : 'Бесплатно',
     #                    1   : 'Безналичный рассчет',
     #                    2   : 'Наличными с курьером',
     #                    3   : 'Web-Money' }
     self.insertTemplate(
         'tpl_user_anketa.html',
         {
             'name': useranketa.name.encode("utf8"),
             'surname': useranketa.surname.encode("utf8"),
             'company': useranketa.company.encode("utf8"),
             'phone': useranketa.phone.encode("utf8"),
             'position': useranketa.position.encode("utf8"),
             #                                                                  'payway'          : payway[int(useranketa.payway)],
             'is_portfolio': useranketa.is_portfolio,
             'isarhitect': useranketa.isarhitect,
             'additional': useranketa.additional.encode("utf8"),
             'login': user.login.encode("utf8"),
         })
     self.drawPage()
Ejemplo n.º 7
0
    def post(self):
        if not super(Approver, self).get(): return
                          
        uri = self.request.uri
        uri = uri.split('/')
        login = str(cgi.escape(uri[-1]).split('?')[0]).replace("%40", "@")
                         
        try: 
            users = DBUser.gql("where login='******'" % login)
            user = users[0]
            user.access = 6
            user.put()
        except:
            self.insertContent("Похоже логин некорректный")
        
#        caption = self.request.get("cap").encode("utf8")
#        content = self.request.get("content").encode("utf8")
        
#        self.insertContent(content)
        try:
            Handler().send(self.Session['user_key'], [DBUser().get_key_by_login(login)], self.request.get('caption'), self.request.get('content'))
#            msgsend = MSGSender()
#            msgsend.send_msg(-1, login, , )
            #PostOffice().append_to_queue(, self.request.get('caption'), self.request.get('content'))
        except:
            self.insertContent("Уведомлние не отправилось")
            
            
                          
        self.insertContent("""Готово""")
        self.drawPage()
Ejemplo n.º 8
0
 def getReceivedMSG(self, owner):
     """ Getting messages sender previously received """
     msg_r = db.GqlQuery(
         "SELECT * FROM DBMSGRecipients where recipient = :recipient ORDER BY date DESC",
         recipient=owner)
     if msg_r.count() == 0:
         self.insertContent(
             '<div style="padding: 10px;">Нет входящих сообщений</div>')
     else:
         self.insertContent(
             '<table><tr><td width="150">Дата</td><td width="450">Тема</td><td width="250">Собеседник</td></tr>'
         )
         for msg in msg_r:
             owner_login = "******"
             try:
                 owner = DBUser.get_by_id(msg.message.owner)
                 owner_login = '******' + owner.login + '">' + owner.login + '</a>'
             except:
                 pass
             template_values = {
                 'id': msg.key().id(),
                 'date': msg.date.strftime("%d.%m.%y %H:%M"),
                 'caption': msg.message.caption,
                 'direction': 'от',
                 'login': owner_login
             }
             self.insertTemplate('tpl_msg.html', template_values)
         self.insertContent('</table>')
     self.drawPage()
Ejemplo n.º 9
0
    def post(self):
        if not super(forum_topic_add, self).get(): return
        cat_id = int(self.get_url_part(1))
        new_topic = DBForumTopic()
        new_topic.name = cgi.escape(self.request.get("name"))
        if len(new_topic.name) < 3:
            self.showMessage("Заголовок сообщения слишком короткий")
            return
        new_topic.description = cgi.escape(self.request.get("descr")).replace("\n", "<br />")
        if len(new_topic.description) < 5:
            self.showMessage("Сообщение слишком короткое")
            return
        category = DBForumCategory.get_by_id(cat_id)
        new_topic.category = category.key()
        new_topic.author = DBUser.get_by_id(self.Session['userid']).key()
        
        info_comment = DBComments() #one of them
        info_comment.user = new_topic.author
        info_comment.obj = new_topic.put()
        info_comment.content = ""
        info_comment_key = info_comment.put()

        try:
            category.topics_count += 1
        except:
            category.topics_count = 1
        category.last_comment = info_comment_key
        category.put()
        
        self.showMessage("Добавлено")
Ejemplo n.º 10
0
 def get(self):
     eventid = self.request.uri.split('/')[-1]
     event = DBEvent.get_by_id(int(eventid))
     if not super(EventInfo, self).get(event.userid): return
     users = db.GqlQuery("SELECT * FROM DBEventAnketa WHERE eventid = :eventid",
                         eventid = event.key().id())
     user_list = []
     for user in users:
         user_list.append({
                            'id' : int(user.userid),
                            'login' : DBUser().get_login_by_id(int(user.userid)),
                            'name' : user.name.encode("utf8"),
                            'surname' : user.surname.encode("utf8"),
                            'phone' : user.phone.encode("utf8"),
                         })
     user_list = sorted(user_list, key=lambda user_list: user_list['surname'])
     self.insertMenu()
     self.insertTemplate("tpl_event_info.html", {
                                                  'user_list' : user_list,
                                                  'event' : { 
                                                              'name' : event.name.encode("utf8"),
                                                              'id'   : event.key().id(),
                                                            },
                                                })
     self.drawPage(event.name.encode("utf8"))
Ejemplo n.º 11
0
    def get(self):

        counter = 0

        letter_bag = Letter.gql("limit 10")
        if letter_bag.count(1):
            for letter in letter_bag:
                rcp = letter.to

                sender_email = DBCustomField().getByName('email')

                # нужен такой цикл, тк фор тупит при добавлении элементов
                while len(rcp) > 0:
                    #for r in rcp:
                    self.send_letter(
                        DBUser.get(rcp[0]).email, letter.subject, letter.body,
                        sender_email)
                    #                    rcp.remove(r)
                    rcp.pop(0)
                    counter += 1
                    print counter
                    if counter == self._step:
                        break
                if len(rcp) > 0:
                    letter.to = rcp
                    letter.put()
                else:
                    db.delete(letter)
Ejemplo n.º 12
0
    def readMSG(self, id):
        """ Reading selected message """
        self.checkSession(self.request.headers.get('Cookie'))
        self.insertMenu()
        msg = DBMSGRecipients.get_by_id(id)
        if msg.message.owner != self.Session[
                'userid'] and msg.recipient != self.Session['userid']:
            self.response.out.write("Это не ваше сообщение")
            return
        reply = False

        owner_login = "******"
        try:
            owner = DBUser.get_by_id(msg.message.owner)
            owner_login = str(owner.login)
        except:
            pass

        if msg.recipient == self.Session['userid']:
            reply = True
            msg.read = True
            msg.put()
        self.insertTemplate(
            'tpl_msg_read.html', {
                'caption': msg.message.caption.encode("utf8"),
                'content': msg.message.content.encode("utf8"),
                'reply': reply,
                'owner': owner_login
            })
        self.drawPage()
Ejemplo n.º 13
0
    def post(self):
        if not super(forum_topic_add, self).get(): return
        cat_id = int(self.get_url_part(1))
        new_topic = DBForumTopic()
        new_topic.name = cgi.escape(self.request.get("name"))
        if len(new_topic.name) < 3:
            self.showMessage("Заголовок сообщения слишком короткий")
            return
        new_topic.description = cgi.escape(self.request.get("descr")).replace(
            "\n", "<br />")
        if len(new_topic.description) < 5:
            self.showMessage("Сообщение слишком короткое")
            return
        category = DBForumCategory.get_by_id(cat_id)
        new_topic.category = category.key()
        new_topic.author = DBUser.get_by_id(self.Session['userid']).key()

        info_comment = DBComments()  #one of them
        info_comment.user = new_topic.author
        info_comment.obj = new_topic.put()
        info_comment.content = ""
        info_comment_key = info_comment.put()

        try:
            category.topics_count += 1
        except:
            category.topics_count = 1
        category.last_comment = info_comment_key
        category.put()

        self.showMessage("Добавлено")
Ejemplo n.º 14
0
 def get(self):
     self.checkSession(self.request.headers.get('Cookie'))
     self.insertMenu()
     temp_uri = self.request.uri
     uri = temp_uri.split('/')
     userid = ""
     try:
         userid = int(cgi.escape(uri[-1]))
     except: pass
     if not (userid == self.Session['userid'] or self.Session['access'] >= 8):
         self.insertContent("""У вас нет прав на выполнение этого действия.""")
         self.drawPage()
         return
         
     if userid != "":
         user = DBUser.get_by_id(int(userid))
         self.insertTemplate('tpl_register.html', { 'title'      : 'Изменение данных пользователя', 
                                                                    'button'     : 'Изменить',
                                                                    'action'     : 'changeinfo',
                                                                    'login'      : str(user.login),
                                                                    'name'       : user.name,
                                                                    'surname'    : user.surname,
                                                                    'email'      : str(user.email),
                                                                    'twitter'    : str(user.twitter) if user.twitter else "",
                                                                    'livejournal': str(user.livejournal) if user.livejournal else "",
                                                                    'userid'     : str(userid),
                                                                    'user_about' : user.about.encode("utf8") if user.about else "",
                                                                    'check'      : True,
                                                                    'checkpwd'   : True,
                                                                    'approve'    : True if userid == self.Session['userid'] and self.Session['access'] < 5 else False, })
     else:
         self.insertTemplate('tpl_admin_user.html', { })
     self.drawPage()
Ejemplo n.º 15
0
 def validated_email(self, email):
     if re.match("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$", email) is None:
         raise EmailFormatInvalid
     email = email.lower()
     if DBUser.all(keys_only=True).filter("email=", email).count(1):
         raise EmailExistsAlready
     return email
Ejemplo n.º 16
0
 def getSentMSG(self, sender):
     """ Getting messages sender previously sent """
     msg = db.GqlQuery("SELECT * FROM DBMSG where owner = :owner",
                       owner=sender)
     if msg.count() == 0:
         self.insertContent(
             '<div style="padding: 10px;">Нет исходящих сообщений</div>')
     else:
         self.insertContent(
             '<table><tr><td width="150">Дата</td><td width="450">Тема</td><td width="250">Собеседник</td></tr>'
         )
         for this_msg in msg:
             if this_msg.show_to_owner == False: continue
             msgrecipient = DBMSGRecipients.gql("where message = :message",
                                                message=this_msg)[0]
             recipient = DBUser.get_by_id(msgrecipient.recipient)
             template_values = {
                 'id':
                 msgrecipient.key().id(),
                 'date':
                 msgrecipient.date.strftime("%d.%m.%y %H:%M"),
                 'caption':
                 this_msg.caption,
                 'direction':
                 'для',
                 'login':
                 '******' + recipient.login + '">' +
                 recipient.login + '</a>'
             }
             self.insertTemplate('tpl_msg.html', template_values)
         self.insertContent('</table>')
     self.drawPage("Личные сообщения")
Ejemplo n.º 17
0
 def validated_login(self, login):
     if len(login) < 4:
         raise LoginLengthSmall
     if len(set(login) & set("~`!@#$%^&*()-=+\\/'\"{}][;:<>, ")):
         raise LoginHasRestrictedSymbols
     login = login.lower()
     if DBUser.all(keys_only=True).filter("login=", login).count(1):
         raise LoginExistsAlready
     return login
Ejemplo n.º 18
0
    def send_msg(self, owner, recipient, content, caption = "None"):
        user = DBUser.gql("where login = :login", login = recipient)[0]
        recipientid = int(user.key().id())
        msg = DBMSG()
#        msg.owner = owner['id']
        msg.owner = owner
        msg.caption = caption if caption else "None"
        msg.content = content
        msgrecipient = DBMSGRecipients()
        msgrecipient.message = msg.put()
        msgrecipient.recipient = recipientid
        msgrecipient.put()
        if owner == -1:
            self.owner_login = "******"
            self.owner_name = "Администрация"
        else:
            dbowner = DBUser.get_by_id(owner)
            self.owner_login = dbowner.login
            self.owner_name = dbowner.name
        return self.__send_mail(recipient, user.email, self.owner_login, self.owner_name, content)
Ejemplo n.º 19
0
    def get(self):

        try:
            i = int(self.get_url_part(1))
        except:
            i = 0

        news = DBAlbum.all()[i:i + 200]
        for new in news:
            new.author = DBUser.get_by_id(new.userid)
            new.put()
Ejemplo n.º 20
0
    def get(self):
        self.checkSession(self.request.headers.get('Cookie'))
        self.insertMenu()
        temp_uri = self.request.uri
        uri = temp_uri.split('/')
        userid = ""
        try:
            userid = int(cgi.escape(uri[-1]))
        except:
            pass
        if not (userid == self.Session['userid']
                or self.Session['access'] >= 8):
            self.insertContent(
                """У вас нет прав на выполнение этого действия.""")
            self.drawPage()
            return

        if userid != "":
            user = DBUser.get_by_id(int(userid))
            self.insertTemplate(
                'tpl_register.html', {
                    'title':
                    'Изменение данных пользователя',
                    'button':
                    'Изменить',
                    'action':
                    'changeinfo',
                    'login':
                    str(user.login),
                    'name':
                    user.name,
                    'surname':
                    user.surname,
                    'email':
                    str(user.email),
                    'twitter':
                    str(user.twitter) if user.twitter else "",
                    'livejournal':
                    str(user.livejournal) if user.livejournal else "",
                    'userid':
                    str(userid),
                    'user_about':
                    user.about.encode("utf8") if user.about else "",
                    'check':
                    True,
                    'checkpwd':
                    True,
                    'approve':
                    True if userid == self.Session['userid']
                    and self.Session['access'] < 5 else False,
                })
        else:
            self.insertTemplate('tpl_admin_user.html', {})
        self.drawPage()
Ejemplo n.º 21
0
    def post(self):
        if super(CommentHandler, self).get():
            if not self.request.get("content"):
                self.showMessage("""Введите текст комментария!
                <br><a href='""" + self.request.headers.get("Referer") + """'>Вернуться в тему</a>""")
                return
            comment = DBComments()
            user = DBUser.get_by_id(self.Session['userid'])
            comment.user = user
            if user.comments_count:
                user.comments_count = user.comments_count + 1
            user.put()
            
            comment.obj = db.Key(str(self.request.get('entity')))
            content = self.request.get("content")
            comment.content = cgi.escape(content).replace("\n", "<br />")
            
            comment.parent_comment = DBComments().get(self.request.get('parent_comment')) if \
                                     self.request.get('parent_comment') else None
            # Old part with id
            #DBComments().get_by_id(int(self.request.get('parent_comment'))) if \
            #                       self.request.get('parent_comment') else None
            
            key_ = comment.put()
            comment = db.get(key_)

            try:
                comment.obj.increase_comments_count(comment)
            except: pass


            #Отсылаем владельцу топика
            if self.Session['user_key'] != comment.obj.author.key():
                body = template.render("comments/comment_notification.html", { 
                                                                                'user' : self.Session,
                                                                                'comment' : comment,
                                                                                'referer' : self.request.headers.get("Referer"),
                                                                                'site_url' : DBCustomField().getByName('url')
                                                                              })
                PostOffice().append_to_queue(comment.obj.author.key(), """Новый комментарий на портале Архимир""".decode("utf-8"), body.decode("utf-8"))
                
            #Отсылаем владельцу коммента-предка:
            if comment.parent_comment and \
            (self.Session['user_key'] != comment.parent_comment.user.key()) and \
            (comment.obj.author.key() != comment.parent_comment.user.key()):
                body = template.render("comments/comment_notification.html", { 
                                                                                'to_parent' : True,
                                                                                'user' : self.Session,
                                                                                'comment' : comment,
                                                                                'referer' : self.request.headers.get("Referer"),
                                                                                'site_url' : DBCustomField().getByName('url')
                                                                              })
                PostOffice().append_to_queue(comment.parent_comment.user.key(), """Новый комментарий на портале Архимир""".decode("utf-8"), body.decode("utf-8"))
            self.redirect(self.request.headers.get("Referer"))
Ejemplo n.º 22
0
 def get(self):
     
     try:
         i = int(self.get_url_part(1))
     except:
         i = 0
     
     news = DBAlbum.all()[i:i+200]
     for new in news:
         new.author = DBUser.get_by_id(new.userid)
         new.put()
Ejemplo n.º 23
0
    def get(self):

        super(ConfQuestWaiting, self).get()

        name = self.get_url_part(1)
        
        conf = 0
        
        try:
            conf = DBConf.gql("where name = :name", name = name)[0]
        except:
            self.showMessage("К сожалению, такой конференции не найдено!")
            return

        if conf.userid != self.Session['userid']:
            self.showMessage("Нет доступа")
            return
        
        #_questions = DBConfQuestion.all().filter("confid =", conf.key().id()).filter("moderated = ", False)
        _questions = DBConfQuestion.gql("where confid = :cid and moderated = :m", cid = conf.key().id(), m = False)
        questions = []
        for q in _questions:
            user = DBUser()
            questions.append(
                             {
                              'id' : q.key().id(),
                              'cap' : q.cap,
                              'text' : q.text,
                              'user' : user.get_login_by_id(q.userid),
                              'date' : q.date,
                             }
                             )
        questions.reverse()        
        self.insertTemplate("conf/tpl_conf_waiting.html", {
                                              'name' : name,
                                              'cap' : conf.cap,
                                              'questions' : questions,
                                              })

        self.drawPage("Конференция :: "+str(conf.name))
        
Ejemplo n.º 24
0
    def get_top(self):
#        print 1
        arhs = []
        data = memcache.get("arch_top")
        if data is not None:
            arhs = pickle.loads(data)
#            print 2
        else:
            data = memcache.get("sorted_objects_v2")
#            print 3
            if not data: return arhs
            o_list = pickle.loads(data)[0:25]
            objects = []
            for object in o_list:
                objects.append(DBGalleryObject.get_by_id(object))
            
            rating = {}
    
            u = DBUser()
            
            obj_k = 100.0
            for object in objects:
                try:
                    rating[int(object.userid)] += 1.0*obj_k
                except:
                    rating[int(object.userid)] = 1.0*obj_k
                obj_k /= 1.1
            
            rate = sorted(rating.items(), key = lambda(k,v): (v,k), reverse=True)
            
            for entity in rate[:25]:

                # lets check if user has a photo
                if not DBAvatara().get_by_userid(entity[0]):
                    continue
                
                slovar = {'id': entity[0], 'login' : str(u.get_login_by_id(entity[0]))}
                arhs.append( slovar )
            memcache.add("arch_top", pickle.dumps(arhs), 3600)
        return arhs
Ejemplo n.º 25
0
    def get(self):
        if super(AdminAlbumAdd, self).get():
            id = 0
            try:
                id = int(self.request.uri.split('/')[-1])
            except: pass
            objects = db.Query(DBGalleryObject)
            if self.Session['access'] < 8:
                if objects.count()!=0:
                    objects.filter("userid =", self.Session['userid'])
                    objects.order("name")
            else:
                if objects.count()!=0: objects.order("userid")
            options = ''
            if objects.count()!=0:
                for object in objects:
                    owner = DBUser.get_by_id(int(object.userid))
                    own = """(Объект """ + owner.login.encode("utf8") + """) """
                    selected = ""
                    if int(object.key().id()) == id:
                        selected = "selected"
                    options += """<option """ + selected + """ value=""" + str(object.key().id()) + """>""" + own + object.name.encode("utf8") + """</option>"""
            self.insertMenu()
            albums = db.Query(DBAlbum)
            albums.filter("objectid =", -1)
            albums.filter("userid =", self.Session['userid'])
            if albums.count() == 0:
                self.album = DBAlbum()
            else:
                photos_to_delete = DBPhoto.gql("where albumid = :aid", aid = int(albums[0].key().id()))
#                photos_to_delete = db.Query(DBPhoto)
#                photos_to_delete.filter("albumid =", int(albums[0].key().id()))
                db.delete(photos_to_delete)
                self.album = DBAlbum.get_by_id(int(albums[0].key().id()))
            secret = str(hashlib.md5(str(random.random())).hexdigest())
            self.album.name = secret
            self.album.objectid = -1
            self.album.userid = self.Session['userid']
            self.album.author = self.Session['user_key']
            self.album.put()
            albums = db.Query(DBAlbum)
            albums.filter("name =", secret)
            
            self.insertContent("Album ID: " + str(int(albums[0].key().id())))
#            statistics = db.GqlQuery("SELECT * FROM __Stat_Kind__ WHERE kind_name = 'DBPhoto'")
#            global_stat = stats.GlobalStat.all().get()
            self.insertTemplate("tpl_admin_album_add.html", { 'options' : options,
                                                              'albumid' : int(albums[0].key().id()),
#                                                              'bytes' : global_stat.bytes,
                                                              'isadmin' : True if self.Session['access'] == 10 else False,
                                                            })
            self.drawPage()
Ejemplo n.º 26
0
 def __SessionWrite(self, Session):
     try:
         dbuser = DBUser.get_by_id(int(Session['userid']))
         Session['name'] = dbuser.name.encode("utf8")
         Session['surname'] = dbuser.surname.encode("utf8")
         Session['email'] = str(dbuser.email)
         Session['access'] = int(dbuser.access)
         Session['type'] = str(dbuser.type)
         Session['user_key'] = str(dbuser.key())
         try:
             memcache.delete("Session_"+str(Session['sid']), 0)
         except: pass
         data = pickle.dumps(Session)
         memcache.add("Session_"+str(Session['sid']), data, 604800)
     except:
         pass
Ejemplo n.º 27
0
    def post(self):
        """ Write bullshit to DB"""        
        self.checkSession(self.request.headers.get('Cookie'))
        uri = self.request.uri
        uri = uri.split('/')
        recipient = str(cgi.escape(uri[-1]).split('?')[0]).replace("%40", "@")

        if recipient == str(self.Session['login']):
            self.insertContent("Нельзя отправлять сообщение самому себе!")
            self.drawPage("Отправка сообщения")
            return
        try:
            PostOffice().append_to_queue(DBUser().gql("WHERE login = :login", login = recipient)[0], self.request.get('caption'), self.request.get('content'))
            self.redirect('/msgbox/msgtrue')
        except:
            self.redirect('/msgbox/msgfalse')
Ejemplo n.º 28
0
    def get(self):
        subject = "Тренинг 'Эффективное общение с клиентом'"
        body = """Уважаемые архитекторы!

19 мая проект "Архимир" проводит бизнес-тренинг для архитекторов и дизайнеров интерьеров.

Тренинг «Эффективное общение с клиентом»

Дата 19 мая

Место проведения улица Малая Ордынка, дом 23

Продолжительность тренинга 1 день с 11 до 19

Бизнес — тренер Ольга Болтович (информация о тренере http://www.arhimir.ru/forum/topic/687001)

Организатор: Проект «Архимир»

Программа тренинга

    * Как преодолеть барьеры в начале разговора?
    * Как произвести благоприятное впечатление на клиента и создать атмосферу доверия? (техники установления контакта)
    * Как грамотно построить переговоры (этапы переговоров)?
    * Как удерживать инициативу и управлять процессом переговоров?
    * Как быстро получать необходимую информацию от клиента (правила постановки вопросов)?
    * Как слушать и слышать клиента (техники активного слушания)?

Ответы на эти  и другие вопросы можно получить на тренинге. Также участники смогут в практических упражнениях потренировать применение основополагающих переговорных техник.

Стоимость тренинга 3000 рублей

Для участия в тренинге необходимо внести предоплату в размере 500 рублей. Оставшуюся стоимость в размере 2500 рублей необходимо оплатить на тренинге. В случае отказа от тренинга менее чем за 2 дня, предоплата не возвращается.

Внести предоплату и получить пригласительный билет Вы можете в офисе компании "Арнэт", по адресу улица пятницкая д. 2.

Зарегистрироваться на тренинг можно по телефону 642-47-43

        """
        # get arhs
        arhs = DBUser.gql("where access = 6")
        for arh in arhs:
            PostOffice().append_to_queue(arh, subject.decode('utf-8'), body.decode('utf-8'))
            
        self.showMessage("ok")
        
Ejemplo n.º 29
0
 def send_msg_mass(self, owner, gqlRecipients, content, caption):
     if owner == -1:
         self.owner_login = "******"
         self.owner_name = "Администрация"
     else:
         dbowner = DBUser.get_by_id(owner)
         self.owner_login = dbowner.login
         self.owner_name = dbowner.name
     msg = DBMSG()
     msg.owner = owner
     msg.caption = caption
     msg.content = content
     msg_key = msg.put()
     for recipient in gqlRecipients:
         msgrecipient =  DBMSGRecipients()
         msgrecipient.message = msg_key
         msgrecipient.recipient = int(recipient.key().id())
         msgrecipient.put()
         self.__send_mail(recipient.login, recipient, self.owner_login, self.owner_name, content)
Ejemplo n.º 30
0
    def get(self):
        old_tags = DBPhotoTags.gql('where fixed = :fixed', fixed=False)
        for tag_string in old_tags:
            tags = tag_string.tags.split(',')
            imageid = tag_string.imageid

            key = DBPhoto.get_by_id(imageid).key()

            user = DBUser.gql("where login='******'")[0]
            new_tag = TagsList()
            new_tag.obj = db.Key(str(key))
            new_tag.tags = tags
            new_tag.user = user
            new_tag.put()

            tag_string.fixed = True
            tag_string.put()
            self.response.out.write('ok')
        self.response.out.write('done')
Ejemplo n.º 31
0
 def post(self):
     self.checkSession(self.request.headers.get('Cookie'))
     if self.Session['access'] < 5:
         #            msgsend = MSGSender()
         content = (self.request.get('fio') + "<br>" +
                    self.Session['login'] + "<br>" +
                    self.request.get('phone') + "<br>" +
                    self.request.get('position') + "<br>" +
                    self.request.get('graduate') + "<br>" +
                    self.request.get('exp'))
         caption = "Architector approve"
         try:
             PostOffice().append_to_queue(DBUser().get_key_by_login("spe"),
                                          caption, content)
             #msgsend.send_msg(self.Session['userid'], "smsteel", content, caption)
             #                msgsend.send_msg(self.Session['userid'], "spe", content, caption)
             self.redirect("/msgbox/approvesend")
         except:
             self.redirect("/msgbox/approvefail")
Ejemplo n.º 32
0
 def post(self):
     #@todo: Test it on GAE
     id = int(self.request.uri.split('/')[-1])
     try:
         self.event = DBEvent.get_by_id(id)
     except:
         self.showMessage("Событие на найдено!")
         return
     if not super(EventMailFeed, self).get(self.event.userid): return
     message_handler = Handler()
     anketas = DBEventAnketa.gql("where eventid = :eventid", eventid=id)
     user_list = []
     for anketa in anketas:
         user_list.append(DBUser.get_by_id(anketa.userid))
     message_handler.send(self.Session['user_key'], user_list,
                          ("""Новая информация о событии %s""" %
                           self.event.name.encode("utf-8")).decode("utf-8"),
                          self.request.get('content'))
     #sender.send_msg_mass(self.event.userid, recipients, self.request.get('content'), db.Text("Новая информация о событии " + self.event.name.encode("utf8"), "utf_8"))
     self.showMessage("Готово")
Ejemplo n.º 33
0
    def get(self):
        user = str(cgi.escape(self.request.uri.split('/')[-1])).replace("%40", "@")
        if self.checkSession(self.request.headers.get('Cookie'), False):
            self.insertMenu()
        dbuser = db.GqlQuery("SELECT * FROM DBUser where login = :login",
                             login = user)
        for user in dbuser:
            objects_count = 0
            objects_list = ""
            if user.access == 5 or user.access == 6:
                objects = db.Query(DBGalleryObject)
                objects.filter("userid =", int(user.key().id()))
#                objects.order("date")
                objects_count = objects.count()
                for object in objects:
                    objects_list += """<div style="padding: 20px 0px 0px 20px; float: left;"><a href="/objects/""" + str(object.key().id()) + """"><div style="border-width: 1px; border-color: #555555; border-style: solid; padding: 2px;"><img style="border: 0;" src="/picture/130/crop/0/""" + str(object.key().id()) + """" /></div></a></div>"""
                
            twitter = False    
            try:
                twitter = user.twitter.encode("utf8")
            except: 
                pass

            self.insertTemplate('tpl_user_info.html', { 
                                                                   'id' :  str(user.key().id()),
                                                                   'name' : user.name.encode("utf8"),
                                                                   'surname' : user.surname.encode("utf8"),
                                                                   'login' : user.login.encode("utf8"),
                                                                   'comments' : DBUser().count_comments(user.key()),
                                                                   'architect' : True if user.access == 5 or user.access == 6 else False,
                                                                   'logged_access' : self.Session['access'],
                                                                   'objects_count' : objects_count,
                                                                   'objects_list' : objects_list,
                                                                   'twitter'      : twitter,
                                                                   'lj'      : user.livejournal.encode("utf8") if user.livejournal else False,
                                                                   'date' : user.date if user.date else False,
                                                                   'user_about' : user.about.encode("utf8") if user.about else False, 
                                                                   })

        self.drawPage("Информация о пользователе "+user.name.encode("utf8")+" "+user.surname.encode("utf8"))
Ejemplo n.º 34
0
    def get(self):
        self.checkSession(self.request.headers.get('Cookie'), False)
        self.insertMenu()
        anketaid = self.request.uri.split('/')[-1]
        useranketa = DBEventAnketa.get_by_id(int(anketaid))
        user = DBUser.get_by_id(int(useranketa.userid))
#        payway = {  0   : 'Бесплатно',
#                    1   : 'Безналичный рассчет',
#                    2   : 'Наличными с курьером',
#                    3   : 'Web-Money' }
        self.insertTemplate('tpl_user_anketa.html', { 'name'            : useranketa.name.encode("utf8"),
                                                                  'surname'         : useranketa.surname.encode("utf8"),
                                                                  'company'         : useranketa.company.encode("utf8"),
                                                                  'phone'           : useranketa.phone.encode("utf8"),
                                                                  'position'        : useranketa.position.encode("utf8"),
#                                                                  'payway'          : payway[int(useranketa.payway)],
                                                                  'is_portfolio'    : useranketa.is_portfolio,
                                                                  'isarhitect'      : useranketa.isarhitect,
                                                                  'additional'      : useranketa.additional.encode("utf8"),
                                                                  'login'       : user.login.encode("utf8"), 
                                                                   })
        self.drawPage()
Ejemplo n.º 35
0
 def post(self):
     self.checkSession(self.request.headers.get('Cookie'))
     login = str(self.request.get('logins'))
     if login != "":
         responsehtml = ''
         dbusers = db.GqlQuery("SELECT * FROM DBUser")
         max_users_in_list = 4
         for dbuser in dbusers:
             if str(dbuser.login).find(login) >= 0 and max_users_in_list:
                 max_users_in_list -= 1
                 if str(self.request.get("objectadd")) == "true":
                     responsehtml += "<a style='cursor: pointer;' id='user" + str(max_users_in_list) + "' onclick='$(\"#login\").attr(\"value\", $(\"#user" + str(max_users_in_list) + "\").text()); $(\"#showlogins\").hide();'>" + str(dbuser.login) + "</a><br>"
                 else:
                     responsehtml += "<a href=/changeinfo/" + str(dbuser.key().id()) + ">" + str(dbuser.login) + "</a><br>"
         if login != "": self.response.out.write(responsehtml)
     else:
         
         need_delete = bool(self.request.get('delete'))
         if not need_delete:
             avatara = DBAvatara()
             data = self.request.get("img")
             if data:
                 print "userava%s" % self.request.get('userid')
                 memcache.delete("userava%s" % self.request.get('userid'))
                 try:
                     
                     dbQuery = DBAvatara.gql("WHERE userid = :dbuserid", 
                                             dbuserid = int(self.request.get('userid')))
                     avataras = dbQuery.fetch(1)
                     avatara = avataras[0]
                     small = images.Image(data).width if images.Image(data).width < images.Image(data).height else images.Image(data).height
                     avatar = images.crop(data, 0., 0., small/float(images.Image(data).width), small/float(images.Image(data).height))
                     avatar = images.resize(avatar, 128, 128)
                     avatara.image = db.Blob(avatar)
                     avatara.put()
                 except:
                     small = images.Image(data).width if images.Image(data).width < images.Image(data).height else images.Image(data).height
                     avatar = images.crop(data, 0., 0., small/float(images.Image(data).width), small/float(images.Image(data).height))
                     avatar = images.resize(avatar, 128, 128)
                     avatara.image = db.Blob(avatar)
                     avatara.userid = int(self.request.get('userid'))
                     avatara.put()
         else:
             dbQuery = db.GqlQuery("SELECT __key__ FROM DBAvatara WHERE userid = :dbuserid", 
                                   dbuserid = int(self.request.get('userid')))
             db.delete(dbQuery)
             
         user = DBUser.get_by_id(int(self.request.get('userid')))
         #editeduser = DBUser()
         user.name = cgi.escape(self.request.get('name'))
         user.surname = cgi.escape(self.request.get('surname'))
         user.about = cgi.escape(self.request.get('user_about'))
         user.twitter = cgi.escape(self.request.get('twitter'))
         user.livejournal = cgi.escape(self.request.get('livejournal'))
         answer = '<h1>Данные изменены</h1><br>'
         self.insertMenu()
         if user.email != self.request.get('email'):
             user.email = self.request.get('email')
             confirmation = hashlib.md5(str(random.random())).hexdigest()
             dbuser.confirmation = confirmation
             rc = RegisterConfirm()
             rc.sendEmailCheck(self.request.get('email'), confirmation)
             answer += '<h1>Почта была изменена и на новый адрес было выслано письмо для подтверждения регистрации</h1>'
         if self.request.get('password') != '':
             if user.password == hashlib.md5(self.request.get('oldpassword')).hexdigest():
                 user.password = hashlib.md5(self.request.get('password')).hexdigest()
             else:
                 self.insertContent('<h1>Пароль не был изменен</h1><br>')
         user.put()
         
         self.insertContent('<h1>Данные изменены</h1>')
         self.drawPage()
Ejemplo n.º 36
0
    def get(self):
        if self.checkSession(self.request.headers.get('Cookie'), False):
            self.insertMenu()
        id = int(self.request.uri.split('/')[-1])
        object = DBGalleryObject.get_by_id(id)
        
        """ count rating """
        votes = DBGalleryObjectRate.gql("where object = :o_key", o_key = id)
        rating = 0
        for vote in votes:
            if vote.is_nice:
                rating += 1
            else:
                rating -= 1
        if rating <0:
            rating = 0 
        can_vote = DBGalleryObjectRate().still_can_vote(self.Session['userid'], id)
        obj = DBGalleryObjectRate.gql("where object = :o_key and voter = :userid", o_key = id, userid = self.Session['userid'])
        my_vote = bool(obj[0].is_nice) if not can_vote else False
        user = DBUser.get_by_id(int(object.userid))

        albums = db.Query(DBAlbum)
        albums.filter("objectid =", id)
        albumhtml = ""
        for album in albums:
            albumhtml += """
                <div class="main">
        
                <div style="width: 100%; float: left;">
                    <div style="float: left;"><img src="/images/border_left_up.png" /></div>
                    <div style="float: right;"><img src="/images/border_right_up.png" /></div>
                </div>
                
                <div style="padding-left: 20px; margin-right: 20px; font-size: 18px;">Альбом <a href=\"/album/""" + str(album.key().id()) + """\">\"""" + album.name.encode("utf8") + """\"</a></div>
                <div style="padding-left: 20px; padding-top: 10px;">
                <a href=\"/album/""" + str(album.key().id()) + """\">Нажмите, чтобы посмотреть весь альбом</a>
                </div>
                <div style="padding-left: 20px; margin-right: 20px; padding-top: 10px;" class="triggers">
            """
            photos = DBPhoto.gql("where albumid = :albumid limit 0,6", albumid = int(album.key().id()))
            photohtml = ""
            for photo in photos:
                photohtml += """<div style="float: left; width: 136px; margin-right: 10px;"><a href="/picture/watermark/4/""" + str(photo.key().id()) + """\"><img src="/picture/3/""" + str(photo.key().id()) + """\" /></a></div>"""
            albumhtml += photohtml + """
                        <div style="clear: both; margin: 20px 20px 0px 0px; padding-top: 20px;">Комментариев к альбому: """ + str(album.comments_count if album.comments_count else 0) + """</div>
                        </div>
                        
                        <div style="width: 100%; float: left;">
                            <div style="float: left;"><img src="/images/border_left_down.png" /></div>
                            <div style="float: right;"><img src="/images/border_right_down.png" /></div>
                        </div>
                        
                </div>"""
#            self.insertContent("""<li><a href='/album/""" + str(album.key().id()) + """'>""" + album.name.encode("utf8") + """</a></li>""")
        show_rating = False
        if self.Session['access'] >= 0:
            show_rating = True
        self.insertContent("</div>")
        
        new_f = DBFavorites()
        in_fav = new_f.exists(self.Session['userid'], id, 1)

        self.insertTemplate("tpl_object_view.html", { 
                                                      'objectname' : object.name.encode("utf8"), 
                                                      'objectid' : str(id),
                                                      'objectdesription' : object.description.encode("utf8").split("\n")[1][1:-1] if object.description and len(object.description.encode("utf8").split("\n"))>1 else "</p>",
                                                      'ownerlogin' : user.login.encode("utf8"),
                                                      'ownername' : user.name.encode("utf8"),
                                                      'ownersurname' : user.surname.encode("utf8"),
                                                      'albums' : albumhtml,
                                                      'rating' : rating,
                                                      'show_rating' : show_rating,
                                                      'delobject' : True if int(object.userid) == self.Session['userid'] or self.Session['access'] >= 8 else False,
                                                      'can_vote': can_vote,
                                                      'my_vote': my_vote,
                                                      'in_fav' : in_fav,
                                                      } )
        self.drawPage("Объект :: " + object.name.encode("utf8"))
        
Ejemplo n.º 37
0
 def send_all(self, subject, body):
     all = DBUser.all()
     self._send(all, subject, body)
Ejemplo n.º 38
0
    def get(self):
        self.checkSession(self.request.headers.get('Cookie'), False)
        id = int(self.request.uri.split('/')[-1])
        self.insertMenu()
        album = DBAlbum.get_by_id(id)
        object = DBGalleryObject.get_by_id(int(album.objectid))

        photos = db.Query(DBPhoto)
        photos.filter("albumid =", id)
        
        user = DBUser.get_by_id(int(object.userid))
            
        
        
#        self.insertContent("""
#        
#        <div id="triggers">
#        """)
        photos_html = ""
        for photo in photos:
#            taghtml = ""
#            try:
#                tags = photo.tags.encode("utf8").split(", ")
#                for tag in tags:
#                    taghtml += tag + """, """
##                    taghtml += """<form style="float: left;" id="search""" + tag + """" action="/search/" method="post"><input type="hidden" name="find" value=""" + tag + """><span class="tag" id="hover" onclick="tagsubmit(\"""" + tag + """\");">""" + tag + """</span></form>"""
#            except: 
#                taghtml = "Тэги отсутствуют"\
            dbtags = DBPhotoTags.gql("where imageid = :imageid", imageid = int(photo.key().id()))
            tags = dbtags[0].tags.encode("utf8") if dbtags.count() != 0 else """Тэги отсутствуют"""
            photos_html += """
    <div style="float: left; width: 136px; margin-right: 10px;">
    <a href="/picture/watermark/4/""" + str(photo.key().id()) + """" title=\"""" + tags + """\">
        <img src="/picture/3/""" + str(photo.key().id()) + """" />
    </a>
"""
#            try:
#                tags = photo.tags.encode("utf8").split(", ")
#                for tag in tags:
#                    self.insertContent("""<div style="float: left;"><form style="float: left;" id="search""" + tag + """" action="/search/" method="post"><input type="hidden" name="find" value=""" + tag + """><span class="tag" id="hover" onclick='$("#search""" + tag + """").submit()'>""" + tag + """</span></form></div>""")
#            except: pass
            try:
                if(self.Session['access'] >=8  or self.Session['userid'] == int(album.userid) ):
                    photos_html += """<div style="float: left; margin-left: 4px;"><span id="hover" class="tag" onclick='window.location = "/edit_photo/%s";'>Редактировать</span></div>""" % str(str(photo.key().id()))
                    photos_html += """<div style="float: left; font-size: 10px; margin-left: 4px;">Photo ID: """ + str(photo.key().id()) + """</div>"""
            except: pass
            photos_html += "</div>"
            
        options = ''
        if self.Session['access'] > 5:
            objects = db.Query(DBGalleryObject)
            if self.Session['access'] < 8:
                objects.filter("userid =", self.Session['userid'])
                if objects.count()!=0: objects.order("name")
            else:
                objects.order("userid")
            
            for objecti in objects:
                owner = DBUser.get_by_id(int(objecti.userid))
                own = """(Объект """ + owner.login.encode("utf8") + """) """
                selected = ""
                if int(objecti.key().id()) == int(album.objectid):
                    selected = "selected"
                options += """<option """ + selected + """ value=""" + str(objecti.key().id()) + """>""" + own + objecti.name.encode("utf8") + """</option>"""
            
        
        new_f = DBFavorites()
        in_fav = new_f.exists(self.Session['userid'], id, 2)
        
        self.insertTemplate("tpl_album_view.html", { 'albumid' : str(id),
                                                                 'isadmin' : True if self.Session['access'] >= 8 else False, 
                                                                 'name' : album.name.encode("utf8"),
                                                                 'connected' : object.name.encode("utf8"),
                                                                 'objectid' : str(object.key().id()),
                                                                 'ownerlogin' : user.login.encode("utf8"),
                                                                 'ownername' : user.name.encode("utf8"),
                                                                 'ownersurname' : user.surname.encode("utf8"),
                                                                 'addphoto' : True if int(object.userid) == self.Session['userid'] or self.Session['access'] >= 8 else False,
                                                                 'photos' : photos_html,
                                                                 'options' : options,
                                                                 'in_fav' : in_fav,
                                                                  })
        self.insertComments(album.key())
        self.drawPage("Альбом :: "+album.name.encode("utf8"))
Ejemplo n.º 39
0
    def post(self):
        self.checkSession(self.request.headers.get('Cookie'), False)
        event = int(self.request.uri.split('/')[-1])
        if not self.Session['authorized']:
            if self.request.get('name') != '' and self.request.get('surname') != '':
                user = db.GqlQuery("SELECT * FROM DBUser WHERE email = :email", 
                                   email = str(self.request.get('email')))
                if user.count() == 0:
                    newuser = DBUser()
                    newuser.name = self.request.get('name')
                    newuser.surname = self.request.get('surname')
                    newuser.login = str(cgi.escape(self.request.get('email'))).lower()
                    newuser.email = str(self.request.get('email'))
                    pwchars = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
                    pwd = "".join(random.choice(pwchars) for _ in range(8))
                    newuser.password = hashlib.md5(str(pwd)).hexdigest()
                    confirmation = hashlib.md5(str(random.random())).hexdigest()
                    newuser.confirmation = confirmation
                    newuser.type = 'pending-email'
                    newuser.put()
                    try:
                        
                        tpl_body = template.Template (self.paramByName("tpl_eventRegMailBody"))
                        mail_body = tpl_body.render(template.Context({
                                                                      "event_url": self.paramByName("url") + "/event/" +  str(event),
                                                                      "confirm": self.paramByName("url") + "/confirm/" + confirmation,
                                                                      "login": str(cgi.escape(self.request.get('email'))),
                                                                      "password": str(pwd)
                                                                      }))
                        
                        mail.send_mail(sender = self.paramByName("email"), 
                                       to = str(self.request.get('email')), 
                                       subject = self.paramByName("eventRegMailSubj"), 
                                       body = mail_body)
                        self.insertContent("""Вы зарегистрированны. На вашу почту была выслана регистрационная информация.<br>""")
                    except:
                        self.insertContent("""Вы зарегистрировались на мероприятие, но в процессе обработки произошел сбой.<br> 
                                    Если вы получили регистрационное письмо, авторизуйтесь с указанными там реквизитами.<br>
                                    Или <a href="/contacts">свяжитесь с администрацией</a>""")
            else:
                self.insertContent("Данные были введены неверно!")
                self.drawPage()
                return

        dbuser = db.GqlQuery("SELECT * FROM DBUser WHERE email = :email", email = str(cgi.escape(self.request.get('email'))).replace("%40", "@"))
        userid = self.Session['userid'] if self.Session['authorized'] else dbuser.fetch(1)[0].key().id()

        anketa = DBEventAnketa()
        anketa.userid = int(userid)
        anketa.eventid = int(event)
        anketa.name = db.Text(self.Session['name'], "utf_8") if self.Session['authorized'] else self.request.get('name')
        anketa.surname = db.Text(self.Session['surname'], "utf_8") if self.Session['authorized'] else self.request.get('surname')
        anketa.phone = self.request.get('phone')
        anketa.email = self.Session['email'] if self.Session['authorized'] else self.request.get('email')
        anketa.company = self.request.get('company')
        anketa.position = self.request.get('position')
#        anketa.payway = int(self.request.get('payway'))
        if self.request.get('is_portfolio'):
            anketa.is_portfolio = bool(int(self.request.get('is_portfolio')))
        anketa.additional = self.request.get('additional')
        if self.request.get('isarhitect'):
            anketa.isarhitect = bool(int(self.request.get('isarhitect')))
        anketa.put()
        self.showMessage(""" Ваша заявка принята! """)
        
Ejemplo n.º 40
0
    def post(self):
        #self.checkSession(self.request.headers.get('Cookie'))
        temp_uri = self.request.uri
        uri = temp_uri.split('/')
        if uri[-2] == 'checklog':
            try:
                if not self.checkLogin(self.request.get('username')): 1 / 0
                self.response.out.write(self.answer)
            except:
                if (self.answer != ""):
                    self.response.out.write(self.answer)
                else:
                    self.response.out.write(
                        "<font color = red>В логине можно использовать только буквы латинского алфавита и цифры,<br>а его длинна должна быть не менее четырех символов</font>"
                    )
        elif uri[-2] == 'checkmail':
            try:
                if not self.checkEmail(self.request.get('email'),
                                       self.request.get('emailload'),
                                       self.request.get('username')):
                    self.response.out.write(
                        "<font color = Red>Пользователь с таким адресом уже зарегистрирован</font>"
                    )

                else:
                    1 / 0
            except:
                self.response.out.write(
                    "<font color = Green>Почта введена верно</font>")

        else:
            is_invited = False
            hash = str(uri[-1])
            invites = db.GqlQuery("SELECT * FROM DBInvite where used = :used",
                                  used=False)
            this_invite = DBInvite()
            for invite in invites:
                if invite.hash == hash:
                    is_invited = True
                    this_invite = invite
                    break

            if self.checkLogin(self.request.get('login')) and self.checkEmail(
                    self.request.get('email')):
                this_invite.used = True
                dbuser = DBUser()
                dbuser.login = str(cgi.escape(
                    self.request.get('login'))).lower()
                dbuser.password = hashlib.md5(
                    self.request.get('password')).hexdigest()
                dbuser.name = cgi.escape(self.request.get('name'))
                dbuser.surname = cgi.escape(self.request.get('surname'))
                dbuser.email = cgi.escape(self.request.get('email'))
                confirmation = hashlib.md5(str(random.random())).hexdigest()
                dbuser.confirmation = confirmation
                dbuser.type = 'pending'

                if is_invited:
                    dbuser.access = 6
                else:
                    dbuser.access = 0

                this_invite.put()

                #                try:

                subject = """[%s] Подтверждение регистрации""" % self.paramByName(
                    "name")

                body = """Спасибо за регистрацию на нашем сайте! Пожалуйста, активируйте свою учетную запись, следуя по ссылке:\n%s/confirm/%s\n__\nС уважением, администрация сайта.""" % (
                    self.paramByName("url"), confirmation)
                PostOffice().append_to_queue(dbuser.put(),
                                             subject.decode("utf-8"),
                                             body.decode("utf-8"))
                #                except:
                #                    self.insertContent('Письмо на подверждение учетной записи не было отправлено<br>')
                self.showMessage(
                    '<h1>Регистрация успешно завершена<br>На ящик ' +
                    str(dbuser.email) +
                    ' было отправлено письмо для активации вашей учетной записи<br>Вы сможете зайти на сайт только после прохождения активации!</h1><br><a href=/>Вернуться на главную</a>'
                )
                return
            else:
                self.insertContent("<h1>Данные введены неверно</h1>")
            self.drawPage("Регистрация")
Ejemplo n.º 41
0
    def post(self):
        if super(CommentHandler, self).get():
            if not self.request.get("content"):
                self.showMessage("""Введите текст комментария!
                <br><a href='""" + self.request.headers.get("Referer") +
                                 """'>Вернуться в тему</a>""")
                return
            comment = DBComments()
            user = DBUser.get_by_id(self.Session['userid'])
            comment.user = user
            if user.comments_count:
                user.comments_count = user.comments_count + 1
            user.put()

            comment.obj = db.Key(str(self.request.get('entity')))
            content = self.request.get("content")
            comment.content = cgi.escape(content).replace("\n", "<br />")

            comment.parent_comment = DBComments().get(self.request.get('parent_comment')) if \
                                     self.request.get('parent_comment') else None
            # Old part with id
            #DBComments().get_by_id(int(self.request.get('parent_comment'))) if \
            #                       self.request.get('parent_comment') else None

            key_ = comment.put()
            comment = db.get(key_)

            try:
                comment.obj.increase_comments_count(comment)
            except:
                pass

            #Отсылаем владельцу топика
            if self.Session['user_key'] != comment.obj.author.key():
                body = template.render(
                    "comments/comment_notification.html", {
                        'user': self.Session,
                        'comment': comment,
                        'referer': self.request.headers.get("Referer"),
                        'site_url': DBCustomField().getByName('url')
                    })
                PostOffice().append_to_queue(
                    comment.obj.author.key(),
                    """Новый комментарий на портале Архимир""".decode("utf-8"),
                    body.decode("utf-8"))

            #Отсылаем владельцу коммента-предка:
            if comment.parent_comment and \
            (self.Session['user_key'] != comment.parent_comment.user.key()) and \
            (comment.obj.author.key() != comment.parent_comment.user.key()):
                body = template.render(
                    "comments/comment_notification.html", {
                        'to_parent': True,
                        'user': self.Session,
                        'comment': comment,
                        'referer': self.request.headers.get("Referer"),
                        'site_url': DBCustomField().getByName('url')
                    })
                PostOffice().append_to_queue(
                    comment.parent_comment.user.key(),
                    """Новый комментарий на портале Архимир""".decode("utf-8"),
                    body.decode("utf-8"))
            self.redirect(self.request.headers.get("Referer"))
Ejemplo n.º 42
0
    def get(self):

        self.checkSession(self.request.headers.get('Cookie'), False)

        is_admin = False
        if self.Session['access'] == 10: is_admin = True

        _categories = []

        cats = db.GqlQuery("SELECT * FROM DBForumCategory order by position")
        #comments = Comments()

        all_comments_count = 0
        all_topics_count = 0
        for cat in cats:

            #topics = db.GqlQuery("SELECT * FROM DBForumTopic where category = :cat", cat = cat.key())
            if cat.access and not cat.access <= self.Session['access']:
                continue
            try:
                all_comments_count += cat.comments_count
            except:
                cat.comments_count = 0
                cat.put()

            try:
                all_topics_count += cat.topics_count
            except:
                cat.topics_count = 0
                cat.put()

            try:
                cat.last_comment.obj.name = cat.last_comment.obj.name[
                    0:32] + "..." if len(cat.last_comment.obj.name
                                         ) > 32 else cat.last_comment.obj.name
            except:
                pass
            _categories.append({
                'id':
                int(cat.key().id()),
                'name':
                cat.name.encode("utf-8"),
                'descr':
                cat.descr.encode("utf-8") if cat.descr else None,
                'last_message':
                cat.last_comment,
                'answers':
                cat.comments_count,
                'topics':
                cat.topics_count
                #'last_message' : last_message, 'answers' : comments_count, 'topics' : len(formilized_topics)
            })

        self.insertTemplate(
            'forum/forum_main.html', {
                'cats': _categories,
                'is_admin': is_admin,
                'all_comments_count': all_comments_count,
                'all_topics_count': all_topics_count,
                'logged': self.Session['authorized'],
                'your_comments': DBUser().count_comments(
                    self.Session['user_key'])
            })
        self.drawPage("Форум")
Ejemplo n.º 43
0
    def post(self):
        self.checkSession(self.request.headers.get('Cookie'))
        login = str(self.request.get('logins'))
        if login != "":
            responsehtml = ''
            dbusers = db.GqlQuery("SELECT * FROM DBUser")
            max_users_in_list = 4
            for dbuser in dbusers:
                if str(dbuser.login).find(login) >= 0 and max_users_in_list:
                    max_users_in_list -= 1
                    if str(self.request.get("objectadd")) == "true":
                        responsehtml += "<a style='cursor: pointer;' id='user" + str(
                            max_users_in_list
                        ) + "' onclick='$(\"#login\").attr(\"value\", $(\"#user" + str(
                            max_users_in_list
                        ) + "\").text()); $(\"#showlogins\").hide();'>" + str(
                            dbuser.login) + "</a><br>"
                    else:
                        responsehtml += "<a href=/changeinfo/" + str(
                            dbuser.key().id()) + ">" + str(
                                dbuser.login) + "</a><br>"
            if login != "": self.response.out.write(responsehtml)
        else:

            need_delete = bool(self.request.get('delete'))
            if not need_delete:
                avatara = DBAvatara()
                data = self.request.get("img")
                if data:
                    print "userava%s" % self.request.get('userid')
                    memcache.delete("userava%s" % self.request.get('userid'))
                    try:

                        dbQuery = DBAvatara.gql(
                            "WHERE userid = :dbuserid",
                            dbuserid=int(self.request.get('userid')))
                        avataras = dbQuery.fetch(1)
                        avatara = avataras[0]
                        small = images.Image(data).width if images.Image(
                            data).width < images.Image(
                                data).height else images.Image(data).height
                        avatar = images.crop(
                            data, 0., 0.,
                            small / float(images.Image(data).width),
                            small / float(images.Image(data).height))
                        avatar = images.resize(avatar, 128, 128)
                        avatara.image = db.Blob(avatar)
                        avatara.put()
                    except:
                        small = images.Image(data).width if images.Image(
                            data).width < images.Image(
                                data).height else images.Image(data).height
                        avatar = images.crop(
                            data, 0., 0.,
                            small / float(images.Image(data).width),
                            small / float(images.Image(data).height))
                        avatar = images.resize(avatar, 128, 128)
                        avatara.image = db.Blob(avatar)
                        avatara.userid = int(self.request.get('userid'))
                        avatara.put()
            else:
                dbQuery = db.GqlQuery(
                    "SELECT __key__ FROM DBAvatara WHERE userid = :dbuserid",
                    dbuserid=int(self.request.get('userid')))
                db.delete(dbQuery)

            user = DBUser.get_by_id(int(self.request.get('userid')))
            #editeduser = DBUser()
            user.name = cgi.escape(self.request.get('name'))
            user.surname = cgi.escape(self.request.get('surname'))
            user.about = cgi.escape(self.request.get('user_about'))
            user.twitter = cgi.escape(self.request.get('twitter'))
            user.livejournal = cgi.escape(self.request.get('livejournal'))
            answer = '<h1>Данные изменены</h1><br>'
            self.insertMenu()
            if user.email != self.request.get('email'):
                user.email = self.request.get('email')
                confirmation = hashlib.md5(str(random.random())).hexdigest()
                dbuser.confirmation = confirmation
                rc = RegisterConfirm()
                rc.sendEmailCheck(self.request.get('email'), confirmation)
                answer += '<h1>Почта была изменена и на новый адрес было выслано письмо для подтверждения регистрации</h1>'
            if self.request.get('password') != '':
                if user.password == hashlib.md5(
                        self.request.get('oldpassword')).hexdigest():
                    user.password = hashlib.md5(
                        self.request.get('password')).hexdigest()
                else:
                    self.insertContent('<h1>Пароль не был изменен</h1><br>')
            user.put()

            self.insertContent('<h1>Данные изменены</h1>')
            self.drawPage()
Ejemplo n.º 44
0
    def post(self):
        #self.checkSession(self.request.headers.get('Cookie'))
        temp_uri = self.request.uri
        uri = temp_uri.split('/')
        if uri[-2]=='checklog':
            try:
                if not self.checkLogin(self.request.get('username')): 1/0
                self.response.out.write(self.answer)
            except:
                if(self.answer!=""):
                    self.response.out.write(self.answer)
                else:
                    self.response.out.write("<font color = red>В логине можно использовать только буквы латинского алфавита и цифры,<br>а его длинна должна быть не менее четырех символов</font>")
        elif uri[-2]=='checkmail':
            try:
                if not self.checkEmail(self.request.get('email'), self.request.get('emailload'), self.request.get('username')):
                    self.response.out.write("<font color = Red>Пользователь с таким адресом уже зарегистрирован</font>")
                    
                else:
                    1/0
            except:
                self.response.out.write("<font color = Green>Почта введена верно</font>")
        
        else:
            is_invited = False
            hash = str(uri[-1])
            invites = db.GqlQuery("SELECT * FROM DBInvite where used = :used", used=False)
            this_invite = DBInvite()
            for invite in invites:
                if invite.hash == hash:
                    is_invited = True
                    this_invite = invite
                    break
            
            if self.checkLogin(self.request.get('login')) and self.checkEmail(self.request.get('email')):
                this_invite.used = True
                dbuser = DBUser()
                dbuser.login = str(cgi.escape(self.request.get('login'))).lower()
                dbuser.password = hashlib.md5(self.request.get('password')).hexdigest()
                dbuser.name = cgi.escape(self.request.get('name'))
                dbuser.surname = cgi.escape(self.request.get('surname'))
                dbuser.email = cgi.escape(self.request.get('email'))
                confirmation = hashlib.md5(str(random.random())).hexdigest()
                dbuser.confirmation = confirmation
                dbuser.type = 'pending'
                
                if is_invited:
                    dbuser.access = 6
                else:
                    dbuser.access = 0
                
                this_invite.put()
                
                
#                try:
                
                subject = """[%s] Подтверждение регистрации""" % self.paramByName("name")

                body = """Спасибо за регистрацию на нашем сайте! Пожалуйста, активируйте свою учетную запись, следуя по ссылке:\n%s/confirm/%s\n__\nС уважением, администрация сайта.""" % (self.paramByName("url"), confirmation)
                PostOffice().append_to_queue(dbuser.put(), subject.decode("utf-8"), body.decode("utf-8"))
#                except:
#                    self.insertContent('Письмо на подверждение учетной записи не было отправлено<br>')
                self.showMessage('<h1>Регистрация успешно завершена<br>На ящик '+str(dbuser.email)+' было отправлено письмо для активации вашей учетной записи<br>Вы сможете зайти на сайт только после прохождения активации!</h1><br><a href=/>Вернуться на главную</a>')
                return
            else:
                self.insertContent("<h1>Данные введены неверно</h1>")
            self.drawPage("Регистрация")