home » zplus/freepost.git
ID: 7995288e1d11edd4292817603b97ef12c83a9bc7
1094 lines — 31K — View raw


   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
#!./venv/bin/python3

import bleach
import bottle
import configparser
import dateutil.parser
import functools
import hashlib
import importlib
import json
import markdown
import timeago
import urllib3
import yaml
from datetime import datetime, timezone
from bottle import abort, get, jinja2_template as template, post, redirect, request, response, static_file
from urllib.parse import urlparse

# This is used to export the bottle object for a WSGI server
# See passenger_wsgi.py
application = bottle.app ()

# Load user settings for this app
with open ('settings.yaml', encoding='UTF-8') as file:
    settings = yaml.safe_load (file)

# Directories to search for app templates
bottle.TEMPLATE_PATH = [ './freepost/templates' ]

# Custom settings and functions for templates
template = functools.partial (
    template,
    template_settings = {
        'filters': {
            'ago': lambda date: timeago.format(date),
            'datetime': lambda date: date, #date.strftime('%b %-d, %Y - %H:%M%p%z%Z'),
            # TODO this should be renamed. It's only a way to pretty print dates
            'title': lambda date: dateutil.parser.parse(date).strftime('%b %-d, %Y - %H:%M%z%Z'),
            # Convert markdown to plain text
            'md2txt': lambda text: bleach.clean (markdown.markdown(text),
                                                 tags=[], attributes={}, strip=True),
            # Convert markdown to html
            'md2html': lambda text: bleach.clean(
                markdown.markdown(
                    text,
                    # https://python-markdown.github.io/extensions/
                    extensions=[ 'extra', 'admonition', 'nl2br', 'smarty' ],
                    output_format='html5'),
                tags = list(bleach.sanitizer.ALLOWED_TAGS) + [ 'br', 'img', 'p', 'pre', 'h1', 'h2', 'h3', 'hr' ]),
            # Get the domain part of a URL
            'netloc': lambda url: urlparse (url).netloc
        },
        'globals': {
            'new_messages': lambda user_id: database.count_unread_messages (user_id),
            'now': lambda: datetime.now (timezone.utc),
            'request': request,
            # Return a setting from 'settings.yaml'
            'settings': lambda section, key: settings[section][key],
            # Get the current user of the session
            'session_user': lambda: session.user (),
            # Split a string of topics into a list
            'split_topics': lambda topics: [ topic for topic in topics.split (' ') ] if topics else [],
            'url': application.get_url,
        },
        'autoescape': True
    })

bleach.sanitizer.ALLOWED_ATTRIBUTES.update ({
    'img': [ 'src' ]
})

from freepost import database, mail, session

# Decorator.
# Make sure user is logged in
def requires_login(controller):
    def wrapper(*args, **kwargs):
        session_token = request.get_cookie(
            key    = settings['session']['name'],
            secret = settings['cookies']['secret'])

        if database.is_valid_session(session_token):
            return controller(*args, **kwargs)
        else:
            redirect(application.get_url('login'))

    return wrapper

# Decorator.
# Make sure user is logged out
def requires_logout(controller):
    def wrapper(*args, **kwargs):
        session_token = request.get_cookie(
            key    = settings['session']['name'],
            secret = settings['cookies']['secret'])

        if database.is_valid_session(session_token):
            redirect(application.get_url('user_settings'))
        else:
            return controller(*args, **kwargs)

    return wrapper

# Routes

@get ('/', name='homepage')
def homepage ():
    """
    Display homepage with posts sorted by 'hot'.
    """

    # Sort order
    sort = request.query.sort or 'hot'

    # Page number
    page = int (request.query.page or 0)

    if page < 0:
        redirect (application.get_url ('homepage'))

    user = session.user ()

    if sort in [ 'hot', 'new' ]:
        posts = database.get_posts (
                    page, user['id'] if user else None,
                    sort)
    else:
        posts = []

    # Disable browser caching
    # Fix issue: https://notabug.org/zPlus/freepost/issues/80
    response.set_header('cache-control', 'no-cache, no-store, must-revalidate')
    response.set_header('pragma', 'no-cache')
    response.set_header('expires', '0')

    return template ('homepage.html', posts=posts, sort=sort)

