~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/database.py

  • Committer: matt.giuca
  • Date: 2009-02-25 07:47:58 UTC
  • Revision ID: svn-v4:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:1215
Rewrote tooltips for the four tabs visible by default.
(Shorter, verber and removed fullstops).

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant
19
19
 
20
 
"""Database utilities and content classes.
 
20
"""
 
21
Database Classes and Utilities for Storm ORM
21
22
 
22
23
This module provides all of the classes which map to database tables.
23
24
It also provides miscellaneous utility functions for database interaction.
24
25
"""
25
26
 
26
 
import hashlib
 
27
import md5
27
28
import datetime
28
 
import os
29
29
 
30
30
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
31
                         Reference, ReferenceSet, Bool, Storm, Desc
32
 
from storm.expr import Select, Max
33
 
from storm.exceptions import NotOneError, IntegrityError
34
32
 
35
 
from ivle.worksheet.rst import rst
 
33
import ivle.conf
36
34
 
37
35
__all__ = ['get_store',
38
36
            'User',
39
37
            'Subject', 'Semester', 'Offering', 'Enrolment',
40
38
            'ProjectSet', 'Project', 'ProjectGroup', 'ProjectGroupMembership',
41
 
            'Assessed', 'ProjectSubmission', 'ProjectExtension',
42
39
            'Exercise', 'Worksheet', 'WorksheetExercise',
43
40
            'ExerciseSave', 'ExerciseAttempt',
44
41
            'TestCase', 'TestSuite', 'TestSuiteVar'
51
48
                % (self.__class__.__name__, k))
52
49
        setattr(self, k, v)
53
50
 
54
 
def get_conn_string(config):
55
 
    """Create a Storm connection string to the IVLE database
56
 
 
57
 
    @param config: The IVLE configuration.
 
51
def get_conn_string():
 
52
    """
 
53
    Returns the Storm connection string, generated from the conf file.
58
54
    """
59
55
 
60
56
    clusterstr = ''
61
 
    if config['database']['username']:
62
 
        clusterstr += config['database']['username']
63
 
        if config['database']['password']:
64
 
            clusterstr += ':' + config['database']['password']
 
57
    if ivle.conf.db_user:
 
58
        clusterstr += ivle.conf.db_user
 
59
        if ivle.conf.db_password:
 
60
            clusterstr += ':' + ivle.conf.db_password
65
61
        clusterstr += '@'
66
62
 
67
 
    host = config['database']['host'] or 'localhost'
68
 
    port = config['database']['port'] or 5432
 
63
    host = ivle.conf.db_host or 'localhost'
 
64
    port = ivle.conf.db_port or 5432
69
65
 
70
66
    clusterstr += '%s:%d' % (host, port)
71
67
 
72
 
    return "postgres://%s/%s" % (clusterstr, config['database']['name'])
73
 
 
74
 
def get_store(config):
75
 
    """Create a Storm store connected to the IVLE database.
76
 
 
77
 
    @param config: The IVLE configuration.
78
 
    """
79
 
    return Store(create_database(get_conn_string(config)))
 
68
    return "postgres://%s/%s" % (clusterstr, ivle.conf.db_dbname)
 
69
 
 
70
def get_store():
 
71
    """
 
72
    Open a database connection and transaction. Return a storm.store.Store
 
73
    instance connected to the configured IVLE database.
 
74
    """
 
75
    return Store(create_database(get_conn_string()))
80
76
 
81
77
# USERS #
82
78
 
83
79
class User(Storm):
84
 
    """An IVLE user account."""
 
80
    """
 
81
    Represents an IVLE user.
 
82
    """
85
83
    __storm_table__ = "login"
86
84
 
87
85
    id = Int(primary=True, name="loginid")
117
115
        return self.hash_password(password) == self.passhash
118
116
 
119
117
    @property
120
 
    def display_name(self):
121
 
        """Returns the "nice name" of the user or group."""
122
 
        return self.fullname
123
 
 
124
 
    @property
125
 
    def short_name(self):
126
 
        """Returns the database "identifier" name of the user or group."""
127
 
        return self.login
128
 
 
129
 
    @property
130
118
    def password_expired(self):
131
119
        fieldval = self.pass_exp
132
120
        return fieldval is not None and datetime.datetime.now() > fieldval
169
157
 
170
158
    # TODO: Invitations should be listed too?
171
159
    def get_groups(self, offering=None):
172
 
        """Get groups of which this user is a member.
173
 
 
174
 
        @param offering: An optional offering to restrict the search to.
175
 
        """
