def get_clean_body(mutant, response):
    """
    @see: Very similar to fingerprint_404.py get_clean_body() bug not quite
          the same maybe in the future I can merge both?

    Definition of clean in this method:
        - input:
            - response.get_url() == http://host.tld/aaaaaaa/?id=1 OR 23=23
            - response.get_body() == '...<x>1 OR 23=23</x>...'

        - output:
            - self._clean_body( response ) == '...<x></x>...'

    All injected values are removed encoded and "as is".

    :param mutant: The mutant where I can get the value from.
    :param response: The HTTPResponse object to clean
    :return: A string that represents the "cleaned" response body.
    """

    body = response.body

    if response.is_text_or_html():
        mod_value = mutant.get_mod_value()

        body = body.replace(mod_value, "")
        body = body.replace(urllib.unquote_plus(mod_value), "")
        body = body.replace(cgi.escape(mod_value), "")
        body = body.replace(cgi.escape(urllib.unquote_plus(mod_value)), "")

    return body
Example #2
0
def get_clean_body(response):
    """
    @see: blind_sqli_response_diff.get_clean_body()

    Definition of clean in this method:
        - input:
            - response.get_url() == http://host.tld/aaaaaaa/
            - response.get_body() == 'spam aaaaaaa eggs'

        - output:
            - self._clean_body( response ) == 'spam  eggs'

    The same works with filenames.
    All of them, are removed encoded and "as is".

    :param response: The HTTPResponse object to clean
    :return: A string that represents the "cleaned" response body of the response.
    """

    body = response.body

    if response.is_text_or_html():
        url = response.get_url()
        to_replace = url.url_string.split("/")
        to_replace.append(url.url_string)

        for repl in to_replace:
            if len(repl) > 6:
                body = body.replace(repl, "")
                body = body.replace(urllib.unquote_plus(repl), "")
                body = body.replace(cgi.escape(repl), "")
                body = body.replace(cgi.escape(urllib.unquote_plus(repl)), "")

    return body
    def post(self):
        response = {"error": False, "errtext": "", "newPage": ""}
        try:
            pageNum = int(self.request.get("pageNum"))
            newPageText = cgi.escape(self.request.get("pageText"))
            newPageLink = cgi.escape(self.request.get("pageLinkText"))
            imageLink = cgi.escape(self.request.get("imageLink"))

            # Make sure there are enough pages left?

            # Escape the text of invalid characters, trimming to 1700
            newPageText = newPageText[:2500]

            acc = db.GqlQuery("SELECT * FROM CurHighPage").get()
            if acc == None:
                acc = CurHighPage(counter=1)
                acc.put()

            newNum = db.run_in_transaction(increment_counter, acc.key())

            # Add the new page, and add the new page link
            np = Page(pageNum=newNum, content=newPageText, imageLink=imageLink)
            np.put()

            npl = PageLink(pageFrom=pageNum, pageTo=newNum, linkText=newPageLink)
            npl.put()

            response["newPage"] = newNum

        except Exception, inst:
            response["error"] = True
            response["errtext"] = "An Exception Has Occured " + str(inst)
Example #4
0
def fetch_paste(request):
    url = request.META.get("PATH_INFO", "")[1:]
    content = ""

    try:
        p = Paste.objects.get(url=url)
    except:
        t = loader.get_template("index.html")
        c = Context(
            {"title": titl + " 404", "title_low": titl.lower() + " 404", "error": "Paste requested does not exist."}
        )
        return http.HttpResponse(t.render(c))

    repl = [("\t", "  "), (" ", "&nbsp;"), ("\n", "<br />")]

    esc_text = cgi.escape(p.content)
    for a, b in repl:
        esc_text = esc_text.replace(a, b)

    if hasattr(settings, "SIMPYL_PASTEBIN_NOTELINE"):
        noteline = cgi.escape(settings.SIMPYL_PASTEBIN_NOTELINE)
    else:
        noteline = ""

    return http.HttpResponse(
        '<h1>paste.</h1><br /><a href="/">make another</a><br />%s<br /><br /><tt>%s</tt>' % (noteline, esc_text)
    )
