Source

fossconf / web / views.py

Full commit
   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
# Create your views here.
from django.template import Context, RequestContext, loader
from django.utils.translation import gettext_lazy as _
from django.shortcuts import render_to_response
from conference.web.models import *
from conference.web.models import TEE_SIZES
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.mail import send_mail,EmailMessage
import re,os,random
from django.conf import settings
from django.db import transaction
from django.db.models import get_model
from django.db.models import Q
import time, datetime
from conference.web.forms import *
from django.http import Http404
from idcards import *
import csv


class menu_enabled(object):
    """This decorator checks if the menu is enabled before allowing a person
        to enter a view
        """
    def __init__(self,menuname):
        self.menuname = menuname
        
    def __call__(self,f):
        def wrapper(*args,**kwargs):
            if self.menuname.lower() in [x.name.lower() for x in Menuitem.objects.filter(active=True)]:
                return f(*args,**kwargs)
            else:
                raise Http404
        return wrapper



def isingroup(user,grp):
    """
    A function to check if the user is a member of the given group.
    """
    return user.is_authenticated() and user.groups.filter(name=grp).count() > 0
        

def makemsg(username,url):
    """
    Email body to be sent to user.
    """
    msg = _("\
Dear %(username)s,\n\n\
\
Thank you for registering with us. Please visit this url:\n\n\
%(url)s\n\n\
to complete the registration\n\n\
regards\n\
PyCon India 2009 Team\
") %{'username': username,'url': url}
    return msg

menu_items = [
                {"name":_("Posts"),"url":"2009/posts/","id":"","feeds": "/2009/feeds/posts/"},
                {"name":_("Schedule"),"url":"2009/displayschedule/","id":""},
                {"name":_("Talks"),"url":"2009/talks/","id":"", "feeds": "/2009/feeds/talks/"},
                {"name":_("Browse slides"),"url":"2009/browseslides/","id":""},
                {"name":_("Delegates"),"url":"2009/delegates/","id":"", "feeds": "/2009/feeds/delegates/"},
                {"name":_("Propose talk"),"url":"2009/addtalk/","id":""},
                {"name":_("Manage talks"),"url":"2009/managetalks/","id":""},
                {"name":_("Speakers schedule" ),"url":"2009/speakerlist/","id":""},
                {"name":_("Volunteers"),"url":"2009/volunteers/","id":"", "feeds": "/2009/feeds/volunteers/"},
                {"name":_("Volunteer to help"),"url":"2009/addvolunteer/","id":""},
                {"name":_("Statistics"),"url":"2009/statistics/","id":"", "feeds": "/2009/feeds/statistics/"},
                {"name":_("Tag cloud"),"url":"cloud_list/","id":"", "feeds": "/feeds/cloud_list/"},
                {"name":_("Request a talk"),"url":"addreqtalk/","id":""},
                {"name":_("Requested talks"),"url":"requesttalk/","id":""},
                {"name":_("Make schedule"),"url":"schedule/","id":""},
                {"name":_("Hall/Day schedule"),"url":"halldayschedule/","id":""},
                {"name":_("Send bulk mail"),"url":"bulkmail/","id":""},
              ]

def index(request):
    """
    Display the landing page as Invitations
    """

    try:
        p = Staticpage.objects.get(menu__name=settings.LANDING_PAGE)
    except:
        msg = _("This item is still under construction")
        return HttpResponseRedirect("/2009/message/%s/" % msg)
    return render_to_response('web/staticpage.html',
                              {'p':p,
                               }, context_instance=RequestContext(request))
    
def staticpage(request,menu):
    try:
        p = Staticpage.objects.get(menu__name=menu)
    except:
        msg = _("This item is still under construction")
        return HttpResponseRedirect("/2009/message/%s/" % msg)
    return render_to_response('web/staticpage.html',
                              {'p':p,
                               }, context_instance=RequestContext(request))

@menu_enabled("Posts")    
def posts(request):
    lst = Article.objects.all().order_by("-pubdate",)
    return render_to_response('web/posts.html',
                              {'lst':lst,
                               }, context_instance=RequestContext(request))
@menu_enabled("Posts")
def postsfull(request,id):
    p = Article.objects.get(pk=id)
    return render_to_response('web/postsfull.html',
                              {'p':p,
                               }, context_instance=RequestContext(request))


