def view_paste(paste, args, handler): pre = html_pre post = '' paste_content = read_paste(filename_path + '/' + paste) meta = read_meta(None, paste) if 'raw' in args: handler.set_header('Content-Type', 'text/plain; charset=utf-8') handler.write(paste_content) return elif 'mldown' in args: handler.write(format_mldown(paste_content)) return elif 'hl' in args or 'hl' in meta: try: hl = ('hl' in args and args['hl']) or meta['hl'] if 'ln' in args: paste_content = highlight_code(paste_content, hl, linenos_type) else: paste_content = highlight_code(paste_content, hl) except ClassNotFound as e: paste_content = escape(paste_content) pre += '<pre>' post += '</pre>' else: if 'ln' in args: paste_content = highlight_code(paste_content, 'text', linenos_type) else: paste_content = escape(paste_content) pre += '<pre>' post += '</pre>' post += html_post handler.content_type = 'text/html' handler.write(pre) handler.write(paste_content) handler.write(post)
def start_item(self): href = '<a href="/account/{guid}">{name}</a>'.format( guid=escape(self.account.guid), name=escape(self.account.name) ) if self.me: href = "<b>{}</b>".format(href) if self.n_children > 0: href = "{} ({})".format(href, len(self.account.children)) return '<li class="acountslist">{}'.format(href)
def view_paste(paste, args, handler): popup = '''<script> function myFunction() { var person = prompt("Please enter the secret password", ""); document.getElementById("myPastes").style.display = 'none'; if (person != null) { if (person != "biche") document.location.replace('http://www.dancourse.co.uk/wp-content/uploads/2015/07/nope.jpg'); } } myFunction(); </script> ''' pre = html_pre post = '' paste_content = read_paste(filename_path + '/' + paste) meta = read_meta(None, paste) if 'raw' in args: handler.set_header('Content-Type', 'text/plain; charset=utf-8') handler.write(paste_content) return elif 'mldown' in args: handler.write(format_mldown(paste_content)) return elif 'hl' in args or 'hl' in meta: try: hl = ('hl' in args and args['hl']) or meta['hl'] if 'ln' in args: paste_content = highlight_code(paste_content, hl, linenos_type) else: paste_content = highlight_code(paste_content, hl) except ClassNotFound as e: paste_content = escape(paste_content) pre += '<pre>' post += '</pre>' else: if 'ln' in args: paste_content = highlight_code(paste_content, 'text', linenos_type) else: paste_content = escape(paste_content) pre += '<pre>' post += '</pre>' post += html_post pre += popup handler.content_type = 'text/html' handler.write(pre) handler.write(paste_content) handler.write(post)
def get_body(self): """Get the XML body.""" return ( '<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">\n' # noqa ' <ows:Exception exceptionCode="%(name)s" locator="%(locator)s" >\n' ' %(description)s\n' ' </ows:Exception>\n' '</ows:ExceptionReport>' ) % { 'version': __version__, 'code': self.code, 'locator': escape(self.locator), 'name': escape(self.name), 'description': self.get_description() }
def post(self): col1 = escape(self.get_argument('col1')) col2 = escape(self.get_argument('col2')) col3 = escape(self.get_argument('col3')) col4 = escape(self.get_argument('col4')) col5 = escape(self.get_argument('col5')) if 'create' in self.request.uri: cmd = "INSERT INTO test VALUES (%s,%s,%s,%s,%s)" cur.execute(cmd, (col1, col2, col3, col4, col5)) else: cmd = "UPDATE test SET name=%s,ip=%s,platform=%s,hardware=%s WHERE id=%s" cur.execute(cmd, (col2, col3, col4, col5, col1)) con.commit() self.redirect('/')
def add_paste(user, content, comment, args, handler): if not valid_username(user): handler.write(html_invalid_user) return paste = basename(dump_paste(content, user)) options = paste meta = {'hl': '', 'comment': escape(comment)} if user: options = '%s/%s' % (user, options) if 'raw' in args: options = 'raw/' + options else: if 'ln' in args: options += '&ln' if 'mldown' in args: options += '&mldown' elif 'hl' in args: hl = args['hl'] meta['hl'] = hl elif 'ext' in args: hl = lang_from_ext(args['ext']) if hl != '': # options += '&hl=' + hl meta['hl'] = hl dump_meta(user, paste, meta) if 'script' in args: handler.set_header('Content-Type', 'text/plain; charset=utf-8') handler.write(options) return handler.redirect(base_url + options);
def add_paste(user, content, comment, args, handler): if not valid_username(user): handler.write(html_invalid_user) return paste = basename(dump_paste(content, user)) options = paste meta = {'hl': '', 'comment': escape(comment)} if user: options = '%s/%s' % (user, options) if 'raw' in args: options = 'raw/' + options else: if 'ln' in args: options += '&ln' if 'mldown' in args: options += '&mldown' elif 'hl' in args: hl = args['hl'] meta['hl'] = hl elif 'ext' in args: hl = lang_from_ext(args['ext']) if hl != '': # options += '&hl=' + hl meta['hl'] = hl dump_meta(user, paste, meta) if 'script' in args: handler.set_header('Content-Type', 'text/plain; charset=utf-8') handler.write(options) return handler.redirect(base_url + options)
def render(self): attrs = self.attrs.copy() attrs['name'] = self.name if self.value is not None: attrs['value'] = self.value html = attrs.pop('html', None) or escape(self.name) return '<button %s>%s</button>' % (attrs, html)
def render(self): attrs = self.attrs.copy() attrs['name'] = self.name x = '<select %s>\n' % attrs for arg in self.args: if isinstance(arg, (tuple, list)): value, desc= arg else: value, desc = arg, arg if self.value == value: select_p = ' selected="selected"' else: select_p = '' x += ' <option%s value="%s">%s</option>\n' % (select_p, escape(value), escape(desc)) x += '</select>\n' return x
def render_css(self): out = [] out.append(self.rendernote(self.note)) for i in self.inputs: if not i.is_hidden(): out.append('<label for="%s">%s</label>' % (i.id, escape(i.description))) out.append(i.pre) out.append(i.render()) out.append(self.rendernote(i.note)) out.append(i.post) out.append('\n') return ''.join(out)
def format_exception(self, exc: NoApplicableCode) -> None: """ Override Format exception as XML response """ if exc.description: description = f'<ows:ExceptionText>{escape(exc.description)}</ows:ExceptionText>' else: description = '' body = ( # noqa '<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">\n' ' <ows:Exception exceptionCode="%(name)s" locator="%(locator)s" >\n' ' %(description)s\n' ' </ows:Exception>\n' '</ows:ExceptionReport>') % { 'code': exc.code, 'locator': escape(exc.locator), 'name': escape(exc.name), 'description': description } self.write_xml(body)
def render(self): x = '<span>' for arg in self.args: if isinstance(arg, (tuple, list)): value, desc= arg else: value, desc = arg, arg attrs = self.attrs.copy() attrs['name'] = self.name attrs['type'] = 'radio' attrs['value'] = value if self.value == value: attrs['checked'] = 'checked' x += '<input %s/> %s' % (attrs, escape(desc)) x += '</span>' return x
def post(self): col1 = escape(self.get_argument('col1')) col2 = escape(self.get_argument('col2')) col3 = escape(self.get_argument('col3')) col4 = escape(self.get_argument('col4')) col5 = escape(self.get_argument('col5')) col6 = escape(self.get_argument('col6')) col7 = escape(self.get_argument('col7')) col8 = escape(self.get_argument('col8')) if 'create' in self.request.uri: cmd = "INSERT INTO gw VALUES (NULL ,%s,%s,%s,%s,%s,%s,%s)" cur.execute(cmd, (col2, col3, col4, col5, col6, col7, col8)) else: cmd = "UPDATE gw SET ip=%s,mac=%s,vlan=%s,hostname=%s,interface=%s ,int_desc=%s ,gateway=%s WHERE id=%s" cur.execute(cmd, (col2, col3, col4, col5, col6, col7, col8, col1)) con.commit() self.redirect('/')
def view_user(user, handler): user = escape(user) if not valid_username(user): raise tornado.web.HTTPError(404) pastes = pastes_for_user(user) body = '<h2>Pastes for %s</h2>' % user if pastes == []: body += '<p>No paste for this user</p>' else: body += '<ul>' for paste in pastes: meta = read_meta(user, paste) body += ('<li><a href="%s%s/%s">%s</a>' % (base_url, user, paste, paste)) if 'comment' in meta and meta['comment'] != '': body += ': %s' % meta['comment'].decode('utf-8') body += '</li>' body += '</ul>' handler.content_type = 'text/html' handler.write(html_pre) handler.write(body) handler.write(html_post)
def view_user(user, handler): user = escape(user) if not valid_username(user): raise tornado.web.HTTPError(404) pastes = pastes_for_user(user) body = '<h2>Pastes for %s</h2>' % user if pastes == []: body += '<p>No paste for this user</p>' else: body += '<ul>' for paste in pastes: meta = read_meta(user, paste) body += ('<li><a href="%s%s/%s">%s</a>' % (base_url, user, paste, paste)) if 'comment' in meta and meta['comment'] != '': body += ': %s' % meta['comment'] body += '</li>' body += '</ul>' handler.content_type = 'text/html' handler.write(html_pre) handler.write(body) handler.write(html_post)
def post(self): '''Create, auto-generate, modify, reassign and search URL redirects. Form submission based operations are performed, based on the 'action' parameter. All operations (except search) require auth. User is redirected to the login endpoint if request doesn't carry auth. ''' # Update in-memory stats counters stats = Stats() stats.update_stats('total_request_count') if self.request.protocol == 'http': self.redirect('https://' + self.request.host + self.request.uri) return self.check_xsrf_cookie() irs = self.application.settings['irs'] # Database shorturls = self.application.settings['shorturls'] # Collection shortname = self.get_body_argument('shortname', None) # Replace underscores in shortnames with hyphen. url = self.get_body_argument('url', None) action = self.get_body_argument('action', None) host_header_based_redirect = self.get_body_argument('hostbasedredirect', 'False') if host_header_based_redirect == 'True': host_header_based_redirect = True else: host_header_based_redirect = False username = self.get_current_user() # All operations except search require user login if not username and action != 'search': login_url = self.application.settings.get('login_url') redirect_url = login_url self.redirect(redirect_url) return log.info('Request from user %s.' % (username)) log.info('Request Body: %s' % self.request.body) if action == 'create': # We need a URL and shortname to work with! if not url or not shortname: log.info('Both URL and shortname are required! Got URL: %s and shortname: %s' % (url, shortname)) self.send_error(status_code=400) return # This standardizes short urls (to a degree) and enhances findability. shortname = shortname.replace('_', '-') # Check if the short name entry already exists redirect_entry = shorturls.find_one({'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect}) if redirect_entry: self.write('Shortcut <b>%s</b> already exists! Please edit the existing entry.' % (escape(shortname))) else: if shortname in RESERVED_URL_SHORTNAMES: log.info('Shortcut %s is on the blacklist %s. Refusing to create shortcut!' % (shortname, RESERVED_URL_SHORTNAMES)) self.send_error(status_code=400) return if host_header_based_redirect: log.info('Creating Host: header based redirect. Host: %s URL: %s' %(shortname, url)) parsed_url = urlparse.urlparse(url) if not parsed_url.scheme in ['http', 'https']: log.info('URL target is not a supported protocol.') self.send_error(status_code=400) return if parsed_url.netloc in self.application.settings['self_hostnames']: log.info('Target URL seems self referential. Could potentially generate a redirect loop.') self.send_error(status_code=400) return # Strip the target url of a trailing '/' (if any) so we don't # end up with redirects to urls ending in '//' #url = url.rstrip('/') url = url[:-1] if url.endswith('//') else url current_time = datetime.datetime.utcnow() shorturls.insert({ 'shortname': shortname, 'url': url, 'owner': username, 'group': None, 'host_header_based_redirect': host_header_based_redirect, 'created': current_time, 'modified': current_time, 'redirect_count': 0 }) # Update in-memory stats counters stats = Stats() stats.update_stats('shortname_count') stats.update_stats('distinct_owner_count', len(shorturls.distinct('owner')), reset=True) collstats = irs.command('collstats', 'shorturls') stats.update_stats('collection_size_bytes', collstats['size'], reset=True) log.info('Shortcut %s for %s created.' % (shortname, url)) self.write('Shortcut <b>%s</b> for URL <b>%s</b> created' % (escape(shortname), escape(url))) self.redirect('/_app/') return elif action == 'generate': # We need a URL to work with if not url: log.info('URL required! Got URL: %s' % (url)) self.send_error(status_code=400) return # Gotta love the ascii art! gibberish = ['_'] # Generate a random 7 character string sequence lower and upper case # chars and digits # We should be good for (62!)/(55!) short URLs. for _ in xrange(7): gibberish.append(random.choice(string.ascii_letters + string.digits)) shortname = ''.join(gibberish) if shorturls.find_one({'shortname': shortname}): self.write('Shortcut <b>%s</b> already exists! Please try again.' % shortname) else: if shortname in RESERVED_URL_SHORTNAMES: log.info('Shortcut %s is reserved: %s. Refusing to create shortcut!' % (shortname, RESERVED_URL_SHORTNAMES)) self.send_error(status_code=400) return parsed_url = urlparse.urlparse(url) if not parsed_url.scheme in ['http', 'https']: log.info('URL target is not a supported protocol.') self.send_error(status_code=400) return if parsed_url.netloc in self.application.settings['self_hostnames']: log.info('Target URL seems self referential. Could potentially generate a redirect loop.') self.send_error(status_code=400) return # Strip the target url of a trailing '/' (if any) so we don't # end up with redirects to urls ending in '//' #url = url.rstrip('/') url = url[:-1] if url.endswith('//') else url current_time = datetime.datetime.utcnow() shorturls.insert({ 'shortname': shortname, 'url': url, 'owner': username, 'group': None, 'host_header_based_redirect': False, 'created': current_time, 'modified': current_time, 'redirect_count': 0 }) log.info('Shortcut %s for %s created.' % (shortname, url)) # Update in-memory stats counters stats = Stats() stats.update_stats('shortname_count') stats.update_stats('distinct_owner_count', len(shorturls.distinct('owner')), reset=True) collstats = irs.command('collstats', 'shorturls') stats.update_stats('collection_size_bytes', collstats['size'], reset=True) self.write('Shortcut <b>%s</b> for URL <b>%s</b> created' % (escape(shortname), escape(url))) self.redirect('/_app/') return elif action == 'edit': # The shortname hidden form field and the url field is rendered escaped. # Need to unescape it now so database lookups with shortname as the key # works correctly. shortname = unescape(self.get_body_argument('shortname')) url = unescape(self.get_body_argument('url')) # We need a URL and shortname to work with if not url or not shortname: log.info('Both URL and shortname are required! Got URL: %s and shortname: %s' % (url, shortname)) self.send_error(status_code=400) return # Find the short name entry to edit redirect_entry = shorturls.find_one({'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect}) if not redirect_entry: self.write('Shortcut <b>%s</b> does not exist! Please create it first.' % (escape(shortname))) else: saved_url = redirect_entry.get('url', None) # Check authorization to modify the short name entry if username != redirect_entry['owner'] and username != self.application.settings['adminuser']: self.set_status(403) self.write('Shortcut <b>%s</b> is not owned by you! Please contact the owner %s.' % (escape(shortname), escape(redirect_entry['owner']))) return else: parsed_url = urlparse.urlparse(url) if not parsed_url.scheme in ['http', 'https']: log.info('URL target is not a supported protocol.') self.send_error(status_code=400) return if parsed_url.netloc in self.application.settings['self_hostnames']: log.info('Target URL seems self referential. Could potentially generate a redirect loop.') self.send_error(status_code=400) return # Strip the target url of a trailing '/' (if any) so we don't # end up with redirects to urls ending in '//' #url = url.rstrip('/') url = url[:-1] if url.endswith('//') else url current_time = datetime.datetime.utcnow() shorturls.update( { 'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect }, { '$set': {'url': url, 'modified': current_time} } ) # Update stats collstats = irs.command('collstats', 'shorturls') stats.update_stats('collection_size_bytes', collstats['size'], reset=True) log.info('Shortcut %s edited. Old URL: %s New URL: %s' % (shortname, saved_url, url)) self.write('Shortcut <b>%s</b> edited successfully.' % (escape(shortname))) self.redirect('/_app/') return elif action == 'search': regex = self.get_body_argument('regex', None) self.render('search.html', regex=regex, shorturls=shorturls, username=self.get_current_user()) elif action == 'delete': # The shortname hidden form field is rendered escaped. Unescape it. shortname = unescape(shortname) redirect_entry = shorturls.find_one({'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect}) if redirect_entry: saved_url = redirect_entry.get('url', None) # Check authorization to delete the short name entry if username != redirect_entry['owner'] and username != self.application.settings['adminuser']: self.set_status(403) self.write('Shortcut <b>%s</b> is not owned by you! Please contact the owner %s.' % (escape(shortname), escape(redirect_entry['owner']))) return shorturls.remove({'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect}) log.info('Shortcut %s for URL %s deleted.' % (shortname, saved_url)) # Update in-memory stats counters. Decrement here. stats = Stats() stats.update_stats('shortname_count', -1) stats.update_stats('distinct_owner_count', len(shorturls.distinct('owner')), reset=True) collstats = irs.command('collstats', 'shorturls') stats.update_stats('collection_size_bytes', collstats['size'], reset=True) self.write('Shortcut <b>%s</b> for URL <b>%s</b> deleted' % (escape(shortname), escape(saved_url))) self.redirect('/_app/') return else: self.write('Shortcut <b>%s</b> does not exist!' % (escape(shortname))) elif action == 'reassign': # The shortname hidden form field is rendered escaped. Unescape it. shortname = unescape(shortname) redirect_entry = shorturls.find_one({'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect}) newowner = self.get_body_argument('newowner', None) if username != redirect_entry['owner'] and username != self.application.settings['adminuser']: self.set_status(403) self.write('You cannot reassign shortcut <b>%s</b> not owned by you! Please contact the owner %s.' % (escape(shortname), escape(redirect_entry['owner']))) return else: # Should really check if the user exists in LDAP/AD. However # AD (by default) does not allow anonymous searches. For now just # make do with a basic regex check for valid userPrincipalName. if re.match(r'^[^@][email protected]$', newowner): current_time = datetime.datetime.utcnow() shorturls.update( { 'shortname': shortname, 'host_header_based_redirect': host_header_based_redirect }, { '$set': {'owner': newowner, 'modified': current_time} } ) stats.update_stats('distinct_owner_count', len(shorturls.distinct('owner')), reset=True) log.info('Ownership of short name %s re-assigned. From: %s -> %s' % (shortname, redirect_entry['owner'], newowner)) self.write('Ownership of short name %s re-assigned. From: %s -> %s' % (escape(shortname), escape(redirect_entry['owner']), escape(newowner))) self.redirect('/') return else: self.set_status(400) self.write('%s is not a valid user name. Should be [email protected]' % (escape(newowner))) return else: log.debug('Unrecognized action specified: shortname: %s url: %s action: %s' % (shortname, url, action)) self.send_error(status_code=400) return
def get(self): # Update in-memory stats counters stats = Stats() stats.update_stats('total_request_count') redirect_url = '/' shorturls = self.application.settings['shorturls'] path = self.request.path path_tokens = path.split('/') host_header_based_redirect = False host = self.request.headers.get('Host', None) if not host: # No Host: header in the request. Assume path based redirect. host_header_based_redirect = False elif host in self.application.settings['self_hostnames']: # Host: header is one of our own names. Assume path based redirect. host_header_based_redirect = False else: # Host: header based redirect. User followed a CNAME shortcut to us # to get here. host_header_based_redirect = True log.info('Host based redirect request for: %s' % (host)) if host_header_based_redirect: redirect_key = host # Short name must exist in the database AND must be Host: based redirect_entry = shorturls.find_one({'shortname': redirect_key, 'host_header_based_redirect': True}) log.info('Redirect entry: %s' % redirect_entry) else: # Normal URL path based lookup redirect_key = path_tokens[1] redirect_entry = shorturls.find_one({'shortname': redirect_key, 'host_header_based_redirect': False}) log.info('Redirect key: %s. Host based: %s' % (redirect_key, host_header_based_redirect)) # If key does not exist in the DB, redirect to / by default if redirect_entry: log.info('Redirect entry found for key: %s' % (redirect_key)) log.info(redirect_entry) url = redirect_entry.get('url', None) # Append path components from the incoming request to the redirect url. # Differs based on whether it is path or host header based redirect. if host_header_based_redirect: # Append the incoming path component in its entirety for host header based redirects redirect_url = url + self.request.uri else: if len(path_tokens) > 2: # E.g., '/abcd/efgh' # Skip the first request path component. redirect_url = url + '/'.join(path_tokens[2:]) if self.request.query: # Query component is present (e.g., /abcd/efgh?ijk=lmn) # Append query string from incoming uri redirect_url = redirect_url + '?' + self.request.query else: # Single path component (e.g., /abcd). First path component # is the key. Redirect to URL found in the DB. # Add query component if it exists. redirect_url = url if self.request.query: # Query component is present (e.g., /abcd?efg=hji) # Append query string from incoming uri. redirect_url = redirect_url + '?' + self.request.query if redirect_url and redirect_url != '/': # Update stats counter shorturls.update( { 'shortname': redirect_key, 'host_header_based_redirect': host_header_based_redirect }, { '$inc': {'redirect_count': 1} } ) # Update in-memory stats counters stats = Stats() stats.update_stats('redirect_count') log.info('Redirecting shortname %s to: %s' % (redirect_key, redirect_url)) # We could do a regular 302 redirect here, but that leaks the Referer # header to the target (same as a regular link on a page). # We have the opporunity to have this service scrub the Referer header so # internal URL namespace is not exposed while following external links. # We use the meta name=referrer tag to achieve referrer scrubbing. # Note: simply using <meta name=referrer content=never> with a regular # 302 redirect does not cut it. The browser simply ignores the 302 # response body. We need to do a <meta http-equiv=refresh ...> too (a.k.a. # client side redirect) for the browser to honor the referrer setting. scheme, netloc, path, params, query, fragment = urlparse.urlparse(redirect_url) if netloc.split(':')[0].endswith('.inmobi.com'): # Do 302 server side redirect. self.redirect(redirect_url) else: # Do client side redirect. self.write('<head><meta name="referrer" content="never"><meta http-equiv="refresh" content="0;url=%s"></head>' % escape(redirect_url)) return
def render(self, text, safe=False): if not safe: text = escape(text or "") return markdown.markdown(text or "-", output_format="html5")
def render(self, text, safe=False): text = text or '' if not safe: text = escape(text) return markdown.markdown(text, output_format='html5')
def post(self): cmd = "DELETE FROM test WHERE id=%s" col1 = escape(self.get_argument('col1')) cur.execute(cmd, (col1,)) con.commit() self.redirect('/')
def get_description(self): """Get the description.""" if self.description: return '''<ows:ExceptionText>%s</ows:ExceptionText>''' % escape(self.description) else: return ''
def __str__(self): return " ".join(['%s="%s"' % (k, escape(v)) for k, v in self.items()])
def work_link(ID): """Return an HTML link for the work designed by ID (using /serie/ for a serie, /movie/ for a movie and /episode/ for an episode)""" if ID[0] != '"': # Movie res = re.search('^(.+) \(([0-9]{4})[^\)]*\)', ID) if res: title = escape(res.group(1)) year = escape(res.group(2)) return ('<a href="/movie/%s">%s (%s)</a>' % (url_escape(ID), title, year)) else: return ('Invalid movie ID: %s' % escape(ID)) elif ID.find('{') != -1: # Episode res = re.search('^"(.+)" \(([0-9]{4})[^\)]*\) \{([^\(]*)(\(#([0-9]{1,3})\.([0-9]{1,3})\))?\}', ID) if res: title = escape(res.group(1)) year = escape(res.group(2)) epi_name = escape(res.group(3)) season = escape(res.group(5) or '') epi_num = escape(res.group(6) or '') return ('<a href="/episode/%s">%s (%s) %sx%s: %s</a>' % (url_escape(ID), title, year, season, epi_num, epi_name)) else: return ('Invalid episode ID: %s' % escape(ID)) else: # Serie res = re.search('"(.+)" \(([0-9]{4})[^\)]*\)', ID) if res: title = escape(res.group(1)) year = escape(res.group(2)) return ('<a href="/serie/%s">%s (%s)</a>' % (url_escape(ID), title, year)) else: return ('Invalid serie ID: %s' % escape(ID))
def rendernote(self, note): if note: return '<strong class="wrong">%s</strong>' % escape(note) else: return ""
def render(self): attrs = self.attrs.copy() attrs['name'] = self.name value = escape(self.value or '') return '<textarea %s>%s</textarea>' % (attrs, value)
def render(self): out = '' out += self.rendernote(self.note) out += '<table>\n' for i in self.inputs: html = i.pre + i.render() + self.rendernote(i.note) + i.post if i.is_hidden(): out += ' <tr style="display: none;"><th></th><td>%s</td></tr>\n' % (html) else: out += ' <tr><th><label for="%s">%s</label></th><td>%s</td></tr>\n' % (i.id, escape(i.description), html) out += "</table>" return out
def get(self): '''Host based redirect requests should be, well, redirected. If this is not a redirect request, send the user along to the /_app endpoint, where they probably wanted to go. ''' # Update in-memory stats counters stats = Stats().update_stats('total_request_count') host = self.request.host # Are we one of the hostnames we know ourselves by ? if not host in self.application.settings['self_hostnames']: # No. Assume it is a Host header based redirect request. log.info('Host based redirect request for: %s' % (host)) redirect_key = host # Short name must exist in the database AND must be Host: based redirect_entry = shorturls.find_one({'shortname': redirect_key, 'host_header_based_redirect': True}) if redirect_entry: log.info('Redirect entry found for key: %s' % (redirect_key)) log.info(redirect_entry) redirect_url = redirect_entry.get('url', None) if redirect_url: # Update stats counter first shorturls.update( { 'shortname': redirect_key, 'host_header_based_redirect': True }, { '$inc': {'redirect_count': 1} } ) # Update in-memory stats counters stats = Stats().update_stats('redirect_count') # Append the incoming request uri in its entirety to the entry found in the DB. redirect_url = redirect_url + self.request.uri scheme, netloc, path, params, query, fragment = urlparse.urlparse(redirect_url) if netloc.split(':')[0].endswith('.inmobi.com'): # Do 302 server side redirect. self.redirect(redirect_url) else: # Do client side redirect. self.write('<head><meta name="referrer" content="never"><meta http-equiv="refresh" content="0;url=%s"></head>' % escape(redirect_url)) return else: log.info('No redirect entry found for key: %s' % (redirect_key)) self.set_status(400) self.write('Host redirect for %s requested, but %s is not a valid short name<br>' % (escape(redirect_key), escape(redirect_key))) self.write('--Your friendly URL redirector service. Brought to you by: ') self.write('*****@*****.**') else: # Yes. One of the hostnames we know ourselves by. Send the user # to the app. Doing so for requests that come in with a valid but # shortened Host: header (e.g,, 'go') avoids cert errors. if re.match(r'^(go)(|\.corp\.inmobi\.com)$', self.request.host): self.redirect('%s%s%s' % ('https://', CANONICAL_HOST, '/_app/')) else: self.redirect('/_app/')