Example #5
0
    def post(self):
        id = cgi.escape(self.request.get("id"))
        password = cgi.escape(self.request.get("password"))

        user = None

        result = User.all()
        result.filter("id", id)
        user = result.get()

        # login success
        if (result.count() >= 1) and (user.password == password):
            user = result.get()
            self.session["user"] = {
                "name": user.name,
                "id": user.id,
                "phone": user.phone,
                "address": user.address,
                "detail_address": user.detail_address,
                "postcode": user.postcode,
            }

            user = self.session.get("user")
            template_values = {"title": self.title, "user": user}
            path = os.path.join(os.path.dirname(__file__), "templates")
            path = os.path.join(path, "start.html")
            self.response.out.write(template.render(path, template_values))

        # login fail
        else:
            template_values = {"title": self.title, "message": "Login failed"}
            path = os.path.join(os.path.dirname(__file__), "templates")
            path = os.path.join(path, "login.html")
            self.response.out.write(template.render(path, template_values))
Example #6
0
def build_accession_table(acc):
    """
    Return an html table from the acc argument.
    """
    parts = ["<table>"]
    row = "<tr><td>%s</td><td>%s</td></tr>"
    # parts.append(row % ('Name:', acc.name))
    name_href = '<a href="/search?name=%(name)s">%(name)s</a>'
    google_href = '<span style="margin-left: 40px"><a href="http://google.com/search?q=%(name)s">google</a></span>'
    name_href = name_href + google_href
    parts.append(row % ("Name:", name_href % {"name": cgi.escape(acc.name)}))
    parts.append(row % ("Acc #:", acc.acc_num))
    parts.append(row % ("Family:", acc.family.capitalize()))
    parts.append(row % ("Common name:", acc.common_name))
    parts.append(row % ("Range:", acc.range))
    parts.append(row % ("Misc. Notes:", acc.misc_notes))
    parts.append("<br />")
    parts.append(row % ("Rec'd. Date:", acc.recd_dt))
    parts.append(row % ("Rec'd. Amt:", acc.recd_amt))
    parts.append(row % ("Rec'd. Size:", acc.recd_size))
    parts.append(row % ("Rec'd. As:", name_href % {"name": cgi.escape(acc.name)}))
    parts.append(row % ("Rec'd. Notes:", acc.recd_notes))

    parts.append(row % ("Source:", acc.psource_current))
    parts.append(row % ("Source Acc. #:", acc.psource_acc_num))
    parts.append(row % ("Source Acc. Date:", acc.psource_acc_dt))
    parts.append(row % ("Source Notes:", acc.psource_misc))
    parts.append("</table>")
    return "".join(parts)
Example #7
0
    def document(self):
        """Render the error document - show custom template for 404"""
        self._disable_cache()
        resp = request.environ.get("pylons.original_response")

        # Don't do fancy error documents for JSON
        if resp.headers["Content-Type"] in ["text/javascript", "application/json", "text/csv"]:
            response.headers["Content-Type"] = resp.headers["Content-Type"]
            return resp.body

        code = cgi.escape(request.GET.get("code", str(resp.status_int)))
        content = literal(resp.body) or cgi.escape(request.GET.get("message", ""))

        if code in self.rendered_error_codes:
            c.code = code
            message = content
            message = message.split("</h1>", 1)[-1]
            message = message.split("</body>", 1)[0]
            c.message = message.split("\n", 2)[-1]
            return templating.render("errors/%s.html" % code)
        else:
            page = error_document_template % dict(
                prefix=request.environ.get("SCRIPT_NAME", ""), code=code, message=content
            )
            return page
def updateMinScale(req, minscale1_, minscale2_):
    session = Session.Session(req)
    oN = cgi.escape(minscale1_)
    uN = cgi.escape(minscale2_)
    a = doSql()
    f = a.execqry("select updateminscale('" + session["sCode"] + "', '" + oN + "', '" + uN + "')", True)
    return True
Example #9
0
    def post(self):
        user = users.get_current_user()
        thesis = ThesisDB(
            year=int(self.request.get("year")),
            title=cgi.escape(self.request.get("title")),
            abstract=cgi.escape(self.request.get("abstract")),
            adviser=cgi.escape(self.request.get("adviser")),
            section=int(self.request.get("section")),
            created_by=user.user_id(),
        )
        thesis.put()

        self.response.headers["Content-Type"] = "application/json"
        response = {
            "result": "OK",
            "data": {
                "id": thesis.key.urlsafe(),
                "year": thesis.year,
                "title": thesis.title,
                "abstract": thesis.abstract,
                "adviser": thesis.adviser,
                "section": thesis.section,
            },
        }
        self.response.out.write(json.dumps(response))