# TODO implement this
@get ('/topic/<name>', name='topic')
def topic (name):
    """
    Display posts by topic.
    """

    # Sort order
    sort = request.query.sort or 'hot'

    # Page number
    page = int (request.query.page or 0)

    if page < 0:
        redirect (application.get_url ('homepage'))

    user = session.user ()

    if sort in [ 'hot', 'new' ]:
        posts = database.get_posts (
                    page, user['id'] if user else None,
                    sort, name)
    else:
        posts = []

    return template (
        'homepage.html',
        topic=name,
        posts=posts)

@get ('/about', name='about')
def about ():
    """
    Display "About" page.
    """

    return template ('about.html')

@get ('/login', name='login')
@requires_logout
def login ():
    """
    The login page.
    """

    return template ('login.html')

@post ('/login')
@requires_logout
def login_check ():
    """
    Check login form.
    """

    username = request.forms.getunicode ('username')
    password = request.forms.getunicode ('password')
    remember = 'remember' in request.forms

    if not username or not password:
        return template (
            'login.html',
            flash = 'Bad login!')

    # Check if user exists
    user = database.check_user_credentials (username, password)

    # Username/Password not working
    if not user:
        return template (
            'login.html',
            flash = 'Bad login!')

    # Delete any existing "reset token"
    database.delete_password_reset_token (user['id'])

    # Start new session
    session.start (user['id'], remember)

    # Redirect logged in user to preferred feed
    if user['preferred_feed'] == 'new':
        redirect (application.get_url ('homepage') + '?sort=new')
    else:
        redirect (application.get_url ('homepage'))

@get ('/register', name='register')
@requires_logout
def register ():
    """
    Register new account.
    """

    return template ('register.html')

@post ('/register')
@requires_logout
def register_new_account ():
    """
    Check form for creating new account.
    """

    abort()

    username = request.forms.getunicode ('username')
    password = request.forms.getunicode ('password')

    # Normalize username
    username = username.strip ()

    # Check if username already exists.
    # Use case-insensitive match to prevent two similar usernames.
    if len (username) == 0 or database.username_exists (username, case_sensitive=False):
        return template (
            'register.html',
            flash='Name taken, please choose another.')

    # Password too short?
    if len (password) < 8:
        return template (
            'register.html',
            flash = 'Password too short')

    # Username OK, Password OK: create new user
    database.new_user (username, password)

    # Retrieve user (check if it was created)
    user = database.check_user_credentials (username, password)

    # Something bad happened...
    if user is None:
        return template (
            'register.html',
            flash = 'An error has occurred, please try again.')

    # Start session...
    session.start (user['id'])

    # ... and go to the homepage of the new user
    redirect (application.get_url ('user_settings'))

@get ('/logout', name='logout')
@requires_login
def logout ():
    """
    Logout user and return to homepage.
    """

    session.close ()

    redirect (application.get_url ('homepage'))

@get ('/password_reset', name='password_reset')
@requires_logout
def password_reset ():
    """
    Display form to reset users password.
    """

    return template ('login_reset.html')

@post ('/password_reset', name='password_reset_send_code')
@requires_logout
def password_reset_send_code ():
    """
    Validate form for resetting password, and if valid send secret
    code via email.
    """

    username = request.forms.getunicode('username')
    email = request.forms.getunicode('email')

    if not username or not email:
        redirect(application.get_url('change_password'))

    user = database.get_user_by_username(username)

    if not user:
        redirect(application.get_url('change_password'))

    # Make sure the given email matches the one that we have in the database
    if user['email'] != email:
        redirect(application.get_url('change_password'))

    # Is there another valid token already (from a previous request)?
    # If yes, do not send another one (to prevent multiple requests or spam)
    if database.is_password_reset_token_valid(user['id']):
        redirect(application.get_url('change_password'))

    # Generate secret token to send via email
    secret_token = random.ascii_string(32)

    # Add token to database
    database.set_password_reset_token(user['id'], secret_token)

    # Send token via email
    client_ip     = request.environ.get('HTTP_X_FORWARDED_FOR') or \
                    request.environ.get('REMOTE_ADDR')
    email_to      = user['email']
    email_subject = 'freepost password reset'
    email_body    = template(
                        'email/password_reset.txt',
                        ip=client_ip,
                        secret_token=secret_token)

    mail.send(email_to, email_subject, email_body)

    redirect(application.get_url('change_password'))

