Example #1
0
def preview():
    # Get the form fields.
    form = get_comment_form(request.form)
    thread = sanitize_name(form["thread"])

    # Trap fields.
    trap1 = request.form.get("website", "x") != "http://"
    trap2 = request.form.get("email", "x") != ""
    if trap1 or trap2:
        flash("Wanna try that again?")
        return redirect(url_for("index"))

    # Validate things.
    if len(form["message"]) == 0:
        flash("You must provide a message with your comment.")
        return redirect(form["url"])

    # Gravatar?
    gravatar = Comment.gravatar(form["contact"])

    # Are they submitting?
    if form["action"] == "submit":
        Comment.add_comment(
            thread=thread,
            uid=g.info["session"]["uid"],
            ip=remote_addr(),
            time=int(time.time()),
            image=gravatar,
            name=form["name"],
            subject=form["subject"],
            message=form["message"],
            url=form["url"],
        )

        # Are we subscribing to the thread?
        if form["subscribe"] == "true":
            email = form["contact"]
            if "@" in email:
                Comment.add_subscriber(thread, email)
                flash(
                    "You have been subscribed to future comments on this page."
                )

        flash("Your comment has been added!")
        return redirect(form["url"])

    # Gravatar.
    g.info["gravatar"] = gravatar
    g.info["preview"] = Comment.format_message(form["message"])
    g.info["pretty_time"] = pretty_time(Config.comment.time_format,
                                        time.time())

    g.info.update(form)
    return template("comment/preview.html")
Example #2
0
def send():
    """Submitting the contact form."""
    name    = request.form.get("name", "") or "Anonymous"
    email   = request.form.get("email", "")
    subject = request.form.get("subject", "") or "[No Subject]"
    message = request.form.get("message", "")

    # Spam traps.
    trap1 = request.form.get("contact", "x") != ""
    trap2 = request.form.get("website", "x") != "http://"
    if trap1 or trap2:
        flash("Wanna try that again?")
        return redirect(url_for(".index"))

    # Message is required.
    if len(message) == 0:
        flash("The message is required.")
        return redirect(url_for(".index"))

    # Email looks valid?
    reply_to = None
    if "@" in email and "." in email:
        reply_to = email

    # Send the e-mail.
    send_email(
        to=Config.site.notify_address,
        reply_to=reply_to,
        subject="Contact Form on {}: {}".format(Config.site.site_name, subject),
        message="""A visitor to {site_name} has sent you a message!

* IP Address: `{ip}`
* User Agent: `{ua}`
* Referrer: <{referer}>
* Name: {name}
* E-mail: <{email}>
* Subject: {subject}

{message}""".format(
            site_name=Config.site.site_name,
            ip=remote_addr(),
            ua=request.user_agent.string,
            referer=request.headers.get("Referer", ""),
            name=name,
            email=email,
            subject=subject,
            message=message,
        )
    )

    flash("Your message has been delivered.")
    return redirect(url_for("index"))
Example #3
0
def preview():
    # Get the form fields.
    form   = get_comment_form(request.form)
    thread = sanitize_name(form["thread"])

    # Trap fields.
    trap1 = request.form.get("website", "x") != "http://"
    trap2 = request.form.get("email", "x") != ""
    if trap1 or trap2:
        flash("Wanna try that again?")
        return redirect(url_for("index"))

    # Validate things.
    if len(form["message"]) == 0:
        flash("You must provide a message with your comment.")
        return redirect(form["url"])

    # Gravatar?
    gravatar = Comment.gravatar(form["contact"])

    # Are they submitting?
    if form["action"] == "submit":
        Comment.add_comment(
            thread=thread,
            uid=g.info["session"]["uid"],
            ip=remote_addr(),
            time=int(time.time()),
            image=gravatar,
            name=form["name"],
            subject=form["subject"],
            message=form["message"],
            url=form["url"],
        )

        # Are we subscribing to the thread?
        if form["subscribe"] == "true":
            email = form["contact"]
            if "@" in email:
                Comment.add_subscriber(thread, email)
                flash("You have been subscribed to future comments on this page.")

        flash("Your comment has been added!")
        return redirect(form["url"])

    # Gravatar.
    g.info["gravatar"]    = gravatar
    g.info["preview"]     = Comment.format_message(form["message"])
    g.info["pretty_time"] = pretty_time(Config.comment.time_format, time.time())

    g.info.update(form)
    return template("comment/preview.html")