Example #10
0
    def actionDumpobj(self):
        import gc
        import sys

        self.sendHeader()
        class_filter = self.get.get("class")

        yield """
        <style>
         * { font-family: monospace; white-space: pre }
         table * { text-align: right; padding: 0px 10px }
        </style>
        """

        objs = gc.get_objects()
        for obj in objs:
            obj_type = str(type(obj))
            if obj_type != "<type 'instance'>" or obj.__class__.__name__ != class_filter:
                continue
            yield "%.1fkb %s... " % (float(sys.getsizeof(obj)) / 1024, cgi.escape(str(obj)))
            for attr in dir(obj):
                yield "- %s: %s<br>" % (attr, cgi.escape(str(getattr(obj, attr))))
            yield "<br>"

        gc.collect()  # Implicit grabage collection
Example #11
0
        def on_message(msg):
            action = msg[0]
            logging.debug("Received: %s" % msg)
            if action == gametypes.Messages.HELLO:
                self.name = escape(msg[1][:15]) if msg[1] else "lorem ipsum"
                self.kind = gametypes.Entities.WARRIOR
                self.equip_armor = msg[2]
                self.equip_weapon = msg[3]

                self.world.enter_callback(self)

                # TODO
                self.send([gametypes.Messages.WELCOME, self.id, self.name, 44, 212, 80])

                self.has_entered_game = True
                self.is_dead = False

            if action == gametypes.Messages.CHAT:
                content = msg[1]
                if content:
                    content = escape(content[:60])
                    self.broadcast_to_zone(message.Chat(self, content), False)

            if action == gametypes.Messages.MOVE:
                self.x = msg[1]
                self.y = msg[2]
Example #12
0
 def getrenderstr(self, entry, url):
     retstr = "<TR><TD>"
     retstr += self.getimgtag(entry)
     retstr += "</TD>\n<TD>&nbsp;"
     if entry.gettype() != "i" and entry.gettype() != "7":
         retstr += '<A HREF="%s">' % url
     retstr += "<TT>"
     if entry.getname() != None:
         retstr += cgi.escape(entry.getname())
     else:
         retstr += cgi.escape(entry.getselector())
     retstr += "</TT>"
     if entry.gettype() != "i" and entry.gettype() != "7":
         retstr += "</A>"
     if entry.gettype() == "7":
         retstr += '<BR><FORM METHOD="GET" ACTION="%s">' % url
         retstr += '<INPUT TYPE="text" NAME="searchrequest" SIZE="30">'
         retstr += '<INPUT TYPE="submit" NAME="Submit" VALUE="Submit">'
         retstr += "</FORM>"
     retstr += '</TD><TD><FONT SIZE="-2">'
     if entry.getmimetype():
         subtype = re.search("/.+$", entry.getmimetype())
         if subtype:
             retstr += cgi.escape(subtype.group()[1:])
     retstr += "</FONT></TD></TR>\n"
     return retstr
Example #13
0
def main_page():
    page_name = flask.request.args.get("page_name", "default")
    response = """
        <html><body>
            <h2>Permenant note page: %s</h2>""" % cgi.escape(
        page_name
    )

    parent = parent_key(page_name)
    notes = Note.query(ancestor=parent).fetch(20)
    for note in notes:
        response += "<h3>%s</h3>" % cgi.escape(note.key.id())
        response += "<blockquote>%s</blockquote>" % cgi.escape(note.content)

    response += """<hr>
           <form action="/add?%s" method="post">
           Submit Note: <input value="Title" name="note_title"><br>
           <textarea value="Note" name="note_text" rows="4" cols="60">
           </textarea>
           <input type="submit" value="Etch in stone"></form>""" % urllib.urlencode(
        {"page_name": page_name}
    )
    response += """
            <hr>
            <form>Switch page: <input value="%s" name="page_name">
            <input type="submit" value="Switch"></form>
            </body>
        </html>""" % cgi.escape(
        page_name, quote=True
    )

    return response
