def _tweet_for_template(tweet, https=False): """Return the dict needed for tweets.html to render a tweet + replies.""" data = json.loads(tweet.raw_json) parsed_date = parsedate(data["created_at"]) date = datetime(*parsed_date[0:6]) # Recursively fetch replies. if settings.CC_SHOW_REPLIES: # If ever slow, optimize to do fewer queries. replies = _get_tweets(limit=0, reply_to=tweet, https=https) else: replies = None if https: img = bleach.clean(data["profile_image_url_https"]) else: img = bleach.clean(data["profile_image_url"]) return { "profile_img": img, "user": bleach.clean(data["from_user"]), "text": bleach.clean(data["text"]), "id": tweet.pk, "date": date, "reply_count": len(replies) if replies else 0, "replies": replies, "reply_to": tweet.reply_to and tweet.reply_to.pk, "hidden": tweet.hidden, }
def _tweet_for_template(tweet, https=False): """Return the dict needed for tweets.html to render a tweet + replies.""" data = json.loads(tweet.raw_json) parsed_date = parsedate(data['created_at']) date = datetime(*parsed_date[0:6]) # Recursively fetch replies. if settings.CC_SHOW_REPLIES: # If ever slow, optimize to do fewer queries. replies = _get_tweets(limit=0, reply_to=tweet, https=https) else: replies = None if 'from_user' in data: # For tweets collected using v1 API user_data = data from_user = data['from_user'] else: user_data = data['user'] from_user = user_data['screen_name'] if https: img = bleach.clean(user_data['profile_image_url_https']) else: img = bleach.clean(user_data['profile_image_url']) return {'profile_img': img, 'user': from_user, 'text': bleach.clean(data['text']), 'id': tweet.pk, 'date': date, 'reply_count': len(replies) if replies else 0, 'replies': replies, 'reply_to': tweet.reply_to and tweet.reply_to.pk, 'hidden': tweet.hidden}
def get_player_opponents(player_id, tournament_id, same_wins=True): """Returns a player's id possible opponents. Args: player_id: the player's id. tournament_id: the tournament' id. same_wins: if should search opponents with same number of wins or not Returns: opponents: the player's possible opponents ids. """ conn = connect() c = conn.cursor() if same_wins is True: query = "SELECT a.p_id AS a_id, b.p_id AS b_id, b.name AS b_name, " \ "a.wins FROM standings AS a LEFT JOIN standings AS b " \ "ON a.p_id <> b.p_id AND a.t_id = b.t_id " \ "WHERE a.wins = b.wins AND a.p_id = %s AND a.t_id = %s;" else: # Get opponents with one win less than player query = "SELECT a.p_id AS a_id, b.p_id AS b_id, b.name AS b_name, " \ "b.wins FROM standings AS a LEFT JOIN standings AS b " \ "ON a.p_id <> b.p_id AND a.t_id = b.t_id " \ "WHERE b.wins = a.wins-1 AND a.p_id = %s AND a.t_id = %s;" c.execute(query, (bleach.clean(player_id), bleach.clean(tournament_id),)) opponents = [(row[1], row[2]) for row in c.fetchall()] conn.commit() conn.close() return opponents
def registerPlayer(name, tournament=1): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ ##Added support for multiple tournaments; players not assigned ##Will be added to tournament id 1 (generic pool) ##Ensure db data stays clean in case of future web enablement bleach.clean(name) DB = psycopg2.connect("dbname = tournament") c = DB.cursor() if tournament is not 1: c.execute("INSERT INTO players (name,tid)\ VALUES (%s,%s) returning pid;", (name, tournament,)) DB.commit() pid = c.fetchone()[0] DB.close() return pid if tournament is 1: c.execute("INSERT INTO players (name,tid) \ VALUES (%s,%s);", (name, tournament,)) DB.commit() DB.close()
def hydrate(self, bundle): # 요청이 POST일 때만 로그인아이디 -> author로 지정 # 요청이 PATCH일 때도 적용하면 다른 사람 노트를 수정할 수도 있음 if "POST" in str(bundle.request): bundle.data['author'] = '/api/v1/user/' + str(bundle.request.user.id) if bundle.data['parent'] == None or bundle.data['parent'] == "#": bundle.data['parent'] = None else: bundle.data['parent'] = '/api/v1/note/' + str(bundle.data['parent']) # bleach.clean #제목 bundle.data['text'] = bleach.clean(bundle.data['text'], strip=True) #본문 if bundle.data['content']: bundle.data['content'] = bundle.data['content'].replace("\t"," ") bundle.data['content'] = bleach.clean( bundle.data['content'], tags=['br', 'div', 'span', 'p', 'pre', 'code', 'blockquote', 'a', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'table', 'tr', 'td', 'b', 'strong', 'u', 'i', 'em'], attributes={ '*': ['class', 'src', 'href'], # '*': ['class', 'style'], }, # styles=['color', 'background', 'background-color', 'font-size', 'font-weight'], strip=True ) return bundle
def test_unclosed_tag(): eq_('<script src="http://xx.com/xss.js&lt;b">', clean('<script src=http://xx.com/xss.js<b>')) eq_('<script src="http://xx.com/xss.js" <b="">', clean('<script src="http://xx.com/xss.js"<b>')) eq_('<script src="http://xx.com/xss.js" <b="">', clean('<script src="http://xx.com/xss.js" <b>'))
def notes_detail(key): """ Retrieve, update or delete note instances. """ note = Note.query.get(key) if request.method == 'PUT': text = str(request.data.get('text', '')) if note: note.text = bleach.clean(text) else: note = Note( text=bleach.clean(text) ) db.session.add(note) db.session.commit() return note.to_json() elif request.method == 'DELETE': note.deleted = True db.session.add(note) db.session.commit() return '', status.HTTP_204_NO_CONTENT # request.method == 'GET' if not note: raise exceptions.NotFound() return note.to_json()
def AddPost(content): conn = psycopg2.connect("dbname=forum") cur = conn.cursor() bleach.clean(content) cur.execute("INSERT INTO posts (content) VALUES (%s)", (content,)) conn.commit() conn.close()
def parse(): my_text = codecs.decode(get_text(), 'windows-1255').splitlines() root, chapter, titles = [], [], [] found_beginning = False for line in my_text: if re.search(u'^ ?<b>', line): if found_beginning: root.append([u'{}.'.format(i) if not re.search(u':(>)?$', i) else i for i in chapter]) chapter = [] else: found_beginning = True chapter.append(bleach.clean(line, tags=['b'], strip=True)) titles.append(bleach.clean(line, tags=[], strip=True)) elif found_beginning: my_line = bleach.clean(line, tags=[], strip=True) if my_line.isspace() or len(my_line) == 0: continue my_line = re.sub(u'(\n|\r)', u'', my_line) chapter.extend(filter(lambda x: x if len(x) > 0 else None, my_line.split(u'.'))) else: continue else: root.append(chapter) # don't forget to add last chapter assert (len(root) == len(titles)) return { 'text': root, 'titles': titles }
def itemDelete(): """ Deletes an item owned by the current user """ state = request.values.get('state') if not check_nonce(state): return bad_request_error() cat_name = bleach.clean(request.values.get("item_delete_parent")) cat = dal.get_category_by_name(cat_name) if not cat: return not_found_error() active_user = get_active_user() if not active_user: return not_authenticated_error() item_name = bleach.clean(request.values.get("item_delete_name")) item = dal.get_item_by_name(cat.cat_id, item_name) if not item: return not_found_error() if active_user.user_id != item.creator_id: return not_authorized_error() # All checks passed generate_nonce() dal.delete_item(item.item_id) return redirect("/")
def get_job_links(job, max_sites=3): if hasattr(job, 'is_approved') and not job.is_approved: return '' locations = job.locations.all() sites = job.on_sites() domains = [site.domain for site in sites] title_slug = bleach.clean(slugify(job.title)) base_url = 'http://{domain}/{loc_slug}/{title_slug}/{guid}/job/' href_tag = '<a href="{url}">{domain}</a>' urls = [] for domain in domains: for location in locations: loc_slug = bleach.clean(slugify(u'{city}, {state}'.format( city=location.city, state=location.state_short))) job_url = base_url.format(domain=domain, loc_slug=loc_slug, title_slug=title_slug, guid=location.guid) urls.append(href_tag.format(url=job_url, domain=domain)) url_html = mark_safe("<br/>".join(urls[:max_sites])) if max_sites and len(urls) > max_sites: url_html = mark_safe("%s <br/>..." % url_html) return url_html
def editItem(id): """ Logged in User attempts to edit an item :param id: unique identifier of the item :return: GET : Renders Edit Item form POST: Adds item to database and redirects user """ item = Item.query.filter_by(id=id).first() # Abort if logged in user is not the owner of the page if int(current_user.get_id()) != item.owner_id: abort(403); form = EditForm(id=id, name=item.name, description=item.description) if form.validate_on_submit(): item.name = bleach.clean(form.name.data) item.description = bleach.clean(form.description.data) db.session.add(item) db.session.commit() return redirect(url_for('main.dashboard')) return render_template('main/editItem.html', form=form)
def test_valid_css(): """The sanitizer should fix missing CSS values.""" styles = ['color', 'float'] eq_('<p style="float: left;">foo</p>', clean('<p style="float: left; color: ">foo</p>', styles=styles)) eq_('<p style="">foo</p>', clean('<p style="color: float: left;">foo</p>', styles=styles))
def registerPlayer(tournament_name, player_name): """ Adds a player to the tournament database. Args: tournament_name: name of the tournament player belongs player_name: the player's full name (need not be unique). """ # sql statement sql = "SELECT tournament_id FROM tournament WHERE tournament_name=%(tournament_name)s;" # use bleach to # escapes or strips markup and attributes tournament_name = bleach.clean(tournament_name) # execute sql to get tournament_id tournament_id = int(_exeSql(sql, {'tournament_name': tournament_name})[0][0]) # use bleach to # escapes or strips markup and attributes player_name = bleach.clean(player_name) # sql statement sql = "INSERT INTO player(tournament_id, player_name) VALUES(%(tournament_id)s, %(player_name)s);" # execute sql _exeSql(sql, {'tournament_id': tournament_id, 'player_name': player_name})
def editItem(category_id, item_id): if 'username' not in login_session: return redirect('/login') category = session.query(Category).filter_by(id=category_id).one() editedItem = session.query(Item).filter_by(id=item_id).one() if request.method == 'POST': file = request.files['image'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if request.form['name']: editedItem.name = bleach.clean(request.form['name']) if request.form['image']: editedItem.image = url_for('uploaded_file', filename=filename) if request.form['description']: editedItem.image = bleach.clean(request.form['description']) if request.form['date']: editedItem.date = bleach.clean(request.form['date']) session.add(editedItem) flash('Item successfully edited!') session.commit() return redirect(url_for('showItems', category_id=category_id)) return render_template('editItem.html', item=editedItem, category_id=category_id)
def post_link(): ''' Performed when a link is POSTed. Inserts the (sanitized) data into the database. The description is parsed as Markdown and saved in HTML, while allowing a few attributes ------------------ NOTE: `request` is global and is implicitly passed as a parameter. It would probably be better to pass the data as a param for testing purposes. ------------------ NOTE: Maybe save the raw data as Markdown and only render it once needed ? Makes editing posts easier, but puts more load on the server. ''' allowed_tags = ("p", "h1", "h2", "h3", "h4", "h5", "h6", "b", "em", "small", "code", "i", "pre", "strong", "table", 'thead', 'tbody', 'th', 'tr', 'td', 'ul', 'ol', 'li', 'input') allowed_attrs = ('type', 'disabled', 'checked') title = bleach.clean(request.form['title']) desc = bleach.clean(request.form['desc'], tags=allowed_tags, attributes=allowed_attrs) url = bleach.clean(request.form["url"]) timestamp = time.time() tags = [] post = Link(title, url, desc, timestamp) post.set_tags(bleach.clean(request.form['tags'])) post.write() return redirect("/")
def context_dict(revision): """Return a dict that fills in the blanks in KB notification templates.""" document = revision.document if revision.document.current_revision is not None: fromfile = u'[%s] %s #%s' % (revision.document.locale, revision.document.title, revision.document.current_revision.id) tofile = u'[%s] %s #%s' % (revision.document.locale, revision.document.title, revision.id) diff = clean(u''.join(difflib.unified_diff( revision.document.current_revision.\ content.splitlines(1), revision.content.splitlines(1), fromfile=fromfile, tofile=tofile)), ALLOWED_TAGS, ALLOWED_ATTRIBUTES) else: diff = '' # No based_on, so diff wouldn't make sense. return { 'document_title': document.title, 'creator': revision.creator, 'host': Site.objects.get_current().domain, 'diff': diff, 'fulltext': clean(revision.content, ALLOWED_TAGS, ALLOWED_ATTRIBUTES)}
def userUpdateSettings(): if request.method == 'POST': form = UserSettingsForm(request.form) if form.validate(): user = current_user user.firstName = bleach.clean(form.firstName.data) user.lastName = bleach.clean(form.lastName.data) if form.email.data == "None": user.email = None else: user.email = bleach.clean(form.email.data) f = request.files.getlist('photo')[0] if len(f.filename) > 0: if user.photoName != None: #Remove the existing photo os.remove(getUserPhotoPath(user)) #We have to upload a new photo photoName = secure_filename(f.filename) name, extension = os.path.splitext(photoName) ensurePathExists(getUserPhotoDir()) f.save(os.path.join(getUserPhotoDir(), str(g.user.id)+extension)) user.photoName = str(g.user.id)+extension user.save() flash("Updated user information", "success") return redirect(url_for('userSettings'))
def wrapper(request, *args, **kwargs): request.GET = request.GET.copy() # see https://stackoverflow.com/questions/18930234/django-modifying-the-request-object/18931697 for k, v in request.GET.items(): request.GET[k] = bleach.clean(v) args = map(lambda a: bleach.clean(a) if isinstance(a, basestring) else a, args) # while we're at it, clean any other vars passed result = func(request, *args, **kwargs) return result
def compile(self, text_start, text_end, target_element_id): brief = self.escape_braces(text_start) text_end = self.escape_braces(text_end) brief = bleach.clean(brief, tags=self.ALLOWED_ELEMENTS, attributes=self.ALLOWED_ATTRIBUTES, strip=True) text_end = bleach.clean(text_end, tags=self.ALLOWED_ELEMENTS, attributes=self.ALLOWED_ATTRIBUTES, strip=True) full = self.concatenate_full(brief, text_end, target_element_id) return brief, full
def registerPlayer(name, email): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) * Arguments: * name: the player's full name (need not be unique). * email: the email address of the player. """ try: DB = connect() player_cursor = DB.cursor() name = bleach.clean(name) email = bleach.clean(email) player_cursor.execute( """insert into players (player_name,player_email) values (%s, %s) RETURNING player_id;;""", (name, email), ) player_id = player_cursor.fetchone()[0] DB.commit() DB.close() return player_id except: printErrorDetails( sys.exc_info(), """There was an error registerPlayer player [registerPlayer]!""", ) DB.rollback() DB.close()
def upload_form(request): #if not request.user.is_authenticated(): # return HttpResponseRedirect('/login/') form = News_form() usr = request.user groups = getGroupsWithUser(usr) if request.method == 'POST': form = News_form(request.POST) if form.is_valid(): # process the data in form.cleaned_data ni = News_item() ni.headline = form.cleaned_data['headline'] ni.date = form.cleaned_data['date'] ni.shortdesc = bleach.clean(form.cleaned_data['shortdesc'], tags=settings.BLEACH_ALLOWED_TAGS) ni.content = bleach.clean(form.cleaned_data['content'], tags=settings.BLEACH_ALLOWED_TAGS) ni.group = form.cleaned_data['group'] ni.save() return render_to_response('news/upload-show.html', { 'headline':form.cleaned_data['headline'], 'date':form.cleaned_data['date'], 'shortdesc':form.cleaned_data['shortdesc'], 'content':form.cleaned_data['content'] }, context_instance=RequestContext(request)) else: form = News_form() gids = [user_group.id for user_group in groups if usr.has_group_perm(user_group, 'Can add gus_news')] form.fields['group'].queryset = gus_group.objects.filter(pk__in=gids) return render_to_response('news/upload.html', { 'form':form }, context_instance=RequestContext(request))
def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'ul', 'pre', 'strong', 'h1', 'h2', 'h3', 'p'] target.body_html = bleach.linkify(bleach.clean(markdown(value, output_format='html'), tags=allowed_tags, strip=True)) target.body_abstract = bleach.linkify(bleach.clean(markdown(value, output_format='html'), tags=['p'], strip=True))
def _parse_offer_form(request, game): commodity_hand = commodities_in_hand(game, request.user) rule_hand = rules_in_hand(game, request.user) # include rules reserved for another trade as they are errors that have to be detected offer_form = OfferForm(request.POST, commodities = commodity_hand, rulecards = rule_hand) offer_valid = offer_form.is_valid() # fill the cleaned_data array errors = offer_form.non_field_errors() selected_commodities = {} for cih in commodity_hand: nb_selected_cards = offer_form.cleaned_data['commodity_{0}'.format(cih.commodity_id)] selected_commodities[cih] = nb_selected_cards if nb_selected_cards > cih.nb_tradable_cards(): errors.append(u"A commodity card in a pending trade can not be offered in another trade.") selected_rules = [] for rih in rule_hand: if offer_form.cleaned_data['rulecard_{0}'.format(rih.id)]: selected_rules.append(rih) if rih.is_in_a_pending_trade(): errors.append(u"A rule card in a pending trade can not be offered in another trade.") offer = Offer(free_information = bleach.clean(offer_form.cleaned_data['free_information'], tags = [], strip = True) or None, # 'or None' necessary to insert null (not empty) values comment = bleach.clean(offer_form.cleaned_data['comment'], tags = [], strip = True) or None) if not offer_valid or errors: raise FormInvalidException({'offer': offer, 'selected_commodities': selected_commodities, 'selected_rules': selected_rules, 'offer_errors': errors}) return offer, selected_commodities, selected_rules
def render_input(v, use_markdown=False): """Tidy up user input and insert breaks for empty lines.""" tags = ALLOWED_TAGS + config.getlist('general', 'extra_tags') attrs = ALLOWED_ATTRIBUTES # Drop any trailing empty lines. v = v.rstrip() if not v: return v if use_markdown: return bleach.clean( markdown.markdown(v, output_format='html5'), tags=tags, attributes=attrs) else: v = bleach.clean(v, tags=tags, attributes=attrs) out = '' for line in v.split('\n'): if not line.strip(): out += '<br/>\n' else: out += line + '\n' return out
def task_add(): try: name = bleach.clean(request.form['task-name'], tags=[]) desc = bleach.clean(request.form['task-desc'], tags=descAllowedTags) category = int(request.form['task-category']) hint = request.form['task-hint'] flag = request.form['task-flag'] if not flag: return jsonify({'message': 'No flag set'}), 400 except KeyError: return jsonify({'message': 'Form incorrect filled'}), 400 else: tasks = db['tasks'] task = dict( name=name, desc=desc, category=category, hint=hint, flag=flag) file = request.files['task-file'] if file: task['file'] = store_file(file) #tasks.update(task, ['id']) task_id = tasks.insert(task) task = tasks.find_one(id=task_id) return jsonify(task), 200
def task_edit(): try: tid = request.form['task-id'] name = bleach.clean(request.form['task-name'], tags=[]) desc = bleach.clean(request.form['task-desc'], tags=descAllowedTags) category = int(request.form['task-category']) hint = request.form['task-hint'] flag = request.form['task-flag'] if not flag: return jsonify({ 'message': 'No flag set' }), 400 except KeyError: return jsonify({ 'message': 'Form incorrect filled' }), 400 else: tasks = db['tasks'] task = tasks.find_one(id=tid) task['name'] = name task['desc'] = desc task['category'] = category task['hint'] = hint task['flag'] = flag file = request.files['task-file'] if file: filename = store_file(file) #remove old file if task['file']: delete_file(task['file']) task["file"] = filename tasks.update(task, ['id']) task = tasks.find_one(name = task["name"], flag = task["flag"]) return jsonify(task), 200
def addUser(): ''' Function Type: Callback-Redirect Function Purpose: Handle a CreateUserForm and create a new user in the course Inputs: None Forms Handled: CreateUserForm: Checks if the username exists. If it doesn't exist it will create a new user with the specified information. ''' if request.method == "POST": form = CreateUserForm(request.form) if form.validate(): try: u = User.objects.get(username=form.username.data) flash("Username already exists") return redirect(url_for('adminUsers')) except User.DoesNotExist: u = User() u.firstName = bleach.clean(form.firstName.data) u.lastName = bleach.clean(form.lastName.data) u.email = bleach.clean(form.email.data) u.username = form.username.data if form.password.data == "": u.setPassword("asdf") else: u.setPassword(form.password.data) u.save() return redirect(url_for('adminUsers'))
def competition_launch_submit(comp_id): """ Attempts to save competition and launch """ competitions = db['competitions'] competition = competitions.find_one(id=comp_id) if not competition: return redirect('/error/competition_not_found') try: name = bleach.clean(request.form['name'], tags=[]) desc = bleach.clean(request.form['desc'], tags=descAllowedTags) date_start = request.form['date-start'] date_end = request.form['date-end'] except KeyError: return jsonify({}), 400 else: competition['name'] = name or competition['name'] competition['desc'] = desc or competition['desc'] competition['active'] = competition['active'] or ('launch-button' in request.form) competition['date_start'] = date_start or competition['date_start'] competition['date_end'] = date_end or competition['date_end'] competitions.update(competition, ['id']) competition = competitions.find_one(id=comp_id) return jsonify(competition), 200 return jsonify({}), 200
def editCandy(candy_id): editCandy = session.query(Candy).filter_by(id=candy_id).one() cats = session.query(Category).all() if 'username' not in login_session: flash("You must be connected to edit a candy.") return redirect('/login') if request.method == 'POST': if request.form['name']: editCandy.name = bleach.clean(request.form['name']) if request.form['description']: editCandy.description = bleach.clean(request.form['description']) if request.form['cavity']: editCandy.cavity = request.form['cavity'] return redirect( url_for('seeOneCandy', candy_id=editCandy.id)) elif 'username' in login_session: return render_template('editCandy.html', candy=editCandy, categories=cats) else: flash("You must be connected to edit a candy.") return redirect('/login')
def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', 'strong'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True))
def moderatechallenge(): currentDayOfMonthIndex = datetime.date.today().day lateCheckinGracePeriodIsInEffect = currentDayOfMonthIndex <= 3 global commentHashesAndComments global submission commentHashesAndComments = {} stringio = StringIO() stringio.write('<html>\n<head>\n</head>\n\n') # redditSession = loginAndReturnRedditSession() redditSession = loginOAuthAndReturnRedditSession() submission = getSubmissionForRedditSession(redditSession) flat_comments = getCommentsForSubmission(submission) retiredHashes = retiredCommentHashes() i = 1 stringio.write( '<iframe name="invisibleiframe" style="display:none;"></iframe>\n') stringio.write("<h3>") stringio.write(os.getcwd()) stringio.write("<br>\n") stringio.write(submission.title) stringio.write("</h3>\n\n") stringio.write( '<form action="copydisplaytoclipboard.html" method="post" target="invisibleiframe">' ) stringio.write( '<input type="submit" name="actiontotake" value="Copy display.py stdout to clipboard">' ) stringio.write( '<input type="submit" name="actiontotake" value="Automatically post display.py stdout">' ) stringio.write('</form>') stringio.write( '<form action="updategooglechart.html" method="post" target="invisibleiframe">' ) stringio.write('<input type="submit" value="update-google-chart.py">') stringio.write('</form>') for comment in flat_comments: # print comment.is_root # print comment.score i += 1 commentHash = sha1() commentHash.update(comment.permalink) commentHash.update(comment.body.encode('utf-8')) commentHash = commentHash.hexdigest() if commentHash not in retiredHashes: commentHashesAndComments[commentHash] = comment authorName = str( comment.author ) # can be None if author was deleted. So check for that and skip if it's None. participant = ParticipantCollection().participantNamed(authorName) stringio.write("<hr>\n") stringio.write('<font color="blue"><b>') stringio.write(authorName) stringio.write('</b></font><br>') if ParticipantCollection().hasParticipantNamed(authorName): stringio.write( ' <small><font color="green">(member)</font></small>') if participant.isStillIn: stringio.write( ' <small><font color="green">(still in)</font></small>' ) else: stringio.write( ' <small><font color="red">(out)</font></small>') if participant.hasCheckedIn: stringio.write( ' <small><font color="green">(checked in)</font></small>' ) else: stringio.write( ' <small><font color="orange">(not checked in)</font></small>' ) if participant.hasRelapsed: stringio.write( ' <small><font color="red">(relapsed)</font></small>') else: stringio.write( ' <small><font color="green">(not relapsed)</font></small>' ) else: stringio.write( ' <small><font color="red">(not a member)</font></small>') stringio.write( '<form action="takeaction.html" method="post" target="invisibleiframe">' ) if lateCheckinGracePeriodIsInEffect: stringio.write( '<input type="submit" name="actiontotake" value="Checkin">' ) stringio.write( '<input type="submit" name="actiontotake" value="Signup and checkin" style="color:white;background-color:green">' ) else: stringio.write( '<input type="submit" name="actiontotake" value="Checkin" style="color:white;background-color:green">' ) stringio.write( '<input type="submit" name="actiontotake" value="Signup and checkin">' ) stringio.write( '<input type="submit" name="actiontotake" value="Relapse" style="color:white;background-color:red">' ) stringio.write( '<input type="submit" name="actiontotake" value="Reinstate with automatic comment">' ) stringio.write( '<input type="submit" name="actiontotake" value="Reply with sorry-too-late comment">' ) stringio.write( '<input type="submit" name="actiontotake" value="Skip comment">' ) stringio.write( '<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">' ) stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">') stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">') stringio.write( '<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">') stringio.write('</form>') stringio.write( bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p'])) stringio.write("\n<br><br>\n\n") stringio.write('</html>') pageString = stringio.getvalue() stringio.close() return Response(pageString, mimetype='text/html')
def xml_cleaning_method(self, method='escape_xml', **clean_kwargs): """Context manager to control how XML data tags are cleaned (escaped) to remove potentially unsafe characters or constructs. The default (``method='escape_xml'``) applies brute-force escaping of certain key XML characters like ``<``, ``>``, and ``&`` to ensure that the output is not valid XML. In order to explicitly allow certain XML tags (e.g. link reference or emphasis tags), use ``method='bleach_clean'``. This sanitizes the data string using the ``clean`` function of the `bleach <https://bleach.readthedocs.io/en/latest/clean.html>`_ package. Any additional keyword arguments will be passed directly to the ``clean`` function. Finally, use ``method='none'`` to disable any sanitization. This should be used sparingly. Example:: w = writer.XMLWriter(ListWriter(lines)) with w.xml_cleaning_method('bleach_clean'): w.start('td') w.data('<a href="https://google.com">google.com</a>') w.end() Parameters ---------- method : str Cleaning method. Allowed values are "escape_xml", "bleach_clean", and "none". **clean_kwargs : keyword args Additional keyword args that are passed to the bleach.clean() function. """ current_xml_escape_cdata = self.xml_escape_cdata if method == 'bleach_clean': # NOTE: bleach is imported locally to avoid importing it when # it is not nocessary try: import bleach except ImportError: raise ValueError( 'bleach package is required when HTML escaping is disabled.\n' 'Use "pip install bleach".') if clean_kwargs is None: clean_kwargs = {} self.xml_escape_cdata = lambda x: bleach.clean(x, **clean_kwargs) elif method == "none": self.xml_escape_cdata = lambda x: x elif method != 'escape_xml': raise ValueError( 'allowed values of method are "escape_xml", "bleach_clean", and "none"' ) yield self.xml_escape_cdata = current_xml_escape_cdata
def safe_vendor_description(value): if isinstance(value, Undefined): return value if not settings.SHUUP_ADMIN_ALLOW_HTML_IN_VENDOR_DESCRIPTION: value = bleach.clean(value, tags=[]) return mark_safe(value)
def strip_tags(value): """Strips provided text of html tags""" return bleach.clean(value, tags=[], strip=True).strip() if u'<' in value else value
def devilry_escape_html(html): """ Escape all html in the given ``html``. """ return bleach.clean(html)
def bleach_tags(text): return bleach.clean(text, tags=[], strip=True).replace('&', '&')
def safe_clean(text): tags = ['b', 'i', 'font', 'br', 'blockquote', 'div', 'h2', 'a', 'p'] attrs = {'*': ['style', 'id', 'class'], 'font': ['color'], 'a': ['href']} styles = ['color'] return Markup(clean(text, tags=tags, attributes=attrs, styles=styles))
def cleank(txt): """Clean and link some user-supplied text.""" return jinja2.Markup(bleach.linkify(bleach.clean(txt)))
def submit_upload(request): current_profile_info = request.user if (not current_profile_info.is_anonymous()): current_profile_info = ProfileInfo.objects.get(user = current_profile_info) print(current_profile_info) else: current_profile_info = None try: # get main data for the Protocol model protocol_title = bleach.clean(request.POST['title']) protocol_desc = bleach.clean(request.POST['description']) protocol_changes = bleach.clean(request.POST['change-log']) protocol = Protocol(change_log = protocol_changes, title = protocol_title, description = protocol_desc, author = current_profile_info) protocol_cat = "" try: # get category and associate it with protocol protocol_cat = bleach.clean(request.POST['category']) cat = Category.objects.get(title = protocol_cat) protocol.category = cat except: pass # associate new protocol with previous revision if necessary try: previous_protocol_id = bleach.clean(request.POST['BranchFrom']) if (previous_protocol_id != -1): # set up previous revisions and first revision for new protocol prev_protocol = Protocol.objects.get(id = previous_protocol_id) protocol.previous_revision = prev_protocol if (prev_protocol.first_revision != None): protocol.first_revision = prev_protocol.first_revision else: protocol.first_revision = prev_protocol except: pass protocol.save() # save the steps now num_steps = 0 # go over each available step number_to_check = int(bleach.clean(request.POST['number_to_check'])) for x in range(0, number_to_check + 1): try: prefix = 'step' + str(x) number = int(bleach.clean(request.POST[prefix + '[number]'])) description = bleach.clean(request.POST[prefix + '[description]']) time = 0 warning = "" title = "" # try to pick up each individual part of each step try: warning = bleach.clean(request.POST[prefix + '[warning]']) print('found warning') except: warning = "" try: time = int(bleach.clean(request.POST[prefix + '[time]'])) except: time = -1 print(warning) ps = ProtocolStep(action = description, warning = warning, step_number = number, time = time, protocol = protocol) try: title = bleach.clean(request.POST[prefix + '[title]']) ps.title = title except: pass ps.save() num_steps = num_steps + 1 except: # Means that the name doesn't exist print('error1') pass protocol.num_steps = num_steps # get any written-in reagents and save them protocol_rea = "" try: protocol_rea = bleach.clean(request.POST['text-reagents']) except: pass protocol.materials = protocol_rea protocol.save() except Exception as e: print('error2') print(e) pass context = { 'title': 'ProtoCat - Submit Upload', 'current_profile_info': current_profile_info, } return HttpResponseRedirect('/')
def render_markdown_as_safe_html(message): html = markdown.markdown(message) return bleach.clean(html, tags=allowed_tags, strip=True)
def format(self, text): return smile_it(self._parser.convert(bleach.clean(text)))
def scrubemail_filter(data, css_junk=''): return Markup( scrubemail(unicode(bleach.linkify(bleach.clean(data))), rot13=True, css_junk=css_junk))
def clean_html_all(text): return bleach.clean(text, tags=[], attributes={}, styles=[], strip=True)
def textify(text): """return a plain text copy of a possible html text""" return bleach.clean(text, strip = True, tags = [])
def item_posting(): # cursor = db.cursor() print(request.form) formsLen = len(request.form) images_path = [] if 'lazyRegistration' in session: print('session file is: ', session_file) insertItemPost(session['item_name'], session['item_category'], session['item_desc'], session['item_price'], session['is_tradable'], session['item_images'], session['sessionUser'], True) session_file.clear() session.pop('lazyRegistration') session.pop('lazyPage') print('Rediret from lazy login to home') # return render_template('home.html', sessionUser=session['sessionUser'], id=-1,categoryName="Catogory") return redirect("/") sessionUser = "" if 'sessionUser' not in session else session['sessionUser'] # print("Session user", sessionUser) if request.method == "POST": if request.form: print("printing request form", request.form) if formsLen > 0: item_name = str(bleach.clean(request.form['item_title'])) item_category = request.form['category'] item_desc = str(bleach.clean(request.form['item_desc'])) item_price = request.form['item_price'] is_tradable = '0' if 'isTradable' not in request.form else request.form[ 'isTradable'] #str(1) if 'isTradable' in request.form else str(0) item_images = [] if sessionUser == "": session['item_images'] = [] # store image in separate folder as per category UPLOAD_FOLDER = 'static/images/' + item_category session['UPLOAD_FOLDER'] = UPLOAD_FOLDER for file in request.files.getlist('file'): if file.filename == '': print('No file selected for uploading') else: # session['item_image'].append(base64.b64encode(file.read()).decode('ascii')) if sessionUser == "": # session_file.append(file) if file and allowed_file(file.filename): filename = secure_filename(file.filename) # unique filename uuid_val = uuid.uuid1() filename = str(uuid_val) + '.' + \ filename.rsplit('.', 1)[1].lower() print(os.path.curdir) file_path = os.path.join(session['UPLOAD_FOLDER'], filename) print("file path from item-posting post req is:", file_path) # file = open(file,"wr") file.save(file_path) session['item_images'].append(file_path) else: item_images.append(file) if sessionUser == "": session['lazyRegistration'] = True session['lazyPage'] = 'item-posting' session['item_name'] = item_name session['item_category'] = item_category session['item_desc'] = item_desc session['item_price'] = item_price session['is_tradable'] = is_tradable # session['item_userid'] = # session['item_images'] = None #item_images print("going to login?") return redirect("/login") else: # sessionUser = session['sessionUser'] insertItemPost(item_name, item_category, item_desc, item_price, is_tradable, item_images, sessionUser, False) if request.method == "GET": cursor = getCursor()[1] cursor.execute(query().fetchAllCategories()) allCategories = cursor.fetchall() cursor.close() categories = [allCategories[i][0] for i in range(len(allCategories))] return render_template("item-posting.html", categories=categories) flash("Item Posted Successfully") return redirect('/')
def clean_tags(self): tags = [bleach.clean(t) for t in self.cleaned_data['tags']] return tags
def sanitize_data(self): ret = super(CommentSerializer, self).sanitize_data() content = self.validated_data.get('get_content', None) if content: ret['get_content'] = bleach.clean(content) return ret
def clean_description(self): return bleach.clean(self.cleaned_data['description'])
def as_text(self): "Returns the body of the post after stripping the HTML tags" text = bleach.clean(self.content, tags=[], attributes=[], styles={}, strip=True) return text
def save(self, *args, **kwargs): self.text = bleach.clean(self.text, tags=[], strip=True) super(URLSource, self).save(*args, **kwargs)
def clean_name(self): return bleach.clean(self.cleaned_data['name'])
def save(self, *args, **kwargs): if self.pk is None and self.date is None: self.date = timezone.now() self.note = bleach.clean(self.note, strip=True, strip_comments=True) super().save(*args, **kwargs)
def get_searchable_content(self, value, data): return bleach.clean(data or '', tags=[], strip=True)
def db_update_note(note: Note): note_dict = note.dict() note_dict["content"] = bleach.clean(note_dict["content"]) notes.put(note_dict, urlsafe_key(note.name)) return Note(**note_dict)
def save(self, **kwargs): self.description = bleach.clean(self.description, strip=True, strip_comments=True) super().save(**kwargs)
def bleach_value(value): return bleach.clean(value, **bleach_args)
def remove_tags(text): """Thanks to http://stackoverflow.com/a/35880312""" return bleach.clean(text, tags=[], attributes={}, styles=[], strip=True)
def clean_content(self): return bleach.clean(self.cleaned_data['content'], tags=self.allowed_tags, attributes=self.allowed_attributes, strip=True)
def moderatesignups(): global commentHashesAndComments commentHashesAndComments = {} stringio = StringIO() stringio.write('<html>\n<head>\n</head>\n\n') # redditSession = loginAndReturnRedditSession() redditSession = loginOAuthAndReturnRedditSession() submissions = getSubmissionsForRedditSession(redditSession) flat_comments = getCommentsForSubmissions(submissions) retiredHashes = retiredCommentHashes() i = 1 stringio.write( '<iframe name="invisibleiframe" style="display:none;"></iframe>\n') stringio.write("<h3>") stringio.write(os.getcwd()) stringio.write("<br>\n") for submission in submissions: stringio.write(submission.title) stringio.write("<br>\n") stringio.write("</h3>\n\n") stringio.write( '<form action="copydisplayduringsignuptoclipboard.html" method="post" target="invisibleiframe">' ) stringio.write( '<input type="submit" value="Copy display-during-signup.py stdout to clipboard">' ) stringio.write('</form>') for comment in flat_comments: # print comment.is_root # print comment.score i += 1 commentHash = sha1() commentHash.update(comment.fullname) commentHash.update(comment.body.encode('utf-8')) commentHash = commentHash.hexdigest() if commentHash not in retiredHashes: commentHashesAndComments[commentHash] = comment authorName = str( comment.author ) # can be None if author was deleted. So check for that and skip if it's None. stringio.write("<hr>\n") stringio.write('<font color="blue"><b>') stringio.write( authorName ) # can be None if author was deleted. So check for that and skip if it's None. stringio.write('</b></font><br>') if ParticipantCollection().hasParticipantNamed(authorName): stringio.write( ' <small><font color="green">(member)</font></small>') # if ParticipantCollection().participantNamed(authorName).isStillIn: # stringio.write(' <small><font color="green">(in)</font></small>') # else: # stringio.write(' <small><font color="red">(out)</font></small>') else: stringio.write( ' <small><font color="red">(not a member)</font></small>') stringio.write( '<form action="takeaction.html" method="post" target="invisibleiframe">' ) stringio.write( '<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">' ) # stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">') # stringio.write('<input type="submit" name="actiontotake" value="Relapse">') # stringio.write('<input type="submit" name="actiontotake" value="Reinstate">') stringio.write( '<input type="submit" name="actiontotake" value="Skip comment">' ) stringio.write( '<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">' ) stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">') stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">') # stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">') stringio.write('</form>') stringio.write( bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p'])) stringio.write("\n<br><br>\n\n") stringio.write('</html>') pageString = stringio.getvalue() stringio.close() return Response(pageString, mimetype='text/html')