@get ('/change_password', name='change_password')
@requires_logout
def change_password ():
    """
    After the secret code was sent via email, display this form where
    the user can insert the secret code + new password.
    """

    return template ('login_change_password.html')

@post ('/change_password', name='validate_new_password')
@requires_logout
def validate_new_password ():
    """
    Validate the new password, check the secret code, and if everything
    is OK change the user password.
    """

    username     = request.forms.getunicode('username')
    email        = request.forms.getunicode('email')
    password     = request.forms.getunicode('password')
    secret_token = request.forms.getunicode('token')

    # We must have all fields
    if not username or not email or not password or not secret_token:
        redirect(application.get_url('login'))

    # Password too short?
    if len (password) < 8:
        return template (
            'login_change_password.html',
            flash = 'Password must be at least 8 characters long')

    # OK, everything should be fine now. Reset user password.
    database.reset_password(username, email, password, secret_token)

    # Check if the password was successfully reset
    user = database.check_user_credentials (username, password)

    # Username/Password not working
    if not user:
        redirect (application.get_url ('login'))

    # Everything matched!
    # Notify user of password change.
    email_to      = user['email']
    email_subject = 'freepost password changed'
    email_body    = template ('email/password_changed.txt')

    mail.send (email_to, email_subject, email_body)

    # Start new session and redirect user
    session.start (user['id'])
    redirect (application.get_url ('user_settings'))

@get ('/user/settings', name='user_settings')
@requires_login
def user_settings ():
    """
    A user's personal page.
    """

    return template ('user_settings.html')

@post ('/user/settings')
@requires_login
def update_user_settings ():
    """
    Update user info (about, email, ...).
    """

    user = session.user ()

    about = request.forms.getunicode ('about')
    email = request.forms.getunicode ('email')
    preferred_feed = request.forms.getunicode ('preferred_feed')

    if about is None or email is None:
        redirect (application.get_url ('user_settings'))

    if preferred_feed not in [ 'hot', 'new' ]:
        preferred_feed = 'hot'

    # Update user info in the database
    database.update_user (user['id'], about, email, False, preferred_feed)

    redirect (application.get_url ('user_settings'))

@get ('/user_activity/posts')
@requires_login
def user_posts ():
    user = session.user ()
    posts = database.get_user_posts (user['id'])

    return template ('user_posts.html', posts=posts)

@get ('/user_activity/comments')
@requires_login
def user_comments ():
    user = session.user ()
    comments = database.get_user_comments (user['id'])

    return template ('user_comments.html', comments=comments)

@get ('/user_activity/replies', name='user_replies')
@requires_login
def user_replies ():
    user = session.user ()
    replies = database.get_user_replies (user['id'])

    database.set_replies_as_read (user['id'])

    return template ('user_replies.html', replies=replies)

@get ('/user/public/<username>', name='user_public')
def user_public_homepage (username):
    """
    Display a publicly accessible page with public info about the user.
    """

    account = database.get_user_by_username (username)

    if account is None:
        redirect (application.get_url ('user_settings'))

    return template ('user_public_homepage.html', account=account)

@get('/c', name='communities')
def communities():
    """
    List communities.
    """

    communities_list = database.get_communities_list()

    return template('communities.html', communities=communities_list)