Example #14
0
 def post(self):
     text = cgi.escape(self.request.get("text"))
     sender = cgi.escape(self.request.get("sender"))
     recipient = cgi.escape(self.request.get("recipient"))
     subject = cgi.escape(self.request.get("subject"))
     parent_message = cgi.escape(self.request.get("parent"))
     q = User.query(User.username == recipient)
     user = q.get()
     if user:
         if len(parent_message) > 0:
             message_key = ndb.Key(urlsafe=parent_message)
             message = Message(parent=message_key)
         else:
             message = Message()
         message.subject = subject
         message.text = text
         message.sender = sender
         message.recipient = recipient
         message.time = datetime.datetime.now() - datetime.timedelta(hours=8)  # For PST
         message.put()
         # Increment message count for navbar
         q = User.query(User.username == recipient)
         user = q.get()
         user.message_count += 1
         user.put()
         self.redirect("/messages")
     else:
         self.redirect("/compose")
 def serializeNode(self, node, indent):
     if node.type == simpletree.TextNode.type:
         if node.parent.name not in html5lib.constants.rcdataElements and node.parent.name != "plaintext":
             value = cgi.escape(node.value, True)
         else:
             value = node.value
         if node.parent.name in ("pre", "textarea"):
             value = "\n" + value
         rv = tag.code(value, class_="text")
     elif node.type == simpletree.Element.type:
         rv = tag("")
         rv.append(tag.code("<" + node.name, class_=tagClasses["element"]))
         if node.attributes:
             for key, value in node.attributes.iteritems():
                 value = cgi.escape(value, True)
                 rv.append(
                     tag(
                         " ",
                         tag.code(key, class_=tagClasses["attr_name"]),
                         "=",
                         tag.code('"' + value + '"', class_=tagClasses["attr_value"]),
                     )
                 )
         rv.append(tag.code(">", class_=tagClasses["element"]))
     elif node.type == simpletree.CommentNode.type:
         rv = tag.code("<!--" + node.data + "-->", class_=tagClasses["comment"])
     elif node.type == simpletree.DocumentType.type:
         rv = tag.code("<!DOCTYPE " + node.name + ">", class_=tagClasses["doctype"])
     return rv
Example #16
0
 def post(self):
     input_un = self.request.get("username")
     input_pw = self.request.get("password")
     input_vf = self.request.get("verify")
     input_em = self.request.get("email")
     un = cgi.escape(input_un, quote=True)
     pw = cgi.escape(input_pw, quote=True)
     vpw = cgi.escape(input_vf, quote=True)
     em = cgi.escape(input_em, quote=True)
     une = ""
     pwe = ""
     vpwe = ""
     eme = ""
     self.response.headers["Content-Type"] = "text/html"
     if not valid_username(input_un):
         une = "That's not a valid username."
     if not valid_password(input_pw):
         pwe = "That wasn't a valid password."
     else:
         if input_pw != input_vf:
             vpwe = "Your passwords didn't match."
     if not valid_email(input_em):
         eme = "That's not a valid email."
     if (not une) and (not pwe) and (not vpwe) and (not eme):
         self.redirect(str("welcome.html?username=%s" % input_un))
     else:
         self.response.out.write(self.render(un, pw, vpw, em, une, pwe, vpwe, eme))
def addScore(req, score, mult):
    session = Session.Session(req)
    b = cgi.escape(score)
    c = cgi.escape(mult)
    e = doSql()
    f = e.execqry("select addscore('" + session["sCode"] + "','" + b + "','" + c + "')", True)
    return True
Example #18
0
def _htmlRenderDict(pathParts, statDict, output):
    """Render a dictionary as a table - recursing as necessary."""
    keys = list(statDict.keys())
    keys.sort()

    links = []

    output.write('<div class="level">')
    for key in keys:
        keyStr = cgi.escape(_utf8str(key))
        value = statDict[key]
        if hasattr(value, "__call__"):
            value = value()
        if hasattr(value, "keys"):
            valuePath = pathParts + (keyStr,)
            if isinstance(value, scales.StatContainer) and value.isCollapsed():
                link = "/status/" + "/".join(valuePath)
                links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
            else:
                output.write('<div class="key">%s</div>' % keyStr)
                _htmlRenderDict(valuePath, value, output)
        else:
            output.write(
                '<div><span class="key">%s</span> <span class="%s">%s</span></div>'
                % (keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace("\n", "<br/>"))
            )

    if links:
        for link in links:
            output.write(link)

    output.write("</div>")
