summaryrefslogtreecommitdiff
path: root/yaksh/views.py
blob: 0293ae7d5ed73f50549e713ad39ace0d25dffbb8 (plain)
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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
import random
import string
import os
from datetime import datetime, timedelta
import collections
import csv
from django.http import HttpResponse, JsonResponse
from django.core.urlresolvers import reverse
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.http import Http404
from django.db.models import Sum, Max, Q, F
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.forms.models import inlineformset_factory
from django.utils import timezone
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.conf import settings
import pytz
from taggit.models import Tag
from itertools import chain
import json
import six
from textwrap import dedent
import zipfile
try:
    from StringIO import StringIO as string_io
except ImportError:
    from io import BytesIO as string_io
import re
# Local imports.
from yaksh.code_server import get_result as get_result_from_code_server, SERVER_POOL_PORT
from yaksh.models import (
    Answer, AnswerPaper, AssignmentUpload, Course, FileUpload, FloatTestCase,
    HookTestCase, IntegerTestCase, McqTestCase, Profile,
    QuestionPaper, QuestionSet, Quiz, Question, StandardTestCase,
    StdIOBasedTestCase, StringTestCase, TestCase, User,
    get_model_class
)
from yaksh.forms import (
    UserRegisterForm, UserLoginForm, QuizForm, QuestionForm,
    RandomQuestionForm, QuestionFilterForm, CourseForm, ProfileForm,
    UploadFileForm, get_object_form, FileForm, QuestionPaperForm
)
from .settings import URL_ROOT
from .file_utils import extract_files
from .send_emails import send_user_mail, generate_activation_key, send_bulk_mail
from .decorators import email_verified, has_profile


def my_redirect(url):
    """An overridden redirect to deal with URL_ROOT-ing. See settings.py
    for details."""
    return redirect(URL_ROOT + url)


def my_render_to_response(template, context=None, **kwargs):
    """Overridden render_to_response.
    """
    if context is None:
        context = {'URL_ROOT': URL_ROOT}
    else:
        context['URL_ROOT'] = URL_ROOT
    return render_to_response(template, context, **kwargs)


def is_moderator(user):
    """Check if the user is having moderator rights"""
    if user.groups.filter(name='moderator').exists():
        return True


def add_to_group(users):
    """ add users to moderator group """
    group = Group.objects.get(name="moderator")
    for user in users:
        if not is_moderator(user):
            user.groups.add(group)


@email_verified
def index(request, next_url=None):
    """The start page.
    """
    user = request.user
    if user.is_authenticated():
        if is_moderator(user):
            return my_redirect('/exam/manage/' if not next_url else next_url)
        return my_redirect("/exam/quizzes/" if not next_url else next_url)

    return my_redirect("/exam/login/")


def user_register(request):
    """ Register a new user.
    Create a user and corresponding profile and store roll_number also."""

    user = request.user
    ci = RequestContext(request)
    if user.is_authenticated():
        return my_redirect("/exam/quizzes/")
    context = {}
    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            u_name, pwd, user_email, key = form.save()
            new_user = authenticate(username=u_name, password=pwd)
            login(request, new_user)
            if user_email and key:
                success, msg = send_user_mail(user_email, key)
                context = {'activation_msg': msg}
                return my_render_to_response(
                    'yaksh/activation_status.html', context
                )
            return index(request)
        else:
            return my_render_to_response('yaksh/register.html', {'form': form},
                                         context_instance=ci)
    else:
        form = UserRegisterForm()
        return my_render_to_response(
            'yaksh/register.html', {'form': form}, context_instance=ci
        )


def user_logout(request):
    """Show a page to inform user that the quiz has been compeleted."""
    logout(request)
    context = {'message': "You have been logged out successfully"}
    return my_render_to_response('yaksh/complete.html', context)


@login_required
@has_profile
@email_verified
def quizlist_user(request, enrolled=None):
    """Show All Quizzes that is available to logged-in user."""
    user = request.user
    ci = RequestContext(request)

    if request.method == "POST":
        course_code = request.POST.get('course_code')
        hidden_courses = Course.objects.get_hidden_courses(code=course_code)
        courses = hidden_courses if hidden_courses else None
        title = 'Search'

    elif enrolled is not None:
        courses = user.students.all()
        title = 'Enrolled Courses'
    else:
        courses = Course.objects.filter(
            active=True, is_trial=False
        ).exclude(
           ~Q(requests=user), ~Q(rejected=user), hidden=True
        )
        title = 'All Courses'

    context = {'user': user, 'courses': courses, 'title': title}

    return my_render_to_response(
        "yaksh/quizzes_user.html", context, context_instance=ci
    )


@login_required
@email_verified
def results_user(request):
    """Show list of Results of Quizzes that is taken by logged-in user."""
    user = request.user
    papers = AnswerPaper.objects.get_user_answerpapers(user)
    context = {'papers': papers}
    return my_render_to_response("yaksh/results_user.html", context)


@login_required
@email_verified
def add_question(request, question_id=None):
    user = request.user
    ci = RequestContext(request)
    test_case_type = None

    if question_id is None:
        question = Question(user=user)
        question.save()
    else:
        question = Question.objects.get(id=question_id)

    if request.method == "POST" and 'delete_files' in request.POST:
        remove_files_id = request.POST.getlist('clear')
        if remove_files_id:
            files = FileUpload.objects.filter(id__in=remove_files_id)
            for file in files:
                file.remove()

    if request.method == 'POST':
        qform = QuestionForm(request.POST, instance=question)
        fileform = FileForm(request.POST, request.FILES)
        files = request.FILES.getlist('file_field')
        extract_files_id = request.POST.getlist('extract')
        hide_files_id = request.POST.getlist('hide')
        if files:
            for file in files:
                FileUpload.objects.get_or_create(question=question, file=file)
        if extract_files_id:
            files = FileUpload.objects.filter(id__in=extract_files_id)
            for file in files:
                file.set_extract_status()
        if hide_files_id:
            files = FileUpload.objects.filter(id__in=hide_files_id)
            for file in files:
                file.toggle_hide_status()
        formsets = []
        for testcase in TestCase.__subclasses__():
            formset = inlineformset_factory(Question, testcase, extra=0,
                                            fields='__all__')
            formsets.append(formset(
                request.POST, request.FILES, instance=question
                )
            )
        files = request.FILES.getlist('file_field')
        uploaded_files = FileUpload.objects.filter(question_id=question.id)
        if qform.is_valid():
            question = qform.save(commit=False)
            question.user = user
            question.save()
            # many-to-many field save function used to save the tags
            qform.save_m2m()
            for formset in formsets:
                if formset.is_valid():
                    formset.save()
            test_case_type = request.POST.get('case_type', None)
        else:
            context = {
                'qform': qform,
                'fileform': fileform,
                'question': question,
                'formsets': formsets,
                'uploaded_files': uploaded_files
            }
            return my_render_to_response(
                "yaksh/add_question.html", context, context_instance=ci
            )

    qform = QuestionForm(instance=question)
    fileform = FileForm()
    uploaded_files = FileUpload.objects.filter(question_id=question.id)
    formsets = []
    for testcase in TestCase.__subclasses__():
        if test_case_type == testcase.__name__.lower():
            formset = inlineformset_factory(Question, testcase, extra=1,
                                            fields='__all__')
        else:
            formset = inlineformset_factory(Question, testcase, extra=0,
                                            fields='__all__')
        formsets.append(formset(instance=question))
    context = {'qform': qform, 'fileform': fileform, 'question': question,
               'formsets': formsets, 'uploaded_files': uploaded_files}
    return my_render_to_response(
        "yaksh/add_question.html", context, context_instance=ci
    )