@post('/c')
@requires_login
def community_create():
    name = request.forms.getunicode('community_name').strip().replace(' ', '').lower()

    if len(name) < 3 or len(name) > 100:
        redirect(application.get_url('communities'))

    user = session.user()

    community = database.get_community(name)
    if community:
        redirect(application.get_url('community', cmty=name))

    database.create_community(name)

    community = database.get_community(name)

    # The community wasn't created for some reasons?
    if not community:
        redirect(application.get_url('communities'))
    else:
        database.add_community_member(community['id'], user['id'], True)
        redirect(application.get_url('community', cmty=name))

@get('/c/<cmty>', name='community')
def community(cmty):
    """
    Show a community.
    """

    # Sort order
    sort = request.query.sort or 'hot'

    user = session.user()
    cmty = database.get_community(cmty)

    if not cmty:
        abort(404, "This community doesn't exist.")

    mods = database.get_community_mods(cmty['id'])

    try:
        is_moderator = database.is_community_moderator(cmty['id'], user['id'])
        is_member = database.is_community_member(cmty['id'], user['id'])
    except:
        is_moderator = False
        is_member = False

    # Page number
    page = int(request.query.page or 0)

    if page < 0:
        redirect(application.get_url('homepage'))

    if sort in [ 'hot', 'new' ]:
        posts = database.get_posts(
                    page, user['id'] if user else None, sort,
                    topic=None, community_id=cmty['id'])
    else:
        posts = []

    return template(
        'community.html',
        community=cmty['name'],
        community_data=cmty,
        is_member=is_member,
        is_moderator=is_moderator,
        moderators=mods,
        posts=posts,
        sort=sort)

@get('/c/<community>/administration', name='community_administration')
@requires_login
def community_administration(community):
    """
    Administration page of community.
    """

    user = session.user()
    community = database.get_community(community)

    try:
        is_moderator = database.is_community_moderator(community['id'], user['id'])
        assert is_moderator
    except:
        redirect(application.get_url('homepage'))
        abort()

    mods = database.get_community_mods(community['id'])

    return template(
        'community_administration.html',
        community=community,
        moderators=mods)

@post('/c/<community>/administration')
@requires_login
def community_administration_update(community):
    """
    Update community settings.
    """

    user = session.user()
    community = database.get_community(community)

    try:
        is_moderator = database.is_community_moderator(community['id'], user['id'])
        assert is_moderator
    except:
        redirect(application.get_url('homepage'))
        abort()

    # Truncate at 1K
    description = request.forms.getunicode('description').strip()[:1024]
    allow_new_posts = request.forms.getunicode('allow_new_posts') == 'yes'

    database.update_community_settings(
        community['id'], description, allow_new_posts)

    redirect(application.get_url('community', cmty=community['name']))

@post('/c/<community>')
@requires_login
def community_join(community):
    user = session.user()
    cmty = database.get_community(community)

    if not cmty:
        abort(500, "Community doesn't exist.")
        return

    if 'join' in request.forms:
        database.add_community_member(cmty['id'], user['id'])

    if 'leave' in request.forms:
        database.remove_community_member(cmty['id'], user['id'])

    redirect(application.get_url('community', cmty=community))

@get('/post/<hash_id>', name='post')
def post_thread(hash_id):
    """
    Display a single post with all its comments.
    """

    user = session.user()
    post = database.get_post(hash_id, user['id'] if user else None)
    comments = database.get_post_comments(post['id'], user['id'] if user else None)
    topics = database.get_post_topics (post['id'])

    # Group comments by parent
    comments_tree = {}

    for comment in comments:
        if comment['parentId'] is None:
            if 0 not in comments_tree:
                comments_tree[0] = []

            comments_tree[0].append(dict(comment))
        else:
            if comment['parentId'] not in comments_tree:
                comments_tree[comment['parentId']] = []

            comments_tree[comment['parentId']].append(dict(comment))

    # Build ordered list of comments (recourse tree)
    def children (parent_id = 0, depth = 0):
        temp_comments = []

        if parent_id in comments_tree:
            for comment in comments_tree[parent_id]:
                comment['depth'] = depth
                temp_comments.append (comment)

                temp_comments.extend (children (comment['id'], depth + 1))

        return temp_comments

    comments = children()

    # Show posts/comments Markdown instead of rendered text
    show_source = 'source' in request.query

    # Disable browser caching
    # Fix issue: https://notabug.org/zPlus/freepost/issues/80
    response.set_header('cache-control', 'no-cache, no-store, must-revalidate')
    response.set_header('pragma', 'no-cache')
    response.set_header('expires', '0')

    return template (
        'post.html',
        community=post['community_name'],
        post=post,
        comments=comments,
        topics=topics,
        show_source=show_source,
        votes = {
            'post': {},
            'comment': {}
        })