176
160
        preds = [
177
161
            ProjectGroupMembership.user_id == self.id,
178
162
            ProjectGroup.id == ProjectGroupMembership.project_group_id,
198
182
        '''A sanely ordered list of all of the user's enrolments.'''
199
183
        return self._get_enrolments(False) 
200
184
 
201
 
    def get_projects(self, offering=None, active_only=True):
202
 
        """Find projects that the user can submit.
203
 
 
204
 
        This will include projects for offerings in which the user is
205
 
        enrolled, as long as the project is not in a project set which has
206
 
        groups (ie. if maximum number of group members is 0).
207
 
 
208
 
        @param active_only: Whether to only search active offerings.
209
 
        @param offering: An optional offering to restrict the search to.
210
 
        """
211
 
        return Store.of(self).find(Project,
212
 
            Project.project_set_id == ProjectSet.id,
213
 
            ProjectSet.max_students_per_group == None,
214
 
            ProjectSet.offering_id == Offering.id,
215
 
            (offering is None) or (Offering.id == offering.id),
216
 
            Semester.id == Offering.semester_id,
217
 
            (not active_only) or (Semester.state == u'current'),
218
 
            Enrolment.offering_id == Offering.id,
219
 
            Enrolment.user_id == self.id,
220
 
            Enrolment.active == True)
221
 
 
222
185
    @staticmethod
223
186
    def hash_password(password):
224
 
        """Hash a password with MD5."""
225
 
        return hashlib.md5(password).hexdigest()
 
187
        return md5.md5(password).hexdigest()
226
188
 
227
189
    @classmethod
228
190
    def get_by_login(cls, store, login):
229
 
        """Find a user in a store by login name."""
 
191
        """
 
192
        Get the User from the db associated with a given store and
 
193
        login.
 
194
        """
230
195
        return store.find(cls, cls.login == unicode(login)).one()
231
196
 
232
 
    def get_permissions(self, user, config):
233
 
        """Determine privileges held by a user over this object.
234
 
 
235
 
        If the user requesting privileges is this user or an admin,
236
 
        they may do everything. Otherwise they may do nothing.
237
 
        """
 
197
    def get_permissions(self, user):
238
198
        if user and user.admin or user is self:
239
 
            return set(['view_public', 'view', 'edit', 'submit_project'])
 
199
            return set(['view', 'edit'])
240
200
        else:
241
 
            return set(['view_public'])
 
201
            return set()
242
202
 
243
203
# SUBJECTS AND ENROLMENTS #
244
204
 
245
205
class Subject(Storm):
246
 
    """A subject (or course) which is run in some semesters."""
247
 
 
248
206
    __storm_table__ = "subject"
249
207
 
250
208
    id = Int(primary=True, name="subjectid")
251
209
    code = Unicode(name="subj_code")
252
210
    name = Unicode(name="subj_name")
253
211
    short_name = Unicode(name="subj_short_name")
 
212
    url = Unicode()
254
213
 
255
214
    offerings = ReferenceSet(id, 'Offering.subject_id')
256
215
 
259
218
    def __repr__(self):
260
219
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
261
220
 
262
 
    def get_permissions(self, user, config):
263
 
        """Determine privileges held by a user over this object.
264
 
 
265
 
        If the user requesting privileges is an admin, they may edit.
266
 
        Otherwise they may only read.
267
 
        """
 
221
    def get_permissions(self, user):
268
222
        perms = set()
269
223
        if user is not None:
270
224
            perms.add('view')
272
226
                perms.add('edit')
273
227
        return perms
274
228
 
275
 
    def active_offerings(self):
276
 
        """Find active offerings for this subject.
277
 
 
278
 
        Return a sequence of currently active offerings for this subject
279
 
        (offerings whose semester.state is "current"). There should be 0 or 1
280
 
        elements in this sequence, but it's possible there are more.
281
 
        """
282
 
        return self.offerings.find(Offering.semester_id == Semester.id,
283
 
                                   Semester.state == u'current')
284
 
 
285
 
    def offering_for_semester(self, year, semester):
286
 
        """Get the offering for the given year/semester, or None.
287
 
 
288
 
        @param year: A string representation of the year.
289
 
        @param semester: A string representation of the semester.
290
 
        """
291
 
        return self.offerings.find(Offering.semester_id == Semester.id,
292
 
                               Semester.year == unicode(year),
293
 
                               Semester.semester == unicode(semester)).one()
294
 
 
295
229
class Semester(Storm):
296
 
    """A semester in which subjects can be run."""
297
 
 
298
230
    __storm_table__ = "semester"
299
231
 
300
232
    id = Int(primary=True, name="semesterid")
303
235
    state = Unicode()
304
236
 
305
237
    offerings = ReferenceSet(id, 'Offering.semester_id')
306
 
    enrolments = ReferenceSet(id,
307
 
                              'Offering.semester_id',
308
 
                              'Offering.id',
309
 
                              'Enrolment.offering_id')
310
238
 
311
239
    __init__ = _kwarg_init
312
240
 
314
242
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
315
243
 
316
244
class Offering(Storm):
317
 
    """An offering of a subject in a particular semester."""
318
 
 
319
245
    __storm_table__ = "offering"
320
246
 
321
247
    id = Int(primary=True, name="offeringid")
323
249
    subject = Reference(subject_id, Subject.id)
324
250
    semester_id = Int(name="semesterid")
325
251
    semester = Reference(semester_id, Semester.id)
326
 
    description = Unicode()
327
 
    url = Unicode()
328
 
    show_worksheet_marks = Bool()
329
 
    worksheet_cutoff = DateTime()
330
252
    groups_student_permissions = Unicode()
331
253
 
332
254
    enrolments = ReferenceSet(id, 'Enrolment.offering_id')
335
257
                           'Enrolment.user_id',
336
258
                           'User.id')
337
259
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
338
 
    projects = ReferenceSet(id,
339
 
                            'ProjectSet.offering_id',
340
 
                            'ProjectSet.id',
341
 
                            'Project.project_set_id')
342
260
 
343
261
    worksheets = ReferenceSet(id, 
344
262
        'Worksheet.offering_id', 
345
 
        order_by="seq_no"
 
263
        order_by="Worksheet.seq_no"
346
264
    )
347
265
 
348
266
    __init__ = _kwarg_init
352
270
                                  self.semester)
353
271
 
354
272
    def enrol(self, user, role=u'student'):
355
 
        """Enrol a user in this offering.
356
 
 
357
 
        Enrolments handle both the staff and student cases. The role controls
358
 
        the privileges granted by this enrolment.
359
 
        """
 
273
        '''Enrol a user in this offering.'''