@login_required
@email_verified
def add_quiz(request, course_id, quiz_id=None):
    """To add a new quiz in the database.
    Create a new quiz and store it."""
    user = request.user
    course = get_object_or_404(Course, pk=course_id)
    ci = RequestContext(request)
    if not is_moderator(user) or (user != course.creator and user not in course.teachers.all()):
        raise Http404('You are not allowed to view this course !')
    context = {}
    if request.method == "POST":
        if quiz_id is None:
            form = QuizForm(request.POST, user=user, course=course_id)
            if form.is_valid():
                form.save()
                return my_redirect("/exam/manage/courses/")

        else:
            quiz = Quiz.objects.get(id=quiz_id)
            form = QuizForm(request.POST, user=user, course=course_id,
                instance=quiz
            )
            if form.is_valid():
                form.save()
                return my_redirect("/exam/manage/courses/")

    else:
        quiz = Quiz.objects.get(id=quiz_id) if quiz_id else None
        form = QuizForm(user=user,course=course_id, instance=quiz)
        context["quiz_id"] = quiz_id
    context["form"] = form
    return my_render_to_response(
        'yaksh/add_quiz.html', context, context_instance=ci
    )


@login_required
@has_profile
@email_verified
def prof_manage(request, msg=None):
    """Take credentials of the user with professor/moderator
    rights/permissions and log in."""
    user = request.user
    ci = RequestContext(request)
    if user.is_authenticated() and is_moderator(user):
        question_papers = QuestionPaper.objects.filter(
            Q(quiz__course__creator=user) |
            Q(quiz__course__teachers=user),
            quiz__is_trial=False
        ).distinct()
        trial_paper = AnswerPaper.objects.filter(
            user=user, question_paper__quiz__is_trial=True
        )
        if request.method == "POST":
            delete_paper = request.POST.getlist('delete_paper')
            for answerpaper_id in delete_paper:
                answerpaper = AnswerPaper.objects.get(id=answerpaper_id)
                qpaper = answerpaper.question_paper
                if qpaper.quiz.course.is_trial:
                    qpaper.quiz.course.delete()
                else:
                    if qpaper.answerpaper_set.count() == 1:
                        qpaper.quiz.delete()
                    else:
                        answerpaper.delete()
        users_per_paper = []
        for paper in question_papers:
            answer_papers = AnswerPaper.objects.filter(question_paper=paper)
            users_passed = AnswerPaper.objects.filter(
                question_paper=paper, passed=True
            ).count()
            users_failed = AnswerPaper.objects.filter(
                question_paper=paper,
                passed=False
            ).count()
            temp = paper, answer_papers, users_passed, users_failed
            users_per_paper.append(temp)
        context = {'user': user, 'users_per_paper': users_per_paper,
                   'trial_paper': trial_paper, 'msg': msg
                   }
        return my_render_to_response(
            'yaksh/moderator_dashboard.html', context, context_instance=ci
        )
    return my_redirect('/exam/login/')


def user_login(request):
    """Take the credentials of the user and log the user in."""

    user = request.user
    ci = RequestContext(request)
    context = {}
    if user.is_authenticated():
        return index(request)

    next_url = request.GET.get('next')

    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data
            login(request, user)
            return index(request, next_url)
        else:
            context = {"form": form}

    else:
        form = UserLoginForm()
        context = {"form": form}

    return my_render_to_response('yaksh/login.html', context,
                                 context_instance=ci)


@login_required
@email_verified
def start(request, questionpaper_id=None, attempt_num=None):
    """Check the user cedentials and if any quiz is available,
    start the exam."""
    user = request.user
    ci = RequestContext(request)
    # check conditions
    try:
        quest_paper = QuestionPaper.objects.get(id=questionpaper_id)
    except QuestionPaper.DoesNotExist:
        msg = 'Quiz not found, please contact your '\
            'instructor/administrator.'
        return complete(request, msg, attempt_num, questionpaper_id=None)
    if not quest_paper.has_questions():
        msg = 'Quiz does not have Questions, please contact your '\
            'instructor/administrator.'
        return complete(request, msg, attempt_num, questionpaper_id=None)
    if not quest_paper.quiz.course.is_enrolled(user):
        raise Http404('You are not allowed to view this page!')
    # prerequisite check and passing criteria
    if quest_paper.quiz.is_expired() or not quest_paper.quiz.course.active:
        if is_moderator(user):
            return redirect("/exam/manage")
        return redirect("/exam/quizzes")
    if quest_paper.quiz.has_prerequisite() and not quest_paper.is_prerequisite_passed(user):
        if is_moderator(user):
            return redirect("/exam/manage")
        return redirect("/exam/quizzes")
    # if any previous attempt
    last_attempt = AnswerPaper.objects.get_user_last_attempt(
            questionpaper=quest_paper, user=user)
    if last_attempt and last_attempt.is_attempt_inprogress():
        return show_question(
            request, last_attempt.current_question(), last_attempt
        )
    # allowed to start
    if not quest_paper.can_attempt_now(user):
        if is_moderator(user):
            return redirect("/exam/manage")
        return redirect("/exam/quizzes")
    if not last_attempt:
        attempt_number = 1
    else:
        attempt_number = last_attempt.attempt_number + 1
    if attempt_num is None:
        context = {
            'user': user,
            'questionpaper': quest_paper,
            'attempt_num': attempt_number
        }
        if is_moderator(user):
            context["user"] = "moderator"
        return my_render_to_response('yaksh/intro.html', context,
                                     context_instance=ci)
    else:
        ip = request.META['REMOTE_ADDR']
        if not hasattr(user, 'profile'):
            msg = 'You do not have a profile and cannot take the quiz!'
            raise Http404(msg)
        new_paper = quest_paper.make_answerpaper(user, ip, attempt_number)
        if new_paper.status ==  'inprogress':
            return show_question(request, new_paper.current_question(),
                                 new_paper
                                 )
        else:
            msg = 'You have already finished the quiz!'
            raise Http404(msg)

@login_required
@email_verified
def show_question(request, question, paper, error_message=None, notification=None):
    """Show a question if possible."""
    user = request.user
    if not question:
        msg = 'Congratulations!  You have successfully completed the quiz.'
        return complete(
            request, msg, paper.attempt_number, paper.question_paper.id
        )
    if not paper.question_paper.quiz.active:
        reason = 'The quiz has been deactivated!'
        return complete(
            request, reason, paper.attempt_number, paper.question_paper.id
        )
    if paper.time_left() <= 0:
        reason = 'Your time is up!'
        return complete(
            request, reason, paper.attempt_number, paper.question_paper.id
        )
    if question in paper.questions_answered.all():
        notification = (
            'You have already attempted this question successfully'
            if question.type == "code" else
            'You have already attempted this question'
        )
    test_cases = question.get_test_cases()
    files = FileUpload.objects.filter(question_id=question.id, hide=False)
    context = {
        'question': question,
        'paper': paper,
        'error_message': error_message,
        'test_cases': test_cases,
        'files': files,
        'notification': notification,
        'last_attempt': question.snippet.encode('unicode-escape')
    }
    answers = paper.get_previous_answers(question)
    if answers:
        last_attempt = answers[0].answer
        if last_attempt:
            context['last_attempt'] = last_attempt.encode('unicode-escape')
    ci = RequestContext(request)
    return my_render_to_response('yaksh/question.html', context,
                                 context_instance=ci)


