ReferenceBrowserWidget

from Products.ATContentTypes.interface import IATLink, IATContentType

from Products.PloneArticle.proxy import BaseInnerContentProxy, \
    BaseInnerContentProxySchema
from Products.PloneArticle.interfaces import ILinkInnerContentProxy
from Products.PloneArticle.config import PROJECTNAME

# Defines schema
LinkInnerContentProxySchema = BaseInnerContentProxySchema.copy() + Schema((
    ComputedField(
        'remoteUrl',
        primary=True,
        expression="""context.getPrimaryValue('')""",
        widget=ComputedWidget(
            label='Remote url',
            label_msgid='label_remote_url',
            i18n_domain='plonearticle',
        ),
    ),
    ReferenceField(
        'referencedContent',
        relationship='article_link',
        widget=ReferenceBrowserWidget(
            label='Referenced link',
            label_msgid='label_referenced_link',
            i18n_domain='plonearticle',
        ),
    ),
    StringField(
        'attachedLink',
Пример #2
0
from Products.CMFPlone.utils import safe_unicode
from bika.lims import bikaMessageFactory as _
from bika.lims.browser.widgets import ScheduleInputWidget
from bika.lims.config import PROJECTNAME
from bika.lims.content.bikaschema import BikaSchema
from bika.lims.interfaces import ICancellable
from zope.interface import implements

schema = BikaSchema.copy() + Schema((
    ReferenceField("Instrument",
                   allowed_types=("Instrument", ),
                   relationship="InstrumentScheduledTaskInstrument",
                   widget=StringWidget(visible=False, )),
    ComputedField(
        "InstrumentUID",
        expression=
        "context.getInstrument() and context.getInstrument().UID() or None",
        widget=ComputedWidget(visible=False, ),
    ),
    StringField(
        "Type",
        vocabulary="getTaskTypes",
        widget=ReferenceWidget(
            checkbox_bound=0,
            label=_("Task type", "Type"),
        ),
    ),
    RecordsField(
        "ScheduleCriteria",
        required=1,
        type="schedulecriteria",
        widget=ScheduleInputWidget(label=_("Criteria"), ),
Пример #3
0
    BooleanField("ManualEntryOfResults",
                 default=False,
                 widget=BooleanWidget(
                     label=_("Manual entry of results"),
                     description=_(
                         "The results for the Analysis Services that use "
                         "this method can be set manually"),
                     modes=("edit"),
                 )),

    # Only shown in readonly view. Not in edit view
    ComputedField(
        "ManualEntryOfResultsViewField",
        expression="context.isManualEntryOfResults()",
        widget=BooleanWidget(
            label=_("Manual entry of results"),
            description=_("The results for the Analysis Services that use "
                          "this method can be set manually"),
            modes=("view"),
        ),
    ),

    # Calculations associated to this method. The analyses services
    # with this method assigned will use the calculation selected here.
    UIDReferenceField(
        "Calculation",
        vocabulary="_getCalculations",
        allowed_types=("Calculation", ),
        accessor="getCalculationUID",
        widget=SelectionWidget(
            visible={
                "edit": "visible",
Пример #4
0
schema = ATCTFolder.schema.copy() + Schema((
    StringField(
        'description',
        isMetadata=1,
        accessor='Description',
        widget=TextAreaWidget(
            label='Description',
            label_msgid="label_blogfolder_description",
            description_msgid="help_blogfolder_description",
            i18n_domain="SimpleBlog",
            description='Breve descripción para este folder.'),
    ),
    ComputedField('existingCats',
                  expression='here.getInheritedCategories()',
                  widget=ComputedWidget(
                      label='Existing categories.',
                      label_msgid="label_blogfolder_existing_cats",
                      i18n_domain="SimpleBlog",
                  )),
    LinesField(
        'categories',
        widget=LinesWidget(
            label='Additional categories',
            label_msgid="label_additional_categories",
            description_msgid="help_additional_categories",
            i18n_domain="SimpleBlog",
            description=
            'Supply a list of possible additional categories that will be available to BlogEntries inside this folder or in sub folders.'
        ),
    )))
Пример #5
0
from zope.i18n import translate
from zope.interface import implements

schema = Schema((
    UIDReferenceField(
        'SampleType',
        vocabulary="getSampleTypes",
        allowed_types=('SampleType', ),
        widget=ReferenceWidget(
            checkbox_bound=0,
            label=_("Sample Type"),
        ),
    ),
    ComputedField(
        'SampleTypeTitle',
        expression=
        "context.getSampleType().Title() if context.getSampleType() else ''",
        widget=ComputedWidget(visible=False, ),
    ),
    ComputedField(
        'SampleTypeUID',
        expression=
        "context.getSampleType().UID() if context.getSampleType() else ''",
        widget=ComputedWidget(visible=False, ),
    ),
)) + BikaSchema.copy() + Schema((
    RecordsField(
        'ResultsRange',
        # schemata = 'Specifications',
        required=1,
        type='resultsrange',
        subfields=('keyword', 'min_operator', 'min', 'max_operator', 'max',
Пример #6
0
class Course(ATFolder):
    """
    A Course belongs to a specific Department although it can contain tutorials from any Department.
    A course has a specific code which is used together with the Department code to uniquely identify the Course.
    Students can be enrolled in a Course. A course is implemented as a folder which can contain additional files
corresponding to relevant Literature and has references to the tutorials which belong to it. It also implements
 a list of students which have enrolled in the course. Only registered users of the tutor-web can enroll in a course.
    It is implemented as an ATFolder as well as interfaces, ICourse and IOrderedTutorWebContent. 
    """

    schema = ATFolderSchema.copy() + Schema((
        StringField(
            'title',
            required=True,
            searchable=0,
            default='Course',
            widget=StringWidget(
                label='Title',
                descriptio='Course title',
            ),
        ),
        ReferenceField(
            'Tutorials',
            widget=ReferenceBrowserWidget(
                label="Tutorials",
                description='Tutorials which belong to the course',
                destination=".",
                destination_types=("Tutorial", ),
                allow_sorting=1,
            ),
            multiValued=True,
            relationship='hasTutorial',
            allowed_types=("Tutorial", ),
        ),
        StringField(
            'Students',
            vocabulary='getAvailableStudents',
            widget=InAndOutWidget(
                label='Students',
                description='Students enrolled in the course.',
            ),
        ),
        StringField(
            'Code',
            widget=StringWidget(
                label='Numberic Course Code',
                description=
                'Specify a numberid code which is used to identify the course. For example: 101, 202',
            ),
            required=1,
            validators=('isSameCourseCode', ),
        ),
        ComputedField(
            'numTutorials',
            expression='context.computeNumTutorials()',
            widget=StringWidget(modes=('view', )),
        ),
    ))

    __implements__ = (ATFolder.__implements__)
    implements(ICourse, IOrderedTutorWebContent)
    global_allow = True
    meta_type = 'Course'  # zope type name
    portal_type = meta_type  # plone type name
    archetype_name = 'Course'  # friendly type name
    _at_rename_after_creation = True
    security = ClassSecurityInfo()

    def publishAll(self, typeofobject=None, originalobj=None):
        """publich content"""
        self.tryWorkflowAction("publish", ignoreErrors=True)

    def computeGrades(self, userId):
        """return the grade for a student based on userId"""
        # FIXME, what is userId is not a alid id???
        tutorials = self.getTutorials()
        numtutorials = len(tutorials)
        points = 0.0
        for tut in tutorials:
            points = points + tut.computeGrades(userId)
        if (numtutorials > 0):
            return float(points / numtutorials)
        else:
            return 0.0

    def addUser(self):
        """enroll the logged in user"""
        pm = self.portal_membership
        memberId = pm.getAuthenticatedMember().getId()
        member = pm.getMemberById(memberId)
        userfull = member.getProperty('fullname')

        pair = []
        pair.append((userfull, memberId))
        # should check if already enrolled
        studs = self.getStudents()
        if (type(studs) == type('itsastring')):
            l = []
            l.append(studs)
            l.append(memberId)
            self.getField('Students').set(self, l)
        else:
            studs.append(memberId)
            self.getField('Students').set(self, studs)

    def getEnrolledStudents(self):
        """return all enrolled students"""
        stud = self.getStudents()
        if (type(stud) == type('itsastring')):
            l = []
            l.append(stud)
            return l
        else:
            return self.getStudents()

    def getAvailableStudents(self):
        """return all registered members of the tutor-web"""
        # FIXME this could be far too big a list to be return in one go
        # needs to return only partly
        pm = self.portal_membership
        pair = []
        for memberId in pm.listMemberIds():
            member = pm.getMemberById(memberId)
            userfull = member.getProperty('fullname')
            pair.append((memberId, userfull))
        return DisplayList(pair)

    def getAvailableStudents2(self):
        """return all registered users of the tutor-web"""
        pm = self.portal_membership
        results = pm.listMembers()
        pair = []
        for r in results:
            pair.append((r.UID, r.Title))
        return DisplayList(pair)

    def getAvailableStudents1(self):
        """return all registered members of the tutor-web"""
        memb = self.portal_membership
        portal_users = getToolByName(self, "acl_users")
        membership = getToolByName(self, 'portal_membership')

        #Beware if hundreds of students this is very expensive!
        # need to use search tool
        results = membership.listMembers()
        numstuds = str(len(results))

        for r in results:
            r1 = r.getUser()
            userid = r1.getId()
            userfull1 = membership.getMemberById(userid)
            userfull = userfull1.getProperty('fullname')

        pair = []

        for c in results:
            r = c.getUser()
            pair.append((r.getUserName(), r.getId()))
        return DisplayList(pair)

    def portalUrl(self):
        """Return the url of the site which the course belongs to """
        portal = getToolByName(self, 'portal_url').getPortalObject()
        return portal

    def isLoggedOn(self):
        """True of user has logged in to the tutor-web else Fase"""
        mtool = getToolByName(self, 'portal_membership')
        if mtool.isAnonymousUser():
            return False
        else:
            return True

    def getCourseCode(self):
        return self.getCode()

    security.declarePrivate('initializeObject')

    def initializeObject(self):
        """Called after course has been created for the first time, publish course
        and reorder department objects"""
        self.tryWorkflowAction("publish", ignoreErrors=True)
        parent = aq_parent(self)

        try:
            parent.orderObjects("id")
            parent.plone_utils.reindexOnReorder(parent)
        except:
            raise 'Failed to create course ' + self.getTitle(
            ) + ' not able to reorder courses'

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        """try to change actions for course"""
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        if wf.isActionSupported(self, action):
            if comment is None:
                #userId = getSecurityManager().getUser().getId()
                comment = 'State changed'
            wtool.doActionFor(self, action, comment=comment)
        elif not ignoreErrors:
            raise TypeError('Unsupported workflow action %s for object %s.' %
                            (repr(action), repr(self)))

    def canSeeQuestions(self):
        """if current user has the role of a manager, editor, owner or belongs to the group: teacher
        then return True else False"""
        try:
            user = getSecurityManager().getUser()
            groups = user.getGroups()
            if (user.has_role('Manager')):
                return True
            elif (user.has_role('Editor')):
                return True
            elif (user.has_role('Owner')):
                return True
            elif ('teacher' in groups):
                return True
            else:
                return False
        except:
            '''could not establish who user is'''
            return False

    def generateNewId(self):
        """Suggest an id for this object based on Department code and Course code.
        This id is used when automatically renaming an object after creation.
        """
        parent = aq_parent(self)

        title = (parent.getCode() + self.getCode()).strip()
        # Can't work w/o a title
        if not title:
            return None

        # Don't do anything without the plone.i18n package
        if not URL_NORMALIZER:
            return None

        if not isinstance(title, unicode):
            charset = self.getCharset()
            title = unicode(title, charset)

        request = getattr(self, 'REQUEST', None)
        if request is not None:
            return IUserPreferredURLNormalizer(request).normalize(title)

        return queryUtility(IURLNormalizer).normalize(title)

    security.declareProtected(View, 'computeNumTutorials')

    def computeNumTutorials(self):
        """find number of tutorials which belong to this course"""
        refs = self.getRawTutorials()
        return len(refs)

    def updateSlideMaterial(self):
        """Update all slides for every tutorial/lecture belonging to the course."""
        tuts = self.getTutorials()
        for tut in tuts:
            tmp = tut.updateSlideMaterial()

    def getFullName(self, userid):
        """Return the full name of a user based on given id"""
        # FIXME what if id is not valid???
        if PLONE_VERSION == 3:

            ecq_tool = getToolByName(self, 'ecq_tool')
            return ecq_tool.getFullNameById(userid)
        else:
            parent = aq_parent(self)
            return parent.getFullName(userid)
Пример #7
0
    ),
    DateTimeField('DateDispatched',
                  widget=DateTimeWidget(
                      label=_("Date Dispatched"),
                      ),
                  ),
    TextField(
        "Remarks",
        allowable_content_types=("text/plain",),
        widget=TextAreaWidget(
            label=_("Remarks"),
        )
    ),
    ComputedField('ClientUID',
                  expression = 'here.aq_parent.UID()',
                  widget = ComputedWidget(
                      visible=False,
                      ),
                  ),
    ComputedField('ProductUID',
                  expression = 'context.getProductUIDs()',
                  widget = ComputedWidget(
                      visible=False,
                      ),
                  ),
),
)

schema['title'].required = False

class SupplyOrderLineItem(PersistentMapping):
    pass
            label='Transaction PST',
            description=
            'Please input the transaction PST. (NOT available after July, 2010)',
            size=8,
            thousands_commas=True,
            dollars_and_cents=True,
        ),
    ),

    # transaction total
    ComputedField(
        'bk_transaction_total',
        searchable=False,
        required=False,
        expression='context.transactionTotal()',
        widget=ComputedWidget(
            label='Transaction Total',
            description=
            'Please input the transaction PST. (NOT available after July, 2010)',
        ),
    ),

    # TODO: image field for the receipt / invoice
))

finalizeATCTSchema(BKTransactionSchema)

# move around the fields.


# define the content type class.
Пример #9
0
from Products.ATContentTypes.interface import IImageContent

from Products.PloneArticle import LOG
from Products.PloneArticle.proxy import BaseFileContentProxy, \
    BaseInnerContentProxySchema
from Products.PloneArticle.interfaces import IImageInnerContentProxy, IBaseInnerContentProxy
from Products.PloneArticle.config import PLONEARTICLE_TOOL, PROJECTNAME


# Defines schema
ImageInnerContentProxySchema = BaseInnerContentProxySchema.copy() + Schema((
    ComputedField(
        'image',
        primary=True,
        expression="""context.getPrimaryValue('image', 'attachedImage', '')""",
        widget=ComputedWidget(
            label='Image',
            label_msgid='label_image',
            i18n_domain='plonearticle',
            ),
        ),
    ReferenceField(
        'referencedContent',
        relationship='article_image',
        keepReferencesOnCopy=True,
        widget=ReferenceBrowserWidget(
            label='Referenced image',
            label_msgid='label_referenced_image',
            i18n_domain='plonearticle',
            ),
        ),
    ImageField(
Пример #10
0
        ),
    ),

    StringField(
        "Surname",
        required=1,
        widget=StringWidget(
            label=_("Surname"),
        ),
    ),

    ComputedField(
        "Fullname",
        expression="context.getFullname()",
        searchable=1,
        widget=ComputedWidget(
            label=_("Full Name"),
            visible={"edit": "invisible", "view": "invisible"},
        ),
    ),

    StringField(
        "Username",
        widget=StringWidget(
            visible=False
        ),
    ),

    StringField(
        "EmailAddress",
        schemata="Email Telephone Fax",
import zLOG

schema = BaseSchema + Schema((
    StringField('moduleId',
                required=0,
                searchable=0,
                default='',
                widget=CompactStringWidget(modes=('view',),
                                           label="Module ID",
                                           i18n_domain="rhaptos"),
                #validators=('isModuleNumber',),
                ),
    ComputedField('repositoryLocation',
                searchable=0,
                expression='context.moduleLocation()',
                widget=URLWidget(modes=('view',),
                                 label=('Published Location'),
                                 i18n_domain="rhaptos"),
                ),
    ComputedField('moduleTitle',
                searchable=0,
                expression='context.getContent().title',
                widget=CompactStringWidget(label="Module Title",
                                           modes=('view',),
                                           i18n_domain="rhaptos"),
                ),
    VersionField('version',
                required=1,
                searchable=0,
                vocabulary='moduleVersions',
                widget=VersionWidget(modes=('edit',),
from Products.ATContentTypes.content.folder import ATFolderSchema
from Products.ATContentTypes.lib.autosort import AutoOrderSupport
from Products.ATContentTypes.interfaces import IATFolder
from Products.RhaptosWorkgroup.interfaces import IWorkgroup
from zope.interface import implements

try:
    from Products.CMFBoardTab.config import forumname
except ImportError:
    forumname = None

ATWGSchema = ATFolderSchema.copy() + Schema((
    ComputedField('title',
                  expression="context._getWorkgroupProperty('title')",
                  searchable=True,
                  accessor='Title',
                  widget=StringWidget(label="Title",
                                      label_msgid="label_title",
                                      i18n_domain="plone")),
    ComputedField('email',
                  expression="context._getWorkgroupProperty('email')",
                  searchable=True,
                  languageIndependent=True,
                  widget=StringWidget(
                      description_msgid="help_description",
                      description="Email address for the group.",
                      label="Email",
                      label_msgid="label_email",
                      i18n_domain="rhaptos")),
    ComputedField('description',
                  expression="context._getWorkgroupProperty('description')",
Пример #13
0
    FixedPointField('AnalysisProfileVAT',
        schemata = "Accounting",
        default = '14.00',
        widget = DecimalWidget(
            label=_("VAT %"),
            description=_(
                "Enter percentage value eg. 14.0. This percentage is applied on the Analysis Profile only, overriding "
                "the systems VAT"),
                visible={'view': 'visible', 'edit': 'visible'},
        )
    ),
    # This VAT amount is computed using the AnalysisProfileVAT instead of systems VAT
    ComputedField('VATAmount',
        schemata="Accounting",
        expression='context.getVATAmount()',
        widget=ComputedWidget(
            label = _("VAT"),
            visible={'view': 'visible', 'edit': 'invisible'},
            ),
    ),
    ComputedField('TotalPrice',
          schemata="Accounting",
          expression='context.getTotalPrice()',
          widget=ComputedWidget(
              label = _("Total price"),
              visible={'edit': 'hidden', }
          ),
    ),
)
                                    )
schema['title'].widget.visible = True
schema['description'].widget.visible = True
Пример #14
0
                            required=0,
                            vocabulary_display_path_bound=sys.maxint,
                            vocabulary='_getAvailableInstrumentsDisplayList',
                            allowed_types=('Instrument',),
                            relationship='AnalysisServiceInstrument',
                            referenceClass=HoldingReference,
                            widget=SelectionWidget(
                                format='select',
                                label=_('Default Instrument')
                            ),
 ),
 # Returns the Default's instrument title. If no default instrument
 # set, returns string.empty
 ComputedField('InstrumentTitle',
               expression="context.getInstrument() and context.getInstrument().Title() or ''",
               widget=ComputedWidget(
                   visible=False,
               ),
 ),
 # Manual methods associated to the AS
 # List of methods capable to perform the Analysis Service. The
 # Methods selected here are displayed in the Analysis Request
 # Add view, closer to this Analysis Service if selected.
 # Use getAvailableMethods() to retrieve the list with methods both
 # from selected instruments and manually entered.
 # Behavior controlled by js depending on ManualEntry/Instrument:
 # - If InstrumentEntry checked, hide and unselect
 # - If InsrtumentEntry not checked, show
 # See browser/js/bika.lims.analysisservice.edit.js
 ReferenceField('Methods',
     schemata = "Method",
     required = 0,
Пример #15
0
class Class(ATFolder):
    """
    A Course belongs to a specific Department although it can contain tutorials from any Department.
    A course has a specific code which is used together with the Department code to uniquely identify the Course.
    Students can be enrolled in a Course. A course is implemented as a folder which can contain additional files
corresponding to relevant Literature and has references to the tutorials which belong to it. It also implements
 a list of students which have enrolled in the course. Only registered users of the tutor-web can enroll in a course.
    It is implemented as an ATFolder as well as interfaces, ICourse and IOrderedTutorWebContent. 
    """

    schema = ATFolderSchema.copy() + Schema((
        StringField(
            'title',
            required=True,
            searchable=0,
            default='Class name',
            widget=StringWidget(
                label='Title',
                description='Class name',
            ),
            validators=('isSameClassName', ),
        ),
        StringField(
            'classDatabaseId',
            widget=StringWidget(
                label="Database Id",
                visible={
                    'edit': 'invisible',
                    'view': 'invisible'
                },
            ),
        ),
        ReferenceField(
            'Tutorials',
            widget=ReferenceBrowserWidget(
                label="Tutorials",
                description='Tutorials which belong to the class',
                destination=".",
                destination_types=("Tutorial", ),
                allow_sorting=1,
            ),

            #allow_sorting=1,
            multiValued=True,
            relationship='hasTutorial',
            allowed_types=("Tutorial", ),
        ),
        StringField(
            'Students',
            vocabulary='getAvailableStudents',
            widget=InAndOutWidget(
                label='Students',
                description='Students enrolled in the course.',
                visible={
                    'edit': 'invisible',
                    'view': 'invisible'
                },
            ),
        ),
        StringField(
            'Instructor',
            #vocabulary='getAvailableStudents',
            default='',
            widget=StringWidget(
                label='Instructor',
                description='Instructor of the class.',
            ),
        ),
        StringField(
            'ContactInformation',
            #vocabulary='getAvailableStudents',
            default='',
            widget=StringWidget(
                label='Contact Information',
                description='How to contact instructor of the class.',
            ),
        ),
        ComputedField(
            'numTutorials',
            expression='context.computeNumTutorials()',
            widget=StringWidget(modes=('view', )),
        ),
    ))

    __implements__ = (ATFolder.__implements__)
    implements(IClass)
    global_allow = True
    meta_type = 'Class'  # zope type name
    portal_type = meta_type  # plone type name
    archetype_name = 'Class'  # friendly type name
    _at_rename_after_creation = True
    security = ClassSecurityInfo()

    def publishAll(self, typeofobject=None, originalobj=None):
        """publich content"""
        self.tryWorkflowAction("publish", ignoreErrors=True)

    def computeGrades(self, userId):
        """return the grade for a student based on userId"""
        # FIXME, what is userId is not a valid id???
        tutorials = self.getTutorials()
        numtutorials = len(tutorials)
        points = 0.0
        for tut in tutorials:
            points = points + tut.computeGrades(userId)
        if (numtutorials > 0):
            return float(points / numtutorials)
        else:
            return 0.0

    def addUser(self):
        """enroll the logged in user"""
        pm = self.portal_membership
        memberId = pm.getAuthenticatedMember().getId()
        member = pm.getMemberById(memberId)
        userfull = member.getProperty('fullname')

        pair = []
        pair.append((userfull, memberId))
        # should check if already enrolled
        studs = self.getStudents()
        if (memberId in studs):
            return userfull + "already enrolled in " + self.getTitle()
        if (type(studs) == type('itsastring')):
            l = []
            l.append(studs)
            l.append(memberId)
            self.getField('Students').set(self, l)
        else:
            studs.append(memberId)
            self.getField('Students').set(self, studs)
        updated = self.updateDatabase(member, memberId)

        if updated:
            tit = self.getTitle()
            if not isinstance(tit, unicode):
                charset = self.getCharset()
                tit = unicode(tit, charset)

            return userfull + " has been enrolled in " + tit
        else:
            return "could not update database"
        ##return "bla"
    def updateDatabase(self, member, candidateId):
        #start by checking if student already registered in tutorweb
        # has been allocated a random number, if not register
        # then add to database if needed.

        portal_catalog = getToolByName(self, 'portal_catalog')

        students = portal_catalog.unrestrictedSearchResults(
            {'portal_type': 'StudentList'})

        if (len(students) > 0):

            numlists = str(len(students))

            objid = self.unrestrictedTraverse(str(students[0].getPath()), None)

            ranid = objid.addStudent(candidateId)

            studlocator = getUtility(IStudentLocator)
            studentinfo = studlocator.student_by_randomnumber(ranid)
            if (not studentinfo):
                '''student has not been added database'''
                email = 'not known'
                firstname = ''
                familyname = ''
                loginname = ''
                #membership = self.portal_membership
                #member = membership.getAuthenticatedMember()
                if member:
                    loginname = member.getUserName()
                    email = member.getProperty('email')
                    fullname = member.getProperty('fullname')
                    tempname = fullname.split()
                    if (len(tempname) > 1):
                        familyname = tempname[1]
                        firstname = tempname[0]
                    elif (len(tempname) == 1):
                        familyname = fullname

                #NB: Code is being migrated to tutorweb.quiz
                #student = StudentInformation(candidateId, ranid, firstname, familyname, email)
                #student.addToDataBase()
            # now find the student just added
            studentinfo = studlocator.student_by_randomnumber(ranid)
            # now find classinfo
            classlocator = getUtility(IClassLocator)
            # should check if databaseid is not empty string
            classinfo = classlocator.class_by_id(int(
                self.getClassDatabaseId()))
            #check if have date
            start = self.getEffectiveDate()
            stop = self.getExpirationDate()
            # maybe should set default values in initialize
            try:
                '''check if start has been set'''
                i = len(start)
            except:
                start = 0
            try:
                '''check if stop has been set'''
                i = len(stop)
            except:
                stop = 0
            #NB: Code is being migrated to tutorweb.quizdb
            #registration = ClassRegistrationInformation(studentinfo, classinfo, start, stop)
            #registration.addToDataBase()
            return True
        else:
            return False

    def getEnrolledStudents(self):
        """return all enrolled students"""
        stud = self.getStudents()
        if (type(stud) == type('itsastring')):
            l = []
            l.append(stud)
            sortedlist = l.sort()
            return sortedlist
        else:
            sortedlist = self.getStudents().sort()
            return self.getStudents().sort()

    def getInstructors(self):
        """return all instructors"""
        stud = self.getInstructor()
        if (type(stud) == type('itsastring')):
            l = []
            l.append(stud)
            return l
        else:
            return stud

    def getAvailableStudents(self):
        """return all registered members of the tutor-web"""
        # FIXME this could be far too big a list to be return in one go
        # needs to return only partly
        pm = self.portal_membership
        pair = []
        for memberId in pm.listMemberIds():
            member = pm.getMemberById(memberId)
            userfull = member.getProperty('fullname')
            pair.append((memberId, userfull))
        return DisplayList(pair)

    def getAvailableStudents2(self):
        """return all registered users of the tutor-web"""
        pm = self.portal_membership
        results = pm.listMembers()
        pair = []
        for r in results:
            pair.append((r.UID, r.Title))
        return DisplayList(pair)

    def getAvailableStudents1(self):
        """return all registered members of the tutor-web"""
        memb = self.portal_membership
        portal_users = getToolByName(self, "acl_users")
        membership = getToolByName(self, 'portal_membership')

        #Beware if hundreds of students this is very expensive!
        # need to use search tool
        results = membership.listMembers()
        numstuds = str(len(results))

        for r in results:
            r1 = r.getUser()
            userid = r1.getId()
            userfull1 = membership.getMemberById(userid)
            userfull = userfull1.getProperty('fullname')

        pair = []

        for c in results:
            r = c.getUser()
            pair.append((r.getUserName(), r.getId()))
        return DisplayList(pair)

    def portalUrl(self):
        """Return the url of the site which the class belongs to """
        portal = getToolByName(self, 'portal_url').getPortalObject()
        return portal

    def isLoggedOn(self):
        """True of user has logged in to the tutor-web else Fase"""
        mtool = getToolByName(self, 'portal_membership')
        if mtool.isAnonymousUser():
            return False
        else:
            return True

    security.declarePrivate('initializeObject')

    def initializeObject(self):
        """Called after class has been created for the first time."""
        self.tryWorkflowAction("publish", ignoreErrors=True)
        '''add school to database when school is created'''
        # get correctschoolinformation
        parent = aq_parent(self)
        #schoollocator = getUtility(ISchoolLocator)
        #schoolinformation = schoollocator.school_by_id(int(parent.getDatabaseId()))
        # set char set might have for example icelandic letters in title
        tit = self.getTitle()
        if not isinstance(tit, unicode):
            charset = self.getCharset()
            tit = unicode(tit, charset)
            self.setTitle(tit)
        email = self.getContactInformation()
        if not isinstance(email, unicode):
            charset = self.getCharset()
            email = unicode(email, charset)
            self.setTitle(email)

        # create class and add to database
        #NB: This is knobbled for now, as code migrates to tutorweb.quizdb
        #myclass = ClassInformation(schoolinformation, tit, email)
        #myclass.addToDataBase()
        #add database id
        #self.setClassDatabaseId(str(myclass.class_id))

        parent = aq_parent(self)

        try:
            parent.orderObjects("id")
            parent.plone_utils.reindexOnReorder(parent)
        except:
            raise 'Failed to create class ' + self.getTitle(
            ) + ' not able to reorder classes'

    def editedObject(self, objtype=None):
        '''if class name changed, change also in database'''
        # Need to make sure that class name is unique before
        # looking for class by name - have added a validator
        # first get handle on the school from sql
        # well if copy/paste school then the title will not change

        #classlocator = getUtility(IClassLocator)
        #classlocator.updateName(self.getClassDatabaseId(), self.getTitle(), self.getContactInformation())
        tit = self.getTitle()
        if not isinstance(tit, unicode):
            charset = self.getCharset()
            tit = unicode(tit, charset)
            self.setTitle(tit)
        # set char set
        email = self.getContactInformation()
        if not isinstance(email, unicode):
            charset = self.getCharset()
            email = unicode(email, charset)
            self.setContactInformation(email)

        classlocator = getUtility(IClassLocator)

        classlocator.updateName(self.getClassDatabaseId(), tit, email)

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        """try to change actions for class"""
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        if wf.isActionSupported(self, action):
            if comment is None:
                #userId = getSecurityManager().getUser().getId()
                comment = 'State changed'
            wtool.doActionFor(self, action, comment=comment)
        elif not ignoreErrors:
            raise TypeError('Unsupported workflow action %s for object %s.' %
                            (repr(action), repr(self)))

    def canSeeQuestions(self):
        """if current user has the role of a manager, editor, owner or belongs to the group: teacher
        then return True else False"""
        try:
            user = getSecurityManager().getUser()
            groups = user.getGroups()
            if (user.has_role('Manager')):
                return True
            elif (user.has_role('Editor')):
                return True
            elif (user.has_role('Owner')):
                return True
            elif ('teacher' in groups):
                return True
            else:
                return False
        except:
            '''could not establish who user is'''
            return False

    security.declareProtected(View, 'computeNumTutorials')

    def computeNumTutorials(self):
        """find number of tutorials which belong to this class"""
        refs = self.getRawTutorials()
        return len(refs)

    def updateSlideMaterial(self):
        """Update all slides for every tutorial/lecture belonging to the class."""
        tuts = self.getTutorials()
        for tut in tuts:
            tmp = tut.updateSlideMaterial()

    def getFullName(self, userid):
        """Return the full name of a user based on given id"""
        # FIXME what if id is not valid???
        if PLONE_VERSION == 3:
            ecq_tool = getToolByName(self, 'ecq_tool')
            return ecq_tool.getFullNameById(userid)
        else:
            parent = aq_parent(self)
            return parent.getFullName(userid)
Пример #16
0
         label=_("Sample Point"),
         description=_("Location where sample is collected"),
         visible={
             "edit": "visible",
             "view": "visible",
             "add": "visible",
             "secondary": "invisible",
         },
         catalog_name="bika_setup_catalog",
         base_query={"is_active": True},
         showOn=True,
     ),
 ),
 ComputedField(
     "SamplePointUID",
     expression=
     "context.Schema()['SamplePoint'].get(context) and context.Schema()['SamplePoint'].get(context).UID() or ''",
     widget=ComputedWidget(visible=False, ),
 ),
 ReferenceField(
     "SampleType",
     vocabulary_display_path_bound=sys.maxint,
     allowed_types=("SampleType", ),
     relationship="ARTemplateSampleType",
     referenceClass=HoldingReference,
     accessor="getSampleType",
     edit_accessor="getSampleType",
     mutator="setSampleType",
     widget=ReferenceWidget(
         label=_("Sample Type"),
         description=_("Create a new sample of this type"),
         visible={
Пример #17
0
contentIddesc = ""
contentId = StringField(
    'contentId',
    required=1,
    searchable=0,
    default='',
    widget=StringWidget(label="Content Id",
                        description=contentIddesc,
                        i18n_domain="rhaptos"),
    #validators=('isModuleNumber',),
)

title = ComputedField(
    'title',
    accessor="Title",
    searchable=0,
    expression='context.computedTitle()',
    widget=StringWidget(label="Title", modes=('view', ),
                        i18n_domain="rhaptos"),
)

# TODO: we have a VersionField...
versionStartdesc = ""
versionStart = TupleVersionField(
    'versionStart',
    required=0,
    searchable=0,
    index=
    "lens_catalog/FieldIndex:brains",  # indexes tuple of int, which is orderable, so we can select ranges
    default_method='currentVersion',
    vocabulary='moduleVersions',
    enforce_vocabulary=1,