def register(request):
    """
    Register function.
    """
    if request.user.is_authenticated():
        msg = _("You are already registered")
        return HttpResponseRedirect("/2009/message/%s/" % msg)
    if request.POST:
        # On POST method.
        form = TempRegisterform(request.POST)
        if form.is_valid():
            # If form is clean and has no errors.
            fm = form.cleaned_data
            if len(fm['username']) > 30 or len(fm['username']) < 4:
                # Username should be > 4 characters and less that 30 characters.
                form.errors['username']=[_("User Name must be 4-30 characters long")]
            else:
                r = re.compile(r"[A-Za-z0-9_]")
                for alph in fm['username']:
                    # Check if every character of the username is either an 
                    # alphabet or numeral.
                    if  not r.match(alph):
                        form.errors['username']=[_("Invalid character %s in Username") %(alph)]
                if not form.errors:
                    test = User.objects.filter(username__iexact=fm['username'])
                    # Check if username already exists.
                    if test:
                        form.errors['username'] = [("Username registered, try something else")]
                    else:
                        # Check if username is pending registration ie has not completed
                        # the formality of activating self through mail.
                        test1 = Tempreg.objects.filter(username__iexact=fm['username'])
                        if test1:
                            form.errors['username'] = [_("Username pending registration. Try tomorrow")]
                    # Check if the email id has already been in use.
                    teste = User.objects.filter(email__iexact=fm['email'])
                    if teste:
                        form.errors['email'] = [_("Email registered. Try something else")]
                    else:
                        # If username is found in the temporary registration database
                        # then show pending error message.
                        teste1 = Tempreg.objects.filter(email__iexact=fm['email'])
                        if teste1:
                            form.errors['email'] = [("Username pending registration. Try tomorrow")]
            if not form.errors:
                # If all goes well then push into database.
                new_reg = form.save()
                # Generate a random code to be sent to the email.
                new_reg.code = str(random.random())[2:]
                new_reg.save()
                # Delete the users who have not activated self within 24 hours.
                lst = Tempreg.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(1))
                for p in lst:
                    p.delete()
                url = "http://in.pycon.org/adduser/%s/" %(new_reg.code)
                # Send the email with the contents of makemsg.
                mg = makemsg(new_reg.username,url)
                subj = "Registration for %s at PyCon India 2009"\
                       %(new_reg.username)
                frm = settings.DEFAULT_FROM_EMAIL
                to = [new_reg.email]
                send_mail(subj,mg,frm,to,fail_silently=False)
                # Redirect to a thank you page after email has been sent.
                return HttpResponseRedirect("/regthank/%i/" % new_reg.id)
    else:
        # On the GET method.
        form = TempRegisterform()
    return render_to_response("web/register.html",
                              {"form":form.as_table(),
                               }, context_instance=RequestContext(request))
                               
def regthank(request,id):
    """
    Function displayed after registration is successful and email has been sent.
    """
    p = Tempreg.objects.get(pk=id)
    t = loader.get_template("web/regthank.html")
    c = RequestContext(request,
                {"p":p,
                 })
    return HttpResponse(t.render(c))

   
@transaction.commit_on_success    
def adduser(request,code):
    """
    Succesfully activate user if correct code is provided.
    """
    if code:
        try:
            # Check if code is right else redirect to a sorry page.
            usr = Tempreg.objects.get(code__exact=code)
            data = {}
            if usr:
                data['email']=usr.email
                data['code']=usr.code
                data['username']=usr.username
        except:
            return HttpResponseRedirect('/sorry/')
    if request.POST:
        form = Adduserform(request.POST)
        if form.is_valid():
            fm = form.cleaned_data
            if fm['username'] != data['username']:
                    form.errors['username'] = [_("Type your username exactly\
                    as you entered it before")]
            if not form.errors:
                newuser = User.objects.create_user(username=fm['username'],
                                        email=data['email'],
                                        password=fm['pass1'])
                newuser.save()
                oldreg = Tempreg.objects.get(username=fm['username'])
                oldreg.delete()
                user = authenticate(username=fm['username'], 
                    password=fm['pass1'])
                login(request,user)
                return HttpResponseRedirect('/edituser/')
    else:
        form = Adduserform()
    return render_to_response('web/adduser.html',
                              {'form':form.as_table(),
                               'request':request,
                               })

