Source

pyforum / controllers / default.py

   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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
import datetime
import hashlib
import base64
import urllib2
import urllib
import json


# IDE "helper" not part of the framework
if False:
    from gluon.globals import *
    from gluon.html import *
    from gluon.http import *
    #from gluon.sqlhtml import SQLFORM, SQLTABLE, form_factory
    session = Session()
    request = Request()
    response = Response()
    # The following three lines are application-specific and used just so
    # komodo (edit) (or even other IDEs sich as Wing) "finds" the methods
    # for my classes, this does not have anyhing to do with the web2py
    # framework itself, as I am already instantiating "auth_user",
    # "stackhelper" etc in one of my models...
    from pyforum.modules.auth import CustomAuthentication as auth_user
    from pyforum.modules.forumhelper import ForumHelper as forumhelper

def index():
    if session.RUN_ONCE is None:
        cat_list = []
        cat_dict = {}
        view_info = {}
        # Get all available Categories/Forums/Hits, etc, etc in one single,
        # optimized query and determine which ones the user is allowed to view.
        # This is one of the few SQL queries that I still need to port
        # to web2py's DAL, any takers?
        sql = """
        select
            zfc.id as cat_id,
            zfc.cat_name,
            zfc.cat_desc,
            zfc.cat_visible_to,
            zfc.cat_sort,
            zf.id as forum_id,
            zf.forum_title,
            zf.forum_desc,
            zf.moderation_flag,
            zf.anonymous_viewaccess,
            zf.add_postings_access_roles,
            zf.reply_postings_access_roles,
            zf.forum_sort,
            count(nullif(zt.parent_flag='T',0)) as parents,
            count(nullif(zt.parent_flag='F',0)) as siblings,
            sum(zt.hits) as hits
        from
            zf_forum_category as zfc
                left join zf_forum as zf on zfc.id = zf.cat_id
                left join zf_topic as zt on zt.forum_id = zf.id
                and zt.disabled_flag = 0
        group by
            zf.id,
            zf.forum_title,
            zf.forum_desc,
            zf.moderation_flag,
            zf.anonymous_viewaccess,
            zf.add_postings_access_roles,
            zfc.id,
            zfc.cat_name,
            zfc.cat_desc,
            zfc.cat_visible_to,
            zfc.cat_sort,
            zf.reply_postings_access_roles,
            zf.forum_sort
        order by
            zfc.cat_sort,
            zf.forum_sort
        """
        # Returns a tuple and each tuple element containing the column values
        cats_and_forums = db.executesql(sql)
        if cats_and_forums:
            today = request.now
            now = datetime.datetime.now()
            for cat_forum in cats_and_forums:
                cat_id = cat_forum[0]
                cat_name = cat_forum[1]
                cat_desc = cat_forum[2]
                cat_visible_to_str = cat_forum[3]
                cat_sort = cat_forum[4]
                forum_id = cat_forum[5]
                forum_title = cat_forum[6]
                forum_desc = cat_forum[7]
                moderation_flag = cat_forum[8]
                anonymous_viewaccess = cat_forum[9]
                add_postings_access_roles = cat_forum[10]
                reply_postings_access_roles = cat_forum[11]
                forum_sort = cat_forum[12]
                parents = cat_forum[13]
                siblings = cat_forum[14]
                hits = cat_forum[15]
    
                cat_view_access = False
    
                cat_visible_to = cat_visible_to_str.strip().split(',')
                # Automatic access if the user is a forum admin, or if the
                # category itself is not restricted to noone (i.e. the
                # "cat_visible_to" field is empty (no roles):
                if auth_user.has_role(
                    'zAdministrator') or cat_visible_to_str.strip() == '':
                    cat_view_access = True
                else:
                    # The "key" here relies in the "auth_user.has_role(cat)"
                    cat_view_access = [
                        cat for cat in cat_visible_to
                        if auth_user.has_role(cat)] != []
    
                if cat_view_access:
                    if forum_id:
                        posts = 0
                        replies = 0
                        views = 0
    
                        if parents:
                            posts = parents
                        if siblings:
                            replies = siblings
                        if hits:
                            views = hits
                        
                        # Get Forum Last Updated Data
                        #select
                        #    zft.modifying_user_if,
                        #    zft.modifying_date,
                        #    zft.topic_id,
                        #    zft.parent_flag,
                        #    zft.parent_id
                        #from
                        #    zf_topic as zft
                        #where
                        #    zft.forum_id = **forum_id**
                        #    and zft.disabled_flag = 0
                        #order by
                        #    zft.modifying_date desc
                        #limit 1
                        #offset 0
                        where_statement = (db.zf_topic.forum_id==forum_id) & \
                        (db.zf_topic.disabled_flag==0)
                        last_update_info = db(
                            where_statement).select(
                            db.zf_topic.modifying_user_id,
                            db.zf_topic.modifying_date,
                            db.zf_topic.id,
                            db.zf_topic.parent_flag,
                            db.zf_topic.parent_id,
                            orderby=~db.zf_topic.modifying_date,
                            limitby=(0,1))
                        if last_update_info:
                            last_updated = last_update_info[0].modifying_date
                            last_updated_by = last_update_info[
                                0].modifying_user_id
                            if last_update_info[0].parent_flag:
                                last_updated_topic_id = last_update_info[0].id
                            else:
                                last_updated_topic_id = last_update_info[
                                    0].parent_id
                        else:
                            last_updated = None
                            last_updated_by = None
                            last_updated_topic_id = None
    
                        # Now, lets' set a flag to mark the "last updated"
                        # message in red (or any other visual cue) if the
                        # message is less than a day old (24 hs)
                        if last_updated:
                            # td is a timedelta object
                            td = (today - last_updated).days
                            if td == 0:
                                update_flag = True
                            else:
                                update_flag = False
                        else:
                            update_flag = False
    
                        # Now here is the deal, not everyone will be able
                        # to view/enter a particular forum, so here is when
                        # the logic applies. We'll check if the user logged
                        # in or not has the role needed note that a forum
                        # could have the role "Anonymous", which would give
                        # an anonymous user access to the forum's topics.
                        add_forum = False
                        access_roles = add_postings_access_roles.split(',') + \
                        reply_postings_access_roles.split(',')
    
                        if [role for role in access_roles \
                            if auth_user.has_role(role) or \
                            anonymous_viewaccess]:
                            add_forum = True
    
                        if add_forum:
                            if last_updated:
                                s_last_updated = last_updated.strftime(
                                    str(T('%b %d, %Y - %I:%M %p')))
                            else:
                                s_last_updated = ''
                            forum_dict = {'forum_id': forum_id,
                                          'forum_title': XML(forum_title),
                                          'forum_desc': forum_desc,
                                          'anonymous_viewaccess':
                                            anonymous_viewaccess,
                                          'posts': posts,
                                          'replies': replies,
                                          'views': views,
                                          'forum_sort': forum_sort,
                                          'last_updated': s_last_updated,
                                          'last_updated_by': last_updated_by,
                                          'last_updated_topic_id':
                                            last_updated_topic_id,
                                          'subscribed_to_forum':
                                            forumhelper.has_forum_subscription(
                                                forum_id,
                                                auth_user.get_user_id()),
                                          'update_flag': update_flag}
                            if cat_dict.has_key(cat_id):
                                cat_dict['forum_list'].append(forum_dict)
                            else:
                                cat_dict = {cat_id: cat_id,
                                            'cat_id': cat_id,
                                            'cat_name': cat_name,
                                            'cat_sort': cat_sort,
                                            'forum_list': [forum_dict],
                                            'cat_visible_to': cat_visible_to,
                                            'cat_desc': cat_desc}
                                cat_list.append(cat_dict)
                    else:
                        # Cat Visible but No Forums
                        cat_dict = {cat_id: cat_id,
                                    'cat_id': cat_id,
                                    'cat_name': cat_name,
                                    'cat_sort': cat_sort,
                                    'forum_list': [],
                                    'cat_visible_to': cat_visible_to,
                                    'cat_desc': cat_desc}
                        cat_list.append(cat_dict)
        # Here get the latest system announceemnt to display in the top line
        sys_topics = forumhelper.get_system_announcements(include_content=True)
        if len(sys_topics):
            sys_topic = sys_topics[0]
            if type(sys_topic) != type({}):
                view_info.update({'sys_topic': sys_topics[0]})
                
        return dict(cat_list=cat_list, view_info=view_info)
    else:
        # So apparently we have a new system install, redirect to the
        # appropriate page:
        redirect(URL(r=request, c='default', f='runonce'))


