def slides(self, request, title): """Dump the HTML content of the pages listed.""" items = self.index.page_links_and_labels(title) contents = [] for t, label in items: page = self.get_page(request, t) try: html = ''.join(page.view_content()) except hatta.error.NotFoundErr: continue slide_title = (u'<h1>%s</h1>' % werkzeug.escape(label)) contents.append(slide_title + html) content = ('<div class="slide">%s</div>' % '</div><div class="slide">'.join(contents)) html = """<!DOCTYPE html> <link type="text/css" href="../+download/slides.css" rel="stylesheet"> <link type="text/css" href="../+download/pygments.css" rel="stylesheet"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>%s</title> %s <script src="../+download/jquery.js"></script> <script src="../+download/slides.js"></script> """ % (werkzeug.escape(title), content) response = hatta.WikiResponse(html, mimetype='text/html') return response
def edit_group(request, group_id=None): """Edit a Group. This is used to create a group as well.""" group = None if group_id is not None: group = Group.query.get(group_id) if group is None: raise NotFound() form = EditGroupForm(group) if request.method == 'POST': if request.form.get('cancel'): return form.redirect('admin/manage_groups') elif request.form.get('delete') and group: return redirect_to('admin/delete_group', group_id=group.id) elif form.validate(request.form): if group is None: group = form.make_group() msg = _(u'Group %s created successfully.') icon = 'add' else: form.save_changes() msg = _(u'Group %s edited successfully.') icon = 'info' db.commit() html_group_detail = u'<a href="%s">%s</a>' % ( escape(url_for(group)), escape(group.name)) flash(msg % html_group_detail, icon) if request.form.get('save'): return form.redirect('admin/manage_groups') return redirect_to('admin/edit_group', group_id=group.id) return render_admin_response('admin/edit_group.html', 'users_groups.groups', form=form.as_widget())
def _block_macro(self, block): for self.line_no, part in block: name = part.lstrip('<').strip() inside = u"\n".join(self.lines_until(self.macro_close_re)) yield u'<div class="%s">%s</div>' % ( werkzeug.escape(name, quote=True), werkzeug.escape(inside))
def configure(self, request): form = QuillsImportForm() if request.method == 'POST' and form.validate(request.form): return self.render_admin_page( 'admin/import_quills_process.html', live_log=self.import_quills( blogurl = form.data['blogurl'], username = form.data['username'], password = form.data['password']), _stream=True) if have_pygments: code_formatter = HtmlFormatter(cssclass='syntax') add_header_snippet('<style type="text/css">\n%s\n</style>' % escape(code_formatter.get_style_defs())) exportscript = highlight(EXPORTSCRIPT, get_lexer_by_name('python'), code_formatter) else: exportscript = '<pre>%s</pre>' % escape(EXPORTSCRIPT) return self.render_admin_page('admin/import_quills.html', exportscript=exportscript, form=form.as_widget())
def html_display_name(self): """The display name as HTML link.""" link = self.plugin_url if link: return u'<a href="%s">%s</a>' % (escape(link), escape(self.display_name)) return escape(self.display_name)
def html_author_info(self): """Return the author info as html link.""" name, email, url = self.author_info if not url: if not email: return escape(name) url = 'mailto:%s' % quote(email) return u'<a href="%s">%s</a>' % (escape(url), escape(name))
def html_author_info(self): """Return the author info as html link.""" name, email, url = self.author_info if not url: if not email: return escape(name) url = "mailto:%s" % quote(email) return u'<a href="%s">%s</a>' % (escape(url), escape(name))
def html_display_name(self): """The display name as HTML link.""" link = self.plugin_url if link: return u'<a href="%s">%s</a>' % ( escape(link), escape(self.display_name) ) return escape(self.display_name)
def dump_category(category): return dict( categoryId=category.id, description=category.name, categoryDescription=category.description, categoryName=category.name, # don't ask me... WordPress is doing that... htmlUrl=escape(url_for(category)), rssUrl=escape(url_for('blog/atom_feed', category=category.slug)))
def html(self, **kwargs): from flask import url_for nickname = self.value.group('nickname') if app: return '<a href="%s">@%s</a>' % ( url_for( 'community:profile.nickname_redirect', nickname=nickname), escape(nickname)) else: return '<a href="#">@%s</a>' % escape(nickname)
def wp_get_tags(blog_id, username, password): request = login(username, password) return [{ 'tag_id': tag['id'], 'name': tag['name'], 'count': tag['count'], 'slug': tag['slug'], 'html_url': escape(url_for('blog/show_tag', slug=tag['slug'])), 'rss_url': escape(url_for('blog/atom_feed', tag=tag['slug'])) } for tag in Tag.query.get_cloud()]
def dump_category(category): return dict( categoryId=category.id, description=category.name, categoryDescription=category.description, categoryName=category.name, # don't ask me... WordPress is doing that... htmlUrl=escape(url_for(category)), rssUrl=escape(url_for('blog/atom_feed', category=category.slug)) )
def html_contributors_info(self): result = [] for contributor in self.contributors: name, contact = contributor if not contact: result.append(escape(name)) else: result.append('<a href="%s">%s</a>' % (escape( check(is_valid_email, contact) and 'mailto:' + contact or contact), escape(name))) return u', '.join(result)
def html_contributors_info(self): result = [] for contributor in self.contributors: name, contact = contributor if not contact: result.append(escape(name)) else: result.append( '<a href="%s">%s</a>' % (escape(check(is_valid_email, contact) and "mailto:" + contact or contact), escape(name)) ) return u", ".join(result)
def edit_user(request, user_id=None): """Edit a user. This can also create a user. If a new user is created the dialog is simplified, some unimportant details are left out. """ user = None if user_id is not None: user = User.query.get(user_id) if user is None: raise NotFound() form = EditUserForm(user) if request.method == 'POST': if request.form.get('cancel'): return form.redirect('admin/manage_users') elif request.form.get('delete') and user: return redirect_to('admin/delete_user', user_id=user.id) elif form.validate(request.form): picfile = request.files.get('picfile') if user is None: user = form.make_user() if picfile and form['userpictype'] == 'Upload': picture.place_file(picfile) msg = _(u'User %s created successfully.') icon = 'add' else: picture = UserPicture(request.user) if picfile: form.save_changes() if form['userpictype'] == 'Upload': picture.place_file(picfile) else: pictype = user.userpictype if not form['userpictype']: form.data['userpictype'] = pictype if form['userpictype'] != pictype: picture.remove() form.save_changes() msg = _(u'User %s edited successfully.') icon = 'info' db.commit() html_user_detail = u'<a href="%s">%s</a>' % ( escape(url_for(user)), escape(user.username) ) flash(msg % html_user_detail, icon) if request.form.get('save'): return form.redirect('admin/manage_users') return redirect_to('admin/edit_user', user_id=user.id) return render_admin_response('admin/edit_user.html', 'users_groups.users', form=form.as_widget())
def wiki_math(self, math_text, display=False): math_url = self.wiki.math_url if math_url == '': return werkzeug.escape(math_text) elif math_url == 'mathjax': if display: return werkzeug.escape("$$\n%s\n$$" % math_text) else: return werkzeug.escape("$%s$" % math_text) if '%s' in math_url: url = math_url % werkzeug.url_quote(math_text) else: url = '%s%s' % (math_url, werkzeug.url_quote(math_text)) label = werkzeug.escape(math_text, quote=True) return werkzeug.html.img(src=url, alt=label, class_="math")
def wiki_math(self, math_text, display=False): math_url = self.wiki.math_url if math_url == '': return werkzeug.escape(math_text) elif math_url == 'mathjax': if display: return werkzeug.escape(u"$$\n%s\n$$" % math_text) else: return werkzeug.escape(u"$%s$" % math_text) if '%s' in math_url: url = math_url % werkzeug.url_quote(math_text) else: url = '%s%s' % (math_url, werkzeug.url_quote(math_text)) label = werkzeug.escape(math_text, quote=True) return werkzeug.html.img(src=url, alt=label, class_="math")
def category_edit(request, category_id=None): """Edit an existing category or create a new one.""" category = None if category_id is not None: category = Category.query.get(category_id) if category is None: raise NotFound() form = CategoryForm(category) if request.method == 'POST': if 'cancel' in request.form: return form.redirect(cat_endpoints['list']) elif 'delete' in request.form and category: return redirect_to(cat_endpoints['delete'], category_id=category_id) elif form.validate(request.form): if category is None: category = form.create_category() msg = _('Category %s was created successfully.') icon = 'add' else: form.save_changes(category) msg = _('Category %s was updated successfully.') icon = 'info' admin_flash(msg % ('<a href="%s">%s</a>' % (url_for(cat_endpoints['edit'], category_id=category.id), escape(category.name))), icon) if 'save_and_continue' in request.form: return redirect_to(cat_endpoints['edit'], category_id=category_id) elif 'save_and_new' in request.form: return redirect_to(cat_endpoints['edit']) return redirect_to(cat_endpoints['list']) return render_admin_response('admin/board_base_edit.html', 'board.categories', form=form.as_widget(), itemname=_('Category'))
def get_serializer(request): """Returns the serializer for the given API request.""" format = request.args.get('format') if format is not None: rv = _serializer_map.get(format) if rv is None: raise BadRequest(_(u'Unknown format "%s"') % escape(format)) return rv # webkit sends useless accept headers. They accept XML over # HTML or have no preference at all. We spotted them, so they # are obviously not regular API users, just ignore the accept # header and return the debug serializer. if request.user_agent.browser in ('chrome', 'safari'): return _serializer_map['debug'] best_match = (None, 0) for mimetype, serializer in _serializer_for_mimetypes.iteritems(): quality = request.accept_mimetypes[mimetype] if quality > best_match[1]: best_match = (serializer, quality) if best_match[0] is None: raise BadRequest(_(u'Could not detect format. You have to specify ' u'the format as query argument or in the accept ' u'HTTP header.')) # special case. If the best match is not html and the quality of # text/html is the same as the best match, we prefer HTML. if best_match[0] != 'text/html' and \ best_match[1] == request.accept_mimetypes['text/html']: return _serializer_map['debug'] return _serializer_map[best_match[0]]
def _dump(obj): if isinstance(obj, dict): d = dict(obj) obj_type = d.pop('#type', None) key = start = 'dict' if obj_type is not None: if obj_type.startswith('solace.'): key = start = obj_type[7:] else: start += ' type=%s' % quoteattr(obj_type) return u'<%s>%s</%s>' % ( start, u''.join((u'<%s>%s</%s>' % (key, _dump(value), key) for key, value in d.iteritems())), key ) if isinstance(obj, (tuple, list)): def _item_dump(obj): if not isinstance(obj, (tuple, list, dict)): return u'<item>%s</item>' % _dump(obj) return _dump(obj) return u'<list>%s</list>' % (u''.join(map(_item_dump, obj))) if isinstance(obj, bool): return obj and u'yes' or u'no' return escape(unicode(obj))
def set_filename(filename): "gets a secure version of filename, sets it in the session, and returns it." filename = escape(secure_filename(filename)) if filename.lower().endswith(".lsc"): filename = filename[:-4] session["filename"] = filename return filename
def _inner_dump(obj): if obj is None: return '<null/>' elif obj is True: return '<true/>' elif obj is False: return '<false/>' elif isinstance(obj, basestring): if isinstance(obj, str): obj = obj.decode('utf-8', 'ignore') return u'<string value="%s"/>' % (escape(obj, True)) elif isinstance(obj, (int, long)): return '<integer value="%s"/>' % str(obj) elif isinstance(obj, float): return '<float value="%s"/>' % str(obj) elif isinstance(obj, dict): return u'<dict>%s</dict>' % ''.join(u'<item><key>%s</key>' u'<value>%s</value></item>' % (_inner_dump(key), _inner_dump(value)) for key, value in obj.iteritems()) elif hasattr(obj, '__iter__'): return u'<list>%s</list>' % u''.join(map(obj, _inner_dump)) else: return u'<invalid/>'
def test__render_data_diff(self): item_name = u'Html_Item' empty_html = u'<span></span>' html = u'<span>\ud55c</span>' meta = {CONTENTTYPE: u'text/html;charset=utf-8'} item = Item.create(item_name) item._save(meta, empty_html) item = Item.create(item_name) # Unicode test, html escaping rev1 = update_item(item_name, meta, html) rev2 = update_item(item_name, {}, u' ') result = Text._render_data_diff(item.content, rev1, rev2) assert escape(html) in result # Unicode test, whitespace rev1 = update_item(item_name, {}, u'\n\n') rev2 = update_item(item_name, {}, u'\n \n') result = Text._render_data_diff(item.content, rev1, rev2) assert '<span> </span>' in result # If fairly similar diffs are correctly spanned or not, also check indent rev1 = update_item(item_name, {}, u'One Two Three Four\nSix\n\ud55c') rev2 = update_item(item_name, {}, u'Two Three Seven Four\nSix\n\ud55c') result = Text._render_data_diff(item.content, rev1, rev2) assert '<span>One </span>Two Three Four' in result assert 'Two Three <span>Seven </span>Four' in result # Check for diff_html.diff return types assert reduce(lambda x, y: x and y, [isinstance(i[1], unicode) and isinstance(i[3], unicode) for i in diff_html.diff(u'One Two Three Four\nSix\n', u'Two Three Seven Four\nSix Seven\n')], True)
def imaccount_edit(request, account_id=None): """Edit an existing game account or create a new one.""" imaccount = None if account_id is not None: imaccount = IMAccount.query.get(account_id) if imaccount is None: raise NotFound() elif imaccount.user != request.user: raise Forbidden() form = EditIMAccountForm(request.user, imaccount) if request.method == 'POST': if 'cancel' in request.form: return form.redirect('account/imaccount_list') elif request.form.get('delete') and imaccount: return redirect_to('account/imaccount_delete', account_id=account_id) elif form.validate(request.form): if imaccount is None: imaccount = form.make_imaccount() msg = _('IM account %s was added successfully.') icon = 'add' else: form.save_changes() msg = _('IM account %s was updated successfully.') icon = 'info' flash(msg % (escape(imaccount.account)), icon) db.commit() if 'save_and_continue' in request.form: return redirect_to('account/imaccount_edit', account_id=imaccount.id) return form.redirect('account/imaccount_list') return render_account_response('account/imaccount_edit.html', 'imaccounts', form=form.as_widget())
def _dump(obj): if isinstance(obj, dict): d = dict(obj) obj_type = d.pop("#type", None) key = start = "dict" if obj_type is not None: if obj_type.startswith("solace."): key = start = obj_type[7:] else: start += " type=%s" % quoteattr(obj_type) return u"<%s>%s</%s>" % ( start, u"".join((u"<%s>%s</%s>" % (key, _dump(value), key) for key, value in d.iteritems())), key, ) if isinstance(obj, (tuple, list)): def _item_dump(obj): if not isinstance(obj, (tuple, list, dict)): return u"<item>%s</item>" % _dump(obj) return _dump(obj) return u"<list>%s</list>" % (u"".join(map(_item_dump, obj))) if isinstance(obj, bool): return obj and u"yes" or u"no" return escape(unicode(obj))
def remove_plugin(request, plugin): """Remove an inactive, instance installed plugin completely.""" plugin = request.app.plugins.get(plugin) if plugin is None or \ not plugin.instance_plugin or \ plugin.active: raise NotFound() form = RemovePluginForm(plugin) if request.method == 'POST' and form.validate(request.form): if request.form.get('confirm'): try: plugin.remove() except IOError: flash(_(u'Could not remove the plugin “%s” because an ' u'IO error occurred. Wrong permissions?') % plugin.html_display_name) flash(_(u'The plugin “%s” was removed from the instance ' u'successfully.') % escape(plugin.display_name), 'remove') return form.redirect('admin/plugins') return render_admin_response('admin/remove_plugin.html', 'options.plugins', plugin=plugin, form=form.as_widget() )
def forum_edit(request, forum_id=None): """Edit an existing forum or create a new one.""" forum = None if forum_id is not None: forum = Forum.query.get(forum_id) if forum is None: raise NotFound() form = ForumForm(forum) if request.method == 'POST': if 'cancel' in request.form: return form.redirect(forum_endpoints['list']) elif 'delete' in request.form and forum: return redirect_to(forum_endpoints['delete'], forum_id=forum_id) elif form.validate(request.form): if forum is None: forum = form.create_forum() msg = _('The forum %s was created successfully.') icon = 'add' else: form.save_changes(forum) msg = _('The forum %s was updated successfully.') icon = 'info' admin_flash(msg % ('<a href="%s">%s</a>' % (url_for(forum_endpoints['edit'], forum_id=forum.id), escape(forum.name))), icon) if 'save_and_continue' in request.form: return redirect_to(forum_endpoints['edit'], forum_id=forum_id) elif 'save_and_new' in request.form: return redirect_to(forum_endpoints['edit']) return redirect_to(forum_endpoints['list']) return render_admin_response('admin/board_base_edit.html', 'board.forums', form=form.as_widget(), itemname=_('Forum'))
def edit_squad(request, squad_id=None): """Edit an existing squad or create a new one.""" squad = None if squad_id is not None: squad = Squad.query.get(squad_id) if squad is None: raise NotFound() form = EditSquadForm(squad) if request.method == 'POST': if 'cancel' in request.form: return form.redirect('admin/squads') elif request.form.get('delete') and squad: return redirect_to('admin/squads/delete', squad_id=squad.id) elif form.validate(request.form): if squad is None: squad = form.make_squad() msg = _('The squad %s was created successfully.') icon = 'add' else: form.save_changes() msg = _('The squad %s was updated successfully.') icon = 'info' admin_flash(msg % (escape(squad.name)), icon) db.commit() if 'save_and_continue' in request.form: return redirect_to('admin/squads/edit', squad_id=squad.id) return redirect_to('admin/squads') return render_admin_response('admin/squad_edit.html', 'gamesquad.squads', form=form.as_widget())
def edit_level(request, level_id=None): """Edit an existing level or create a new one.""" level = None if level_id is not None: level = Level.query.get(level_id) if level is None: raise NotFound() form = EditLevelForm(level) if request.method == 'POST': if 'cancel' in request.form: return form.redirect('admin/levels') elif request.form.get('delete') and level: return redirect_to('admin/levels/delete', level_id=level_id) elif form.validate(request.form): if level is None: level = form.make_level() msg = _('The level %s was created successfully.') icon = 'add' else: form.save_changes() msg = _('The level %s was updated successfully.') icon = 'info' admin_flash(msg % (escape(level.name)), icon) db.commit() if 'save_and_continue' in request.form: return redirect_to('admin/levels/edit', level_id=level.id) return redirect_to('admin/levels') return render_admin_response('admin/level_edit.html', 'levelsquad.levels', form=form.as_widget())
def gameaccount_edit(request, account_id=None): """Edit an existing game account or create a new one.""" gameaccount = None if account_id is not None: gameaccount = GameAccount.query.get(account_id) if gameaccount is None: raise NotFound() form = EditGameAccountForm(request.user, gameaccount) if request.method == 'POST': if 'cancel' in request.form: return form.redirect('account/gameaccounts') elif request.form.get('delete') and gameaccount: return redirect_to('account/gameaccounts/delete', account_id=account_id) elif form.validate(request.form): if gameaccount is None: gameaccount = form.make_gameaccount() msg = _('The game account %s was registered successfully.') icon = 'add' else: form.save_changes() msg = _('The game account %s was updated successfully.') icon = 'info' account_flash(msg % (escape(gameaccount.account)), icon) db.commit() if 'save_and_continue' in request.form: return redirect_to('account/gameaccounts/edit', account_id=gameaccount.id) return redirect_to('account/gameaccounts') return render_account_response('account/gameaccount_edit.html', 'gameaccounts', form=form.as_widget())
def content_iter(self, lines=None): import csv _ = self.wiki.gettext # XXX Add preview support csv_file = self.storage.open_page(self.title) reader = csv.reader(csv_file) html_title = werkzeug.escape(self.title, quote=True) yield '<table id="%s" class="csvfile">' % html_title try: for row in reader: yield '<tr>%s</tr>' % (''.join('<td>%s</td>' % cell for cell in row)) except csv.Error as e: yield '</table>' yield werkzeug.html.p( werkzeug.html( _('Error parsing CSV file %{file}s on ' 'line %{line}d: %{error}s') % { 'file': html_title, 'line': reader.line_num, 'error': e })) finally: csv_file.close() yield '</table>'
def _inner_dump(obj): if obj is None: return '<null/>' elif obj is True: return '<true/>' elif obj is False: return '<false/>' elif isinstance(obj, basestring): if isinstance(obj, str): obj = obj.decode('utf-8', 'ignore') return u'<string value="%s"/>' % (escape(obj, True)) elif isinstance(obj, (int, long)): return '<integer value="%s"/>' % str(obj) elif isinstance(obj, float): return '<float value="%s"/>' % str(obj) elif isinstance(obj, dict): return u'<dict>%s</dict>' % ''.join( u'<item><key>%s</key>' u'<value>%s</value></item>' % (_inner_dump(key), _inner_dump(value)) for key, value in obj.iteritems()) elif hasattr(obj, '__iter__'): return u'<list>%s</list>' % u''.join(map(obj, _inner_dump)) else: return u'<invalid/>'
def edit_game(request, game_id=None): """Edit an existing game or create a new one.""" game = None if game_id is not None: game = Game.query.get(game_id) if game is None: raise NotFound() form = EditGameForm(game) if request.method == 'POST': if 'cancel' in request.form: return form.redirect('admin/games') elif request.form.get('delete') and game: return redirect_to('admin/games/delete', game_id=game.id) elif form.validate(request.form): if game is None: game = form.make_game() msg = _('The game %s was created successfully.') icon = 'add' else: form.save_changes() msg = _('The game %s was updated successfully.') icon = 'info' admin_flash(msg % (escape(game.name)), icon) db.commit() if 'save_and_continue' in request.form: return redirect_to('admin/game_edit', game_id=game.id) return redirect_to('admin/games') return render_admin_response('admin/game_edit.html', 'gamesquad.games', form=form.as_widget())
def get_serializer(request): """Returns the serializer for the given API request.""" format = request.args.get('format') if format is not None: rv = _serializer_map.get(format) if rv is None: raise BadRequest(_(u'Unknown format "%s"') % escape(format)) return rv # webkit sends useless accept headers. They accept XML over # HTML or have no preference at all. We spotted them, so they # are obviously not regular API users, just ignore the accept # header and return the debug serializer. if request.user_agent.browser in ('chrome', 'safari'): return _serializer_map['debug'] best_match = (None, 0) for mimetype, serializer in _serializer_for_mimetypes.iteritems(): quality = request.accept_mimetypes[mimetype] if quality > best_match[1]: best_match = (serializer, quality) if best_match[0] is None: raise BadRequest( _(u'Could not detect format. You have to specify ' u'the format as query argument or in the accept ' u'HTTP header.')) # special case. If the best match is not html and the quality of # text/html is the same as the best match, we prefer HTML. if best_match[0] != 'text/html' and \ best_match[1] == request.accept_mimetypes['text/html']: return _serializer_map['debug'] return _serializer_map[best_match[0]]
def index(request): return Response(''' <title>Logged in</title> <h1>Logged in</h1> <p>Logged in as %s <p><a href="/?do=logout">Logout</a> ''' % escape(request.user), mimetype='text/html')
def show_config(req): """Request handler that provides an admin page with the configuration for the pygments plugin. So far this only allows changing the style. """ active_style = get_current_style() styles = sorted([(x, x.title()) for x in STYLES]) form = ConfigurationForm(initial=dict(style=active_style)) form.fields['style'].choices = styles if req.method == 'POST' and form.validate(req.form): active_style = form['style'] if 'apply' in req.form: req.app.cfg.change_single('pygments_support/style', active_style) flash(_('Pygments theme changed successfully.'), 'configure') return redirect_to('pygments_support/config') preview_formatter = get_formatter(active_style, preview=True) add_header_snippet('<style type="text/css">\n%s\n</style>' % escape(preview_formatter.get_style_defs())) example = highlight(EXAMPLE, get_lexer_by_name('html+jinja'), preview_formatter) return render_admin_response('admin/pygments_support.html', 'options.pygments_support', example=example, form=form.as_widget())
def view_content(self, lines=None): if self.title not in self.storage: raise hatta.error.NotFoundErr() content = ['<img src="%s" alt="%s">' % (self.request.get_url(self.title, 'render'), werkzeug.escape(self.title))] return content
def view_content(self, lines=None): if self.title not in self.storage: raise hatta.error.NotFoundErr() content = ['<p>Download <a href="%s">%s</a> as <i>%s</i>.</p>' % (self.request.get_download_url(self.title), werkzeug.escape(self.title), self.mime)] return content
def datetimeformat_filter(obj, html=True, prefixed=True): rv = format_datetime(obj) if prefixed: rv = _(u'on %s') % rv if html: rv = u'<span class="datetime" title="%s">%s</span>' % ( obj.strftime('%Y-%m-%dT%H:%M:%SZ'), escape(rv)) return Markup(rv)
def view_content(self, lines=None): if self.title not in self.storage: raise error.NotFoundErr() content = [ '<img src="%s" alt="%s">' % (self.request.get_url( self.title, self.wiki.render), werkzeug.escape(self.title)) ] return content
def __init__(self, show_title=True, title=u'Shoutbox', entrycount=10, hide_form=False): super(ShoutboxWidget, self).__init__() self.title = title self.show_title = show_title self.hide_form = hide_form self.entries = ShoutboxEntry.query.order_by(ShoutboxEntry.postdate.desc()) \ .limit(entrycount).all() self.newposturl = escape(url_for('shoutbox/post', next=get_request().path))
def highlight_section(pos): start, filename, lang = last section_code = _escaped_marker.sub('', code[start:pos]) if section_code: result.append( u'<div class="section">%s%s</div>' % (filename and u'<p class="filename">%s</p>' % escape(filename) or u'', highlight(section_code, lang)))
def wiki_math(self, math): math_url = self.config.get( 'math_url', 'http://www.mathtran.org/cgi-bin/mathtran?tex=') if '%s' in math_url: url = math_url % werkzeug.url_quote(math) else: url = '%s%s' % (math_url, werkzeug.url_quote(math)) label = werkzeug.escape(math, quote=True) return werkzeug.html.img(src=url, alt=label, class_="math")
def view_content(self, lines=None): if self.title not in self.storage: raise error.NotFoundErr() content = [ '<a href="%s"><img src="%s" alt="%s"></a>' % (self.get_url(self.title, 'download'), self.get_url(self.title, 'render'), werkzeug.escape(self.title)) ] return content
def view_content(self, lines=None): if self.title not in self.storage: raise error.NotFoundErr() content = [ '<p>Download <a href="%s">%s</a> as <i>%s</i>.</p>' % (self.get_download_url(self.title), werkzeug.escape( self.title), self.mime) ] return content
def _block_heading(self, block): for self.line_no, line in block: level = min(len(self.heading_re.match(line).group(0).strip()), 5) self.headings[level - 1] = self.headings.get(level - 1, 0) + 1 label = u"-".join( str(self.headings.get(i, 0)) for i in range(level)) yield werkzeug.html.a(name="head-%s" % label) yield u'<h%d id="line_%d">%s</h%d>' % ( level, self.line_no, werkzeug.escape( line.strip("= \t\n\r\v")), level)
def wiki_link(self, addr, label=None, class_=None, image=None, lineno=0): """Create HTML for a wiki link.""" addr = addr.strip() text = werkzeug.escape(label or addr) chunk = '' if class_ is not None: classes = [class_] else: classes = [] if parser.external_link(addr): classes.append('external') if addr.startswith('mailto:'): # Obfuscate e-mails a little bit. classes.append('mail') text = text.replace('@', '@').replace('.', '.') href = werkzeug.escape(addr, quote=True).replace('@', '%40').replace( '.', '%2E') else: href = werkzeug.escape(werkzeug.url_fix(addr), quote=True) else: if '#' in addr: addr, chunk = addr.split('#', 1) chunk = '#' + werkzeug.url_fix(chunk) if addr.startswith(':'): alias = self.link_alias(addr[1:]) href = werkzeug.escape(werkzeug.url_fix(alias) + chunk, True) classes.append('external') classes.append('alias') elif addr.startswith('+'): href = '/'.join([ self.request.script_root, '+' + werkzeug.escape(addr[1:], quote=True) ]) classes.append('special') elif addr == u'': href = werkzeug.escape(chunk, True) classes.append('anchor') else: classes.append('wiki') href = werkzeug.escape(self.get_url(addr) + chunk, True) if addr not in self.storage: classes.append('nonexistent') class_ = werkzeug.escape(' '.join(classes) or '', True) # We need to output HTML on our own to prevent escaping of href return '<a href="%s" class="%s" title="%s">%s</a>' % ( href, class_, werkzeug.escape(addr + chunk, True), image or text)
def _block_display_math(self, block): for self.line_no, part in block: math_text = "\n".join(self.lines_until(self.display_math_close_re)) if self.wiki_math: math_text = self.wiki_math(math_text, True) else: math_text = werkzeug.escape(math_text) yield werkzeug.html.div( math_text, class_="display-math", id="line_%d" % self.line_no, )
def list_documented_plugins(app): """Return a list of all documented plugins.""" plugins = [] for plugin in app.plugins.itervalues(): if plugin.is_documented: plugins.append( '<li><a href="%s">%s</a></li>' % (url_for('admin/help', page='plugins/%s/' % plugin.name), escape(plugin.display_name))) if not plugins: return u'<ul><li>%s</li></ul>' % _('no documented plugins installed.') return '<ul>%s</ul>' % '\n'.join(plugins)
def format_csv(code): """Display CSV code.""" class dialect(csv.excel): quoting = csv.QUOTE_ALL result = ['<div class="csv"><table>'] lines = code.encode('utf-8').splitlines() for idx, row in enumerate(csv.reader(lines, dialect=dialect)): result.append('<tr class="%s">' % (idx % 2 == 0 and 'even' or 'odd')) for col in row: result.append('<td>%s</td>' % escape(col)) result.append('</tr>\n') result.append('</table></div>') return ''.join(result).decode('utf-8')
def render_query_table(queries): """Renders a nice table of all queries in the page.""" total = 0 stylesheet = url_for('core/shared', filename='debug.css') result = [ u'<style type="text/css">@import url(%s)</style>' % stylesheet, u'<div class="_database_debug_table"><ul>' ] for statement, parameters, start, end, calling_context in queries: total += (end - start) result.append(u'<li><pre>%s</pre><div class="detail"><em>%s</em> | ' u'<strong>took %.3f ms</strong></div></li>' % (statement, escape(calling_context), (end - start) * 1000)) result.append(u'<li><strong>%d queries in %.2f ms</strong></ul></div>' % (len(queries), total * 1000)) return u'\n'.join(result)
def wiki_link(self, addr, label=None, class_=None, image=None, lineno=0): addr = addr.strip() text = werkzeug.escape(label or addr) chunk = '' if class_ is not None: classes = [class_] else: classes = [] if hatta.parser.external_link(addr): classes.append('external') if addr.startswith('mailto:'): # Obfuscate e-mails a little bit. classes.append('mail') text = text.replace('@', '@').replace('.', '.') href = werkzeug.escape(addr, quote=True).replace('@', '%40').replace( '.', '%2E') else: href = werkzeug.escape(werkzeug.url_fix(addr), quote=True) else: if '#' in addr: addr, chunk = addr.split('#', 1) chunk = '#' + werkzeug.url_fix(chunk) if addr.startswith(':'): alias = self._link_alias(addr[1:]) href = werkzeug.escape(werkzeug.url_fix(alias) + chunk, True) classes.append('external') classes.append('alias') elif addr == u'': href = werkzeug.escape(chunk, True) classes.append('anchor') else: classes.append('wiki') href = werkzeug.escape(self.get_ref_path(addr) + chunk, True) if addr not in self.wiki.storage: classes.append('nonexistent') # if necessary, add suffix if self.add_link_ext is not None: href += self.add_link_ext class_ = werkzeug.escape(' '.join(classes) or '', True) # We need to output HTML on our own to prevent escaping of href return u'<a href="%s" class="%s" title="%s">%s</a>' % ( href, class_, werkzeug.escape(addr + chunk, True), image or text)
def search_snippet(title, words): """Extract a snippet of text for search results.""" try: text = current_app.storage.page_text(title) except error.NotFoundErr: return '' regexp = re.compile("|".join(re.escape(w) for w in words), re.U | re.I) match = regexp.search(text) if match is None: return "" position = match.start() min_pos = max(position - 60, 0) max_pos = min(position + 60, len(text)) snippet = werkzeug.escape(text[min_pos:max_pos]) html = regexp.sub(highlight_html, snippet) return html
def search_snippet(title, words): """Extract a snippet of text for search results.""" try: text = self.storage.page_text(title) except error.NotFoundErr: return u'' regexp = re.compile(u"|".join(re.escape(w) for w in words), re.U | re.I) match = regexp.search(text) if match is None: return u"" position = match.start() min_pos = max(position - 60, 0) max_pos = min(position + 60, len(text)) snippet = werkzeug.escape(text[min_pos:max_pos]) highlighted = werkzeug.html.b(match.group(0), class_="highlight") html = regexp.sub(highlighted, snippet) return html
def diff_content(self, from_text, to_text, message=''): """Generate the HTML markup for a diff.""" def infiniter(iterator): """Turn an iterator into an infinite one, padding it with None""" for i in iterator: yield i while True: yield None diff = difflib._mdiff(from_text.split('\n'), to_text.split('\n')) mark_re = re.compile('\0[-+^]([^\1\0]*)\1|([^\0\1])') yield message yield '<pre class="diff">' for old_line, new_line, changed in diff: old_no, old_text = old_line new_no, new_text = new_line line_no = (new_no or old_no or 1) - 1 if changed: yield '<div class="change" id="line_%d">' % line_no old_iter = infiniter(mark_re.finditer(old_text)) new_iter = infiniter(mark_re.finditer(new_text)) old = next(old_iter) new = next(new_iter) buff = '' while old or new: while old and old.group(1): if buff: yield werkzeug.escape(buff) buff = '' yield '<del>%s</del>' % werkzeug.escape(old.group(1)) old = next(old_iter) while new and new.group(1): if buff: yield werkzeug.escape(buff) buff = '' yield '<ins>%s</ins>' % werkzeug.escape(new.group(1)) new = next(new_iter) if new: buff += new.group(2) old = next(old_iter) new = next(new_iter) if buff: yield werkzeug.escape(buff) yield '</div>' else: yield '<div class="orig" id="line_%d">%s</div>' % ( line_no, werkzeug.escape(old_text)) yield '</pre>'