@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/")  
@transaction.commit_on_success
def edituser(request):
    """
    Function to save the edited user credentials along with city and organisation
    """
    if request.POST:
        # On POST request.
        form = Edituserform(request.POST,request.FILES)
        if form.is_valid():
            fm = form.cleaned_data
            newuser = User.objects.get(pk=request.user.id)
            newuser.first_name = fm['first_name']
            newuser.last_name = fm['last_name']
            if fm.get('pass1') and fm.get('pass2'):
                newuser.set_password(fm['pass1'])
            newuser.save()
            changed = False
            newdel,created = Delegate.objects.get_or_create(username=request.user)
            newdel.bio = fm['bio']
            newdel.teesize = fm['teesize']
            newdel.occupation_id= int(fm['occupation'])
            newdel.city = fm['city']
            newdel.organisation = fm['organisation']
            newdel.private = fm['private']
            changed = True
            newdel.save()
            if request.FILES:
                # Delete the old photo
                pat = settings.MEDIA_ROOT+request.POST['flname']
                try:
                    os.unlink(pat)
                except:
                    pass
                newdel.photo = request.FILES['photo']
                newdel.save()
            return HttpResponseRedirect("/delegatefull/%d/" %newdel.id )
    else:
        id = request.user.id
        usr = User.objects.get(pk=id)
        data = {
                 'username'  : usr.username,
                 'first_name':usr.first_name,
                 'last_name' : usr.last_name
               }
        try:
            a = Delegate.objects.get(username=request.user)
            data['bio'] = a.bio
            data['teesize'] = a.teesize
            data['occupation'] = a.occupation.id
            data['city'] = a.city
            data['organisation'] = a.organisation
            data['private'] = a.private
            try:
                pat = settings.MEDIA_ROOT+a.photo.name
                filedt = open(pat,'r')
                filedata = {
                             'photo':  {'filename': a.photo.url,'content': filedt.read()}
                           }
                data['flname'] = a.photo.name
                data['flurl'] = a.photo.url
            except:
                pass
            
            form = Edituserform(data,filedata)
        except:
            form = Edituserform(data)
    return render_to_response("web/edituser.html",
                              {'form':form,
                               'request':request,
                               })
                               
def sorry(request):
    """
    Redirected page if the code activation fails.
    """
    t = loader.get_template("web/sorry.html")
    c = RequestContext(request)
    return HttpResponse(t.render(c))
    

@menu_enabled("Propose talk")
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/") 
@transaction.commit_on_success   
def addtalk(request):
    """
    Function to add the talk.
    """
    #send users without profiles to profile page
    try:
        delgid = Delegate.objects.get(username=request.user).id
    except:
        return HttpResponseRedirect("/edituser/")
    #proceed if there is a delegate id
    you = Delegate.objects.get(id=delgid)
    if request.POST:
        temp_data_dict = request.POST.copy()
        initial_selection = temp_data_dict.getlist('speaker')
        temp_data_dict['speaker'] = temp_data_dict.getlist('confirm_speaker')
        data_dict = dict(temp_data_dict)
        for key in data_dict.keys():
            data_dict[key]= data_dict[key][0]
        form = Addtalkform(delgid,data_dict,request.FILES,cached_choices=initial_selection)
        if form.is_valid():
            fm = form.cleaned_data
            categ = Category.objects.get(pk=int(fm['category'].id))
            newtalk = Talk.objects.create(title = fm['title'],
                                          abstract = fm['abstract'],
                                          category = categ,
                                          level = fm['level'],
                                          talk_tags = fm['tag_talk'])
            newtalk.speaker.add(you)
            for spk in fm['speaker']:
                newtalk.speaker.add(Delegate.objects.get(pk=int(spk.id)))
            if request.FILES:
                newtalk.slides = request.FILES['slides']
                newtalk.save()
            return HttpResponseRedirect("/talkfull/%d/" % newtalk.id)
        else:
            speaker_details = Delegate.objects.filter(id__in=data_dict.get('speaker'))
    else:
        form = Addtalkform(delgid)
        speaker_details = None
    return render_to_response("web/addtalk.html",
                              context_instance=RequestContext(request,{'form':form,
                                                                       'speakers': speaker_details,
                                                                       'you': you
                                                                       }))