@login_required
@email_verified
def skip(request, q_id, next_q=None, attempt_num=None, questionpaper_id=None):
    user = request.user
    paper = get_object_or_404(
        AnswerPaper, user=request.user, attempt_number=attempt_num,
        question_paper=questionpaper_id
    )
    question = get_object_or_404(Question, pk=q_id)

    if request.method == 'POST' and question.type == 'code':
        if not paper.answers.filter(question=question, correct=True).exists():
            user_code = request.POST.get('answer')
            new_answer = Answer(
                question=question, answer=user_code,
                correct=False, skipped=True,
                error=json.dumps([])
            )
            new_answer.save()
            paper.answers.add(new_answer)
    if next_q is not None:
        next_q = get_object_or_404(Question, pk=next_q)
    else:
        next_q = paper.next_question(q_id)
    return show_question(request, next_q, paper)


@login_required
@email_verified
def check(request, q_id, attempt_num=None, questionpaper_id=None):
    """Checks the answers of the user for particular question"""
    user = request.user
    paper = get_object_or_404(
        AnswerPaper,
        user=request.user,
        attempt_number=attempt_num,
        question_paper=questionpaper_id
    )
    current_question = get_object_or_404(Question, pk=q_id)

    if request.method == 'POST':
        # Add the answer submitted, regardless of it being correct or not.
        if current_question.type == 'mcq':
            user_answer = request.POST.get('answer')
        elif current_question.type == 'integer':
            try:
                user_answer = int(request.POST.get('answer'))
            except ValueError:
                msg = "Please enter an Integer Value"
                return show_question(
                    request, current_question, paper, notification=msg
                )
        elif current_question.type == 'float':
            try:
                user_answer = float(request.POST.get('answer'))
            except ValueError:
                msg = "Please enter a Float Value"
                return show_question(request, current_question,
                                     paper, notification=msg)
        elif current_question.type == 'string':
            user_answer = str(request.POST.get('answer'))

        elif current_question.type == 'mcc':
            user_answer = request.POST.getlist('answer')
        elif current_question.type == 'upload':
            # if time-up at upload question then the form is submitted without
            # validation
            assignment_filename = request.FILES.getlist('assignment')
            if not assignment_filename:
                msg = "Please upload assignment file"
                return show_question(
                    request, current_question, paper, notification=msg
                )
            for fname in assignment_filename:
                assignment_files = AssignmentUpload.objects.filter(
                            assignmentQuestion=current_question,
                            assignmentFile__icontains=fname, user=user,
                            question_paper=questionpaper_id)
                if assignment_files.exists():
                    assign_file = assignment_files.get(
                            assignmentQuestion=current_question,
                            assignmentFile__icontains=fname, user=user,
                            question_paper=questionpaper_id)
                    os.remove(assign_file.assignmentFile.path)
                    assign_file.delete()
                AssignmentUpload.objects.create(
                    user=user, assignmentQuestion=current_question,
                    assignmentFile=fname, question_paper_id=questionpaper_id
                )
            user_answer = 'ASSIGNMENT UPLOADED'
            if not current_question.grade_assignment_upload:
                new_answer = Answer(
                    question=current_question, answer=user_answer,
                    correct=False, error=json.dumps([])
                )
                new_answer.save()
                paper.answers.add(new_answer)
                next_q = paper.add_completed_question(current_question.id)
                return show_question(request, next_q, paper)
        else:
            user_answer = request.POST.get('answer')
        if not user_answer:
            msg = "Please submit a valid answer."
            return show_question(
                request, current_question, paper, notification=msg
            )
        if current_question in paper.get_questions_answered()\
         and current_question.type not in ['code', 'upload']:
            new_answer = paper.get_latest_answer(current_question.id)
            new_answer.answer = user_answer
            new_answer.correct = False
        else:
            new_answer = Answer(
            question=current_question, answer=user_answer,
            correct=False, error=json.dumps([])
        )
        new_answer.save()
        uid = new_answer.id
        paper.answers.add(new_answer)
        # If we were not skipped, we were asked to check.  For any non-mcq
        # questions, we obtain the results via XML-RPC with the code executed
        # safely in a separate process (the code_server.py) running as nobody.
        json_data = current_question.consolidate_answer_data(user_answer, user) \
            if current_question.type == 'code' or \
            current_question.type == 'upload' else None
        result = paper.validate_answer(
            user_answer, current_question, json_data, uid
        )
        if current_question.type in ['code', 'upload']:
            if paper.time_left() <= 0:
                url = 'http://localhost:%s' % SERVER_POOL_PORT
                result_details = get_result_from_code_server(url, uid, block=True)
                result = json.loads(result_details.get('result'))
                next_question, error_message, paper = _update_paper(request, uid,
                        result)
                return show_question(request, next_question, paper, error_message)
            else:
                return JsonResponse(result)
        else:
            next_question, error_message, paper = _update_paper(request, uid, result)
            return show_question(request, next_question, paper, error_message)
    else:
        return show_question(request, current_question, paper)


@csrf_exempt
def get_result(request, uid):
    result = {}
    url = 'http://localhost:%s' % SERVER_POOL_PORT
    result_state = get_result_from_code_server(url, uid)
    result['status'] = result_state.get('status')
    if result['status'] == 'done':
        result = json.loads(result_state.get('result'))
        next_question, error_message, paper = _update_paper(request, uid, result)
        return show_question(request, next_question, paper, error_message)
    return JsonResponse(result)


def _update_paper(request, uid, result):
    new_answer = Answer.objects.get(id=uid)
    current_question = new_answer.question
    paper = new_answer.answerpaper_set.first()

    if result.get('success'):
        new_answer.marks = (current_question.points * result['weight'] /
            current_question.get_maximum_test_case_weight()) \
            if current_question.partial_grading and \
            current_question.type == 'code' or current_question.type == 'upload' \
            else current_question.points
        new_answer.correct = result.get('success')
        error_message = None
        new_answer.error = json.dumps(result.get('error'))
        next_question = paper.add_completed_question(current_question.id)
    else:
        new_answer.marks = (current_question.points * result['weight'] /
            current_question.get_maximum_test_case_weight()) \
            if current_question.partial_grading and \
            current_question.type == 'code' or current_question.type == 'upload' \
            else 0
        error_message = result.get('error') if current_question.type == 'code' \
            or current_question.type == 'upload' else None
        new_answer.error = json.dumps(result.get('error'))
        next_question = current_question if current_question.type == 'code' \
            or current_question.type == 'upload' \
            else paper.add_completed_question(current_question.id)
    new_answer.save()
    paper.update_marks('inprogress')
    paper.set_end_time(timezone.now())
    return next_question, error_message, paper