360
274
        enrolment = Store.of(self).find(Enrolment,
361
275
                               Enrolment.user_id == user.id,
362
276
                               Enrolment.offering_id == self.id).one()
368
282
        enrolment.active = True
369
283
        enrolment.role = role
370
284
 
371
 
    def unenrol(self, user):
372
 
        '''Unenrol a user from this offering.'''
373
 
        enrolment = Store.of(self).find(Enrolment,
374
 
                               Enrolment.user_id == user.id,
375
 
                               Enrolment.offering_id == self.id).one()
376
 
        Store.of(enrolment).remove(enrolment)
377
 
 
378
 
    def get_permissions(self, user, config):
 
285
    def get_permissions(self, user):
379
286
        perms = set()
380
287
        if user is not None:
381
 
            enrolment = self.get_enrolment(user)
382
 
            if enrolment or user.admin:
383
 
                perms.add('view')
384
 
            if enrolment and enrolment.role == u'tutor':
385
 
                perms.add('view_project_submissions')
386
 
                # Site-specific policy on the role of tutors
387
 
                if config['policy']['tutors_can_enrol_students']:
388
 
                    perms.add('enrol')
389
 
                    perms.add('enrol_student')
390
 
                if config['policy']['tutors_can_edit_worksheets']:
391
 
                    perms.add('edit_worksheets')
392
 
                if config['policy']['tutors_can_admin_groups']:
393
 
                    perms.add('admin_groups')
394
 
            if (enrolment and enrolment.role in (u'lecturer')) or user.admin:
395
 
                perms.add('view_project_submissions')
396
 
                perms.add('admin_groups')
397
 
                perms.add('edit_worksheets')
398
 
                perms.add('edit')           # Can edit projects & details
399
 
                perms.add('enrol')          # Can see enrolment screen at all
400
 
                perms.add('enrol_student')  # Can enrol students
401
 
                perms.add('enrol_tutor')    # Can enrol tutors
 
288
            perms.add('view')
402
289
            if user.admin:
403
 
                perms.add('enrol_lecturer') # Can enrol lecturers
 
290
                perms.add('edit')
404
291
        return perms
405
292
 
406
 
    def get_enrolment(self, user):
407
 
        """Find the user's enrolment in this offering."""
408
 
        try:
409
 
            enrolment = self.enrolments.find(user=user).one()
410
 
        except NotOneError:
411
 
            enrolment = None
412
 
 
413
 
        return enrolment
414
 
 
415
 
    def get_members_by_role(self, role):
416
 
        return Store.of(self).find(User,
417
 
                Enrolment.user_id == User.id,
418
 
                Enrolment.offering_id == self.id,
419
 
                Enrolment.role == role
420
 
                ).order_by(User.login)
421
 
 
422
 
    @property
423
 
    def students(self):
424
 
        return self.get_members_by_role(u'student')
425
 
 
426
 
    def get_open_projects_for_user(self, user):
427
 
        """Find all projects currently open to submissions by a user."""
428
 
        # XXX: Respect extensions.
429
 
        return self.projects.find(Project.deadline > datetime.datetime.now())
430
 
 
431
 
    def clone_worksheets(self, source):
432
 
        """Clone all worksheets from the specified source to this offering."""
433
 
        import ivle.worksheet.utils
434
 
        for worksheet in source.worksheets:
435
 
            newws = Worksheet()
436
 
            newws.seq_no = worksheet.seq_no
437
 
            newws.identifier = worksheet.identifier
438
 
            newws.name = worksheet.name
439
 
            newws.assessable = worksheet.assessable
440
 
            newws.published = worksheet.published
441
 
            newws.data = worksheet.data
442
 
            newws.format = worksheet.format
443
 
            newws.offering = self
444
 
            Store.of(self).add(newws)
445
 
            ivle.worksheet.utils.update_exerciselist(newws)
446
 
 
447
 
 
448
293
class Enrolment(Storm):
449
 
    """An enrolment of a user in an offering.
450
 
 
451
 
    This represents the roles of both staff and students.
452
 
    """
453
 
 
454
294
    __storm_table__ = "enrolment"
455
295
    __storm_primary__ = "user_id", "offering_id"
456
296
 
476
316
        return "<%s %r in %r>" % (type(self).__name__, self.user,
477
317
                                  self.offering)
478
318
 
479
 
    def get_permissions(self, user, config):
480
 
        # A user can edit any enrolment that they could have created.
481
 
        perms = set()
482
 
        if ('enrol_' + str(self.role)) in self.offering.get_permissions(
483
 
            user, config):
484
 
            perms.add('edit')
485
 
        return perms
486
 
 
487
 
    def delete(self):
488
 
        """Delete this enrolment."""
489
 
        Store.of(self).remove(self)
490
 
 
491
 
 
492
319
# PROJECTS #
493
320
 
494
321
class ProjectSet(Storm):
495
 
    """A set of projects that share common groups.
496
 
 
497
 
    Each student project group is attached to a project set. The group is
498
 
    valid for all projects in the group's set.
499
 
    """
500
 
 
501
322
    __storm_table__ = "project_set"
502
323
 
503
324
    id = Int(name="projectsetid", primary=True)
514
335
        return "<%s %d in %r>" % (type(self).__name__, self.id,
515
336
                                  self.offering)
516
337
 
517
 
    def get_permissions(self, user, config):
518
 
        return self.offering.get_permissions(user, config)
519
 
 
520
 
    def get_groups_for_user(self, user):
521
 
        """List all groups in this offering of which the user is a member."""
522
 
        assert self.is_group