@menu_enabled("Manage talks")
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/")  
@transaction.commit_on_success
def edittalk(request,id):
    """view to edit a user's profile - this is saved in User and Delegate
        """
    delgid = Delegate.objects.get(username=request.user).id
    tkid = Talk.objects.get(pk=id).id
    you = Delegate.objects.get(id=delgid)
    if request.POST:
        temp_data_dict = request.POST.copy()
        initial_selection = temp_data_dict.getlist('speaker')
        temp_data_dict['speaker'] = temp_data_dict.getlist('confirm_speaker')
        data_dict = dict(temp_data_dict)
        for key in data_dict.keys():
            data_dict[key]= data_dict[key][0]
        form = Edittalkform(tkid,delgid,data_dict,request.FILES,cached_choices=initial_selection)
        form.fields['speaker'].queryset = Delegate.objects.exclude(id=delgid)
        if form.is_valid():
            fm = form.cleaned_data
            categ = Category.objects.get(pk=int(fm['category'].id))
            newtalk = Talk.objects.get(pk=id)
            newtalk.title = fm['title']
            newtalk.abstract = fm['abstract']
            newtalk.category = categ
            newtalk.level = fm['level']
            newtalk.talk_tags = fm['tag_talk']
            newtalk.save()
            # remove all the previous speakers
            newtalk.speaker.clear()
            newtalk.speaker.add(you)
            for spk in fm['speaker']:
                newtalk.speaker.add(Delegate.objects.get(pk=int(spk.id)))
            if request.FILES:
                # Delete the old slides
                pat = settings.MEDIA_ROOT+request.POST['flname']
                try:
                    os.unlink(pat)
                except:
                    pass
                newtalk.slides = request.FILES['slides']
                newtalk.save()
            return HttpResponseRedirect("/talkfull/%d/" % newtalk.id)
        else:
            speaker_details = Delegate.objects.filter(id__in=data_dict.get('speaker'))
    else:
        tlk = Talk.objects.get(pk=id)
        tkid = tlk.id
        delgid = Delegate.objects.get(username=request.user).id
        data = {
            'title'   : tlk.title,
            'level'   : tlk.level,
            'abstract': tlk.abstract,
            'speaker' : Delegate.objects.all().exclude(id__in=[p['id'] for p in \
                                                       Talk.objects.get(pk=tkid).speaker.values('id')]),
            'category':tlk.category.id,
            'tag_talk': tlk.talk_tags,
            }
        try:
            pat = settings.MEDIA_ROOT+tlk.slides
            filedt = open(pat,'r')
            filedata = {
                'slides':  {'filename': tlk.slides.url,'content': filedt.read()}
                }
            data['flname'] = tlk.slides.name
            data['flurl'] = tlk.slides.url
            form = Edittalkform(tkid,delgid,data,filedata)

            # Assign the clean_speaker method to a dummy to
            # remove any validation errors on GET (which is a
            # side-effect.
            def clean_speaker_dummy():
                pass
            
            # Or setattr(form,'clean_speaker',clean_speaker_dummy)
            form.clean_speaker = clean_speaker_dummy
        except:
            form = Edittalkform(tkid,delgid,data)

            def clean_speaker_dummy():
                pass
            form.clean_speaker = clean_speaker_dummy
            speaker_details = Delegate.objects.filter(id__in=[p.id for p in tlk.speaker.all() if p.id != delgid])

        form = Edittalkform(tkid,delgid,data)
    return render_to_response("web/edittalk.html",
                              context_instance=RequestContext(request,{'form':form,
                                                                       'speakers': speaker_details,
                                                                       'you': you
                                                                       }))
@menu_enabled("Manage talks")                               
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/") 
def managetalks(request):
    """
    list all talks of a given user for modification
    """
    id  = request.user.id
    try:
        usr = Delegate.objects.get(username=id)
    except:
        msg = _("You do not have any talks to manage")
        return HttpResponseRedirect("/2009/message/%s/" % msg)
    lst = usr.speakers.all()
    t   = loader.get_template('web/managetalks.html')
    c   = RequestContext(request,{'lst':lst,})
    return HttpResponse(t.render(c))

@menu_enabled("Delegates")
def delegates(request):
    """
    list of all delegates those who are registered
    """
    lst=Delegate.objects.select_related().order_by('auth_user.first_name')
    t = loader.get_template('web/delegates.html')
    c = RequestContext(request,
                {'lst':lst,
                 })
    return HttpResponse(t.render(c))

@menu_enabled("Talks")    
def talks(request):
    """
    list of all talks who are all registered
    """
    lst = Talk.objects.select_related().order_by('title')
    talk_slot = Slot.objects.all()
    tag_colours = Tag_Colour.objects.all()
    t = loader.get_template('web/talks.html')
    c = RequestContext(request,
                {'lst_list': lst,
                'scheduled':talk_slot, 
                'tag_colours': tag_colours,
                 })
    return HttpResponse(t.render(c))
    