@login_required
@email_verified
def quit(request, reason=None, attempt_num=None, questionpaper_id=None):
    """Show the quit page when the user logs out."""
    paper = AnswerPaper.objects.get(user=request.user,
                                    attempt_number=attempt_num,
                                    question_paper=questionpaper_id)
    context = {'paper': paper, 'message': reason}
    return my_render_to_response('yaksh/quit.html', context,
                                 context_instance=RequestContext(request))


@login_required
@email_verified
def complete(request, reason=None, attempt_num=None, questionpaper_id=None):
    """Show a page to inform user that the quiz has been compeleted."""
    user = request.user
    if questionpaper_id is None:
        message = reason or "An Unexpected Error occurred. Please contact your '\
            'instructor/administrator.'"
        context = {'message': message}
        return my_render_to_response('yaksh/complete.html', context)
    else:
        q_paper = QuestionPaper.objects.get(id=questionpaper_id)
        paper = AnswerPaper.objects.get(
            user=user, question_paper=q_paper,
            attempt_number=attempt_num
        )
        paper.update_marks()
        paper.set_end_time(timezone.now())
        message = reason or "Quiz has been submitted"
        context = {'message': message, 'paper': paper}
        return my_render_to_response('yaksh/complete.html', context)


@login_required
@email_verified
def add_course(request, course_id=None):
    user = request.user
    ci = RequestContext(request)
    if course_id:
        course = Course.objects.get(id=course_id)
    else:
        course = None

    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')
    if request.method == 'POST':
        form = CourseForm(request.POST, instance=course)
        if form.is_valid():
            new_course = form.save(commit=False)
            new_course.creator = user
            new_course.save()
            return my_redirect('/exam/manage/')
        else:
            return my_render_to_response(
                'yaksh/add_course.html', {'form': form}, context_instance=ci
            )
    else:
        form = CourseForm(instance=course)
        return my_render_to_response(
            'yaksh/add_course.html', {'form': form}, context_instance=ci
        )


@login_required
@email_verified
def enroll_request(request, course_id):
    user = request.user
    ci = RequestContext(request)
    course = get_object_or_404(Course, pk=course_id)
    if not course.is_active_enrollment and course.hidden:
        msg = (
            'Unable to add enrollments for this course, please contact your '
            'instructor/administrator.'
        )
        return complete(request, msg, attempt_num=None, questionpaper_id=None)

    course.request(user)
    if is_moderator(user):
        return my_redirect('/exam/manage/courses')
    else:
        return my_redirect('/exam/quizzes/')


@login_required
@email_verified
def self_enroll(request, course_id):
    user = request.user
    ci = RequestContext(request)
    course = get_object_or_404(Course, pk=course_id)
    if course.is_self_enroll():
        was_rejected = False
        course.enroll(was_rejected, user)
    if is_moderator(user):
        return my_redirect('/exam/manage/')
    else:
        return my_redirect('/exam/quizzes/')


@login_required
@email_verified
def courses(request):
    user = request.user
    ci = RequestContext(request)
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')
    courses = Course.objects.filter(creator=user, is_trial=False)
    allotted_courses = Course.objects.filter(teachers=user, is_trial=False)
    context = {'courses': courses, "allotted_courses": allotted_courses}
    return my_render_to_response('yaksh/courses.html', context,
                                 context_instance=ci)


@login_required
@email_verified
def course_detail(request, course_id):
    user = request.user
    ci = RequestContext(request)

    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')

    course = get_object_or_404(Course, pk=course_id)
    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('This course does not belong to you')

    return my_render_to_response(
        'yaksh/course_detail.html', {'course': course}, context_instance=ci
    )


@login_required
@email_verified
def enroll(request, course_id, user_id=None, was_rejected=False):
    user = request.user
    ci = RequestContext(request)
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')

    course = get_object_or_404(Course, pk=course_id)
    if not course.is_active_enrollment:
        msg = (
            'Enrollment for this course has been closed,'
            ' please contact your '
            'instructor/administrator.'
        )
        return complete(request, msg, attempt_num=None, questionpaper_id=None)

    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('This course does not belong to you')

    if request.method == 'POST':
        enroll_ids = request.POST.getlist('check')
    else:
        enroll_ids = [user_id]
    if not enroll_ids:
        return my_render_to_response(
            'yaksh/course_detail.html', {'course': course}, context_instance=ci
        )
    users = User.objects.filter(id__in=enroll_ids)
    course.enroll(was_rejected, *users)
    return course_detail(request, course_id)


@login_required
@email_verified
def send_mail(request, course_id, user_id=None):
    user = request.user
    ci = RequestContext(request)
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')

    course = get_object_or_404(Course, pk=course_id)
    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('This course does not belong to you')

    message = None
    if request.method == 'POST':
        user_ids = request.POST.getlist('check')
        if request.POST.get('send_mail') == 'send_mail':
            users = User.objects.filter(id__in=user_ids)
            recipients = [student.email for student in users]
            email_body = request.POST.get('body')
            subject = request.POST.get('subject')
            attachments = request.FILES.getlist('email_attach')
            message = send_bulk_mail(
                subject, email_body, recipients, attachments
            )
    context = {
        'course': course, 'message': message,
        'state': 'mail'
    }
    return my_render_to_response(
        'yaksh/course_detail.html', context, context_instance=ci
    )


@login_required
@email_verified
def reject(request, course_id, user_id=None, was_enrolled=False):
    user = request.user
    ci = RequestContext(request)
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')

    course = get_object_or_404(Course, pk=course_id)
    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('This course does not belong to you')

    if request.method == 'POST':
        reject_ids = request.POST.getlist('check')
    else:
        reject_ids = [user_id]
    if not reject_ids:
        message = "Please select atleast one User"
        return my_render_to_response(
            'yaksh/course_detail.html', {'course': course, 'message': message},
            context_instance=ci
        )
    users = User.objects.filter(id__in=reject_ids)
    course.reject(was_enrolled, *users)
    return course_detail(request, course_id)


@login_required
@email_verified
def toggle_course_status(request, course_id):
    user = request.user
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')

    course = get_object_or_404(Course, pk=course_id)
    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('This course does not belong to you')

    if course.active:
        course.deactivate()
    else:
        course.activate()
    course.save()
    return course_detail(request, course_id)


@login_required
@email_verified
def show_statistics(request, questionpaper_id, attempt_number=None):
    user = request.user
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page')
    attempt_numbers = AnswerPaper.objects.get_attempt_numbers(questionpaper_id)
    quiz = get_object_or_404(QuestionPaper, pk=questionpaper_id).quiz
    if attempt_number is None:
        context = {'quiz': quiz, 'attempts': attempt_numbers,
                   'questionpaper_id': questionpaper_id}
        return my_render_to_response('yaksh/statistics_question.html', context,
                                     context_instance=RequestContext(request))
    total_attempt = AnswerPaper.objects.get_count(questionpaper_id,
                                                  attempt_number)
    if not AnswerPaper.objects.has_attempt(questionpaper_id, attempt_number):
        return my_redirect('/exam/manage/')
    question_stats = AnswerPaper.objects.get_question_statistics(
        questionpaper_id, attempt_number
    )
    context = {'question_stats': question_stats, 'quiz': quiz,
               'questionpaper_id': questionpaper_id,
               'attempts': attempt_numbers, 'total': total_attempt}
    return my_render_to_response('yaksh/statistics_question.html', context,
                                 context_instance=RequestContext(request))