Example #19
0
def main(script_path):
    checker_bin, checker_opts, checker_ver = find_checker_program()
    my_revision = __version__.split()[1]
    version_string = "PyCheckMate r%s &ndash; %s" % (my_revision, checker_ver)
    warning_string = ""
    if not checker_bin:
        href_format = "<a href=\"javascript:TextMate.system('open %s', null)\">%s</a>"
        pychecker_url = href_format % (PYCHECKER_URL, "PyChecker")
        pyflakes_url = href_format % (PYFLAKES_URL, "PyFlakes")
        pylint_url = href_format % (PYLINT_URL, "Pylint")
        warning_string = "<p>Please install %s, %s or %s for more extensive code checking." "</p><br>" % (
            pychecker_url,
            pyflakes_url,
            pylint_url,
        )

    basepath = os.getenv("TM_PROJECT_DIRECTORY")
    if basepath:
        project_dir = os.path.basename(basepath)
        script_name = os.path.basename(script_path)
        title = "%s &mdash; %s" % (escape(script_name), escape(project_dir))
    else:
        title = escape(script_path)

    print HTML_HEADER_FORMAT % (title, version_string)
    if warning_string:
        print warning_string
    if checker_bin:
        run_checker_program(checker_bin, checker_opts, script_path)
    else:
        check_syntax(script_path)
    print HTML_FOOTER
    return 0
Example #20
0
def proxy(path, start_response, proxy_url):
    # pylint:disable=too-many-locals
    if "://" not in path:
        path = "http://" + path
    try:
        try:
            response = urllib2.urlopen(path)
        except urllib2.HTTPError as ex:
            response = ex
        print("%s: %s %s" % (path, response.code, response.msg))
        headers = [(k, v) for (k, v) in response.headers.items() if k not in drop_headers]
        scheme, netloc, path, _params, _query, _fragment = urlparse(path)
        host = (scheme or "http") + "://" + netloc
    except Exception as ex:  # pylint:disable=broad-except
        sys.stderr.write("error while reading %s:\n" % path)
        traceback.print_exc()
        tb = traceback.format_exc()
        start_response("502 Bad Gateway", [("Content-Type", "text/html")])
        # pylint:disable=deprecated-method
        error_str = escape(str(ex) or ex.__class__.__name__ or "Error")
        error_str = "<h1>%s</h1><h2>%s</h2><pre>%s</pre>" % (error_str, escape(path), escape(tb))
        return [_as_bytes(error_str)]
    else:
        start_response("%s %s" % (response.code, response.msg), headers)
        data = response.read()
        data = fix_links(data, proxy_url, host)
        return [data]
Example #21
0
def fixanchor(current, match):
    text = match.group(0)
    link = None
    if text.startswith("http:") or text.startswith("https:") or text.startswith("ftp:"):
        # Strip off trailing punctuation.  Pattern taken from faqwiz.
        ltext = list(text)
        while ltext:
            c = ltext.pop()
            if c not in "();:,.?'\"<>":
                ltext.append(c)
                break
        link = EMPTYSTRING.join(ltext)
    elif text.endswith(".txt") and text <> current:
        link = SEPDIRURL + os.path.splitext(text)[0] + "/" + text
    elif text.startswith("sep-") and text <> current:
        link = os.path.splitext(text)[0] + ".html"
    elif text.startswith("SEP"):
        sepnum = int(match.group("sepnum"))
        link = SEPURL % sepnum
    elif text.startswith("RFC"):
        rfcnum = int(match.group("rfcnum"))
        link = RFCURL % rfcnum
    if link:
        return '<a href="%s">%s</a>' % (cgi.escape(link), cgi.escape(text))
    return cgi.escape(match.group(0))  # really slow, but it works...
