Пример #1
0
    def post(self, slug=None):
        self.response.headers['Content-Type'] = 'text/xml'
        if not slug:
            postid = self.request.get('p')
            try:
                postid = int(postid)
            except:
                postid = None
            if not postid:
                self.response.out.write(self.error % 'empty slug/postid')
                return

        coming_url = self.request.get('url')
        blog_name = myfilter.do_filter(self.request.get('blog_name'))
        excerpt = myfilter.do_filter(self.request.get('excerpt'))
        title = myfilter.do_filter(self.request.get('title'))

        if not coming_url or not blog_name or not excerpt or not title:
            self.response.out.write(self.error % 'not enough post info')
            return

        import time

        time.sleep(0.5)

        try:
            result = urlfetch.fetch(coming_url)
            if result.status_code != 200 or g_blog.baseurl + '/' + slug not in result.content.decode('ascii', 'ignore'):
                self.response.out.write(self.error % 'probably spam')
                return
        except Exception, e:
            logging.info(e)
            self.response.out.write(self.error % 'urlfetch error')
            return
Пример #2
0
def handle_socket(client_conn):

    BUF_SIZE = 2048  # 缓冲区大小
    client_req = ''
    client_conn.settimeout(C.CLIENT_SOCKET_TIMEOUT)
    try:
        # 缓冲区不满说明读取完毕,否则还应继续读取
        while True:
            buf = client_conn.recv(BUF_SIZE).decode('utf-8')
            client_req += buf
            if len(buf) < BUF_SIZE:
                break
        log("接收到请求:\n------\n" + client_req + '\n------', 1)

    except Exception as e:
        print("超时了,接收到的信息如下\n-------\n" + client_req + "\n------")
        print(e)
        return

    if not client_req:
        log("出现空请求,丢弃", 1)
        return

    ip = client_conn.getpeername()[0]
    log("请求ip:" + ip, 1)

    action = do_filter(client_req, ip, common.compiled_rules,
                       common.blacklists, common.whitelists)
    do_response(client_conn, client_req, action)
    log("-----------请求处理完毕。---------", 1)
Пример #3
0
    def post(self, slug=None):
        self.response.headers["Content-Type"] = "text/xml"
        if not slug:
            postid = self.request.get("p")
            try:
                postid = int(postid)
            except:
                postid = None
            if not postid:
                self.response.out.write(self.error % "empty slug/postid")
                return

        coming_url = self.request.get("url")
        blog_name = myfilter.do_filter(self.request.get("blog_name"))
        excerpt = myfilter.do_filter(self.request.get("excerpt"))
        title = myfilter.do_filter(self.request.get("title"))

        if not coming_url or not blog_name or not excerpt or not title:
            self.response.out.write(self.error % "not enough post info")
            return

        import time

        # wait for half second in case otherside hasn't been published
        time.sleep(0.5)

        # also checking the coming url is valid and contains our link
        # this is not standard trackback behavior
        try:
            result = urlfetch.fetch(coming_url)
            if result.status_code != 200 or (
                (g_blog.baseurl + "/" + slug) not in result.content.decode("ascii", "ignore")
            ):
                self.response.out.write(self.error % "probably spam")
                return
        except Exception, e:
            logging.info(e)
            self.response.out.write(self.error % "urlfetch error")
            return