@login_required
@email_verified
def monitor(request, quiz_id=None):
    """Monitor the progress of the papers taken so far."""

    user = request.user
    ci = RequestContext(request)
    if not user.is_authenticated() or not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if quiz_id is None:
        course_details = Course.objects.filter(
            Q(creator=user) | Q(teachers=user),
            is_trial=False
        ).distinct()
        context = {
            "papers": [], "course_details": course_details,
            "msg": "Monitor"
        }
        return my_render_to_response(
            'yaksh/monitor.html', context, context_instance=ci
        )
    # quiz_id is not None.
    try:
        quiz = get_object_or_404(Quiz, id=quiz_id)
        if not quiz.course.is_creator(user) and not quiz.course.is_teacher(user):
            raise Http404('This course does not belong to you')
        q_paper = QuestionPaper.objects.filter(Q(quiz__course__creator=user) |
                                               Q(quiz__course__teachers=user),
                                               quiz__is_trial=False,
                                               quiz_id=quiz_id).distinct()
    except QuestionPaper.DoesNotExist:
        papers = []
        q_paper = None
        latest_attempts = []
        attempt_numbers = []
    else:
        if q_paper:
            attempt_numbers = AnswerPaper.objects.get_attempt_numbers(q_paper.last().id)
        else:
            attempt_numbers = []
        latest_attempts = []
        papers = AnswerPaper.objects.filter(question_paper=q_paper).order_by(
            'user__profile__roll_number'
        )
        users = papers.values_list('user').distinct()
        for auser in users:
            last_attempt = papers.filter(user__in=auser).aggregate(
                last_attempt_num=Max('attempt_number')
            )
            latest_attempts.append(
                papers.get(
                    user__in=auser,
                    attempt_number=last_attempt['last_attempt_num']
                )
            )
    csv_fields = ['name', 'username', 'roll_number', 'institute',
            'department', 'questions', 'total', 'out_of', 'percentage', 'status']
    context = {
        "papers": papers,
        "quiz": quiz,
        "msg": "Quiz Results",
        "latest_attempts": latest_attempts,
        "csv_fields": csv_fields,
        "attempt_numbers": attempt_numbers
    }
    return my_render_to_response('yaksh/monitor.html', context,
                                 context_instance=ci)


@csrf_exempt
def ajax_questions_filter(request):
    """Ajax call made when filtering displayed questions."""

    user = request.user
    filter_dict = {"user_id": user.id, "active": True}
    question_type = request.POST.get('question_type')
    marks = request.POST.get('marks')
    language = request.POST.get('language')

    if question_type != "select":
        filter_dict['type'] = str(question_type)

    if marks != "select":
        filter_dict['points'] = marks

    if language != "select":
        filter_dict['language'] = str(language)
    questions = list(Question.objects.filter(**filter_dict))

    return my_render_to_response(
        'yaksh/ajax_question_filter.html', {'questions': questions}
    )


def _get_questions(user, question_type, marks):
    if question_type is None and marks is None:
        return None
    if question_type:
        questions = Question.objects.filter(
            type=question_type,
            user=user,
            active=True
        )
        if marks:
            questions = questions.filter(points=marks)
    return questions


def _remove_already_present(questionpaper_id, questions):
    if questionpaper_id is None:
        return questions
    questionpaper = QuestionPaper.objects.get(pk=questionpaper_id)
    questions = questions.exclude(
            id__in=questionpaper.fixed_questions.values_list('id', flat=True))
    for random_set in questionpaper.random_questions.all():
        questions = questions.exclude(
                id__in=random_set.questions.values_list('id', flat=True))
    return questions


@login_required
@email_verified
def design_questionpaper(request, quiz_id, questionpaper_id=None):
    user = request.user

    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    quiz = Quiz.objects.get(id=quiz_id)
    if not quiz.course.is_creator(user) and not quiz.course.is_teacher(user):
        raise Http404('This course does not belong to you')
    filter_form = QuestionFilterForm(user=user)
    questions = None
    marks = None
    state = None
    if questionpaper_id is None:
        question_paper = QuestionPaper.objects.get_or_create(quiz_id=quiz_id)[0]
    else:
        question_paper = get_object_or_404(QuestionPaper, id=questionpaper_id)
    qpaper_form = QuestionPaperForm(instance=question_paper)

    if request.method == 'POST':

        filter_form = QuestionFilterForm(request.POST, user=user)
        qpaper_form = QuestionPaperForm(request.POST, instance=question_paper)
        question_type = request.POST.get('question_type', None)
        marks = request.POST.get('marks', None)
        state = request.POST.get('is_active', None)

        if 'add-fixed' in request.POST:
            question_ids = request.POST.get('checked_ques', None)
            if question_paper.fixed_question_order:
                ques_order = question_paper.fixed_question_order.split(",") +\
                            question_ids.split(",")
                questions_order = ",".join(ques_order)
            else:
                questions_order = question_ids
            questions = Question.objects.filter(id__in=question_ids.split(','))
            question_paper.fixed_question_order = questions_order
            question_paper.save()
            question_paper.fixed_questions.add(*questions)

        if 'remove-fixed' in request.POST:
            question_ids = request.POST.getlist('added-questions', None)
            if question_paper.fixed_question_order:
                que_order = question_paper.fixed_question_order.split(",")
                for qid in question_ids:
                    que_order.remove(qid)
                if que_order:
                    question_paper.fixed_question_order = ",".join(que_order)
                else:
                    question_paper.fixed_question_order = ""
                question_paper.save()
            question_paper.fixed_questions.remove(*question_ids)

        if 'add-random' in request.POST:
            question_ids = request.POST.getlist('random_questions', None)
            num_of_questions = request.POST.get('num_of_questions', 1)
            if question_ids and marks:
                random_set = QuestionSet(marks=marks, num_questions=num_of_questions)
                random_set.save()
                for question in Question.objects.filter(id__in=question_ids):
                    random_set.questions.add(question)
                question_paper.random_questions.add(random_set)

        if 'remove-random' in request.POST:
            random_set_ids = request.POST.getlist('random_sets', None)
            question_paper.random_questions.remove(*random_set_ids)

        if 'save' in request.POST or 'back' in request.POST:
            qpaper_form.save()
            return my_redirect('/exam/manage/courses/')

        if marks:
            questions = _get_questions(user, question_type, marks)
            questions = _remove_already_present(questionpaper_id, questions)

        question_paper.update_total_marks()
        question_paper.save()
    random_sets = question_paper.random_questions.all()
    fixed_questions = question_paper.get_ordered_questions()
    context = {
        'qpaper_form': qpaper_form,
        'filter_form': filter_form,
        'qpaper': question_paper,
        'questions': questions,
        'fixed_questions': fixed_questions,
        'state': state,
        'random_sets': random_sets
    }
    return my_render_to_response(
        'yaksh/design_questionpaper.html',
        context,
        context_instance=RequestContext(request)
    )