Example #22
0
    def doProcess(self):
        """Handle the redirect from the OpenID server.
        """
        oidconsumer = self.getConsumer()

        # Ask the library to check the response that the server sent
        # us.  Status is a code indicating the response type. info is
        # either None or a string containing more information about
        # the return type.
        url = "http://" + self.headers.get("Host") + self.path
        info = oidconsumer.complete(self.query, url)

        sreg_resp = None
        pape_resp = None
        css_class = "error"
        display_identifier = info.getDisplayIdentifier()

        if info.status == consumer.FAILURE and display_identifier:
            # In the case of failure, if info is non-None, it is the
            # URL that we were verifying. We include it in the error
            # message to help the user figure out what happened.
            fmt = "Verification of %s failed: %s"
            message = fmt % (cgi.escape(display_identifier), info.message)
        elif info.status == consumer.SUCCESS:
            # Success means that the transaction completed without
            # error. If info is None, it means that the user cancelled
            # the verification.
            css_class = "alert"

            # This is a successful verification attempt. If this
            # was a real application, we would do our login,
            # comment posting, etc. here.
            fmt = "You have successfully verified %s as your identity."
            message = fmt % (cgi.escape(display_identifier),)
            sreg_resp = sreg.SRegResponse.fromSuccessResponse(info)
            pape_resp = pape.Response.fromSuccessResponse(info)
            if info.endpoint.canonicalID:
                # You should authorize i-name users by their canonicalID,
                # rather than their more human-friendly identifiers.  That
                # way their account with you is not compromised if their
                # i-name registration expires and is bought by someone else.
                message += "  This is an i-name, and its persistent ID is %s" % (cgi.escape(info.endpoint.canonicalID),)
        elif info.status == consumer.CANCEL:
            # cancelled
            message = "Verification cancelled"
        elif info.status == consumer.SETUP_NEEDED:
            if info.setup_url:
                message = "<a href=%s>Setup needed</a>" % (quoteattr(info.setup_url),)
            else:
                # This means auth didn't succeed, but you're welcome to try
                # non-immediate mode.
                message = "Setup needed"
        else:
            # Either we don't understand the code or there is no
            # openid_url included with the error. Give a generic
            # failure message. The library should supply debug
            # information in a log.
            message = "Verification failed."

        self.render(message, css_class, display_identifier, sreg_data=sreg_resp, pape_data=pape_resp)
Example #23
0
    def post(self):
        name = cgi.escape(self.request.get("name"))
        price = int(cgi.escape(self.request.get("price")))
        company = cgi.escape(self.request.get("company"))
        description = cgi.escape(self.request.get("description"))
        size = int(cgi.escape(self.request.get("size")))

        # Get the actual data for the picture and Transform
        imgHandlerIns = ImgHandler()
        thumbnail_img = None
        repre_img = None

        if self.request.get("image"):
            repre_img = imgHandlerIns.transform(self.request.get("image"))
            thumbnail_img = imgHandlerIns.transform(self.request.get("image"))

        obj = Product(
            name=name,
            price=price,
            company=company,
            image=thumbnail_img,
            description=description,
            size=size,
            repre_img=repre_img,
        ).put()

        self.redirect("/sales")
Example #24
0
    def emit(self, g, f):
        tag = "%s Parameters" % g.name
        t = "\n\n<h1>%s</h1>\n" % tag

        for param in g.params:
            if not hasattr(param, "DisplayName") or not hasattr(param, "Description"):
                continue
            d = param.__dict__
            tag = "%s (%s)" % (param.DisplayName, param.name)
            t += "\n\n<h2>%s</h2>" % tag
            if d.get("User", None) == "Advanced":
                t += "<em>Note: This parameter is for advanced users</em><br>"
            t += "\n\n<p>%s</p>\n" % cgi.escape(param.Description)
            t += "<ul>\n"

            for field in param.__dict__.keys():
                if field not in ["name", "DisplayName", "Description", "User"] and field in known_param_fields:
                    if field == "Values" and Emit.prog_values_field.match(param.__dict__[field]):
                        values = (param.__dict__[field]).split(",")
                        t += "<table><th>Value</th><th>Meaning</th>\n"
                        for value in values:
                            v = value.split(":")
                            t += "<tr><td>%s</td><td>%s</td></tr>\n" % (v[0], v[1])
                        t += "</table>\n"
                    else:
                        t += "<li>%s: %s</li>\n" % (field, cgi.escape(param.__dict__[field]))
            t += "</ul>\n"
        self.t += t
Example #25
0
def process_signup():

    connection = pymongo.Connection(connection_string, safe=True)

    email = bottle.request.forms.get("email")
    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")
    verify = bottle.request.forms.get("verify")

    # set these up in case we have an error case
    errors = {"username": cgi.escape(username), "email": cgi.escape(email)}
    if user.validate_signup(username, password, verify, email, errors):
        if not user.newuser(connection, username, password, email):
            # this was a duplicate
            errors["username_error"] = "Username already in use. Please choose another"
            return bottle.template("signup", errors)

        session_id = user.start_session(connection, username)
        print session_id
        cookie = user.make_secure_val(session_id)
        bottle.response.set_cookie("session", cookie)
        bottle.redirect("/welcome")
    else:
        print "user did not validate"
        return bottle.template("signup", errors)
