source: WAeUP_SRP/base/Widgets.py @ 2377

Last change on this file since 2377 was 2358, checked in by Henrik Bettermann, 17 years ago

fixed

  • Property svn:keywords set to Id
File size: 76.9 KB
RevLine 
[47]1#-*- mode: python; mode: fold -*-
[990]2# $Id: Widgets.py 2358 2007-10-13 21:02:28Z henrik $
[295]3from cgi import escape
[502]4from types import *
[2110]5import Globals
[22]6from Globals import InitializeClass
[2098]7from ZPublisher.HTTPRequest import FileUpload
[2354]8from OFS.Image import cookId, File, Image
[199]9##from Products.CPSSchemas.Widget import CPSWidgetType
[295]10from Products.CMFCore.utils import getToolByName
[1772]11from Products.CPSSchemas.BasicWidgets import CPSBooleanWidget, CPSWidget, CPSStringWidget, CPSEmailWidget,CPSImageWidget
[2098]12from Products.CPSSchemas.BasicWidgets import CPSFileWidget
[295]13from Products.CPSSchemas.BasicWidgets import renderHtmlTag,CPSSelectWidget, CPSStringWidget
[22]14from Products.CPSSchemas.ExtendedWidgets import CPSDateTimeWidget
[199]15from Products.CPSSchemas.Widget import widgetRegistry
[2098]16from Products.CPSUtil.file import PersistableFileUpload
17from Products.CPSUtil.id import generateFileName
[199]18##from Products.CPSSchemas.WidgetTypesTool import WidgetTypeRegistry
[22]19from DateTime.DateTime import DateTime
20from AccessControl import getSecurityManager
[502]21from Products.WAeUP_SRP.Students import getStudentByRegNo
[1747]22from Products.WAeUP_SRP.Academics import makeCertificateCode
[2099]23#from Products.ExtFile.ExtFile import ExtFile
[2110]24import logging,os,re
[1915]25import operator
[2110]26p_home = Globals.package_home(globals())
27i_home = Globals.INSTANCE_HOME
[22]28
[952]29#from zLOG import LOG, DEBUG
[22]30
[295]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()
[444]56            res = renderHtmlTag('select',
57                                name='%s.%s:records' % (self.record_id,html_widget_id),
[295]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
[373]85class CPSStringWidgetForRecord(CPSStringWidget): ###(
[295]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,
[444]107                  'name': '%s.%s:records' % (self.record_id,html_widget_id),
[295]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
[373]120###)
121
122class CertificateCourseIdWidget(CPSStringWidget): ###(
123    """ CertificateCourseId Widget"""
124    meta_type = "CertificateCourseId Widget"
[444]125
[373]126    def validate(self, datastructure, **kw):
127        """Validate datastructure and update datamodel."""
[444]128
[373]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"})]
[381]137            if hasattr(self.aq_parent,value):
[1891]138                err = 'Course already exists'
[381]139            elif value not in c_ids:
[1891]140                err = 'Course does not exist'
[373]141            if err:
142                datastructure.setError(widget_id, err)
143            else:
144                datamodel = datastructure.getDataModel()
145                datamodel[self.fields[0]] = value
[444]146
[373]147            return not err
148
149InitializeClass(CertificateCourseIdWidget)
150
151widgetRegistry.register(CertificateCourseIdWidget)
[551]152###)
[373]153
[551]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
[2282]168            res = self.courses_catalog(code = value)
[551]169            if len(res) > 0:
[1891]170                err = 'Course already exists'
[551]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
[373]184###)
185
[1820]186class WAeUPStudyModeWidget(CPSSelectWidget): ###(
[1986]187    """WAeUP StudyMode Widget."""
[1820]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:
[1836]209            v = value = 'ume_ft'
[1820]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
[1804]255class WAeUPSessionWidget(CPSSelectWidget): ###(
[1986]256    """WAeUP Session Widget."""
[1804]257    meta_type = 'WAeUP Session Widget'
[2099]258
[1804]259    def _getSessions(self):
260        current_year = DateTime().year()
[1986]261        d = {'-1': 'N/A'}
[1804]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
[1805]275
[1804]276        if len(v) == 1:
277            v = value = '0%c' % v
278        elif not value:
279            v = value = self.getSessionId()[-2:]
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:
[1986]305                vocabulary_items.sort(key=operator.itemgetter(0))
[1804]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):
[1986]331        d = {'000':'N/A'}
[1804]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
[1805]345
346        if not value:
[1804]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:
[1986]373                vocabulary_items.sort(key=operator.itemgetter(0))
[1804]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): ###(
[1986]395    """WAeUP Verdict Widget."""
[1804]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
[2094]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        states = []
491        lgas  = []
492        d = {}
493        for k,v in voc.items():
[2110]494            parts = v.split(' / ')
[2187]495            if len(parts) == 1:
496                state = parts[0].lower()
497                lga = ""
498            elif len(parts) == 2:
499                state = parts[0].lower()
500                lga = "_".join(re.split('\W+',parts[1].lower()))
501            else:
[2110]502                continue
[2094]503            if state not in states:
504                states.append(state)
[2187]505            if lga not in lgas:
506                lgas.append(lga)
[2094]507            d[k] = v
[2110]508
[2094]509        return (d,states,lgas)
510
511    def validate(self, datastructure, **kw):
512        """Validate datastructure and update datamodel."""
513        widget_id = self.getWidgetId()
514        value = datastructure[widget_id]
515        #import pdb;pdb.set_trace()
516        try:
517            v = str(value)
518        except ValueError:
519            datastructure.setError(widget_id, "'%s' not a valid lga key" % value)
520            return 0
521        v = v.lower()
522        combined,states,lgas = self._getLGAs()
523        one_field = False
[2185]524        if len(v) == 0:
525            pass
526        elif not self.state_field and not self.lga_field:
[2094]527            one_field = True
528            if v not in combined.keys():
529                datastructure.setError(widget_id, "'%s' not a valid lga key" % v)
530                return 0
531        else:
532            if widget_id == self.state_field:
533                if v not in states:
534                    datastructure.setError(widget_id, "'%s' not a valid state" % v)
535                    return 0
536            elif widget_id == self.lga_field:
[2110]537                if "_".join(re.split('\W+',v)) not in lgas:
[2094]538                    datastructure.setError(widget_id, "'%s' not a valid lga" % v)
539                    return 0
540                if datastructure[self.state_field]:
541                    v = datastructure[self.state_field] + '_' + v
[2099]542
[2094]543        if self.is_required and not len(v):
544            datastructure.setError(widget_id, "lga required")
545            return 0
546
547        datamodel = datastructure.getDataModel()
548        if one_field:
549            datamodel[self.fields[0]] = v
550        else:
551            state = datastructure[self.state_field].lower()
552            lga = "_".join(datastructure[self.lga_field].lower().split())
[2099]553            datamodel[self.fields[0]] =   state + "_" + lga
[2094]554        return 1
555
556    def render(self, mode, datastructure, **kw):
557        """Render in mode from datastructure."""
558        w_id = self
559        value = datastructure[self.getWidgetId()]
560        lgas,x,y = self._getLGAs(datastructure)
561        if mode == 'view':
562            return escape(lgas.get(value, value))
563        elif mode == 'edit':
564            html_widget_id = self.getHtmlWidgetId()
565            res = renderHtmlTag('select', name=html_widget_id, id=html_widget_id)
566            in_selection = 0
567            vocabulary_items = lgas.items()
568            # if self.sorted:
569            #     vocabulary_items.sort(key=operator.itemgetter(1))
570            for k, v in vocabulary_items:
571                kw = {'value': k, 'contents': v}
572                if value == k:
573                    kw['selected'] = 'selected'
574                    in_selection = 1
575                res += renderHtmlTag('option', **kw)
576            if value and not in_selection:
577                kw = {'value': value, 'contents': 'invalid: '+ str(value),
578                      'selected': 'selected'}
579                res += renderHtmlTag('option', **kw)
580            res += '</select>'
581            return res
582        raise RuntimeError('unknown mode %s' % mode)
583
584InitializeClass(WAeUPLGAWidget)
585
586widgetRegistry.register(WAeUPLGAWidget)
587
588###)
589
[714]590class WAeUPReservedRoomsWidget(CPSStringWidget): ###(
591    """ WAeUPReservedRooms Widget"""
592    meta_type = "WAeUPReservedRooms Widget"
593
594    def validate(self, datastructure, **kw):
595        """Validate datastructure and update datamodel."""
596        import re
597        valid = CPSStringWidget.validate(self, datastructure, **kw)
598        if not valid:
599            return 0
600        else:
601            widget_id = self.getWidgetId()
602            value = datastructure[widget_id]
603            err = 0
604            try:
[926]605                reserved = [(r.split('/')[0],int(r.split('/')[1])) for r in re.split(',|\.| ',value)
[714]606                                     if r]
[1038]607            except (ValueError,IndexError),msg:
[714]608                err = str(msg)
609            if err:
610                datastructure.setError(widget_id, err)
611            else:
612                datamodel = datastructure.getDataModel()
613                datamodel[self.fields[0]] = value
614            return not err
615
616InitializeClass(WAeUPReservedRoomsWidget)
617
618widgetRegistry.register(WAeUPReservedRoomsWidget)
619###)
620
[388]621class WAeUPIdWidget(CPSStringWidget): ###(
622    """ WAeUPId Widget"""
623    meta_type = "WAeUPId Widget"
[444]624
[388]625    def validate(self, datastructure, **kw):
626        """Validate datastructure and update datamodel."""
[2289]627        mode = kw.get('mode','create')
[388]628        valid = CPSStringWidget.validate(self, datastructure, **kw)
[422]629        id_pat_str = r"\S"
[2110]630        inv_id_pat = re.compile(r"^%s$" % id_pat_str)
[388]631        if not valid:
632            return 0
633        else:
[586]634            portal_type_query = {'query':['Faculty',
635                                          'Department',
636                                          'Course',
637                                          'Certificate',
638                                          'CertificateCourse',]}
[388]639            widget_id = self.getWidgetId()
[2013]640            value = datastructure[widget_id]  #.upper()  is not necessary here because it's also done in waeup_document_create_do
[388]641            err = 0
[1907]642            mapping = {}
[440]643            if len(value.split()) > 1:
[783]644                err = 'Invalid Id, Id contains space(s).'
[2289]645            elif mode == "create" and\
646                          self.portal_catalog(portal_type=portal_type_query,id=value):
[1718]647                brain = self.portal_catalog(portal_type=portal_type_query,id=value)[0]
[1907]648                err = 'An ${portal_type} object with the Id ${id} already exists at ${path}.'
649                mapping = {'portal_type': brain.portal_type,
650                           'id': value,
651                           'path': brain.getPath(),
652                           }
[388]653            if err:
[1907]654                datastructure.setError(widget_id, err, mapping)
[388]655            else:
656                datamodel = datastructure.getDataModel()
657                datamodel[self.fields[0]] = value
[444]658
[388]659            return not err
660
661InitializeClass(WAeUPIdWidget)
662
663widgetRegistry.register(WAeUPIdWidget)
664
665
666###)
667
[1025]668class StudyCourseWidget(CPSStringWidget): ###(
669    """ StudyCourse Widget"""
670    meta_type = "StudyCourse Widget"
671
672    def validate(self, datastructure, **kw):
673        """Validate datastructure and update datamodel."""
674        #from Products.zdb import set_trace
675        #set_trace()
[1747]676##        valid = CPSStringWidget.validate(self, datastructure, **kw)
677##        if not valid:
678##            return 0
679        widget_id = self.getWidgetId()
680        value = makeCertificateCode(datastructure[widget_id]).upper()
[1025]681        id_pat_str = r"\S"
[2110]682        inv_id_pat = re.compile(r"^%s$" % id_pat_str)
[1747]683        err = 0
684        if len(value.split()) > 1:
685            err = 'Invalid Id, Id contains space(s).'
686        elif not self.portal_catalog(portal_type='Certificate',id=value):
687            err = 'No such certificate'
688        if err:
689            datastructure.setError(widget_id, err)
[1025]690        else:
[1747]691            datamodel = datastructure.getDataModel()
692            datamodel[self.fields[0]] = value
693        return not err
[1025]694
695InitializeClass(StudyCourseWidget)
696
697widgetRegistry.register(StudyCourseWidget)
698###)
699
[463]700class JambRegNoWidget(CPSStringWidget): ###(
701    """ JambRegNo Widget"""
702    meta_type = "JambRegNo Widget"
[1169]703    _properties = CPSStringWidget._properties + (
704        {'id': 'catalog', 'type': 'string', 'mode': 'w',
705         'label': 'Catalog to search'},
706         {'id': 'reference', 'type': 'string', 'mode': 'w',
707         'label': 'Reference Field'},
708         )
[2100]709    #catalog = "portal_pumeresults" #the catalog to search for jamb_reg_no
[1169]710    reference = ""
[463]711    digits = 8
712    digits_str = "N"*digits
713    letters = 2
714    letters_str = "L"*letters
715    def validate(self, datastructure, **kw):
716        """Validate datastructure and update datamodel."""
717        valid = CPSStringWidget.validate(self, datastructure, **kw)
[2100]718        reg_no_catalog = getattr(self,self.catalog)
[1169]719        widget_id = self.getWidgetId()
720        value = datastructure[widget_id].upper()
721        err = 0
[2094]722        #import pdb;pdb.set_trace()
723        if kw.has_key('mode'):
724            mode = kw['mode']
725        else:
[2098]726            mode = "edit"
[2099]727        if not valid:
[2100]728            err = 'Invalid registration number'
[1169]729        elif self.reference == '':
730            #s = getStudentByRegNo(self,value)
[2100]731            pume = reg_no_catalog(jamb_reg_no = value)
[1169]732            if len(pume) < 1:
[2100]733                err = 'No student record with this registration number'
[1169]734            else:
735                datastructure['pume'] = pume[0]
[2094]736        elif mode == 'add':
737            pass
[2095]738        elif self.reference != '' and self.catalog == "applicants_catalog":
[2100]739            res = reg_no_catalog.searchResults({"%s" % self.reference: value})
[2094]740            if len(res) != 1:
[2100]741                err = 'No record with this registration number'
[2094]742            else:
743                datastructure['record'] = res[0]
[463]744        else:
[1169]745            record = datastructure[self.reference]
746            #jamb_reg_no = getattr(record,widget_id)
747            jamb_reg_no = record.Entryregno
748            if jamb_reg_no != value:
[1783]749                err = 'Registration number does not match.'
[1169]750        if err:
751            datastructure.setError(widget_id, err)
752        else:
753            datamodel = datastructure.getDataModel()
754            datamodel[self.fields[0]] = value
755        return not err
[463]756
757InitializeClass(JambRegNoWidget)
758
759widgetRegistry.register(JambRegNoWidget)
[47]760###)
761
[1175]762class SecretWidget(CPSStringWidget): ###(
763    """ Secret Widget"""
764    meta_type = "Secret Widget"
765    _properties = CPSStringWidget._properties + (
766        {'id': 'reference', 'type': 'string', 'mode': 'w',
767         'label': 'Reference Record'},
768         {'id': 'check_fields', 'type': 'tokens', 'mode': 'w',
769         'label': 'Fields to check'},
770         )
771    reference = "student"
[1747]772    matric_no_catalog = 'returning_import'
[1175]773    check_fields = ("Firstname", "Middlename","Lastname")
774    def validate(self, datastructure, **kw):
775        """Validate datastructure and update datamodel."""
[1571]776        logger = logging.getLogger('Widgets.SecretWidget.validate')
[1175]777        valid = CPSStringWidget.validate(self, datastructure, **kw)
778        widget_id = self.getWidgetId()
779        value = datastructure[widget_id].upper()
780        err = 0
[1189]781        record = datastructure.get(self.reference,None)
[1747]782        #import pdb;pdb.set_trace()
[1379]783        if not valid or len(value) < 2:
[1793]784            err = 'Invalid string'
[1189]785        elif not record or datastructure.errors:
[1177]786            err = 0
[1175]787        else:
788            found = False
789            cvs = []
790            for field in self.check_fields:
791                cv = getattr(record,field).upper()
[1243]792                if len(cv.split()) > 1:
793                    for splited in cv.split():
[1747]794                        cvs.append(splited.strip())
[1243]795                else:
796                    cvs.append(cv)
[1747]797            for cv in cvs:
[1175]798                if cv  == value.upper():
799                    found = True
800                    break
801            matric_no = record.matric_no
802            name = " ".join(cvs)
803            if not found:
[1573]804                logger.info('%(matric_no)s did not find %(value)s in %(name)s' % vars())
805                err = 'No name does match.'
[1175]806            else:
[1571]807                logger.info('%(matric_no)s found %(value)s in %(name)s' % vars())
[1175]808        if err:
809            datastructure.setError(widget_id, err)
810        else:
811            datamodel = datastructure.getDataModel()
812            datamodel[self.fields[0]] = value
813        return not err
814
815InitializeClass(SecretWidget)
816
817widgetRegistry.register(SecretWidget)
818###)
819
[1804]820class WAeUPSexWidget(CPSBooleanWidget): ###(
[1772]821    """WAeUP sex widget."""
822    meta_type = 'WAeUP Sex Widget'
823
824    def validate(self, datastructure, **kw):
825        """Validate datastructure and update datamodel."""
826        value = datastructure[self.getWidgetId()]
827
828        if self.render_format not in self.render_formats:
829            self.render_format = 'select'
830
831        female = value in ('F','f','Female','female',"True",True)
832        male = value in ('M','m','Male','male','False',False)
833        if not female and not male:
834            datastructure.setError(self.getWidgetId(),
835                                   "invalid sex %s" % value)
836            return 0
837        elif female:
838            v = True
839        else:
840            v = False
841        datamodel = datastructure.getDataModel()
842        datamodel[self.fields[0]] = v
843        return 1
844
845InitializeClass(WAeUPSexWidget)
846
847widgetRegistry.register(WAeUPSexWidget)
848
[1804]849###)
850
[1146]851class MatricNoWidget(CPSStringWidget): ###(
852    """ MatricNo Widget"""
853    meta_type = "MatricNo Widget"
[1747]854
855    _properties = CPSStringWidget._properties + (
856        {'id': 'matric_no_catalog', 'type': 'string', 'mode': 'w',
857         'label': 'Catalog to search for MatricNo'},
858        { 'id': 'results_catalog', 'type': 'string', 'mode': 'w',
859         'label': 'Results Catalog'},
860         )
861    matric_no_catalog = "" #the catalog to search for matric_no
[1748]862    results_catalog = "results_import" #results catalog
[1747]863
[1146]864    def validate(self, datastructure, **kw):
865        """Validate datastructure and update datamodel."""
[1747]866        #import pdb;pdb.set_trace()
[1146]867        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]868        logger = logging.getLogger('Widgets.MatricNoWidget.validate')
[1747]869        returning = getattr(self,self.matric_no_catalog)
870        results = getattr(self,self.results_catalog,None)
[1146]871        err = 0
[1189]872        widget_id = self.getWidgetId()
873        value = datastructure[widget_id]
874        if not valid or not value:
[1891]875            err = 'Invalid string'
[1573]876            logger.info('Invalid matric_no string %s' % value)
[1146]877        else:
[1189]878            value = value.upper()
[1177]879            datastructure['student'] = None
[1146]880            while not err:
[1151]881                res = returning(matric_no = value)
[1146]882                if len(res) < 1:
[1573]883                    logger.info('matric_no %s not found' % value)
[1915]884                    err = 'No student with this matriculation number.'
[1747]885                    break
[1146]886                datastructure['student'] = res[0]
[1747]887                if results is not None:
888                    res = results(matric_no = value)
889                    if len(res) < 1:
[1891]890                        err = 'No results for this matriculation number'
[1747]891                        continue
892                    datastructure['results'] = res
[1146]893                break
[1189]894        if err:
895            datastructure.setError(widget_id, err)
896        else:
897            datamodel = datastructure.getDataModel()
898            datamodel[self.fields[0]] = value
899        return not err
[1146]900
901InitializeClass(MatricNoWidget)
902
903widgetRegistry.register(MatricNoWidget)
904###)
905
[1393]906class StudentIdWidget(CPSStringWidget): ###(
907    """ StudentId Widget"""
908    meta_type = "StudentId Widget"
909    def validate(self, datastructure, **kw):
910        """Validate datastructure and update datamodel."""
911        valid = CPSStringWidget.validate(self, datastructure, **kw)
[1571]912        logger = logging.getLogger('Widgets.StudentIdWidget.validate')
[1393]913        #import pdb;pdb.set_trace()
914        s_cat = self.students_catalog
915        err = 0
916        widget_id = self.getWidgetId()
917        value = datastructure[widget_id]
918        if not valid or not value:
[1891]919            err = 'Invalid Id string'
[1573]920            logger.info('Invalid id string %s' % value)
[1449]921            datastructure['student'] = None
[1393]922        else:
923            value = value.upper()
924            res = s_cat(id = value)
925            if not res:
[1573]926                logger.info('Student id %s not found' % value)
[1891]927                err = 'No student with this Id'
[1393]928                datastructure['student'] = None
929            else:
930                datastructure['student'] = res[0]
931        if err:
932            datastructure.setError(widget_id, err)
933        else:
934            datamodel = datastructure.getDataModel()
935            datamodel[self.fields[0]] = value
936        return not err
937
938InitializeClass(StudentIdWidget)
939
940widgetRegistry.register(StudentIdWidget)
941###)
942
[1146]943class WAeUPMultilineResultsWidget(CPSStringWidget): ###(
944    """ WAeUPMultilineResults Widget"""
945    meta_type = "WAeUp Multiline Results Widget"
946    _properties = CPSWidget._properties + (
947        {'id': 'nr_of_lines', 'type': 'int', 'mode': 'w',
948         'label': 'Nr of Lines'},
949         )
950    nr_of_lines = 5
951    def prepare(self, datastructure, **kw): ###(
952        """Prepare datastructure from datamodel."""
953        datamodel = datastructure.getDataModel()
954        #import pdb;pdb.set_trace()
955        widget_id = self.getWidgetId()
956        v = datamodel[self.fields[0]]
957        if type(v) is ListType and v:
958            nr_results = len(v)
959        else:
960            v = []
961            nr_results = 0
962        count = 1
963        for s,g in v:
964            wid = "%s%02d"% (widget_id,count)
965            datastructure[wid+'_s'] = s
966            datastructure[wid+'_g'] = g
967            count += 1
968        if nr_results < self.nr_of_lines:
969            for line in range(nr_results,self.nr_of_lines):
970                v.append(('',''))
971                wid = "%s%02d"% (widget_id,line)
972                datastructure[wid+'_s'] = ''
973                datastructure[wid+'_g'] = ''
974        datastructure[widget_id] = v
975        datastructure[widget_id+'_s'] = ''
976        datastructure[widget_id+'_g'] = ''
977    ###)
978
979    def validate(self, datastructure, **kw): ###(
980        """Validate datastructure and update datamodel."""
981        #import pdb;pdb.set_trace()
982        widget_id = self.getWidgetId()
983        err = 0
984        lines = []
985        for line in range(1,30):
986            wid = "%s%02d"% (widget_id,line)
987            if not datastructure.has_key(wid+'_s'):
988                break
989            lines.append((datastructure[wid+'_s'].strip(),
990                         datastructure[wid+'_g'].strip()))
[1155]991
[1146]992        s = datastructure[widget_id+'_s'].strip()
993        g = datastructure[widget_id+'_g'].strip()
994        if s and g:
995            lines.append((s,g))
996        active = []
997        for s,g in lines:
998            if g != "":
999                active.append((s,g))
1000        if err:
1001            datastructure.setError(widget_id, err)
1002        else:
1003            datamodel = datastructure.getDataModel()
1004            datamodel[self.fields[0]] = active
1005        return not err
1006    ###)
1007
1008    def render(self, mode, datastructure, **kw): ###(
1009        """Render in mode from datastructure."""
1010        render_method = 'widget_waeup_multiline_result_render'
1011        meth = getattr(self, render_method, None)
1012        if meth is None:
1013            raise RuntimeError("Unknown Render Method %s for widget type %s"
1014                               % (render_method, self.getId()))
1015        #import pdb;pdb.set_trace()
1016        datamodel = datastructure.getDataModel()
1017        widget_id = self.getWidgetId()
1018        lines = datamodel[self.fields[0]]
1019        if len(lines) < self.nr_of_lines:
1020            for line in range(len(lines),self.nr_of_lines + 1):
1021                lines.append(('',''))
1022        datastructure[widget_id] = lines
1023        datastructure[widget_id+'_s'] = ''
1024        datastructure[widget_id+'_g'] = ''
1025##        count = 1
1026##        for s,g in v:
1027##            wid = "%s%02d"% (widget_id,count)
1028##            count += 1
1029        return meth(mode=mode,
1030                    datastructure=datastructure,
1031                    )
1032    ###)
1033
1034
1035InitializeClass(WAeUPMultilineResultsWidget)
1036widgetRegistry.register(WAeUPMultilineResultsWidget)
1037###)
1038
[794]1039class WAeUPResultsWidget(CPSStringWidget): ###(
1040    """ WAeUPResults Widget"""
1041    meta_type = "WAeUp Results Widget"
1042
1043    def prepare(self, datastructure, **kw): ###(
1044        """Prepare datastructure from datamodel."""
1045        datamodel = datastructure.getDataModel()
1046        v = datamodel[self.fields[0]]
1047        #import pdb;pdb.set_trace()
1048        widget_id = self.getWidgetId()
[807]1049        datastructure[widget_id] = v
[794]1050        datastructure[widget_id+'_s'] = ''
1051        datastructure[widget_id+'_g'] = ''
1052    ###)
1053
1054    def validate(self, datastructure, **kw): ###(
1055        """Validate datastructure and update datamodel."""
[807]1056        #import pdb;pdb.set_trace()
[794]1057        widget_id = self.getWidgetId()
1058        v = datastructure[widget_id]
1059        err = 0
1060        s = datastructure[widget_id+'_s'].strip()
1061        g = datastructure[widget_id+'_g'].strip()
[807]1062        while 1:
1063            if not s and g:
[1891]1064                err = "No subject grade for subject"
[807]1065                break
1066            i = 0
1067            done = False
1068            for sv,gv in v:
1069                if sv == s:
1070                    done = True
1071                    if not g:
1072                        v.pop(i)
1073                        break
1074                    v[i] = (s,g)
1075                    break
1076                i += 1
1077            if done:
1078                break
1079            if s and g:
1080                v.append((s,g))
1081            break
[794]1082        if err:
1083            datastructure.setError(widget_id, err)
1084        else:
1085            datamodel = datastructure.getDataModel()
1086            datamodel[self.fields[0]] = v
1087            datastructure[widget_id+'_s'] = s
1088            datastructure[widget_id+'_g'] = g
1089        return not err
1090    ###)
1091
1092    def render(self, mode, datastructure, **kw): ###(
1093        """Render in mode from datastructure."""
1094        render_method = 'widget_waeup_result_render'
1095        meth = getattr(self, render_method, None)
1096        if meth is None:
1097            raise RuntimeError("Unknown Render Method %s for widget type %s"
1098                               % (render_method, self.getId()))
1099        #import pdb;pdb.set_trace()
1100        datamodel = datastructure.getDataModel()
1101        widget_id = self.getWidgetId()
1102        datastructure[widget_id+'_s'] = ''
1103        datastructure[widget_id+'_g'] = ''
1104        return meth(mode=mode,
1105                    datastructure=datastructure,
1106                    )
1107    ###)
1108
1109
1110InitializeClass(WAeUPResultsWidget)
1111widgetRegistry.register(WAeUPResultsWidget)
1112###)
1113
[488]1114class ScratchCardPin: ###(
1115    """the ScratchCardPin"""
1116    def __init__(self,prefix,batch_no,number):
[990]1117        if not batch_no and not number:
1118            s = prefix
[996]1119            if len(s) > 3:
[990]1120                prefix,batch_no,number = s[:3],s[3:-10],s[-10:]
1121            else:
[996]1122                prefix,batch_no,number = s,'',''
[488]1123        self.p = prefix
1124        self.b = batch_no
1125        self.n = number
1126
1127    def __str__(self):
1128        return "%s-%s-%s" % (self.p,self.b,self.n)
[1146]1129
1130    def __repr__(self):
1131        return "%s%s%s" % (self.p,self.b,self.n)
[488]1132###)
1133
[47]1134class ScratchcardPinWidget(CPSStringWidget): ###(
[22]1135    """ ScratchcardPin Widget"""
[199]1136    meta_type = "Scratchcard Pin Widget"
[488]1137    _properties = CPSWidget._properties + (
1138        {'id': 'prefix', 'type': 'string', 'mode': 'w',
1139         'label': 'Prefix'},
1140         {'id': 'reference', 'type': 'string', 'mode': 'w',
1141         'label': 'Reference Field'},
1142        )
1143    prefix = ''
1144    reference = ''
[502]1145    def prepare(self, datastructure, **kw): ###(
[488]1146        """Prepare datastructure from datamodel."""
1147        datamodel = datastructure.getDataModel()
1148        v = datamodel[self.fields[0]]
1149        widget_id = self.getWidgetId()
[747]1150        if v and type(v) is StringType:
[990]1151            try:
1152                p,b,n = v.split('-')
1153                v = ScratchCardPin(p,b,n)
1154            except ValueError:
1155                v = ScratchCardPin(v,'','')
[488]1156        if v:
[742]1157            p = '%s' % v.p
[488]1158            b = '%s' % v.b
1159            n = '%s' % v.n
1160        else:
[742]1161            p = self.prefix
1162            if p.startswith('@'):
1163                p = getattr(self,self.prefix[1:])()
[488]1164            b = n = ''
[742]1165            v = ScratchCardPin(p,b,n)
[488]1166        datastructure[widget_id] = v
[742]1167        datastructure[widget_id+'_p'] = p
[488]1168        datastructure[widget_id+'_b'] = b
1169        datastructure[widget_id+'_n'] = n
[1376]1170    ###)
[758]1171
[1169]1172    def validate(self, datastructure, **kw): ###(
[22]1173        """Validate datastructure and update datamodel."""
[1571]1174        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
[488]1175        widget_id = self.getWidgetId()
1176        v = datastructure[widget_id]
[996]1177        #import pdb;pdb.set_trace()
[488]1178        err = 0
[1907]1179        mapping = {}
[742]1180        prefix= self.prefix
1181        if prefix.startswith('@'):
1182            prefix= getattr(self,self.prefix[1:])()
[488]1183        b = datastructure[widget_id+'_b'].strip()
1184        n = datastructure[widget_id+'_n'].strip()
[502]1185        pins = self.portal_pins
[742]1186        pin = "%(prefix)s%(b)s%(n)s" % vars()
[2001]1187        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
[816]1188        do = 1
[1025]1189        s_id = str(self.portal_membership.getAuthenticatedMember())
[1343]1190        if self.isStaff():
[1326]1191            do = 0
1192            err ='You are not a Student. PIN neither checked nor used.'
[1571]1193            s_logger.info('%s tried to use scratch card %s' % (s_id,pin_str))
[1557]1194        elif len(b) > 1 and b.find('-') > -1:
1195            do = 0
[1573]1196            err = 'PIN must not contain "-"'
1197            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1557]1198        elif n.find('-') > -1:
1199            do = 0
[1573]1200            err = 'PIN must not contain "-"'
1201            s_logger.info('%s entered invalid PIN  containing "-"' % (s_id))
[1376]1202        elif len(n) != 10:
1203            do = 0
[1891]1204            err = 'Invalid PIN length'
[1573]1205            s_logger.info('%s entered invalid PIN with length %d' % (s_id,len(n)))
[1326]1206        elif self.reference == "":
[1030]1207            ref = s_id
[635]1208        else:
1209            ref = datastructure[self.reference]
[843]1210            if datastructure.errors:
[816]1211                do = 0
[1805]1212                datastructure.setError(widget_id, 'PIN neither checked nor used.')
[1571]1213                s_logger.info('%s/%s entered wrong data together with PIN %s' % (s_id,ref,pin_str))
[816]1214        while do:
1215            ok = pins.searchAndSetRecord(pin,ref,prefix)
[1030]1216            if ok < -2 or ok > 2:
1217                err = 'Unknown error, please report!'
[1571]1218                s_logger.info('%s/%s caused unknown error with PIN %s' % (s_id,ref,pin_str))
[1030]1219                break
1220            elif ok == -2:
[1783]1221                err = 'Service already is activated but with a different PIN.'
[1571]1222                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (s_id,ref,pin_str))
[710]1223                break
1224            elif ok == -1:
[1793]1225                err = 'Invalid PIN'
[1571]1226                s_logger.info('%s/%s entered invalid PIN %s' % (s_id,ref,pin_str))
[502]1227                break
1228            if ok == 0:
[1571]1229                err = 'PIN already used'
1230                s_logger.info('%s/%s entered used PIN %s' % (s_id,ref,pin_str))
[502]1231                break
1232            if ok >= 1:
[710]1233                #import pdb;pdb.set_trace()
[635]1234                if self.isStudent():
[992]1235                    if self.reference == "jamb_reg_no":
[997]1236                        err = "You are already logged in."
[1573]1237                        s_logger.info('%s/%s checked admission with PIN %s though logged in' % (s_id,ref,pin_str))
[992]1238                        break
[1082]1239                    if ok == 1:
[1571]1240                        s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[1032]1241                    else:
[1571]1242                        s_logger.info('%s/%s repeatedly used PIN %s' % (s_id,ref,pin_str))
[637]1243                    break
[635]1244                else:
1245                    student = getStudentByRegNo(self,ref)
[1571]1246                    s_logger.info('%s/%s successfully used PIN %s' % (s_id,ref,pin_str))
[502]1247                if student is None:
[1793]1248                    err = "Student not found"
[1571]1249                    s_logger.info('%s not found in admission list' % (ref))
[502]1250                    break
[648]1251                s_id = student.getId()
[502]1252                if ok == 2:
[990]1253                    if self.reference == "jamb_reg_no":
1254                        if hasattr(self.portal_directories.students,s_id):
[1907]1255                            err = "Please login with your Student Id ${id} and 10-digit PIN."
1256                            mapping = {'id': s_id}
[1571]1257                            s_logger.info('%s/%s repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1258                            break
1259                        else:
[1571]1260                            s_logger.info('%s/%s (non-member) repeatedly checked admission with PIN %s' % (s_id,ref,pin_str))
[990]1261                    else:
[1891]1262                        err = "Unknown error"
[1571]1263                        s_logger.info('%s/%s repeatedly activated service with PIN %s' % (s_id,ref,pin_str))
[986]1264                        break
1265                try:
1266                    student.getContent().makeStudentMember(s_id,password=pin[4:])
[1571]1267                    s_logger.info('%s/%s has been created using PIN %s' % (s_id,ref,pin_str))
[986]1268                except:
[1907]1269                    err = "Please login with your Student Id ${id} and 10-digit PIN."
1270                    mapping = {'id': s_id}
[1571]1271                    s_logger.info('%s/%s could not be made a member with PIN %s' % (s_id,ref,pin_str))
[986]1272                    break
[502]1273            break
[488]1274        if err:
[1907]1275            datastructure.setError(widget_id, err,mapping)
[488]1276        else:
1277            datamodel = datastructure.getDataModel()
[742]1278            datamodel[self.fields[0]] = ScratchCardPin(prefix,b,n)
1279            datastructure[widget_id] = ScratchCardPin(prefix,b,n)
1280            datastructure[widget_id+'_p'] = prefix
[488]1281            datastructure[widget_id+'_b'] = b
1282            datastructure[widget_id+'_n'] = n
[502]1283            datastructure['s_id'] = s_id
[488]1284        return not err
[444]1285
[1169]1286###)
1287
[502]1288    def render(self, mode, datastructure, **kw): ###(
[488]1289        """Render in mode from datastructure."""
1290        render_method = 'widget_scratch_card_pin_render'
1291        meth = getattr(self, render_method, None)
1292        if meth is None:
1293            raise RuntimeError("Unknown Render Method %s for widget type %s"
1294                               % (render_method, self.getId()))
1295
1296        # XXX AT: datastructure has to be set again here, in case we're in edit
1297        # or create mode, because a default value has to be provided.
1298        #import pdb;pdb.set_trace()
1299        datamodel = datastructure.getDataModel()
1300        v = datamodel[self.fields[0]]
[502]1301        if v and type(v) is StringType:
[990]1302            try:
1303                p,b,n = v.split('-')
1304                v = ScratchCardPin(p,b,n)
1305            except ValueError:
[2002]1306                v = ScratchCardPin(self.prefix,'XXX',v)
[996]1307                pass
[488]1308        if v:
[742]1309            prefix= '%s' % v.p
[488]1310            b = '%s' % v.b
1311            n = '%s' % v.n
[22]1312        else:
[742]1313            prefix= self.prefix
1314            if prefix.startswith('@'):
1315                prefix= getattr(self,self.prefix[1:])()
[488]1316            b = n = ''
[742]1317            v = ScratchCardPin(prefix,b,n)
1318        widget_id = self.getWidgetId()
1319        datastructure[widget_id] = v
1320        datastructure[widget_id+'_p'] = prefix
1321        datastructure[widget_id+'_b'] = b
1322        datastructure[widget_id+'_n'] = n
[758]1323        return meth(mode=mode,
1324                    datastructure=datastructure,
[488]1325                    )
[523]1326    ###)
[488]1327
[22]1328InitializeClass(ScratchcardPinWidget)
[199]1329widgetRegistry.register(ScratchcardPinWidget)
[2094]1330###)
[22]1331
[2094]1332class PumePinWidget(ScratchcardPinWidget): ###(
1333    """ Pume Pin Widget"""
1334    meta_type = "Pume Pin Widget"
[2098]1335    catalog = "applicants_catalog"
[2307]1336    reference = ''
[2099]1337
[2342]1338    def prepare(self, datastructure, **kw): ###(
1339        """Prepare datastructure from datamodel."""
1340        datamodel = datastructure.getDataModel()
[2350]1341        #import pdb;pdb.set_trace()
[2342]1342        v = datamodel[self.fields[0]]
1343        widget_id = self.getWidgetId()
1344        if v and type(v) is StringType:
1345            try:
1346                p,b,n = v.split('-')
1347                v = ScratchCardPin(p,b,n)
1348            except ValueError:
1349                v = ScratchCardPin(v,'','')
1350        if v:
1351            p = '%s' % v.p
1352            b = '%s' % v.b
1353            n = '%s' % v.n
1354        else:
1355            p = self.prefix
1356            if p.startswith('@'):
1357                p = getattr(self,self.prefix[1:])()
1358            b = n = ''
1359            v = ScratchCardPin(p,b,n)
1360        datastructure[widget_id] = v
1361        datastructure[widget_id+'_p'] = p
1362        datastructure[widget_id+'_b'] = b
1363        datastructure[widget_id+'_n'] = n
1364    ###)
1365
[2094]1366    def validate(self, datastructure, **kw): ###(
1367        """Validate datastructure and update datamodel."""
[2353]1368        #import pdb;pdb.set_trace()
[2094]1369        s_logger = logging.getLogger('Widgets.ScratchcardPinWidget.validate')
1370        widget_id = self.getWidgetId()
1371        v = datastructure[widget_id]
1372        err = 0
1373        mapping = {}
1374        prefix= self.prefix
1375        if prefix.startswith('@'):
1376            prefix= getattr(self,self.prefix[1:])()
1377        b = datastructure[widget_id+'_b'].strip()
1378        n = datastructure[widget_id+'_n'].strip()
1379        pins = self.portal_pins
1380        pin = "%(prefix)s%(b)s%(n)s" % vars()
1381        pin_str = "%(prefix)s-%(b)s-%(n)s" % vars()
[2307]1382        member_id = str(self.portal_membership.getAuthenticatedMember())
[2094]1383        do = 1
1384        if self.isStaff():
1385            do = 0
1386            err ='You are not a Student. PIN neither checked nor used.'
[2344]1387            s_logger.info('%s tried to use scratch card %s' % (member_id,pin_str))
[2094]1388        elif len(b) > 1 and b.find('-') > -1:
1389            do = 0
1390            err = 'PIN must not contain "-"'
[2307]1391            s_logger.info('%s entered invalid PIN  containing "-"' % (member_id))
[2094]1392        elif n.find('-') > -1:
1393            do = 0
1394            err = 'PIN must not contain "-"'
[2307]1395            s_logger.info('%s entered invalid PIN  containing "-"' % (member_id))
[2094]1396        elif len(n) != 10:
1397            do = 0
1398            err = 'Invalid PIN length'
[2307]1399            s_logger.info('%s entered invalid PIN with length %d' % (member_id,len(n)))
[2094]1400        elif self.reference == "":
[2307]1401            ref = n
[2094]1402        else:
1403            ref = datastructure[self.reference]
1404            if datastructure.errors:
1405                do = 0
1406                datastructure.setError(widget_id, 'PIN neither checked nor used.')
[2307]1407                s_logger.info('%s/%s entered wrong data together with PIN %s' % (member_id,ref,pin_str))
[2094]1408        while do:
1409            ok = pins.searchAndSetRecord(pin,ref,prefix)
1410            if ok < -2 or ok > 2:
1411                err = 'Unknown error, please report!'
[2307]1412                s_logger.info('%s/%s caused unknown error with PIN %s' % (member_id,ref,pin_str))
[2094]1413                break
1414            elif ok == -2:
[2352]1415                err = 'Service is already activated but with a different PIN.'
[2307]1416                s_logger.info('%s/%s repeatedly activated service but with different PIN %s' % (member_id,ref,pin_str))
[2094]1417                break
1418            elif ok == -1:
1419                err = 'Invalid PIN'
[2307]1420                s_logger.info('%s/%s entered invalid PIN %s' % (member_id,ref,pin_str))
[2094]1421                break
1422            if ok == 0:
1423                err = 'PIN already used'
[2307]1424                s_logger.info('%s/%s entered used PIN %s' % (member_id,ref,pin_str))
[2094]1425                break
1426            if ok >= 1:
[2342]1427                #screening_type = self.REQUEST.form.get('screening_type','unknown')
[2356]1428                #screening_type = datastructure['screening_type']
1429
[2353]1430                if self.REQUEST.traverse_subpath:
1431                    screening_type_request = self.REQUEST.traverse_subpath[0]
1432                else:
1433                    screening_type_request = 'manage'
[2094]1434                if self.isStudent():
[2352]1435                    err = "You are a student!"
[2307]1436                    s_logger.info('%s/%s applied for screening test with PIN %s' % (member_id,ref,pin_str))
[2094]1437                    break
[2307]1438                elif datastructure.has_key('record'):
[2094]1439                    applicant = datastructure['record']
[2355]1440                    if applicant.screening_type != screening_type_request\
1441                          and screening_type_request != 'manage':
[2357]1442                        err = "You are using the wrong access form!"
[2356]1443                        s_logger.info('%s tried to use %s application form but has applied for %s' % (ref,screening_type_request,applicant.screening_type))
[2350]1444                        break
[2099]1445                    if not applicant.pin:
[2094]1446                        s_logger.info('%s successfully used PIN %s' % (ref,pin_str))
1447                        d = {}
1448                        d['reg_no'] = applicant.reg_no
[2098]1449                        d['pin'] = pin_str
[2353]1450                        #d['screening_type'] = screening_type
[2144]1451                        d['status'] = 'entered'
[2098]1452                        getattr(self,self.catalog).modifyRecord(**d)
[2094]1453                    elif applicant.pin != pin_str:
[2307]1454                        s_logger.info('%s/%s tried to enter application record with different PIN %s' % (member_id,ref,pin_str))
[2094]1455                    elif applicant.pin == pin_str:
[2307]1456                        s_logger.info('%s/%s repeatedly entered application record with PIN %s' % (member_id,ref,pin_str))
1457                else:
[2324]1458                    datastructure['reg_no'] = ref
[2307]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'
[2353]1466                        d['screening_type'] = screening_type_request
[2307]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))
[2094]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
[2098]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
[2094]1524InitializeClass(PumePinWidget)
1525widgetRegistry.register(PumePinWidget)
[47]1526###)
1527
[1169]1528class WAeUPImageWidget(CPSImageWidget): ###(
[537]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)
[1804]1544###)
[537]1545
[2342]1546class ApplicationImageWidget(CPSImageWidget): ###(
[2110]1547    """Image widget with filesystem storage."""
[2342]1548    meta_type = 'Application Image Widget'
[2110]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"
[2119]1557    storage_path = "%s/import/%s" % (i_home,path)
[2110]1558    id_field = "reg_no"
[537]1559
[2110]1560    def getImageInfo(self, datastructure): ###(
[2098]1561        """Get the file info from the datastructure."""
1562        widget_id = self.getWidgetId()
[2120]1563        if  datastructure.has_key(widget_id):
1564            fileupload = datastructure[widget_id]
1565            dm = datastructure.getDataModel()
1566            field_id = self.fields[0]
[2342]1567            screening_type = datastructure.get('screening_type')
[2120]1568            current_filename = "%s_%s.jpg" % (datastructure[self.id_field],
1569                                            field_id,)
[2342]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()
[2120]1574        else:
1575            file_path = "XXX"
[2114]1576        # read the file from the filesystem
1577        if not os.path.exists(file_path):
[2120]1578            height = -1
1579            width = -1
[2098]1580            empty_file = True
1581            session_file = False
1582            current_filename = ''
[2120]1583            content_url = ''
[2098]1584            size = 0
[2116]1585            mimetype = ''
[2098]1586            last_modified = ''
[2119]1587            height = ''
1588            width = ''
[2122]1589
[2098]1590        else:
[2114]1591            image = open(file_path)
[2142]1592            from OFS.Image import getImageInfo as getImageInfoOFS
[2110]1593            image.seek(0)
[2142]1594            data = image.read(2000)
[2114]1595            size = len(data)
1596            empty_file = size == 0
1597            session_file = False
1598            last_modified = ''
1599            image.close()
[2142]1600            mimetype, width, height = getImageInfoOFS(data)
[2119]1601
[2110]1602            if width < 0:
1603                width = None
1604            if height < 0:
1605                height = None
[2117]1606
[2110]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)
[2117]1621                #import pdb;pdb.set_trace()
[2114]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 ''
[2117]1633        #height = int(self.display_height)
1634        #width = int(self.display_width)
[2114]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)
[2110]1642
1643        image_info['height'] = height
1644        image_info['width'] = width
1645        image_info['image_tag'] = tag
1646        return image_info
[2098]1647    ###)
1648
[2114]1649    def checkFileName(self, filename, mimetype):
1650        return '', {}
1651        if mimetype and mimetype.startswith('image'):
1652            return '', {}
1653        return 'cpsschemas_err_image', {}
1654
[2098]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]]
[2136]1660        #import pdb; pdb.set_trace()
1661        if self.allow_resize:
1662            datastructure[self.getWidgetId() + '_resize'] = ''
[2342]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
[2110]1667        datastructure[widget_id] = file_name
[2114]1668        datastructure[widget_id + '_choice'] = 'change'
1669        title = 'Passport Foto'
[2098]1670        datastructure[widget_id + '_filename'] = title
1671    ###)
1672
[2114]1673    def validate(self, datastructure, **kw): ###(
[2098]1674        """Update datamodel from user data in datastructure.
1675        """
[2342]1676        logger = logging.getLogger('Widgets.ApplicationImageWidget.validate')
[2098]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]
[2114]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)
[2136]1691        #import pdb; pdb.set_trace()
1692        if not is_upload and not datamodel[field_id]:
1693            if self.is_required:
[2137]1694                return self.validateError('Picture upload required', {},
[2136]1695                                          datastructure)
[2098]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
[2114]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:
[2098]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)
[2120]1726                err = 'This file is too big, the allowed max size is ${max_size}'
[2122]1727                logger.info('%s tried to upload picture with size %dk' %(datastructure['reg_no'],int(size)/1000) )
[2098]1728                err_mapping = {'max_size': max_size_str}
1729                return self.validateError(err, err_mapping, datastructure)
1730            store = True
1731
1732
1733        # Find filename
[2136]1734        if is_upload and store:
[2114]1735            ext ='jpg'
[2342]1736            screening_type = datastructure.get('screening_type')
[2114]1737            filename = "%s_%s.%s" % (datastructure[self.id_field],
[2342]1738                                     self.getWidgetId(),
1739                                     ext)
[2136]1740            datamodel[field_id] = filename
[2114]1741            registry = getToolByName(self, 'mimetypes_registry')
1742            mimetype = registry.lookupExtension(filename.lower())
1743            if mimetype is not None:
1744                mimetype = str(mimetype) # normalize
[2110]1745            file = self.makeFile(filename, fileupload, datastructure)
[2098]1746            # Fixup mimetype
[2110]1747            if mimetype and file.content_type != mimetype:
1748                file.content_type = mimetype
1749            # Store the file in the filesystem
[2114]1750            #import pdb;pdb.set_trace()
[2342]1751            base_path = os.path.join(self.storage_path, screening_type)
1752            if not os.path.exists(base_path):
1753                os.mkdir(base_path)
[2344]1754            full_path = os.path.join(base_path, filename)
[2114]1755            pict = open(full_path,"w")
1756            fileupload.seek(0)
1757            pict.write(fileupload.read())
1758            pict.close()
[2098]1759
[2110]1760
[2098]1761        return True
1762
[2114]1763###)
[2098]1764
[2114]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
[2342]1775InitializeClass(ApplicationImageWidget)
[2098]1776
[2342]1777widgetRegistry.register(ApplicationImageWidget)
[2098]1778###)
1779
[2335]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'},
[2342]1789     {'id': 'show_image', 'type': 'boolean', 'mode': 'w',
1790      'label': 'Show Image'},
[2335]1791    )
1792    path = "images"
1793    storage_path = "%s/%s" % (i_home,path)
1794    id_field = ""
[2342]1795    show_image = False
[2344]1796
[2354]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 = ''
[2358]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
[2354]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
[2356]1826
[2335]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]
[2354]1834            info = self.getStorageImageInfo(field_id)
[2335]1835        else:
1836            file_path = "XXX"
[2354]1837            title = ""
[2335]1838        # read the file from the filesystem
[2354]1839        #import pdb; pdb.set_trace()
1840        #if not os.path.exists(file_path):
1841        if not info:
1842            title = ""
[2335]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:
[2354]1855            title = info['image_name']
1856            current_filename = info['current_filename']
1857            content_url = info['content_url']
1858            image = open(info['file_path'])
[2335]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
[2342]1914        image_info['show_image'] = self.show_image
[2335]1915        return image_info
1916    ###)
1917
[2354]1918    # def checkFileName(self, filename, mimetype):
1919    #     return '', {}
1920    #     if mimetype and mimetype.startswith('image'):
1921    #         return '', {}
1922    #     return 'cpsschemas_err_image', {}
[2335]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]]
[2336]1929        if self.id_field == "":
1930            student_id = self.getStudentId()
1931        else:
1932            student_id = datastructure[self.id_field]
[2346]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)
[2335]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)
[2354]1972            info= self.getStorageImageInfo(field_id)
[2335]1973            # Remove the file in the filesystem
[2354]1974            if info:
1975                os.remove(info['file_path'])
[2335]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}'
[2356]2003                member_id = str(self.portal_membership.getAuthenticatedMember())
2004                logger.info('%s tried to upload picture with size %dk' %(member_id,int(size)/1000) )
[2335]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:
[2354]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)
[2335]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")
[2355]2032            #fileupload.seek(0)
2033            #import pdb; pdb.set_trace()
2034            pict.write(str(file.data))
[2335]2035            pict.close()
2036        return True
[2354]2037    ###)
[2335]2038
2039    def render(self, mode, datastructure, **kw): ###(
2040        render_method = 'widget_image_render'
2041        meth = getattr(self, render_method, None)
[2342]2042        #import pdb;pdb.set_trace()
[2335]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
[22]2055###########
2056
Note: See TracBrowser for help on using the repository browser.