@post('/post/<hash_id>')
@requires_login
def new_comment(hash_id):
    # The comment text
    comment = request.forms.getunicode('new_comment').strip()

    # Empty comment?
    if len(comment) == 0:
        redirect(application.get_url('post', hash_id=hash_id))

    # Retrieve the post
    post = database.get_post (hash_id)

    # Does post exist?
    if not post:
        redirect (application.get_url ('homepage'))

    user = session.user ()

    comment_hash_id = database.new_comment (comment, hash_id, user['id'], post['userId'])

    # Retrieve new comment
    comment = database.get_comment (comment_hash_id)

    # Automatically add an upvote for the original poster
    database.vote_comment (comment['id'], user['id'], +1)

    redirect (application.get_url ('post', hash_id=hash_id))

@get ('/edit/post/<hash_id>', name='edit_post')
@requires_login
def edit_post(hash_id):
    user = session.user()
    post = database.get_post(hash_id, user['id'])

    # Make sure the session user is the actual poster/commenter
    if post['userId'] != user['id']:
        redirect(application.get_url('post', hash_id=hash_id))

    return template('edit_post.html', community=post['community_name'], post=post)

@post ('/edit/post/<hash_id>')
@requires_login
def edit_post_check(hash_id):
    user = session.user()
    post = database.get_post(hash_id, user['id'])

    # Make sure the session user is the actual poster/commenter
    if post['userId'] != user['id']:
        redirect(application.get_url('homepage'))

    # MUST have a title. If empty, use original title
    title = request.forms.getunicode('title').strip()
    if len (title) == 0: title = post['title']
    link  = request.forms.getunicode('link').strip() if 'link' in request.forms else ''
    text  = request.forms.getunicode('text').strip() if 'text' in request.forms else ''

    # If there is a URL, make sure it has a "scheme"
    if len(link) > 0 and urlparse(link).scheme == '':
        link = 'http://' + link

    # Update post
    database.update_post(title, link, text, hash_id, user['id'])

    redirect(application.get_url ('post', hash_id=hash_id))

@get ('/edit/comment/<hash_id>', name='edit_comment')
@requires_login
def edit_comment (hash_id):
    user = session.user ()
    comment = database.get_comment (hash_id, user['id'])

    # Make sure the session user is the actual poster/commenter
    if comment['userId'] != user['id']:
        redirect (application.get_url ('post', hash_id=comment['postHashId']))

    return template ('edit_comment.html', comment=comment)

@post ('/edit/comment/<hash_id>')
@requires_login
def edit_comment_check (hash_id):
    user = session.user ()
    comment = database.get_comment (hash_id, user['id'])

    # Make sure the session user is the actual poster/commenter
    if comment['userId'] != user['id']:
        redirect (application.get_url ('homepage'))

    text = request.forms.getunicode ('text').strip () if 'text' in request.forms else ''

    # Only update if the text is not empty
    if len (text) > 0:
        database.update_comment (text, hash_id, user['id'])

    redirect (application.get_url ('post', hash_id=comment['postHashId']) + '#comment-' + hash_id)

@get('/c/<community>/submit', name='submit')
@requires_login
def submit(community):
    """
    Submit a new post.
    """

    return template('submit.html', community=community)

