29
32
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
30
33
Reference, ReferenceSet, Bool, Storm, Desc
228
231
"""Find a user in a store by login name."""
229
232
return store.find(cls, cls.login == unicode(login)).one()
234
def get_svn_url(self, config):
235
"""Get the subversion repository URL for this user or group."""
236
url = config['urls']['svn_addr']
237
path = 'users/%s' % self.login
238
return urlparse.urljoin(url, path)
231
240
def get_permissions(self, user, config):
232
241
"""Determine privileges held by a user over this object.
324
333
semester = Reference(semester_id, Semester.id)
325
334
description = Unicode()
336
show_worksheet_marks = Bool()
337
worksheet_cutoff = DateTime()
327
338
groups_student_permissions = Unicode()
329
340
enrolments = ReferenceSet(id, 'Enrolment.offering_id')
392
403
perms.add('view_project_submissions')
393
404
perms.add('admin_groups')
394
405
perms.add('edit_worksheets')
406
perms.add('view_worksheet_marks')
395
407
perms.add('edit') # Can edit projects & details
396
408
perms.add('enrol') # Can see enrolment screen at all
397
409
perms.add('enrol_student') # Can enrol students
425
437
# XXX: Respect extensions.
426
438
return self.projects.find(Project.deadline > datetime.datetime.now())
440
def has_worksheet_cutoff_passed(self, user):
441
"""Check whether the worksheet cutoff has passed.
442
A user is required, in case we support extensions.
444
if self.worksheet_cutoff is None:
447
return self.worksheet_cutoff < datetime.datetime.now()
449
def clone_worksheets(self, source):
450
"""Clone all worksheets from the specified source to this offering."""
451
import ivle.worksheet.utils
452
for worksheet in source.worksheets:
454
newws.seq_no = worksheet.seq_no
455
newws.identifier = worksheet.identifier
456
newws.name = worksheet.name
457
newws.assessable = worksheet.assessable
458
newws.published = worksheet.published
459
newws.data = worksheet.data
460
newws.format = worksheet.format
461
newws.offering = self
462
Store.of(self).add(newws)
463
ivle.worksheet.utils.update_exerciselist(newws)
428
466
class Enrolment(Storm):
429
467
"""An enrolment of a user in an offering.
456
494
return "<%s %r in %r>" % (type(self).__name__, self.user,
497
def get_permissions(self, user, config):
498
# A user can edit any enrolment that they could have created.
500
if ('enrol_' + str(self.role)) in self.offering.get_permissions(
506
"""Delete this enrolment."""
507
Store.of(self).remove(self)
461
512
class ProjectSet(Storm):
559
610
return "<%s '%s' in %r>" % (type(self).__name__, self.short_name,
560
611
self.project_set.offering)
562
def can_submit(self, principal, user):
613
def can_submit(self, principal, user, late=False):
615
@param late: If True, does not take the deadline into account.
563
617
return (self in principal.get_projects() and
564
not self.has_deadline_passed(user))
618
(late or not self.has_deadline_passed(user)))
566
def submit(self, principal, path, revision, who):
620
def submit(self, principal, path, revision, who, late=False):
567
621
"""Submit a Subversion path and revision to a project.
569
623
@param principal: The owner of the Subversion repository, and the
571
625
@param path: A path within that repository to submit.
572
626
@param revision: The revision of that path to submit.
573
627
@param who: The user who is actually making the submission.
628
@param late: If True, will not raise a DeadlinePassed exception even
629
after the deadline. (Default False.)
576
if not self.can_submit(principal, who):
632
if not self.can_submit(principal, who, late=late):
577
633
raise DeadlinePassed()
579
635
a = Assessed.get(Store.of(self), principal, self)
580
636
ps = ProjectSubmission()
637
# Raise SubmissionError if the path is illegal
638
ps.path = ProjectSubmission.test_and_normalise_path(path)
582
639
ps.revision = revision
583
640
ps.date_submitted = datetime.datetime.now()
615
672
return assessed.submissions
675
def can_delete(self):
676
"""Can only delete if there are no submissions."""
677
return self.submissions.count() == 0
680
"""Delete the project. Fails if can_delete is False."""
681
if not self.can_delete:
682
raise IntegrityError()
683
for assessed in self.assesseds:
685
Store.of(self).remove(self)
619
687
class ProjectGroup(Storm):
620
688
"""A group of students working together on a project."""
670
738
Semester.id == Offering.semester_id,
671
739
(not active_only) or (Semester.state == u'current'))
741
def get_svn_url(self, config):
742
"""Get the subversion repository URL for this user or group."""
743
url = config['urls']['svn_addr']
744
path = 'groups/%s_%s_%s_%s' % (
745
self.project_set.offering.subject.short_name,
746
self.project_set.offering.semester.year,
747
self.project_set.offering.semester.semester,
750
return urlparse.urljoin(url, path)
674
752
def get_permissions(self, user, config):
675
753
if user.admin or user in self.members:
849
"""Delete the assessed. Fails if there are any submissions. Deletes
851
if self.submissions.count() > 0:
852
raise IntegrityError()
853
for extension in self.extensions:
855
Store.of(self).remove(self)
771
857
class ProjectExtension(Storm):
772
858
"""An extension granted to a user or group on a particular project.
779
865
id = Int(name="extensionid", primary=True)
780
866
assessed_id = Int(name="assessedid")
781
867
assessed = Reference(assessed_id, Assessed.id)
782
deadline = DateTime()
783
869
approver_id = Int(name="approver")
784
870
approver = Reference(approver_id, User.id)
785
871
notes = Unicode()
874
"""Delete the extension."""
875
Store.of(self).remove(self)
877
class SubmissionError(Exception):
878
"""Denotes a validation error during submission."""
787
881
class ProjectSubmission(Storm):
788
882
"""A submission from a user or group repository to a particular project.
819
913
return "/files/%s/%s/%s?r=%d" % (user.login,
820
914
self.assessed.checkout_location, submitpath, self.revision)
916
def get_svn_url(self, config):
917
"""Get subversion URL for this submission"""
918
princ = self.assessed.principal
919
base = princ.get_svn_url(config)
920
if self.path.startswith(os.sep):
921
return os.path.join(base,
922
urllib.quote(self.path[1:].encode('utf-8')))
924
return os.path.join(base, urllib.quote(self.path.encode('utf-8')))
926
def get_svn_export_command(self, req):
927
"""Returns a Unix shell command to export a submission"""
928
svn_url = self.get_svn_url(req.config)
929
username = (req.user.login if req.user.login.isalnum() else
930
"'%s'"%req.user.login)
931
export_dir = self.assessed.principal.short_name
932
return "svn export --username %s -r%d '%s' %s"%(req.user.login,
933
self.revision, svn_url, export_dir)
936
def test_and_normalise_path(path):
937
"""Test that path is valid, and normalise it. This prevents possible
938
injections using malicious paths.
939
Returns the updated path, if successful.
940
Raises SubmissionError if invalid.
942
# Ensure the path is absolute to prevent being tacked onto working
944
# Prevent '\n' because it will break all sorts of things.
945
# Prevent '[' and ']' because they can be used to inject into the
947
# Normalise to avoid resulting in ".." path segments.
948
if not os.path.isabs(path):
949
raise SubmissionError("Path is not absolute")
950
if any(c in path for c in "\n[]"):
951
raise SubmissionError("Path must not contain '\\n', '[' or ']'")
952
return os.path.normpath(path)
956
"""True if the project was submitted late."""
957
return self.days_late > 0
961
"""The number of days the project was submitted late (rounded up), or
963
# XXX: Need to respect extensions.
965
(self.date_submitted - self.assessed.project.deadline).days + 1)
822
967
# WORKSHEETS AND EXERCISES #
824
969
class Exercise(Storm):
882
def get_description(self):
883
"""Return the description interpreted as reStructuredText."""
884
return rst(self.description)
1028
def _cache_description_xhtml(self, invalidate=False):
1029
# Don't regenerate an existing cache unless forced.
1030
if self._description_xhtml_cache is not None and not invalidate:
1033
if self.description:
1034
self._description_xhtml_cache = rst(self.description)
1036
self._description_xhtml_cache = None
1039
def description_xhtml(self):
1040
"""The XHTML exercise description, converted from reStructuredText."""
1041
self._cache_description_xhtml()
1042
return self._description_xhtml_cache
1044
def set_description(self, description):
1045
self.description = description
1046
self._cache_description_xhtml(invalidate=True)
886
1048
def delete(self):
887
1049
"""Deletes the exercise, providing it has no associated worksheets."""
941
1105
WorksheetExercise.worksheet == self).remove()
943
1107
def get_permissions(self, user, config):
944
# Almost the same permissions as for the offering itself
945
perms = self.offering.get_permissions(user, config)
946
# However, "edit" permission is derived from the "edit_worksheets"
947
# permission of the offering
948
if 'edit_worksheets' in perms:
1108
offering_perms = self.offering.get_permissions(user, config)
1112
# Anybody who can view an offering can view a published
1114
if 'view' in offering_perms and self.published:
1117
# Any worksheet editors can both view and edit.
1118
if 'edit_worksheets' in offering_perms:
949
1120
perms.add('edit')
951
perms.discard('edit')
955
"""Returns the xml of this worksheet, converts from rst if required."""
956
if self.format == u'rst':
957
ws_xml = rst(self.data)
1124
def _cache_data_xhtml(self, invalidate=False):
1125
# Don't regenerate an existing cache unless forced.
1126
if self._data_xhtml_cache is not None and not invalidate:
1129
if self.format == u'rst':
1130
self._data_xhtml_cache = rst(self.data)
1132
self._data_xhtml_cache = None
1135
def data_xhtml(self):
1136
"""The XHTML of this worksheet, converted from rST if required."""
1137
# Update the rST -> XHTML cache, if required.
1138
self._cache_data_xhtml()
1140
if self.format == u'rst':
1141
return self._data_xhtml_cache
960
1143
return self.data
1145
def set_data(self, data):
1147
self._cache_data_xhtml(invalidate=True)
962
1149
def delete(self):
963
1150
"""Deletes the worksheet, provided it has no attempts on any exercises.
1027
1214
def __repr__(self):
1028
1215
return "<%s %s by %s at %s>" % (type(self).__name__,
1029
self.exercise.name, self.user.login, self.date.strftime("%c"))
1216
self.worksheet_exercise.exercise.name, self.user.login,
1217
self.date.strftime("%c"))
1031
1219
class ExerciseAttempt(ExerciseSave):
1032
1220
"""An attempt at solving an exercise.