@login_required
@email_verified
def show_all_questions(request):
    """Show a list of all the questions currently in the database."""

    user = request.user
    ci = RequestContext(request)
    context = {}
    if not is_moderator(user):
        raise Http404("You are not allowed to view this page !")

    questions = Question.objects.filter(user_id=user.id, active=True)
    form = QuestionFilterForm(user=user)
    user_tags = questions.values_list('tags', flat=True).distinct()
    all_tags = Tag.objects.filter(id__in = user_tags)
    upload_form = UploadFileForm()
    context['questions'] = questions
    context['all_tags'] = all_tags
    context['papers'] = []
    context['question'] = None
    context['form'] = form
    context['upload_form'] = upload_form

    if request.method == 'POST':
        if request.POST.get('delete') == 'delete':
            data = request.POST.getlist('question')
            if data is not None:
                questions = Question.objects.filter(id__in=data, user_id=user.id,
                                                    active=True)
                for question in questions:
                    question.active = False
                    question.save()

        if request.POST.get('upload') == 'upload':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                questions_file = request.FILES['file']
                file_name = questions_file.name.split('.')
                if file_name[-1] == "zip":
                    ques = Question()
                    files, extract_path = extract_files(questions_file)
                    context['message'] = ques.read_yaml(extract_path, user,
                                                        files)
                else:
                    message = "Please Upload a ZIP file"
                    context['message'] = message

        if request.POST.get('download') == 'download':
            question_ids = request.POST.getlist('question')
            if question_ids:
                question = Question()
                zip_file = question.dump_questions(question_ids, user)
                response = HttpResponse(content_type='application/zip')
                response['Content-Disposition'] = dedent(
                    '''attachment; filename={0}_questions.zip'''.format(user)
                )
                zip_file.seek(0)
                response.write(zip_file.read())
                return response
            else:
                context['msg'] = "Please select atleast one question to download"

        if request.POST.get('test') == 'test':
            question_ids = request.POST.getlist("question")
            if question_ids:
                trial_paper = test_mode(user, False, question_ids, None)
                trial_paper.update_total_marks()
                trial_paper.save()
                return my_redirect("/exam/start/1/{0}".format(trial_paper.id))
            else:
                context["msg"] = "Please select atleast one question to test"

        if request.POST.get('question_tags'):
            question_tags = request.POST.getlist("question_tags")
            search_tags = []
            for tags in question_tags:
                search_tags.extend(re.split('[; |, |\*|\n]',tags))
            search_result = Question.objects.filter(tags__name__in=search_tags,
                                                    user=user).distinct()
            context['questions'] = search_result

    return my_render_to_response('yaksh/showquestions.html', context,
                                 context_instance=ci)


@login_required
@email_verified
def user_data(request, user_id, questionpaper_id=None):
    """Render user data."""
    current_user = request.user
    if not current_user.is_authenticated() or not is_moderator(current_user):
        raise Http404('You are not allowed to view this page!')
    user = User.objects.get(id=user_id)
    data = AnswerPaper.objects.get_user_data(user, questionpaper_id)

    context = {'data': data}
    return my_render_to_response('yaksh/user_data.html', context,
                                 context_instance=RequestContext(request))


def _expand_questions(questions, field_list):
    i = field_list.index('questions')
    field_list.remove('questions')
    for question in questions:
        field_list.insert(i, '{0}-{1}'.format(question.summary, question.points))
    return field_list 


@login_required
@email_verified
def download_quiz_csv(request, course_id, quiz_id):
    current_user = request.user
    if not is_moderator(current_user):
        raise Http404('You are not allowed to view this page!')
    course = get_object_or_404(Course, id=course_id)
    quiz = get_object_or_404(Quiz, id=quiz_id)
    if not course.is_creator(current_user) and not course.is_teacher(current_user):
        raise Http404('The quiz does not belong to your course')
    users = course.get_enrolled().order_by('first_name')
    if not users:
        return monitor(request, quiz_id)
    csv_fields = []
    attempt_number = None
    question_paper = quiz.questionpaper_set.last()
    last_attempt_number =AnswerPaper.objects.get_attempt_numbers(question_paper.id).last()
    if request.method == 'POST':
        csv_fields = request.POST.getlist('csv_fields')
        attempt_number = request.POST.get('attempt_number', last_attempt_number)
    if not csv_fields:
        csv_fields = ['name', 'username', 'roll_number', 'institute',
                'department', 'questions', 'total', 'out_of', 'percentage', 'status']
    if not attempt_number:
        attempt_number = last_attempt_number

    questions = question_paper.get_question_bank()
    answerpapers = AnswerPaper.objects.filter(question_paper=question_paper,
            attempt_number=attempt_number)
    if not answerpapers:
        return monitor(request, quiz_id)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{0}-{1}-attempt{2}.csv"'.format(
            course.name.replace('.', ''),  quiz.description.replace('.', ''),
            attempt_number)
    writer = csv.writer(response)
    if 'questions' in csv_fields:
        csv_fields = _expand_questions(questions, csv_fields)
    writer.writerow(csv_fields)

    csv_fields_values = {'name': 'user.get_full_name().title()',
            'roll_number': 'user.profile.roll_number',
            'institute': 'user.profile.institute',
            'department': 'user.profile.department',
            'username': 'user.username', 'total': 'answerpaper.marks_obtained',
            'out_of': 'question_paper.total_marks',
            'percentage': 'answerpaper.percent', 'status': 'answerpaper.status'}
    questions_scores = {}
    for question in questions:
        questions_scores['{0}-{1}'.format(question.summary, question.points)] \
                = 'answerpaper.get_per_question_score({0})'.format(question.id) 
    csv_fields_values.update(questions_scores)

    users = users.exclude(id=course.creator.id).exclude(id__in=course.teachers.all())
    for user in users:
        row = []
        answerpaper = None
        papers = answerpapers.filter(user=user)
        if papers:
            answerpaper = papers.first()
        for field in csv_fields:
            try:
                row.append(eval(csv_fields_values[field]))
            except AttributeError:
                row.append('-')
        writer.writerow(row)
    return response


@login_required
@email_verified
def grade_user(request, quiz_id=None, user_id=None, attempt_number=None):
    """Present an interface with which we can easily grade a user's papers
    and update all their marks and also give comments for each paper.
    """
    current_user = request.user
    ci = RequestContext(request)
    if not current_user.is_authenticated() or not is_moderator(current_user):
        raise Http404('You are not allowed to view this page!')
    course_details = Course.objects.filter(Q(creator=current_user) |
                                           Q(teachers=current_user),
                                           is_trial=False).distinct()
    context = {"course_details": course_details}
    if quiz_id is not None:
        questionpaper_id = QuestionPaper.objects.filter(
            quiz_id=quiz_id
        ).values("id")
        user_details = AnswerPaper.objects.get_users_for_questionpaper(
            questionpaper_id
        )
        quiz = get_object_or_404(Quiz, id=quiz_id)
        if not quiz.course.is_creator(current_user) and not \
                quiz.course.is_teacher(current_user):
            raise Http404('This course does not belong to you')

        has_quiz_assignments = AssignmentUpload.objects.filter(
                                question_paper_id=questionpaper_id
                                ).exists()
        context = {
            "users": user_details,
            "quiz_id": quiz_id,
            "quiz": quiz,
            "has_quiz_assignments": has_quiz_assignments
        }
        if user_id is not None:
            attempts = AnswerPaper.objects.get_user_all_attempts(
                questionpaper_id, user_id
            )
            try:
                if attempt_number is None:
                    attempt_number = attempts[0].attempt_number
            except IndexError:
                raise Http404('No attempts for paper')
            has_user_assignments = AssignmentUpload.objects.filter(
                                question_paper_id=questionpaper_id,
                                user_id=user_id
                                ).exists()
            user = User.objects.get(id=user_id)
            data = AnswerPaper.objects.get_user_data(
                user, questionpaper_id, attempt_number
            )
            context = {
                "data": data,
                "quiz_id": quiz_id,
                "users": user_details,
                "attempts": attempts,
                "user_id": user_id,
                "has_user_assignments": has_user_assignments,
                "has_quiz_assignments": has_quiz_assignments
            }
    if request.method == "POST":
        papers = data['papers']
        for paper in papers:
            for question, answers in six.iteritems(paper.get_question_answers()):
                marks = float(request.POST.get('q%d_marks' % question.id, 0))
                answer = answers[-1]['answer']
                answer.set_marks(marks)
                answer.save()
            paper.update_marks()
            paper.comments = request.POST.get(
                'comments_%d' % paper.question_paper.id, 'No comments')
            paper.save()

    return my_render_to_response(
        'yaksh/grade_user.html', context, context_instance=ci
    )