def runonce():
    """ This method will automatically be executed after initial install of
    the system.
    
    """
    if session.RUN_ONCE is not None:
        tmp_username = session['NEW_USER']
        tmp_passwd = session['NEW_USER_PASSWD']
        # Remove these values from the session now..
        session.RUN_ONCE = None
        session.NEW_USER_PASSWD = None
        session.RUN_ONCE = None
        return dict(tmp_username=tmp_username, tmp_passwd=tmp_passwd)
    else:
        # Just die silently..
        redirect(URL(r=request, c='default', f='index'))


def login():
    """ Handles login actions """
    custom_messages = {}
    errors = []
    isauth = False
    req = request.vars
    if req.form_submitted:
        if req.login_b:
            if auth_user.authenticate(req.auth_alias, req.passwd):
                isauth = True
            else:
                errors.append('Invalid Username or Password entered')
        else:
            redirect(URL(r=request, c='default', f='index'))
    custom_messages['errors'] = errors
    if isauth:
        # Grab the Language preferences here, and send it
        lang = forumhelper.get_member_property(
            property_name='zfmp_locale', user_id=auth_user.get_user_id(),
            default_value='')
        redirect(URL(r=request, c='default', f='index', vars=dict(lang=lang)))
    else:
        return dict(request=request, custom_messages=custom_messages)

def login_janrain():
    # Must be posted by the external calling process
    token = request.vars.token

    # Part of the Janrain API docs.
    api_params = {
    'token': token,
    'apiKey': '092eba675ac7eb1a3d6f82862984a2734c714829',
    'format': 'json',}

    # make the api call
    http_response = urllib2.urlopen('https://rpxnow.com/api/v2/auth_info',
                                urllib.urlencode(api_params))
    # read the json response
    auth_info_json = http_response.read()

    # Process the json response
    auth_info = json.loads(auth_info_json)
    # Step 4) use the response to sign the user in
    if auth_info['stat'] == 'ok':
        profile = auth_info['profile']

        # 'identifier' will always be in the payload
        # this is the unique identifier that you use to sign the user
        # in to your site
        identifier = profile['identifier']

        # These fields MAY be in the profile, but are not guaranteed. it
        # depends on the provider and their implementation.
        name = profile.get('displayName')
        email = profile.get('email')
        profile_pic_url = profile.get('photo')

        # Sign the user in.
        user_id = auth_user.authenticate_janrain(
            identifier,
            name.lower(),
            email.lower(),
            profile_pic_url)
        form_vars = {}

        # Now, update some properties
        stackhelper.put_member_property('zfmp_last_login', user_id,
                                        request.now)
        # Only update Name (zfmp_display_name) if the field is actually empty
        # 'zfmp_display_name' is the name that the user will have in the
        # system, it is an editable property and it will show in various
        # parts of the system.
        if forumhelper.get_member_property(
            'zfmp_display_name',
            name.lower(),
            '') == '':
            
            stackhelper.put_member_property('zfmp_display_name', name.lower(),
                                            name)
    else:
        # TODO: Do something more elegant than this
        #raise ValueError('An error occured: %s' % (auth_info['err']['msg']))
        form_vars = dict(login_error=auth_info['err']['msg'])
    redirect(URL(r=request, c='default', f='index', vars=form_vars))