@menu_enabled("Statistics")
def statistics(request):
    """
        find total number of talks and percentage of talks by 
        type, talks by level. Total delegates and percentage
        of delegates by occupation
        """
    #totals of talks and delegates
    talktot =Talk.objects.count()
    deltot =Delegate.objects.count()
    # find percentage of talk types
    categ_count={}
    for categ in Category.objects.all():
        talknum = Talk.objects.filter(category=categ).count()
        if talknum > 0:
            talkpercent = round((float(talknum)/talktot)*100,2)
            categ_count[categ.name] = [talknum,talkpercent]
    # percentage of talk levels
    level_count={}
    for level in levels:
        talknum = Talk.objects.filter(level=level[0]).count()
        if talknum > 0:
            talkpercent = round((float(talknum)/talktot)*100,2)
            level_count[level[1]] = [talknum,talkpercent]
    occup_count ={}
    for occ in Occupation.objects.all():
        talknum = Delegate.objects.filter(occupation=occ).count()
        if talknum > 0:
            talkpercent = round((float(talknum)/deltot)*100,2)
            occup_count[occ.name] = [talknum,talkpercent]
    teesizes = {}
    teetot = 0
    for sz in TEE_SIZES:
        x = Delegate.objects.filter(teesize=sz[0]).count()
        teesizes[sz[1]] = x
        teetot = teetot +x
        
    t = loader.get_template('web/statistics.html')
    c = RequestContext(request,
                {'talktot': talktot,
                'deltot': deltot,
                'categ_count': categ_count,
                'occup_count': occup_count,
                'level_count': level_count,
                'teesizes': teesizes,
                'teetot': teetot,
                 })
    return HttpResponse(t.render(c))

@menu_enabled("Delegates")
def delegatefull(request,id):
    p = Delegate.objects.get(pk=id)
    tak= Talk.objects.filter(speaker=p).order_by('title')
    defph = ''
    if not p.photo:
        try:
            defph = Defaultimage.objects.all().order_by('?')[0]
        except:
            pass
    t = loader.get_template('web/delegatefull.html')
    c = RequestContext(request,
                {'p': p,
                'tak':tak, 
                'defph':defph,
                 })
    return HttpResponse(t.render(c))
    
@menu_enabled("Talks")    
def talkfull(request,id):
    p = Talk.objects.get(pk=id)
    if request.POST:
        # do not allow anonymous users to rate
        if request.user.is_anonymous():
            return HttpResponseRedirect("/login/")
        instance = Talkrating(username=request.user,talk=p)
        form = Talkratingform(request.POST,instance=instance)
        if form.is_valid:
            spklst = p.speaker.all()
            for spk in spklst:
                if request.user == spk.username:
                    form.errors['rating'] = [_("You cannot rate your own talk")]
            try:
                chk = Talkrating.objects.get(username=request.user,talk=p)
                if chk:
                    form.errors['rating'] = [_("You have already rated this talk")]
            except:
                pass
            if not form.errors:
                r = form.save()
                return HttpResponseRedirect("/talkfull/%d/" % int(id))
    else:
        form = Talkratingform()
    t = loader.get_template('web/talkfull.html')
    c = RequestContext(request,
                {'p': p,
                'form': form,
                'speaker': p.speaker.all(),
                })
    return HttpResponse(t.render(c))

@menu_enabled("Volunteer to help")
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/") 
@transaction.commit_on_success
def addvolunteer(request):
    """view to add a volunteer
        """
    instance = {}
    #send users without profiles to profile page
    try:
        delg = Delegate.objects.get(username=request.user)
    except:
        return HttpResponseRedirect("/edituser/")
    # check whether the delegate is a volunteer
    try:
        vol = Volunteer.objects.get(name=delg)
        instance = vol 
    except:
        instance = Volunteer(name = delg)
    if request.POST:
        form = Addvolunteerform(request.POST,instance=instance)
        if form.is_valid():
            newvol = form.save()
            return HttpResponseRedirect("/volunteerfull/%d/" % newvol.id)
        
    else:
        form = Addvolunteerform(instance = instance)
    return render_to_response("web/addvolunteer.html",
                              {'form':form.as_table(),
                               },context_instance=RequestContext(request))