523
 
        return Store.of(self).find(
524
 
            ProjectGroup,
525
 
            ProjectGroupMembership.user_id == user.id,
526
 
            ProjectGroupMembership.project_group_id == ProjectGroup.id,
527
 
            ProjectGroup.project_set_id == self.id)
528
 
 
529
 
    def get_submission_principal(self, user):
530
 
        """Get the principal on behalf of which the user can submit.
531
 
 
532
 
        If this is a solo project set, the given user is returned. If
533
 
        the user is a member of exactly one group, all the group is
534
 
        returned. Otherwise, None is returned.
535
 
        """
536
 
        if self.is_group:
537
 
            groups = self.get_groups_for_user(user)
538
 
            if groups.count() == 1:
539
 
                return groups.one()
540
 
            else:
541
 
                return None
542
 
        else:
543
 
            return user
544
 
 
545
 
    @property
546
 
    def is_group(self):
547
 
        return self.max_students_per_group is not None
548
 
 
549
 
    @property
550
 
    def assigned(self):
551
 
        """Get the entities (groups or users) assigned to submit this project.
552
 
 
553
 
        This will be a Storm ResultSet.
554
 
        """
555
 
        #If its a solo project, return everyone in offering
556
 
        if self.is_group:
557
 
            return self.project_groups
558
 
        else:
559
 
            return self.offering.students
560
 
 
561
 
class DeadlinePassed(Exception):
562
 
    """An exception indicating that a project cannot be submitted because the
563
 
    deadline has passed."""
564
 
    def __init__(self):
565
 
        pass
566
 
    def __str__(self):
567
 
        return "The project deadline has passed"
568
 
 
569
338
class Project(Storm):
570
 
    """A student project for which submissions can be made."""
571
 
 
572
339
    __storm_table__ = "project"
573
340
 
574
341
    id = Int(name="projectid", primary=True)
575
 
    name = Unicode()
576
 
    short_name = Unicode()
577
342
    synopsis = Unicode()
578
343
    url = Unicode()
579
344
    project_set_id = Int(name="projectsetid")
580
345
    project_set = Reference(project_set_id, ProjectSet.id)
581
346
    deadline = DateTime()
582
347
 
583
 
    assesseds = ReferenceSet(id, 'Assessed.project_id')
584
 
    submissions = ReferenceSet(id,
585
 
                               'Assessed.project_id',
586
 
                               'Assessed.id',
587
 
                               'ProjectSubmission.assessed_id')
588
 
 
589
348
    __init__ = _kwarg_init
590
349
 
591
350
    def __repr__(self):