def logout():
    if session.has_key('lang'):
        del session['lang']
    auth_user.logout()
    redirect(URL(r=request, c='default', f='index', vars=dict(lang='')))

def view_forum():
    req = request.vars
    view_info = {}
    view_info['errors'] = []
    view_info['all_topics'] = 0
    security_info = {'can_add': False, 'can_reply': False}
    user_id = auth_user.get_user_id()

    if req.remove_topics:
        forum_id = (req.forum_id)
        forum = db(db.zf_forum.id==forum_id).select()[0]
    else:
        forum_id = int(request.args[0])
        # Here handle subscription/unsubscriptions
        if len(request.args) > 1 and auth_user.is_auth():
            subscription_flag = int(request.args[1])
            is_subscription = db(
                (db.zf_member_subscriptions.subscription_id == forum_id) &
                (db.zf_member_subscriptions.user_id==user_id)).select(
                db.zf_member_subscriptions.id)
            if subscription_flag == 1: # Request Subscription
                if len(is_subscription) == 0:
                    # (new) Subscription
                    db.zf_member_subscriptions.insert(
                        user_id=user_id,
                        subscription_id=forum_id,
                        subscription_type='F', subscription_active=True)
                else:
                    # Update an existing subscription back to "true"
                    db(
                        (db.zf_member_subscriptions.subscription_id == \
                         forum_id) &
                        (db.zf_member_subscriptions.subscription_type == 'F') &
                        (db.zf_member_subscriptions.user_id == \
                         user_id)).update(subscription_active=True)
            else: # User is requesting removal (or inactivate subscription)
                if len(is_subscription) > 0:
                    db(
                        (db.zf_member_subscriptions.subscription_id == \
                         forum_id) &
                        (db.zf_member_subscriptions.user_id == \
                         user_id)).update(subscription_active=False)
        forum = db(db.zf_forum.id==forum_id).select()[0]

    # Information to pass regarding system variables, etc
    # Forum Subscription:
    view_info.update({'subscribed_to_forum':
        forumhelper.has_forum_subscription(forum_id, user_id)})
    # Max preview length:
    view_info.update({'zfsp_topic_teaser_length':
        int(forumhelper.get_system_property('zfsp_topic_teaser_length', 250))})

    # Security Checks here
    user_can_enter = True
    if not auth_user.is_auth() and not forum.anonymous_viewaccess:
        user_can_enter = False

    if user_can_enter:
        if auth_user.is_admin():
            security_info['can_add'] = True
            security_info['can_reply'] = True
        else:
            if len(forum.add_postings_access_roles):
                security_info['can_add'] = [
                    role for role in auth_user.get_roles()
                    if forum.add_postings_access_roles.find(role)] != []
            else:
                security_info['can_add'] = True

            if len(forum.reply_postings_access_roles):
                security_info['can_reply'] = [
                    role for role in auth_user.get_roles()
                    if forum.reply_postings_access_roles.find(role)] != []
            else:
                security_info['can_reply'] = True

        if req.del_topics:
            for req_var in req:
                if req_var[:10] == 'del_topic_':
                    del_topic_id = int(req[req_var])
                    db(db.zf_topic.parent_id==del_topic_id).delete() # Children
                    db(db.zf_topic.id==del_topic_id).delete() # Parent
                    view_info.update({'topics_removed': True})

        
        # Pagination Manager Part I/II
        start = int(req.get('start', 0))
        #try:
        topics_per_page = int(
            forumhelper.get_system_property('zfsp_threads_per_page', 15))
        #except:
        #    topics_per_page = 15
        
        # all Topics
        all_topics = db((db.zf_topic.forum_id==forum_id) & \
            (db.zf_topic.parent_flag==True)).count()
        view_info['all_topics'] = all_topics
        parent_topics = db(
            (db.zf_topic.forum_id==forum_id) & \
            (db.zf_topic.parent_flag==True)).select(
            orderby=(~db.zf_topic.sticky_flag, ~db.zf_topic.modifying_date),
            limitby=(start, start+topics_per_page))
        
        # Pagination Manager Part II/II
        pagination_widget = forumhelper.pagination_widget(
            all_topics,
            start,
            URL(r=request, c='default', f='view_forum', args=[forum.id]),
            'forum')
        view_info.update({'pagination_widget': pagination_widget})

        # Now plug in the information regarding their children
        topic_replies_info = {}
        for topic in parent_topics:
            # Get the number of children topics for this (parent) topic
            topic_replies_info.update({topic.id:
                db(db.zf_topic.parent_id==topic.id).count()})
            # Topic Subscription
            if forumhelper.has_topic_subscription(topic.id, user_id):
                view_info.update({topic.id: {'subscribed_to_topic': True}})
            else:
                view_info.update({topic.id: {'subscribed_to_topic': False}})

        return dict(request=request, forum=forum, parent_topics=parent_topics,
                    view_info=view_info, security_info=security_info,
                    topic_replies_info=topic_replies_info)
    else:
        redirect(URL(r=request, c='default', f='unauthorized'))

