source: WAeUP_SRP/base/Widgets.py @ 2345

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

some fixes in Widgets.py and in application_pde.xml

DateTime? Widgets must never been required!

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