@menu_enabled("Volunteers")
def volunteerfull(request,id):
    """ Display volunteer details based on the id"""
    p = Volunteer.objects.get(pk=id)
    t = loader.get_template('web/voldetails.html')
    c = RequestContext(request,
                {'p': p,
                 })
    return HttpResponse(t.render(c))
    
@menu_enabled("Volunteers")
def volunteers(request):
    """
    list of all volunteers who are all registered
    """
    lst = Volunteer.objects.all()
    t = loader.get_template('web/volunteers.html')
    c = RequestContext(request,
                {'lst': lst,
                 })
    return HttpResponse(t.render(c))

@menu_enabled("Request a talk")    
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/") 
def addreqtalk(request,id=None):
    """view to addrequesttalk
        """
    #send users without profiles to profile page
    try:
        delg = Delegate.objects.get(username=request.user)
    except:
        return HttpResponseRedirect("/edituser/")
    #proceed if there is a delegate id
    if id:
        instance = Requesttalk.objects.get(pk=id)
    else:
        instance = None
    if request.POST:
        form = Addrequesttalkform(request.POST,instance=instance)
        if form.is_valid():
            f = form.save()
            return HttpResponseRedirect("/requesttalk/")
    else:
        form = Addrequesttalkform(instance=instance)
    return render_to_response("web/addreqtalk.html",
                              {'form':form,
                               },context_instance=RequestContext(request))    

@menu_enabled("Requested talks")
def requesttalk(request):
    """
    list of all requested talk.
    """
    lst = Requesttalk.objects.all()
    t = loader.get_template('web/requesttalk.html')
    c = RequestContext(request,
                {'lst': lst,
                 })
    return HttpResponse(t.render(c))


def message(request,msg):
    t = loader.get_template("web/message.html")
    c = RequestContext(request,
                {
                'msg': msg,
                 })
    return HttpResponse(t.render(c))
    




# Function subtract_time is not a part of web-operations.
# It is just a helper function.
def subtract_time(day,end_time,start_time):
    # Without the date (essentially dummy), python
    # returns a tuple beyond the unix epoch.
    end_time_tuple   = time.strptime(unicode(day)+u" "+unicode(end_time),"%Y-%m-%d %H:%M:%S")
    start_time_tuple = time.strptime(unicode(day)+u" "+unicode(start_time),"%Y-%m-%d %H:%M:%S")
    end_time_float   = time.mktime(end_time_tuple)
    start_time_float = time.mktime(start_time_tuple)
    time_diff = end_time_float - start_time_float
    time_diff_float_in_hours = time_diff/3600.0
    return time_diff_float_in_hours

# Another helper function to generate schedule time slots.
def add_time(day,end_time,start_time):
    num_slots = subtract_time(day,end_time,start_time) * 4
    gen_time_list = []
    gen_time = start_time
    for i in range(int(num_slots)+1):
        if gen_time <= end_time:
            gen_time_list.append(datetime.time(gen_time.hour, gen_time.minute).strftime("%H:%M"))
            gen_time_tuple  = time.strptime(unicode(day)+u" "+unicode(gen_time),"%Y-%m-%d %H:%M:%S")
            gen_time_float  = time.mktime(gen_time_tuple)
            # Add 900 seconds. Essentially for a 15 minute slot
            next_slot_float = gen_time_float + 900
            next_slot_tuple = time.localtime(next_slot_float)
            gen_time = datetime.time(next_slot_tuple.tm_hour,next_slot_tuple.tm_min)
    return gen_time_list