def signup():
    req = request.vars
    view_info = {}
    view_info['errors'] = []
    allow_registration = forumhelper.get_system_property(
        'zfsp_allow_registration', '') != ''
    view_info.update({'allow_registration': allow_registration})
    if req.form_submitted:
        if req.register_b:

            # Verify required fields
            if len(req.auth_alias) > 0 and len(req.auth_email) > 0 and len(
                req.auth_passwd) > 0:
                auth_email = req.auth_email.strip()
                auth_passwd = req.auth_passwd
                auth_passwd_c = req.auth_passwd_c

                # Lamo validation.. embarrasing ;)
                if auth_email.find(' ') >= 0:
                    view_info['errors'].append('Email must not contain spaces')

                if auth_passwd != auth_passwd_c:
                    view_info['errors'].append('Password and confirmation '
                                               'do not match')

                # See if this name has been taken
                if db(db.auth_users.auth_email.lower() == \
                      auth_email.lower()).select(db.auth_users.id):
                    view_info['errors'].append('The selected email is'
                                               'unavailable, please choose '
                                               'another one')

                if not view_info['errors']:
                    # Authenticate user
                    auth_token = auth_email + auth_passwd
                    hash_passwd = hashlib.sha1(auth_token).hexdigest()
                    auth_user_id = db.auth_users.insert(
                        auth_email=auth_email,
                        auth_passwd=hash_passwd,
                        auth_created_on=request.now,
                        auth_modified_on=request.now)
                    # Add the default role of zMember
                    # (NOTE: THIS ROLE MUST EXIST)
                    auth_role_id = db(
                        db.auth_roles.auth_role_name=='zMember').select(
                        db.auth_roles.id)[0].id
                    db.auth_user_role.insert(auth_user_id=auth_user_id,
                                             auth_role_id=auth_role_id)
                    # Now authenticate user
                    auth_user.authenticate(auth_email, auth_passwd)
            else:
                view_info['errors'].append('Please make sure you fill in all '
                                           'the required fields in order to '
                                           'continue')

            if view_info['errors']:
                return dict(request=request, view_info=view_info)
            else:
                redirect(URL(r=request, c='default', f='index'))
        else:
            redirect(URL(r=request, c='default', f='index'))
    else:
        return dict(request=request, view_info=view_info)

def view_topic():
    req = request.vars
    view_info = {}
    view_info['errors'] = []
    security_info = {'can_add': False, 'can_reply': False}
    parent_topic_removed = False
    user_id = auth_user.get_user_id()
    emoticons = ['icon_arrow.png', 'icon_biggrin.png', 'icon_confused.png',
                 'icon_cool.png', 'icon_cry.png', 'icon_exclaim.png',
                 'icon_idea.png', 'icon_lol.png', 'icon_mad.png',
                 'icon_mrgreen.png', 'icon_neutral.png', 'icon_question.png',
                 'icon_razz.png', 'icon_redface.png', 'icon_rolleyes.png',
                 'icon_sad.png', 'icon_smile.png', 'icon_twisted.png',
                 'icon_wink.png']
    view_info.update({'emoticons': emoticons})
    # Added in 1.0.3 - Captcha-like
    captcha = forumhelper.gen_pwd()
    view_info['anon_captcha'] = captcha
    view_info['anon_captcha_base64'] = base64.standard_b64encode(captcha)
    
    if req.form_submitted:
        topic_id = (req.topic_id)
    else:
        topic_id = int(request.args[0])
    # Get This topic
    topic = db(db.zf_topic.id==topic_id).select()[0]
    if topic.parent_flag:

        # Handle Topic subscriptions here
        if len(request.args) > 1:
            subscription_request = int(request.args[1]) == 1
            if subscription_request:
                forumhelper.add_topic_subscription(topic_id, user_id)
            else:
                forumhelper.del_topic_subscription(topic_id, user_id)

        # Handle Topic Hits Here as well
        db(db.zf_topic.id==topic_id).update(hits=topic.hits+1)

        # Grab the forum
        forum = db(db.zf_forum.id==topic.forum_id).select()[0]

        if len(forum.add_postings_access_roles):
            security_info['can_add'] = [
                role for role in auth_user.get_roles()
                if forum.add_postings_access_roles.find(role)] != []
        else:
            security_info['can_add'] = True

        if len(forum.reply_postings_access_roles):
            security_info['can_reply'] = [
                role for role in auth_user.get_roles()
                if forum.reply_postings_access_roles.find(role)] != []
        else:
            security_info['can_reply'] = True

        # HANDLE Removals/Submission of new topic, etc
        # Was a removal requested?
        if req.remove and auth_user.is_admin():
            # At this point, there are several important things to consider,
            # if the admin requested removal of the parent topic, along with
            # one or more children topics, there is no point in processing
            # the children since they'll be deleted anyway
            if req.get('remove_topic_parent_%s' % (topic_id), '') != '':
                # Removal of parent requested, remove children first,
                # then parent.
                db(db.zf_topic.parent_id==topic_id).delete()
                db(db.zf_topic.id==topic_id).delete()
                parent_topic_removed = True
            else:
                # Removal of certain children topics requested only
                for req_var in req:
                    if req_var[:19] == 'remove_topic_child_':
                        child_topic_id = int(req[req_var])
                        db(db.zf_topic.id==child_topic_id).delete()
        if parent_topic_removed:
            redirect(URL(r=request, c='default', f='view_forum',
                         args=[forum.id]))
        else:

            # Here now check if the user is trying to add a new response
            # (or preview)
            if req.preview:
                view_info.update({'preview': True})
            elif req.form_submitted and security_info['can_reply'] and not \
                auth_user.is_auth() and \
                base64.standard_b64encode(req.captcha_response) != req.c:
                # Use this slot when captcha fails
                # This test must be evaluated when:
                # - The User is Anonymous
                # - AND the forum allow anonymous replies
                view_info['errors'].append('Please make sure all required '
                                           'fields are properly filled')
                view_info.update({'preview': True})
            elif req.add and (security_info['can_reply'] or \
                              auth_user.is_admin()):
                if req.response_content.strip():
                    now = request.now.strftime('%Y-%m-%d %H:%M:%S')
                    # User is requesting addition of a response (child topic)
                    db.zf_topic.insert(forum_id=forum.id,
                        title=topic.title,
                        content=req.response_content,
                        parent_id=topic_id,
                        creation_user_id=user_id,
                        creation_date=now,
                        modifying_user_id=user_id,
                        modifying_date=now,
                        hits=0,
                        parent_flag=False,
                        locked_flag=False,
                        disabled_flag=False,
                        sticky_flag=False,
                        poll_flag=False,
                        system_announcement_flag=False,
                        reply_to_topic_id=0,
                        ip_address=request.remote_addr)

                    # Update the modifying date, and the modifying user of
                    # its parent also
                    db(db.zf_topic.id == topic_id).update(
                        modifying_date=now,
                        modifying_user_id=user_id)

                    # Increment the number of postings for this user
                    postings = int(forumhelper.get_member_property(
                        'zfmp_postings', user_id, '0')) + 1
                    forumhelper.put_member_property('zfmp_postings',
                                                    user_id, str(postings))

                    # Notify Subscribed users about changes in this topic
                    forumhelper.setup_notifications(subscription_id=topic_id,
                                                    subscription_type='T',
                                                    now=request.now)

                else:
                    view_info['errors'].append('Content must be specified for '
                                               'the reply')

            # Information to pass regarding system variables, etc
            # Topic Subscription:
            view_info.update({'subscribed_to_topic':
                forumhelper.has_topic_subscription(topic_id, user_id)})

            # Pagination Manager Part I/II
            start = int(req.get('start', 0))
            responses_per_page = int(forumhelper.get_system_property(
                'zfsp_responses_per_page', 15))
            # Children Topics
            all_children = db(db.zf_topic.parent_id==topic.id).count()
            children = db(db.zf_topic.parent_id == topic.id).select(
                db.zf_topic.ALL, orderby=db.zf_topic.modifying_date,
                limitby=(start, start+responses_per_page))
            
            # Pagination Manager Part II/II
            pagination_widget = forumhelper.pagination_widget(
                all_children, start, URL(r=request,
                                         c='default',
                                         f='view_topic',
                                         args=[topic_id]), 'topic')
            view_info.update({'pagination_widget': pagination_widget})

            return dict(request=request,
                        security_info=security_info,
                        forum=forum,
                        topic=topic,
                        children=children,
                        view_info=view_info)
    else:
        redirect(URL(r=request, c='default', f='invalid_request'))