Example #4
0
def send():
    """Submitting the contact form."""
    name = request.form.get("name", "") or "Anonymous"
    email = request.form.get("email", "")
    subject = request.form.get("subject", "") or "[No Subject]"
    message = request.form.get("message", "")

    # Spam traps.
    trap1 = request.form.get("contact", "x") != ""
    trap2 = request.form.get("website", "x") != "http://"
    if trap1 or trap2:
        flash("Wanna try that again?")
        return redirect(url_for(".index"))

    # Message is required.
    if len(message) == 0:
        flash("The message is required.")
        return redirect(url_for(".index"))

    # Email looks valid?
    reply_to = None
    if "@" in email and "." in email:
        reply_to = email

    # Send the e-mail.
    send_email(to=Config.site.notify_address,
               reply_to=reply_to,
               subject="Contact Form on {}: {}".format(Config.site.site_name,
                                                       subject),
               message="""A visitor to {site_name} has sent you a message!

IP Address: {ip}
User Agent: {ua}
Referrer: {referer}
Name: {name}
E-mail: {email}
Subject: {subject}

{message}""".format(
                   site_name=Config.site.site_name,
                   ip=remote_addr(),
                   ua=request.user_agent.string,
                   referer=request.headers.get("Referer", ""),
                   name=name,
                   email=email,
                   subject=subject,
                   message=message,
               ))

    flash("Your message has been delivered.")
    return redirect(url_for("index"))
Example #5
0
def process_photo(form, filename):
    """Formats an incoming photo."""

    # Resize the photo to each of the various sizes and collect their names.
    sizes = dict()
    for size in PHOTO_SCALES.keys():
        sizes[size] = resize_photo(filename, size)

    # Remove the temp file.
    os.unlink(filename)

    # What album are the photos going to?
    album = form.get("album", "")
    new_album = form.get("new-album", None)
    new_desc = form.get("new-description", None)
    if album == "" and new_album:
        album = new_album

    # Sanitize the name.
    album = sanitize_name(album)
    if album == "":
        logger.warning(
            "Album name didn't pass sanitization! Fall back to default album name."
        )
        album = Config.photo.default_album

    # Make up a unique public key for this set of photos.
    key = random_hash()
    while photo_exists(key):
        key = random_hash()
    logger.debug("Photo set public key: {}".format(key))

    # Get the album index to manipulate ordering.
    index = get_index()

    # Update the photo data.
    if not album in index["albums"]:
        index["albums"][album] = {}
    if not "settings" in index:
        index["settings"] = dict()
    if not album in index["settings"]:
        index["settings"][album] = {
            "format": "classic",
            "description": new_desc,
        }

    index["albums"][album][key] = dict(ip=remote_addr(),
                                       author=g.info["session"]["uid"],
                                       uploaded=int(time.time()),
                                       caption=form.get("caption", ""),
                                       description=form.get("description", ""),
                                       **sizes)

    # Maintain a photo map to album.
    index["map"][key] = album

    # Add this pic to the front of the album.
    if not album in index["photo-order"]:
        index["photo-order"][album] = []
    index["photo-order"][album].insert(0, key)

    # If this is a new album, add it to the front of the album ordering.
    if not album in index["album-order"]:
        index["album-order"].insert(0, album)

    # Set the album cover for a new album.
    if not album in index["covers"] or len(index["covers"][album]) == 0:
        index["covers"][album] = key

    # Save changes to the index.
    write_index(index)

    return dict(success=True, photo=key)