Example #26
0
def html_table_row(lhs, rhs, style1, style2, line1, line2, chunkIndex, escapeHTML=True):
    # Escape both lines
    if escapeHTML:
        lhs = escape(lhs)
        rhs = escape(rhs)
    output = (
        "<tr><th><pre>"
        + line1
        + '</pre></th><td class="'
        + style1
        + '" id="lhs-'
        + str(chunkIndex)
        + "-"
        + line1
        + '"><pre>'
        + lhs
        + "</pre></td><th><pre>"
        + line2
        + '</pre></th><td class="'
        + style2
        + '" id="rhs-'
        + str(chunkIndex)
        + "-"
        + line2
        + '"><pre>'
        + rhs
        + "</pre></td></tr>"
    )
    return output
    def post(self):
        response = {"error": False, "errtext": "", "newPage": ""}
        try:
            pageNum = int(self.request.get("pageNum"))
            pageLinkPage = int(cgi.escape(self.request.get("pageLinkPage")))
            newPageLink = cgi.escape(self.request.get("pageLinkText"))

            page = db.GqlQuery("SELECT * FROM Page WHERE pageNum = :1", pageLinkPage).get()

            if page == None:
                raise Exception("Target page does not exist")

            oldPageLink = db.GqlQuery(
                "SELECT * FROM PageLink WHERE pageTo = :1 AND pageFrom = :2", pageNum, pageLinkPage
            ).get()

            if oldPageLink != None:
                raise Exception("Target already has link to page " + str(pageLinkPage))

            npl = PageLink(pageFrom=pageNum, pageTo=pageLinkPage, linkText=newPageLink)
            npl.put()

            response["newPage"] = pageLinkPage

        except Exception, inst:
            response["error"] = True
            response["errtext"] = "An Exception Has Occured " + str(inst)
Example #28
0
 def post(self):
     user = users.get_current_user()
     if user:
         u = user.user_id()
         url = str(self.request.get("url"))
         mode = str(self.request.get("mode"))
         content = safe_unicode(unquote_u(self.request.get("content")))
         cc = ""
         title = str(self.request.get("title"))
         bookmarks = db.GqlQuery("SELECT * FROM bookmark WHERE user = :1 AND url = :2", u, url)
         for bk in bookmarks:
             title = bk.title
             key = bk.key()
             db.delete(key)
         bm = bookmark()
         bm.url = url
         bm.user = u
         bm.title = title
         bm.content = content
         bm.date_save = datetime.datetime.now().date()
         bm.put()
         if mode == "1":
             self.redirect(cgi.escape(Location_url))
         else:
             self.redirect(cgi.escape(url))
     else:
         self.redirect(users.create_login_url(self.request.uri))
Example #29
0
def format_element(bfo, keyword_prefix, keyword_suffix, separator=" ; ", link="yes"):
    """
    Display keywords of the record.

    @param keyword_prefix: a prefix before each keyword
    @param keyword_suffix: a suffix after each keyword
    @param separator: a separator between keywords
    @param link: links the keywords if 'yes' (HTML links)
    """

    keywords = bfo.fields("6531_a")

    if len(keywords) > 0:
        if link == "yes":
            keywords = [
                '<a href="'
                + CFG_SITE_URL
                + "/search?f=keyword&amp;p="
                + quote('"' + keyword + '"')
                + "&amp;ln="
                + bfo.lang
                + '">'
                + cgi.escape(keyword)
                + "</a>"
                for keyword in keywords
            ]
        else:
            keywords = [cgi.escape(keyword) for keyword in keywords]

        keywords = [keyword_prefix + keyword + keyword_suffix for keyword in keywords]
        return separator.join(keywords)
 def additional_short_value_html(self, value):
     if not value:
         return ""
     return '<br><a href="./datastore/edit?key=%s">%s</a>' % (
         cgi.escape(str(value), True),
         cgi.escape(PseudoBreadcrumbs(value), True),
     )