def add_topic():
    req = request.vars
    view_info = {}
    view_info['errors'] = []
    view_info['messages'] = []
    captcha = forumhelper.gen_pwd()
    view_info['anon_captcha'] = captcha
    view_info['anon_captcha_base64'] = base64.standard_b64encode(captcha)
    security_info = {'can_add': False, 'can_reply': False}
    is_admin = auth_user.has_role('zAdministrator')
    emoticons = ['icon_arrow.png',
                 'icon_biggrin.png',
                 'icon_confused.png',
                 'icon_cool.png',
                 'icon_cry.png',
                 'icon_exclaim.png',
                 'icon_idea.png',
                 'icon_lol.png',
                 'icon_mad.png',
                 'icon_mrgreen.png',
                 'icon_neutral.png',
                 'icon_question.png',
                 'icon_razz.png',
                 'icon_redface.png',
                 'icon_rolleyes.png',
                 'icon_sad.png',
                 'icon_smile.png',
                 'icon_twisted.png',
                 'icon_wink.png']
    view_info.update({'emoticons': emoticons})
    if req.form_submitted:
        forum_id = int(req.forum_id)
        if req.add_topic:
            # First thing, required fields check:
            if (req.title and req.content) and (auth_user.is_auth() or (
                not auth_user.is_auth() and base64.standard_b64encode(
                    req.captcha_response) == req.c)):
                content = req.content
                # Parse the title
                # Ignore ALL html tags ANDdo not convert it
                title = parse_content(req.title) 
                if is_admin:
                    locked_flag = req.locked_flag is not None
                    sticky_flag = req.sticky_flag is not None
                    system_announcement_flag = req.system_announcement_flag \
                                               is not None
                    creation_user = req.creation_user
                    creation_date = req.creation_date
                    modifying_user = req.modifying_user
                    modifying_date = req.modifying_date
                else:
                    locked_flag = False
                    sticky_flag = False
                    system_announcement_flag = False
                    creation_user = auth_user.get_user_id()
                    creation_date = request.now
                    modifying_user = creation_user
                    modifying_date = creation_date

                # Add Signature from Member Profile if requested.
                if req.add_signature:
                    signature = forumhelper.get_member_property(
                        'zfmp_signature', creation_user, '')
                    if signature:
                        content += '\n\n<code>\n%s</code>' % (signature)

                # Add the topic
                topic_id = db.zf_topic.insert(forum_id=forum_id,
                    title=title,
                    content=content,
                    creation_user_id=creation_user,
                    creation_date=creation_date,
                    modifying_user_id=modifying_user,
                    modifying_date=modifying_date,
                    parent_flag=True,
                    locked_flag=locked_flag,
                    disabled_flag=False,
                    sticky_flag=sticky_flag,
                    poll_flag=False,
                    system_announcement_flag=system_announcement_flag,
                    ip_address=request.remote_addr)

                # Notify Subscribed users about changes in this Forum
                forumhelper.setup_notifications(subscription_id=forum_id,
                                                subscription_type='F',
                                                now=request.now)

                # Subscribe user to topic if requested
                if req.add_subscription:
                    forumhelper.add_topic_subscription(topic_id,
                                                       creation_user) # ID

                # Increment the number of postings for this user
                postings = int(forumhelper.get_member_property(
                    'zfmp_postings', creation_user, '0')) + 1
                forumhelper.put_member_property('zfmp_postings',
                                                creation_user,
                                                str(postings))

                view_info['messages'].append('Topic has been added')
                redirect(URL(r=request,
                             c='default',
                             f='view_forum',
                             args=[forum_id],
                             vars=dict(added='1')))
            else:
                view_info['errors'].append('Please make sure all required '
                                           'fields are properly filled')
                return dict(request=request,
                            view_info=view_info,
                            forum_id=forum_id)
        elif req.preview_b:
            content = req.content
            if is_admin:
                creation_user = req.creation_user
            else:
                creation_user = auth_user.get_user_id()
            # Add Signature from Member Profile if requested.
            if req.add_signature:
                signature = forumhelper.get_member_property('zfmp_signature',
                                                            creation_user,
                                                            '')
                if signature:
                    content += '\n\n<code>\n%s</code>' % (signature)
            view_info.update({'preview': content})
            return dict(request=request,
                        view_info=view_info,
                        forum_id=forum_id)
        else:
            redirect(URL(r=request,
                         c='default',
                         f='view_forum',
                         args=[forum_id]))
    else:
        forum_id = int(request.args[0])
        return dict(request=request, view_info=view_info, forum_id=forum_id)