Example #6
0
def update():
    """Post/edit a blog entry."""

    # Get our available avatars.
    g.info["avatars"] = Blog.list_avatars()
    g.info["userpic"] = User.get_picture(uid=g.info["session"]["uid"])

    # Default vars.
    g.info.update(dict(
        post_id="",
        fid="",
        author=g.info["session"]["uid"],
        subject="",
        body="",
        format="markdown",
        avatar="",
        categories="",
        privacy=Config.blog.default_privacy,
        sticky=False,
        emoticons=True,
        comments=Config.blog.allow_comments,
        preview=False,
    ))

    # Editing an existing post?
    post_id = request.args.get("id", request.form.get("id", None))
    if post_id:
        post_id = Blog.resolve_id(post_id, drafts=True)
        if post_id:
            logger.info("Editing existing blog post {}".format(post_id))
            post = Blog.get_entry(post_id)
            g.info["post_id"] = post_id
            g.info["post"] = post

            # Copy fields.
            for field in ["author", "fid", "subject", "time", "format",
                          "body", "avatar", "categories", "privacy",
                          "sticky", "emoticons", "comments"]:
                g.info[field] = post[field]

    # Are we SUBMITTING the form?
    if request.method == "POST":
        action = request.form.get("action")

        # Get all the fields from the posted params.
        g.info["post_id"] = request.form.get("id")
        for field in ["fid", "subject", "format", "body", "avatar", "categories", "privacy"]:
            g.info[field] = request.form.get(field)
        for boolean in ["sticky", "emoticons", "comments"]:
            g.info[boolean] = True if request.form.get(boolean, None) == "true" else False
        g.info["author"] = int(g.info["author"])

        # What action are they doing?
        if action == "preview":
            g.info["preview"] = True

            # Render markdown?
            if g.info["format"] == "markdown":
                g.info["rendered_body"] = render_markdown(g.info["body"])
            else:
                g.info["rendered_body"] = g.info["body"]

            # Render emoticons.
            if g.info["emoticons"]:
                g.info["rendered_body"] = Emoticons.render(g.info["rendered_body"])

        elif action == "publish":
            # Publishing! Validate inputs first.
            invalid = False
            if len(g.info["body"]) == 0:
                invalid = True
                flash("You must enter a body for your blog post.")
            if len(g.info["subject"]) == 0:
                invalid = True
                flash("You must enter a subject for your blog post.")

            # Resetting the post's time stamp?
            if not request.form.get("id") or request.form.get("reset-time"):
                g.info["time"] = float(time.time())
            else:
                g.info["time"] = float(request.form.get("time", time.time()))

            # Format the categories.
            tags = []
            for tag in g.info["categories"].split(","):
                tags.append(tag.strip())

            # Okay to update?
            if invalid is False:
                new_id, new_fid = Blog.post_entry(
                    post_id    = g.info["post_id"],
                    epoch      = g.info["time"],
                    author     = g.info["author"],
                    subject    = g.info["subject"],
                    fid        = g.info["fid"],
                    avatar     = g.info["avatar"],
                    categories = tags,
                    privacy    = g.info["privacy"],
                    ip         = remote_addr(),
                    emoticons  = g.info["emoticons"],
                    sticky     = g.info["sticky"],
                    comments   = g.info["comments"],
                    format     = g.info["format"],
                    body       = g.info["body"],
                )

                return redirect(url_for(".entry", fid=new_fid))


    if type(g.info["categories"]) is list:
        g.info["categories"] = ", ".join(g.info["categories"])

    return template("blog/update.html")