def get_schedule(queryset_day,queryset_hall,queryset_slots):
    halls = queryset_hall
    hall_count = halls.count()
    c = []
    for i in range(hall_count):
        c.append((halls[i].id,i))
    hall_dict = dict(c)
    days = queryset_day
    day_count = days.count()
    c = []
    for i in range(day_count):
        c.append((days[i].id,i))
    day_dict = dict(c)
    slots = queryset_slots
    # Initialization of all matrix elements to 0
    schedule_matrix = []
    for day in days:
        time_intervals = add_time(day.confdate,day.conf_end_time,day.conf_start_time)
        total_rows = int(subtract_time(day.confdate,day.conf_end_time,day.conf_start_time) * 4)
        a = []
        for i in range(total_rows+1):
            b = []
            for j in range(hall_count):
                b.append(0)
            a.append((time_intervals[i],b))
        schedule_matrix.append((day,a))

    # Assigning talkid to matrix
    for slot in slots:
        if day_count == 1:
            num_of_rows = len(schedule_matrix[0])
        else:
            num_of_rows = len(schedule_matrix[slot.day.id-1])
        # Time slot the talk falls in and number of slots occupied
        num_slots_for_talk = int(subtract_time(slot.day.confdate,slot.talk_end_time,\
                                           slot.talk_start_time) * 4) 
        num_of_rows_from_first_row = int(subtract_time(slot.day.confdate,slot.talk_start_time,\
                                                       slot.day.conf_start_time) * 4)
        for i in range(num_slots_for_talk):
            # This is for the rowspan thingie.
            if i == 0:
                if day_count == 1:
                    schedule_matrix[0][1][num_of_rows_from_first_row+i][1][0] = ([slot, num_slots_for_talk],)
                else:
                    schedule_matrix[day_dict[slot.day.id]][1]\
                                   [num_of_rows_from_first_row+i][1]\
                                   [hall_dict[slot.hall.id]] = ([slot, num_slots_for_talk],)                    
            else:
                if day_count == 1:
                    schedule_matrix[0][1][num_of_rows_from_first_row+i][1][0] = 1
                else:
                    schedule_matrix[day_dict[slot.day.id]][1]\
                                   [num_of_rows_from_first_row+i][1]\
                                   [hall_dict[slot.hall.id]] = 1
    return (halls, hall_count, slots,schedule_matrix)

@menu_enabled("Make Schedule")    
@user_passes_test(lambda u: isingroup(u,'schedulers') == True,login_url="/login/") 
def schedule(request):
    """
    Returns the schedule of talks.
    """
    halls, hall_count, slots,schedule_matrix = get_schedule(Day.objects.all(),\
                                                            Hall.objects.all().order_by('id'),\
                                                            Slot.objects.all())
    if request.POST:
        schedule_form = ScheduleForm(request.POST)
        if schedule_form.is_valid():
            newslot = schedule_form.save()
            tlk = Talk.objects.get(pk=newslot.talk_id)
            tlk.scheduled = True
            tlk.save()
            return HttpResponseRedirect('/schedule/')
    else:
        schedule_form = ScheduleForm()
    
    t = loader.get_template('web/schedule.html')
    c = RequestContext(request,
                {
                 "schedule_form": schedule_form,
                 "halls": halls,
                 "hall_count": hall_count,
                 "slots": slots,
                 "schedule_data": schedule_matrix,
                })
    return HttpResponse(t.render(c))
    

@menu_enabled("Schedule")    
def displayschedule(request):
    """
    Returns the schedule of talks.
    """
    halls, hall_count, slots,schedule_matrix = get_schedule(Day.objects.all(),\
                                                            Hall.objects.all().order_by('id'),\
                                                            Slot.objects.all())
    
    t = loader.get_template('web/displayschedule.html')
    c = RequestContext(request,{
                 "halls": halls,
                 "hall_count": hall_count,
                 "slots": slots,
                 "schedule_data": schedule_matrix,
                })
    return HttpResponse(t.render(c))

def halldayschedule(request,day,hall):
    """
    Returns the schedule of talks for a hall for a given day.
    """
    halls, hall_count, slots, schedule_matrix = get_schedule(Day.objects.filter(id=day),\
                                                             Hall.objects.filter(id=hall),\
                                                             Slot.objects.filter(\
                                                             Q(hall__id=hall) & Q(day__id=day)))
    t = loader.get_template('web/displayschedule.html')
    c = RequestContext(request,{
                 "halls": halls,
                 "hall_count": hall_count,
                 "slots": slots,
                 "schedule_data": schedule_matrix,
                })
    return HttpResponse(t.render(c))    
    
def deleteslot(request,slot):
    slt = Slot.objects.get(pk=slot)
    slt.delete()
    tlk = Talk.objects.get(pk=slt.talk_id)
    tlk.scheduled = False
    tlk.save()
    return HttpResponseRedirect('/schedule/')