@auth_user.requires_role('zAdministrator')
def edit_topic():
    req = request.vars
    view_info = {}
    view_info['errors'] = []
    view_info['messages'] = []
    security_info = {'can_add': False, 'can_reply': False}
    emoticons = ['icon_arrow.png',
                 'icon_biggrin.png',
                 'icon_confused.png',
                 'icon_cool.png',
                 'icon_cry.png',
                 'icon_exclaim.png',
                 'icon_idea.png',
                 'icon_lol.png',
                 'icon_mad.png',
                 'icon_mrgreen.png',
                 'icon_neutral.png',
                 'icon_question.png',
                 'icon_razz.png',
                 'icon_redface.png',
                 'icon_rolleyes.png',
                 'icon_sad.png',
                 'icon_smile.png',
                 'icon_twisted.png',
                 'icon_wink.png']
    view_info.update({'emoticons': emoticons})
    if req.form_submitted:
        topic_id = int(req.topic_id)
        topic = db(db.zf_topic.id==topic_id).select()[0]
        forum_id = topic.forum_id

        if req.edit_topic:
            if req.title and req.content and req.creation_user and \
            req.creation_date and req.modifying_user and req.modifying_date:
                title = parse_content(req.title)
                creation_user = req.creation_user
                creation_date = req.creation_date
                modifying_user = req.modifying_user
                modifying_date = req.modifying_date

                if topic.parent_flag:
                    parent_topic_id = topic_id
                    locked_flag = req.locked_flag is not None
                    sticky_flag = req.sticky_flag is not None
                    system_announcement_flag = req.system_announcement_flag \
                                               is not None
                    db(db.zf_topic.id==topic_id).update(title=title,
                        content=req.content,
                        creation_user_id=creation_user,
                        creation_date=creation_date,
                        modifying_user_id=modifying_user,
                        modifying_date=modifying_date,
                        locked_flag=locked_flag,
                        sticky_flag=sticky_flag,
                        system_announcement_flag=system_announcement_flag)
                else:
                    parent_topic_id = topic.parent_id
                    # Just Update child-required fields
                    db(db.zf_topic.id==topic_id).update(title=title,
                        content=req.content,
                        creation_user_id=creation_user,
                        creation_date=creation_date,
                        modifying_user_id=modifying_user,
                        modifying_date=modifying_date)
                redirect(URL(r=request, c='default', f='view_topic',
                             args=[parent_topic_id]))
            else:
                view_info['errors'].append('All fields are required')
                return dict(request=request, topic=topic, view_info=view_info)
        elif req.preview_b:
            view_info.update({'preview': True})
            return dict(request=request, view_info=view_info, topic=topic)
        elif req.remove_b:
            if topic.parent_flag:
                parent_topic_id = topic_id
                db(db.zf_topic.parent_id==parent_topic_id).delete()
                db(db.zf_topic.id==parent_topic_id).delete()
                redirect_to = URL(r=request, c='default', f='view_forum',
                                  args=[forum_id])
            else:
                parent_topic_id = topic.parent_id
                db(db.zf_topic.id==topic_id).delete()
                redirect_to = URL(r=request, c='default', f='view_topic',
                                  args=[parent_topic_id])
            redirect(redirect_to)
        else:
            if topic.parent_flag:
                parent_topic_id = topic.id
            else:
                parent_topic_id = topic.parent_id
            redirect(URL(r=request, c='default', f='view_topic',
                         args=[parent_topic_id]))
    else:
        topic_id = int(request.args[0])
        topic = db(db.zf_topic.id==topic_id).select()[0]
        return dict(request=request, topic=topic, view_info=view_info)

def report_inappropriate():
    topic_id = int(request.args[1])
    child_id = int(request.args[0])
    if auth_user.is_auth():
        db.zf_topic_inappropriate.insert(
            topic_id=topic_id,
            child_id=child_id,
            creation_user_id=auth_user.get_user_id(),
            creation_date=request.now,
            read_flag=False)
    redirect(URL(r=request, c='default', f='view_topic', args=[topic_id]))