Пример #4
0
	def post(self,slug=None):
		useajax=self.param('useajax')=='1'

		name=self.param('author')
		email=self.param('email')
		url=self.param('url')

		key=self.param('key')
		content=self.param('comment')
		parent_id=self.paramint('parentid',0)
		reply_notify_mail=self.parambool('reply_notify_mail')

		sess=Session(self,timeout=180)
		if not self.is_login:
			#if not (self.request.cookies.get('comment_user', '')):
			try:
				check_ret=True
				if g_blog.comment_check_type in (1,2)  :
					checkret=self.param('checkret')
					logging.info('______'+checkret)
					check_ret=(int(checkret) == sess['code'])
				elif  g_blog.comment_check_type ==3:
					import app.gbtools as gb
					checknum=self.param('checknum')
					checkret=self.param('checkret')
					check_ret=eval(checknum)==int(gb.stringQ2B( checkret))

				if not check_ret:
					if useajax:
						self.write(simplejson.dumps((False,-102,_('Your check code is invalid .'))))
					else:
						self.error(-102,_('Your check code is invalid .'))
					return
			except:
				if useajax:
					self.write(simplejson.dumps((False,-102,_('Your check code is invalid .'))))
				else:
					self.error(-102,_('Your check code is invalid .'))
				return

		sess.invalidate()
		content=content.replace('\n','<br>')
		content=myfilter.do_filter(content)
		name=cgi.escape(name)[:20]
		url=cgi.escape(url)[:100]

		if not (name and email and content):
			if useajax:
						self.write(simplejson.dumps((False,-101,_('Please input name, email and comment .'))))
			else:
				self.error(-101,_('Please input name, email and comment .'))
		else:
			comment=Comment(author=name,
							content=content,
							email=email,
							reply_notify_mail=reply_notify_mail,
							entry=Entry.get(key))
			if url:
			   try:
					comment.weburl=url
			   except:
				   comment.weburl=None

			#name=name.decode('utf8').encode('gb2312')


			info_str='#@#'.join([urlencode(name),urlencode(email),urlencode(url)])

			 #info_str='#@#'.join([name,email,url.encode('utf8')])
			cookiestr='comment_user=%s;expires=%s;domain=%s;path=/'%( info_str,
					   (datetime.now()+timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
					   ''
					   )
			comment.ip=self.request.remote_addr
			
			if parent_id:
				comment.parent=Comment.get_by_id(parent_id)
				
			try:
				comment.save()
				memcache.delete("/"+comment.entry.link)

				self.response.headers.add_header( 'Set-Cookie', cookiestr)
				if useajax:
					comment_c=self.get_render('comment',{'comment':comment})
					self.write(simplejson.dumps((True,comment_c.decode('utf8'))))
				else:
					self.redirect(self.referer+"#comment-"+str(comment.key().id()))

				comment.entry.removecache()
				memcache.delete("/feed/comments")
			except:
				if useajax:
					self.write(simplejson.dumps((False,-102,_('Comment not allowed.'))))
				else:
					self.error(-102,_('Comment not allowed .'))
Пример #5
0
	def post(self,slug=None,postid=None):
		'''handle trackback'''
		error = '''
<?xml version="1.0" encoding="utf-8"?>
<response>
<error>1</error>
<message>%s</message>
</response>
'''
		success = '''
<?xml version="1.0" encoding="utf-8"?>
<response>
<error>0</error>
</response>
'''

		if not g_blog.allow_trackback:
			self.response.out.write(self.error % "Trackback denied.")
			return
		self.response.headers['Content-Type'] = "text/xml"
		if postid:
			entries = Entry.all().filter("published =", True).filter('post_id =', postid).fetch(1)
		else:
			slug=urldecode(slug)
			entries = Entry.all().filter("published =", True).filter('link =', slug).fetch(1)

		if not entries or len(entries) == 0 :#or  (postid and not entries[0].link.endswith(g_blog.default_link_format%{'post_id':postid})):
			self.response.out.write(error % "empty slug/postid")
			return
		#check code ,rejest spam
		entry=entries[0]
		#key=self.param("code")
		#if (self.request.uri!=entry.trackbackurl) or entry.is_external_page or not entry.allow_trackback:
		import cgi
		param=cgi.parse_qs(self.request.uri)
		if param.has_key('code'):
			code=param['code'][0]

		if  (not str(entry.key())==code) or entry.is_external_page or not entry.allow_trackback:
			self.response.out.write(error % "Invalid trackback url.")
			return


		coming_url = self.param('url')
		blog_name = myfilter.do_filter(self.param('blog_name'))
		excerpt = myfilter.do_filter(self.param('excerpt'))
		title = myfilter.do_filter(self.param('title'))

		if not coming_url or not blog_name or not excerpt or not title:
			self.response.out.write(error % "not enough post info")
			return

		import time
		#wait for half second in case otherside hasn't been published
		time.sleep(0.5)

##		#also checking the coming url is valid and contains our link
##		#this is not standard trackback behavior
##		try:
##
##			result = urlfetch.fetch(coming_url)
##			if result.status_code != 200 :
##				#or ((g_blog.baseurl + '/' + slug) not in result.content.decode('ascii','ignore')):
##				self.response.out.write(error % "probably spam")
##				return
##		except Exception, e:
##			logging.info("urlfetch error")
##			self.response.out.write(error % "urlfetch error")
##			return

		comment = Comment.all().filter("entry =", entry).filter("weburl =", coming_url).get()
		if comment:
			self.response.out.write(error % "has pinged before")
			return

		comment=Comment(author=blog_name,
				content="<strong>"+title[:250]+"...</strong><br/>" +
						excerpt[:250] + '...',
				weburl=coming_url,
				entry=entry)

		comment.ip=self.request.remote_addr
		comment.ctype=COMMENT_TRACKBACK
		try:
			comment.save()

			memcache.delete("/"+entry.link)
			self.write(success)
			g_blog.tigger_action("pingback_post",comment)
		except:
			self.response.out.write(error % "unknow error")
Пример #6
0
	def post(self,slug=None):
		useajax=self.param('useajax')=='1'

		name=self.param('author')
		email=self.param('email')
		url=self.param('url')

		key=self.param('key')
		content=self.param('comment')
		parent_id=self.paramint('parentid',0)
		reply_notify_mail=self.parambool('reply_notify_mail')

		sess=Session(self,timeout=180)

		if not self.is_login:
			#if not (self.request.cookies.get('comment_user', '')):
			try:
				check_ret=True
				if g_blog.comment_check_type in (1,2)  :
					checkret=self.param('checkret')
					check_ret=(int(checkret) == sess['code'])
				elif  g_blog.comment_check_type ==3:
					import app.gbtools as gb
					checknum=self.param('checknum')
					checkret=self.param('checkret')
					check_ret=eval(checknum)==int(gb.stringQ2B( checkret))
				elif g_blog.comment_check_type == 4:#reCAPTCHA, probably not working in China mainland
					ip = self.request.remote_addr
					private_key = "6Leox8YSAAAAAGJ734ttj4OYojDiCcsb1tcDBarA"
					resp = self.param('checkret')
					chalg = self.param('challenge')
					import urllib
					import urllib2
					params = urllib.urlencode({
						'privatekey': private_key,
						'remoteip' : ip,
						'challenge' : chalg,
						'response' : resp 
					})
					request = urllib2.Request(
						url = "http://www.google.com/recaptcha/api/verify",
						data = params,
						headers = { "Content-type": "application/x-www-form-urlencoded" }
						)
					httpresp = urllib2.urlopen(request)
					return_values = httpresp.read().splitlines();
					check_ret = (return_values[0] == "true")

				if not check_ret:
					if useajax:
						self.write(simplejson.dumps((False,-102,_('Your check code is invalid .')),ensure_ascii = False))
					else:
						self.error(-102,_('Your check code is invalid .'))
					return
			except Exception:
				logging.exception('Error when checking CAPTCHA')
				#Assume the captcha is right, which is less confusing. TODO: send admin an email to notify this event
				'''
				if useajax:
					self.write(simplejson.dumps((False,-102,_('Your check code is invalid .')),ensure_ascii = False))
				else:
					self.error(-102,_('Your check code is invalid .'))
				return
				'''

		sess.invalidate()
		content=content.replace('\n','<br />')
		content=myfilter.do_filter(content)
		name=cgi.escape(name)[:20]
		url=cgi.escape(url)[:100]

		if not (name and email and content):
			if useajax:
				self.write(simplejson.dumps((False,-101,_('Please input name, email and comment .'))))
			else:
				self.error(-101,_('Please input name, email and comment .'))
		else:
			comment=Comment(author=name,
							content=content,
							email=email,
							reply_notify_mail=reply_notify_mail,
							entry=Entry.get(key))

			if url:
				try:
					if not url.startswith(('http://','https://')):
						url = 'http://' + url
					comment.weburl=url
				except:
					comment.weburl=None

			#name=name.decode('utf8').encode('gb2312')
			info_str='#@#'.join([urlencode(name),urlencode(email),urlencode(url)])

			 #info_str='#@#'.join([name,email,url.encode('utf8')])
			cookiestr='comment_user=%s;expires=%s;domain=%s;path=/'%( info_str,
					   (datetime.now()+timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
					   ''
					   )
			comment.ip=self.request.remote_addr

			if parent_id:
				comment.parent=Comment.get_by_id(parent_id)

			comment.no=comment.entry.commentcount+1
			try:
				comment.save() #take care of cache

				self.response.headers.add_header( 'Set-Cookie', cookiestr)
				if useajax:
					comment_c=self.get_render('comment',{'comment':comment})
					self.write(simplejson.dumps((True,comment_c.decode('utf8')),ensure_ascii = False))
				else:
					self.redirect(self.referer+"#comment-"+str(comment.key().id()))

				comment.entry.removecache()
				memcache.delete("/feed/comments")
			except:
				if useajax:
					self.write(simplejson.dumps((False,-102,_('Comment not allowed.'))))
				else:
					self.error(-102,_('Comment not allowed .'))
Пример #7
0
    def post(self, slug=None):
        useajax = self.param('useajax') == '1'

        name = self.param('author')
        email = self.param('email')
        url = self.param('url')

        key = self.param('key')
        content = self.param('comment')
        parent_id = self.paramint('parentid', 0)
        reply_notify_mail = self.parambool('reply_notify_mail')

        sess = Session(self, timeout=180)
        if not self.is_login:
            #if not (self.request.cookies.get('comment_user', '')):
            try:
                check_ret = True
                if g_blog.comment_check_type in (1, 2):
                    checkret = self.param('checkret')
                    check_ret = (int(checkret) == sess['code'])
                elif g_blog.comment_check_type == 3:
                    import app.gbtools as gb
                    checknum = self.param('checknum')
                    checkret = self.param('checkret')
                    check_ret = eval(checknum) == int(gb.stringQ2B(checkret))

                if not check_ret:
                    if useajax:
                        self.write(
                            simplejson.dumps(
                                (False, -102,
                                 _('Your check code is invalid .')),
                                ensure_ascii=False))
                    else:
                        self.error(-102, _('Your check code is invalid .'))
                    return
            except:
                if useajax:
                    self.write(
                        simplejson.dumps(
                            (False, -102, _('Your check code is invalid .')),
                            ensure_ascii=False))
                else:
                    self.error(-102, _('Your check code is invalid .'))
                return

        sess.invalidate()
        content = content.replace('\n', '<br />')
        content = myfilter.do_filter(content)
        name = cgi.escape(name)[:20]
        url = cgi.escape(url)[:100]

        if not (name and email and content):
            if useajax:
                self.write(
                    simplejson.dumps(
                        (False, -101,
                         _('Please input name, email and comment .'))))
            else:
                self.error(-101, _('Please input name, email and comment .'))
        else:
            comment = Comment(author=name,
                              content=content,
                              email=email,
                              reply_notify_mail=reply_notify_mail,
                              entry=Entry.get(key))
            if url:
                try:
                    if not url.startswith(('http://', 'https://')):
                        url = 'http://' + url
                    comment.weburl = url
                except:
                    comment.weburl = None

            #name=name.decode('utf8').encode('gb2312')

            info_str = '#@#'.join(
                [urlencode(name),
                 urlencode(email),
                 urlencode(url)])

            #info_str='#@#'.join([name,email,url.encode('utf8')])
            cookiestr = 'comment_user=%s;expires=%s;domain=%s;path=/' % (
                info_str, (datetime.now() + timedelta(days=100)
                           ).strftime("%a, %d-%b-%Y %H:%M:%S GMT"), '')
            comment.ip = self.request.remote_addr

            if parent_id:
                comment.parent = Comment.get_by_id(parent_id)

            comment.no = comment.entry.commentcount + 1
            try:
                comment.save()
                memcache.delete("/" + comment.entry.link)

                self.response.headers.add_header('Set-Cookie', cookiestr)
                if useajax:
                    comment_c = self.get_render('comment',
                                                {'comment': comment})
                    self.write(
                        simplejson.dumps((True, comment_c.decode('utf8')),
                                         ensure_ascii=False))
                else:
                    self.redirect(self.referer + "#comment-" +
                                  str(comment.key().id()))

                comment.entry.removecache()
                memcache.delete("/feed/comments")
            except:
                if useajax:
                    self.write(
                        simplejson.dumps(
                            (False, -102, _('Comment not allowed.'))))
                else:
                    self.error(-102, _('Comment not allowed .'))
Пример #8
0
    def post(self, slug=None, postid=None):
        '''handle trackback'''
        error = '''<?xml version="1.0" encoding="utf-8"?>
<response>
<error>1</error>
<message>%s</message>
</response>
'''
        success = '''<?xml version="1.0" encoding="utf-8"?>
<response>
<error>0</error>
</response>
'''

        if not g_blog.allow_trackback:
            self.response.out.write(self.error % "Trackback denied.")
            return
        self.response.headers['Content-Type'] = "text/xml"
        if postid:
            entries = Entry.all().filter("published =",
                                         True).filter('post_id =',
                                                      postid).fetch(1)
        else:
            slug = urldecode(slug)
            entries = Entry.all().filter("published =",
                                         True).filter('link =', slug).fetch(1)

        if not entries or len(
                entries
        ) == 0:  #or  (postid and not entries[0].link.endswith(g_blog.default_link_format%{'post_id':postid})):
            self.response.out.write(error % "empty slug/postid")
            return
        #check code ,rejest spam
        entry = entries[0]
        logging.info(self.request.remote_addr + self.request.path + " " +
                     entry.trackbackurl)
        #key=self.param("code")
        #if (self.request.uri!=entry.trackbackurl) or entry.is_external_page or not entry.allow_trackback:
        #import cgi
        from urlparse import urlparse
        param = urlparse(self.request.uri)
        code = param[4]
        param = cgi.parse_qs(code)
        if param.has_key('code'):
            code = param['code'][0]

        if (not str(entry.key()) == code
            ) or entry.is_external_page or not entry.allow_trackback:
            self.response.out.write(error % "Invalid trackback url.")
            return

        coming_url = self.param('url')
        blog_name = myfilter.do_filter(self.param('blog_name'))
        excerpt = myfilter.do_filter(self.param('excerpt'))
        title = myfilter.do_filter(self.param('title'))

        if not coming_url or not blog_name or not excerpt or not title:
            self.response.out.write(error % "not enough post info")
            return

        import time
        #wait for half second in case otherside hasn't been published
        time.sleep(0.5)

        ##		#also checking the coming url is valid and contains our link
        ##		#this is not standard trackback behavior
        ##		try:
        ##
        ##			result = urlfetch.fetch(coming_url)
        ##			if result.status_code != 200 :
        ##				#or ((g_blog.baseurl + '/' + slug) not in result.content.decode('ascii','ignore')):
        ##				self.response.out.write(error % "probably spam")
        ##				return
        ##		except Exception, e:
        ##			logging.info("urlfetch error")
        ##			self.response.out.write(error % "urlfetch error")
        ##			return

        comment = Comment.all().filter("entry =",
                                       entry).filter("weburl =",
                                                     coming_url).get()
        if comment:
            self.response.out.write(error % "has pinged before")
            return

        comment = Comment(author=blog_name,
                          content="<strong>" + title[:250] +
                          "...</strong><br/>" + excerpt[:250] + '...',
                          weburl=coming_url,
                          entry=entry)

        comment.ip = self.request.remote_addr
        comment.ctype = COMMENT_TRACKBACK
        try:
            comment.save()

            memcache.delete("/" + entry.link)
            self.write(success)
            g_blog.tigger_action("pingback_post", comment)
        except:
            self.response.out.write(error % "unknow error")
Пример #9
0
    def post(self,slug=None):
        useajax=self.param('useajax')=='1'
##        if self.is_admin:
##            name=self.blog.author
##            email=self.login_user.email()
##            url=self.blog.baseurl
##        else:
        name=self.param('author')
        email=self.param('email')
        url=self.param('url')

        key=self.param('key')
        content=self.param('comment')
        checknum=self.param('checknum')
        checkret=self.param('checkret')
##        if useajax:
##            name=urldecode(name)
##            email=urldecode(email)
##            url=urldecode(url)
##            key=urldecode(key)
##            content=urldecode(content)
##            checknum=urldecode(checknum)
##            checkret=urldecode(checkret)

        if not self.is_login:
            if not (self.request.cookies.get('comment_user', '')):

                try:
                    import app.gbtools as gb
                    if eval(checknum)<>int(gb.stringQ2B( checkret)):
                        if useajax:
                            self.write(simplejson.dumps((False,-102,_('Your check code is invalid .'))))
                        else:
                            self.error(-102,_('Your check code is invalid .'))
                        return
                except:
                    if useajax:
                        self.write(simplejson.dumps((False,-102,_('Your check code is invalid .'))))
                    else:
                        self.error(-102,_('Your check code is invalid .'))
                    return



        content=content.replace('\n','<br>')
        content=myfilter.do_filter(content)
        name=cgi.escape(name)[:20]
        url=cgi.escape(url)[:100]

        if not (name and email and content):
            if useajax:
                        self.write(simplejson.dumps((False,-101,_('Please input name, email and comment .'))))
            else:
                self.error(-101,_('Please input name, email and comment .'))
        else:
            comment=Comment(author=name,
                            content=content,
                            email=email,
                            entry=Entry.get(key))
            if url:
               try:
                    comment.weburl=url
               except:
                   comment.weburl='http://'+url

            #name=name.decode('utf8').encode('gb2312')


            info_str='#@#'.join([urlencode(name),urlencode(email),urlencode(url)])

            logging.info("info:"+info_str)
             #info_str='#@#'.join([name,email,url.encode('utf8')])
            cookiestr='comment_user=%s;expires=%s;domain=%s;path=/'%( info_str,
                       (datetime.now()+timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
                       ''
                       )
            comment.save()
            memcache.delete("/"+comment.entry.link)

            self.response.headers.add_header( 'Set-Cookie', cookiestr)
            if useajax:
                comment_c=self.get_render('comment',{'comment':comment})
                self.write(simplejson.dumps((True,comment_c.decode('utf8'))))
            else:

                self.redirect(self.referer)
Пример #10
0
    def post(self, slug=None):
        useajax = self.param("useajax") == "1"

        name = self.param("author")
        email = self.param("email")
        url = self.param("url")

        key = self.param("key")
        content = self.param("comment")
        parent_id = self.paramint("parentid", 0)
        reply_notify_mail = self.parambool("reply_notify_mail")

        sess = Session(self, timeout=180)
        if not self.is_login:
            # if not (self.request.cookies.get('comment_user', '')):
            try:
                check_ret = True
                if g_blog.comment_check_type in (1, 2):
                    checkret = self.param("checkret")
                    check_ret = int(checkret) == sess["code"]
                elif g_blog.comment_check_type == 3:
                    import app.gbtools as gb

                    checknum = self.param("checknum")
                    checkret = self.param("checkret")
                    check_ret = eval(checknum) == int(gb.stringQ2B(checkret))

                if not check_ret:
                    if useajax:
                        self.write(
                            simplejson.dumps((False, -102, _("Your check code is invalid .")), ensure_ascii=False)
                        )
                    else:
                        self.error(-102, _("Your check code is invalid ."))
                    return
            except:
                if useajax:
                    self.write(simplejson.dumps((False, -102, _("Your check code is invalid .")), ensure_ascii=False))
                else:
                    self.error(-102, _("Your check code is invalid ."))
                return

        sess.invalidate()
        content = content.replace("\n", "<br />")
        content = myfilter.do_filter(content)
        name = cgi.escape(name)[:20]
        url = cgi.escape(url)[:100]

        if not (name and email and content):
            if useajax:
                self.write(simplejson.dumps((False, -101, _("Please input name, email and comment ."))))
            else:
                self.error(-101, _("Please input name, email and comment ."))
        else:
            comment = Comment(
                author=name, content=content, email=email, reply_notify_mail=reply_notify_mail, entry=Entry.get(key)
            )
            if url:
                try:
                    if not url.startswith(("http://", "https://")):
                        url = "http://" + url
                    comment.weburl = url
                except:
                    comment.weburl = None

                    # name=name.decode('utf8').encode('gb2312')

            info_str = "#@#".join([urlencode(name), urlencode(email), urlencode(url)])

            # info_str='#@#'.join([name,email,url.encode('utf8')])
            cookiestr = "comment_user=%s;expires=%s;domain=%s;path=/" % (
                info_str,
                (datetime.now() + timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
                "",
            )
            comment.ip = self.request.remote_addr

            if parent_id:
                comment.parent = Comment.get_by_id(parent_id)

            comment.no = comment.entry.commentcount + 1
            try:
                comment.save()
                memcache.delete("/" + comment.entry.link)

                self.response.headers.add_header("Set-Cookie", cookiestr)
                if useajax:
                    comment_c = self.get_render("comment", {"comment": comment})
                    self.write(simplejson.dumps((True, comment_c.decode("utf8")), ensure_ascii=False))
                else:
                    self.redirect(self.referer + "#comment-" + str(comment.key().id()))

                comment.entry.removecache()
                memcache.delete("/feed/comments")
            except:
                if useajax:
                    self.write(simplejson.dumps((False, -102, _("Comment not allowed."))))
                else:
                    self.error(-102, _("Comment not allowed ."))
Пример #11
0
    def post(self, slug=None):
        useajax = self.param("useajax") == "1"
        ##        if self.is_admin:
        ##            name=self.blog.author
        ##            email=self.login_user.email()
        ##            url=self.blog.baseurl
        ##        else:
        name = self.param("author")
        email = self.param("email")
        url = self.param("url")

        key = self.param("key")
        content = self.param("comment")
        checknum = self.param("checknum")
        checkret = self.param("checkret")
        ##        if useajax:
        ##            name=urldecode(name)
        ##            email=urldecode(email)
        ##            url=urldecode(url)
        ##            key=urldecode(key)
        ##            content=urldecode(content)
        ##            checknum=urldecode(checknum)
        ##            checkret=urldecode(checkret)

        if not self.is_login:
            if not (self.request.cookies.get("comment_user", "")):

                try:
                    import app.gbtools as gb

                    if eval(checknum) <> int(gb.stringQ2B(checkret)):
                        if useajax:
                            self.write(simplejson.dumps((False, -102, _("Your check code is invalid ."))))
                        else:
                            self.error(-102, _("Your check code is invalid ."))
                        return
                except:
                    if useajax:
                        self.write(simplejson.dumps((False, -102, _("Your check code is invalid ."))))
                    else:
                        self.error(-102, _("Your check code is invalid ."))
                    return

        content = content.replace("\n", "<br>")
        content = myfilter.do_filter(content)
        name = cgi.escape(name)[:20]
        url = cgi.escape(url)[:100]

        if not (name and email and content):
            if useajax:
                self.write(simplejson.dumps((False, -101, _("Please input name, email and comment ."))))
            else:
                self.error(-101, _("Please input name, email and comment ."))
        else:
            comment = Comment(author=name, content=content, email=email, entry=Entry.get(key))
            if url:
                try:
                    comment.weburl = url
                except:
                    comment.weburl = "http://" + url

            # name=name.decode('utf8').encode('gb2312')

            info_str = "#@#".join([urlencode(name), urlencode(email), urlencode(url)])

            logging.info("info:" + info_str)
            # info_str='#@#'.join([name,email,url.encode('utf8')])
            cookiestr = "comment_user=%s;expires=%s;domain=%s;path=/" % (
                info_str,
                (datetime.now() + timedelta(days=100)).strftime("%a, %d-%b-%Y %H:%M:%S GMT"),
                "",
            )
            comment.save()
            memcache.delete("/" + comment.entry.link)

            self.response.headers.add_header("Set-Cookie", cookiestr)
            if useajax:
                comment_c = self.get_render("comment", {"comment": comment})
                self.write(simplejson.dumps((True, comment_c.decode("utf8"))))
            else:
                self.redirect(self.referer + "#comment-" + str(comment.key().id()))
Пример #12
0
    def post(self,slug=None):
        useajax=self.param('useajax')=='1'
        ismobile=self.paramint('ismobile')==1
        #if not self.is_login:
        #    if useajax:
        #            self.write(simplejson.dumps((False,-102,_('You must login before comment.')),ensure_ascii = False))
        #    else:
        #            self.error(-102,_('You must login before comment .'))
        #    return

        if self.is_login:
            name=self.login_user.nickname()
            email=self.login_user.email()
        else:
            name=self.param('author')
            email=self.param('email')
        
        url=self.param('url')
        key=self.param('key')
        content=self.param('comment')
        parent_id=self.paramint('parentid',0)
        reply_notify_mail=self.parambool('reply_notify_mail')
        
        # Verify the captcha (copied from the old source code)
        if not self.is_login:
            check_ret = self.verify_checkcode()
            if not check_ret:
                if useajax:
                    self.write(simplejson.dumps((False,-102,_('Your check code is invalid .')),ensure_ascii = False))
                else:
                    self.error(-102,_('Your check code is invalid .'))
                return

        content=content.replace('\n','<br />')
        content=filter.do_filter(content)
        name=cgi.escape(name)[:20]
        url=cgi.escape(url)[:100]

        if not (name and email and content):
            if useajax:
                self.write(simplejson.dumps((False,-101,_('Please input comment .'))))
            else:
                self.error(-101,_('Please input comment .'))
        else:
            comment=Comment(author=name,
                            content=content,
                            email=email,
                            reply_notify_mail=reply_notify_mail,
                            entry=ndb.Key(Entry,int(key)))
            if url:
                try:
                    if not url.lower().startswith(('http://','https://')):
                        url = 'http://' + url
                    comment.weburl=url
                except:
                    comment.weburl=None

            comment.ip=self.request.remote_addr

            if parent_id:
                comment.parent=Comment.get_by_id(parent_id)

            #comment.no=comment.entry.commentcount+1
            try:
                comment.save()
                #memcache.delete("/"+comment.entry.link)

                #self.response.headers.add_header( 'Set-Cookie', cookiestr)
                if useajax:
                    if ismobile:
                        self.write(simplejson.dumps((True,'')))
                    else:
                        comment_c=self.get_render('comment',{'comment':comment})
                        self.write(simplejson.dumps((True,comment_c),ensure_ascii = False))
                else:
                    self.redirect(self.referer+"#comment-"+str(comment.key().id()))

                #comment.entry.removecache()
                #memcache.delete("/feed/comments")
            except Exception,e:
                logging.error(e)
                if useajax:
                    self.write(simplejson.dumps((False,-103,_('Comment not allowed.'))))
                else:
                    self.error(-102,_('Comment not allowed .'))