def flat(t, level): r = [] for x, y in sorted(t.iteritems(), key = lambda x: x[0]): tag, z = y # indent_s = level*"—" indent_s = " style=\"padding-left:"+str(30*level)+"pt\"" if "file"==tag: f = z r.append(""" <tr> <td"""+indent_s+"""><a href="""+"\""+urllib.pathname2url("/"+f.path)+"\""+""">"""+escape_html(x)+"""</a></td> <td>"""+str(f.size)+"""</td> </tr> """) elif "dir"==tag: r.append(""" <tr><td colspan=\"2\""""+indent_s+""">"""+escape_html(x)+"""</td></tr> """) r.append(flat(z, level+1)) else: pass return "".join(r)
def send_diff_by_email(cfg, module, revision, log, diff): logger = logging.getLogger(module) subscribers = cfg.get(MAIN_CONFIG_SECTION, OPT_SUBSCRIBERS) if cfg.has_option(module, OPT_SUBSCRIBERS): subscribers = cfg.get(module, OPT_SUBSCRIBERS) # create message context = { "revision": revision, "author": log.author_name, "timestamp": log.timestamp, "message": escape_html(log.message), "diff": escape_html(diff), "files": diffparser.get_files(diff, cfg.get(module, OPT_REPO)) } msg_str = template.render(open(TEMPLATE_FILE, 'r').read(), context) # create email message from_domain = cfg.get(MAIN_CONFIG_SECTION, OPT_FROM_DOMAIN) from_addr = "%s@%s" % (log.author, from_domain) msg = MIMEText(msg_str, "html") msg['Subject'] = "[svn-diff for %s, r%d] %s" % (module, revision, log.message) msg['From'] = from_addr msg['To'] = subscribers # connect to SMTP server and send message smtp_server = cfg.get(MAIN_CONFIG_SECTION, OPT_SMTPSERVER) logger.info("Sending mail to %s through %s from %s" , subscribers, smtp_server, from_addr) s = smtplib.SMTP(smtp_server) #s.connect() s.sendmail(from_addr, subscribers.split(','), msg.as_string(False)) s.close()
def flat(t, level): r = [] for x, y in sorted(t.iteritems(), key=lambda x: x[0]): tag, z = y # indent_s = level*"—" indent_s = " style=\"padding-left:" + str(30 * level) + "pt\"" if "file" == tag: f = z r.append(""" <tr> <td""" + indent_s + """><a href=""" + "\"" + urllib.pathname2url("/" + f.path) + "\"" + """>""" + escape_html(x) + """</a></td> <td>""" + str(f.size) + """</td> </tr> """) elif "dir" == tag: r.append(""" <tr><td colspan=\"2\"""" + indent_s + """>""" + escape_html(x) + """</td></tr> """) r.append(flat(z, level + 1)) else: pass return "".join(r)
def block_code(self, text, lang): if not lang: return '\n<pre><code>%s</code></pre>\n' % \ escape_html(text.strip()) lexer = get_lexer_by_name(lang, stripall=True) formatter = HtmlFormatter() return pygments.highlight(text, lexer, formatter)
def run_creation(options): global epp if epp is None: epp = ClientSession() epp.load_config() epp.set_auto_connect(0) # set OFF auto connection command_name, epp_doc, stop = epp.create_eppdoc(options['command']) errors = epp.fetch_errors() if not epp_doc and not errors: errors = '%s %s' % (_T('Unknown command'), command_name.encode(encoding)) str_error = '' if errors: if type(command_name) == unicode: command_name = command_name.encode(encoding) if type(errors) == unicode: errors = errors.encode(encoding) if options['output'] == 'html': str_error = '<div class="fred_errors">\n<strong>%s errors:</strong>\n<pre>\n%s</pre><div>' % ( command_name, escape_html(errors)) elif options['output'] == 'php': str_error = '<?php\n$fred_error_create_name = %s;\n$fred_error_create_value = %s;\n%s\n?>' % ( php_string(command_name), php_string(errors), epp.get_empty_php_code()) elif options['output'] == 'xml': str_error = "<?xml version='1.0' encoding='%s'?>\n<errors>\n\t<error>%s</error>\n</errors>" % ( encoding, errors) else: # default 'text' str_error = "%s: %s" % (_T('ERROR'), errors) return epp_doc, str_error
def write_html(self, s): return """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>"""+escape_html(self.torrent_info.name())+"""</title> </head> <body> """+s+"""
def write_html(self, s): return """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>""" + escape_html(self.torrent_info.name()) + """</title> </head> <body> """ + s + """
def parse_pad_text(doc): text_url = doc.xpath(xpath_txtfile)[0].get("thref") text_url = text_url.replace("%revision%", parse_pad_revision(doc)) text_url = urljoin(doc.docinfo.URL, text_url) with closing(urllib2.urlopen(text_url)) as response: lines = escape_html(response.read().decode("utf-8")).split(u"\n") return u"<br />".join(lines)
def generate_index(self): display_name = escape_html(self.dir_name if self.dir_name else "/") html = StringIO() html.write(self.header % locals()) # If this is a subdirectory, create a link back to the parent. if self.dir_name: parent_dirname = ("/" + self.dir_name).rsplit("/", 1)[0] html.write(self.parent_backlink % locals()) for subdir_name, subdir in sorted(iteritems(self.subdirs)): subdir_link = escape_html(url_quote( self.dir_name + "/" + subdir_name if self.dir_name else subdir_name)) subdir_name = escape_html(subdir_name) html.write(self.subdir_link % locals()) for filename, key in sorted(iteritems(self.contents)): ext = splitext(filename)[-1] icon_name = self.icons.get(ext, "binary.png") suffix_type = self.suffix_types.get(ext, " ") file_link = escape_html(url_quote(key.name)) filename = escape_html(filename) last_modified = escape_html(key.last_modified) size = str(key.size) description = "" html.write(self.file_link % locals()) html.write(self.footer % locals()) return html.getvalue()
def manage_exception(): # Print the backtrace info = traceback.format_exc() #print(info, file=sys.stderr) # Custom error management if error.page: try: page = error.page(info, desc) response = HTTP_Response(error=500, body=page.Render()) self.send(str(response)) return except Exception as e: print("!!!!!!", e) pass # No error handling page html = '<pre>%s</pre>' % (escape_html(info)) self.send(str(HTTP_Error(desc=html)))
def handle_request (self): def manage_exception(): # Print the backtrace info = traceback.format_exc() print >> sys.stderr, info # Custom error management if error.page: try: page = error.page (info, desc) response = HTTP_Response (error=500, body=page.Render()) self.send (str(response)) return except Exception, e: print "!!!!!!", e pass # No error handling page html = '<pre>%s</pre>' %(escape_html(info)) self.send (str(HTTP_Error(desc=html)))
def squeeze_text_into_box(canvas, text, x0, y0, x1, y1, units=inch, style=default_style, escape=True): if escape: text = escape_html(text).replace('\n', '<br/>') frame = Frame(x0 * units, y0 * units, (x1 - x0) * units, (y1 - y0) * units, leftPadding=2, rightPadding=2, topPadding=0, bottomPadding=4, showBoundary=0) current_style = style current_size = style.fontSize while True: story = [Paragraph(text, current_style)] frame.addFromList(story, canvas) if len(story) == 0: break # Story empty, so all text was successfully flowed into frame if current_size > 6: current_size -= 1 elif current_size > 3: current_size -= 0.5 elif current_size > 1: current_size -= 0.1 else: raise Exception("Could not squeeze text into box, even with a font size of 1 point.") current_style = ParagraphStyle("temp_style", parent=style, fontSize=current_size, leading=current_size)
def run_creation(options): global epp command_name, errors, epp_doc = "", "", None if epp is None: epp = ClientSession() epp.load_config() if epp._conf.has_option("creator", "server_disclose_policy"): server_disclose_policy = epp._conf.get("creator", "server_disclose_policy") if server_disclose_policy not in ("0", "1"): errors = "The variable 'server_disclose_policy' in config section [creator] has an unexpected value.\n" else: epp._epp_cmd.server_disclose_policy = int( server_disclose_policy) if not errors: epp.set_auto_connect(0) # set OFF auto connection command_name, epp_doc, stop = epp.create_eppdoc(options['command']) errors = epp.fetch_errors() if not epp_doc and not errors: errors = '%s %s' % (_T('Unknown command'), command_name.encode(encoding)) str_error = '' if errors: if type(command_name) == unicode: command_name = command_name.encode(encoding) if type(errors) == unicode: errors = errors.encode(encoding) if options['output'] == 'html': str_error = '<div class="fred_errors">\n<strong>%s errors:</strong>\n<pre>\n%s</pre><div>' % ( command_name, escape_html(errors)) elif options['output'] == 'php': str_error = '<?php\n$fred_error_create_name = %s;\n$fred_error_create_value = %s;\n%s\n?>' % ( php_string(command_name), php_string(errors), epp.get_empty_php_code()) elif options['output'] == 'xml': str_error = "<?xml version='1.0' encoding='%s'?>\n<errors>\n\t<error>%s</error>\n</errors>" % ( encoding, errors) else: # default 'text' str_error = "%s: %s" % (_T('ERROR'), errors) return epp_doc, str_error
def squeeze_text_into_box(canvas, text, x0, y0, x1, y1, units=inch, style=default_style, escape=True): if escape: text = escape_html(text).replace('\n', '<br/>') frame = Frame(x0 * units, y0 * units, (x1 - x0) * units, (y1 - y0) * units, leftPadding=2, rightPadding=2, topPadding=0, bottomPadding=4, showBoundary=0) current_style = style current_size = style.fontSize while True: story = [Paragraph(text, current_style)] frame.addFromList(story, canvas) if len(story) == 0: break # Story empty, so all text was successfully flowed into frame if current_size > 6: current_size -= 1 elif current_size > 3: current_size -= 0.5 elif current_size > 1: current_size -= 0.1 else: raise Exception( "Could not squeeze text into box, even with a font size of 1 point." ) current_style = ParagraphStyle("temp_style", parent=style, fontSize=current_size, leading=current_size)
def run_creation(options): global epp if epp is None: epp = ClientSession() epp.load_config() epp.set_auto_connect(0) # set OFF auto connection command_name, epp_doc, stop = epp.create_eppdoc(options["command"]) errors = epp.fetch_errors() if not epp_doc and not errors: errors = "%s %s" % (_T("Unknown command"), command_name.encode(encoding)) str_error = "" if errors: if type(command_name) == unicode: command_name = command_name.encode(encoding) if type(errors) == unicode: errors = errors.encode(encoding) if options["output"] == "html": str_error = '<div class="fred_errors">\n<strong>%s errors:</strong>\n<pre>\n%s</pre><div>' % ( command_name, escape_html(errors), ) elif options["output"] == "php": str_error = "<?php\n$fred_error_create_name = %s;\n$fred_error_create_value = %s;\n%s\n?>" % ( php_string(command_name), php_string(errors), epp.get_empty_php_code(), ) elif options["output"] == "xml": str_error = "<?xml version='1.0' encoding='%s'?>\n<errors>\n\t<error>%s</error>\n</errors>" % ( encoding, errors, ) else: # default 'text' str_error = "%s: %s" % (_T("ERROR"), errors) return epp_doc, str_error
def __init__(self, line, type = TYPE_UNMODIFIED): self.line = escape_html(line) self.type = type
def write_html_index(self, piece_par): t = {} error = [] size = 0 for f in self.torrent_info.files(): if f.size > size: size = f.size path = urllib.pathname2url("/" + f.path) print path, size return """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>""" + escape_html(self.torrent_info.name()) + """</title> </head> <body> </body> <script>window.location = "http://peer.local:8080/stream/http%3A//0.0.0.0%3A8000""" + path + """"</script> </html> """ for f in self.torrent_info.files(): t0 = t level = 0 xs = split_path_list(f.path) level_n = len(xs) for x in reversed(xs): key_found = x in t0 if level + 1 >= level_n: if key_found: error.append("duplicate file: " + f.path) else: t0[x] = ("file", f) else: if key_found: tag, t1 = t0[x] if not (tag == "dir"): error.append("file and directory: " + f.path) break t0 = t1 else: t1 = {} t0[x] = ("dir", t1) t0 = t1 level += 1 def flat(t, level): r = [] for x, y in sorted(t.iteritems(), key=lambda x: x[0]): tag, z = y # indent_s = level*"—" indent_s = " style=\"padding-left:" + str(30 * level) + "pt\"" if "file" == tag: f = z r.append(""" <tr> <td""" + indent_s + """><a href=""" + "\"" + urllib.pathname2url("/" + f.path) + "\"" + """>""" + escape_html(x) + """</a></td> <td>""" + str(f.size) + """</td> </tr> """) elif "dir" == tag: r.append(""" <tr><td colspan=\"2\"""" + indent_s + """>""" + escape_html(x) + """</td></tr> """) r.append(flat(z, level + 1)) else: pass return "".join(r) file_tree_s = flat(t, 0) error2s = lambda x: "<li>" + escape_html(x) + "</li>" if 0 == len(error): error_s = "" else: error_s = "<p>error:</p><ol>" + "".join(map(error2s, error)) + "</ol>" return self.write_html( """<p><form method=\"get\" action=\"/\"><strong>piece_par:</strong> """ + str(piece_par) + """ <input type=\"text\" name=\"piece_par\" value=\"""" + str(piece_par) + """\" maxlength="6" size="8" /> <input type=\"submit\" value=\"change\" /></form></p> <h1>torrent parameters</h1> <p><strong>name:</strong> """ + escape_html(self.torrent_info.name()) + """</p> <p><strong>comment:</strong></p> <p>""" + escape_html(self.torrent_info.comment()) + """</p> <p><strong>size:</strong> """ + str(self.torrent_info.total_size()) + """</p> <p><strong>piece length in bytes:</strong> """ + str(self.torrent_info.piece_length()) + """</p> <table> <tr> <th>file</th> <th>size</th> </tr> """ + file_tree_s + """</table>""" + error_s)
def write_html_index(self, piece_par): t = {} error = [] size=0 for f in self.torrent_info.files(): if f.size > size: size=f.size path=urllib.pathname2url("/"+f.path) print path,size return """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>"""+escape_html(self.torrent_info.name())+"""</title> </head> <body> </body> <script>window.location = "http://peer.local:8080/stream/http%3A//0.0.0.0%3A8000"""+path+ """"</script> </html> """ for f in self.torrent_info.files(): t0 = t level = 0 xs = split_path_list(f.path) level_n = len(xs) for x in reversed(xs): key_found = x in t0 if level+1 >= level_n: if key_found: error.append("duplicate file: "+f.path) else: t0[x] = ("file", f) else: if key_found: tag, t1 = t0[x] if not (tag == "dir"): error.append("file and directory: "+f.path) break t0 = t1 else: t1 = {} t0[x] = ("dir", t1) t0 = t1 level += 1 def flat(t, level): r = [] for x, y in sorted(t.iteritems(), key = lambda x: x[0]): tag, z = y # indent_s = level*"—" indent_s = " style=\"padding-left:"+str(30*level)+"pt\"" if "file"==tag: f = z r.append(""" <tr> <td"""+indent_s+"""><a href="""+"\""+urllib.pathname2url("/"+f.path)+"\""+""">"""+escape_html(x)+"""</a></td> <td>"""+str(f.size)+"""</td> </tr> """) elif "dir"==tag: r.append(""" <tr><td colspan=\"2\""""+indent_s+""">"""+escape_html(x)+"""</td></tr> """) r.append(flat(z, level+1)) else: pass return "".join(r) file_tree_s = flat(t, 0) error2s = lambda x: "<li>"+escape_html(x)+"</li>" if 0==len(error): error_s = "" else: error_s = "<p>error:</p><ol>"+"".join(map(error2s, error))+"</ol>" return self.write_html("""<p><form method=\"get\" action=\"/\"><strong>piece_par:</strong> """+str(piece_par)+""" <input type=\"text\" name=\"piece_par\" value=\""""+str(piece_par)+"""\" maxlength="6" size="8" /> <input type=\"submit\" value=\"change\" /></form></p> <h1>torrent parameters</h1> <p><strong>name:</strong> """+escape_html(self.torrent_info.name())+"""</p> <p><strong>comment:</strong></p> <p>"""+escape_html(self.torrent_info.comment())+"""</p> <p><strong>size:</strong> """+str(self.torrent_info.total_size())+"""</p> <p><strong>piece length in bytes:</strong> """+str(self.torrent_info.piece_length())+"""</p> <table> <tr> <th>file</th> <th>size</th> </tr> """+file_tree_s+"""</table>"""+error_s)
def load_buffer(buf): load_html((escape_html(line) + eol for line in buf))
def get_messages(self, sep="\n"): """Same as display but returns as local string. In xml output mode collect only errors. """ # TODO: log file msg = [] is_php = self._session[OUTPUT_TYPE] == "php" is_xml = self._session[OUTPUT_TYPE] == "xml" is_html = self._session[OUTPUT_TYPE] == "html" xml_close_tag = 0 if is_xml: if self.is_note() or self.is_error() or self._notes_afrer_errors: msg.append('<?xml version="1.0" encoding="%s"?>' % translate.encoding) msg.append("<FredClient>") xml_close_tag = 1 if self.is_note(): # report, note, values if is_xml: msg.append("<notes>") elif is_html: msg.append('<div class="notes">') for text in self._notes: if is_php: msg.append("$fred_client_notes[] = %s;" % php_string(text)) elif is_xml: msg.append("\t<note>%s</note>" % strip_colors(text)) elif is_html: msg.append(escape_html(strip_colors(text))) else: msg.append(get_ltext(colored_output.render(text))) if is_xml: msg.append("</notes>") elif is_html: msg.append("</div>") self._notes = [] if self.is_error(): # error messages if is_xml: msg.append("<errors>") elif is_html: msg.append('<div class="errors">') if is_php: msg.append("$fred_client_errors[] = %s;" % php_string(self._errors[0])) elif is_xml: msg.append("\t<error>%s</error>" % strip_colors(self._errors[0])) elif is_html: msg.append(escape_html(strip_colors(self._errors[0]))) else: if len(msg) and msg[-1] != "": msg.append("") self._errors[-1] += colored_output.render("${NORMAL}") label = _T("ERROR") msg.append("%s%s: %s" % (colored_output.render("${RED}${BOLD}"), label, self._errors[0])) for text in self._errors[1:]: if is_php: msg.append("$fred_client_errors[] = %s;" % php_string(text)) elif is_xml: msg.append("\t<error>%s</error>" % strip_colors(text)) elif is_html: msg.append(escape_html(strip_colors(text))) else: msg.append(get_ltext(text)) if is_xml: msg.append("</errors>") elif is_html: msg.append("</div>") self._errors = [] if len(self._notes_afrer_errors): if is_xml: msg.append("<remarks>") elif is_html: msg.append('<div class="remark">') if is_php: msg.extend(map(lambda s: "$fred_client_notes[] = %s;" % php_string(s), self._notes_afrer_errors)) elif is_xml: msg.extend(map(lambda s: "\t<remark>%s</remark>" % strip_colors(s), self._notes_afrer_errors)) elif is_html: msg.extend(map(lambda s: escape_html(strip_colors(s)), self._notes_afrer_errors)) else: msg.extend(map(get_ltext, self._notes_afrer_errors)) self._notes_afrer_errors = [] if is_xml: msg.append("</remarks>") elif is_html: msg.append("</div>") if xml_close_tag: msg.append("</FredClient>") return sep.join(map(get_ltext, msg))
def get_answer_html(self, dct=None): """Returns data in HTML format. Used syles: CSS: .fred_client - main div of HTML output .fred_code - div part of message (code + reason) .fred_errors - ul li with errors .fred_data - table with data .fred_source - pre with XML sources .command_success - reason with code 1000 .command_done - other readons .even - every even row in data table """ body=[] report = body.append if not dct: dct = self._dct_answer #... code and reason ............................. code = dct['code'] reason_css_class = code==1000 and 'command_success' or 'command_done' if self._session[VERBOSE] > 0: if code != 1000: # full tbl_reason=['<table class="fred_data">'] tbl_reason.append('<tr>\n\t<th>%s</th>\n\t<td>%d</td>\n</tr>'%(_T('Return code'),code)) #tbl_reason.append('<tr>\n\t<th>command</th>\n\t<td>%s</td>\n</tr>'%get_ltext(dct['command'])) tbl_reason.append('<tr>\n\t<th>%s</th>\n\t<td><span class="%s">%s</span></td>\n</tr>'%(_T('Reason'), reason_css_class,get_ltext(dct['reason']))) tbl_reason.append('</table>') report('\n'.join(tbl_reason)) #... errors ............................. if len(dct['errors']): report('<div class="fred_errors">\n<strong>errors:</strong><ul>') for error in dct['errors']: report('<li>%s</li>'%get_ltext(error)) report('</ul></div>') #... data ............................. is_check = re.match('\w+:check',dct['command']) and 1 or 0 # object:check data_indent = '' data = [] dct_data = dct['data'] self.reduce_info_status(dct['command'], dct_data) # join status key and description together is_list = dct['command'] == 'fred:getresults' or self._loop_status == LOOP_INSIDE for key,verbose,explain in self.__get_column_items__(dct['command'], dct_data): if verbose > self._session[VERBOSE]: continue key = key.strip() # client normaly trim whitespaces, but if you use sender, you can send everything... value = dct_data.get(key,u'') if value not in ('',[]): if is_check: # Tighten check response by code. value = dct_data.get(key+':reason',u'') __append_into_report__(data, key, value, explain, self._ljust, '', 2, # 2 - use HTML pattern; is_list) if len(data): if self._loop_status == LOOP_NONE or self._loop_status == LOOP_FIRST_STEP: report('<table class="fred_data">') body.extend(data) if self._loop_status == LOOP_NONE or self._loop_status == LOOP_LAST_STEP: report('</table>') elif self._loop_status == LOOP_LAST_STEP: report('</table>') # encode to 8bit local for n in range(len(body)): if type(body[n]) == unicode: body[n] = body[n].encode(encoding) else: # Zero verbose level report(escape_html(human_readable(self._raw_answer))) #... third verbose level ............................. if self._session[VERBOSE] == 3 and self._loop_status == LOOP_NONE: report('<pre class="fred_source">') report('<strong>COMMAND:</strong>') report(escape_html(human_readable(self._raw_cmd))) report('<strong>ANSWER:</strong>') report(escape_html(human_readable(self._raw_answer))) report('</pre>') # .............. return '\n'.join(body)
def generate_graph(filenames, filter_invalid=True, restrict_keys=None, prog='neato'): ctx = gpgme.Context() ctx.keylist_mode = gpgme.KEYLIST_MODE_SIGS if restrict_keys is None: keys = ctx.keylist() else: keys = ctx.keylist(restrict_keys) key_list = [] for key in keys: try: subkey = key.subkeys[0] except IndexError: continue if filter_invalid and (subkey.expired or subkey.revoked): continue key_list.append(key) graph_dict = build_signature_graph(key_list) cliques = _find_max_cliques(graph_dict) signature_stats = _build_signature_stats(graph_dict) # Calculate labels and unconnected nodes labels = {} unconnected_nodes = [] for key in key_list: keyid = key.subkeys[0].keyid name = key.uids[0].name labels[keyid] = '<{0}<BR/><FONT POINT-SIZE="10">{1}</FONT>>'.format( escape_html(name), keyid) not_connected = (signature_stats['sigcount'][keyid] == 0 and signature_stats['signedbycount'][keyid] == 0) if not_connected: unconnected_nodes.append(keyid) # Map keyids to their cliques clique_map = {} for clique_no, clique in enumerate(cliques): for keyid in clique: clique_map.setdefault(keyid, []).append(clique_no) # Start building the graph flipped_edges = set() g = pygraphviz.AGraph(directed=True, overlap='scale', splines=True, nodesep=0.2, outputMode='edgesfirst') g.node_attr['style'] = 'filled' for keyid in graph_dict: red, green, blue = _get_color(signature_stats, keyid) luminance = 0.299 * red + 0.587 * green + 0.114 * blue attrs = { 'id': keyid, 'label': labels[keyid], 'fillcolor': _hex_color(red, green, blue), 'fontcolor': '#eeeeee' if luminance < 0.55 else '#000000' } if keyid in clique_map: clique_no = clique_map[keyid][0] color = MAX_CLIQUE_COLORS[clique_no % len(MAX_CLIQUE_COLORS)] attrs['penwidth'] = 2 attrs['color'] = color g.add_node(keyid, **attrs) # Add edges for signatures for signed_keyid, signer_keyids in list(graph_dict.items()): for signer_keyid in signer_keyids: if (signer_keyid, signed_keyid) in flipped_edges: continue edge_id = '{0}_{1}'.format(signer_keyid, signed_keyid) both_signed = signed_keyid in graph_dict[signer_keyid] direction = 'both' if both_signed else 'forward' attrs = {'id': edge_id, 'dir': direction} same_clique = -1 if signer_keyid in clique_map and signed_keyid in clique_map: for clique_a in clique_map[signer_keyid]: for clique_b in clique_map[signed_keyid]: if clique_a == clique_b: same_clique = clique_a if same_clique != -1: color = MAX_CLIQUE_COLORS[same_clique % len(MAX_CLIQUE_COLORS)] attrs['penwidth'] = 2 attrs['color'] = color g.add_edge(signer_keyid, signed_keyid, **attrs) if both_signed: flipped_edges.add((signed_keyid, signer_keyid)) # Draw invisible edges around unconnected nodes for better styling if prog == 'dot': for keyid_a, keyid_b in zip(unconnected_nodes, unconnected_nodes[1:]): g.add_edge(keyid_a, keyid_b, style='invis') g.layout(prog) for filename in filenames: g.draw(filename) if filename.endswith('.svg'): _annotate_svg(filename)
def get_messages(self, sep='\n'): """Same as display but returns as local string. In xml output mode collect only errors. """ #TODO: log file msg = [] is_php = self._session[OUTPUT_TYPE] == 'php' is_xml = self._session[OUTPUT_TYPE] == 'xml' is_html = self._session[OUTPUT_TYPE] == 'html' xml_close_tag = 0 if is_xml: if self.is_note() or self.is_error() or self._notes_afrer_errors: msg.append('<?xml version="1.0" encoding="%s"?>'%translate.encoding) msg.append('<FredClient>') xml_close_tag = 1 if self.is_note(): # report, note, values if is_xml: msg.append('<notes>') elif is_html: msg.append('<div class="notes">') for text in self._notes: if is_php: msg.append('$fred_client_notes[] = %s;'%php_string(text)) elif is_xml: msg.append('\t<note>%s</note>'%strip_colors(text)) elif is_html: msg.append(escape_html(strip_colors(text))) else: msg.append(get_ltext(colored_output.render(text))) if is_xml: msg.append('</notes>') elif is_html: msg.append('</div>') self._notes = [] if self.is_error(): # error messages if is_xml: msg.append('<errors>') elif is_html: msg.append('<div class="errors">') if is_php: msg.append('$fred_client_errors[] = %s;'%php_string(self._errors[0])) elif is_xml: msg.append('\t<error>%s</error>'%strip_colors(self._errors[0])) elif is_html: msg.append(escape_html(strip_colors(self._errors[0]))) else: if len(msg) and msg[-1] != '': msg.append('') self._errors[-1] += colored_output.render('${NORMAL}') label = _T('ERROR') msg.append('%s%s: %s'%(colored_output.render('${RED}${BOLD}'),label, self._errors[0])) for text in self._errors[1:]: if is_php: msg.append('$fred_client_errors[] = %s;'%php_string(text)) elif is_xml: msg.append('\t<error>%s</error>'%strip_colors(text)) elif is_html: msg.append(escape_html(strip_colors(text))) else: msg.append(get_ltext(text)) if is_xml: msg.append('</errors>') elif is_html: msg.append('</div>') self._errors = [] if len(self._notes_afrer_errors): if is_xml: msg.append('<remarks>') elif is_html: msg.append('<div class="remark">') if is_php: msg.extend(map(lambda s: '$fred_client_notes[] = %s;'%php_string(s), self._notes_afrer_errors)) elif is_xml: msg.extend(map(lambda s: '\t<remark>%s</remark>'%strip_colors(s), self._notes_afrer_errors)) elif is_html: msg.extend(map(lambda s: escape_html(strip_colors(s)), self._notes_afrer_errors)) else: msg.extend(map(get_ltext, self._notes_afrer_errors)) self._notes_afrer_errors = [] if is_xml: msg.append('</remarks>') elif is_html: msg.append('</div>') if xml_close_tag: msg.append('</FredClient>') return sep.join(map(get_ltext, msg))
def blockcode(self, text, lang=''): if not lang: return "\n<pre><code>%s</code></pre>\n" % escape_html(text) lexer = get_lexer_by_name(lang, stripall=True) formatter = HtmlFormatter() return highlight(text, lexer, formatter)
def generate_graph(filenames, filter_invalid=True, restrict_keys=None, prog='neato'): ctx = gpgme.Context() ctx.keylist_mode = gpgme.KEYLIST_MODE_SIGS if restrict_keys is None: keys = ctx.keylist() else: keys = ctx.keylist(restrict_keys) key_list = [] for key in keys: try: subkey = key.subkeys[0] except IndexError: continue if filter_invalid and (subkey.expired or subkey.revoked): continue key_list.append(key) graph_dict = build_signature_graph(key_list) cliques = _find_max_cliques(graph_dict) signature_stats = _build_signature_stats(graph_dict) # Calculate labels and unconnected nodes labels = {} unconnected_nodes = [] for key in key_list: keyid = key.subkeys[0].keyid name = key.uids[0].name labels[keyid] = '<{0}<BR/><FONT POINT-SIZE="10">{1}</FONT>>'.format( escape_html(name), keyid) not_connected = (signature_stats['sigcount'][keyid] == 0 and signature_stats['signedbycount'][keyid] == 0) if not_connected: unconnected_nodes.append(keyid) # Map keyids to their cliques clique_map = {} for clique_no, clique in enumerate(cliques): for keyid in clique: clique_map.setdefault(keyid, []).append(clique_no) # Start building the graph flipped_edges = set() g = pygraphviz.AGraph(directed=True, overlap='scale', splines=True, nodesep=0.2, outputMode='edgesfirst') g.node_attr['style']='filled' for keyid in graph_dict: red, green, blue = _get_color(signature_stats, keyid) luminance = 0.299 * red + 0.587 * green + 0.114 * blue attrs = { 'id': keyid, 'label': labels[keyid], 'fillcolor': _hex_color(red, green, blue), 'fontcolor': '#eeeeee' if luminance < 0.55 else '#000000' } if keyid in clique_map: clique_no = clique_map[keyid][0] color = MAX_CLIQUE_COLORS[clique_no % len(MAX_CLIQUE_COLORS)] attrs['penwidth'] = 2 attrs['color'] = color g.add_node(keyid, **attrs) # Add edges for signatures for signed_keyid, signer_keyids in list(graph_dict.items()): for signer_keyid in signer_keyids: if (signer_keyid, signed_keyid) in flipped_edges: continue edge_id = '{0}_{1}'.format(signer_keyid, signed_keyid) both_signed = signed_keyid in graph_dict[signer_keyid] direction = 'both' if both_signed else 'forward' attrs = { 'id': edge_id, 'dir': direction } same_clique = -1 if signer_keyid in clique_map and signed_keyid in clique_map: for clique_a in clique_map[signer_keyid]: for clique_b in clique_map[signed_keyid]: if clique_a == clique_b: same_clique = clique_a if same_clique != -1: color = MAX_CLIQUE_COLORS[same_clique % len(MAX_CLIQUE_COLORS)] attrs['penwidth'] = 2 attrs['color'] = color g.add_edge(signer_keyid, signed_keyid, **attrs) if both_signed: flipped_edges.add((signed_keyid, signer_keyid)) # Draw invisible edges around unconnected nodes for better styling if prog == 'dot': for keyid_a, keyid_b in zip(unconnected_nodes, unconnected_nodes[1:]): g.add_edge(keyid_a, keyid_b, style='invis') g.layout(prog) for filename in filenames: g.draw(filename) if filename.endswith('.svg'): _annotate_svg(filename)
def get_answer_html(self, dct=None): """Returns data in HTML format. Used syles: CSS: .fred_client - main div of HTML output .fred_code - div part of message (code + reason) .fred_errors - ul li with errors .fred_data - table with data .fred_source - pre with XML sources .command_success - reason with code 1000 .command_done - other readons .even - every even row in data table """ body = [] report = body.append if not dct: dct = self._dct_answer #... code and reason ............................. code = dct['code'] reason_css_class = code == 1000 and 'command_success' or 'command_done' if self._session[VERBOSE] > 0: if code != 1000: # full tbl_reason = ['<table class="fred_data">'] tbl_reason.append('<tr>\n\t<th>%s</th>\n\t<td>%d</td>\n</tr>' % (_T('Return code'), code)) #tbl_reason.append('<tr>\n\t<th>command</th>\n\t<td>%s</td>\n</tr>'%get_ltext(dct['command'])) tbl_reason.append( '<tr>\n\t<th>%s</th>\n\t<td><span class="%s">%s</span></td>\n</tr>' % (_T('Reason'), reason_css_class, get_ltext(dct['reason']))) tbl_reason.append('</table>') report('\n'.join(tbl_reason)) #... errors ............................. if len(dct['errors']): report( '<div class="fred_errors">\n<strong>errors:</strong><ul>') for error in dct['errors']: report('<li>%s</li>' % get_ltext(error)) report('</ul></div>') #... data ............................. is_check = re.match('\w+:check', dct['command']) and 1 or 0 # object:check data_indent = '' data = [] dct_data = dct['data'] self.reduce_info_status( dct['command'], dct_data) # join status key and description together is_list = dct[ 'command'] == 'fred:getresults' or self._loop_status == LOOP_INSIDE for key, verbose, explain in self.__get_column_items__( dct['command'], dct_data): if verbose > self._session[VERBOSE]: continue key = key.strip( ) # client normaly trim whitespaces, but if you use sender, you can send everything... value = dct_data.get(key, u'') if value not in ('', []): if is_check: # Tighten check response by code. value = dct_data.get(key + ':reason', u'') __append_into_report__( data, key, value, explain, self._ljust, '', 2, # 2 - use HTML pattern; is_list) if len(data): if self._loop_status == LOOP_NONE or self._loop_status == LOOP_FIRST_STEP: report('<table class="fred_data">') body.extend(data) if self._loop_status == LOOP_NONE or self._loop_status == LOOP_LAST_STEP: report('</table>') elif self._loop_status == LOOP_LAST_STEP: report('</table>') # encode to 8bit local for n in range(len(body)): if type(body[n]) == unicode: body[n] = body[n].encode(encoding) else: # Zero verbose level report(escape_html(human_readable(self._raw_answer))) #... third verbose level ............................. if self._session[VERBOSE] == 3 and self._loop_status == LOOP_NONE: report('<pre class="fred_source">') report('<strong>COMMAND:</strong>') report(escape_html(human_readable(self._raw_cmd))) report('<strong>ANSWER:</strong>') report(escape_html(human_readable(self._raw_answer))) report('</pre>') # .............. return '\n'.join(body)
def escape_context(self, context): for escape_field in self.escape_list: context[escape_field] = escape_html( context[escape_field]) if context[escape_field] else "" return context