@login_required
@has_profile
@email_verified
def view_profile(request):
    """ view moderators and users profile """
    user = request.user
    ci = RequestContext(request)
    if is_moderator(user):
        template = 'manage.html'
    else:
        template = 'user.html'
    context = {'template': template, 'user': user}
    return my_render_to_response('yaksh/view_profile.html', context)


@login_required
@has_profile
@email_verified
def edit_profile(request):
    """ edit profile details facility for moderator and students """

    user = request.user
    ci = RequestContext(request)
    if is_moderator(user):
        template = 'manage.html'
    else:
        template = 'user.html'
    context = {'template': template}
    profile = Profile.objects.get(user_id=user.id)

    if request.method == 'POST':
        form = ProfileForm(request.POST, user=user, instance=profile)
        if form.is_valid():
            form_data = form.save(commit=False)
            form_data.user = user
            form_data.user.first_name = request.POST['first_name']
            form_data.user.last_name = request.POST['last_name']
            form_data.user.save()
            form_data.save()
            return my_render_to_response(
                'yaksh/profile_updated.html', context_instance=ci
            )
        else:
            context['form'] = form
            return my_render_to_response(
                'yaksh/editprofile.html', context, context_instance=ci
            )
    else:
        form = ProfileForm(user=user, instance=profile)
        context['form'] = form
        return my_render_to_response(
            'yaksh/editprofile.html', context, context_instance=ci
        )


@login_required
@email_verified
def search_teacher(request, course_id):
    """ search teachers for the course """
    user = request.user
    ci = RequestContext(request)

    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    context = {'success': False}
    course = get_object_or_404(Course, pk=course_id)
    context['course'] = course

    if user != course.creator and user not in course.teachers.all():
        raise Http404('You are not allowed to view this page!')

    if request.method == 'POST':
        u_name = request.POST.get('uname')
        if not len(u_name) == 0:
            teachers = User.objects.filter(
                Q(username__icontains=u_name) |
                Q(first_name__icontains=u_name) |
                Q(last_name__icontains=u_name) |
                Q(email__icontains=u_name)
            ).exclude(
                Q(id=user.id) |
                Q(is_superuser=1) |
                Q(id=course.creator.id)
            )
            context['success'] = True
            context['teachers'] = teachers
    return my_render_to_response(
        'yaksh/addteacher.html', context, context_instance=ci
    )


@login_required
@email_verified
def add_teacher(request, course_id):
    """ add teachers to the course """

    user = request.user
    ci = RequestContext(request)

    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    context = {}
    course = get_object_or_404(Course, pk=course_id)
    if user == course.creator or user in course.teachers.all():
        context['course'] = course
    else:
        raise Http404('You are not allowed to view this page!')

    if request.method == 'POST':
        teacher_ids = request.POST.getlist('check')
        teachers = User.objects.filter(id__in=teacher_ids)
        add_to_group(teachers)
        course.add_teachers(*teachers)
        context['status'] = True
        context['teachers_added'] = teachers
    return my_render_to_response(
        'yaksh/addteacher.html', context, context_instance=ci
    )


@login_required
@email_verified
def remove_teachers(request, course_id):
    """ remove user from a course """

    user = request.user
    course = get_object_or_404(Course, pk=course_id)
    if not is_moderator(user) and (user != course.creator and user
        not in course.teachers.all()):
        raise Http404('You are not allowed to view this page!')

    if request.method == "POST":
        teacher_ids = request.POST.getlist('remove')
        teachers = User.objects.filter(id__in=teacher_ids)
        course.remove_teachers(*teachers)
    return my_redirect('/exam/manage/courses')


def test_mode(user, godmode=False, questions_list=None, quiz_id=None):
    """creates a trial question paper for the moderators"""

    if questions_list is not None:
        trial_course = Course.objects.create_trial_course(user)
        trial_quiz = Quiz.objects.create_trial_quiz(trial_course, user)
        trial_questionpaper = QuestionPaper.objects.create_trial_paper_to_test_questions(
            trial_quiz, questions_list
        )
    else:
        trial_quiz = Quiz.objects.create_trial_from_quiz(
            quiz_id, user, godmode
        )
        trial_questionpaper = QuestionPaper.objects.create_trial_paper_to_test_quiz(
            trial_quiz, quiz_id
        )
    return trial_questionpaper


@login_required
@email_verified
def test_quiz(request, mode, quiz_id):
    """creates a trial quiz for the moderators"""
    godmode = True if mode == "godmode" else False
    current_user = request.user
    quiz = Quiz.objects.get(id=quiz_id)
    if (quiz.is_expired() or not quiz.active) and not godmode:
        return my_redirect('/exam/manage')

    trial_questionpaper = test_mode(current_user, godmode, None, quiz_id)
    return my_redirect("/exam/start/{0}".format(trial_questionpaper.id))


@login_required
@email_verified
def view_answerpaper(request, questionpaper_id):
    user = request.user
    quiz = get_object_or_404(QuestionPaper, pk=questionpaper_id).quiz
    if quiz.view_answerpaper and user in quiz.course.students.all():
        data = AnswerPaper.objects.get_user_data(user, questionpaper_id)
        has_user_assignment = AssignmentUpload.objects.filter(
            user=user,
            question_paper_id=questionpaper_id
        ).exists()
        context = {'data': data, 'quiz': quiz,
                   "has_user_assignment": has_user_assignment}
        return my_render_to_response('yaksh/view_answerpaper.html', context)
    else:
        return my_redirect('/exam/quizzes/')


@login_required
@email_verified
def create_demo_course(request):
    """ creates a demo course for user """
    user = request.user
    ci = RequestContext(request)
    if not is_moderator(user):
        raise("You are not allowed to view this page")
    demo_course = Course()
    success = demo_course.create_demo(user)
    if success:
        msg = "Created Demo course successfully"
    else:
        msg = "Demo course already created"
    return prof_manage(request, msg)