592
 
        return "<%s '%s' in %r>" % (type(self).__name__, self.short_name,
 
351
        return "<%s '%s' in %r>" % (type(self).__name__, self.synopsis,
593
352
                                  self.project_set.offering)
594
353
 
595
 
    def can_submit(self, principal, user):
596
 
        return (self in principal.get_projects() and
597
 
                not self.has_deadline_passed(user))
598
 
 
599
 
    def submit(self, principal, path, revision, who):
600
 
        """Submit a Subversion path and revision to a project.
601
 
 
602
 
        @param principal: The owner of the Subversion repository, and the
603
 
                          entity on behalf of whom the submission is being made
604
 
        @param path: A path within that repository to submit.
605
 
        @param revision: The revision of that path to submit.
606
 
        @param who: The user who is actually making the submission.
607
 
        """
608
 
 
609
 
        if not self.can_submit(principal, who):
610
 
            raise DeadlinePassed()
611
 
 
612
 
        a = Assessed.get(Store.of(self), principal, self)
613
 
        ps = ProjectSubmission()
614
 
        # Raise SubmissionError if the path is illegal
615
 
        ps.path = ProjectSubmission.test_and_normalise_path(path)
616
 
        ps.revision = revision
617
 
        ps.date_submitted = datetime.datetime.now()
618
 
        ps.assessed = a
619
 
        ps.submitter = who
620
 
 
621
 
        return ps
622
 
 
623
 
    def get_permissions(self, user, config):
624
 
        return self.project_set.offering.get_permissions(user, config)
625
 
 
626
 
    @property
627
 
    def latest_submissions(self):
628
 
        """Return the latest submission for each Assessed."""
629
 
        return Store.of(self).find(ProjectSubmission,
630
 
            Assessed.project_id == self.id,
631
 
            ProjectSubmission.assessed_id == Assessed.id,
632
 
            ProjectSubmission.date_submitted == Select(
633
 
                    Max(ProjectSubmission.date_submitted),
634
 
                    ProjectSubmission.assessed_id == Assessed.id,
635
 
                    tables=ProjectSubmission
636
 
            )
637
 
        )
638
 
 
639
 
    def has_deadline_passed(self, user):
640
 
        """Check whether the deadline has passed."""
641
 
        # XXX: Need to respect extensions.
642
 
        return self.deadline < datetime.datetime.now()
643
 
 
644
 
    def get_submissions_for_principal(self, principal):
645
 
        """Fetch a ResultSet of all submissions by a particular principal."""
646
 
        assessed = Assessed.get(Store.of(self), principal, self)
647
 
        if assessed is None:
648
 
            return
649
 
        return assessed.submissions
650
 
 
651
 
 
652
 
 
653
354
class ProjectGroup(Storm):
654
 
    """A group of students working together on a project."""
655
 
 
656
355
    __storm_table__ = "project_group"
657
356
 
658
357
    id = Int(name="groupid", primary=True)
675
374
        return "<%s %s in %r>" % (type(self).__name__, self.name,
676
375
                                  self.project_set.offering)
677
376
 
678
 
    @property
679
 
    def display_name(self):
680
 
        """Returns the "nice name" of the user or group."""
681
 
        return self.nick
682
 
 
683
 
    @property
684
 
    def short_name(self):
685
 
        """Returns the database "identifier" name of the user or group."""
686
 
        return self.name
687
 
 
688
 
    def get_projects(self, offering=None, active_only=True):
689
 
        '''Find projects that the group can submit.
690
 
 
691
 
        This will include projects in the project set which owns this group,
692
 
        unless the project set disallows groups (in which case none will be
693
 
        returned).
694
 
 
695
 
        @param active_only: Whether to only search active offerings.
696
 
        @param offering: An optional offering to restrict the search to.
697
 
        '''
698
 
        return Store.of(self).find(Project,
699
 
            Project.project_set_id == ProjectSet.id,
700
 
            ProjectSet.id == self.project_set.id,
701
 
            ProjectSet.max_students_per_group != None,
702
 
            ProjectSet.offering_id == Offering.id,
703
 
            (offering is None) or (Offering.id == offering.id),
704
 
            Semester.id == Offering.semester_id,
705
 
            (not active_only) or (Semester.state == u'current'))
706
 
 
707
 
 
708
 
    def get_permissions(self, user, config):
709
 
        if user.admin or user in self.members:
710
 
            return set(['submit_project'])
711
 
        else:
712
 
            return set()
713
 
 
714
377
class ProjectGroupMembership(Storm):
715
 
    """A student's membership in a project group."""
716
 
 
717
378
    __storm_table__ = "group_member"
718
379
    __storm_primary__ = "user_id", "project_group_id"
719
380
 
728
389
        return "<%s %r in %r>" % (type(self).__name__, self.user,
729
390
                                  self.project_group)
730
391
 
731
 
class Assessed(Storm):
732
 
    """A composite of a user or group combined with a project.
733
 
 
734
 
    Each project submission and extension refers to an Assessed. It is the
735
 
    sole specifier of the repository and project.
736
 
    """
737
 
 
738
 
    __storm_table__ = "assessed"
739
 
 
740
 
    id = Int(name="assessedid", primary=True)
741
 
    user_id = Int(name="loginid")
742
 
    user = Reference(user_id, User.id)
743
 
    project_group_id = Int(name="groupid")
744
 
    project_group = Reference(project_group_id, ProjectGroup.id)
745
 
 
746
 
    project_id = Int(name="projectid")
747
 
    project = Reference(project_id, Project.id)
748
 
 
749
 
    extensions = ReferenceSet(id, 'ProjectExtension.assessed_id')
750
 
    submissions = ReferenceSet(
751
 
        id, 'ProjectSubmission.assessed_id', order_by='date_submitted')
752
 
 
753
 
    def __repr__(self):
754
 
        return "<%s %r in %r>" % (type(self).__name__,
755
 
            self.user or self.project_group, self.project)
756
 
 
757
 
    @property
758
 
    def is_group(self):
759
 
        """True if the Assessed is a group, False if it is a user."""
760
 
        return self.project_group is not None
761
 
 
762
 
    @property
763
 
    def principal(self):
764
 
        return self.project_group or self.user
765
 
 
766
 
    @property
767
 
    def checkout_location(self):
768
 
        """Returns the location of the Subversion workspace for this piece of
769
 
        assessment, relative to each group member's home directory."""
770
 
        subjectname = self.project.project_set.offering.subject.short_name
771
 
        if self.is_group:
772
 
            checkout_dir_name = self.principal.short_name
773
 
        else:
774
 
            checkout_dir_name = "mywork"
775
 
        return subjectname + "/" + checkout_dir_name
776
 
 
777
 
    @classmethod
778
 
    def get(cls, store, principal, project):
779
 
        """Find or create an Assessed for the given user or group and project.
780
 
 
781
 
        @param principal: The user or group.
782
 
        @param project: The project.
783
 
        """
784
 
        t = type(principal)
785
 
        if t not in (User, ProjectGroup):
786
 
            raise AssertionError('principal must be User or ProjectGroup')
787
 
 
788
 
        a = store.find(cls,
789
 
            (t is User) or (cls.project_group_id == principal.id),
790
 
            (t is ProjectGroup) or (cls.user_id == principal.id),
791
 
            cls.project_id == project.id).one()
792
 
 
793
 
        if a is None:
794
 
            a = cls()
795
 
            if t is User:
796
 
                a.user = principal
797
 
            else:
798
 
                a.project_group = principal
799
 
            a.project = project
800
 
            store.add(a)
801
 
 
802
 
        return a
803
 
 
804
 
 
805
 
class ProjectExtension(Storm):
806
 
    """An extension granted to a user or group on a particular project.
807
 
 
808
 
    The user or group and project are specified by the Assessed.
809
 
    """
810
 
 
811
 
    __storm_table__ = "project_extension"
812
 
 
813
 
    id = Int(name="extensionid", primary=True)
814
 
    assessed_id = Int(name="assessedid")
815
 
    assessed = Reference(assessed_id, Assessed.id)
816
 
    deadline = DateTime()
817
 
    approver_id = Int(name="approver")
818
 
    approver = Reference(approver_id, User.id)
819
 
    notes = Unicode()
820
 
 
821
 
class SubmissionError(Exception):
822
 
    """Denotes a validation error during submission."""
823
 
    pass
824
 
 
825
 
class ProjectSubmission(Storm):
826
 
    """A submission from a user or group repository to a particular project.
827
 
 
828
 
    The content of a submission is a single path and revision inside a
829
 
    repository. The repository is that owned by the submission's user and
830
 
    group, while the path and revision are explicit.
831
 
 
832
 
    The user or group and project are specified by the Assessed.
833
 
    """
834
 
 
835
 
    __storm_table__ = "project_submission"
836
 
 
837
 
    id = Int(name="submissionid", primary=True)
838
 
    assessed_id = Int(name="assessedid")
839
 
    assessed = Reference(assessed_id, Assessed.id)
840
 
    path = Unicode()
841
 
    revision = Int()
842
 
    submitter_id = Int(name="submitter")
843
 
    submitter = Reference(submitter_id, User.id)
844
 
    date_submitted = DateTime()
845
 
 
846
 
    def get_verify_url(self, user):
847
 
        """Get the URL for verifying this submission, within the account of
848
 
        the given user."""
849
 
        # If this is a solo project, then self.path will be prefixed with the
850
 
        # subject name. Remove the first path segment.
851
 
        submitpath = self.path[1:] if self.path[:1] == '/' else self.path
852
 
        if not self.assessed.is_group:
853
 
            if '/' in submitpath:
854
 
                submitpath = submitpath.split('/', 1)[1]
855
 
            else:
856
 
                submitpath = ''
857
 
        return "/files/%s/%s/%s?r=%d" % (user.login,
858
 
            self.assessed.checkout_location, submitpath, self.revision)
859
 
 
860
 
    @staticmethod
861
 
    def test_and_normalise_path(path):
862
 
        """Test that path is valid, and normalise it. This prevents possible
863
 
        injections using malicious paths.
864
 
        Returns the updated path, if successful.
865
 
        Raises SubmissionError if invalid.
866
 
        """
867
 
        # Ensure the path is absolute to prevent being tacked onto working
868
 
        # directories.
869
 
        # Prevent '\n' because it will break all sorts of things.
870
 
        # Prevent '[' and ']' because they can be used to inject into the
871
 
        # svn.conf.
872
 
        # Normalise to avoid resulting in ".." path segments.
873
 
        if not os.path.isabs(path):
874
 
            raise SubmissionError("Path is not absolute")
875
 
        if any(c in path for c in "\n[]"):
876
 
            raise SubmissionError("Path must not contain '\\n', '[' or ']'")
877
 
        return os.path.normpath(path)
878
 
 
879
392
# WORKSHEETS AND EXERCISES #
880
393
 
881
394
class Exercise(Storm):
882
 
    """An exercise for students to complete in a worksheet.
883
 
 
884
 
    An exercise may be present in any number of worksheets.
885
 
    """
886
 
 
887
395
    __storm_table__ = "exercise"
888
396
    id = Unicode(primary=True, name="identifier")
889
397
    name = Unicode()
893
401
    include = Unicode()
894
402
    num_rows = Int()
895
403
 
896
 
    worksheet_exercises =  ReferenceSet(id,
897
 
        'WorksheetExercise.exercise_id')
898
 
 
899
404
    worksheets = ReferenceSet(id,
900
405
        'WorksheetExercise.exercise_id',
901
406
        'WorksheetExercise.worksheet_id',
902
407
        'Worksheet.id'
903
408
    )
904
 
 
905
 
    test_suites = ReferenceSet(id, 
906
 
        'TestSuite.exercise_id',
907
 
        order_by='seq_no')
 
409
    
 
410
    test_suites = ReferenceSet(id, 'TestSuite.exercise_id')
908
411
 
909
412
    __init__ = _kwarg_init
910
413
 
911
414
    def __repr__(self):
912
415
        return "<%s %s>" % (type(self).__name__, self.name)
913
416
 
914
 
    def get_permissions(self, user, config):
915
 
        return self.global_permissions(user, config)
916
 
 
917
 
    @staticmethod
918
 
    def global_permissions(user, config):
919
 
        """Gets the set of permissions this user has over *all* exercises.
920
 
        This is used to determine who may view the exercises list, and create
921
 
        new exercises."""
 
417
    def get_permissions(self, user):
922
418
        perms = set()
923
 
        roles = set()
924
419
        if user is not None:
925
420
            if user.admin:
926
421
                perms.add('edit')
927
422
                perms.add('view')
928
 
            elif u'lecturer' in set((e.role for e in user.active_enrolments)):
929
 
                perms.add('edit')
930
 
                perms.add('view')
931
 
            elif (config['policy']['tutors_can_edit_worksheets']
932
 
            and u'tutor' in set((e.role for e in user.active_enrolments))):
933
 
                # Site-specific policy on the role of tutors
934
 
                perms.add('edit')
935
 
                perms.add('view')
936
 
 
937
423
        return perms
938
424
 
939
 
    def get_description(self):
940
 
        """Return the description interpreted as reStructuredText."""
941
 
        return rst(self.description)
942
 
 
943
 
    def delete(self):
944
 
        """Deletes the exercise, providing it has no associated worksheets."""
945
 
        if (self.worksheet_exercises.count() > 0):
946
 
            raise IntegrityError()
947
 
        for suite in self.test_suites:
948
 
            suite.delete()
949
 
        Store.of(self).remove(self)
950
 
 
951
425
class Worksheet(Storm):
952
 
    """A worksheet with exercises for students to complete.
953
 
 
954
 
    Worksheets are owned by offerings.
955
 
    """
956
 
 
957
426
    __storm_table__ = "worksheet"
958
427
 
959
428
    id = Int(primary=True, name="worksheetid")
961
430
    identifier = Unicode()
962
431
    name = Unicode()
963
432
    assessable = Bool()
964
 
    published = Bool()
965
433
    data = Unicode()
966
434
    seq_no = Int()
967
435
    format = Unicode()
975
443
    # Use worksheet_exercises to get access to the *active* WorksheetExercise
976
444
    # objects binding worksheets to exercises. This is required to access the
977
445
    # "optional" field.
978
 
 
979
446
    @property
980
447
    def worksheet_exercises(self):
981
448
        return self.all_worksheet_exercises.find(active=True)
985
452
    def __repr__(self):
986
453
        return "<%s %s>" % (type(self).__name__, self.name)
987
454
 
988
 
    def remove_all_exercises(self):
989
 
        """Remove all exercises from this worksheet.
 
455
    # XXX Refactor this - make it an instance method of Subject rather than a
 
456
    # class method of Worksheet. Can't do that now because Subject isn't
 
457
    # linked referentially to the Worksheet.
 
458
    @classmethod
 
459
    def get_by_name(cls, store, subjectname, worksheetname):
 
460
        """
 
461
        Get the Worksheet from the db associated with a given store, subject
 
462
        name and worksheet name.
 
463
        """
 
464
        return store.find(cls, cls.subject == unicode(subjectname),
 
465
            cls.name == unicode(worksheetname)).one()
990
466
 
 
467
    def remove_all_exercises(self, store):
 
468
        """
 
469
        Remove all exercises from this worksheet.
991
470
        This does not delete the exercises themselves. It just removes them
992
471
        from the worksheet.
993
472
        """
994
 
        store = Store.of(self)
995
 
        for ws_ex in self.all_worksheet_exercises:
996
 
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
997
 
                raise IntegrityError()
998
473
        store.find(WorksheetExercise,
999
474
            WorksheetExercise.worksheet == self).remove()
1000
 
 
1001
 
    def get_permissions(self, user, config):
1002
 
        # Almost the same permissions as for the offering itself
1003
 
        perms = self.offering.get_permissions(user, config)
1004
 
        # However, "edit" permission is derived from the "edit_worksheets"
1005
 
        # permission of the offering
1006
 
        if 'edit_worksheets' in perms:
1007
 
            perms.add('edit')
1008
 
        else:
1009
 
            perms.discard('edit')
1010
 
        return perms
1011
 
 
1012
 
    def get_xml(self):
1013
 
        """Returns the xml of this worksheet, converts from rst if required."""
1014
 
        if self.format == u'rst':
1015
 
            ws_xml = rst(self.data)
1016
 
            return ws_xml
1017
 
        else:
1018
 
            return self.data
1019
 
 
1020
 
    def delete(self):
1021
 
        """Deletes the worksheet, provided it has no attempts on any exercises.
1022
 
 
1023
 
        Returns True if delete succeeded, or False if this worksheet has
1024
 
        attempts attached."""
1025
 
        for ws_ex in self.all_worksheet_exercises:
1026
 
            if ws_ex.saves.count() > 0 or ws_ex.attempts.count() > 0:
1027
 
                raise IntegrityError()
1028
 
 
1029
 
        self.remove_all_exercises()
1030
 
        Store.of(self).remove(self)
 
475
            
 
476
    def get_permissions(self, user):
 
477
        return self.offering.get_permissions(user)
1031
478
 
1032
479
class WorksheetExercise(Storm):
1033
 
    """A link between a worksheet and one of its exercises.
1034
 
 
1035
 
    These may be marked optional, in which case the exercise does not count
1036
 
    for marking purposes. The sequence number is used to order the worksheet
1037
 
    ToC.
1038
 
    """
1039
 
 
1040
480
    __storm_table__ = "worksheet_exercise"
1041
 
 
 
481
    
1042
482
    id = Int(primary=True, name="ws_ex_id")
1043
483
 
1044
484
    worksheet_id = Int(name="worksheetid")
1048
488
    optional = Bool()
1049
489
    active = Bool()
1050
490
    seq_no = Int()
1051
 
 
 
491
    
1052
492
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
1053
493
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
1054
494
 
1058
498
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
1059
499
                                  self.worksheet.identifier)
1060
500
 
1061
 
    def get_permissions(self, user, config):
1062
 
        return self.worksheet.get_permissions(user, config)
1063
 
 
1064
 
 
1065
501
class ExerciseSave(Storm):
1066
 
    """A potential exercise solution submitted by a user for storage.
1067
 
 
1068
 
    This is not an actual tested attempt at an exercise, it's just a save of
1069
 
    the editing session.
1070
 
    """
1071
 
 
 
502
    """
 
503
    Represents a potential solution to an exercise that a user has submitted
 
504
    to the server for storage.
 
505
    A basic ExerciseSave is just the current saved text for this exercise for
 
506
    this user (doesn't count towards their attempts).
 
507
    ExerciseSave may be extended with additional semantics (such as
 
508
    ExerciseAttempt).
 
509
    """
1072
510
    __storm_table__ = "exercise_save"
1073
511
    __storm_primary__ = "ws_ex_id", "user_id"
1074
512
 
1087
525
            self.exercise.name, self.user.login, self.date.strftime("%c"))
1088
526
 
1089
527
class ExerciseAttempt(ExerciseSave):
1090
 
    """An attempt at solving an exercise.
1091
 
 
1092
 
    This is a special case of ExerciseSave, used when the user submits a
1093
 
    candidate solution. Like an ExerciseSave, it constitutes exercise solution
1094
 
    data.
1095
 
 
1096
 
    In addition, it contains information about the result of the submission:
1097
 
 
1098
 
     - complete - True if this submission was successful, rendering this
1099
 
                  exercise complete for this user in this worksheet.
1100
 
     - active   - True if this submission is "active" (usually true).
1101
 
                  Submissions may be de-activated by privileged users for
1102
 
                  special reasons, and then they won't count (either as a
1103
 
                  penalty or success), but will still be stored.
1104
 
    """
1105
 
 
 
528
    """
 
529
    An ExerciseAttempt is a special case of an ExerciseSave. Like an
 
530
    ExerciseSave, it constitutes exercise solution data that the user has
 
531
    submitted to the server for storage.
 
532
    In addition, it contains additional information about the submission.
 
533
    complete - True if this submission was successful, rendering this exercise
 
534
        complete for this user.
 
535
    active - True if this submission is "active" (usually true). Submissions
 
536
        may be de-activated by privileged users for special reasons, and then
 
537
        they won't count (either as a penalty or success), but will still be
 
538
        stored.
 
539
    """
1106
540
    __storm_table__ = "exercise_attempt"
1107
541
    __storm_primary__ = "ws_ex_id", "user_id", "date"
1108
542
 
1111
545
    text = Unicode(name="attempt")
1112
546
    complete = Bool()
1113
547
    active = Bool()
1114
 
 
1115
 
    def get_permissions(self, user, config):
 
548
    
 
549
    def get_permissions(self, user):
1116
550
        return set(['view']) if user is self.user else set()
1117
 
 
 
551
  
1118
552
class TestSuite(Storm):
1119
 
    """A container to group an exercise's test cases.
1120
 
 
1121
 
    The test suite contains some information on how to test. The function to
1122
 
    test, variables to set and stdin data are stored here.
1123
 
    """
1124
 
 
 
553
    """A Testsuite acts as a container for the test cases of an exercise."""
1125
554
    __storm_table__ = "test_suite"
1126
555
    __storm_primary__ = "exercise_id", "suiteid"
1127
 
 
 
556
    
1128
557
    suiteid = Int()
1129
558
    exercise_id = Unicode(name="exerciseid")
1130
559
    description = Unicode()
1132
561
    function = Unicode()
1133
562
    stdin = Unicode()
1134
563
    exercise = Reference(exercise_id, Exercise.id)
1135
 
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid', order_by="seq_no")
1136
 
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid', order_by='arg_no')
1137
 
 
1138
 
    def delete(self):
1139
 
        """Delete this suite, without asking questions."""
1140
 
        for variable in self.variables:
1141
 
            variable.delete()
1142
 
        for test_case in self.test_cases:
1143
 
            test_case.delete()
1144
 
        Store.of(self).remove(self)
 
564
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
 
565
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid')
1145
566
 
1146
567
class TestCase(Storm):
1147
 
    """A container for actual tests (see TestCasePart), inside a test suite.
1148
 
 
1149
 
    It is the lowest level shown to students on their pass/fail status."""
1150
 
 
 
568
    """A TestCase is a member of a TestSuite.
 
569
    
 
570
    It contains the data necessary to check if an exercise is correct"""
1151
571
    __storm_table__ = "test_case"
1152
572
    __storm_primary__ = "testid", "suiteid"
1153
 
 
 
573
    
1154
574
    testid = Int()
1155
575
    suiteid = Int()
1156
576
    suite = Reference(suiteid, "TestSuite.suiteid")
1157
577
    passmsg = Unicode()
1158
578
    failmsg = Unicode()
1159
 
    test_default = Unicode() # Currently unused - only used for file matching.
 
579
    test_default = Unicode()
1160
580
    seq_no = Int()
1161
 
 
 
581
    
1162
582
    parts = ReferenceSet(testid, "TestCasePart.testid")
1163
 
 
 
583
    
1164
584
    __init__ = _kwarg_init
1165
585
 
1166
 
    def delete(self):
1167
 
        for part in self.parts:
1168
 
            part.delete()
1169
 
        Store.of(self).remove(self)
1170
 
 
1171
586
class TestSuiteVar(Storm):
1172
 
    """A variable used by an exercise test suite.
1173
 
 
1174
 
    This may represent a function argument or a normal variable.
1175
 
    """
1176
 
 
 
587
    """A container for the arguments of a Test Suite"""
1177
588
    __storm_table__ = "suite_variable"
1178
589
    __storm_primary__ = "varid"
1179
 
 
 
590
    
1180
591
    varid = Int()
1181
592
    suiteid = Int()
1182
593
    var_name = Unicode()
1183
594
    var_value = Unicode()
1184
595
    var_type = Unicode()
1185
596
    arg_no = Int()
1186
 
 
 
597
    
1187
598
    suite = Reference(suiteid, "TestSuite.suiteid")
1188
 
 
 
599
    
1189
600
    __init__ = _kwarg_init
1190
 
 
1191
 
    def delete(self):
1192
 
        Store.of(self).remove(self)
1193
 
 
 
601
    
1194
602
class TestCasePart(Storm):
1195
 
    """An actual piece of code to test an exercise solution."""
1196
 
 
 
603
    """A container for the test elements of a Test Case"""
1197
604
    __storm_table__ = "test_case_part"
1198
605
    __storm_primary__ = "partid"
1199
 
 
 
606
    
1200
607
    partid = Int()
1201
608
    testid = Int()
1202
 
 
 
609
    
1203
610
    part_type = Unicode()
1204
611
    test_type = Unicode()
1205
612
    data = Unicode()
1206
613
    filename = Unicode()
1207
 
 
 
614
    
1208
615
    test = Reference(testid, "TestCase.testid")
1209
 
 
 
616
    
1210
617
    __init__ = _kwarg_init
1211
 
 
1212
 
    def delete(self):
1213
 
        Store.of(self).remove(self)