def xhr_list_tenants(self): sess = DbSession() qry = sess.query(Principal.id, Principal.display_name).order_by( Principal.display_name) opts = "\n".join(['<option value="{0}">{1}</option>'.format( markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry]) return "<select>\n" + opts + "\n</select>"
def get_cached_board_topic(topic_id): try: topic = BoardTopic.objects.with_id(topic_id) if topic is None: return None if topic.content: topic.html_content = urlink(escape(topic.content)) #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30) else: topic.html_content = '' if topic.more_content: topic.html_more_content = br_escape(urlink(escape(topic.more_content))) #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30) else: topic.html_more_content = '' if topic.video_urls: topic.extra_content = '' video_html = '<p></p>' for url in topic.video_urls: video_html += video(url) topic.extra_content = video_html return topic except Exception, error: return None
def _check_access(self, trans, is_admin, item, current_user_roles): can_access = True if isinstance(item, trans.model.HistoryDatasetAssociation): # Make sure the user has the DATASET_ACCESS permission on the history_dataset_association. if not item: message = "Invalid history dataset (%s) specified." % escape(str(item)) can_access = False elif not trans.app.security_agent.can_access_dataset(current_user_roles, item.dataset) and item.history.user == trans.user: message = "You do not have permission to access the history dataset with id (%s)." % str(item.id) can_access = False else: # Make sure the user has the LIBRARY_ACCESS permission on the library item. if not item: message = "Invalid library item (%s) specified." % escape(str(item)) can_access = False elif not (is_admin or trans.app.security_agent.can_access_library_item(current_user_roles, item, trans.user)): if isinstance(item, trans.model.Library): item_type = 'data library' elif isinstance(item, trans.model.LibraryFolder): item_type = 'folder' else: item_type = '(unknown item type)' message = "You do not have permission to access the %s with id (%s)." % (escape(item_type), str(item.id)) can_access = False if not can_access: return 400, message
def _format_quote(self, tag, contents, options, parent, context): """Handle a [quote] tag. Examples: [quote]contents[/quote] [quote=name]contents[/quote] [quote=name;123]123 is a TCoDf post id in this example[/quote] """ contents = _chomp(contents) html = [] # Add header for [quote=name] or [quote=name;123] if 'quote' in options: html.append('<div class="bbcode-quote-header">Quote from <b>') match = re.fullmatch('(.+?)(;\d+)?', options['quote']) (name, post_id) = match.groups() if post_id is not None: post_id = int(post_id.lstrip(';')) html.append('<a href="{}">{}</a>'.format( asb.tcodf.post_link(post_id), markupsafe.escape(name) )) else: html.append(markupsafe.escape(name)) html.append(':</b></div>') html.append('<blockquote>{}</blockquote>'.format(contents)) return ''.join(html)
def route_do_edit(): title = form('title') id = int(form('id')) content = form('content') hpot = form('email') if title is None or id is None or content is None or hpot is not "": return 'Error' if app.config['locked']: if form('pass') != app.config['pass']: return redirect('/') if not database.init(): return error(app.config['db_err_title'], app.config['db_err_msg']), 503 if id == 0: database.query('INSERT INTO articles VALUES(NULL, ?, ?, 0)', [escape(title), escape(content)]) else: database.query("UPDATE articles SET revision = 1 WHERE title=?", [title]) database.query("INSERT INTO articles VALUES(NULL, ?, ?, 0)", [escape(title), escape(content)]) database.close() return redirect(url_for('route_article', title=title))
def block_code(self, text, lang): if not lang: text = text.strip() return u'<pre><code>%s</code></pre>\n' % escape(text) inlinestyles = False linenos = False if hasattr(self, '_inlinestyles'): inlinestyles = self._inlinestyles if hasattr(self, '_linenos'): linenos = self._linenos try: lexer = get_lexer_by_name(lang, stripall=True) formatter = HtmlFormatter( noclasses=inlinestyles, linenos=linenos ) code = highlight(text, lexer, formatter) if linenos: return '<div class="highlight-wrapper">%s</div>\n' % code return code except: return '<pre class="%s"><code>%s</code></pre>\n' % ( lang, escape(text) )
def share(self, trans, id, email="", use_panels=False): msg = mtype = None # Load workflow from database stored = self.get_stored_workflow(trans, id) if email: other = trans.sa_session.query(model.User) \ .filter(and_(model.User.table.c.email == email, model.User.table.c.deleted == expression.false())) \ .first() if not other: mtype = "error" msg = ("User '%s' does not exist" % escape(email)) elif other == trans.get_user(): mtype = "error" msg = ("You cannot share a workflow with yourself") elif trans.sa_session.query(model.StoredWorkflowUserShareAssociation) \ .filter_by(user=other, stored_workflow=stored).count() > 0: mtype = "error" msg = ("Workflow already shared with '%s'" % escape(email)) else: share = model.StoredWorkflowUserShareAssociation() share.stored_workflow = stored share.user = other session = trans.sa_session session.add(share) session.flush() trans.set_message("Workflow '%s' shared with user '%s'" % (escape(stored.name), escape(other.email))) return trans.response.send_redirect(url_for(controller='workflow', action='sharing', id=id)) return trans.fill_template("/ind_share_base.mako", message=msg, messagetype=mtype, item=stored, email=email, use_panels=use_panels)
def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) c = context.get('c', UNDEFINED) config = context.get('config', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 1 __M_writer(u'<html>\n<head>\n<meta charset="utf-8" />\n\n<script type="text/javascript" src="http://localhost:5000/jquery.js"> </script>\n<script type="text/javascript" src="http://localhost:5000/all.js"> </script>\n<script type = "text/javascript" src="http://localhost:5000/usrsignup.js"> </script>\n<script language = javascript>\n\t$user_id = ') # SOURCE LINE 9 __M_writer(escape(c.id)) __M_writer(u' ;\n\talert("logged in user = "******"stylesheet" href="http://localhost:5000/header.css" media="screen" type="text/css"/>\n<link rel="stylesheet" href="http://localhost:5000/mnbody.css" media="screen" type="text/css"/>\n\n<style type="text/css">\nhtml \t {\n background-color: #ddd;\n font: 62.5%/1 "Lucida Sans Unicode","Lucida Grande",Verdana,Arial,Helvetica,sans-serif;\n }\n body { padding: 100px; }\n #wrapper { text-align: center; }\n .icon:before { line-height: .7em; }\n</style> \n</head>\n<body>\n<!-- Header -->\n<div id="backwrap" class="bodybg">\n\n <img src="/home/purvi/Desktop/masti/Preetis... 0619.jpg" height="100" width="200" border="0" hspace=150 vspace=0 />\n \n <span class="centerDoc"> <h1>Welcome to Fiesta</h1></span>\n\n <div id="usrlogin">\n <h2 style="position:absolute; left:1050px; width:200px; height:40px">Want to share with us</h2>\n <img style="cursor:pointer" src="https://dgjcoqnzn763b.cloudfront.net/images/general/btn_fconnect.png" onClick="connectToapp()"/>\n <h2 style="position:absolute; left:1050px; width:200px; height:40px">R u a merchant?</h2>\n <img style="cursor:pointer" src="https://dgjcoqnzn763b.cloudfront.net/images/general/btn_fconnect.png" onClick="merchantToapp()"/>\n </div>\n</div>\n\n<!-- Header ends-->\n<div id="mainbody">\n<div id="main_content">\n\n <div id="wrapper">\n <h1>Merchant Registration for ') # SOURCE LINE 47 __M_writer(escape(c.name)) __M_writer(u'</h1>\n <br /><br />\n <div class="form_section">\n <div class="field_wrapper">\n <div class="label_wrapper">\n <label for="id_name">\n Name\n </label>\n </div>\n <input id="id_name" type="text" name="name" />\n\t\t ') # SOURCE LINE 57 __M_writer(escape(c.name)) __M_writer(u' = name.value\n </div>\n\n\n \t <div class="field_wrapper">\n <div class="label_wrapper">\n <label for="contact">\n Contact No <span class="required">*</span>\n </label>\n </div>\n <input id="contact" type="text" name="contactno" />\n\n \t </div> \n\n \t\t<div class="field_wrapper">\n <div class="label_wrapper">\n <label for="store">\n Store Name <span class="required">*</span>\n </label>\n </div>\n <input id="store" type="text" name="storenamee" />\n\n \t\t</div>\n\n \t\t<div class="field_wrapper">\n <div class="label_wrapper">\n <label for="ttl">\n Title <span class="required">*</span>\n </label>\n </div>\n <input id="ttl" type="text" name="title" />\n\n \t</div>\n\n \t<div class="field_wrapper">\n <div class="label_wrapper">\n <label for="site_url">\n SiteURL <span class="required">*</span>\n </label>\n </div>\n <input id="site_url" type="text" name="siteurl" />\n\n \t</div>\n\n\n<a title="" href="http://') # SOURCE LINE 102 __M_writer(escape(config['myhost'])) __M_writer(u':5000/retailer/store?id=') __M_writer(escape(c.name)) __M_writer(u'">submit</a>\n</div>\n</div>\n\n</body>\n</html>\n') return '' finally: context.caller_stack._pop_frame()
def get_exclusions(request, naics_code, link_page=None, all_langs=False): with request.connmgr.get_connection() as conn: cursor = conn.execute('EXEC dbo.sp_NAICS_Exclusion_l ?,?', str(naics_code), all_langs) exclusions = cursor.fetchall() cursor.nextset() uses = cursor.fetchall() cursor.close() uses = dict((k, list(v)) for k,v in groupby(uses, attrgetter('Exclusion_ID'))) output = [] for establishment, exclusions in groupby(exclusions, attrgetter('Establishment')): if establishment: output.extend([Markup('<p>'), _('Establishments primarily engaged in:', request), Markup('</p>')]) output.append(Markup('<ul>')) for exclusion in exclusions: use_instead = "; ".join(link_code(request, x.Code, x.Code, link_page) + ' ' + escape(x.Classification) for x in (uses.get(exclusion.Exclusion_ID) or [])) if use_instead: use_instead = use_instead.join([" (", ")"]) output.extend([Markup('<li>'), escape(exclusion.Description), use_instead,Markup('</li>')]) output.append(Markup('</ul>')) return Markup(''.join(output))
def redirect_to_twitter(twitter_handle): """Redirect GET requests for /@TwitterHandle/ to respective the OSF user account if it associated with an active account :param uid: uid for requested User :return: Redirect to User's Twitter account page """ try: user = User.find_one(Q("social.twitter", "iexact", twitter_handle)) except NoResultsFound: raise HTTPError( http.NOT_FOUND, data={ "message_short": "User Not Found", "message_long": "There is no active user associated with the Twitter handle: {0}.".format( twitter_handle ), }, ) except MultipleResultsFound: users = User.find(Q("social.twitter", "iexact", twitter_handle)) message_long = ( "There are multiple OSF accounts associated with the " "Twitter handle: <strong>{0}</strong>. <br /> Please " "select from the accounts below. <br /><ul>".format(markupsafe.escape(twitter_handle)) ) for user in users: message_long += '<li><a href="{0}">{1}</a></li>'.format(user.url, markupsafe.escape(user.fullname)) message_long += "</ul>" raise HTTPError( http.MULTIPLE_CHOICES, data={"message_short": "Multiple Users Found", "message_long": message_long} ) return redirect(user.url)
def xhr_list_domains(self): sess = DbSession() qry = sess.query(Domain.id, Domain.name).order_by( Domain.name) opts = "\n".join(['<option value="{0}">{1}</option>'.format( markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry]) return "<select>\n" + opts + "\n</select>"
def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) c = context.get('c', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 1 __M_writer(u'<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n\t<title>DestrActions: Singapore\'s Monthly Design Distraction & Interaction</title>\n\t<link rel="shortcut icon" href="favicon.png" />\n\t<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Arvo">\n\t<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Cantarell">\n\t<link rel="stylesheet" type="text/css" href="styles.css">\n\t<script type="text/javascript">\n\t\tfunction showFAQ() {\n\t\t\tdocument.getElementById("show_faq").style.display = "none";\n\t\t\tdocument.getElementById("faq_text").style.display = "block";\n\t\t} \n\t</script>\n\t<!-- GOOGLE ANALYTICS //-->\n\t<script type="text/javascript">\n\n\t\tvar _gaq = _gaq || [];\n\t\t_gaq.push([\'_setAccount\', \'UA-30242158-1\']);\n\t\t_gaq.push([\'_setDomainName\', \'dactions.org\']);\n\t\t_gaq.push([\'_trackPageview\']);\n\n\t\t(function() {\n\t\t\tvar ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;\n\t\t\tga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';\n\t\t\tvar s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);\n\t\t})();\n\t</script>\n</head>\n<body>\n\n\t<div class="contents_wrapper">\n\t\t<div class="contents">\n\t\t\t<h3>Manifesto</h3>\n\t\t\t<p>\n\t\t\t\tWe ♥ design meet-ups to mingle and network, to inspire and being inspired. But we miss variety\n\t\t\t\tin topics and activities. In our daily project routines we dread for creative interruptions and small challenges\n\t\t\t\tto keep our minds nimble. Therefore working an evening on out-of-context challenge with new faces is sheer bliss.\n\t\t\t</p>\n\t\t</div>\n\t</div>\n\t\n\t<div id="banner">\n\t\t<div class="contents_wrapper">\n\t\t\t<div class="contents">\n\t\t\t\t<h1>DestrActions</h1>\n\t\t\t\t<h6>Design × Distraction × Interaction</h6>\n\t\t\t\n\t\t\t\t<h3>Details</h3>\n\t\t\t\t<p>\n\t\t\t\t\tTuesday, ') # SOURCE LINE 52 __M_writer(escape(c.next_date)) __M_writer(u' at 19:00 (7pm)<br/>\n\t\t\t\t\tAt <a href="http://thepigeonhole.com.sg/" name="link to location">The Pigeonhole</a>, 52/53 Duxton Road. <a href="http://maps.google.com.sg/maps?q=The+Pidgeonhole,+52%2F53+Duxton+Road,+Singapore&hl=en&ll=1.279286,103.843267&spn=0.011563,0.015385&sll=1.278179,103.843328&sspn=0.011563,0.015385&vpsrc=0&hq=The+Pidgeonhole,&hnear=53+Duxton+Rd,+Singapore+089517&t=m&cid=8372603932834912927&z=16&iwloc=A" name="link to location map">(map)</a>\n\t\t\t\t</p>\n\n\t\t\t\t<h3>Signup</h3>\n\t\t\t\t<p><a href="https://www.flickevents.com/destractions-sg-march-2012">Signup via FlickEvents</a></p>\n\t\t\t\n\t\t\t\t<h3>Contact</h3>\n\t\t\t\t<p>\n\t\t\t\t\tTwitter: <a href="http://twitter.com/#!/DActions" name="Link to DActions on Twitter"> @DActions</a>\n\t\t\t\t\t × Facebook: <a href="http://www.facebook.com/groups/DActions.SG" name="Link to DActions on Facebook"> DActions.SG</a>\n\t\t\t\t\t × e-Mail:\n\t\t\t\t\t<a href="mailto:[email protected]" name="e-mail to DActions"> [email protected]</a>\n\t\t\t\t</p>\n\t\t\t\t<h3>Cost</h3>\n\t\t\t\t<p>free but we encourage you to get a drink or two</p>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n\n\t<div class="contents_wrapper">\n\t\t<div id="contents_box">\n\t\t\t<div class="contents">\n\n\t\t\t\t<h3>What</h3>\n\t\t\t\t<p>We meet on the <em>3rd Tuesday every month</em> with fellow designers to <em>collaborate</em> a few hours on <em>small design challenges</em> across the disciplines. We conclude the session with a brief presentation and discussion of the designs before making them available online.</p>\n\t\t\t\t<h3>Who</h3>\n\t\t\t\t<p>\n\t\t\t\t\tThe sessions are <em>open for everybody</em> with interest in designing stuff. You don\'t need to be an architect,\n\t\t\t\t\tindustrial/graphic/fashion/etc. designer, ergonomist or artist to join. The engineer, business girl, accounting guy,\n\t\t\t\t\tkindergarden teacher or hobby inventor is as welcome to join and get their creative juices flow. The goal is to open up to other\n\t\t\t\t\tdesign ideas, get out of the comfort zone and be inspired.<br/><br />\n\t\t\t\t\tWho we don\u2019t want are elitists, design divas and rockstars that can\u2019t collaborate. <em>Keep it simple and down to\n\t\t\t\t\tearth, creative and sharing.</em> It\u2019s to tickle your brain out of the routine.\n\t\t\t\t</p>\n\t\t\t\t<h3>Format</h3>\n\t\t\t\t<table>\n\t\t\t\t\t<tr><th>Challenge</th><td>Pitch and explanation of the different challenges to choose from. If you have proposals please <a href="http://twitter.com/#!/DActions" name="Link to DActions on Twitter">tweet</a> or <a href="mailto:[email protected]" name="e-mail to DActions">e-mail</a> them.</td></tr>\n\t\t\t\t\t<tr><th>Team Lottery</th><td>A simple hat-lottery system to draft the groups to make sure you don\'t always work with your buddies.</td></tr>\n\t\t\t\t\t<tr><th>Team Work</th><td>Group work for 90 minutes to design the proposals (i.e. brainstorming, discussion, sketching, etc.).</td></tr>\n\t\t\t\t\t<tr><th>Presentation</th><td>Each group briefly presents their designs with a short discussion and feedback session.</td></tr>\n\t\t\t\t</table>\n\t\n\t\t\t\t<h3>Supplies</h3>\n\t\t\t\t<p>\n\t\t\t\t\tBring you jolly self, your <em>charm, sharp mind and keen eye</em>, your design instinct and anything else\n\t\t\t\t\tthat has been dulled down. Bringing your <em>favourite designing pen and paper</em> will help to come up with results.\n\t\t\t\t</p>\n\t\n\t\t\t\t<h3>Results</h3>\n\t\t\t\t<p>\n\t\t\t\t\tIn the end the <em>results will be published online as Creative Commons Attribution</em> so you can share and refer to them. The place for this\n\t\t\t\t\thas not yet been decided.\n\t\t\t\t</p>\n\t\t\t\t\t\n\t\t\t</div>\n\t\t\t<div class="right">\n\t\t\t\t<h4>Session Results</h4>\n\n <ul>\n') # SOURCE LINE 112 for result in c.results: # SOURCE LINE 113 __M_writer(u' <li>\n ') # SOURCE LINE 114 __M_writer(escape(result['name'])) __M_writer(u':\n <a href="') # SOURCE LINE 115 __M_writer(escape(result['path'])) __M_writer(u'results.html" title="Results from ') __M_writer(escape(result['name'])) __M_writer(u'">Results</a>\n </li>\n') pass # SOURCE LINE 118 __M_writer(u' </ul>\n\n\t\t\t\t<p class="separator"> × × × </p>\n\t\t\t\t\n\t\t\t\t<h4>Related Events</h4>\n\t\t\t\t<ul>\n\t\t\t\t\t<li><a href="http://www.creativemixer.co" title="Link to Creative Mixer">Creative Mixer</a></li>\n\t\t\t\t\t<li><a href="http://www.ixdsessions.com" title="Link to IXD Sessions">IXD Sessions</a></li>\n\t\t\t\t\t<li><a href="http://experienceunion.wordpress.com/category/kennel-nights" title="Link to Kennel Nights">Kennel Nights</a></li>\n\t\t\t\t\t<li><a href="http://www.farm.sg/rojak" title="Link to ROJAK">ROJAK</a></li>\n\t\t\t\t\t<li><a href="http://www.pecha-kucha.org" name="Link to Pecha Kucha">Pecha Kucha</a></li>\n\t\t\t\t</ul>\n\n\t\t\t\t<p class="separator"> × × × </p>\n\t\t\t\t\n\t\t\t\t<h4>Supporters</h4>\n\t\t\t\t<ul>\n\t\t\t\t\t<li><a href="http://thepigeonhole.com.sg" name="supporter The Pigeonhole">The Pigeonhole</a></li>\n\t\t\t\t\t<li><a href="https://www.flickevents.com" name="supporter FlickEvents">FlickEvents</a></li>\n\t\t\t\t</ul>\n\t\t\t\t\n\t\t\t</div>\n\t\t\t<div class="contents" id="faq">\n\t\t\t\t<h3>F.A.Q.</h3>\n\t\t\t\t<p id="show_faq"><a href="javascript:showFAQ();">read faq</a></p>\n\t\t\t\t<dl id="faq_text">\n\t\t\t\t\t<dt>Can I come up with my own challenge?</dt>\n\t\t\t\t\t<dd>We are open to any kind of interesting topic so yes, please share your challenges. We do moderate topics to avoid inappropriate ones, but at the same time we want variety. So please share your challenges beforehand via mail or twitter or bring them with you to DestrActions. At the end it will be the people present choosing what challenge they pick.</dd>\n\t\t\t\t\t<dt>Who owns the designs made?</dt>\n\t\t\t\t\t<dd>Creativity is all about sharing but the creators shall be acclaimed. So it\u2019s only fair to make the results available as Creative Commons Attribution. What happens afterwards is up to people but we recommend that if you want to take things further you talk to the guys that were in your team. DestrActions is only a facilitator and shall not own any of the contents created.</dd>\n\t\t\t\t\t<dt>Can I work further on the things made at DestrActions?</dt>\n\t\t\t\t\t<dd>Yes, we hope you do find useful nuggets. If you find things useful, please give back to the community.</dd>\n\t\t\t\t\t<dt>Can I have people work on my commercial project?</dt>\n\t\t\t\t\t<dd>You can, if people are willing to choose your challenge. This might be a good way to find new talent for your team or bump you product further. No matter why you would want that, we recommend you to at least buy those guys a drink, it\u2019s only fair. ;)</dd>\n\t\t\t\t\t<dt>Can I have people work on my confidential project?</dt>\n\t\t\t\t\t<dd>As said before, the results of the session will be shared as Creative Commons Attribution, no two ways about it. This is about openness. But if your project has a part that presents an interesting challenge and that\u2019s not crucially confidential, why not crowd-source it?</dd>\n\t\t\t\t\t<dt>Why do you do this?</dt>\n\t\t\t\t\t<dd>We want to mingle and work other creative heads, it\u2019s liberating. We want to stimulate the design scene to share and cross trenches. We believe in openness and that inspiration often comes from fields outside your expertise. And who doesn\u2019t enjoy a nice challenge that distracts from dull routine?</dd>\n\t\t\t\t\t<dt>How about the money?</dt>\n\t\t\t\t\t<dd>This is or volunteer effort and we plan to not make any money or charge anything. However, as we don\u2019t know where this is headed, this is where we stand ideologically:<br />People who give shall receive, people who receive shall give; a community that shares fairly benefits everybody. Meaning, participation shall always be free besides that we encourage you to consume something at the venue. Submitting challenges shall be free unless you have a clear commercial intent with the challenge. Donations and/or free food and drinks are always welcome but shall not be the incentive.</dd>\n\t\t\t\t\t<dt>Can I use DestrActions to meet people and eventually hire them?</dt>\n\t\t\t\t\t<dd>Yes, use the sessions to get to know people and network. Give and take. :)</dd>\n\t\t\t\t\t<dt>Any more questions?</dt>\n\t\t\t\t\t<dd>Get in touch via <a href="http://twitter.com/#!/DActions" name="Link to DActions on Twitter">Twitter</a> or <a href="mailto:[email protected]" name="e-mail to DActions">email</a>.</dd>\n\t\t\t\t</dl>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n\t\n\t<div id="footer">\n\t\t<div class="contents_wrapper">\n\t\t\t<div class="contents">\n\t\t\t\t<p class="note">DestrActions is run by <a href="mailto:[email protected]">Wolfgang Maehr</a> from <a href="http://www.extrathought.com">Extra Thought</a> as an effort to connect designers and enable contacts and inspiration across the fields.</p>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n\t\n</body>\n</html>') return '' finally: context.caller_stack._pop_frame()
def test_markup_operations(self): # adding two strings should escape the unsafe one unsafe = '<script type="application/x-some-script">alert("foo");</script>' safe = Markup('<em>username</em>') assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe) # string interpolations are safe to use too assert Markup('<em>%s</em>') % '<bad user>' == \ '<em><bad user></em>' assert Markup('<em>%(username)s</em>') % { 'username': '******' } == '<em><bad user></em>' # an escaped object is markup too assert type(Markup('foo') + 'bar') is Markup # and it implements __html__ by returning itself x = Markup("foo") assert x.__html__() is x # it also knows how to treat __html__ objects class Foo(object): def __html__(self): return '<em>awesome</em>' def __unicode__(self): return 'awesome' assert Markup(Foo()) == '<em>awesome</em>' assert Markup('<strong>%s</strong>') % Foo() == \ '<strong><em>awesome</em></strong>' # escaping and unescaping assert escape('"<>&\'') == '"<>&'' assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar" assert Markup("<test>").unescape() == "<test>"
def test_validation_warnings(self, send_confirmation): applicant = factories.ApplicantFactory.create() self.set_form_session_data( counties=['sanfrancisco'], applicant_id=applicant.id) with self.assertLogs( 'project.services.logging_service', logging.INFO) as logs: response = self.client.fill_form( reverse(self.view_name), **mock.fake.sf_pubdef_answers(ssn='')) self.assertRedirects( response, reverse('intake-confirm'), fetch_redirect_response=False) response = self.client.get(response.url) self.assertContains(response, escape(WARNING_FLASH_MESSAGE)) self.assertContains( response, escape( fields.SocialSecurityNumberField.is_recommended_error_message)) send_confirmation.assert_not_called() assertInLogsCount( logs, { 'event_name=application_page_complete': 1, 'event_name=application_started': 0, 'event_name=application_submitted': 0, 'event_name=application_errors': 0, })
def index( self, trans, **kwd ): not_is_admin = not trans.user_is_admin() if not_is_admin and not trans.app.config.enable_data_manager_user_view: raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." ) message = escape( kwd.get( 'message', '' ) ) status = escape( kwd.get( 'status', 'info' ) ) return trans.fill_template( "data_manager/index.mako", data_managers=trans.app.data_managers, tool_data_tables=trans.app.tool_data_tables, view_only=not_is_admin, message=message, status=status )
def after_fork(self, node, fork, user, save=True): """ :param Node node: Original node :param Node fork: Forked node :param User user: User creating fork :param bool save: Save settings after callback :return tuple: Tuple of cloned settings and alert message """ clone, _ = super(AddonFigShareNodeSettings, self).after_fork( node, fork, user, save=False ) # Copy authentication if authenticated by forking user if self.user_settings and self.user_settings.owner == user: clone.user_settings = self.user_settings message = messages.AFTER_FORK_OWNER.format( category=markupsafe.escape(fork.project_or_component), ) else: message = messages.AFTER_FORK_NOT_OWNER.format( category=markupsafe.escape(fork.project_or_component), url=fork.url + 'settings/' ) return AddonFigShareNodeSettings(), message if save: clone.save() return clone, message
def after_remove_contributor(self, node, removed, auth=None): """ :param Node node: :param User removed: :return str: Alert message """ if self.user_settings and self.user_settings.owner == removed: # Delete OAuth tokens self.user_settings = None self.save() message = ( u'Because the GitLab add-on for {category} "{title}" was authenticated ' u'by {user}, authentication information has been deleted.' ).format( category=markupsafe.escape(node.category_display), title=markupsafe.escape(node.title), user=markupsafe.escape(removed.fullname) ) if not auth or auth.user != removed: url = node.web_url_for('node_setting') message += ( u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.' ).format(url=url) # return message
def test_serialize_metadata_file(self): file_record = model.OsfStorageFileRecord( path='kind/of/<strong>magic.mp3', node_settings=self.project.get_addon('osfstorage'), ) permissions = {'edit': False, 'view': True} serialized = utils.serialize_metadata_hgrid( file_record, self.project, permissions, ) assert_equal(serialized['addon'], 'osfstorage') assert_equal( serialized['path'], markupsafe.escape('kind/of/<strong>magic.mp3'), ) assert_equal( serialized['name'], markupsafe.escape('<strong>magic.mp3'), ) assert_equal(serialized['ext'], '.mp3') assert_equal(serialized['kind'], 'item') assert_equal( serialized['urls'], utils.build_hgrid_urls(file_record, self.project), ) assert_equal(serialized['permissions'], permissions)
def get_short_str(cls, pja): # Prevent renaming a dataset to the empty string. if pja.action_arguments and pja.action_arguments.get('newname', ''): return "Rename output '%s' to '%s'." % (escape(pja.output_name), escape(pja.action_arguments['newname'])) else: return "Rename action used without a new name specified. Output name will be unchanged."
def abbr(text, limit=60, tolerance=10): """Returns an abbreviated and HTML-escaped version of the specified text. The text is trimmed to the given length limit, but if a space is found within the preceeding 'tolerance' number of characters, then it is trimmed there. The result is an HTML span element with the full text as the title, unless it was not necessary to trim it. >>> abbr('alpha bravo', 15, 5) 'alpha bravo' >>> abbr('alpha bravo charlie', 15, 5) '<span title="alpha bravo charlie">alpha bravo…</span>' """ if len(text) > limit: space = text.rfind(' ', limit - tolerance, limit) if space == -1: shorttext = text[:limit] else: shorttext = text[:space] return ('<span title="' + str(markupsafe.escape(text)) + '">' + str(markupsafe.escape(shorttext)) + '…</span>') else: return str(markupsafe.escape(text))
def send_verification_email(self, trans, email, username): """ Send the verification email containing the activation link to the user's email. """ if username is None: username = trans.user.username activation_link = self.prepare_activation_link(trans, escape(email)) host = trans.request.host.split(':')[0] if host in ['localhost', '127.0.0.1', '0.0.0.0']: host = socket.getfqdn() body = ("Hello %s,\n\n" "In order to complete the activation process for %s begun on %s at %s, please click on the following link to verify your account:\n\n" "%s \n\n" "By clicking on the above link and opening a Galaxy account you are also confirming that you have read and agreed to Galaxy's Terms and Conditions for use of this service (%s). This includes a quota limit of one account per user. Attempts to subvert this limit by creating multiple accounts or through any other method may result in termination of all associated accounts and data.\n\n" "Please contact us if you need help with your account at: %s. You can also browse resources available at: %s. \n\n" "More about the Galaxy Project can be found at galaxyproject.org\n\n" "Your Galaxy Team" % (escape(username), escape(email), datetime.utcnow().strftime("%D"), trans.request.host, activation_link, trans.app.config.terms_url, trans.app.config.error_email_to, trans.app.config.instance_resource_url)) to = email frm = trans.app.config.email_from or 'galaxy-no-reply@' + host subject = 'Galaxy Account Activation' try: util.send_mail(frm, to, subject, body, trans.app.config) return True except Exception: log.exception('Unable to send the activation email.') return False
def view_job(self, trans, **kwd): not_is_admin = not trans.user_is_admin() if not_is_admin and not trans.app.config.enable_data_manager_user_view: raise paste.httpexceptions.HTTPUnauthorized("This Galaxy instance is not configured to allow non-admins to view the data manager.") message = escape(kwd.get('message', '')) status = escape(kwd.get('status', 'info')) job_id = kwd.get('id', None) try: job_id = trans.security.decode_id(job_id) job = trans.sa_session.query(trans.app.model.Job).get(job_id) except Exception as e: job = None log.error("Bad job id (%s) passed to view_job: %s" % (job_id, e)) if not job: return trans.response.send_redirect(web.url_for(controller="data_manager", action="index", message="Invalid job (%s) was requested" % job_id, status="error")) data_manager_id = job.data_manager_association.data_manager_id data_manager = trans.app.data_managers.get_manager(data_manager_id) hdas = [assoc.dataset for assoc in job.get_output_datasets()] data_manager_output = [] error_messages = [] for hda in hdas: try: data_manager_json = loads(open(hda.get_file_name()).read()) except Exception as e: data_manager_json = {} error_messages.append(escape("Unable to obtain data_table info for hda (%s): %s" % (hda.id, e))) values = [] for key, value in data_manager_json.get('data_tables', {}).items(): values.append((key, value)) data_manager_output.append(values) return trans.fill_template("data_manager/view_job.mako", data_manager=data_manager, job=job, view_only=not_is_admin, hdas=hdas, data_manager_output=data_manager_output, message=message, status=status, error_messages=error_messages)
def pre_validate(self, form): unique_used = set() uuid_used = set() coercions = {f['id']: f['coerce'] for f in self.fields if f.get('coerce') is not None} for i, item in enumerate(self.serialized_data): if not isinstance(item, dict): raise ValueError('Invalid item type: {}'.format(type(item).__name__)) item_keys = set(item) if self.uuid_field: item_keys.discard(self.uuid_field) if item_keys != {x['id'] for x in self.fields}: raise ValueError('Invalid item (bad keys): {}'.format(escape(', '.join(item.viewkeys())))) if self.unique_field: if item[self.unique_field] in unique_used: raise ValueError('{} must be unique'.format(self.field_names[self.unique_field])) unique_used.add(item[self.unique_field]) if self.uuid_field and not self.uuid_field_opaque: if item[self.uuid_field] in uuid_used: raise ValueError('UUID must be unique') # raises ValueError if uuid is invalid uuid.UUID(item[self.uuid_field], version=4) uuid_used.add(item[self.uuid_field]) for key, fn in coercions.viewitems(): try: self.data[i][key] = fn(self.data[i][key]) except ValueError: raise ValueError(u"Invalid value for field '{}': {}".format(self.field_names[key], escape(item[key])))
def after_remove_contributor(self, node, removed, auth=None): """If the removed contributor was the user who authorized the Dropbox addon, remove the auth credentials from this node. Return the message text that will be displayed to the user. """ if self.user_settings and self.user_settings.owner == removed: self.user_settings = None self.save() message = ( u'Because the Dropbox add-on for {category} "{title}" was authenticated ' u'by {user}, authentication information has been deleted.' ).format( category=markupsafe.escape(node.category_display), title=markupsafe.escape(node.title), user=markupsafe.escape(removed.fullname) ) if not auth or auth.user != removed: url = node.web_url_for('node_setting') message += ( u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.' ).format(url=url) # return message
def message_long(self): src_user = markupsafe.escape(self.user.username) dest_user = markupsafe.escape(self.user_to_merge.username) return language.MERGE_CONFIRMATION_REQUIRED_LONG.format( src_user=src_user, dest_user=dest_user, )
def after_fork(self, node, fork, user, save=True): """After forking, copy user settings if the user is the one who authorized the addon. :return: A tuple of the form (cloned_settings, message) """ clone, _ = super(DropboxNodeSettings, self).after_fork( node=node, fork=fork, user=user, save=False ) if self.user_settings and self.user_settings.owner == user: clone.user_settings = self.user_settings message = ( 'Dropbox authorization copied to forked {cat}.' ).format( cat=markupsafe.escape(fork.project_or_component) ) else: message = ( u'Dropbox authorization not copied to forked {cat}. You may ' u'authorize this fork on the <u><a href="{url}">Settings</a></u> ' u'page.' ).format( url=fork.web_url_for('node_setting'), cat=markupsafe.escape(fork.project_or_component) ) if save: clone.save() return clone, message
def after_fork(self, node, fork, user, save=True): """ :param Node node: Original node :param Node fork: Forked node :param User user: User creating fork :param bool save: Save settings after callback :return tuple: Tuple of cloned settings and alert message """ clone, _ = super(GitHubNodeSettings, self).after_fork( node, fork, user, save=False ) # Copy authentication if authenticated by forking user if self.user_settings and self.user_settings.owner == user: clone.user_settings = self.user_settings message = ( 'GitHub authorization copied to forked {cat}.' ).format( cat=markupsafe.escape(fork.project_or_component), ) else: message = ( 'GitHub authorization not copied to forked {cat}. You may ' 'authorize this fork on the <u><a href={url}>Settings</a></u> ' 'page.' ).format( cat=markupsafe.escape(fork.project_or_component), url=fork.url + 'settings/' ) if save: clone.save() return clone, message
def test_agency_user_can_only_see_latest_status_for_their_org(self, slack): user = self.be_apubdef_user() submission = self.combo_submissions[0] statuses = models.StatusUpdate.objects.filter( application__form_submission=submission) latest_status = statuses.filter( application__organization=user.profile.organization, ).latest('updated') latest_status_date = statuses.latest('updated').updated even_later = latest_status_date + timedelta(days=3) other_status = statuses.exclude( application__organization=user.profile.organization, ).first() other_status.updated = even_later other_status.save() response = self.get_page(submission) other_logged_by = 'logged by ' + other_status.author.profile.name other_status_name = other_status.status_type.display_name this_status_logged_by = \ 'logged by ' + latest_status.author.profile.name this_status_name = latest_status.status_type.display_name self.assertContains(response, escape(this_status_name)) self.assertContains(response, escape(this_status_logged_by)) self.assertNotContains(response, escape(other_logged_by)) if other_status_name not in this_status_name: self.assertNotContains(response, escape(other_status_name))
def new_client(): """ About block edit """ # if errors detected errors = [] # if form incoming if request.method == 'POST': if not request.form['title']: errors += ['Title required!'] if not errors: client = dict() client['title'] = unicode(escape(request.form['title'])) client['description'] = unicode(escape(request.form['description'])) client['logo'] = unicode(escape(request.form['logo'])) client['link'] = unicode(escape(request.form['link'])) client = Client(**client) try: db_session.add(client) db_session.commit() except exc.SQLAlchemyError: db_session.rollback() errors += ['Error creating client #{0}\n'.format(client.id)] return redirect(url_for('edit_client', client_id=client.id)) prop = dict() prop.update(default) prop['errors'] = errors return render_template('admin/new_client.html', **prop)
def after_remove_contributor(self, node, removed, auth=None): """If removed contributor authorized this addon, remove addon authorization from owner. """ if self.user_settings and self.user_settings.owner == removed: # Delete OAuth tokens self.user_settings.oauth_grants[self.owner._id].pop(self.external_account._id) self.clear_auth() message = ( u'Because the {addon} add-on for {category} "{title}" was authenticated ' u"by {user}, authentication information has been deleted." ).format( addon=self.config.full_name, category=markupsafe.escape(node.category_display), title=markupsafe.escape(node.title), user=markupsafe.escape(removed.fullname), ) if not auth or auth.user != removed: url = node.web_url_for("node_setting") message += (u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.').format( url=url ) # return message
def tools_and_job_state_per_month(self, trans, **kwd): """ fill tools_and_job_state_per_month.mako template with - the name of the tool - the number of jobs using this tool in state 'ok' - the number of jobs using this tool in error """ message = escape(util.restore_text(kwd.get('message', ''))) user_cutoff = int(kwd.get('user_cutoff', 60)) # sort by history space, or by user mail or by number of history/dataset # sort_by = kwd.get( 'sorting', 'Tool' ) # sorting = 0 if sort_by == 'Tool' else 1 if sort_by == 'ok' else 2 # descending = 1 if kwd.get( 'descending', 'desc' ) == 'desc' else -1 tool = kwd.get('tool', None) if tool is None: raise TypeError("Tool can't be None") data = collections.OrderedDict() # select count(id), create_time from job where state='ok' and tool_id=$tool group by date; date_and_jobs_ok = sa.select( (sa.func.date(galaxy.model.Job.table.c.create_time).label('date'), sa.func.count(galaxy.model.Job.table.c.id).label('job')), from_obj=[galaxy.model.Job.table], whereclause=and_(galaxy.model.Job.table.c.state == 'ok', galaxy.model.Job.table.c.tool_id == tool), group_by=['date']) # select count(id), create_time from job where state='error' and tool_id=$tool group by date; date_and_jobs_error = sa.select( (sa.func.date(galaxy.model.Job.table.c.create_time).label('date'), sa.func.count(galaxy.model.Job.table.c.id).label('job')), from_obj=[galaxy.model.Job.table], whereclause=and_(galaxy.model.Job.table.c.state == 'error', galaxy.model.Job.table.c.tool_id == tool), group_by=['date']) # sort_functions = (lambda first, second: descending if first.lower() > second.lower() else -descending, # lambda first, second: -descending if tools_and_jobs_ok.get( first, 0 ) > # tools_and_jobs_ok.get( second ) else descending, # lambda first, second: -descending if tools_and_jobs_error.get( first, 0 ) > # tools_and_jobs_error.get( second, 0 ) else descending) date_and_jobs_ok = dict(list(date_and_jobs_ok.execute())) date_and_jobs_error = dict(list(date_and_jobs_error.execute())) # select each date dates = list( set(date_and_jobs_ok.keys()) | set(date_and_jobs_error.keys())) dates.sort(reverse=True) for date in dates: date_key = date.strftime("%B %Y") if date_key not in data: data[date_key] = [ int(date_and_jobs_ok.get(date, 0)), int(date_and_jobs_error.get(date, 0)) ] else: data[date_key][0] += int(date_and_jobs_ok.get(date, 0)) data[date_key][1] += int(date_and_jobs_error.get(date, 0)) return trans.fill_template( '/webapps/reports/tools_and_job_state_per_month.mako', data=data, tool=tool, user_cutoff=user_cutoff, message=message)
def show_subpath(subpath): # show the sabbath after /path/ return 'Sabpath %s' % escape(subpath)
class DataManager(BaseUIController): @web.expose def index(self, trans, **kwd): not_is_admin = not trans.user_is_admin() if not_is_admin and not trans.app.config.enable_data_manager_user_view: raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." ) message = escape(kwd.get('message', '')) status = escape(kwd.get('status', 'info')) return trans.fill_template("data_manager/index.mako", data_managers=trans.app.data_managers, tool_data_tables=trans.app.tool_data_tables, view_only=not_is_admin, message=message, status=status) @web.expose def manage_data_manager(self, trans, **kwd): not_is_admin = not trans.user_is_admin() if not_is_admin and not trans.app.config.enable_data_manager_user_view: raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." ) message = escape(kwd.get('message', '')) status = escape(kwd.get('status', 'info')) data_manager_id = kwd.get('id', None) data_manager = trans.app.data_managers.get_manager(data_manager_id) if data_manager is None: return trans.response.send_redirect( web.url_for(controller="data_manager", action="index", message="Invalid Data Manager (%s) was requested" % data_manager_id, status="error")) jobs = list( reversed([ assoc.job for assoc in trans.sa_session.query( trans.app.model.DataManagerJobAssociation).filter_by( data_manager_id=data_manager_id) ])) return trans.fill_template("data_manager/manage_data_manager.mako", data_manager=data_manager, jobs=jobs, view_only=not_is_admin, message=message, status=status) @web.expose def view_job(self, trans, **kwd): not_is_admin = not trans.user_is_admin() if not_is_admin and not trans.app.config.enable_data_manager_user_view: raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." ) message = escape(kwd.get('message', '')) status = escape(kwd.get('status', 'info')) job_id = kwd.get('id', None) try: job_id = trans.security.decode_id(job_id) job = trans.sa_session.query(trans.app.model.Job).get(job_id) except Exception, e: job = None log.error("Bad job id (%s) passed to view_job: %s" % (job_id, e)) if not job: return trans.response.send_redirect( web.url_for(controller="data_manager", action="index", message="Invalid job (%s) was requested" % job_id, status="error")) data_manager_id = job.data_manager_association.data_manager_id data_manager = trans.app.data_managers.get_manager(data_manager_id) hdas = [assoc.dataset for assoc in job.get_output_datasets()] data_manager_output = [] error_messages = [] for hda in hdas: try: data_manager_json = loads(open(hda.get_file_name()).read()) except Exception, e: data_manager_json = {} error_messages.append( escape( "Unable to obtain data_table info for hda (%s): %s" % (hda.id, e))) values = [] for key, value in data_manager_json.get('data_tables', {}).iteritems(): values.append((key, value)) data_manager_output.append(values)
def resend_activation_email(self, trans, email, username): """ Function resends the verification email in case user wants to log in with an inactive account or he clicks the resend link. """ if email is None: # User is coming from outside registration form, load email from trans if not trans.user: return "No session found, cannot send activation email.", None email = trans.user.email if username is None: # User is coming from outside registration form, load email from trans username = trans.user.username is_activation_sent = self.user_manager.send_activation_email(trans, email, username) if is_activation_sent: message = 'This account has not been activated yet. The activation link has been sent again. Please check your email address <b>{}</b> including the spam/trash folder. <a target="_top" href="{}">Return to the home page</a>.'.format(escape(email), url_for('/')) else: message = 'This account has not been activated yet but we are unable to send the activation link. Please contact your local Galaxy administrator. <a target="_top" href="%s">Return to the home page</a>.' % url_for('/') if trans.app.config.error_email_to is not None: message += ' Error contact: %s.' % trans.app.config.error_email_to return message, is_activation_sent
def get_short_str(cls, pja): return "Set the datatype of output '%s' to '%s'" % (escape( pja.output_name), escape(pja.action_arguments['newtype']))
def slice_link(self) -> Markup: name = escape(self.chart) return Markup(f'<a href="{self.url}">{name}</a>')
def get_value(self, trans, grid, form): return escape(form.latest_form.desc)
def addon_view_or_download_file(auth, path, provider, **kwargs): extras = request.args.to_dict() extras.pop('_', None) # Clean up our url params a bit action = extras.get('action', 'view') node = kwargs.get('node') or kwargs['project'] node_addon = node.get_addon(provider) provider_safe = markupsafe.escape(provider) path_safe = markupsafe.escape(path) project_safe = markupsafe.escape(node.project_or_component) if not path: raise HTTPError(httplib.BAD_REQUEST) if not isinstance(node_addon, StorageAddonBase): raise HTTPError( httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'The {} add-on containing {} is no longer connected to {}.'. format(provider_safe, path_safe, project_safe) }) if not node_addon.has_auth: raise HTTPError( httplib.UNAUTHORIZED, data={ 'message_short': 'Unauthorized', 'message_long': 'The {} add-on containing {} is no longer authorized.'.format( provider_safe, path_safe) }) if not node_addon.complete: raise HTTPError( httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'The {} add-on containing {} is no longer configured.'.format( provider_safe, path_safe) }) file_node = FileNode.resolve_class(provider, FileNode.FILE).get_or_create( node, path) # Note: Cookie is provided for authentication to waterbutler # it is overriden to force authentication as the current user # the auth header is also pass to support basic auth version = file_node.touch( request.headers.get('Authorization'), **dict(extras, cookie=request.cookies.get(settings.COOKIE_NAME))) if version is None: return addon_deleted_file(file_node=file_node, path=path, **kwargs) # TODO clean up these urls and unify what is used as a version identifier if request.method == 'HEAD': return make_response(('', 200, { 'Location': file_node.generate_waterbutler_url( **dict(extras, direct=None, version=version.identifier)) })) if action == 'download': return redirect( file_node.generate_waterbutler_url( **dict(extras, direct=None, version=version.identifier))) if len(request.path.strip('/').split('/')) > 1: guid = file_node.get_guid(create=True) return redirect( furl.furl('/{}/'.format(guid._id)).set(args=extras).url) return addon_view_file(auth, node, file_node, version)
def addon_deleted_file(auth, node, error_type='BLAME_PROVIDER', **kwargs): """Shows a nice error message to users when they try to view a deleted file """ # Allow file_node to be passed in so other views can delegate to this one file_node = kwargs.get('file_node') or TrashedFileNode.load( kwargs.get('trashed_id')) deleted_by, deleted_on = None, None if isinstance(file_node, TrashedFileNode): deleted_by = file_node.deleted_by deleted_by_guid = file_node.deleted_by._id if deleted_by else None deleted_on = file_node.deleted_on.strftime('%c') + ' UTC' if file_node.suspended: error_type = 'FILE_SUSPENDED' elif file_node.deleted_by is None: if file_node.provider == 'osfstorage': error_type = 'FILE_GONE_ACTOR_UNKNOWN' else: error_type = 'BLAME_PROVIDER' else: error_type = 'FILE_GONE' else: error_type = 'DONT_KNOW' file_path = kwargs.get('path', file_node.path) file_name = file_node.name or os.path.basename(file_path) file_name_title, file_name_ext = os.path.splitext(file_name) provider_full = settings.ADDONS_AVAILABLE_DICT[ file_node.provider].full_name try: file_guid = file_node.get_guid()._id except AttributeError: file_guid = None format_params = dict(file_name=markupsafe.escape(file_name), deleted_by=markupsafe.escape(deleted_by), deleted_on=markupsafe.escape(deleted_on), provider=markupsafe.escape(provider_full)) if deleted_by: format_params['deleted_by_guid'] = markupsafe.escape(deleted_by_guid) ret = serialize_node(node, auth, primary=True) ret.update(rubeus.collect_addon_assets(node)) ret.update({ 'error': ERROR_MESSAGES[error_type].format(**format_params), 'urls': { 'render': None, 'sharejs': None, 'mfr': settings.MFR_SERVER_URL, 'gravatar': get_gravatar(auth.user, 25), 'files': node.web_url_for('collect_file_trees'), }, 'extra': {}, 'size': 9966699, # Prevent file from being edited, just in case 'sharejs_uuid': None, 'file_name': file_name, 'file_path': file_path, 'file_name_title': file_name_title, 'file_name_ext': file_name_ext, 'file_guid': file_guid, 'file_id': file_node._id, 'provider': file_node.provider, 'materialized_path': file_node.materialized_path or file_path, 'private': getattr(node.get_addon(file_node.provider), 'is_private', False), 'file_tags': [tag._id for tag in file_node.tags], 'allow_comments': file_node.provider in settings.ADDONS_COMMENTABLE, }) return ret, httplib.GONE
def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): """Load an instance of Model by primary key or query. Raise an appropriate HTTPError if no record is found or if the query fails to find a unique record :param type Model: StoredObject subclass to query :param pk_or_query: :type pk_or_query: either - a <basestring> representation of the record's primary key, e.g. 'abcdef' - a <QueryBase> subclass query to uniquely select a record, e.g. Q('title', 'eq', 'Entitled') & Q('version', 'eq', 1) :param bool allow_deleted: allow deleleted records? :param basestring display_name: :raises: HTTPError(404) if the record does not exist :raises: HTTPError(400) if no unique record is found :raises: HTTPError(410) if the resource is deleted and allow_deleted = False :return: Model instance """ display_name = display_name or '' # FIXME: Not everything that uses this decorator needs to be markupsafe, but OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name) select_for_update = check_select_for_update(request) if isinstance(pk_or_query, Q): try: instance = Model.objects.filter(pk_or_query).select_for_update( ).get() if select_for_update else Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError( http_status.HTTP_404_NOT_FOUND, data=dict(message_long= 'No {name} record matching that query could be found' .format(name=safe_name))) except Model.MultipleObjectsReturned: raise HTTPError( http_status.HTTP_400_BAD_REQUEST, data=dict( message_long= 'The query must match exactly one {name} record'.format( name=safe_name))) else: instance = Model.load(pk_or_query, select_for_update=select_for_update) if not instance: raise HTTPError( http_status.HTTP_404_NOT_FOUND, data=dict( message_long= 'No {name} record with that primary key could be found'. format(name=safe_name))) if getattr(instance, 'is_deleted', False) and getattr( instance, 'suspended', False): raise HTTPError( 451, data=dict( # 451 - Unavailable For Legal Reasons message_short='Content removed', message_long='This content has been removed')) if not allow_deleted and getattr(instance, 'is_deleted', False): raise HTTPError(http_status.HTTP_410_GONE) return instance
def get_short_str(cls, pja): return "Set the following metadata values:<br/>" + "<br/>".join( '%s : %s' % (escape(k), escape(v)) for k, v in pja.action_arguments.items())
def get_short_str(cls, pja): if pja.action_arguments and 'host' in pja.action_arguments: return "Email the current user from server %s when this job is complete." % escape( pja.action_arguments['host']) else: return "Email the current user when this job is complete."
def get_short_str(cls, pja): return "Hide output '%s'." % escape(pja.output_name)
def get_short_str(cls, pja): if pja.action_arguments: return "%s -> %s" % (pja.action_type, escape(pja.action_arguments)) else: return "%s" % pja.action_type
def info(cursor, cindex, settings): """Initialize a new warning popup.""" popup = Popup() popup.__popup_type = 'panel-info "ECC: Info"' type_decl = [ cindex.CursorKind.STRUCT_DECL, cindex.CursorKind.UNION_DECL, cindex.CursorKind.CLASS_DECL, cindex.CursorKind.ENUM_DECL, cindex.CursorKind.TYPEDEF_DECL, cindex.CursorKind.CLASS_TEMPLATE, cindex.CursorKind.TYPE_ALIAS_DECL, cindex.CursorKind.TYPE_REF ] # Initialize the text the declaration. declaration_text = '' # Show the return type of the function/method if applicable, # macros just show that they are a macro. macro_parser = None is_macro = cursor.kind == cindex.CursorKind.MACRO_DEFINITION is_type = cursor.kind in type_decl if is_macro: macro_parser = MacroParser(cursor.spelling, cursor.location) declaration_text += r'\#define ' else: if cursor.result_type.spelling: result_type = cursor.result_type elif cursor.type.spelling: result_type = cursor.type else: result_type = None log.warning("No spelling for type provided in info.") return "" if cursor.is_static_method(): declaration_text += "static " if cursor.spelling != cursor.type.spelling: # Don't show duplicates if the user focuses type, not variable declaration_text += Popup.link_from_location( Popup.location_from_type(result_type), result_type.spelling) # Link to declaration of item under cursor if cursor.location: declaration_text += Popup.link_from_location( cursor.location, cursor.spelling) else: declaration_text += cursor.spelling # Macro/function/method arguments args_string = None if is_macro: # cursor.get_arguments() doesn't give us anything for macros, # so we have to parse those ourselves args_string = macro_parser.args_string else: args = [] for arg in cursor.get_arguments(): arg_type_location = Popup.location_from_type(arg.type) arg_type_link = Popup.link_from_location( arg_type_location, arg.type.spelling) if arg.spelling: args.append(arg_type_link + arg.spelling) else: args.append(arg_type_link) if cursor.kind in [ cindex.CursorKind.FUNCTION_DECL, cindex.CursorKind.CXX_METHOD, cindex.CursorKind.CONSTRUCTOR, cindex.CursorKind.DESTRUCTOR, cindex.CursorKind.CONVERSION_FUNCTION, cindex.CursorKind.FUNCTION_TEMPLATE ]: args_string = '(' if len(args): args_string += ', '.join(args) args_string += ')' if args_string: declaration_text += args_string # Show value for enum if cursor.kind == cindex.CursorKind.ENUM_CONSTANT_DECL: declaration_text += " = " + str(cursor.enum_value) declaration_text += "(" + hex(cursor.enum_value) + ")" # Method modifiers if cursor.is_const_method(): declaration_text += " const" # Save declaration text. popup.__text = DECLARATION_TEMPLATE.format( type_declaration=markupsafe.escape(declaration_text)) # Doxygen comments if cursor.brief_comment: popup.__text += BRIEF_DOC_TEMPLATE.format( content=CODE_TEMPLATE.format(lang="", code=cursor.brief_comment)) if cursor.raw_comment: clean_comment = Popup.cleanup_comment(cursor.raw_comment).strip() print(clean_comment) if clean_comment: # Only add this if there is a Doxygen comment. popup.__text += FULL_DOC_TEMPLATE.format( content=CODE_TEMPLATE.format(lang="", code=clean_comment)) # Show macro body if is_macro: popup.__text += BODY_TEMPLATE.format(content=CODE_TEMPLATE.format( lang="c++", code=macro_parser.body_string)) # Show type declaration if settings.show_type_body and is_type and cursor.extent: body = Popup.get_text_by_extent(cursor.extent) body = Popup.prettify_body(body) popup.__text += BODY_TEMPLATE.format( content=CODE_TEMPLATE.format(lang="c++", code=body)) return popup
def __html__(self): return u'<div class="preformatted">{}</div>'.format( escape(unicode(self)))
def error(text): """Initialize a new error popup.""" popup = Popup() popup.__popup_type = 'panel-error "ECC: Error"' popup.__text = markupsafe.escape(text) return popup
def warning(text): """Initialize a new warning popup.""" popup = Popup() popup.__popup_type = 'panel-warning "ECC: Warning"' popup.__text = markupsafe.escape(text) return popup
def get_flash_messages(self): with self.client.session_transaction() as session: return tuple((category, escape(message)) for category, message in (session.get("_flashes") or ()))
def editor(self, trans, id=None, version=None): """ Render the main workflow editor interface. The canvas is embedded as an iframe (necessary for scrolling to work properly), which is rendered by `editor_canvas`. """ if not id: error("Invalid workflow id") stored = self.get_stored_workflow(trans, id) # The following query loads all user-owned workflows, # So that they can be copied or inserted in the workflow editor. workflows = trans.sa_session.query(model.StoredWorkflow) \ .filter_by(user=trans.user, deleted=False) \ .order_by(desc(model.StoredWorkflow.table.c.update_time)) \ .options(joinedload('latest_workflow').joinedload('steps')) \ .all() if version is None: version = len(stored.workflows) - 1 else: version = int(version) # create workflow module models module_sections = [] for section_name, module_section in load_module_sections(trans).items(): module_sections.append({ "title": module_section.get("title"), "name": module_section.get("name"), "elems": [{ "name": elem.get("name"), "title": elem.get("title"), "description": elem.get("description") } for elem in module_section.get("modules")] }) # create data manager tool models data_managers = [] if trans.user_is_admin and trans.app.data_managers.data_managers: for data_manager_id, data_manager_val in trans.app.data_managers.data_managers.items(): tool = data_manager_val.tool if not tool.hidden: data_managers.append({ "id": tool.id, "name": tool.name, "hidden": tool.hidden, "description": tool.description, "is_workflow_compatible": tool.is_workflow_compatible }) # create workflow models workflows = [{ 'id' : trans.security.encode_id(workflow.id), 'latest_id' : trans.security.encode_id(workflow.latest_workflow.id), 'step_count' : len(workflow.latest_workflow.steps), 'name' : workflow.name } for workflow in workflows if workflow.id != stored.id] # identify item tags item_tags = [tag for tag in stored.tags if tag.user == trans.user] item_tag_names = [] for ta in item_tags: item_tag_names.append(escape(ta.tag.name)) # build workflow editor model editor_config = { 'id' : trans.security.encode_id(stored.id), 'name' : stored.name, 'tags' : item_tag_names, 'version' : version, 'annotation' : self.get_item_annotation_str(trans.sa_session, trans.user, stored), 'toolbox' : trans.app.toolbox.to_dict(trans), 'moduleSections' : module_sections, 'dataManagers' : data_managers, 'workflows' : workflows } # parse to mako return trans.fill_template("workflow/editor.mako", editor_config=editor_config)
def test_no_counties_selected_returns_error(self): response = self.client.fill_form(reverse('intake-apply'), confirm_county_selection='yes') self.assertEqual(response.status_code, 200) self.assertContains(response, escape(fields.Counties.is_required_error_message))
def test_shows_error_messages_in_flash(self): response = self.client.fill_form(reverse('intake-apply'), confirm_county_selection='yes') self.assertContains(response, escape(fields.Counties.is_required_error_message))
def addon_view_or_download_file(auth, path, provider, **kwargs): extras = request.args.to_dict() extras.pop('_', None) # Clean up our url params a bit action = extras.get('action', 'view') guid = kwargs.get('guid') guid_target = getattr(Guid.load(guid), 'referent', None) target = guid_target or kwargs.get('node') or kwargs['project'] provider_safe = markupsafe.escape(provider) path_safe = markupsafe.escape(path) if not path: raise HTTPError(httplib.BAD_REQUEST) if hasattr(target, 'get_addon'): node_addon = target.get_addon(provider) if not isinstance(node_addon, BaseStorageAddon): object_text = markupsafe.escape( getattr(target, 'project_or_component', 'this object')) raise HTTPError( httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'The {} add-on containing {} is no longer connected to {}.' .format(provider_safe, path_safe, object_text) }) if not node_addon.has_auth: raise HTTPError( httplib.UNAUTHORIZED, data={ 'message_short': 'Unauthorized', 'message_long': 'The {} add-on containing {} is no longer authorized.'. format(provider_safe, path_safe) }) if not node_addon.complete: raise HTTPError( httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'The {} add-on containing {} is no longer configured.'. format(provider_safe, path_safe) }) savepoint_id = transaction.savepoint() file_node = BaseFileNode.resolve_class(provider, BaseFileNode.FILE).get_or_create( target, path) # Note: Cookie is provided for authentication to waterbutler # it is overriden to force authentication as the current user # the auth header is also pass to support basic auth version = file_node.touch( request.headers.get('Authorization'), **dict(extras, cookie=request.cookies.get(settings.COOKIE_NAME))) if version is None: # File is either deleted or unable to be found in the provider location # Rollback the insertion of the file_node transaction.savepoint_rollback(savepoint_id) if not file_node.pk: file_node = BaseFileNode.load(path) if file_node.kind == 'folder': raise HTTPError( httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'You cannot request a folder from this endpoint.' }) # Allow osfstorage to redirect if the deep url can be used to find a valid file_node if file_node and file_node.provider == 'osfstorage' and not file_node.is_deleted: return redirect( file_node.target.web_url_for('addon_view_or_download_file', path=file_node._id, provider=file_node.provider)) return addon_deleted_file(target=target, file_node=file_node, path=path, **kwargs) else: transaction.savepoint_commit(savepoint_id) # TODO clean up these urls and unify what is used as a version identifier if request.method == 'HEAD': return make_response(('', httplib.FOUND, { 'Location': file_node.generate_waterbutler_url( **dict(extras, direct=None, version=version.identifier, _internal=extras.get('mode') == 'render')) })) if action == 'download': format = extras.get('format') _, extension = os.path.splitext(file_node.name) # avoid rendering files with the same format type. if format and '.{}'.format(format.lower()) != extension.lower(): return redirect('{}/export?format={}&url={}'.format( get_mfr_url(target, provider), format, urllib.quote( file_node.generate_waterbutler_url( **dict(extras, direct=None, version=version.identifier, _internal=extras.get('mode') == 'render'))))) return redirect( file_node.generate_waterbutler_url( **dict(extras, direct=None, version=version.identifier, _internal=extras.get('mode') == 'render'))) if action == 'get_guid': draft_id = extras.get('draft') draft = DraftRegistration.load(draft_id) if draft is None or draft.is_approved: raise HTTPError(httplib.BAD_REQUEST, data={ 'message_short': 'Bad Request', 'message_long': 'File not associated with required object.' }) guid = file_node.get_guid(create=True) guid.referent.save() return dict(guid=guid._id) if len(request.path.strip('/').split('/')) > 1: guid = file_node.get_guid(create=True) return redirect( furl.furl('/{}/'.format(guid._id)).set(args=extras).url) if isinstance(target, Preprint): # Redirecting preprint file guids to the preprint detail page return redirect('/{}/'.format(target._id)) return addon_view_file(auth, target, file_node, version)
def test_escape_silent(self): assert escape_silent(None) == Markup() assert escape(None) == Markup(None) assert escape_silent('<foo>') == Markup(u'<foo>')
def dashboard_link(self) -> Markup: title = escape(self.dashboard_title or "<empty>") return Markup(f'<a href="{self.url}">{title}</a>')
def addon_deleted_file(auth, target, error_type='BLAME_PROVIDER', **kwargs): """Shows a nice error message to users when they try to view a deleted file """ # Allow file_node to be passed in so other views can delegate to this one file_node = kwargs.get('file_node') or TrashedFileNode.load( kwargs.get('trashed_id')) deleted_by, deleted_on = None, None if isinstance(file_node, TrashedFileNode): deleted_by = file_node.deleted_by deleted_by_guid = file_node.deleted_by._id if deleted_by else None deleted_on = file_node.deleted_on.strftime('%c') + ' UTC' if getattr(file_node, 'suspended', False): error_type = 'FILE_SUSPENDED' elif file_node.deleted_by is None or (auth.private_key and auth.private_link.anonymous): if file_node.provider == 'osfstorage': error_type = 'FILE_GONE_ACTOR_UNKNOWN' else: error_type = 'BLAME_PROVIDER' else: error_type = 'FILE_GONE' else: error_type = 'DONT_KNOW' file_path = kwargs.get('path', file_node.path) file_name = file_node.name or os.path.basename(file_path) file_name_title, file_name_ext = os.path.splitext(file_name) provider_full = settings.ADDONS_AVAILABLE_DICT[ file_node.provider].full_name try: file_guid = file_node.get_guid()._id except AttributeError: file_guid = None format_params = dict(file_name=markupsafe.escape(file_name), deleted_by=markupsafe.escape( getattr(deleted_by, 'fullname', None)), deleted_on=markupsafe.escape(deleted_on), provider=markupsafe.escape(provider_full)) if deleted_by: format_params['deleted_by_guid'] = markupsafe.escape(deleted_by_guid) error_msg = ERROR_MESSAGES[error_type].format(**format_params) if isinstance(target, AbstractNode): error_msg += format_last_known_metadata(auth, target, file_node, error_type) ret = serialize_node(target, auth, primary=True) ret.update(rubeus.collect_addon_assets(target)) ret.update({ 'error': error_msg, 'urls': { 'render': None, 'sharejs': None, 'mfr': get_mfr_url(target, file_node.provider), 'profile_image': get_profile_image_url(auth.user, 25), 'files': target.web_url_for('collect_file_trees'), }, 'extra': {}, 'size': 9966699, # Prevent file from being edited, just in case 'sharejs_uuid': None, 'file_name': file_name, 'file_path': file_path, 'file_name_title': file_name_title, 'file_name_ext': file_name_ext, 'target_deleted': getattr(target, 'is_deleted', False), 'version_id': None, 'file_guid': file_guid, 'file_id': file_node._id, 'provider': file_node.provider, 'materialized_path': file_node.materialized_path or file_path, 'private': getattr(target.get_addon(file_node.provider), 'is_private', False), 'file_tags': list( file_node.tags.filter(system=False).values_list( 'name', flat=True)) if not file_node._state.adding else [], # Only access ManyRelatedManager if saved 'allow_comments': file_node.provider in settings.ADDONS_COMMENTABLE, }) else: # TODO - serialize deleted metadata for future types of deleted file targets ret = {'error': error_msg} return ret, httplib.GONE
def show_user_profile(username): # show the user profile for that user return 'User %s' % escape(username)
def getMember(memberName): return ("Hello %s\n" % escape(memberName))
def format_errmsg(errmsg, *args): return Markup((errmsg % tuple("<i><b>%s</b></i>" % escape(x) for x in args)))
def assert_not_in_html(member, container, **kwargs): """Looks for the specified member in markupsafe-escaped HTML output""" member = markupsafe.escape(member) return assert_not_in(member, container, **kwargs)