def processHTMLText(content='', usesmileys=True, is_html=False): if is_html: content = urlify(content) content = content.replace('\n', '') content = content.replace('\\', '\') result = [] tokens = _url_pattern.split(content) for token in tokens: if not is_html and _url_pattern_exact.match(token): type, d, rest = token.partition(":") url = type + d + urllib.parse.quote(rest.encode('utf-8'), "/%?&=;:,@+$#!") token = r'<a href=\"%s\">%s</a>' % (url, escape_html(token)) else: if not is_html: token = escape_html(token) else: token = token.replace('"', r'\"') if usesmileys: token = SmileyManager().subst_smileys_html(token) result.append(token) content = "".join(result) return content
def processHTMLText(text, usesmileys=True, is_html=False): def suball(pat, repl, html): ohtml = "" while ohtml != html: html = pat.sub(repl, html) ohtml = html return html if is_html: text = text.replace('\n', '<br>') result = [] tokens = _url_pattern.split(text) for token in tokens: if not is_html and _url_pattern_exact.match(token): type, d, rest = token.partition(":") url = type + d + urllib.quote(rest, "/%?&=;:,@+$#") token = r'<a href=\"%s\">%s</a>' % (url, escape_html(token)) else: if not is_html: token = escape_html(token) else: token = token.replace('"', r'\"') if usesmileys: token = SmileyManager().subst_smileys_html(token) result.append(token) return "".join(result)
def from_request(cls, form, request): # extract form data if not form.validate(): pass else: text = cls(text = escape_html(form.text.data)) return text
def from_request(cls, form, request): # extract form data if not form.validate(): pass else: c = Configuration() # -- store image -- file_obj = request.files.get('image') # check mimetype mimetype = file_obj.content_type filetype = check_mimetype(mimetype, ["image"], ["jpeg", "png", "gif", "tiff"]) # read image buf_image = file_obj.read() image = Image.open(StringIO(buf_image)) thumbnail = generate_thumbnail(image, 300) # assemble filenames assetspath = os.path.join(c.base_path, 'assets') filename = md5(buf_image).hexdigest()+'.'+filetype imagepath = os.path.join(assetspath, filename) thumbpath = os.path.join(assetspath, 'thumb_'+filename) # write images image.save(imagepath) thumbnail.save(thumbpath) # generate image URLs image_url = c.base_url+'assets/'+filename thumb_url = c.base_url+'assets/thumb_'+filename # -- assemble post -- image_post = cls( image_url = image_url, thumb_url = thumb_url, source = escape_html(form.source.data), description = escape_html(form.description.data) ) return image_post
def from_request(cls, form, request): # extract form data if not form.validate(): pass else: # -- assemble post -- video_url = form.video_url.data video_id = re.findall('(v=|youtu\.be/)(.*)&?', video_url)[0][1] post = cls(video_id = escape_html(video_id)) return post
def load_theme(self, smiley_theme_directory, name="default"): self.smiley_directory = smiley_theme_directory self.theme = name self.icon = None in_header = True found = False f = open(os.path.join(self.smiley_directory, self.theme, "theme"), "r") for line in f: line = line.strip() if not line or line[0] == "#": continue if in_header: if "=" in line: k, v = line.split("=", 1) if k == "Icon": self.icon = v continue if line[0] == "[": in_header = False else: continue if line == "[%s]" % SMILEY_STYLE: if found: break found = True continue elif line.startswith("["): if found: break if found: line = line.replace("\\\\", "\\") toks = [s.strip() for s in line.split()] if len(toks) >= 2: file = toks[0] for text in toks[1:]: self.smileys[text] = file self.smiley_keys.append(toks[1]) f.close() self.smileys_html = {} for k, v in self.smileys.iteritems(): # pre-escape the smiley so that it matches escaped text later ek = escape_html(k) self.smileys_html[ek] = "<img src='file:%s' class='smiley' />" % ( self.get_smiley(k))
def load_theme(self, smiley_theme_directory, name="default"): self.smiley_directory = smiley_theme_directory self.theme = name self.icon = None in_header = True found = False f = open(os.path.join(self.smiley_directory, self.theme, "theme"), "r") for line in f: line = line.strip() if not line or line[0] == "#": continue if in_header: if "=" in line: k, v = line.split("=", 1) if k == "Icon": self.icon = v continue if line[0] == "[": in_header = False else: continue if line == "[%s]"%SMILEY_STYLE: if found: break found = True continue elif line.startswith("["): if found: break if found: line = line.replace("\\\\", "\\") toks = [s.strip() for s in line.split()] if len(toks) >= 2: file = toks[0] for text in toks[1:]: self.smileys[text] = file self.smiley_keys.append(toks[1]) f.close() self.smileys_html = {} for k, v in self.smileys.iteritems(): # pre-escape the smiley so that it matches escaped text later ek = escape_html(k) self.smileys_html[ek] = "<img src='file:%s' class='smiley' />"%(self.get_smiley(k))
def web_change_profile(request, environment, session, username): """ makes changes to <username>'s user object Possible errortypes are: * May raise the following Exceptions: * """ class changeProfileForm(Form): tagline = TextField("Tagline") bio = TextAreaField("Something about yourself") avatar = FileField("Your Avatar") password = PasswordField("New Password (leave empty if you \ don't want to change it") password_confirm = PasswordField("Confirm new password") u = get_user_obj(username, session) if request.method == 'POST': form = changeProfileForm(request.form) u.identity.tagline = escape_html(form.tagline.data) u.identity.bio = escape_html(form.bio.data) # avatar uploaded = request.files.get('avatar') if uploaded: mimetype = uploaded.content_type try: filetype = util.check_mimetype(mimetype, ["image"], ["jpeg", "png", "gif", "tiff"]) except Exception: # TODO no valid filetype pass else: buf_image = uploaded.read() image = util.force_quadratic(Image.open(StringIO(buf_image))) thumbnail = util.generate_thumbnail(image, 50) assetspath = os.path.join(Configuration().base_path, 'assets') filename = "avatar_" + md5(buf_image).hexdigest() + "." +\ filetype imagepath = os.path.join(assetspath, filename) thumbnailpath = os.path.join(assetspath, "thumb_" + filename) image.save(imagepath) thumbnail.save(thumbnailpath) u.identity.avatar_url = Configuration().base_url + 'assets/' +\ filename u.identity.avatar_small_url = Configuration().base_url +\ 'assets/thumb_' + filename # TODO: use hash if form.password.data != "" and form.password.data == form.password_confirm.data: u.passwordhash = form.password.data session.commit() return render_template("web_change_profile.htmljinja", environment, success=True, user=u) else: form = changeProfileForm() form.bio.data = escape_html(u.identity.bio) form.tagline.data = escape_html(u.identity.tagline) return render_template("web_change_profile.htmljinja", environment, user=u, form=form)
def web_insert_post(request, environment, session, username, plugin_str=None): """ Saves a post to <username>'s wurstgulasch. Possible errortypes are: * May raise the following Exceptions: * """ if not request.method == "POST": if plugin_str is None: # list all available plugins pluginlist = environment['content_plugins'].keys() return render_template("web_choose_post_plugin.htmljinja", environment, pluginlist=pluginlist) else: # check if plugin actually exists if plugin_str not in environment['content_plugins'].keys(): raise Exception('Content Plugin not found :(') # show the specific form else: form = environment['content_plugins'][plugin_str].\ CreatePostForm() return render_template("web_insert_post.htmljinja", environment, form=form) else: if not plugin_str is None: # check if plugin actually exists if plugin_str not in environment['content_plugins'].keys(): raise Exception('Content Plugin not found :(') form = environment['content_plugins'][plugin_str].CreatePostForm(request.form) # create post object if form.validate(): plugin_class = environment['content_plugins'][plugin_str] post_obj = plugin_class.from_request(form, request) # set user and time u = get_user_obj(username, session) post_obj.owner = u.identity # add tags tag_strings = [ t.strip() for t in escape_html(request.form['tags']).split(',') ] for tag_str in tag_strings: res = session.query(tag).filter(tag.tag == tag_str).all() if res: post_obj.tags.append(res[0]) else: new_tag = tag(tag_str) session.add(new_tag) post_obj.tags.append(new_tag) # insert into database session.add(post_obj) session.commit() # return to Stream return redirect('/' + username + '/stream') else: return render_template("web_insert_post.htmljinja", environment, form=form) else: # this should not happen pass
def news_scroll(request): text = cache.get('news_scroll') if text is None: prof.start('news-scroll-no-cache') # Hit the database baby - Uh. text = [] friendships = Friends.objects.filter(accepted=True).order_by('-modified_on')[:const.NewsConst.Scroll.NEW_FRIEND_MAX] for friendship in friendships: text.append(const.NewsConst.Scroll.NEW_FRIEND % ( '/' + util.escape_html(friendship.friend.username), prettyuser.user_or_first_name(friendship.friend), '/' + util.escape_html(friendship.user.username), prettyuser.user_or_first_name(friendship.user))) gossips = News.objects.filter(about_id__isnull=False).order_by('-time')[:const.NewsConst.Scroll.NEW_GOSSIP_MAX] for gossip in gossips: if gossip.anonymous: text.append(const.NewsConst.Scroll.NEW_GOSSIP_ANONYMOUS % ( '/' + util.escape_html(gossip.about_id.username), util.escape_html(prettyuser.user_or_first_name(gossip.about_id)), '/profile/?n=' + util.escape_html(str(gossip.id)), util.escape_html(gossip.title) )) else: text.append(const.NewsConst.Scroll.NEW_GOSSIP % ( '/' + util.escape_html(gossip.user.username), util.escape_html(prettyuser.user_or_first_name(gossip.user)), '/' + util.escape_html(gossip.about_id.username), util.escape_html(prettyuser.user_or_first_name(gossip.about_id)), '/profile/?n=' + util.escape_html(str(gossip.id)), util.escape_html(gossip.title) )) new_users = User.objects.order_by('-date_joined')[:const.NewsConst.Scroll.NEW_USER_MAX] for new_user in new_users: text.append(const.NewsConst.Scroll.NEW_USER % ( '/' + util.escape_html(new_user.username), util.escape_html(prettyuser.user_or_first_name(new_user)), )) # Save it in cache for 30 seconds cache.set('news_scroll', text, 30) prof.stop('news-scroll-no-cache') # Randomize it each time random.shuffle(text) return {'news_scroll': text}