@post('/c/<community>/submit')
@requires_login
def submit_check(community):
    """
    Check submission of new post.
    """

    # Somebody sent a <form> without a title???
    if 'title' not in request.forms:
        abort()

    user = session.user()

    # Retrieve title
    title = request.forms.getunicode('title').strip()

    # Bad title?
    if len(title) == 0:
        return template('submit.html', community=community, flash='Title is missing.')

    # Retrieve link
    link = request.forms.getunicode('link').strip()

    if len (link) > 0:
        # If there is a URL, make sure it has a "scheme"
        if urlparse (link).scheme == '':
            link = 'http://' + link

        # Check if this link was already posted in order to avoid duplicate posting.
        previous_posts = database.link_exists(link)
        if previous_posts:
            posts_list = ''.join([
                '<li><a href="{link}">{title}</a></li>'.format(
                    link  = application.get_url('post', hash_id=post['hashId']),
                    title = post['title'])
                for post in previous_posts ])

            return template('submit.html',
                            community=community,
                            flash='This link was already submitted:<ul>{posts}</ul>'.format(posts=posts_list))

    # Retrieve topics
    # topics = request.forms.getunicode ('topics')

    # Retrieve text
    text = request.forms.getunicode('text')

    # Retrieve the community
    community = database.get_community(community)

    if not community:
        abort(500, "Community doesn't exist.")
        return

    # Does this community allow new posts?
    if not community['allow_new_posts']:
        return template('submit.html',
                        community=community['name'],
                        flash='This community does not allow new posts.')

    # Add the new post
    post_hash_id = database.new_post(title, link, text, user['id'], community['id'])

    # Retrieve the new post just created
    post = database.get_post(post_hash_id)

    # Add topics for this post
    # database.replace_post_topics (post['id'], topics)

    # Automatically add an upvote for the original poster
    database.vote_post(post['id'], user['id'], +1)

    # Posted. Now go the new post's page
    redirect(application.get_url('post', hash_id=post_hash_id))

@get ('/reply/<hash_id>', name='reply')
@requires_login
def reply (hash_id):
    user = session.user ()

    # The comment to reply to
    comment = database.get_comment (hash_id)

    # Does the comment exist?
    if not comment:
        redirect (application.get_url ('homepage'))

    return template ('reply.html', comment=comment)

@post ('/reply/<hash_id>')
@requires_login
def reply_check (hash_id):
    user = session.user ()

    # The comment to reply to
    comment = database.get_comment (hash_id)

    # The text of the reply
    text = request.forms.getunicode ('text').strip ()

    # Empty comment. Redirect to parent post
    if len (text) == 0:
        redirect (application.get_url ('post', hash_id=comment['postHashId']))

    # We have a text, add the reply and redirect to the new reply
    reply_hash_id = database.new_comment (
                        text, comment['postHashId'], user['id'],
                        comment['userId'], comment['id'])

    # Retrieve new comment
    comment = database.get_comment (reply_hash_id)

    # Automatically add an upvote for the original poster
    database.vote_comment (comment['id'], user['id'], +1)

    redirect (application.get_url ('post', hash_id=comment['postHashId']) + '#comment-' + reply_hash_id)