def rss():
    import gluon.contrib.rss2 as rss2
    import gluon.contrib.markdown as md

    default_type = 'system'
    if len(request.args) == 1:
        rss_type = request.args[0].lower()
        if not rss_type in ['system', 'latest']:
            rss_type = default_type
    else:
        rss_type = default_type

    if rss_type == 'system':
        title = str(XML(T('pyForum Latest System Topics')))
        descr = str(XML(T('pyForum Latest System Topics')))
        rss_topics = forumhelper.get_system_announcements(include_content=True)
    else:
        title = str(XML(T('pyForum Latest Topics')))
        descr = str(XML(T('pyForum Latest Topics')))
        rss_topics = forumhelper.get_latest_topics(include_content=True)

    rss_feed = rss2.RSS2(title = title,
                    link = URL(r=request, c='default', f='index'),
                    description = descr,
                    lastBuildDate = request.now,
                    items = [
                        rss2.RSSItem(
                            title = topic.title,
                            link = URL(r=request, c='default', f='view_topic',
                                       args=[topic.id]),
                            description = parse_content(topic.content,
                                                        'forumfull'),
                            pubDate = topic.modifying_date) \
                        for topic in rss_topics]
                    )
    response.headers['Content-Type'] = 'application/rss+xml'
    return rss2.dumps(rss_feed)

def contact_admin():
    """ Contact Admin - This can allow anonymous users to post spam, so
    for them, I'll add some "poor man's captcha"
    
    """
    view_info = {}
    view_info['errors'] = []
    captcha = forumhelper.gen_pwd()
    view_info['anon_captcha'] = captcha
    view_info['anon_captcha_base64'] = base64.standard_b64encode(captcha)
    user_id = auth_user.get_user_id()
    req = request.vars
    if req.form_submitted:
        if req.send_b:
            if req.subject and req.message:
                if auth_user.is_auth() or (
                    not auth_user.is_auth() and base64.standard_b64encode(
                        req.captcha_response) == req.c):
                    db.zf_admin_messages.insert(user_id=user_id,
                        subject=parse_content(req.subject),
                        message=parse_content(req.message),
                        creation_date=request.now,
                        read_flag=False)
                    redirect(URL(r=request, c='default', f='index'))
                else:
                    view_info['errors'].append('Invalid humanity challenge '
                                               'response, please try again')
                    return dict(request=request, view_info=view_info)
            else:
                view_info['errors'].append('Both Subject and Message are '
                                           'required fields')
                return dict(request=request, view_info=view_info)
        else:
            redirect(URL(r=request, c='default', f='index'))
    else:
        return dict(request=request, view_info=view_info)

def unauthorized():
    return dict()

def invalid_request():
    return dict()

def search():
    search_str = request.vars.search_str.strip().lower()
    results = []
    view_info = {}
    view_info['errors'] = []
    if len(search_str) >= 3:
        search_str = '%%%s%%' % (search_str)
        results = db(((
            (db.zf_topic.title.lower().like(search_str)) &
            (db.zf_topic.parent_flag==True)) |
            (db.zf_topic.content.lower().like(search_str))) &
            (db.zf_topic.disabled_flag==False) &
            (db.zf_forum.id==db.zf_topic.forum_id)).select(
            db.zf_topic.ALL, db.zf_forum.forum_title,
            orderby=~db.zf_topic.modifying_date, limitby=(0, 100))
    else:
        view_info['errors'].append('Search string must be three or more '
                                   'characters')
    return dict(request=request, search_str=request.vars.search_str,
                results=results, view_info=view_info)

