source: WAeUP_SRP/base/Widgets.py @ 2558

Last change on this file since 2558 was 2557, checked in by joachim, 17 years ago

unprotect makeStudentData, fix ref

  • Property svn:keywords set to Id
File size: 77.2 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: Widgets.py 2557 2007-11-06 15:40:21Z joachim $
3from cgi import escape
4from types import *
5import Globals
6from Globals import InitializeClass
7from ZPublisher.HTTPRequest import FileUpload
8from OFS.Image import cookId, File, Image
9##from Products.CPSSchemas.Widget import CPSWidgetType
10from Products.CMFCore.utils import getToolByName
11from Products.CPSSchemas.BasicWidgets import CPSBooleanWidget, CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
12from Products.CPSSchemas.BasicWidgets import CPSFileWidget
13from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
14from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
15from Products.CPSSchemas.Widget import widgetRegistry
16from Products.CPSUtil.file import PersistableFileUpload
17from Products.CPSUtil.id import generateFileName
18##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
19from DateTime.DateTime import DateTime
20from AccessControl import getSecurityManager
21from Products.WAeUP_SRP.Students import getStudentByRegNo
22from Products.WAeUP_SRP.Academics import makeCertificateCode
23#from Products.ExtFile.ExtFile import ExtFile
24import logging,os,re
25import operator
26p_home = Globals.package_home(globals())
27i_home = Globals.INSTANCE_HOME
28
29#from zLOG import LOG, DEBUG
30
31class CPSSelectWidgetForRecord(CPSSelectWidget): ###(
32    """Select widget. with record names"""
33    meta_type = 'Select Widget for Records'
34
35    field_types = ('CPS String Field',)
36    field_inits = ({'is_searchabletext': 1,},)
37
38    _properties = CPSSelectWidget._properties + (
39        {'id': 'record_id', 'type': 'string', 'mode': 'w',
40         'label': 'Record Id', 'is_required' : 1},
41        )
42
43    def render(self, mode, datastructure, **kw):
44        """Render in mode from datastructure."""
45        value = datastructure[self.getWidgetId()]
46        vocabulary = self._getVocabulary(datastructure)
47        portal = getToolByName(self, 'portal_url').getPortalObject()
48        cpsmcat = portal.translation_service
49        if mode == 'view':
50            if self.translated:
51                return escape(cpsmcat(vocabulary.getMsgid(value, value)).encode('ISO-8859-15', 'ignore'))
52            else:
53                return escape(vocabulary.get(value, value))
54        elif mode == 'edit':
55            html_widget_id = self.getHtmlWidgetId()
56            res = renderHtmlTag('select',
57                                name='%s.%s:records' % (self.record_id,html_widget_id),
58                                id=html_widget_id)
59            in_selection = 0
60            for k, v in vocabulary.items():
61                if self.translated:
62                    kw = {'value': k,
63                          'contents': cpsmcat(vocabulary.getMsgid(k, k)).encode('ISO-8859-15', 'ignore')
64                          }
65                else:
66                    kw = {'value': k, 'contents': v}
67                if value == k:
68                    kw['selected'] = 'selected'
69                    in_selection = 1
70                res += renderHtmlTag('option', **kw)
71            if value and not in_selection:
72                kw = {'value': value, 'contents': 'invalid: '+ str(value),
73                      'selected': 'selected'}
74                res += renderHtmlTag('option', **kw)
75            res += '</select>'
76            return res
77        raise RuntimeError('unknown mode %s' % mode)
78
79InitializeClass(CPSSelectWidgetForRecord)
80
81widgetRegistry.register(CPSSelectWidgetForRecord)
82
83###)
84
85class CPSStringWidgetForRecord(CPSStringWidget): ###(
86    """String widget."""
87    meta_type = 'String Widget For Record'
88
89    field_types = ('CPS String Field',)
90    field_inits = ({'is_searchabletext': 1,},)
91    _properties = CPSStringWidget._properties + (
92        {'id': 'record_id', 'type': 'string', 'mode': 'w',
93         'label': 'Record Id', 'is_required' : 1},
94        )
95
96    def render(self, mode, datastructure, **kw):
97        """Render in mode from datastructure."""
98        value = datastructure[self.getWidgetId()]
99        if mode == 'view':
100            return escape(value)
101        elif mode == 'edit':
102            # XXX TODO should use an other name than kw !
103            # XXX change this everywhere
104            html_widget_id = self.getHtmlWidgetId()
105            kw = {'type': 'text',
106                  'id'  : html_widget_id,
107                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
108                  'value': escape(value),
109                  'size': self.display_width,
110                  }
111            if self.size_max:
112                kw['maxlength'] = self.size_max
113            return renderHtmlTag('input', **kw)
114        raise RuntimeError('unknown mode %s' % mode)
115
116InitializeClass(CPSStringWidgetForRecord)
117
118widgetRegistry.register(CPSStringWidgetForRecord)
119
120###)
121
122class CertificateCourseIdWidget(CPSStringWidget): ###(
123    """ CertificateCourseId Widget"""
124    meta_type = "CertificateCourseId Widget"
125
126    def validate(self, datastructure, **kw):
127        """Validate datastructure and update datamodel."""
128
129        valid = CPSStringWidget.validate(self, datastructure, **kw)
130        if not valid:
131            return 0
132        else:
133            widget_id = self.getWidgetId()
134            value = datastructure[widget_id].upper()
135            err = 0
136            c_ids = [c.id for c in self.portal_catalog({'meta_type': "Course"})]
137            if hasattr(self.aq_parent,value):
138                err = 'Course already exists'
139            elif value not in c_ids:
140                err = 'Course does not exist'
141            if err:
142                datastructure.setError(widget_id, err)
143            else:
144                datamodel = datastructure.getDataModel()
145                datamodel[self.fields[0]] = value
146
147            return not err
148
149InitializeClass(CertificateCourseIdWidget)
150
151widgetRegistry.register(CertificateCourseIdWidget)
152###)
153
154class CourseIdWidget(CPSStringWidget): ###(
155    """ CourseId Widget"""
156    meta_type = "CourseId Widget"
157
158    def validate(self, datastructure, **kw):
159        """Validate datastructure and update datamodel."""
160
161        valid = CPSStringWidget.validate(self, datastructure, **kw)
162        if not valid:
163            return 0
164        else:
165            widget_id = self.getWidgetId()
166            value = datastructure[widget_id].upper()
167            err = 0
168            res = self.courses_catalog(code = value)
169            if len(res) > 0:
170                err = 'Course already exists'
171            if err:
172                datastructure.setError(widget_id, err)
173            else:
174                datamodel = datastructure.getDataModel()
175                datamodel[self.fields[0]] = value
176
177            return not err
178
179InitializeClass(CourseIdWidget)
180
181widgetRegistry.register(CourseIdWidget)
182
183
184###)
185
186class WAeUPStudyModeWidget(CPSSelectWidget): ###(
187    """WAeUP StudyMode Widget."""
188    meta_type = 'WAeUP StudyMode Widget'
189    vocabulary = 'entry_modes'
190
191    def _getStudyModes(self):
192        voc = getattr(self.portal_vocabularies,self.vocabulary)
193        d = {}
194        for k,v in voc.items():
195            d[k] = v
196        return d
197
198    def validate(self, datastructure, **kw):
199        """Validate datastructure and update datamodel."""
200        widget_id = self.getWidgetId()
201        value = datastructure[widget_id]
202        try:
203            v = str(value)
204        except ValueError:
205            datastructure.setError(widget_id, "'%s' not a valid session key" % value)
206            return 0
207        studymodes = self._getStudyModes()
208        if not value:
209            v = value = 'ume_ft'
210        #import pdb;pdb.set_trace()
211        if not studymodes.has_key(value):
212            datastructure.setError(widget_id, "'%s' not a valid session key" % v)
213            return 0
214        if self.is_required and not len(v):
215            datastructure.setError(widget_id, "session key required")
216            return 0
217
218        datamodel = datastructure.getDataModel()
219        datamodel[self.fields[0]] = v
220        return 1
221
222    def render(self, mode, datastructure, **kw):
223        """Render in mode from datastructure."""
224        value = datastructure[self.getWidgetId()]
225        studymodes = self._getStudyModes()
226        if mode == 'view':
227            return escape(studymodes.get(value, value))
228        elif mode == 'edit':
229            html_widget_id = self.getHtmlWidgetId()
230            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
231            in_selection = 0
232            vocabulary_items = studymodes.items()
233            if self.sorted:
234                vocabulary_items.sort(key=operator.itemgetter(1))
235            for k, v in vocabulary_items:
236                kw = {'value': k, 'contents': v}
237                if value == k:
238                    kw['selected'] = 'selected'
239                    in_selection = 1
240                res += renderHtmlTag('option', **kw)
241            if value and not in_selection:
242                kw = {'value': value, 'contents': 'invalid: '+ str(value),
243                      'selected': 'selected'}
244                res += renderHtmlTag('option', **kw)
245            res += '</select>'
246            return res
247        raise RuntimeError('unknown mode %s' % mode)
248
249InitializeClass(WAeUPStudyModeWidget)
250
251widgetRegistry.register(WAeUPStudyModeWidget)
252
253###)
254
255class WAeUPSessionWidget(CPSSelectWidget): ###(
256    """WAeUP Session Widget."""
257    meta_type = 'WAeUP Session Widget'
258
259    def _getSessions(self):
260        current_year = DateTime().year()
261        d = {'-1': 'N/A'}
262        for y in range(current_year - 9,current_year + 1):
263            d['%s' % str(y)[-2:]] = '%4d/%4d' % (y,y+1)
264        return d
265
266    def validate(self, datastructure, **kw):
267        """Validate datastructure and update datamodel."""
268        widget_id = self.getWidgetId()
269        value = datastructure[widget_id]
270        try:
271            v = str(value)
272        except ValueError:
273            datastructure.setError(widget_id, "'%s' not a valid session key" % value)
274            return 0
275
276        if len(v) == 1:
277            v = value = '0%c' % v
278        elif not value:
279            v = value = self.getSessionId()[0]
280        #import pdb;pdb.set_trace()
281        sessions = self._getSessions()
282        if not sessions.has_key(value):
283            datastructure.setError(widget_id, "'%s' not a valid session key" % v)
284            return 0
285        if self.is_required and not len(v):
286            datastructure.setError(widget_id, "session key required")
287            return 0
288
289        datamodel = datastructure.getDataModel()
290        datamodel[self.fields[0]] = v
291        return 1
292
293    def render(self, mode, datastructure, **kw):
294        """Render in mode from datastructure."""
295        value = datastructure[self.getWidgetId()]
296        sessions = self._getSessions()
297        if mode == 'view':
298            return escape(sessions.get(value, value))
299        elif mode == 'edit':
300            html_widget_id = self.getHtmlWidgetId()
301            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
302            in_selection = 0
303            vocabulary_items = sessions.items()
304            if self.sorted:
305                vocabulary_items.sort(key=operator.itemgetter(0))
306            for k, v in vocabulary_items:
307                kw = {'value': k, 'contents': v}
308                if value == k:
309                    kw['selected'] = 'selected'
310                    in_selection = 1
311                res += renderHtmlTag('option', **kw)
312            if value and not in_selection:
313                kw = {'value': value, 'contents': 'invalid: '+ str(value),
314                      'selected': 'selected'}
315                res += renderHtmlTag('option', **kw)
316            res += '</select>'
317            return res
318        raise RuntimeError('unknown mode %s' % mode)
319
320InitializeClass(WAeUPSessionWidget)
321
322widgetRegistry.register(WAeUPSessionWidget)
323
324###)
325
326class WAeUPLevelWidget(CPSSelectWidget): ###(
327    """WAeUP Level Widget."""
328    meta_type = 'WAeUP Level Widget'
329
330    def _getLevels(self):
331        d = {'':'N/A','000':'Pre-Studies'}
332        for y in range(100,800,100):
333            d['%s' % str(y)] = 'Year %1d (%3d Level)' % (y/100,y)
334        return d
335
336    def validate(self, datastructure, **kw):
337        """Validate datastructure and update datamodel."""
338        widget_id = self.getWidgetId()
339        value = datastructure[widget_id]
340        try:
341            v = str(value)
342        except ValueError:
343            datastructure.setError(widget_id, "'%s' not a valid level key" % value)
344            return 0
345
346        if not value:
347            v = value = '100'
348        #import pdb;pdb.set_trace()
349        levels = self._getLevels()
350        if not levels.has_key(value):
351            datastructure.setError(widget_id, "'%s' not a valid level" % v)
352            return 0
353        if self.is_required and not len(v):
354            datastructure.setError(widget_id, "level key required")
355            return 0
356
357        datamodel = datastructure.getDataModel()
358        datamodel[self.fields[0]] = v
359        return 1
360
361    def render(self, mode, datastructure, **kw):
362        """Render in mode from datastructure."""
363        value = datastructure[self.getWidgetId()]
364        levels = self._getLevels()
365        if mode == 'view':
366            return escape(levels.get(value, value))
367        elif mode == 'edit':
368            html_widget_id = self.getHtmlWidgetId()
369            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
370            in_selection = 0
371            vocabulary_items = levels.items()
372            if self.sorted:
373                vocabulary_items.sort(key=operator.itemgetter(0))
374            for k, v in vocabulary_items:
375                kw = {'value': k, 'contents': v}
376                if value == k:
377                    kw['selected'] = 'selected'
378                    in_selection = 1
379                res += renderHtmlTag('option', **kw)
380            if value and not in_selection:
381                kw = {'value': value, 'contents': 'invalid: '+ str(value),
382                      'selected': 'selected'}
383                res += renderHtmlTag('option', **kw)
384            res += '</select>'
385            return res
386        raise RuntimeError('unknown mode %s' % mode)
387
388InitializeClass(WAeUPLevelWidget)
389
390widgetRegistry.register(WAeUPLevelWidget)
391
392###)
393
394class WAeUPVerdictWidget(CPSSelectWidget): ###(
395    """WAeUP Verdict Widget."""
396    meta_type = 'WAeUP Verdict Widget'
397
398    # XXX make a menu for the vocabulary.
399    vocabulary = 'verdicts'
400
401    # Associating the widget label with an input area to improve the widget
402    # accessibility.
403    has_input_area = True
404
405    def _getVerdicts(self,datastructure):
406        voc = getattr(self.portal_vocabularies,self.vocabulary)
407        d = {}
408        for k,v in voc.items():
409            d[k] = v
410        return d
411
412    def validate(self, datastructure, **kw):
413        """Validate datastructure and update datamodel."""
414        widget_id = self.getWidgetId()
415        value = datastructure[widget_id]
416        try:
417            v = str(value)
418        except ValueError:
419            datastructure.setError(widget_id, "'%s' not a valid verdict key" % value)
420            return 0
421        #import pdb;pdb.set_trace()
422        verdicts = self._getVerdicts(datastructure)
423        if not value:
424            v = value = verdicts['N/A']
425        if not verdicts.has_key(value):
426            datastructure.setError(widget_id, "'%s' not a valid verdict key" % v)
427            return 0
428        if self.is_required and not len(v):
429            datastructure.setError(widget_id, "verdict required")
430            return 0
431
432        datamodel = datastructure.getDataModel()
433        datamodel[self.fields[0]] = v
434        return 1
435
436    def render(self, mode, datastructure, **kw):
437        """Render in mode from datastructure."""
438        value = datastructure[self.getWidgetId()]
439        verdicts = self._getVerdicts(datastructure)
440        if mode == 'view':
441            return escape(verdicts.get(value, value))
442        elif mode == 'edit':
443            html_widget_id = self.getHtmlWidgetId()
444            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
445            in_selection = 0
446            vocabulary_items = verdicts.items()
447            if self.sorted:
448                vocabulary_items.sort(key=operator.itemgetter(1))
449            for k, v in vocabulary_items:
450                kw = {'value': k, 'contents': v}
451                if value == k:
452                    kw['selected'] = 'selected'
453                    in_selection = 1
454                res += renderHtmlTag('option', **kw)
455            if value and not in_selection:
456                kw = {'value': value, 'contents': 'invalid: '+ str(value),
457                      'selected': 'selected'}
458                res += renderHtmlTag('option', **kw)
459            res += '</select>'
460            return res
461        raise RuntimeError('unknown mode %s' % mode)
462
463InitializeClass(WAeUPVerdictWidget)
464
465widgetRegistry.register(WAeUPVerdictWidget)
466
467###)
468
469class WAeUPLGAWidget(CPSSelectWidget): ###(
470    """WAeUP LGA Widget."""
471    meta_type = 'WAeUP LGA Widget'
472    _properties = CPSSelectWidget._properties + (
473        {'id': 'state_field', 'type': 'string', 'mode': 'w',
474         'label': 'Name of the state field'},
475         {'id': 'lga_field', 'type': 'string', 'mode': 'w',
476         'label': 'Name of the lga field (without state)'},
477         )
478    state_field = "state"
479    lga_field = "lga"
480
481    # XXX make a menu for the vocabulary.
482    vocabulary = 'local_gov_areas'
483
484    # Associating the widget label with an input area to improve the widget
485    # accessibility.
486    has_input_area = True
487
488    def _getLGAs(self):
489        voc = getattr(self.portal_vocabularies,self.vocabulary)
490        if getattr(self,'_v_states',None) is not None and\
491           getattr(self,'_v_lgas',None) is not None and\
492           getattr(self,'_v_d',None) is not None:
493            return (_v_d,_v_states,_v_lgas)
494        states = []
495        lgas  = []
496        d = {}
497        for k,v in voc.items():
498            parts = v.split(' / ')
499            if len(parts) == 1:
500                state = parts[0].lower()
501                lga = ""
502            elif len(parts) == 2:
503                state = parts[0].lower()
504                lga = "_".join(re.split('\W+',parts[1].lower()))
505            else:
506                continue
507            if state not in states:
508                states.append(state)
509            if lga not in lgas:
510                lgas.append(lga)
511            d[k] = v
512        self._v_d = d
513        self._v_state = state
514        self._v_lga = lga
515        return (d,states,lgas)
516
517    def validate(self, datastructure, **kw):
518        """Validate datastructure and update datamodel."""
519        widget_id = self.getWidgetId()
520        value = datastructure[widget_id]
521        #import pdb;pdb.set_trace()
522        try:
523            v = str(value)
524        except ValueError:
525            datastructure.setError(widget_id, "'%s' not a valid lga key" % value)
526            return 0
527        v = v.lower()
528        combined,states,lgas = self._getLGAs()
529        datamodel = datastructure.getDataModel()
530        if not self.state_field and not self.lga_field:
531            if len(v) == 0 and self.is_required:
532                datastructure.setError(widget_id, "%s required" % widget_id)
533                return 0
534            elif v not in combined.keys():
535                datastructure.setError(widget_id, "'%s' not a valid lga key" % v)
536                return 0
537            datamodel[self.fields[0]] = v
538        else:
539            state = datastructure.get(self.state_field,"").lower()
540            lga = datastructure.get(self.lga_field,"").lower()
541            if widget_id == self.state_field:
542                if state not in states:
543                    datastructure.setError(widget_id, "'%s' not a valid state" % v)
544                    return 0
545            elif widget_id == self.lga_field:
546                if lga not in lgas:
547                    datastructure.setError(widget_id, "'%s' not a valid lga" % v)
548                    return 0
549            if len(state) == 0 or len(lga) == 0:
550                datastructure.setError(widget_id, "state AND lga must be given")
551                return 0
552            datamodel[self.fields[0]] =   state + "_" + lga
553        return 1
554
555    def render(self, mode, datastructure, **kw):
556        """Render in mode from datastructure."""
557        w_id = self
558        value = datastructure[self.getWidgetId()]
559        lgas,x,y = self._getLGAs(datastructure)
560        if mode == 'view':
561            return escape(lgas.get(value, value))
562        elif mode == 'edit':
563            html_widget_id = self.getHtmlWidgetId()
564            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
565            in_selection = 0
566            vocabulary_items = lgas.items()
567            # if self.sorted:
568            #     vocabulary_items.sort(key=operator.itemgetter(1))
569            for k, v in vocabulary_items:
570                kw = {'value': k, 'contents': v}
571                if value == k:
572                    kw['selected'] = 'selected'
573                    in_selection = 1
574                res += renderHtmlTag('option', **kw)
575            if value and not in_selection:
576                kw = {'value': value, 'contents': 'invalid: '+ str(value),
577                      'selected': 'selected'}
578                res += renderHtmlTag('option', **kw)
579            res += '</select>'
580            return res
581        raise RuntimeError('unknown mode %s' % mode)
582
583InitializeClass(WAeUPLGAWidget)
584
585widgetRegistry.register(WAeUPLGAWidget)
586
587###)
588
589class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
590    """ WAeUPReservedRooms Widget"""
591    meta_type = "WAeUPReservedRooms Widget"
592
593    def validate(self, datastructure, **kw):
594        """Validate datastructure and update datamodel."""
595        import re
596        valid = CPSStringWidget.validate(self, datastructure, **kw)
597        if not valid:
598            return 0
599        else:
600            widget_id = self.getWidgetId()
601            value = datastructure[widget_id]
602            err = 0
603            try:
604                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
605                                     if r]
606            except (ValueError,IndexError),msg:
607                err = str(msg)
608            if err:
609                datastructure.setError(widget_id, err)
610            else:
611                datamodel = datastructure.getDataModel()
612                datamodel[self.fields[0]] = value
613            return not err
614
615InitializeClass(WAeUPReservedRoomsWidget)
616
617widgetRegistry.register(WAeUPReservedRoomsWidget)
618###)
619
620class WAeUPIdWidget(CPSStringWidget): ###(
621    """ WAeUPId Widget"""
622    meta_type = "WAeUPId Widget"
623
624    def validate(self, datastructure, **kw):
625        """Validate datastructure and update datamodel."""
626        mode = kw.get('mode','create')
627        valid = CPSStringWidget.validate(self, datastructure, **kw)
628        id_pat_str = r"\S"
629        inv_id_pat = re.compile(r"^%s$" % id_pat_str)
630        if not valid:
631            return 0
632        else:
633            portal_type_query = {'query':['Faculty',
634                                          'Department',
635                                          'Course',
636                                          'Certificate',
637                                          'CertificateCourse',]}
638            widget_id = self.getWidgetId()
639            value = datastructure[widget_id]  #.upper()  is not necessary here because it's also done in waeup_document_create_do
640            err = 0
641            mapping = {}
642            if len(value.split()) > 1:
643                err = 'Invalid Id, Id contains space(s).'
644            elif mode == "create" and\
645                          self.portal_catalog(portal_type=portal_type_query,id=value):
646                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
647                err = 'An ${portal_type} object with the Id ${id} already exists at ${path}.'
648                mapping = {'portal_type': brain.portal_type,
649                           'id': value,
650                           'path': brain.getPath(),
651                           }
652            if err:
653                datastructure.setError(widget_id, err, mapping)
654            else:
655                datamodel = datastructure.getDataModel()
656                datamodel[self.fields[0]] = value
657
658            return not err
659
660InitializeClass(WAeUPIdWidget)
661
662widgetRegistry.register(WAeUPIdWidget)
663
664
665###)
666
667class StudyCourseWidget(CPSStringWidget): ###(
668    """ StudyCourse Widget"""
669    meta_type = "StudyCourse Widget"
670
671    def validate(self, datastructure, **kw):
672        """Validate datastructure and update datamodel."""
673        #from Products.zdb import set_trace
674        #set_trace()
675##        valid = CPSStringWidget.validate(self, datastructure, **kw)
676##        if not valid:
677##            return 0
678        widget_id = self.getWidgetId()
679        value = makeCertificateCode(datastructure[widget_id]).upper()
680        id_pat_str = r"\S"
681        inv_id_pat = re.compile(r"^%s$" % id_pat_str)
682        err = 0
683        if len(value.split()) > 1:
684            err = 'Invalid Id, Id contains space(s).'
685        elif not self.portal_catalog(portal_type='Certificate',id=value):
686            err = 'No such certificate'
687        if err:
688            datastructure.setError(widget_id, err)
689        else:
690            datamodel = datastructure.getDataModel()
691            datamodel[self.fields[0]] = value
692        return not err
693
694InitializeClass(StudyCourseWidget)
695
696widgetRegistry.register(StudyCourseWidget)
697###)
698
699class JambRegNoWidget(CPSStringWidget): ###(
700    """ JambRegNo Widget"""
701    meta_type = "JambRegNo Widget"
702    _properties = CPSStringWidget._properties + (
703        {'id': 'catalog', 'type': 'string', 'mode': 'w',
704         'label': 'Catalog to search'},
705         {'id': 'reference', 'type': 'string', 'mode': 'w',
706         'label': 'Reference Field'},
707         )
708    #catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
709    reference = ""
710    digits = 8
711    digits_str = "N"*digits
712    letters = 2
713    letters_str = "L"*letters
714    def validate(self, datastructure, **kw):
715        """Validate datastructure and update datamodel."""
716        valid = CPSStringWidget.validate(self, datastructure, **kw)
717        reg_no_catalog = getattr(self,self.catalog)
718        widget_id = self.getWidgetId()
719        value = datastructure[widget_id].upper()
720        err = 0
721        #import pdb;pdb.set_trace()
722        if kw.has_key('mode'):
723            mode = kw['mode']
724        else:
725            mode = "edit"
726        if not valid:
727            err = 'Invalid registration number'
728        elif self.reference == '':
729            #s = getStudentByRegNo(self,value)
730            pume = reg_no_catalog(jamb_reg_no = value)
731            if len(pume) < 1:
732                err = 'No student record with this registration number'
733            else:
734                datastructure['pume'] = pume[0]
735        elif mode == 'add':
736            pass
737        elif self.reference != '' and self.catalog == "applicants_catalog":
738            res = reg_no_catalog.searchResults({"%s" % self.reference: value})
739            if len(res) != 1:
740                err = 'No record with this registration number'
741            else:
742                datastructure['record'] = res[0]
743        else:
744            record = datastructure[self.reference]
745            #jamb_reg_no = getattr(record,widget_id)
746            jamb_reg_no = record.Entryregno
747            if jamb_reg_no != value:
748                err = 'Registration number does not match.'
749        if err:
750            datastructure.setError(widget_id, err)
751        else:
752            datamodel = datastructure.getDataModel()
753            datamodel[self.fields[0]] = value
754        return not err
755
756InitializeClass(JambRegNoWidget)
757
758widgetRegistry.register(JambRegNoWidget)
759###)
760
761class SecretWidget(CPSStringWidget): ###(
762    """ Secret Widget"""
763    meta_type = "Secret Widget"
764    _properties = CPSStringWidget._properties + (
765        {'id': 'reference', 'type': 'string', 'mode': 'w',
766         'label': 'Reference Record'},
767         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
768         'label': 'Fields to check'},
769         )
770    reference = "student"
771    matric_no_catalog = 'returning_import'
772    check_fields = ("Firstname", "Middlename","Lastname")
773    def validate(self, datastructure, **kw):
774        """Validate datastructure and update datamodel."""
775        logger = logging.getLogger('Widgets.SecretWidget.validate')
776        valid = CPSStringWidget.validate(self, datastructure, **kw)
777        widget_id = self.getWidgetId()
778        value = datastructure[widget_id].upper()
779        err = 0
780        record = datastructure.get(self.reference,None)
781        #import pdb;pdb.set_trace()
782        if not valid or len(value) < 2:
783            err = 'Invalid string'
784        elif not record or datastructure.errors:
785            err = 0
786        else:
787            found = False
788            cvs = []
789            for field in self.check_fields:
790                cv = getattr(record,field).upper()
791                if len(cv.split()) > 1:
792                    for splited in cv.split():
793                        cvs.append(splited.strip())
794                else:
795                    cvs.append(cv)
796            for cv in cvs:
797                if cv  == value.upper():
798                    found = True
799                    break
800            matric_no = record.matric_no
801            name = " ".join(cvs)
802            if not found:
803                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
804                err = 'No name does match.'
805            else:
806                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
807        if err:
808            datastructure.setError(widget_id, err)
809        else:
810            datamodel = datastructure.getDataModel()
811            datamodel[self.fields[0]] = value
812        return not err
813
814InitializeClass(SecretWidget)
815
816widgetRegistry.register(SecretWidget)
817###)
818
819class WAeUPSexWidget(CPSBooleanWidget): ###(
820    """WAeUP sex widget."""
821    meta_type = 'WAeUP Sex Widget'
822
823    def validate(self, datastructure, **kw):
824        """Validate datastructure and update datamodel."""
825        value = datastructure[self.getWidgetId()]
826
827        if self.render_format not in self.render_formats:
828            self.render_format = 'select'
829
830        female = value in ('F','f','Female','female',"True",True)
831        male = value in ('M','m','Male','male','False',False)
832        if not female and not male:
833            datastructure.setError(self.getWidgetId(),
834                                   "invalid sex %s" % value)
835            return 0
836        elif female:
837            v = True
838        else:
839            v = False
840        datamodel = datastructure.getDataModel()
841        datamodel[self.fields[0]] = v
842        return 1
843
844InitializeClass(WAeUPSexWidget)
845
846widgetRegistry.register(WAeUPSexWidget)
847
848###)
849
850class MatricNoWidget(CPSStringWidget): ###(
851    """ MatricNo Widget"""
852    meta_type = "MatricNo Widget"
853
854    _properties = CPSStringWidget._properties + (
855        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
856         'label': 'Catalog to search for MatricNo'},
857        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
858         'label': 'Results Catalog'},
859         )
860    matric_no_catalog = "" #the catalog to search for matric_no
861    results_catalog = "results_import" #results catalog
862
863    def validate(self, datastructure, **kw):
864        """Validate datastructure and update datamodel."""
865        #import pdb;pdb.set_trace()
866        valid = CPSStringWidget.validate(self, datastructure, **kw)
867        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
868        returning = getattr(self,self.matric_no_catalog)
869        results = getattr(self,self.results_catalog,None)
870        err = 0
871        widget_id = self.getWidgetId()
872        value = datastructure[widget_id]
873        if not valid or not value:
874            err = 'Invalid string'
875            logger.info('Invalid matric_no string %s' % value)
876        else:
877            value = value.upper()
878            datastructure['student'] = None
879            while not err:
880                res = returning(matric_no = value)
881                if len(res) < 1:
882                    logger.info('matric_no %s not found' % value)
883                    err = 'No student with this matriculation number.'
884                    break
885                datastructure['student'] = res[0]
886                if results is not None:
887                    res = results(matric_no = value)
888                    if len(res) < 1:
889                        err = 'No results for this matriculation number'
890                        continue
891                    datastructure['results'] = res
892                break
893        if err:
894            datastructure.setError(widget_id, err)
895        else:
896            datamodel = datastructure.getDataModel()
897            datamodel[self.fields[0]] = value
898        return not err
899
900InitializeClass(MatricNoWidget)
901
902widgetRegistry.register(MatricNoWidget)
903###)
904
905class StudentIdWidget(CPSStringWidget): ###(
906    """ StudentId Widget"""
907    meta_type = "StudentId Widget"
908    def validate(self, datastructure, **kw):
909        """Validate datastructure and update datamodel."""
910        valid = CPSStringWidget.validate(self, datastructure, **kw)
911        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
912        #import pdb;pdb.set_trace()
913        s_cat = self.students_catalog
914        err = 0
915        widget_id = self.getWidgetId()
916        value = datastructure[widget_id]
917        if not valid or not value:
918            err = 'Invalid Id string'
919            logger.info('Invalid id string %s' % value)
920            datastructure['student'] = None
921        else:
922            value = value.upper()
923            res = s_cat(id = value)
924            if not res:
925                logger.info('Student id %s not found' % value)
926                err = 'No student with this Id'
927                datastructure['student'] = None
928            else:
929                datastructure['student'] = res[0]
930        if err:
931            datastructure.setError(widget_id, err)
932        else:
933            datamodel = datastructure.getDataModel()
934            datamodel[self.fields[0]] = value
935        return not err
936
937InitializeClass(StudentIdWidget)
938
939widgetRegistry.register(StudentIdWidget)
940###)
941
942class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
943    """ WAeUPMultilineResults Widget"""
944    meta_type = "WAeUp Multiline Results Widget"
945    _properties = CPSWidget._properties + (
946        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
947         'label': 'Nr of Lines'},
948         )
949    nr_of_lines = 5
950    def prepare(self, datastructure, **kw): ###(
951        """Prepare datastructure from datamodel."""
952        datamodel = datastructure.getDataModel()
953        #import pdb;pdb.set_trace()
954        widget_id = self.getWidgetId()
955        v = datamodel[self.fields[0]]
956        if type(v) is ListType and v:
957            nr_results = len(v)
958        else:
959            v = []
960            nr_results = 0
961        count = 1
962        for s,g in v:
963            wid = "%s%02d"% (widget_id,count)
964            datastructure[wid+'_s'] = s
965            datastructure[wid+'_g'] = g
966            count += 1
967        if nr_results < self.nr_of_lines:
968            for line in range(nr_results,self.nr_of_lines):
969                v.append(('',''))
970                wid = "%s%02d"% (widget_id,line)
971                datastructure[wid+'_s'] = ''
972                datastructure[wid+'_g'] = ''
973        datastructure[widget_id] = v
974        datastructure[widget_id+'_s'] = ''
975        datastructure[widget_id+'_g'] = ''
976    ###)
977
978    def validate(self, datastructure, **kw): ###(
979        """Validate datastructure and update datamodel."""
980        #import pdb;pdb.set_trace()
981        widget_id = self.getWidgetId()
982        err = 0
983        lines = []
984        for line in range(1,30):
985            wid = "%s%02d"% (widget_id,line)
986            if not datastructure.has_key(wid+'_s'):
987                break
988            lines.append((datastructure[wid+'_s'].strip(),
989                         datastructure[wid+'_g'].strip()))
990
991        s = datastructure[widget_id+'_s'].strip()
992        g = datastructure[widget_id+'_g'].strip()
993        if s and g:
994            lines.append((s,g))
995        active = []
996        for s,g in lines:
997            if g != "":
998                active.append((s,g))
999        if err:
1000            datastructure.setError(widget_id, err)
1001        else:
1002            datamodel = datastructure.getDataModel()
1003            datamodel[self.fields[0]] = active
1004        return not err
1005    ###)
1006
1007    def render(self, mode, datastructure, **kw): ###(
1008        """Render in mode from datastructure."""
1009        render_method = 'widget_waeup_multiline_result_render'
1010        meth = getattr(self, render_method, None)
1011        if meth is None:
1012            raise RuntimeError("Unknown Render Method %s for widget type %s"
1013                               % (render_method, self.getId()))
1014        #import pdb;pdb.set_trace()
1015        datamodel = datastructure.getDataModel()
1016        widget_id = self.getWidgetId()
1017        lines = datamodel[self.fields[0]]
1018        if len(lines) < self.nr_of_lines:
1019            for line in range(len(lines),self.nr_of_lines + 1):
1020                lines.append(('',''))
1021        datastructure[widget_id] = lines
1022        datastructure[widget_id+'_s'] = ''
1023        datastructure[widget_id+'_g'] = ''
1024##        count = 1
1025##        for s,g in v:
1026##            wid = "%s%02d"% (widget_id,count)
1027##            count += 1
1028        return meth(mode=mode,
1029                    datastructure=datastructure,
1030                    )
1031    ###)
1032
1033
1034InitializeClass(WAeUPMultilineResultsWidget)
1035widgetRegistry.register(WAeUPMultilineResultsWidget)
1036###)
1037
1038class WAeUPResultsWidget(CPSStringWidget): ###(
1039    """ WAeUPResults Widget"""
1040    meta_type = "WAeUp Results Widget"
1041
1042    def prepare(self, datastructure, **kw): ###(
1043        """Prepare datastructure from datamodel."""
1044        datamodel = datastructure.getDataModel()
1045        v = datamodel[self.fields[0]]
1046        #import pdb;pdb.set_trace()
1047        widget_id = self.getWidgetId()
1048        datastructure[widget_id] = v
1049        datastructure[widget_id+'_s'] = ''
1050        datastructure[widget_id+'_g'] = ''
1051    ###)
1052
1053    def validate(self, datastructure, **kw): ###(
1054        """Validate datastructure and update datamodel."""
1055        #import pdb;pdb.set_trace()
1056        widget_id = self.getWidgetId()
1057        v = datastructure[widget_id]
1058        err = 0
1059        s = datastructure[widget_id+'_s'].strip()
1060        g = datastructure[widget_id+'_g'].strip()
1061        while 1:
1062            if not s and g:
1063                err = "No subject grade for subject"
1064                break
1065            i = 0
1066            done = False
1067            for sv,gv in v:
1068                if sv == s:
1069                    done = True
1070                    if not g:
1071                        v.pop(i)
1072                        break
1073                    v[i] = (s,g)
1074                    break
1075                i += 1
1076            if done:
1077                break
1078            if s and g:
1079                v.append((s,g))
1080            break
1081        if err:
1082            datastructure.setError(widget_id, err)
1083        else:
1084            datamodel = datastructure.getDataModel()
1085            datamodel[self.fields[0]] = v
1086            datastructure[widget_id+'_s'] = s
1087            datastructure[widget_id+'_g'] = g
1088        return not err
1089    ###)
1090
1091    def render(self, mode, datastructure, **kw): ###(
1092        """Render in mode from datastructure."""
1093        render_method = 'widget_waeup_result_render'
1094        meth = getattr(self, render_method, None)
1095        if meth is None:
1096            raise RuntimeError("Unknown Render Method %s for widget type %s"
1097                               % (render_method, self.getId()))
1098        #import pdb;pdb.set_trace()
1099        datamodel = datastructure.getDataModel()
1100        widget_id = self.getWidgetId()
1101        datastructure[widget_id+'_s'] = ''
1102        datastructure[widget_id+'_g'] = ''
1103        return meth(mode=mode,
1104                    datastructure=datastructure,
1105                    )
1106    ###)
1107
1108
1109InitializeClass(WAeUPResultsWidget)
1110widgetRegistry.register(WAeUPResultsWidget)
1111###)
1112
1113class ScratchCardPin: ###(
1114    """the ScratchCardPin"""
1115    def __init__(self,prefix,batch_no,number):
1116        if not batch_no and not number:
1117            s = prefix
1118            if len(s) > 3:
1119                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
1120            else:
1121                prefix,batch_no,number = s,'',''
1122        self.p = prefix
1123        self.b = batch_no
1124        self.n = number
1125
1126    def __str__(self):
1127        return "%s-%s-%s" % (self.p,self.b,self.n)
1128
1129    def __repr__(self):
1130        return "%s%s%s" % (self.p,self.b,self.n)
1131###)
1132
1133class ScratchcardPinWidget(CPSStringWidget): ###(
1134    """ ScratchcardPin Widget"""
1135    meta_type = "Scratchcard Pin Widget"
1136    _properties = CPSWidget._properties + (
1137        {'id': 'prefix', 'type': 'string', 'mode': 'w',
1138         'label': 'Prefix'},
1139         {'id': 'reference', 'type': 'string', 'mode': 'w',
1140         'label': 'Reference Field'},
1141        )
1142    prefix = ''
1143    reference = ''
1144    def prepare(self, datastructure, **kw): ###(
1145        """Prepare datastructure from datamodel."""
1146        datamodel = datastructure.getDataModel()
1147        v = datamodel[self.fields[0]]
1148        widget_id = self.getWidgetId()
1149        if v and type(v) is StringType:
1150            try:
1151                p,b,n = v.split('-')
1152                v = ScratchCardPin(p,b,n)
1153            except ValueError:
1154                v = ScratchCardPin(v,'','')
1155        if v:
1156            p = '%s' % v.p
1157            b = '%s' % v.b
1158            n = '%s' % v.n
1159        else:
1160            p = self.prefix
1161            if p.startswith('@'):
1162                p = getattr(self,self.prefix[1:])()
1163            b = n = ''
1164            v = ScratchCardPin(p,b,n)
1165        datastructure[widget_id] = v
1166        datastructure[widget_id+'_p'] = p
1167        datastructure[widget_id+'_b'] = b
1168        datastructure[widget_id+'_n'] = n
1169    ###)
1170
1171    def validate(self, datastructure, **kw): ###(
1172        """Validate datastructure and update datamodel."""
1173        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
1174        widget_id = self.getWidgetId()
1175        v = datastructure[widget_id]
1176        #import pdb;pdb.set_trace()
1177        err = 0
1178        mapping = {}
1179        prefix= self.prefix
1180        if prefix.startswith('@'):
1181            prefix= getattr(self,self.prefix[1:])()
1182        b = datastructure[widget_id+'_b'].strip()
1183        n = datastructure[widget_id+'_n'].strip()
1184        pins = self.portal_pins
1185        pin = "%(prefix)s%(b)s%(n)s" % vars()
1186        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
1187        do = 1
1188        s_id = str(self.portal_membership.getAuthenticatedMember())
1189        if self.isStaff():
1190            do = 0
1191            err ='You are not a Student. PIN neither checked nor used.'
1192            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
1193        elif len(b) > 1 and b.find('-') > -1:
1194            do = 0
1195            err = 'PIN must not contain "-"'
1196            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1197        elif n.find('-') > -1:
1198            do = 0
1199            err = 'PIN must not contain "-"'
1200            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
1201        elif len(n) != 10:
1202            do = 0
1203            err = 'Invalid PIN length'
1204            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
1205        elif self.reference == "":
1206            ref = s_id
1207        else:
1208            ref = datastructure[self.reference]
1209            if datastructure.errors:
1210                do = 0
1211                datastructure.setError(widget_id, 'PIN neither checked nor used.')
1212                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
1213        while do:
1214            ok = pins.searchAndSetRecord(pin,ref,prefix)
1215            if ok < -2 or ok > 2:
1216                err = 'Unknown error, please report!'
1217                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
1218                break
1219            elif ok == -2:
1220                err = 'Service already is activated but with a different PIN.'
1221                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
1222                break
1223            elif ok == -1:
1224                err = 'Invalid PIN'
1225                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
1226                break
1227            if ok == 0:
1228                err = 'PIN already used'
1229                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
1230                break
1231            if ok >= 1:
1232                #import pdb;pdb.set_trace()
1233                if self.isStudent():
1234                    if self.reference == "jamb_reg_no":
1235                        err = "You are already logged in."
1236                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
1237                        break
1238                    if ok == 1:
1239                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1240                    else:
1241                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
1242                    break
1243                else:
1244                    student = getStudentByRegNo(self,ref)
1245                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
1246                if student is None:
1247                    err = "Student not found"
1248                    s_logger.info('%s not found in admission list' % (ref))
1249                    break
1250                s_id = student.getId()
1251                if ok == 2:
1252                    if self.reference == "jamb_reg_no":
1253                        if hasattr(self.portal_directories.students,s_id):
1254                            err = "Please login with your Student Id ${id} and 10-digit PIN."
1255                            mapping = {'id': s_id}
1256                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1257                            break
1258                        else:
1259                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
1260                    else:
1261                        err = "Unknown error"
1262                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
1263                        break
1264                try:
1265                    student.getContent().makeStudentMember(s_id,password=pin[4:])
1266                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
1267                except:
1268                    err = "Please login with your Student Id ${id} and 10-digit PIN."
1269                    mapping = {'id': s_id}
1270                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
1271                    break
1272            break
1273        if err:
1274            datastructure.setError(widget_id, err,mapping)
1275        else:
1276            datamodel = datastructure.getDataModel()
1277            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1278            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1279            datastructure[widget_id+'_p'] = prefix
1280            datastructure[widget_id+'_b'] = b
1281            datastructure[widget_id+'_n'] = n
1282            datastructure['s_id'] = s_id
1283        return not err
1284
1285###)
1286
1287    def render(self, mode, datastructure, **kw): ###(
1288        """Render in mode from datastructure."""
1289        render_method = 'widget_scratch_card_pin_render'
1290        meth = getattr(self, render_method, None)
1291        if meth is None:
1292            raise RuntimeError("Unknown Render Method %s for widget type %s"
1293                               % (render_method, self.getId()))
1294
1295        # XXX AT: datastructure has to be set again here, in case we're in edit
1296        # or create mode, because a default value has to be provided.
1297        #import pdb;pdb.set_trace()
1298        datamodel = datastructure.getDataModel()
1299        v = datamodel[self.fields[0]]
1300        if v and type(v) is StringType:
1301            try:
1302                p,b,n = v.split('-')
1303                v = ScratchCardPin(p,b,n)
1304            except ValueError:
1305                v = ScratchCardPin(self.prefix,'XXX',v)
1306                pass
1307        if v:
1308            prefix= '%s' % v.p
1309            b = '%s' % v.b
1310            n = '%s' % v.n
1311        else:
1312            prefix= self.prefix
1313            if prefix.startswith('@'):
1314                prefix= getattr(self,self.prefix[1:])()
1315            b = n = ''
1316            v = ScratchCardPin(prefix,b,n)
1317        widget_id = self.getWidgetId()
1318        datastructure[widget_id] = v
1319        datastructure[widget_id+'_p'] = prefix
1320        datastructure[widget_id+'_b'] = b
1321        datastructure[widget_id+'_n'] = n
1322        return meth(mode=mode,
1323                    datastructure=datastructure,
1324                    )
1325    ###)
1326
1327InitializeClass(ScratchcardPinWidget)
1328widgetRegistry.register(ScratchcardPinWidget)
1329###)
1330
1331class PumePinWidget(ScratchcardPinWidget): ###(
1332    """ Pume Pin Widget"""
1333    meta_type = "Pume Pin Widget"
1334    catalog = "applicants_catalog"
1335    reference = ''
1336
1337    def prepare(self, datastructure, **kw): ###(
1338        """Prepare datastructure from datamodel."""
1339        datamodel = datastructure.getDataModel()
1340        #import pdb;pdb.set_trace()
1341        v = datamodel[self.fields[0]]
1342        widget_id = self.getWidgetId()
1343        if v and type(v) is StringType:
1344            try:
1345                p,b,n = v.split('-')
1346                v = ScratchCardPin(p,b,n)
1347            except ValueError:
1348                v = ScratchCardPin(v,'','')
1349        if v:
1350            p = '%s' % v.p
1351            b = '%s' % v.b
1352            n = '%s' % v.n
1353        else:
1354            p = self.prefix
1355            if p.startswith('@'):
1356                p = getattr(self,self.prefix[1:])()
1357            b = n = ''
1358            v = ScratchCardPin(p,b,n)
1359        datastructure[widget_id] = v
1360        datastructure[widget_id+'_p'] = p
1361        datastructure[widget_id+'_b'] = b
1362        datastructure[widget_id+'_n'] = n
1363    ###)
1364
1365    def validate(self, datastructure, **kw): ###(
1366        """Validate datastructure and update datamodel."""
1367        #import pdb;pdb.set_trace()
1368        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
1369        widget_id = self.getWidgetId()
1370        v = datastructure[widget_id]
1371        err = 0
1372        mapping = {}
1373        prefix= self.prefix
1374        if prefix.startswith('@'):
1375            prefix= getattr(self,self.prefix[1:])()
1376        b = datastructure[widget_id+'_b'].strip()
1377        n = datastructure[widget_id+'_n'].strip()
1378        pins = self.portal_pins
1379        pin = "%(prefix)s%(b)s%(n)s" % vars()
1380        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
1381        member_id = str(self.portal_membership.getAuthenticatedMember())
1382        do = 1
1383        if self.isStaff():
1384            do = 0
1385            err ='You are logged in, please log out. PIN neither checked nor used.'
1386            s_logger.info('%s tried to use scratch card %s' % (member_id,pin_str))
1387        elif self.isStudent():
1388            do = 0
1389            ref = datastructure[self.reference]
1390            err ='You are logged in, please log out. PIN neither checked nor used.'
1391            s_logger.info('%s/%s applied for screening test with PIN %s' % (member_id,ref,pin_str))
1392        elif len(b) > 1 and b.find('-') > -1:
1393            do = 0
1394            err = 'PIN must not contain "-"'
1395            s_logger.info('%s entered invalid PIN  containing "-"' % (member_id))
1396        elif n.find('-') > -1:
1397            do = 0
1398            err = 'PIN must not contain "-"'
1399            s_logger.info('%s entered invalid PIN  containing "-"' % (member_id))
1400        elif len(n) != 10:
1401            do = 0
1402            err = 'Invalid PIN length'
1403            s_logger.info('%s entered invalid PIN with length %d' % (member_id,len(n)))
1404        elif self.reference == "":
1405            ref = n
1406        else:
1407            ref = datastructure[self.reference]
1408            if datastructure.errors:
1409                do = 0
1410                datastructure.setError(widget_id, 'PIN neither checked nor used.')
1411                s_logger.info('%s/%s entered wrong data together with PIN %s' % (member_id,ref,pin_str))
1412        while do:
1413            ok = pins.searchAndSetRecord(pin,ref,prefix)
1414            if ok < -2 or ok > 2:
1415                err = 'Unknown error, please report!'
1416                s_logger.info('%s/%s caused unknown error with PIN %s' % (member_id,ref,pin_str))
1417                break
1418            elif ok == -2:
1419                err = 'Service is already activated but with a different PIN.'
1420                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (member_id,ref,pin_str))
1421                break
1422            elif ok == -1:
1423                err = 'Invalid PIN'
1424                s_logger.info('%s/%s entered invalid PIN %s' % (member_id,ref,pin_str))
1425                break
1426            if ok == 0:
1427                err = 'PIN already used'
1428                s_logger.info('%s/%s entered used PIN %s' % (member_id,ref,pin_str))
1429                break
1430            if ok >= 1:
1431                #screening_type = self.REQUEST.form.get('screening_type','unknown')
1432                #screening_type = datastructure['screening_type']
1433                if self.REQUEST.traverse_subpath:
1434                    screening_type_request = self.REQUEST.traverse_subpath[0]
1435                else:
1436                    screening_type_request = 'manage'
1437
1438                if datastructure.has_key('record'):
1439                    applicant = datastructure['record']
1440                    if applicant.screening_type != screening_type_request\
1441                          and screening_type_request != 'manage':
1442                        err = "You are using the wrong access form!"
1443                        s_logger.info('%s tried to use %s application form but has applied for %s' % (ref,screening_type_request,applicant.screening_type))
1444                        break
1445                    if not applicant.pin:
1446                        s_logger.info('%s successfully used PIN %s' % (ref,pin_str))
1447                        d = {}
1448                        d['reg_no'] = applicant.reg_no
1449                        d['pin'] = pin_str
1450                        #d['screening_type'] = screening_type
1451                        #d['status'] = 'entered'
1452                        getattr(self,self.catalog).modifyRecord(**d)
1453                    elif applicant.pin != pin_str:
1454                        s_logger.info('%s/%s tried to enter application record with different PIN %s' % (member_id,ref,pin_str))
1455                    elif applicant.pin == pin_str:
1456                        s_logger.info('%s/%s repeatedly entered application record with PIN %s' % (member_id,ref,pin_str))
1457                else:
1458                    datastructure['reg_no'] = ref
1459                    res = self.applicants_catalog(reg_no = ref)
1460                    if not res:
1461                        s_logger.info('%s successfully used PIN %s' % (ref,pin_str))
1462                        d = {}
1463                        d['reg_no'] = ref
1464                        d['pin'] = pin_str
1465                        d['status'] = 'entered'
1466                        d['screening_type'] = screening_type_request
1467                        self.applicants_catalog.addRecord(**d)
1468                    else:
1469                        s_logger.info('%s/%s repeatedly entered application record with PIN %s' % (ref,ref,pin_str))
1470            break
1471        if err:
1472            datastructure.setError(widget_id, err,mapping)
1473        else:
1474            datamodel = datastructure.getDataModel()
1475            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1476            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1477            datastructure[widget_id+'_p'] = prefix
1478            datastructure[widget_id+'_b'] = b
1479            datastructure[widget_id+'_n'] = n
1480        return not err
1481    ###)
1482
1483    def render(self, mode, datastructure, **kw): ###(
1484        """Render in mode from datastructure."""
1485        render_method = 'widget_scratch_card_pin_render'
1486        meth = getattr(self, render_method, None)
1487        if meth is None:
1488            raise RuntimeError("Unknown Render Method %s for widget type %s"
1489                               % (render_method, self.getId()))
1490
1491        # XXX AT: datastructure has to be set again here, in case we're in edit
1492        # or create mode, because a default value has to be provided.
1493        #import pdb;pdb.set_trace()
1494        datamodel = datastructure.getDataModel()
1495        v = datamodel[self.fields[0]]
1496        #import pdb;pdb.set_trace()
1497        if v and type(v) is StringType:
1498            try:
1499                p,b,n = v.split('-')
1500                v = ScratchCardPin(p,b,n)
1501            except ValueError:
1502                v = ScratchCardPin(self.prefix,'XXX',v)
1503                pass
1504        if v:
1505            prefix= '%s' % v.p
1506            b = '%s' % v.b
1507            n = '%s' % v.n
1508        else:
1509            prefix= self.prefix
1510            if prefix.startswith('@'):
1511                prefix= getattr(self,self.prefix[1:])()
1512            b = n = ''
1513            v = ScratchCardPin(prefix,b,n)
1514        widget_id = self.getWidgetId()
1515        datastructure[widget_id] = v
1516        datastructure[widget_id+'_p'] = prefix
1517        datastructure[widget_id+'_b'] = b
1518        datastructure[widget_id+'_n'] = n
1519        return meth(mode=mode,
1520                    datastructure=datastructure,
1521                    )
1522    ###)
1523
1524InitializeClass(PumePinWidget)
1525widgetRegistry.register(PumePinWidget)
1526###)
1527
1528class WAeUPImageWidget(CPSImageWidget): ###(
1529    """Photo widget."""
1530    meta_type = 'WAeUP Image Widget'
1531
1532    def render(self, mode, datastructure, **kw):
1533        render_method = 'widget_waeup_image_render'
1534        meth = getattr(self, render_method, None)
1535        if meth is None:
1536            raise RuntimeError("Unknown Render Method %s for widget type %s"
1537                               % (render_method, self.getId()))
1538        img_info = self.getImageInfo(datastructure)
1539        return meth(mode=mode, datastructure=datastructure, **img_info)
1540
1541InitializeClass(WAeUPImageWidget)
1542
1543widgetRegistry.register(WAeUPImageWidget)
1544###)
1545
1546class ApplicationImageWidget(CPSImageWidget): ###(
1547    """Image widget with filesystem storage."""
1548    meta_type = 'Application Image Widget'
1549    _properties = CPSImageWidget._properties +\
1550    (
1551     {'id': 'path', 'type': 'string', 'mode': 'w',
1552      'label': 'Relative Path'},
1553     {'id': 'id_field', 'type': 'string', 'mode': 'w',
1554      'label': 'Field to build the id'},
1555    )
1556    path = "images"
1557    storage_path = "%s/import/%s" % (i_home,path)
1558    id_field = "reg_no"
1559
1560    def getImageInfo(self, datastructure): ###(
1561        """Get the file info from the datastructure."""
1562        widget_id = self.getWidgetId()
1563        if  datastructure.has_key(widget_id):
1564            fileupload = datastructure[widget_id]
1565            dm = datastructure.getDataModel()
1566            field_id = self.fields[0]
1567            screening_type = datastructure.get('screening_type')
1568            current_filename = "%s_%s.jpg" % (datastructure[self.id_field],
1569                                            field_id,)
1570            base_path = os.path.join(screening_type,current_filename)
1571            content_url = os.path.join('viewimage',self.path,base_path)
1572            file_path = os.path.join(self.storage_path,base_path)
1573            #import pdb; pdb.set_trace()
1574        else:
1575            file_path = "XXX"
1576        # read the file from the filesystem
1577        if not os.path.exists(file_path):
1578            height = -1
1579            width = -1
1580            empty_file = True
1581            session_file = False
1582            current_filename = ''
1583            content_url = ''
1584            size = 0
1585            mimetype = ''
1586            last_modified = ''
1587            height = ''
1588            width = ''
1589
1590        else:
1591            image = open(file_path)
1592            from OFS.Image import getImageInfo as getImageInfoOFS
1593            image.seek(0)
1594            data = image.read(2000)
1595            size = len(data)
1596            empty_file = size == 0
1597            session_file = False
1598            last_modified = ''
1599            image.close()
1600            mimetype, width, height = getImageInfoOFS(data)
1601
1602            if width < 0:
1603                width = None
1604            if height < 0:
1605                height = None
1606
1607            if (self.allow_resize
1608                and height is not None
1609                and width  is not None):
1610                z_w = z_h = 1
1611                h = int(self.display_height)
1612                w = int(self.display_width)
1613                if w and h:
1614                    if w < width:
1615                        z_w = w / float(width)
1616                    if h < height:
1617                        z_h = h / float(height)
1618                    zoom = min(z_w, z_h)
1619                    width = int(zoom * width)
1620                    height = int(zoom * height)
1621                #import pdb;pdb.set_trace()
1622        image_info = {
1623            'empty_file': empty_file,
1624            'session_file': session_file,
1625            'current_filename': current_filename,
1626            'size': size,
1627            'last_modified': last_modified,
1628            'content_url': content_url,
1629            'mimetype': mimetype,
1630            }
1631        title = image_info['current_filename']
1632        alt = title or ''
1633        #height = int(self.display_height)
1634        #width = int(self.display_width)
1635        if height is None or width is None:
1636            tag = renderHtmlTag('img', src=image_info['content_url'],
1637                                alt=alt, title=title)
1638        else:
1639            tag = renderHtmlTag('img', src=image_info['content_url'],
1640                                width=str(width), height=str(height),
1641                                alt=alt, title=title)
1642
1643        image_info['height'] = height
1644        image_info['width'] = width
1645        image_info['image_tag'] = tag
1646        return image_info
1647    ###)
1648
1649    def checkFileName(self, filename, mimetype):
1650        return '', {}
1651        if mimetype and mimetype.startswith('image'):
1652            return '', {}
1653        return 'cpsschemas_err_image', {}
1654
1655    def prepare(self, datastructure, **kw): ###(
1656        """Prepare datastructure from datamodel."""
1657        datamodel = datastructure.getDataModel()
1658        widget_id = self.getWidgetId()
1659        file_name = datamodel[self.fields[0]]
1660        #import pdb; pdb.set_trace()
1661        if self.allow_resize:
1662            datastructure[self.getWidgetId() + '_resize'] = ''
1663        screening_type = datamodel.get('screening_type',None)
1664        if not screening_type:
1665            screening_type = self.REQUEST.form.get('screening_type','pume')
1666        datastructure["screening_type"] = screening_type
1667        datastructure[widget_id] = file_name
1668        datastructure[widget_id + '_choice'] = 'change'
1669        title = 'Passport Foto'
1670        datastructure[widget_id + '_filename'] = title
1671    ###)
1672
1673    def validate(self, datastructure, **kw): ###(
1674        """Update datamodel from user data in datastructure.
1675        """
1676        logger = logging.getLogger('Widgets.ApplicationImageWidget.validate')
1677        datamodel = datastructure.getDataModel()
1678        field_id = self.fields[0]
1679        widget_id = self.getWidgetId()
1680        store = False
1681        fileupload = None
1682        mimetype = None
1683        old_file = datamodel[field_id]
1684        # if old_file is not None:
1685        #     old_filename = old_file.title
1686        # else:
1687        #     old_filename = ''
1688        choice = datastructure[widget_id+'_choice']
1689        fileupload = datastructure[widget_id]
1690        is_upload = isinstance(fileupload, FileUpload)
1691        #import pdb; pdb.set_trace()
1692        if not is_upload and not datamodel[field_id]:
1693            if self.is_required:
1694                return self.validateError('Picture upload required', {},
1695                                          datastructure)
1696        if choice == 'delete':
1697            if self.is_required:
1698                return self.validateError('cpsschemas_err_required', {},
1699                                          datastructure)
1700            datamodel[field_id] = None
1701        elif choice == 'keep':
1702            fileupload = datastructure[widget_id]
1703            if isinstance(fileupload, PersistableFileUpload):
1704                # Keeping something from the session means we
1705                # actually want to store it.
1706                store = True
1707            # else:
1708            #     # Nothing to change, don't pollute datastructure
1709            #     # with something costly already stored, which therefore
1710            #     # doesn't need to be kept in the session.
1711            #     self.unprepare(datastructure)
1712        elif choice == 'change' and is_upload:
1713            if not fileupload:
1714                return self.validateError('cpsschemas_err_file_empty', {},
1715                                          datastructure)
1716            if not isinstance(fileupload, FileUpload):
1717                return self.validateError('cpsschemas_err_file', {},
1718                                          datastructure)
1719            fileupload.seek(0, 2) # end of file
1720            size = fileupload.tell()
1721            if not size:
1722                return self.validateError('cpsschemas_err_file_empty', {},
1723                                          datastructure)
1724            if self.size_max and size > self.size_max:
1725                max_size_str = self.getHumanReadableSize(self.size_max)
1726                err = 'This file is too big, the allowed max size is ${max_size}'
1727                logger.info('%s tried to upload picture with size %dk' %(datastructure['reg_no'],int(size)/1000) )
1728                err_mapping = {'max_size': max_size_str}
1729                return self.validateError(err, err_mapping, datastructure)
1730            store = True
1731
1732
1733        # Find filename
1734        if is_upload and store:
1735            ext ='jpg'
1736            screening_type = datastructure.get('screening_type')
1737            filename = "%s_%s.%s" % (datastructure[self.id_field],
1738                                     self.getWidgetId(),
1739                                     ext)
1740            datamodel[field_id] = filename
1741            registry = getToolByName(self, 'mimetypes_registry')
1742            mimetype = registry.lookupExtension(filename.lower())
1743            if mimetype is not None:
1744                mimetype = str(mimetype) # normalize
1745            file = self.makeFile(filename, fileupload, datastructure)
1746            # Fixup mimetype
1747            if mimetype and file.content_type != mimetype:
1748                file.content_type = mimetype
1749            # Store the file in the filesystem
1750            #import pdb;pdb.set_trace()
1751            base_path = os.path.join(self.storage_path, screening_type)
1752            if not os.path.exists(base_path):
1753                os.mkdir(base_path)
1754            full_path = os.path.join(base_path, filename)
1755            pict = open(full_path,"w")
1756            fileupload.seek(0)
1757            pict.write(fileupload.read())
1758            pict.close()
1759
1760
1761        return True
1762
1763###)
1764
1765    def render(self, mode, datastructure, **kw): ###(
1766        render_method = 'widget_passport_render'
1767        meth = getattr(self, render_method, None)
1768        if meth is None:
1769            raise RuntimeError("Unknown Render Method %s for widget type %s"
1770                               % (render_method, self.getId()))
1771        img_info = self.getImageInfo(datastructure)
1772        return meth(mode=mode, datastructure=datastructure, **img_info)
1773    ###)
1774
1775InitializeClass(ApplicationImageWidget)
1776
1777widgetRegistry.register(ApplicationImageWidget)
1778###)
1779
1780class FileImageWidget(CPSImageWidget): ###(
1781    """Image widget with filesystem storage."""
1782    meta_type = 'File Image Widget'
1783    _properties = CPSImageWidget._properties +\
1784    (
1785     {'id': 'path', 'type': 'string', 'mode': 'w',
1786      'label': 'Relative Path'},
1787     {'id': 'id_field', 'type': 'string', 'mode': 'w',
1788      'label': 'Field to build the id'},
1789     {'id': 'show_image', 'type': 'boolean', 'mode': 'w',
1790      'label': 'Show Image'},
1791    )
1792    path = "images"
1793    storage_path = "%s/%s" % (i_home,path)
1794    id_field = ""
1795    show_image = False
1796
1797    def getStorageImageInfo(self,field_id):
1798        info = {}
1799        if self.id_field == "":
1800            student_id = self.getStudentId()
1801        else:
1802            student_id = datastructure[self.id_field]
1803        student_path = os.path.join(self.storage_path,
1804                                    student_id)
1805        image_name = ''
1806        content_url = ''
1807        current_filename = ''
1808        if os.path.exists(student_path):
1809            for name in os.listdir(student_path):
1810                if name.startswith(field_id):
1811                    image_name = name
1812                    break
1813        if image_name:
1814            info['image_name'] = image_name
1815            info['content_url'] = os.path.join(self.portal_url(),
1816                                   "viewimage",
1817                                   self.path,
1818                                   student_id,
1819                                   image_name,
1820                                   )
1821            info['current_filename'] = os.path.join(student_id,
1822                                                    image_name)
1823            info['file_path'] = os.path.join(self.storage_path,
1824                                             info['current_filename'])
1825        return info
1826
1827    def getImageInfo(self, datastructure): ###(
1828        """Get the file info from the datastructure."""
1829        widget_id = self.getWidgetId()
1830        if  datastructure.has_key(widget_id):
1831            fileupload = datastructure[widget_id]
1832            dm = datastructure.getDataModel()
1833            field_id = self.fields[0]
1834            info = self.getStorageImageInfo(field_id)
1835        else:
1836            file_path = "XXX"
1837            title = ""
1838        # read the file from the filesystem
1839        #import pdb; pdb.set_trace()
1840        #if not os.path.exists(file_path):
1841        if not info:
1842            title = ""
1843            height = -1
1844            width = -1
1845            empty_file = True
1846            session_file = False
1847            current_filename = ''
1848            content_url = ''
1849            size = 0
1850            mimetype = ''
1851            last_modified = ''
1852            height = ''
1853            width = ''
1854        else:
1855            title = info['image_name']
1856            current_filename = info['current_filename']
1857            content_url = info['content_url']
1858            image = open(info['file_path'])
1859            from OFS.Image import getImageInfo as getImageInfoOFS
1860            image.seek(0)
1861            data = image.read(2000)
1862            size = len(data)
1863            empty_file = size == 0
1864            session_file = False
1865            last_modified = ''
1866            image.close()
1867            mimetype, width, height = getImageInfoOFS(data)
1868            registry = getToolByName(self, 'mimetypes_registry')
1869            mimetype = (registry.lookupExtension(current_filename.lower()) or
1870                        registry.lookupExtension('file.bin'))
1871            if width < 0:
1872                width = None
1873            if height < 0:
1874                height = None
1875
1876            if (self.allow_resize
1877                and height is not None
1878                and width  is not None):
1879                z_w = z_h = 1
1880                h = int(self.display_height)
1881                w = int(self.display_width)
1882                if w and h:
1883                    if w < width:
1884                        z_w = w / float(width)
1885                    if h < height:
1886                        z_h = h / float(height)
1887                    zoom = min(z_w, z_h)
1888                    width = int(zoom * width)
1889                    height = int(zoom * height)
1890                #import pdb;pdb.set_trace()
1891        image_info = {
1892            'empty_file': empty_file,
1893            'session_file': session_file,
1894            'current_filename': title,
1895            'size': size,
1896            'last_modified': last_modified,
1897            'content_url': content_url,
1898            'mimetype': mimetype,
1899            }
1900        alt = title or ''
1901        #height = int(self.display_height)
1902        #width = int(self.display_width)
1903        if height is None or width is None:
1904            tag = renderHtmlTag('img', src=image_info['content_url'],
1905                                alt=alt, title=title)
1906        else:
1907            tag = renderHtmlTag('img', src=image_info['content_url'],
1908                                width=str(width), height=str(height),
1909                                alt=alt, title=title)
1910
1911        image_info['height'] = height
1912        image_info['width'] = width
1913        image_info['image_tag'] = tag
1914        image_info['show_image'] = self.show_image
1915        return image_info
1916    ###)
1917
1918    # def checkFileName(self, filename, mimetype):
1919    #     return '', {}
1920    #     if mimetype and mimetype.startswith('image'):
1921    #         return '', {}
1922    #     return 'cpsschemas_err_image', {}
1923
1924    def prepare(self, datastructure, **kw): ###(
1925        """Prepare datastructure from datamodel."""
1926        datamodel = datastructure.getDataModel()
1927        widget_id = self.getWidgetId()
1928        file_name = datamodel[self.fields[0]]
1929        if self.id_field == "":
1930            student_id = self.getStudentId()
1931        else:
1932            student_id = datastructure[self.id_field]
1933        if student_id is not None:
1934            student_path = os.path.join(self.storage_path,student_id)
1935            if not os.path.exists(student_path):
1936                self.waeup_tool.moveImagesToFS(student_id)
1937        if self.allow_resize:
1938            datastructure[self.getWidgetId() + '_resize'] = ''
1939        datastructure[widget_id] = file_name
1940        datastructure[widget_id + '_choice'] = 'change'
1941        title = 'Passport Foto'
1942        datastructure[widget_id + '_filename'] = title
1943    ###)
1944
1945    def validate(self, datastructure, **kw): ###(
1946        """Update datamodel from user data in datastructure.
1947        """
1948        logger = logging.getLogger('Widgets.FileImageWidget.validate')
1949        datamodel = datastructure.getDataModel()
1950        field_id = self.fields[0]
1951        widget_id = self.getWidgetId()
1952        store = False
1953        fileupload = None
1954        mimetype = None
1955        old_file = datamodel[field_id]
1956        choice = datastructure[widget_id+'_choice']
1957        fileupload = datastructure[widget_id]
1958        is_upload = isinstance(fileupload, FileUpload)
1959        #import pdb; pdb.set_trace()
1960        if not is_upload and not datamodel[field_id]:
1961            if self.is_required:
1962                return self.validateError('Picture upload required', {},
1963                                          datastructure)
1964        if self.id_field == "":
1965            student_id = self.getStudentId()
1966        else:
1967            student_id = datastructure[self.id_field]
1968        if choice == 'delete':
1969            if self.is_required:
1970                return self.validateError('cpsschemas_err_required', {},
1971                                          datastructure)
1972            info= self.getStorageImageInfo(field_id)
1973            # Remove the file in the filesystem
1974            if info:
1975                os.remove(info['file_path'])
1976            datamodel[field_id] = None
1977        elif choice == 'keep':
1978            fileupload = datastructure[widget_id]
1979            if isinstance(fileupload, PersistableFileUpload):
1980                # Keeping something from the session means we
1981                # actually want to store it.
1982                store = True
1983            # else:
1984            #     # Nothing to change, don't pollute datastructure
1985            #     # with something costly already stored, which therefore
1986            #     # doesn't need to be kept in the session.
1987            #     self.unprepare(datastructure)
1988        elif choice == 'change' and is_upload:
1989            if not fileupload:
1990                return self.validateError('cpsschemas_err_file_empty', {},
1991                                          datastructure)
1992            if not isinstance(fileupload, FileUpload):
1993                return self.validateError('cpsschemas_err_file', {},
1994                                          datastructure)
1995            fileupload.seek(0, 2) # end of file
1996            size = fileupload.tell()
1997            if not size:
1998                return self.validateError('cpsschemas_err_file_empty', {},
1999                                          datastructure)
2000            if self.size_max and size > self.size_max:
2001                max_size_str = self.getHumanReadableSize(self.size_max)
2002                err = 'This file is too big, the allowed max size is ${max_size}'
2003                member_id = str(self.portal_membership.getAuthenticatedMember())
2004                logger.info('%s tried to upload picture with size %dk' %(member_id,int(size)/1000) )
2005                err_mapping = {'max_size': max_size_str}
2006                return self.validateError(err, err_mapping, datastructure)
2007            store = True
2008
2009
2010        # Find filename
2011        if is_upload and store:
2012            filename = cookId('', '', fileupload)[0].strip()
2013            base,ext = os.path.splitext(filename)
2014            filename = "%s_%s%s" % (field_id,
2015                                    student_id,
2016                                    ext)
2017            datamodel[field_id] = filename
2018            registry = getToolByName(self, 'mimetypes_registry')
2019            mimetype = registry.lookupExtension(filename.lower())
2020            if mimetype is not None:
2021                mimetype = str(mimetype) # normalize
2022            file = self.makeFile(filename, fileupload, datastructure)
2023            # Fixup mimetype
2024            if mimetype and file.content_type != mimetype:
2025                file.content_type = mimetype
2026            # Store the file in the filesystem
2027            student_path = os.path.join(self.storage_path,student_id)
2028            if not os.path.exists(student_path):
2029                os.mkdir(student_path)
2030            full_path = os.path.join(student_path, filename)
2031            pict = open(full_path,"w")
2032            #fileupload.seek(0)
2033            #import pdb; pdb.set_trace()
2034            pict.write(str(file.data))
2035            pict.close()
2036        return True
2037    ###)
2038
2039    def render(self, mode, datastructure, **kw): ###(
2040        render_method = 'widget_image_render'
2041        meth = getattr(self, render_method, None)
2042        #import pdb;pdb.set_trace()
2043        if meth is None:
2044            raise RuntimeError("Unknown Render Method %s for widget type %s"
2045                               % (render_method, self.getId()))
2046        img_info = self.getImageInfo(datastructure)
2047        return meth(mode=mode, datastructure=datastructure, **img_info)
2048    ###)
2049
2050InitializeClass(FileImageWidget)
2051
2052widgetRegistry.register(FileImageWidget)
2053###)
2054
2055###########
2056
Note: See TracBrowser for help on using the repository browser.