def attempt_login(cursor): username, password = "", "" # Try to get it from CGI, failing that try cookies # Don't try to get it from CGI if it's mode=edit_user if common_f.get_val('mode',"") != "edit_user": username = common_f.get_val('username', "") password = common_f.get_val('password', "") from_cookie = False # Cookies method if username == "" and password == "": username = html_f.get_cookie('profiteer_username', "") password = html_f.get_cookie('profiteer_password', "") from_cookie = True # Still nothing? if username == "" and password == "": if os.environ.get('REMOTE_ADDR') == "::1" or os.environ.get('REMOTE_ADDR') == None: u = common_q.get_one(cursor, User, id=1) common_f.cache['user'] = u return u return "" response = get_user(cursor, username, password, from_cookie) if type(response) == User: html_f.set_cookie("profiteer_username", username) html_f.set_cookie("profiteer_password", response.password) return response
def main(cursor, error_id=-1): error_id = int(common_f.get_val("error", error_id)) sub_mode = common_f.get_val("sub_mode", "form") if sub_mode == "fix": return fix(cursor, error_id) if sub_mode == "delete": return delete(cursor, error_id) the_error = common_q.get_one(cursor, error.Error, id=error_id) the_user = common_q.get_one(cursor, user.User, id=the_error.user_id) output = [] http_args = the_error.args.replace("\n\n", "\n").replace(" ", "") http_args = "&".join(http_args.split("\n")) http_args = http_args.replace("mode=", "emulate_mode=") output.append( """ <div style="padding:10px;"> <span style="float:right;padding-right:20px;"> <a href="web.py?mode=edit_error&sub_mode=delete&error={error_id}">Delete</a> </span> <a href="web.py?mode=emulate_user&{http_args}&user_id={user_id}">Emulate</a> <br><br> <strong>Time:</strong> {timestamp} <strong>User:</strong> {user} <strong>Mode:</strong> <a href="web.py?mode=list_errors&filter={mode}">{mode}</a> <br> <strong>Data:</strong><br> <textarea rows="8" style="width:99%;">{args}</textarea> </div> <br> <div style="padding:0px;border-top:1px solid #AAA;"> {traceback} </div> """.format( error_id=int(error_id), user_id=the_user.id, user=the_user.username if the_user != None else "Not logged in", mode=the_error.mode, args=the_error.args, http_args=http_args, timestamp=common_f.display_date(the_error.timestamp, "%d of %B at %H:%M"), traceback=the_error.traceback, ) ) return "".join(output)
def login_form(message, username=""): if message == "Incorrect password" and username == "": username = common_f.get_val('username', "") return """ <form action="web.py?mode=login" method="post" accept-charset="utf-8" style="text-align:center;"> <br /> {message} <br /> <br /><br /> <div style="border:1px solid #AAA; width:250px; margin: 0 auto;"> <table border="0" cellspacing="5" cellpadding="5" style="margin: 0 auto;"> <tr> <td><label for="username">Username:</label></td> <td><input type="text" name="username" id="username" value="{username}" /></td> </tr> <tr> <td><label for="password">Password:</label></td> <td><input type="password" name="password" id="password" value="" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Login" /> </td> </tr> </table> </div> </form> {onload}""".format( onload = html_f.onload % "$('#username').focus();", message = '<div class="error">%s</div>' % message if message != "" else "", username = username, )
def _func(cursor, *args, **kwargs): response = attempt_login(cursor) # If it's a string they've failed to login if type(response) == str: return login_form(response) # They are logged in, now we need to make sure they have the privilages if response.has_privileges(*privileges) != []: if response.root: return no_access(missing=response.has_privileges(*privileges)) return no_access() # Try to get the page itself try: page_result = f(cursor, *args, **kwargs) except Exception as e: if common_f.cache['user'].root or False: print(error.html_render()) exit() else: return error.log_error(cursor, e, context=0) # Try logging the usage, if not we'll quietly log the error try: if config.get("log_usage") and common_f.get_val("ajax", False) == False: user_log.log_usage(cursor) except Exception as e: error.log_error(cursor, e) return page_result
def import_page(page_name, handle_exception=True): """This is the main firing function of the admin GUI, it loads the page that we'll be using.""" if page_name not in page_dict: the_page = html_f.HTTP404(page_name) else: try: path = page_dict[page_name][0], [page_dict[page_name][1], sys.path[0] + "/" + page_dict[page_name][1]] find = imp.find_module(*path) the_page = imp.load_module("the_page", *find) find[0].close() except Exception: try: find[0].close() except Exception: pass if not handle_exception: raise print(error.html_render(context=1, headers=True)) print("<br /><br />Found mode: {}<br />".format(common_f.get_val("mode", "none"))) print("Used mode: {}<br />".format(page_name)) print("Page dict: {}<br />".format(str(page_dict[page_name]))) print("Used path: {}<br />".format(path)) exit() return the_page
def test_cgi_form_functions(self): self.test_targets.append(common_f.get_val) self.test_targets.append(common_f.print_post_data) gui_test_utils.new_cgi_form(( ("a", 1), ("b", 2), ("c", 3), )) self.assertEqual(common_f.get_val("a"), 1) self.assertEqual(common_f.get_val("b"), 2) self.assertEqual(common_f.get_val("c"), 3) self.assertEqual(common_f.print_post_data(joiner="\n"), """a = 1 b = 2 c = 3""")
def main(cursor, message=""): username = common_f.get_val('username', '') password = common_f.get_val('password', '') # No details, show the login default page if username == "" or password == "": return """<script type="text/javascript" charset="utf-8"> setTimeout("document.location='web.py';"); </script>""" response = user.attempt_login(cursor) if type(response) != str and response != None: return """<script type="text/javascript" charset="utf-8"> setTimeout("document.location='web.py';"); </script>""" return user.login_form(response, username=username)
def log_error(cursor, e, context=5, function_call=""): error_output = html_render(sys.exc_info(), context=5, headers=False) # It might be they're not logged in if "user" in common_f.cache and common_f.cache['user'] != None: user_id = common_f.cache['user'].id else: user_id = -1 exception_type = str(sys.exc_info()[0]).replace("<class '", "").replace("'>", "") # We log the error here the_error = Error( args = common_f.print_post_data(joiner="\n\n"), user_id = user_id, mode = common_f.get_val("mode", pages.default_page), function_call = function_call, exception_type = exception_type, traceback = error_output, ) error_logged = True try: the_error.insert(cursor) except Exception as e: if context != 0: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), the_error.insert(test_mode=True))) else: error_logged = False # Display an output here if context == 0: # No context means it's a user we don't want seeing the stack trace cgi_form = cgi.FieldStorage() return """<br><div class="error"> There has been an error. {error_logged} </div> <div style="padding:10px"> Below is a copy of all the data you submitted. <br> <hr> <br> {cgi_form} </div> """.format( cgi_form = "<br><br>".join([str(http_data.value) for http_data in cgi_form.list]), error_logged = "The error has been logged automatically." if error_logged else "The error could not be logged" ) # No limit to context, this means we can print the stack trace return ("Content-type: text/html; charset=utf-8" + "\n" + error_output)
def main(cursor): table_name = common_f.get_val("table", "") field_name = common_f.get_val("field", "") where = common_f.get_val("where", "") print_query = common_f.get_val("p", False) query = """SELECT {field} FROM {table} WHERE {where}""".format( table = table_name, field = field_name, where = where, ) if print_query: return query try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return row[field_name]
def main(cursor): table_name = common_f.get_val("table", "") field_name = common_f.get_val("field", "") new_value = common_f.get_val("value", "").strip() where = common_f.get_val("where", "") print_query = common_f.get_val("p", False) silent = common_f.get_val("silent", False) new_value_db = new_value try: if new_value_db != float(new_value_db) and new_value_db != int(new_value_db): new_value_db = "'%s'" % database_f.escape(new_value_db) except Exception as e: new_value_db = "'%s'" % database_f.escape(new_value_db) query = """UPDATE {table} SET {field} = {value} WHERE {where};""".format( table=table_name, field=field_name, value=new_value_db, where=where ) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n", ""), query)) if print_query: return query if not silent: return new_value else: return ""
def main(cursor, user_id=-1): sub_mode = common_f.get_val('sub_mode', "form") if sub_mode == "add": return add(cursor) if sub_mode == "commit": return commit(cursor) if sub_mode == "delete": return delete(cursor, user_id) return show_form(cursor, user_id)
def log_usage(cursor, override_mode=None): if common_f.cache.get("user", None) != None: user_id = common_f.cache['user'].id else: user_id = -1 if not override_mode: override_mode = common_f.get_val("mode", pages.default_page) if override_mode in excluded_pages: return the_log = UserLog( user_id = user_id, page = override_mode, access_time = int(import_time), load_time = time.time() - import_time, ) try: the_log.insert(cursor) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), the_log.insert(test_mode=True)))
def delete(cursor, error_id): the_error = edit_f.delete(cursor, error.Error, id=int(common_f.get_val("error", error_id))) page_data["Redirect"] = "web.py?mode=list_errors" return ""
def main(): # Need this so it uses the correct path try: for k, v in page_dict.items(): v[1] = v[1].replace("gui/", "{}/gui/".format(sys.path[0])) except Exception as e: print(error.html_render(context=1)) raise import cgitb cgitb.enable(context=1) cgitb.html = error.html_render # Override the shell patterns to output HTML instead cli_f.shell_patterns = cli_f.html_patterns # Connect to DB cursor = database_f.get_cursor() # Default to listing players m = common_f.get_val("mode", pages.default_page) the_page = import_page(m) output = [] try: page_results = the_page.main(cursor) except Exception as e: print("Content-type: text/html; charset=utf-8") print("") print( "There was an error executing the main function of the_page: %s" % str(the_page).replace("<", "<").replace(">", ">") ) print("<br /><br />") print(error.log_error(cursor, e, context=0)) return # Is this an AJAX request? ajax = bool(common_f.get_val("ajax", False)) # Redirect if page_results == "" and the_page.page_data.get("Redirect", "") != "": print("Location: {0}".format(the_page.page_data["Redirect"])) print("") return # Serving content print(the_page.page_data.get("Content-type", "Content-type: text/html; charset=utf-8")) print(html_f.cookies) print("") # Import the header/footer try: find = imp.find_module(the_page.page_data["Template"], ["templates"]) the_template = imp.load_module("the_template", *find) find[0].close() except KeyError: print(error.html_render(context=1, headers=False)) exit() except Exception: try: find[0].close() except Exception: pass print(error.html_render(context=1, headers=False)) print("<br /><br />Found template: {}<br />".format(the_page.page_data["Template"])) exit() # Headers if the_page.page_data.get("Headers", True) and page_results != "" and ajax != True: output.append(the_template.headers(cursor, the_page.page_data)) # Core output output.append(page_results) the_page.page_data["time"] = time.time() - start_time # Footers if the_page.page_data.get("Headers", True) and page_results != "" and ajax != True: output.append(the_template.footers(cursor, the_page.page_data)) output = de_unicode("".join([str(i) for i in output])) # We now want to print it out, sometimes there can be errors # related to unicode try: print(output) except UnicodeEncodeError as e: ignore_uni_errror = common_f.get_val("iue", 0) from profiteer import config try: f = open("%sutf8_out.html" % config.get("cache_path"), "w", encoding="utf-8") f.write(output) f.close() except Exception: pass if ignore_uni_errror: _print_ignoring_error(output) o = output print( "Unicode error at character %d, Ignore errors by adding '&iue=1', <a href='http://localhost/profiteer/utf8_out.html'>alternately view raw</a><br />" % e.start ) print( "%s<strong style='color:red;'>*</strong>%s" % ( o[e.start - 300 : e.start].replace("<", "<").replace(">", ">"), o[e.start + 1 : e.start + 20].replace("<", "<").replace(">", ">"), ) ) print("<br />") print(e.start, "<br />") print(dir(e)) exit() except Exception as e: raise
def delete(cursor, user_id): the_user = edit_f.delete(cursor, user.User, id=int(common_f.get_val('user', user_id))) page_data['Redirect'] = "web.py?mode=list_users" return ""
def show_form(cursor, user_id): user_id = int(common_f.get_val('user', user_id)) the_user = common_q.get_one(cursor, user.User, id=user_id) if the_user == None: page_data["Padding"] = 0 return """ <div class='error'> No user selected, listing all users instead. </div> {}""".format(list_users.main(cursor)) permissions = [] i = 1 for p in user.permission_fields: if p == "root": continue # You can't edit attributes you don't have if not getattr(common_f.cache['user'], p) and not common_f.cache['user'].root: continue i += 1 permissions.append(""" <tr class="row{row}"> <td><label for="{name}">{name}</label></td> <td>{value}</td> </tr>""".format( row = i % 2, name = p, value = html_f.check_box(p, getattr(the_user, p), custom_id=p), )) output = [] output.append(""" <form action="web.py" method="post" accept-charset="utf-8"> <input type="hidden" name="mode" id="mode" value="edit_user" /> <input type="hidden" name="sub_mode" value="commit" /> <input type="hidden" name="id" value="{user_id}" /> <input type="hidden" name="salt" value="{salt}" /> {root} Editing: {name_text} <br /><br /> <table border="0" cellspacing="5" cellpadding="5"> <tr> <td><label for="password">New password:</label></td> <td style="padding: 1px;"><input type="password" name="password" id="password" value="" /></td> <td width="5"> </td> <td><label for="password2">Confirm password:</label></td> <td style="padding: 1px;"><input type="password" name="password2" id="password2" value="" /></td> </tr> <tr> <td colspan="2"> <table border="0" cellspacing="0" cellpadding="5"> <tr class="row2"> <th>Permission</th> <th>Value</th> </tr> {permissions} </table> </td> </tr> </table> <br /> <input type="submit" value="Perform edit" /> </form> <form id="delete_form" action="web.py" method="post" accept-charset="utf-8"> <input type="hidden" name="user" value="{user_id}" /> <input type="hidden" name="mode" value="edit_user" /> <input type="hidden" name="sub_mode" value="delete" /> <input style="float:right; margin-right:100px;" type="button" value="Delete user" onclick="var answer = confirm('Delete {name_safe}?') if (answer) $('#delete_form').submit();" /> </form> {onload} <br /><br />""".format( user_id = user_id, name_text = html_f.text_box("name", the_user.username, size=20, custom_id="user_name"), name_safe = html_f.js_name(the_user.username), onload = html_f.onload % "$('#user_name').focus();", root = '<input type="hidden" name="root" value="True" />' if the_user.root else "", salt = the_user.salt, permissions = "".join(permissions), )) page_data['Title'] = "Edit user ({})".format(the_user.username) return "".join(output)
def html_render(einfo=None, context=5, headers=True): """Copied from cgitb.html() and altered to suit my needs and preferences""" # If no info passed, grab it from the sys library if einfo == None: einfo = sys.exc_info() etype, evalue, etb = einfo if isinstance(etype, type): etype = etype.__name__ indent = str((' ' * 6)) frames = [] records = inspect.getinnerframes(etb, context) final_file, final_line = "", 0 for frame, the_file, lnum, func, lines, index in records: if the_file: file_path = os.path.abspath(the_file) final_file = file_path link = '<a href="file://{}">{}</a>'.format(file_path, pydoc.html.escape(file_path)) else: the_file = link = '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in <strong>' + func + '</strong>' + \ inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value)) highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(the_file, lnum[0]) finally: lnum[0] += 1 vars = cgitb.scanvars(reader, frame, locals) rows = [] if index is not None: i = lnum - index for line in lines: num = "<span style='font-size:0.8em;'>" + ' ' * (5-len(str(i))) + str(i) + '</span> ' if i in highlight: final_line = i line = '=>%s%s' % (num, pydoc.html.preformat(line)) rows.append('<div style="{}">{}</div>'.format(styles['highlighted_row'], line)) else: line = ' %s%s' % (num, pydoc.html.preformat(line)) rows.append('<div style="%s">%s</div>' % (styles['grey_text'], line)) i += 1 done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not cgitb.__UNDEF__: if where in ('global', 'builtin'): name = ('<em>%s</em> ' % where) + "<strong>%s</strong>" % name elif where == 'local': name = "<strong>%s</strong>" % name else: name = where + "<strong>" + name.split('.')[-1] + "</strong>" dump.append('%s = %s' % (name, pydoc.html.repr(value))) else: dump.append(name + ' <em>undefined</em>') rows.append('<div style="{};font-size:0.9em;">{}</div>'.format(styles['grey_text'], ', '.join(dump))) frames.append(''' <div style="{styles[frame]}"> {link} {call} {rows} </div>'''.format( styles = styles, link = link, call = call, rows = '\n'.join(rows) )) final_file, final_line exception = ['<br><strong>%s</strong>: %s' % (pydoc.html.escape(str(etype)), pydoc.html.escape(str(evalue)))] for name in dir(evalue): if name[:1] == '_': continue value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n<br>%s%s =\n%s' % (indent, name, value)) mode = common_f.get_val("mode", pages.default_page) if mode in pages.page_dict: path = "/".join(pages.page_dict[mode][1::-1]) else: path = "NO PATH" output = """ <html> <body style='padding:0;margin:0;'> <div id="exception_container" style="{styles[body]}"> <div id="exception_header" style="{styles[header]}"> <span style="font-size:2em;">{etype} at {short_file_path}.py</span><br /> <div style="padding: 10px 30px;"> <table border="0" cellspacing="0" cellpadding="5"> <tr> <td style="text-align:right; width:200px;">Request url:</td> <td>{url}.py</td> </tr> <tr> <td style="text-align:right;">Exception type:</td> <td>{etype}</td> </tr> <tr> <td style="text-align:right;">Exception value:</td> <td>{evalue}</td> </tr> <tr> <td style="text-align:right;">Exception location:</td> <td>{location}</td> </tr> <tr> <td style="text-align:right;">Python executable:</td> <td>{python_exe}</td> </tr> <tr> <td style="text-align:right;">Python version:</td> <td>{pyver}</td> </tr> <tr> <td style="text-align:right;vertical-align: top;">Python path:</td> <td>{pypath}</td> </tr> <tr> <td style="text-align:right;">Server time:</td> <td>{server_time}</td> </tr> </table> </div> </div> </div>""".format( styles = styles, url = path, location = final_file + ", line %d" % final_line, etype = pydoc.html.escape(str(etype)), evalue = pydoc.html.escape(str(evalue)), pyver = sys.version.split()[0], python_exe = sys.executable, pypath = "<br>".join(sys.path), server_time = datetime.datetime.now().strftime("%A, %d of %b %Y %H:%M:%S %Z"), file_path = path, # Takes file path and removes the root/system path from it short_file_path = path.replace(sys.path[0], ""), ) if headers: output = "Content-type: text/html; charset=utf-8\n" + output # return output + ''.join(frames) + ''.join(exception) + ''' return output + ''.join(frames) + ''' <!-- The above is a description of an error in a Python program, formatted for a Web browser because the 'cgitb' module was enabled. In case you are not reading this in a Web browser, here is the original traceback: %s --> </body> </html> ''' % pydoc.html.escape( ''.join(traceback.format_exception(etype, evalue, etb)))
def main(cursor, query_filter=""): query_filter = common_f.get_val("filter", query_filter) if query_filter == "": error_dict = common_q.get_all(cursor, error.Error, where="fixed = False", orderby="timestamp DESC") elif query_filter == "today": today = datetime.date.today() today = time.mktime(today.timetuple()) error_dict = common_q.get_all( cursor, error.Error, where="timestamp >= %d AND fixed = False" % today, orderby="timestamp DESC" ) else: error_dict = common_q.get_all( cursor, error.Error, where="mode='%s' and fixed = False" % database_f.escape(query_filter), orderby="timestamp DESC", ) output = [] if len(error_dict) > 0: user_dict = common_q.get_all(cursor, user.User) user_dict[-1] = user.User(username="******") output.append( """<table border="0" cellspacing="0" cellpadding="5" style="width:100%;"> <tr class="row2"> <th>Date</th> <th>Mode</th> <th>Func Call</th> <th>Type</th> <th>User</th> <th colspan="2"> </th> </tr> """ ) i = 1 for error_id, the_error in error_dict.items(): i += 1 the_date = the_error.timestamp output.append( """ <tr class="row{row}" id="row{error_id}"> <td>{date}</td> <td>{mode}</td> <td>{function_call}</td> <td>{etype}</td> <td>{user}</td> <td class="block_cell"><a href="web.py?mode=edit_error&error={error_id}">View</a></td> <td class="block_cell"><a href="#" onclick="{onclick}">Fix</a></td> </tr>""".format( error_id=error_id, row=i % 2, etype=the_error.exception_type, date=common_f.display_date(the_date, "%d of %B at %H:%M"), mode="No mode specified" if the_error.mode == "" else the_error.mode, function_call="" if the_error.function_call == "" else the_error.function_call, user=user_dict[the_error.user_id].username, onclick="""$('#ajax_target').load('web.py', {'mode':'edit_error', 'error':'%d', 'sub_mode':'fix'}); $('#row%d').hide(); return false;""" % (error_id, error_id), ) ) output.append("</table>") else: output.append("<div style='padding:10px;'>No errors found</div>") modes = {} # Select all the groups possible query = """SELECT mode FROM errors GROUP BY mode""" try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n", ""), query)) for row in cursor: modes[row["mode"]] = row["mode"] page_data["Rows"] = len(error_dict) page_data["Title"] = "Error list (%d)" % len(error_dict) page_data[ "Filters" ] = """ <form action="web.py" method="get" accept-charset="utf-8" style="float: left;"> <a href="web.py?mode=list_errors">All errors</a> <a href="web.py?mode=list_errors&filter=today">Todays errors</a> <input type="hidden" name="mode" value="list_errors" /> {} <input type="submit" value="Sort by mode" /> </form> """.format( html_f.option_box("filter", modes, selected=query_filter) ) return "".join(output)
def main(cursor, query_filter=""): query_filter = common_f.get_val("filter", query_filter) if query_filter == "": log_dict = common_q.get_all(cursor, user_log.UserLog, orderby="access_time DESC") elif query_filter == "today": today = datetime.date.today() today = time.mktime(today.timetuple()) log_dict = common_q.get_all( cursor, user_log.UserLog, where="access_time >= %d" % today, orderby="access_time DESC" ) else: log_dict = common_q.get_all( cursor, user_log.UserLog, where="mode='%s'" % database_f.escape(query_filter), orderby="access_time DESC" ) output = [] if len(log_dict) > 0: user_dict = common_q.get_all(cursor, user.User) user_dict[-1] = user.User(username="******") output.append( """<table border="0" cellspacing="0" cellpadding="5" style="width:100%;"> <tr class="row2"> <th>Date</th> <th>Mode</th> <th>User</th> <th>Load time</th> <th colspan="2"> </th> </tr> """ ) i = 1 for log_id, the_log in log_dict.items(): i += 1 the_date = the_log.access_time output.append( """ <tr class="row{row}"> <td>{date}</td> <td>{page}</td> <td>{user}</td> <td>{load_time}</td> <td class="block_cell"><a href="web.py?mode=edit_log&log={log_id}">View</a></td> <td class="block_cell"><a href="web.py?mode=edit_log&log={log_id}&sub_mode=delete">Delete</a></td> </tr>""".format( log_id=log_id, row=i % 2, load_time=round(the_log.load_time, 4), date=common_f.display_date(the_date, "%d of %B at %H:%M"), page="No mode specified" if the_log.page == "" else the_log.page, user=user_dict[the_log.user_id].username, ) ) output.append("</table>") else: output.append("<div style='padding:10px;'>No logs found</div>") return "".join(output)
def main(cursor, emulate_mode="", user_id=-1, mask_cursor=True): user_id = int(common_f.get_val("user_id", user_id)) emulate_mode = common_f.get_val("emulate_mode", emulate_mode) mask_cursor = bool(common_f.get_val("mask_cursor", mask_cursor)) if user_id < 1 and emulate_mode == "": return show_form(cursor) if user_id < 1: return "No user selected" if emulate_mode == "": return "No mode to emulate" # Allows us to test the traceback display force_error = bool(common_f.get_val("force_error", False)) if force_error: return force_error_func() # Set ourselves to fake the user that saw the bug real_user = common_f.cache['user'] the_user = common_q.get_one(cursor, user.User, id=user_id) common_f.cache['user'] = the_user output = [] # The two new lines are for our regex # the_error.args += "\n\n" # re_results = re.findall(r"([a-zA-Z_]*?) = (.*?\n\n)", the_error.args) # Now build the CGI form # cgi_fields = [(k, v.strip()) for k,v in re_results] # gui_test_utils.new_cgi_form(cgi_fields) # Alter the require function to suit our emulation needs user.require = error.emulate_require # Also stop our cursor from altering the database if mask_cursor: cursor.execute = error.emulate_execute(cursor.execute) # Lets try importing the page try: the_page = web.import_page(emulate_mode, handle_exception=False) except Exception: return " Unable to import page" + error.html_render(headers=False) # Some variables for displaying stuff output.append(""" <div style="padding:10px;"> <strong>Emulating:</strong> <a href="?mode=edit_user&user={user_id}">{user}</a> <strong>Mode:</strong> {mode} <a style="float:right;" href="web.py">Your dashboard</a> </div> <hr> <div style='padding:10px;'> <span class="stitle">Page output</span><br /><br /> """.format( user = the_user.username, user_id = the_user.id, mode = emulate_mode, )) # Good good, now lets try executing it try: page_output = the_page.main(cursor) except Exception: output.append(error.html_render(headers=False)) else: output.append(page_output) finally: output.append("</div>") # Reset the real user # common_f.cache['user'] = real_user return "".join(output)
def main(cursor): one_query = common_f.get_val('one', False) query = common_f.get_val('query') # If it's 1 query then we can multiline it if one_query: queries = [query] else: queries = query.split("\r") output = [""" <form action="web.py?mode=direct_query" method="post" accept-charset="utf-8"> One query: <input type="checkbox" name="one" value="True" /> <textarea name="query" id="query" rows="5" style="width:99%;">{0}</textarea> <br /> <input type="submit" value="Run" style="float:right;margin-right: 40px;font-size:1.2em;"/> <br /><br /> </form> """.format(query)] output.append(html_f.onload % "$('#query').focus();") if query != "": output.append("<hr /><div id='qrun' style='background-color:#FFC;padding:5px;'>Query run successfully.</div><br /><br />") first_row = True headers = [] data = [] id_list = [] i = 0 if len(queries) > 1: cursor.execute('BEGIN') for q in queries: q = q.strip() if q == '': continue if q[0:2] == '--': continue try: cursor.execute(q) except Exception as e: print("\nError with '%s'" % q) cursor.execute('ROLLBACK') raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), q)) cursor.execute('COMMIT') else: # If we have an error then we want to rollback and print out the error message try: cursor.execute(query) except Exception as e: cursor.execute('ROLLBACK') output.append(""" <div class="error"> {1} <br /><br /> Query: {0} </div> """.format(e.args[0].decode('utf-8'), query)) return "".join(output) # It's possible that our query returned some information, lets try to print it out totals = {} try: for row in cursor: if "id" in row: id_list.append(str(row['id'])) if first_row: for k, v in row.items(): totals[k] = 0 headers.append("<th>%s</th>" % k) data.append("<tr class='row%d'>" % (i % 2)) for k, v in row.items(): data.append("<td>%s</td>" % v) if type(v) in (int, float): totals[k] += v data.append("</tr>") first_row = False i += 1 output.append(""" <table border="0" cellspacing="0" cellpadding="5"> <tr class='row2'> {headers} </tr> {data} </table> """.format( headers="".join(headers), data="".join(data), )) output.append(' Id list: <input type="text" value="%s" style="width: 400px;"/>' % ", ".join(id_list)) except Exception as e: output.append('No result set') output.append('<br /><br /><table border="0" cellspacing="0" cellpadding="5">') for t in templates: output.append( """<tr> <td onclick="$('#query').text('%s');">%s</td> </tr>""" % (t, t) ) output.append('</table>%s' % html_f.onload % "$('#qrun').animate({backgroundColor:'white'}, 3000);") return "".join(output)
def main_shortform(cursor): output = [] user_dict = common_q.get_all(cursor, user.User) output.append(""" <table border="0" cellspacing="0" cellpadding="5" style="width: 100%;"> <tr class="row2"> <th>Name</th> <th>Blocked</th> <th>Privilages</th> <th> </th> </tr>""") count = -1 for i, u in user_dict.items(): count += 1 priviliages = [] for p in user.permission_fields: if p == "root": continue if getattr(u, p): priviliages.append("✔") else: priviliages.append(" ") output.append(""" <tr class="row{row}" id="{user_id}"> <td><strong>{username}</strong></td> <td>{blocked}</td> <td>{privileges}</td> <td class="block_cell"><a href="web.py?mode=edit_user&user={user_id}">Edit</a></td> </tr> """.format( row = count % 2, user_id = u.id, username = u.username, blocked = "True" if u.blocked else "", privileges = " ".join(priviliages) )) # Add new user count += 1 output.append(""" <tr class="row{row}"> <td> <form action="web.py" id="add_user_form" method="post" accept-charset="utf-8"> <input type="hidden" name="mode" value="edit_user" /> <input type="hidden" name="sub_mode" value="add" /> <input type="text" id="new_name" name="username" value="" /> </td> <td> <input type="password" name="password" id="password" value="" size="10"/> <input type="password" name="password2" id="password2" value="" size="10"/> <input type="hidden" name="salt" value="{salt}" /> </td> <td> </td> <td> <input type="submit" value="Add" /> </form> </td> </tr> """.format( row = count % 2, salt = user.make_salt().replace('"', "'"), colspan = len(user.permission_fields)-1, )) output.append("</table>") if common_f.get_val('ajax', False): output.append("<br /><br />") else: # output.append(html_f.onload % "$('#new_name').focus();") pass return "".join(output)