Example #7
0
def update():
    """Post/edit a blog entry."""

    # Get our available avatars.
    g.info["avatars"] = Blog.list_avatars()
    g.info["userpic"] = User.get_picture(uid=g.info["session"]["uid"])

    # Default vars.
    g.info.update(dict(
        post_id="",
        fid="",
        author=g.info["session"]["uid"],
        subject="",
        body="",
        format="markdown",
        avatar="",
        categories="",
        privacy=Config.blog.default_privacy,
        emoticons=True,
        comments=Config.blog.allow_comments,
        month="",
        day="",
        year="",
        hour="",
        min="",
        sec="",
        preview=False,
    ))

    # Editing an existing post?
    post_id = request.args.get("id", None)
    if post_id:
        post_id = Blog.resolve_id(post_id)
        if post_id:
            logger.info("Editing existing blog post {}".format(post_id))
            post = Blog.get_entry(post_id)
            g.info["post_id"] = post_id
            g.info["post"] = post

            # Copy fields.
            for field in ["author", "fid", "subject", "format", "format",
                          "body", "avatar", "categories", "privacy",
                          "emoticons", "comments"]:
                g.info[field] = post[field]

            # Dissect the time.
            date = datetime.datetime.fromtimestamp(post["time"])
            g.info.update(dict(
                month="{:02d}".format(date.month),
                day="{:02d}".format(date.day),
                year=date.year,
                hour="{:02d}".format(date.hour),
                min="{:02d}".format(date.minute),
                sec="{:02d}".format(date.second),
            ))

    # Are we SUBMITTING the form?
    if request.method == "POST":
        action = request.form.get("action")

        # Get all the fields from the posted params.
        g.info["post_id"] = request.form.get("id")
        for field in ["fid", "subject", "format", "body", "avatar", "categories", "privacy"]:
            g.info[field] = request.form.get(field)
        for boolean in ["emoticons", "comments"]:
            g.info[boolean] = True if request.form.get(boolean, None) == "true" else False
        for number in ["author", "month", "day", "year", "hour", "min", "sec"]:
            g.info[number] = int(request.form.get(number, 0))

        # What action are they doing?
        if action == "preview":
            g.info["preview"] = True

            # Render markdown?
            if g.info["format"] == "markdown":
                g.info["rendered_body"] = render_markdown(g.info["body"])
            else:
                g.info["rendered_body"] = g.info["body"]

            # Render emoticons.
            if g.info["emoticons"]:
                g.info["rendered_body"] = Emoticons.render(g.info["rendered_body"])

        elif action == "publish":
            # Publishing! Validate inputs first.
            invalid = False
            if len(g.info["body"]) == 0:
                invalid = True
                flash("You must enter a body for your blog post.")
            if len(g.info["subject"]) == 0:
                invalid = True
                flash("You must enter a subject for your blog post.")

            # Make sure the times are valid.
            date = None
            try:
                date = datetime.datetime(
                    g.info["year"],
                    g.info["month"],
                    g.info["day"],
                    g.info["hour"],
                    g.info["min"],
                    g.info["sec"],
                )
            except ValueError as e:
                invalid = True
                flash("Invalid date/time: " + str(e))

            # Format the categories.
            tags = []
            for tag in g.info["categories"].split(","):
                tags.append(tag.strip())

            # Okay to update?
            if invalid is False:
                # Convert the date into a Unix time stamp.
                epoch = float(date.strftime("%s"))

                new_id, new_fid = Blog.post_entry(
                    post_id    = g.info["post_id"],
                    epoch      = epoch,
                    author     = g.info["author"],
                    subject    = g.info["subject"],
                    fid        = g.info["fid"],
                    avatar     = g.info["avatar"],
                    categories = tags,
                    privacy    = g.info["privacy"],
                    ip         = remote_addr(),
                    emoticons  = g.info["emoticons"],
                    comments   = g.info["comments"],
                    format     = g.info["format"],
                    body       = g.info["body"],
                )

                return redirect(url_for(".entry", fid=new_fid))


    if type(g.info["categories"]) is list:
        g.info["categories"] = ", ".join(g.info["categories"])

    return template("blog/update.html")