@user_passes_test(lambda u: isingroup(u,'committee') == True,login_url="/login/") 
def bulkmail(request,sstr=''):
    """
    Bulkmailer for the group "committee"
    """
    if not sstr:
        sstr = ''
    if request.POST:
        form = Bulkmailform(sstr,request.POST)
        if 'srch' in request.POST.keys():
                sstr = request.POST['sstr']
                return HttpResponseRedirect("/bulkmail/%s/" %(sstr))
        if form.is_valid():
            fm = form.cleaned_data
            
            subject  = fm['subject']
            message  = fm['message']
            lst = []
            emaillist = []
            if 'spk' in request.POST.keys():
                for talk in Talk.objects.all():
                    for spk in talk.speaker.all():
                        lst.append(spk)
                emaillist = [x.username for x in lst]
                emaillist = list(set(emaillist))
            if 'sel' in request.POST.keys():
                for us in fm['delegates']:
                    emaillist.append(Delegate.objects.get(pk=int(us)).username)
            if 'vol' in request.POST.keys():
                lst = Volunteer.objects.all()
                emaillist = [x.name.username for x in lst]
            if 'del' in request.POST.keys():
                lst = Delegate.objects.all()
                emaillist = [x.username for x in lst]
            frm = 'contact@in.pycon.org'
            
            for user in emaillist:
                salute = ''
                try:
                    salute = "Dear %s %s\n\n" %(user.first_name,user.last_name)
                except:
                    salute = "Dear %s \n\n" %(user.last_name)
                greet = "\n\nPyCon India 2009 team"
                url = "\n\nhttp://in.pycon.org/"
                msg = salute+message+greet+url
                send_id = [user.email]
                emailmsg = EmailMessage(subject,msg,frm,send_id)
                try:
                    emailmsg.send()
                except:
                    pass
            return HttpResponseRedirect("/bulkmail/")
    else:
        form = Bulkmailform(sstr)
    t = loader.get_template('web/bulkmail.html')
    c = RequestContext(request,{
            'form':form,
            })
    return HttpResponse(t.render(c))


def mailsent(request):
    return render_to_response('web/mailsent.html')

@menu_enabled("Browse slides")    
def browseslides(request):
    """browser for presentation materials
        """
    lst = Talk.objects.all()
    t = loader.get_template('web/browseslides.html')
    c = RequestContext(request,
                {'lst':lst,
                 })
    return HttpResponse(t.render(c))
    
def makespeechtarball(request):
    """This will label all the slides and make a tarball with
        index
        """
    #clean the tarball directory
    #get each slide and save it in the directory
    #after saving the slide, add talk title and location to the index
    #tar the directory
    pass

@menu_enabled("Speaker list")
def speakerlist(request):
    lst = Talk.objects.filter(scheduled=True).order_by('title')
    lst = list(lst)
    lst.sort(key=lambda w: w.getschedule())
    talk_slot = Slot.objects.all()
    hal = Hall.objects.all()
    t = loader.get_template('web/speakerlist.html')
    c = RequestContext(request,
                {'lst_list': lst,
                 'scheduled':talk_slot, 
                 'hall':hal, 
                 })
    return HttpResponse(t.render(c))

@menu_enabled("Tag cloud")
def cloud_list(request):
    return render_to_response('web/cloud_list.html', 
                              context_instance=RequestContext(request))
                              
#generate id cards
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/login/")  
def idcard(request):
      
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
    buffer = StringIO()
    p = Delegate.objects.get(username=request.user)
    tak= Talk.objects.filter(speaker=p).order_by('title')
    defph = ''
    if not p.photo:
        try:
            defph = Defaultimage.objects.all().order_by('?')[0]
            defph = str(defph.photo)
        except:
            pass
    else:
        defph = str(p.photo)
    
    # Create the PDF object, using the response object as its "file."
    c = canvas.Canvas(buffer, bottomup = 1, pagesize = A4)
    c.translate(2*cm,2*cm)
    draw_borders(c)
    draw_banner(c)
    draw_image(c)
    c.drawImage("/home/pycon/media/"+defph,0 + cm, 0 + cm, width = 2.5*cm, height = 2.5*cm, preserveAspectRatio = True)
    jndte="Registered on %d/%d/%d" %(p.joindate.day,p.joindate.month,p.joindate.year)
    write_details(c,str(getname(p)),p.organisation,jndte)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.

    # Close the PDF object cleanly, and we're done.
    c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

@user_passes_test(lambda u: isingroup(u,'committee') == True,login_url="/login/")    
def get_delegates(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=delegates.csv'
    dels = Delegate.objects.exclude(private=True)
    writer = csv.writer(response)
    writer.writerow(['Name', 'Email', 'City', 'Occupation','organisation','bio'])
    for dl in dels:
        try:
            writer.writerow([getname(dl),dl.username.email,dl.city,
            dl.occupation,dl.organisation,dl.bio])
        except:
            pass

    return response