@auth_user.requires_login()
def preferences():
    view_info = {}
    view_info['errors'] = []
    view_info['props'] = {}
    req = request.vars
    user_id = auth_user.get_user_id()
    # Avatar Restrictions (px) - Maybe we need to make these dynamic??
    AVATAR_MAX_HEIGHT = 100
    AVATAR_MAX_WIDTH  = 120
    AVATAR_MAX_SIZE   = 15000 # Bytes
    user_email = db(db.auth_users.id==user_id).select(
        db.auth_users.auth_email)[0].auth_email
    view_info['props'].update({'real_name':
        forumhelper.get_member_property('zfmp_real_name', user_id, '')})
    view_info['props'].update({'web_page':
        forumhelper.get_member_property('zfmp_web_page', user_id, '')})
    view_info['props'].update({'country':
        forumhelper.get_member_property('zfmp_country', user_id, '')})
    view_info['props'].update({'signature':
        forumhelper.get_member_property('zfmp_signature', user_id, '')})
    view_info['props'].update({'locale':
        forumhelper.get_member_property('zfmp_locale', user_id, '')})
    view_info['props'].update({'allow_pm_use':
        forumhelper.get_member_property('zfmp_allow_pm_use', user_id, '')})
    view_info['props'].update({'postings':
        forumhelper.get_member_property('zfmp_postings', user_id, '0')})
    view_info['props'].update({'last_login':
        forumhelper.get_member_property(
            'zfmp_last_login', user_id, str(XML(T('Never'))))})
    view_info['props'].update({'username':
        forumhelper.get_member_property(
            'zfmp_display_name', user_id, 'user_%s' % (user_id))})
    forum_subscriptions = db((db.zf_member_subscriptions.user_id==user_id) &
        (db.zf_member_subscriptions.subscription_type=='F') &
        (db.zf_member_subscriptions.subscription_id==db.zf_forum.id) &
        (db.zf_member_subscriptions.subscription_active==True)).select(
        db.zf_forum.id, db.zf_forum.forum_title)
    topic_subscriptions = db((db.zf_member_subscriptions.user_id==user_id) &
        (db.zf_member_subscriptions.subscription_type=='T') &
        (db.zf_member_subscriptions.subscription_id==db.zf_topic.id) &
        (db.zf_member_subscriptions.subscription_active==True)).select(
        db.zf_topic.id, db.zf_topic.title)
    available_languages = db(db.zf_available_languages.enabled==True).select(
        db.zf_available_languages.ALL,
        orderby=db.zf_available_languages.language_desc)

    if req.form_submitted:
        if req.update_b:
            # Standard Properties
            forumhelper.put_member_property('zfmp_real_name', user_id,
                                            req.real_name)
            forumhelper.put_member_property('zfmp_web_page', user_id,
                                            req.web_page)
            forumhelper.put_member_property('zfmp_country', user_id,
                                            req.country)
            forumhelper.put_member_property('zfmp_signature', user_id,
                                            req.signature)
            forumhelper.put_member_property('zfmp_locale', user_id,
                                            req.locale)
            if req.allow_pm_use:
                zfmp_allow_pm_use = "1"
            else:
                zfmp_allow_pm_use = ""
            forumhelper.put_member_property('zfmp_allow_pm_use', user_id,
                                            zfmp_allow_pm_use)
            
            # "Username" is a new member property called 'zfmp_display_name'
            # Which is only an identifier for the user, which they can change,
            # however, there cannot be two users with the same name, so
            # if the username is taken, notify the user to change it, or
            # use the default of "user_[id]"
            username = req.username.strip()
            if username:
                # Check if this username is already taken... and that
                # user is (obviously) not yourself
                if db(
                    (db.zf_member_properties.property_value.lower() == \
                     username.lower()) &
                    (db.zf_member_properties.property_id == \
                     db.zf_member_properties_skel.id) &
                    (db.zf_member_properties_skel.property_name == \
                     'zfmp_display_name') &
                    (db.zf_member_properties.user_id != user_id)).count():
                        view_info['errors'].append('This username already '
                                                   'exists, please choose '
                                                   'another one')
                else:
                    # Nope, does not exist, update..
                    forumhelper.put_member_property('zfmp_display_name',
                                                    user_id, username)
            else:
                view_info['errors'].append('The Username value cannot be '
                                           'empty')

            # Topic Subscriptions
            remove_topic_subscription = req.remove_topic_subscription
            if remove_topic_subscription:
                if type(remove_topic_subscription) == type([]):
                    for topic_id in remove_topic_subscription:
                        forumhelper.del_topic_subscription(int(topic_id),
                                                           user_id)
                else:
                    forumhelper.del_topic_subscription(
                        int(remove_topic_subscription), user_id)

            # Forum Subscriptions
            remove_forum_subscription = req.remove_forum_subscription
            if remove_forum_subscription:
                if type(remove_forum_subscription) == type([]):
                    for forum_id in remove_forum_subscription:
                        forumhelper.del_forum_subscription(int(forum_id),
                                                           user_id)
                else:
                    forumhelper.del_forum_subscription(
                        int(remove_forum_subscription), user_id)

            # Password Changes
            if req.new_passwd or req.new_passwd_confirm:
                if req.new_passwd == req.new_passwd_confirm:
                    hash_passwd = hashlib.sha1(
                        auth_user.get_user_name() + req.new_passwd).hexdigest()
                    db(db.auth_users.id==user_id).update(
                        auth_passwd=hash_passwd)
                else:
                    view_info['errors'].append('Password and confirmation do '
                                               'not match, please try again')

            # Avatars
            if req.remove_avatar:
                db(db.zf_member_avatars.user_id==user_id).update(
                    avatar_active=False)
                
            # Selected Language (allow storing the "default"
            # value (an empty string))
            forumhelper.put_member_property('zfmp_locale', user_id,
                                            req.lang_code)

            # Crude verification of a FileUpload object set
            try:
                filename = req.avatar_data.filename
            except AttributeError:
                filename = ''

            if filename:
                # Resource: http://epydoc.sourceforge.net/stdlib/cgi.
                # FieldStorage-class.html
                image_data = req.avatar_data.file.read()
                content_type = req.avatar_data.type # "image/png"
                doc_type, ext = content_type.split('/')
                if doc_type == 'image':
                    c_type, width, height = forumhelper.get_image_info(
                        image_data)
                    update_avatar = True
                    if height > AVATAR_MAX_HEIGHT or width > AVATAR_MAX_WIDTH:
                        view_info['errors'].append('Image dimensions exceed '
                                                   'the limits set by the '
                                                   'administrator: (H:'
                                                   '%spx, W:%spx)' % (height,
                                                                      width))
                        update_avatar = False
                    if len(image_data) > AVATAR_MAX_SIZE:
                        view_info['errors'].append('Avatar exceeds the '
                                                   'maximum image size set by '
                                                   'the administrator: '
                                                   '%s bytes' % (
                                                    len(image_data)))
                        update_avatar = False

                    if update_avatar:
                        if forumhelper.has_member_avatar(user_id,
                                                         bypass=False):
                            # Update:
                            db(db.zf_member_avatars.user_id==user_id).update(
                                content_type=content_type,
                                avatar_image=image_data, avatar_active=True)
                        else:
                            # Add:
                            db.zf_member_avatars.insert(
                                content_type=content_type,
                                user_id=user_id,
                                avatar_image=image_data, avatar_active=True)

            if view_info['errors']:
                return dict(request=request, view_info=view_info,
                            user_id=user_id, user_email=user_email,
                            forum_subscriptions=forum_subscriptions,
                            topic_subscriptions=topic_subscriptions,
                            available_languages=available_languages)
            else:
                redirect(URL(r=request, c='default', f='preferences',
                             vars=dict(lang=req.lang_code, upd=1)))
        else:
            redirect(URL(r=request, c='default', f='index'))
    else:
        return dict(request=request, view_info=view_info, user_id=user_id,
                    user_email=user_email,
                    forum_subscriptions=forum_subscriptions,
                    topic_subscriptions=topic_subscriptions,
                    available_languages=available_languages)


def get_avatar_image():
    auth_user = request.args[0]
    avatar_info = db(db.zf_member_avatars.auth_user==auth_user).select(
        db.zf_member_avatars.content_type, db.zf_member_avatars.avatar_image)
    response.headers['Content-Type'] = '%s' % (avatar_info[0].content_type)
    return avatar_info[0].avatar_image
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.