Example #8
0
def process_photo(form, filename):
    """Formats an incoming photo."""

    # Resize the photo to each of the various sizes and collect their names.
    sizes = dict()
    for size in PHOTO_SCALES.keys():
        sizes[size] = resize_photo(filename, size)

    # Remove the temp file.
    os.unlink(filename)

    # What album are the photos going to?
    album     = form.get("album", "")
    new_album = form.get("new-album", None)
    new_desc  = form.get("new-description", None)
    if album == "" and new_album:
        album = new_album

    # Sanitize the name.
    album = sanitize_name(album)
    if album == "":
        logger.warning("Album name didn't pass sanitization! Fall back to default album name.")
        album = Config.photo.default_album

    # Make up a unique public key for this set of photos.
    key = random_hash()
    while photo_exists(key):
        key = random_hash()
    logger.debug("Photo set public key: {}".format(key))

    # Get the album index to manipulate ordering.
    index = get_index()

    # Update the photo data.
    if not album in index["albums"]:
        index["albums"][album] = {}
    if not "settings" in index:
        index["settings"] = dict()
    if not album in index["settings"]:
        index["settings"][album] = {
            "format": "classic",
            "description": new_desc,
        }

    index["albums"][album][key] = dict(
        ip=remote_addr(),
        author=g.info["session"]["uid"],
        uploaded=int(time.time()),
        caption=form.get("caption", ""),
        description=form.get("description", ""),
        **sizes
    )

    # Maintain a photo map to album.
    index["map"][key] = album

    # Add this pic to the front of the album.
    if not album in index["photo-order"]:
        index["photo-order"][album] = []
    index["photo-order"][album].insert(0, key)

    # If this is a new album, add it to the front of the album ordering.
    if not album in index["album-order"]:
        index["album-order"].insert(0, album)

    # Set the album cover for a new album.
    if not album in index["covers"] or len(index["covers"][album]) == 0:
        index["covers"][album] = key

    # Save changes to the index.
    write_index(index)

    return dict(success=True, photo=key)
Example #9
0
def track_visit(request, session):
    """Main logic to track and log visitor details."""

    # Get their tracking cookie value. The value will either be their HTTP
    # referrer (if exists and valid) or else a "1".
    cookie = session.get("tracking")
    addr = remote_addr()
    values = dict()  # Returnable traffic values

    # Log hit counts. We need four kinds:
    # - Unique today   - Unique total
    # - Hits today     - Hits total
    today = pretty_time("%Y-%m-%d", time.time())
    files = {
        "unique/{}".format(today): "unique_today",
        "unique/total": "unique_total",
        "hits/{}".format(today): "hits_today",
        "hits/total": "hits_total",
    }

    # Go through the hit count files. Update them only if their tracking
    # cookie was not present.
    for file, key in files.items():
        dbfile = "traffic/{}".format(file)
        if file.startswith("hits"):
            # Hit file is just a simple counter.
            db = dict(hits=0)
            if JsonDB.exists(dbfile):
                db = JsonDB.get(dbfile)
                if db is None:
                    db = dict(hits=0)

            # Update it?
            if not cookie:
                db["hits"] += 1
                JsonDB.commit(dbfile, db)

            # Store the copy.
            values[key] = db["hits"]
        else:
            # Unique file is a collection of IP addresses.
            db = dict()
            if JsonDB.exists(dbfile):
                db = JsonDB.get(dbfile)
                if db is None:
                    db = dict()

            # Update with their IP?
            if not cookie and not addr in db:
                db[addr] = time.time()
                JsonDB.commit(dbfile, db)

            # Store the copy.
            values[key] = len(db.keys())

    # Log their HTTP referrer.
    referrer = "1"
    if request.referrer:
        # Branch and check this.
        referrer = log_referrer(request, request.referrer)
        if not referrer:
            # Wasn't a valid referrer.
            referrer = "1"

    # Set their tracking cookie.
    if not cookie:
        cookie = referrer
        session["tracking"] = cookie

    return values