[7191] | 1 | ## $Id: student.py 8448 2012-05-14 14:29:02Z uli $ |
---|
| 2 | ## |
---|
[6621] | 3 | ## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann |
---|
| 4 | ## This program is free software; you can redistribute it and/or modify |
---|
| 5 | ## it under the terms of the GNU General Public License as published by |
---|
| 6 | ## the Free Software Foundation; either version 2 of the License, or |
---|
| 7 | ## (at your option) any later version. |
---|
| 8 | ## |
---|
| 9 | ## This program is distributed in the hope that it will be useful, |
---|
| 10 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 11 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 12 | ## GNU General Public License for more details. |
---|
| 13 | ## |
---|
| 14 | ## You should have received a copy of the GNU General Public License |
---|
| 15 | ## along with this program; if not, write to the Free Software |
---|
| 16 | ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
---|
| 17 | ## |
---|
| 18 | """ |
---|
| 19 | Container for the various objects owned by students. |
---|
| 20 | """ |
---|
[7097] | 21 | import os |
---|
[8448] | 22 | import re |
---|
[8403] | 23 | import shutil |
---|
[6621] | 24 | import grok |
---|
[7949] | 25 | from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo |
---|
[8323] | 26 | from zope.component import getUtility, createObject |
---|
[6749] | 27 | from zope.component.interfaces import IFactory |
---|
[6621] | 28 | from zope.interface import implementedBy |
---|
[6838] | 29 | from zope.securitypolicy.interfaces import IPrincipalRoleManager |
---|
[8403] | 30 | |
---|
[7949] | 31 | from waeup.kofa.image import KofaImageFile |
---|
| 32 | from waeup.kofa.imagestorage import DefaultFileStoreHandler |
---|
[7811] | 33 | from waeup.kofa.interfaces import ( |
---|
[7359] | 34 | IObjectHistory, IUserAccount, IFileStoreNameChooser, IFileStoreHandler, |
---|
[8411] | 35 | IKofaUtils, CLEARANCE, registration_states_vocab, IExtFileStore,) |
---|
[7949] | 36 | from waeup.kofa.students.accommodation import StudentAccommodation |
---|
[8403] | 37 | from waeup.kofa.students.export import EXPORTER_NAMES |
---|
[8411] | 38 | from waeup.kofa.students.interfaces import ( |
---|
| 39 | IStudent, IStudentNavigation, ICSVStudentExporter) |
---|
[7949] | 40 | from waeup.kofa.students.payments import StudentPaymentsContainer |
---|
| 41 | from waeup.kofa.students.utils import generate_student_id |
---|
[8403] | 42 | from waeup.kofa.utils.helpers import attrs_to_fields, now, copy_filesystem_tree |
---|
[6621] | 43 | |
---|
[8448] | 44 | RE_STUDID_NON_NUM = re.compile('[^\d]+') |
---|
| 45 | |
---|
[6621] | 46 | class Student(grok.Container): |
---|
| 47 | """This is a student container for the various objects |
---|
| 48 | owned by students. |
---|
| 49 | """ |
---|
[7538] | 50 | grok.implements(IStudent, IStudentNavigation) |
---|
[6621] | 51 | grok.provides(IStudent) |
---|
| 52 | |
---|
| 53 | def __init__(self): |
---|
| 54 | super(Student, self).__init__() |
---|
[6749] | 55 | # The site doesn't exist in unit tests |
---|
[6652] | 56 | try: |
---|
[6749] | 57 | students = grok.getSite()['students'] |
---|
| 58 | self.student_id = generate_student_id(students,'?') |
---|
| 59 | except TypeError: |
---|
[6666] | 60 | self.student_id = u'Z654321' |
---|
[6699] | 61 | self.password = None |
---|
[6621] | 62 | return |
---|
| 63 | |
---|
[6637] | 64 | def loggerInfo(self, ob_class, comment=None): |
---|
| 65 | target = self.__name__ |
---|
| 66 | return grok.getSite()['students'].logger_info(ob_class,target,comment) |
---|
| 67 | |
---|
| 68 | @property |
---|
[7364] | 69 | def display_fullname(self): |
---|
[7357] | 70 | middlename = getattr(self, 'middlename', None) |
---|
[7819] | 71 | kofa_utils = getUtility(IKofaUtils) |
---|
[7811] | 72 | return kofa_utils.fullname(self.firstname, self.lastname, middlename) |
---|
[7357] | 73 | |
---|
| 74 | @property |
---|
[7364] | 75 | def fullname(self): |
---|
| 76 | middlename = getattr(self, 'middlename', None) |
---|
| 77 | if middlename: |
---|
| 78 | return '%s-%s-%s' % (self.firstname.lower(), |
---|
| 79 | middlename.lower(), self.lastname.lower()) |
---|
| 80 | else: |
---|
| 81 | return '%s-%s' % (self.firstname.lower(), self.lastname.lower()) |
---|
| 82 | |
---|
| 83 | @property |
---|
[6637] | 84 | def state(self): |
---|
| 85 | state = IWorkflowState(self).getState() |
---|
| 86 | return state |
---|
| 87 | |
---|
| 88 | @property |
---|
[7677] | 89 | def translated_state(self): |
---|
| 90 | state = registration_states_vocab.getTermByToken( |
---|
| 91 | self.state).title |
---|
| 92 | return state |
---|
| 93 | |
---|
| 94 | @property |
---|
[6637] | 95 | def history(self): |
---|
| 96 | history = IObjectHistory(self) |
---|
| 97 | return history |
---|
| 98 | |
---|
[6642] | 99 | def getStudent(self): |
---|
| 100 | return self |
---|
| 101 | |
---|
[6814] | 102 | @property |
---|
[7203] | 103 | def certcode(self): |
---|
[6814] | 104 | cert = getattr(self.get('studycourse', None), 'certificate', None) |
---|
[7203] | 105 | if cert is not None: |
---|
| 106 | return cert.code |
---|
| 107 | return |
---|
[6814] | 108 | |
---|
[7062] | 109 | @property |
---|
[7203] | 110 | def faccode(self): |
---|
| 111 | cert = getattr(self.get('studycourse', None), 'certificate', None) |
---|
| 112 | if cert is not None: |
---|
| 113 | return cert.__parent__.__parent__.__parent__.code |
---|
| 114 | return |
---|
| 115 | |
---|
| 116 | @property |
---|
| 117 | def depcode(self): |
---|
| 118 | cert = getattr(self.get('studycourse', None), 'certificate', None) |
---|
| 119 | if cert is not None: |
---|
| 120 | return cert.__parent__.__parent__.code |
---|
| 121 | return |
---|
| 122 | |
---|
| 123 | @property |
---|
[7062] | 124 | def current_session(self): |
---|
[7948] | 125 | session = getattr( |
---|
| 126 | self.get('studycourse', None), 'current_session', None) |
---|
[7641] | 127 | return session |
---|
[7062] | 128 | |
---|
[7641] | 129 | @property |
---|
| 130 | def current_mode(self): |
---|
[7948] | 131 | certificate = getattr( |
---|
| 132 | self.get('studycourse', None), 'certificate', None) |
---|
[7641] | 133 | if certificate is not None: |
---|
| 134 | return certificate.study_mode |
---|
| 135 | return |
---|
| 136 | |
---|
[6621] | 137 | # Set all attributes of Student required in IStudent as field |
---|
| 138 | # properties. Doing this, we do not have to set initial attributes |
---|
| 139 | # ourselves and as a bonus we get free validation when an attribute is |
---|
| 140 | # set. |
---|
| 141 | Student = attrs_to_fields(Student) |
---|
| 142 | |
---|
| 143 | class StudentFactory(grok.GlobalUtility): |
---|
| 144 | """A factory for students. |
---|
| 145 | """ |
---|
| 146 | grok.implements(IFactory) |
---|
| 147 | grok.name(u'waeup.Student') |
---|
| 148 | title = u"Create a new student.", |
---|
| 149 | description = u"This factory instantiates new student instances." |
---|
| 150 | |
---|
| 151 | def __call__(self, *args, **kw): |
---|
| 152 | return Student() |
---|
| 153 | |
---|
| 154 | def getInterfaces(self): |
---|
| 155 | return implementedBy(Student) |
---|
[6836] | 156 | |
---|
[6838] | 157 | @grok.subscribe(IStudent, grok.IObjectAddedEvent) |
---|
[6839] | 158 | def handle_student_added(student, event): |
---|
[6838] | 159 | """If a student is added all subcontainers are automatically added |
---|
[7948] | 160 | and the transition create is fired. The latter produces a logging |
---|
| 161 | message. |
---|
[6838] | 162 | """ |
---|
[8375] | 163 | if student.state == CLEARANCE: |
---|
[7527] | 164 | student.clearance_locked = False |
---|
| 165 | else: |
---|
| 166 | student.clearance_locked = True |
---|
[8323] | 167 | studycourse = createObject(u'waeup.StudentStudyCourse') |
---|
[6838] | 168 | student['studycourse'] = studycourse |
---|
[6859] | 169 | payments = StudentPaymentsContainer() |
---|
[6838] | 170 | student['payments'] = payments |
---|
| 171 | accommodation = StudentAccommodation() |
---|
| 172 | student['accommodation'] = accommodation |
---|
| 173 | # Assign global student role for new student |
---|
| 174 | account = IUserAccount(student) |
---|
| 175 | account.roles = ['waeup.Student'] |
---|
| 176 | # Assign local StudentRecordOwner role |
---|
| 177 | role_manager = IPrincipalRoleManager(student) |
---|
| 178 | role_manager.assignRoleToPrincipal( |
---|
| 179 | 'waeup.local.StudentRecordOwner', student.student_id) |
---|
[8375] | 180 | if student.state is None: |
---|
[7513] | 181 | IWorkflowInfo(student).fireTransition('create') |
---|
[6838] | 182 | return |
---|
| 183 | |
---|
[8448] | 184 | def path_from_studid(student_id): |
---|
| 185 | """Convert a student_id into a predictable relative folder path. |
---|
| 186 | |
---|
| 187 | Used for storing files. |
---|
| 188 | |
---|
| 189 | Returns the name of folder in which files for a particular student |
---|
| 190 | should be stored. This is a relative path, relative to any general |
---|
| 191 | students folder. |
---|
| 192 | |
---|
| 193 | For instance ``K1000000`` will give ``01000/K1000000`` and |
---|
| 194 | ``KM123456`` will result in ``00123/KM123456``. |
---|
| 195 | """ |
---|
| 196 | # remove all non numeric characters and turn this into an int. |
---|
| 197 | num = int(RE_STUDID_NON_NUM.sub('', student_id)) |
---|
| 198 | # store max. of 1000 studs per folder |
---|
| 199 | folder_name = u'%05d' % (num / 1000) |
---|
| 200 | folder_name = os.path.join(folder_name, student_id) |
---|
| 201 | return folder_name |
---|
| 202 | |
---|
[8403] | 203 | def move_student_files(student, del_dir): |
---|
| 204 | """Move files belonging to `student` to `del_dir`. |
---|
| 205 | |
---|
| 206 | `del_dir` is expected to be the path to the site-wide directory |
---|
| 207 | for storing backup data. |
---|
| 208 | |
---|
| 209 | The current files of the student are removed after backup. |
---|
| 210 | |
---|
| 211 | If the student has no associated files stored, nothing is done. |
---|
| 212 | """ |
---|
| 213 | stud_id = student.student_id |
---|
| 214 | |
---|
| 215 | src = getUtility(IExtFileStore).root |
---|
[8448] | 216 | src = os.path.join(src, 'students', path_from_studid(stud_id)) |
---|
[8403] | 217 | |
---|
[8448] | 218 | dst = os.path.join( |
---|
| 219 | del_dir, 'media', 'students', path_from_studid(stud_id)) |
---|
[8403] | 220 | |
---|
| 221 | if not os.path.isdir(src): |
---|
| 222 | # Do not copy if no files were stored. |
---|
| 223 | return |
---|
| 224 | if not os.path.exists(dst): |
---|
| 225 | os.makedirs(dst, 0755) |
---|
| 226 | copy_filesystem_tree(src, dst) |
---|
| 227 | shutil.rmtree(src) |
---|
| 228 | return |
---|
| 229 | |
---|
| 230 | def update_student_deletion_csvs(student, del_dir): |
---|
| 231 | """Update deletion CSV files with data from student. |
---|
| 232 | |
---|
| 233 | `del_dir` is expected to be the path to the site-wide directory |
---|
| 234 | for storing backup data. |
---|
| 235 | |
---|
| 236 | Each exporter available for students (and their many subobjects) |
---|
| 237 | is called in order to export CSV data of the given student to csv |
---|
| 238 | files in the site-wide backup directory for object data (see |
---|
| 239 | DataCenter). |
---|
| 240 | |
---|
| 241 | Each exported row is appended a column giving the deletion date |
---|
| 242 | (column `del_date`) as a UTC timestamp. |
---|
| 243 | """ |
---|
| 244 | for name in EXPORTER_NAMES: |
---|
[8411] | 245 | exporter = getUtility(ICSVStudentExporter, name=name) |
---|
| 246 | csv_data = exporter.export_student(student) |
---|
[8403] | 247 | csv_data = csv_data.split('\r\n') |
---|
| 248 | |
---|
| 249 | # append a deletion timestamp on each data row |
---|
| 250 | timestamp = str(now().replace(microsecond=0)) # store UTC timestamp |
---|
| 251 | for num, row in enumerate(csv_data[1:-1]): |
---|
| 252 | csv_data[num+1] = csv_data[num+1] + ',' + timestamp |
---|
| 253 | csv_path = os.path.join(del_dir, '%s.csv' % name) |
---|
| 254 | |
---|
| 255 | # write data to CSV file |
---|
| 256 | if not os.path.exists(csv_path): |
---|
| 257 | # create new CSV file (including header line) |
---|
| 258 | csv_data[0] = csv_data[0] + ',del_date' |
---|
| 259 | open(csv_path, 'wb').write('\r\n'.join(csv_data)) |
---|
| 260 | else: |
---|
| 261 | # append existing CSV file (omitting headerline) |
---|
| 262 | open(csv_path, 'a').write('\r\n'.join(csv_data[1:])) |
---|
| 263 | return |
---|
| 264 | |
---|
[6836] | 265 | @grok.subscribe(IStudent, grok.IObjectRemovedEvent) |
---|
[6839] | 266 | def handle_student_removed(student, event): |
---|
[8403] | 267 | """If a student is removed a message is logged and data is put |
---|
| 268 | into a backup location. |
---|
| 269 | |
---|
| 270 | The data of the removed student is appended to CSV files in local |
---|
| 271 | datacenter and any existing external files (passport images, etc.) |
---|
| 272 | are copied over to this location as well. |
---|
| 273 | |
---|
| 274 | Documents in the file storage refering to the given student are |
---|
| 275 | removed afterwards (if they exist). Please make no assumptions |
---|
| 276 | about how the deletion takes place. Files might be deleted |
---|
| 277 | individually (leaving the students file directory intact) or the |
---|
| 278 | whole student directory might be deleted completely. |
---|
| 279 | |
---|
| 280 | All CSV rows created/appended contain a timestamp with the |
---|
| 281 | datetime of removal in an additional `del_date` column. |
---|
| 282 | |
---|
| 283 | XXX: blocking of used student_ids yet not implemented. |
---|
[6836] | 284 | """ |
---|
| 285 | comment = 'Student record removed' |
---|
| 286 | target = student.student_id |
---|
[6841] | 287 | try: |
---|
[8403] | 288 | site = grok.getSite() |
---|
| 289 | site['students'].logger.info('%s - %s' % ( |
---|
[7652] | 290 | target, comment)) |
---|
[7212] | 291 | except KeyError: |
---|
| 292 | # If we delete an entire university instance there won't be |
---|
| 293 | # a students subcontainer |
---|
| 294 | return |
---|
[8403] | 295 | |
---|
| 296 | del_dir = site['datacenter'].deleted_path |
---|
| 297 | |
---|
| 298 | # save files of the student |
---|
| 299 | move_student_files(student, del_dir) |
---|
| 300 | |
---|
| 301 | # update CSV files |
---|
| 302 | update_student_deletion_csvs(student, del_dir) |
---|
[7097] | 303 | return |
---|
| 304 | |
---|
| 305 | #: The file id marker for student files |
---|
| 306 | STUDENT_FILE_STORE_NAME = 'file-student' |
---|
| 307 | |
---|
| 308 | class StudentFileNameChooser(grok.Adapter): |
---|
[7099] | 309 | """A file id chooser for :class:`Student` objects. |
---|
[7097] | 310 | |
---|
[7099] | 311 | `context` is an :class:`Student` instance. |
---|
[7097] | 312 | |
---|
[7099] | 313 | The :class:`StudentImageNameChooser` can build/check file ids for |
---|
| 314 | :class:`Student` objects suitable for use with |
---|
[7097] | 315 | :class:`ExtFileStore` instances. The delivered file_id contains |
---|
[7099] | 316 | the file id marker for :class:`Student` object and the student id |
---|
| 317 | of the context student. |
---|
[7097] | 318 | |
---|
| 319 | This chooser is registered as an adapter providing |
---|
[7811] | 320 | :class:`waeup.kofa.interfaces.IFileStoreNameChooser`. |
---|
[7097] | 321 | |
---|
| 322 | File store name choosers like this one are only convenience |
---|
[7099] | 323 | components to ease the task of creating file ids for student |
---|
[7097] | 324 | objects. You are nevertheless encouraged to use them instead of |
---|
[7099] | 325 | manually setting up filenames for students. |
---|
[7097] | 326 | |
---|
[7811] | 327 | .. seealso:: :mod:`waeup.kofa.imagestorage` |
---|
[7097] | 328 | |
---|
| 329 | """ |
---|
| 330 | grok.context(IStudent) |
---|
| 331 | grok.implements(IFileStoreNameChooser) |
---|
| 332 | |
---|
| 333 | def checkName(self, name=None, attr=None): |
---|
| 334 | """Check whether the given name is a valid file id for the context. |
---|
| 335 | |
---|
| 336 | Returns ``True`` only if `name` equals the result of |
---|
| 337 | :meth:`chooseName`. |
---|
| 338 | |
---|
| 339 | """ |
---|
| 340 | return name == self.chooseName() |
---|
| 341 | |
---|
[7106] | 342 | def chooseName(self, attr, name=None): |
---|
[7097] | 343 | """Get a valid file id for student context. |
---|
| 344 | |
---|
| 345 | *Example:* |
---|
| 346 | |
---|
[7105] | 347 | For a student with student id ``'A123456'`` and |
---|
[7106] | 348 | with attr ``'nice_image.jpeg'`` stored in |
---|
[7097] | 349 | the students container this chooser would create: |
---|
| 350 | |
---|
[7106] | 351 | ``'__file-student__students/A/A123456/nice_image_A123456.jpeg'`` |
---|
[7097] | 352 | |
---|
| 353 | meaning that the nice image of this applicant would be |
---|
| 354 | stored in the site-wide file storage in path: |
---|
| 355 | |
---|
[7106] | 356 | ``students/A/A123456/nice_image_A123456.jpeg`` |
---|
[7097] | 357 | |
---|
| 358 | """ |
---|
[7106] | 359 | basename, ext = os.path.splitext(attr) |
---|
[7099] | 360 | stud_id = self.context.student_id |
---|
[8448] | 361 | marked_filename = '__%s__%s/%s_%s%s' % ( |
---|
| 362 | STUDENT_FILE_STORE_NAME, path_from_studid(stud_id), basename, |
---|
[7948] | 363 | stud_id, ext) |
---|
[7097] | 364 | return marked_filename |
---|
| 365 | |
---|
| 366 | |
---|
| 367 | class StudentFileStoreHandler(DefaultFileStoreHandler, grok.GlobalUtility): |
---|
| 368 | """Student specific file handling. |
---|
| 369 | |
---|
| 370 | This handler knows in which path in a filestore to store student |
---|
| 371 | files and how to turn this kind of data into some (browsable) |
---|
| 372 | file object. |
---|
| 373 | |
---|
| 374 | It is called from the global file storage, when it wants to |
---|
| 375 | get/store a file with a file id starting with |
---|
| 376 | ``__file-student__`` (the marker string for student files). |
---|
| 377 | |
---|
| 378 | Like each other file store handler it does not handle the files |
---|
| 379 | really (this is done by the global file store) but only computes |
---|
| 380 | paths and things like this. |
---|
| 381 | """ |
---|
| 382 | grok.implements(IFileStoreHandler) |
---|
| 383 | grok.name(STUDENT_FILE_STORE_NAME) |
---|
| 384 | |
---|
| 385 | def pathFromFileID(self, store, root, file_id): |
---|
[7099] | 386 | """All student files are put in directory ``students``. |
---|
[7097] | 387 | """ |
---|
| 388 | marker, filename, basename, ext = store.extractMarker(file_id) |
---|
[7122] | 389 | sub_root = os.path.join(root, 'students') |
---|
| 390 | return super(StudentFileStoreHandler, self).pathFromFileID( |
---|
| 391 | store, sub_root, basename) |
---|
[7097] | 392 | |
---|
| 393 | def createFile(self, store, root, filename, file_id, file): |
---|
| 394 | """Create a browsable file-like object. |
---|
| 395 | """ |
---|
[7122] | 396 | # call super method to ensure that any old files with |
---|
| 397 | # different filename extension are deleted. |
---|
| 398 | file, path, file_obj = super( |
---|
| 399 | StudentFileStoreHandler, self).createFile( |
---|
| 400 | store, root, filename, file_id, file) |
---|
[7819] | 401 | return file, path, KofaImageFile( |
---|
[7122] | 402 | file_obj.filename, file_obj.data) |
---|