@login_required
@email_verified
def grader(request, extra_context=None):
    user = request.user
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    courses = Course.objects.filter(is_trial=False)
    user_courses = list(courses.filter(creator=user)) + list(courses.filter(teachers=user))
    context = {'courses': user_courses}
    if extra_context:
        context.update(extra_context)
    return my_render_to_response('yaksh/regrade.html', context)


@login_required
@email_verified
def regrade(request, course_id, question_id=None, answerpaper_id=None, questionpaper_id=None):
    user = request.user
    course = get_object_or_404(Course, pk=course_id)
    if not is_moderator(user) or (user != course.creator and user not in course.teachers.all()):
        raise Http404('You are not allowed to view this page!')
    details = []
    if answerpaper_id is not None and question_id is None:
        answerpaper = get_object_or_404(AnswerPaper, pk=answerpaper_id)
        for question in answerpaper.questions.all():
            details.append(answerpaper.regrade(question.id))
    if questionpaper_id is not None and question_id is not None:
        answerpapers = AnswerPaper.objects.filter(questions=question_id,
                question_paper_id=questionpaper_id)
        for answerpaper in answerpapers:
            details.append(answerpaper.regrade(question_id))
    if answerpaper_id is not None and question_id is not None:
        answerpaper = get_object_or_404(AnswerPaper, pk=answerpaper_id)
        details.append(answerpaper.regrade(question_id))
    return grader(request, extra_context={'details': details})


@login_required
@email_verified
def download_course_csv(request, course_id):
    user = request.user
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    course = get_object_or_404(Course, pk=course_id)
    if not course.is_creator(user) and not course.is_teacher(user):
        raise Http404('The question paper does not belong to your course')
    students = course.get_only_students().annotate(
        roll_number=F('profile__roll_number'),
        institute=F('profile__institute')
    ).values(
        "id", "first_name", "last_name",
        "email", "institute", "roll_number"
    )
    quizzes = Quiz.objects.filter(course=course, is_trial=False)

    for student in students:
        total_course_marks = 0.0
        user_course_marks = 0.0
        for quiz in quizzes:
            quiz_best_marks = AnswerPaper.objects.get_user_best_of_attempts_marks\
                               (quiz, student["id"])
            user_course_marks += quiz_best_marks
            total_course_marks += quiz.questionpaper_set.values_list(
                "total_marks", flat=True)[0]
            student["{}".format(quiz.description)] = quiz_best_marks
        student["total_scored"] = user_course_marks
        student["out_of"] = total_course_marks
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{0}.csv"'.format(
                                      (course.name).lower().replace('.', ''))
    header = ['first_name', 'last_name', "roll_number", "email", "institute"]\
            + [quiz.description for quiz in quizzes] + ['total_scored', 'out_of']
    writer = csv.DictWriter(response, fieldnames=header, extrasaction='ignore')
    writer.writeheader()
    for student in students:
        writer.writerow(student)
    return response


def activate_user(request, key):
    ci = RequestContext(request)
    profile = get_object_or_404(Profile, activation_key=key)
    context = {}
    context['success'] = False
    if profile.is_email_verified:
        context['activation_msg'] = "Your account is already verified"
        return my_render_to_response(
            'yaksh/activation_status.html', context, context_instance=ci
        )

    if timezone.now() > profile.key_expiry_time:
        context['msg'] = dedent("""
                    Your activation time expired.
                    Please try again.
                    """)
    else:
        context['success'] = True
        profile.is_email_verified = True
        profile.save()
        context['msg'] = "Your account is activated"
    return my_render_to_response(
        'yaksh/activation_status.html', context, context_instance=ci
    )


def new_activation(request, email=None):
    ci = RequestContext(request)
    context = {}
    if request.method == "POST":
        email = request.POST.get('email')

    try:
        user = User.objects.get(email=email)
    except MultipleObjectsReturned:
        context['email_err_msg'] = "Multiple entries found for this email"\
                                    "Please change your email"
        return my_render_to_response(
            'yaksh/activation_status.html', context, context_instance=ci
        )
    except ObjectDoesNotExist:
        context['success'] = False
        context['msg'] = "Your account is not verified. \
                            Please verify your account"
        return render_to_response(
            'yaksh/activation_status.html', context, context_instance=ci
        )

    if not user.profile.is_email_verified:
        user.profile.activation_key = generate_activation_key(user.username)
        user.profile.key_expiry_time = timezone.now() + \
            timezone.timedelta(minutes=20)
        user.profile.save()
        new_user_data = User.objects.get(email=email)
        success, msg = send_user_mail(new_user_data.email,
                                      new_user_data.profile.activation_key
                                      )
        if success:
            context['activation_msg'] = msg
        else:
            context['msg'] = msg
    else:
        context['activation_msg'] = "Your account is already verified"

    return my_render_to_response(
        'yaksh/activation_status.html', context, context_instance=ci
    )


def update_email(request):
    context = {}
    ci = RequestContext(request)
    if request.method == "POST":
        email = request.POST.get('email')
        username = request.POST.get('username')
        user = get_object_or_404(User, username=username)
        user.email = email
        user.save()
        return new_activation(request, email)
    else:
        context['email_err_msg'] = "Please Update your email"
        return my_render_to_response(
            'yaksh/activation_status.html', context, context_instance=ci
        )


@login_required
@email_verified
def download_assignment_file(request, quiz_id, question_id=None, user_id=None):
    user = request.user
    if not is_moderator(user):
        raise Http404("You are not allowed to view this page")
    qp = QuestionPaper.objects.get(quiz_id=quiz_id)
    assignment_files, file_name = AssignmentUpload.objects.get_assignments(
        qp, question_id, user_id
    )
    zipfile_name = string_io()
    zip_file = zipfile.ZipFile(zipfile_name, "w")
    for f_name in assignment_files:
        folder = f_name.user.get_full_name().replace(" ", "_")
        sub_folder = f_name.assignmentQuestion.summary.replace(" ", "_")
        folder_name = os.sep.join((folder, sub_folder, os.path.basename(
                        f_name.assignmentFile.name))
                        )
        zip_file.write(
            f_name.assignmentFile.path, folder_name
        )
    zip_file.close()
    zipfile_name.seek(0)
    response = HttpResponse(content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename={0}.zip'.format(
                                            file_name.replace(" ", "_")
                                            )
    response.write(zipfile_name.read())
    return response


@login_required
@email_verified
def duplicate_course(request, course_id):
    user = request.user
    course = get_object_or_404(Course, pk=course_id)
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')

    if course.is_teacher(user) or course.is_creator(user):
        course.create_duplicate_course(user)
    else:
        msg = 'You do not have permissions to clone this course, please contact your '\
            'instructor/administrator.'
        return complete(request, msg, attempt_num=None, questionpaper_id=None)
    return my_redirect('/exam/manage/courses/')

@login_required
@email_verified
def download_yaml_template(request):
    user = request.user
    if not is_moderator(user):
        raise Http404('You are not allowed to view this page!')
    template_path = os.path.join(os.path.dirname(__file__), "fixtures",
                                 "demo_questions.zip"
                                 )
    yaml_file = zipfile.ZipFile(template_path, 'r')
    template_yaml = yaml_file.open('questions_dump.yaml', 'r')
    response = HttpResponse(template_yaml, content_type='text/yaml')
    response['Content-Disposition'] = 'attachment;\
                                      filename="questions_dump.yaml"'
    
    return response