@post ('/vote', name='vote')
@requires_login
def vote ():
    """
    Handle upvotes and downvotes.
    """

    user = session.user ()

    # Vote a post
    if request.forms.getunicode ('target') == 'post':
        # Retrieve the post
        post = database.get_post (request.forms.getunicode ('post'), user['id'])

        if not post:
            return

        # If user clicked the "upvote" button...
        if request.forms.getunicode ('updown') == 'up':
            # If user has upvoted this post before...
            if post['user_vote'] == 1:
                # Remove +1
                database.vote_post (post['id'], user['id'], -1)
            # If user has downvoted this post before...
            elif post['user_vote'] == -1:
                # Change vote from -1 to +1
                database.vote_post (post['id'], user['id'], +2)
            # If user hasn't voted this post...
            else:
                # Add +1
                database.vote_post (post['id'], user['id'], +1)

        # If user clicked the "downvote" button...
        if request.forms.getunicode ('updown') == 'down':
            # If user has downvoted this post before...
            if post['user_vote'] == -1:
                # Remove -1
                database.vote_post (post['id'], user['id'], +1)
            # If user has upvoted this post before...
            elif post['user_vote'] == 1:
                # Change vote from +1 to -1
                database.vote_post (post['id'], user['id'], -2)
            # If user hasn't voted this post...
            else:
                # Add -1
                database.vote_post (post['id'], user['id'], -1)

    # Vote a comment
    if request.forms.getunicode ('target') == 'comment':
        # Retrieve the comment
        comment = database.get_comment (request.forms.getunicode ('comment'), user['id'])

        if not comment:
            return

        # If user clicked the "upvote" button...
        if request.forms.getunicode ('updown') == 'up':
            # If user has upvoted this comment before...
            if comment['user_vote'] == 1:
                # Remove +1
                database.vote_comment (comment['id'], user['id'], -1)
            # If user has downvoted this comment before...
            elif comment['user_vote'] == -1:
                # Change vote from -1 to +1
                database.vote_comment (comment['id'], user['id'], +2)
            # If user hasn't voted this comment...
            else:
                # Add +1
                database.vote_comment (comment['id'], user['id'], +1)

        # If user clicked the "downvote" button...
        if request.forms.getunicode ('updown') == 'down':
            # If user has downvoted this comment before...
            if comment['user_vote'] == -1:
                # Remove -1
                database.vote_comment (comment['id'], user['id'], +1)
            # If user has upvoted this comment before...
            elif comment['user_vote'] == 1:
                # Change vote from +1 to -1
                database.vote_comment (comment['id'], user['id'], -2)
            # If user hasn't voted this comment...
            else:
                # Add -1
                database.vote_comment (comment['id'], user['id'], -1)

@get ('/search', name='search')
def search ():
    """
    Search content on this instance, and display the results.
    """

    # Get the search query
    query = request.query.getunicode ('q')

    # Get the offset
    page = int (request.query.getunicode ('page') or 0)

    if page < 0:
        return "Page cannot be less than zero."

    # Page increment
    if 'next' in request.query:
        page += 1
    if 'previous' in request.query:
        page -= 1

    # Results order
    sort = request.query.getunicode ('sort')
    if sort not in [ 'newest', 'points' ]:
        sort = 'newest'

    posts = database.search (query, sort=sort, page=page) or []

    return template ('search.html', posts=posts)

@get ('/rss')
def rss_default ():
    """
    Redirect base RSS URL to default "hot" feed.
    """

    return redirect (application.get_url ('rss', sorting='hot'))

@get ('/rss/<sorting>', name='rss')
def rss (sorting):
    """
    Output an RSS feed of posts.
    """

    posts = []

    # Retrieve the hostname from the HTTP request.
    # This is used to build absolute URLs in the RSS feed.
    base_url = request.urlparts.scheme + '://' + request.urlparts.netloc

    if sorting == 'new':
        posts = database.get_posts (sort='new')

    if sorting == 'hot':
        posts = database.get_posts (sort='hot')

    # Set correct Content-Type header for this RSS feed
    response.content_type = 'application/rss+xml; charset=UTF-8'

    return template ('rss.xml', base_url=base_url, posts=posts)

@get ('/rss_comments', name='rss_comments')
def rss_comments ():
    """
    Output an RSS feed of the latest comments.
    """

    # Retrieve the hostname from the HTTP request.
    # This is used to build absolute URLs in the RSS feed.
    base_url = request.urlparts.scheme + '://' + request.urlparts.netloc

    comments = database.get_latest_comments ()

    # Set correct Content-Type header for this RSS feed
    response.content_type = 'application/rss+xml; charset=UTF-8'

    return template ('rss_comments.xml', base_url=base_url, comments=comments)

@get ('/<filename:path>', name='static')
def static (filename):
    """
    Serve static files.
    """

    return static_file (filename, root='freepost/static/')