class ContentTypeExtender(object):
    adapts(IATContentType)
    implements(ISchemaExtender, IBrowserLayerAwareExtender)
    layer = ICollectiveCarouselLayer

    _fields = [
        CarouselProviderField("carouselprovider",
            schemata = "settings",
            # the field accepts Collections only atm.
            # Would be cool to have ATRBW to be able to select items by
            # interface with something like 'allowed_interfaces'
            allowed_types = ('Topic', 'Collection',),
            relationship = 'Carousel',
            languageIndependent = True,
            multiValued = True,
            widget = ReferenceBrowserWidget(
                label = _(u"label_carouselprovider_title",
                    default=u"Carousel object."),
                description = _(u"help_carouselprovider",
                    default=u"Object providing items (content) for carousel."),
                ),
            ),
        ]

    def __init__(self, context):
        self.context = context

    def getFields(self):
        return self._fields
예제 #2
0
class FolderPrenotazioniExtender(object):
    adapts(IPrenotazioniFolder)
    implements(ISchemaExtender, IBrowserLayerAwareExtender)
    layer = ICciaapdContenttypesLayer

    _fields = [
        CustomReferenceField(
            "relatedItems",
            schemata="categorization",
            relationship='relatesTo',
            multiValued=True,
            isMetadata=True,
            languageIndependent=False,
            index='KeywordIndex',
            referencesSortable=True,
            keepReferencesOnCopy=True,
            write_permission=ModifyPortalContent,
            widget=ReferenceBrowserWidget(
                allow_search=True,
                allow_browse=True,
                allow_sorting=True,
                show_indexes=False,
                force_close_on_insert=True,
                label=atct_mf(
                    u'label_related_items', default=u'Related Items'
                ),
                description='',
                visible={'edit': 'visible', 'view': 'invisible'},
            ),
        )
    ]

    def __init__(self, context):
        self.context = context

    def getFields(self):
        return self._fields
예제 #3
0
class ContentTypeExtender(object):
    adapts(IATContentType)
    implements(ISchemaExtender, IBrowserLayerAwareExtender)
    layer = ICciaapdContenttypesLayer

    _fields = [
        CustomReferenceField(
            "related_office",
            schemata="categorization",
            allowed_types=('Ufficio'),
            relationship='to_office',
            languageIndependent=True,
            multiValued=True,
            widget=ReferenceBrowserWidget(
                label=_(u"label_related_office", default=u"Related office")
            ),
        )
    ]

    def __init__(self, context):
        self.context = context

    def getFields(self):
        return self._fields
예제 #4
0
     widget=atapi.SelectionWidget(
         label="Type",
         description=
         "Describe correctly the type of comment. Different types will be visible for different users.",
         label_msgid="gcommons_comment_type",
         description_msgid="gcommons_help_comment_type",
     ),
     required=True,
     vocabulary="getCommentTypesVocabulary",
     searchable=True),
 atapi.ReferenceField('refDraft',
                      relationship='refDraft',
                      multiValued=False,
                      default_method='getDefaultRefDraft',
                      widget=ReferenceBrowserWidget(visible={
                          'edit': 'invisible',
                          'view': 'visible'
                      })),
 atapi.TextField(
     'text',
     required=False,
     searchable=True,
     primary=True,
     storage=atapi.AnnotationStorage(),
     validators=('isTidyHtmlWithCleanup', ),
     default_output_type='text/x-html-safe',
     widget=atapi.RichWidget(
         description='',
         label=_(u'label_body_text', default=u'Body Text'),
         rows=25,
         allow_file_upload=True,
     ),
예제 #5
0
 inverse_relation_description=
 "Politicas de Negocio de las que se deriva la Regla de Negocio",
 description=
 "Reglas de Negocio que refinan la Politica de Negocio en terminos decidibles.",
 relationship='BPDReglasDeNegocioDerivadas',
 inverse_relation_field_name='politicasDeNegocioBase',
 inverse_relation_label2="Base Business Policies",
 label2="Derived Business Rules",
 inverse_relation_description2=
 "Business Policies that are the basis of the Business Rule",
 widget=ReferenceBrowserWidget(
     label="Reglas de Negocio derivadas",
     label2="Derived Business Rules",
     description=
     "Reglas de Negocio que refinan la Politica de Negocio en terminos decidibles.",
     description2="Business Rules derived from the Business Policy.",
     label_msgid=
     'gvSIGbpd_BPDPoliticaDeNegocio_rel_reglasDeNegocioDerivadas_label',
     description_msgid=
     'gvSIGbpd_BPDPoliticaDeNegocio_rel_reglasDeNegocioDerivadas_help',
     i18n_domain='gvSIGbpd',
 ),
 write_permission='Modify portal content',
 label="Reglas de Negocio derivadas",
 description2="Business Rules derived from the Business Policy.",
 multiValued=1,
 deststyle=
 "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
 containment="Unspecified",
 inverse_relationship='BPDPoliticasDeNegocioBase',
 owner_class_name="BPDPoliticaDeNegocio",
 dependency_supplier=True),
예제 #6
0
from Products.ATBackRef.BackReferenceField import BackReferenceField, BackReferenceWidget
from Products.UWOshMusicRecruiting.config import *

##code-section module-header #fill in your manual code here
##/code-section module-header

copied_fields = {}
copied_fields['title'] = BaseSchema['title'].copy()
copied_fields['title'].widget.label = "Name"
schema = Schema((
    copied_fields['title'],
    ReferenceField(
        name='visits',
        widget=ReferenceBrowserWidget(
            label='Visits',
            label_msgid='UWOshMusicRecruiting_label_visits',
            i18n_domain='UWOshMusicRecruiting',
        ),
        allowed_types=('Visit', ),
        multiValued=1,
        relationship='school_visit',
    ),
), )

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

School_schema = BaseSchema.copy() + \
    schema.copy()

##code-section after-schema #fill in your manual code here
예제 #7
0
from Products.LinguaPlone import permissions

from slc.seminarportal import seminarportalMessageFactory as _
from slc.seminarportal.config import PROJECTNAME
from slc.seminarportal.interfaces import ISpeech

SpeechSchema = atapi.OrderedBaseFolderSchema.copy() + ATEventSchema.copy() + \
               atapi.Schema((
    RelationField(
        name='speakers',
        widget=ReferenceBrowserWidget(
            label=_(u"label_speech_speakers", default=u'Speaker(s)'),
            base_query={'portal_type': 'SPSpeaker',
                        'sort_on': 'getSortableName'},
            allow_browse=1,
            allow_search=1,
            show_results_without_query=1,
            image_portal_types=('SPSpeaker',),
            image_method='image_icon',
            macro='seminarportal_referencebrowser',
        ),
        languageIndependent=True,
        allowed_types=('SPSpeaker',),
        multiValued=1,
        relationship='speech_speakers',
    ),
))

SpeechSchema['description'].widget.label = \
    _(u'label_abstract', default=u'Abstract')
SpeechSchema['description'].widget.description = \
예제 #8
0
     inverse_relation_description=
     "Envios que se destinan a este Perfil o Unidad Organizacional.",
     description=
     "Perfiles o Unidades Organizacionales a los que se destina el Envio.",
     relationship='BPDDestinatarios',
     inverse_relation_field_name='destinatarioDeEnvios',
     inverse_relation_label2="Receiver of Send steps",
     label2="Receivers",
     inverse_relation_description2=
     "Send process steps addressed to this participant Profile or Organisational Unit.",
     widget=ReferenceBrowserWidget(
         label="Destinatarios",
         label2="Receivers",
         description=
         "Perfiles o Unidades Organizacionales a los que se destina el Envio.",
         description2=
         "Participant Profiles or Organisational Units to whom this is Sent",
         label_msgid='gvSIGbpd_BPDEnvio_rel_destinatarios_label',
         description_msgid='gvSIGbpd_BPDEnvio_rel_destinatarios_help',
         i18n_domain='gvSIGbpd',
     ),
     label="Destinatarios",
     description2=
     "Participant Profiles or Organisational Units to whom this is Sent",
     multiValued=1,
     containment="Unspecified",
     inverse_relationship='BPDDestinatarioDeEnvios',
     owner_class_name="BPDEnvio",
     deststyle=
     "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;"),
 ComputedField(
예제 #9
0
 inverse_relation_description=
 "Escenario para el que se definen los conjuntos de valores.",
 description=
 "Casos de Prueba definiendo conjuntos de valores concretos para el Escenario contenedor.",
 relationship='CasosDePrueba_Escenario',
 inverse_relation_field_name='casosDePrueba',
 inverse_relation_label2="Scenario",
 label2="Test Cases",
 inverse_relation_description2=
 "Scenario for which concreate value sets are defined.",
 widget=ReferenceBrowserWidget(
     label="Casos de Prueba",
     label2="Test Cases",
     description=
     "Casos de Prueba definiendo conjuntos de valores concretos para el Escenario contenedor.",
     description2=
     "Test Cases defining concrete data sets of values for the container Scenario.",
     label_msgid='gvSIGbpd_BPDCasoDePrueba_rel_escenario_label',
     description_msgid='gvSIGbpd_BPDCasoDePrueba_rel_escenario_help',
     i18n_domain='gvSIGbpd',
 ),
 write_permission='Modify portal content',
 label="Casos de Prueba",
 description2=
 "Test Cases defining concrete data sets of values for the container Scenario.",
 multiValued=0,
 deststyle=
 "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
 containment="Unspecified",
 inverse_relationship='Escenario_CasosDePrueba',
 owner_class_name="BPDCasoDePrueba",
예제 #10
0
        read_only="True",
        scale="0",
        label="Identificador del elemento de Control del Progreso",
        length="0",
        containment="Not Specified",
        position="3",
        owner_class_name="TRAContribuciones"
    ),

    ComputedField(
        name='elementoProgreso',
        widget=ReferenceBrowserWidget(
            label="Elemento de Progreso y Resultados",
            label2="Progress and Results element",
            description="Elemento para control del Progreso de la creacion del informe y almacenamiento de los resultados durante el proceso.",
            description2="Element to control the Progress of the report process, and storage of import results during the process.",
            label_msgid='gvSIGi18n_TRAContribuciones_attr_elementoProgreso_label',
            description_msgid='gvSIGi18n_TRAContribuciones_attr_elementoProgreso_help',
            i18n_domain='gvSIGi18n',
        ),
        description="Elemento para control del Progreso de la creacion del informe y almacenamiento de los resultados durante el proceso.",
        duplicates="0",
        label2="Progress and Results element",
        ea_localid="2075",
        derived="0",
        precision=0,
        collection="false",
        styleex="volatile=0;",
        description2="Element to control the Progress of the report process, and storage of import results during the process.",
        ea_guid="{7345AAE8-084E-4649-B4F8-B9E7F7E5765D}",
        allowed_types=['TRAProgreso'],
예제 #11
0
    "Elementos del Proceso de Negocio para los que se definen Datos de Prueba en el Caso de Prueba.",
    description=
    "Datos de Pruebas definidos para este elemento de proceso en varios Casos de Pruebas.",
    relationship='ElementosProceso_DatosDePrueba',
    inverse_relation_field_name='datosDePruebas',
    sourcestyle=
    "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
    label2="Test Data",
    inverse_relation_description2=
    "Business Process elements for which Test Data is defined in the Test Case.",
    widget=ReferenceBrowserWidget(
        label="Datos de Pruebas",
        label2="Test Data",
        description=
        "Datos de Pruebas definidos para este elemento de proceso en varios Casos de Pruebas.",
        description2=
        "Test Data defined for this process element in various Test Cases.",
        label_msgid='gvSIGbpd_BPDDatosDePrueba_rel_elementosDeProceso_label',
        description_msgid=
        'gvSIGbpd_BPDDatosDePrueba_rel_elementosDeProceso_help',
        i18n_domain='gvSIGbpd',
    ),
    label="Datos de Pruebas",
    description2=
    "Test Data defined for this process element in various Test Cases.",
    multiValued=1,
    inverse_relation_label2="Process Elements",
    inverse_relationship='DatosDePrueba_ElementosProceso',
    write_permission='Modify portal content',
    additional_columns=[]), ), )

##code-section after-local-schema #fill in your manual code here
예제 #12
0
    StringField(
        name='VATNumber',
        widget=StringWidget(
            label='VAT number',
            label_msgid='TKContactManager_label_VATNumber',
            i18n_domain='TKContactManager',
        ),
        schemata="Organisation Details",
    ),

    RelationField(
        name='client',
        widget=ReferenceBrowserWidget(
            label='Client',
            label_msgid='TKContactManager_label_client',
            i18n_domain='TKContactManager',
        ),
        multiValued=1,
        relationship='suppliers_client'
    ),

    RelationField(
        name='annotations',
        widget=ReferenceBrowserWidget(
            label='Annotations',
            label_msgid='TKContactManager_label_annotations',
            i18n_domain='TKContactManager',
        ),
        multiValued=1,
        relationship='concerningorganisation_annotations'
예제 #13
0
     "Envios que se destinan a este Perfil o Unidad Organizacional.",
     relationship='BPDDestinatarioDeEnvios',
     inverse_relation_field_name='destinatarios',
     sourcestyle=
     "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
     inverse_relation_label2="Receivers",
     label2="Receiver of Send steps",
     inverse_relation_description2=
     "Participant Profiles or Organisational Units to whom this is Sent",
     widget=ReferenceBrowserWidget(
         label="Destinatario de Envios",
         label2="Receiver of Send steps",
         description=
         "Envios que se destinan a este Perfil o Unidad Organizacional.",
         description2=
         "Send process steps addressed to this participant Profile or Organisational Unit.",
         label_msgid=
         'gvSIGbpd_BPDParticipante_rel_destinatarioDeEnvios_label',
         description_msgid=
         'gvSIGbpd_BPDParticipante_rel_destinatarioDeEnvios_help',
         i18n_domain='gvSIGbpd',
     ),
     label="Destinatario de Envios",
     description2=
     "Send process steps addressed to this participant Profile or Organisational Unit.",
     multiValued=1,
     containment="Unspecified",
     inverse_relationship='BPDDestinatarios',
     dependency_supplier=True),
 RelationField(
     name='pasosEjecutados',
예제 #14
0
        inverse_relation_description=
        "Pasos de otros Procesos de Negocio donde este proceso se ejecuta de principio a fin, como un Paso Sub-Proceso.",
        description=
        "Proceso de Negocio que se ejecuta como parte del Proceso de Negocio de mayor alcance.",
        relationship='BPDProcesoUsado',
        inverse_relation_field_name='usadoComoSubProcesos',
        inverse_relation_label2="Used as Sub-Business Process in",
        label2="Used Business Process",
        inverse_relation_description2=
        "Business Processes where this one is used as a Sub-Process",
        widget=ReferenceBrowserWidget(
            label="Proceso de Negocio usado",
            label2="Used Business Process",
            description=
            "Proceso de Negocio que se ejecuta como parte del Proceso de Negocio de mayor alcance.",
            description2=
            "Business Process executed as part of the current one.",
            label_msgid='gvSIGbpd_BPDSubProceso_rel_procesoUsado_label',
            description_msgid='gvSIGbpd_BPDSubProceso_rel_procesoUsado_help',
            i18n_domain='gvSIGbpd',
        ),
        label="Proceso de Negocio usado",
        description2="Business Process executed as part of the current one.",
        multiValued=0,
        containment="Unspecified",
        inverse_relationship='BPDUsadoComoSubProcesos',
        owner_class_name="BPDSubProceso",
        deststyle=
        "Owned=0;Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;"),
), )
예제 #15
0
                     required=False,
                     default=90.0,
                     storage=atapi.AnnotationStorage(),
                     widget=atapi.DecimalWidget(
                         label=_(u'Score to approve'),
                         description=_(u'Minimun score to pass the exam'),
                     )),
    atapi.ReferenceField(
        'evaluationDependecy',
        relationship='evaluation_dependecy',
        allowed_types=('Exam', ),
        multiValued=False,
        #keepReferencesOnCopy=True,
        storage=atapi.AnnotationStorage(),
        widget=ReferenceBrowserWidget(
            label=_(u'Referenced Evaluation'),
            description=_(u'Choose an exam that allow to take this exam'),
        ),
    ),
))

###########################################################
# Schema for messaging?
###########################################################

message_schema = atapi.Schema((
    atapi.BooleanField('showMessages',
                       schemata="Messages",
                       storage=atapi.AnnotationStorage(),
                       widget=atapi.BooleanWidget(
                           label=_(u'Show messages'),
                           visible=0,
예제 #16
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)
예제 #17
0
        position="0",
        owner_class_name="BPDPasoGeneral"
    ),

    RelationField(
        name='ejecutores',
        inverse_relation_label="Pasos Ejecutados",
        inverse_relation_description="Pasos de Negocio que se encarga de ejecutar el Perfil o Unidad Organizacional",
        description="Perfiles y Unidades Organizacionales a cargo de ejecutar el Paso.",
        relationship='BPDEjecutoresDelPaso',
        label2="Performers",
        widget=ReferenceBrowserWidget(
            label="Ejecutores",
            label2="Performers",
            description="Perfiles y Unidades Organizacionales a cargo de ejecutar el Paso.",
            description2="Participant Profiles and Organisational Units allowed to execute the Step.",
            label_msgid='gvSIGbpd_BPDPasoGeneral_rel_ejecutores_label',
            description_msgid='gvSIGbpd_BPDPasoGeneral_rel_ejecutores_help',
            i18n_domain='gvSIGbpd',
        ),
        description2="Participant Profiles and Organisational Units allowed to execute the Step.",
        inverse_relation_label2="Performed Business Process Steps",
        deststyle="Owned=0;Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;",
        write_permission='Modify portal content',
        inverse_relation_field_name='pasosEjecutados',
        inverse_relation_description2="Business Process Steps performed by the participant Profile or Organisational Unit.",
        additional_columns=['abreviatura'],
        label="Ejecutores",
        multiValued=1,
        containment="Unspecified",
        inverse_relationship='BPDPasosEjecutados',
예제 #18
0
class SchemaExtender(object):
    """ Extend a file to get more publication related fields """
    implements(IOrderableSchemaExtender)

    _fields = [
        # Override relatedItems make it langauge independent and override
        # the accessor to return langage dependent references.
        ExtendedReferenceField(
            'relatedItems',
            relationship='relatesTo',
            multiValued=True,
            isMetadata=True,
            languageIndependent=True,
            accessor='getRelatedItems',
            mutator='setRelatedItems',
            index='KeywordIndex',
            write_permission=permissions.ModifyPortalContent,
            widget=ReferenceBrowserWidget(allow_search=True,
                                          allow_browse=True,
                                          show_indexes=False,
                                          force_close_on_insert=True,
                                          label=_(u"Related Items"),
                                          description='',
                                          visible={
                                              'edit': 'visible',
                                              'view': 'invisible'
                                          }),
        ),
        ExtendedImageField(
            'cover_image',
            schemata='publication',
            sizes={'cover': (70, 100)},
            languageIndependent=True,
            accessor='getCover_image',
            mutator='setCover_image',
            widget=atapi.ImageWidget(
                label=_(u'label_cover_image', default=u'Cover Image'),
                description=_(
                    u'description_cover_image',
                    default=
                    u'Upload a cover image. Leave empty to have the system autogenerate one for you.'
                ),
            ),
        ),
        ExtendedStringField(
            'author',
            schemata='publication',
            languageIndependent=True,
            accessor='getAuthor',
            mutator='setAuthor',
            widget=atapi.StringWidget(
                label=_(u'label_author', default=u'Author'),
                description=_(
                    u'description_author',
                    default=
                    u'Fill in the Name of the Author of this Publication.'),
            ),
        ),
        ExtendedStringField(
            'isbn',
            schemata='publication',
            languageIndependent=False,
            widget=atapi.StringWidget(
                label=_(u'label_isbn', default=u'ISBN'),
                description=_(
                    u'description_isbn',
                    default=u'Fill in the ISBN Number of this Publication.'),
            ),
        ),
        ExtendedStringField(
            'order_id',
            schemata='publication',
            languageIndependent=False,
            widget=atapi.StringWidget(
                label=_(u'label_order_id', default=u'Order ID'),
                description=_(
                    u'description_order_id',
                    default=u'Fill in the Order ID of this Publication.'),
            ),
        ),
        ExtendedBooleanField(
            'for_sale',
            schemata='publication',
            languageIndependent=True,
            accessor='getFor_sale',
            mutator='setFor_sale',
            widget=atapi.BooleanWidget(
                label=_(u'label_for_sale', default=u'For sale?'),
                description=_(u'description_for_sale',
                              default=u'Is this Publication for sale?'),
            ),
        ),
        ExtendedLinesField(
            'chapters',
            schemata='publication',
            languageIndependent=True,
            accessor='getChapters',
            mutator='setChapters',
            widget=atapi.LinesWidget(
                label=_(u'label_chapters', default=u'Chapters'),
                description=_(
                    u'description_chapters',
                    default=
                    u'Chapters of this Publication. Specify the Link targets defined in your pdf file, one per line.'
                ),
            ),
        ),
        ExtendedFileField(
            'metadata_upload',
            schemata='publication',
            languageIndependent=True,
            accessor='getMetadata_upload',
            mutator='setMetadata_upload',
            widget=atapi.FileWidget(
                label=_(u'label_metadata_upload',
                        default=u'Metadata INI upload'),
                description=_(u'description_metadata_upload',
                              default=u'Upload Metadata in INI style format.'),
            ),
        ),
        ExtendedStringField(
            'owner_password',
            schemata='publication',
            languageIndependent=False,
            widget=atapi.StringWidget(
                label=_(u'label_owner_password', default=u'Owner Password'),
                description=_(
                    u'description_owner_password',
                    default=
                    u'If this publication is protected, speciy the pdf owner password if you want to parse the file.'
                ),
            ),
        ),
        ExtendedStringField(
            'user_password',
            schemata='publication',
            languageIndependent=False,
            widget=atapi.StringWidget(
                label=_(u'label_user_password', default=u'User Password'),
                description=_(
                    u'description_user_password',
                    default=
                    u'If this publication is protected, speciy the pdf user password if you want to parse the file.'
                ),
            ),
        ),
    ]

    def __init__(self, context):
        """ init """
        self.context = context
        klass = context.__class__
        if HAVE_LINGUAPLONE and not getattr(
                klass, LANGUAGE_INDEPENDENT_INITIALIZED, False):
            fields = [
                field for field in self._fields if field.languageIndependent
            ]
            generateMethods(klass, fields)
            setattr(klass, LANGUAGE_INDEPENDENT_INITIALIZED, True)

    def getFields(self):
        """ get fields """
        return self._fields

    def getOrder(self, original):
        """ new order """
        publication = original.get('publication', [])

        publication.insert(0, 'author')
        publication.insert(1, 'isbn')
        publication.insert(2, 'order_id')
        publication.insert(3, 'for_sale')
        publication.insert(4, 'chapters')
        publication.insert(5, 'cover_image')
        publication.insert(6, 'metadata_upload')
        publication.insert(7, 'owner_password')
        publication.insert(8, 'user_password')

        original['publication'] = publication

        return original
예제 #19
0
 RelationField(
     name='entradasAProcesosDeNegocio',
     inverse_relation_label="Artefactos de Entrada",
     inverse_relation_description=
     "Artefactos que deben estar disponibles para comenzar el Proceso de Negocio",
     description=
     "Entradas a Procesos de Negocio en que el Artefacto debe estar disponible, para poder comenzar la ejecucion.",
     relationship='BPDEntradasAProcesosDeNegocio',
     label2="Input to Business Processes",
     widget=ReferenceBrowserWidget(
         label="Entrada a Procesos de Negocio",
         label2="Input to Business Processes",
         description=
         "Entradas a Procesos de Negocio en que el Artefacto debe estar disponible, para poder comenzar la ejecucion.",
         description2=
         "Inputs to Business Processes where the Artefact must be made available , in order  to start execution.",
         label_msgid=
         'gvSIGbpd_BPDArtefacto_rel_entradasAProcesosDeNegocio_label',
         description_msgid=
         'gvSIGbpd_BPDArtefacto_rel_entradasAProcesosDeNegocio_help',
         i18n_domain='gvSIGbpd',
     ),
     description2=
     "Inputs to Business Processes where the Artefact must be made available , in order  to start execution.",
     sourcestyle=
     "Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;Owned=0;",
     inverse_relation_label2="Input Artefacts",
     dependency_supplier=True,
     inverse_relation_field_name='artefactosDeEntrada',
     inverse_relation_description2=
     "Artefacts required as input to allow the start of the Business Processes.",
예제 #20
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)
예제 #21
0
class MapServer(BaseFolder):
    '''Map Server for CoGIS'''
    schema = BaseFolderSchema

    schema = BaseSchema + Schema([
        StringField('description',
                    required=False,
                    searchable=1,
                    widget=StringWidget(
                        label='Description',
                        description="Enter project description")),
        ReferenceField('relatedItems',
                       relationship='relatesTo',
                       multiValued=True,
                       isMetadata=True,
                       languageIndependent=False,
                       index='KeywordIndex',
                       write_permission=ModifyPortalContent,
                       widget=ReferenceBrowserWidget(
                           allow_search=True,
                           allow_browse=True,
                           show_indexes=False,
                           force_close_on_insert=True,
                           label=_(u'label_related_items',
                                   default=u'Related Items'),
                           description='',
                           visible={
                               'edit': 'visible',
                               'view': 'invisible'
                           }))
    ], )

    actions = (
        {
            'id': 'publish',
            'name': 'Publish',
            'action': 'string:${object_url}/Map_Server_PublishAll',
            'permissions': (permissions.ViewManagementScreens, )
        },
        {
            'id': 'pingServer',
            'name': 'Ping Server',
            'action': 'string:${object_url}/Map_Server_PingServer',
            'permissions': (permissions.ViewManagementScreens, )
        },
        {
            'id': 'licenseAgreement',
            'name': 'License Agreement',
            'action': 'string:${object_url}/Map_Server_LicenseAgreement_Edit',
            'permissions': (permissions.ViewManagementScreens, )
        },
    )

    #schema = schema + extra_schema
    content_icon = "mapServer.gif"
    security = ClassSecurityInfo()

    archetype_name = 'MapServer'
    meta_type = 'MapServer'
    portal_type = 'MapServer'
    allowed_content_types = []  #['MapLayer']
    filter_content_types = 1
    global_allow = 0
    allow_discussion = 0
    content_icon = "mapServer.gif"

    def __init__(self, id, title=''):
        '''Initialize an instance of the class'''
        self.id = id
        if title == '':
            self.title = id
        else:
            self.title = title

        self.organization = ""
        self.wmsSource = ""
        self.wfsSource = ""
        self.enableLicenseAgreement = False
        # licenseAgreent is the text to display in the tbx
        self.licenseAgreement = "Put the license text here \nPlease read license before publishing"
        # its a list of usernames that have accepted the license agreement
        self.acceptedUserNames = []

    def dummyTest(self):
        """
        """
        return dir(self)

    def updateLicenseAgreement(self, REQUEST=None):
        """
        @summary: udpate the server license agreement and disables/enables the agreement
        """
        try:
            self.acceptedUserNames = []

            if REQUEST.has_key('enableIt'):
                enable = True
            else:
                enable = False

            licenseText = REQUEST.form['licenseText']

            self.enableLicenseAgreement = enable
            self.licenseAgreement = licenseText

            self._p_changed = 1
            transaction.savepoint(True)

            status_message = "License Agreement Updated"

            REQUEST.RESPONSE.redirect(
                "%s/Map_Server_LicenseAgreement_Edit?portal_status_message=%s"
                % (self.absolute_url(), status_message))
        except:
            logger.exception('failed updateLicenseAgreement')

    security.declarePublic('userIsOwner')

    def userIsOwner(self):
        """
        @summary: this is a zope specific method to get logged in user name
        @return: boolean, true if logged in user is the owner
        """
        try:
            ownerName = self.owner_info()['id']
            member = self.portal_membership.getAuthenticatedMember()
            userName = member.getUserName()
            if userName == ownerName:
                return True
            else:
                return False
        except:
            logger.exception('failed user is owner')

    def publishLayersForRoles(self, rolesToPublish):
        """
        @summary : publishes layer for the given roles passed
        @param   : a list of roles to publish layers for
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getPublishedStructureForRoles(rolesToPublish))
            return 1
        except:
            logger.exception('failed publishLayersForRoles')

    def publishAllLayers(self):
        """
        @summary: this will publish all the layers in the server
        @return: 1
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getPublishedSecurityStructure())
            return 1
        except:
            logger.exception('failed publishAllLayers')

    def retractAllLayers(self):
        """
        @summary: this will retract all the layers in the server
        @return: 1
        """

        try:
            items = self.objectItems()
            for i in items:
                if i[1].meta_type == 'MapLayer':
                    l = i[1]
                    secStruct = l.setSecurity(
                        self.getRetractedSecurityStructure())
            return 1
        except:
            logger.exception('failed retractAllLayers')

    def pingServer(self):
        """
        """
        try:
            startTime = time.time()
            wmsPingRes = self._getURLContent(self.wmsSource)
            endTime = time.time()
            wmsTime = endTime - startTime
            if wmsPingRes.find("Exception occured") != -1:
                wmsTime = "Server Unavailable"

            startTime = time.time()
            wfsPingRes = self._getURLContent(self.wfsSource)
            endTime = time.time()
            wfsTime = endTime - startTime
            if wfsPingRes.find("Exception occured") != -1:
                wfsTime = "Server Unavailable"

            return [str(wfsTime), str(wmsTime)]
        except:
            logger.exception('failed pingServer')

    def pingAllLayers(self):
        """
        """
        try:
            results = {}
            items = self.objectItems()
            for i in items:
                layer = i[1]
                pingResWMS = layer.pingWMSLayer()
                pingResWFS = layer.pingWFSLayer()
                results[layer.uniqueName] = [pingResWFS, pingResWMS]
            return results
        except:
            logger.exception('error')

    def getPublishedSecurityStructure(self):
        """
        @summary: builds a security structure that will expose all layers
        @return: a dictionary with all the roles as keys and another dict as value
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                tmpDict[role] = {'Render': 1, 'Extract': 1}
            return tmpDict
        except:
            logger.exception('failed getPublishedSercurityStructure')

    def getPublishedStructureForRoles(self, theRoles):
        """
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                if role in theRoles:
                    tmpDict[role] = {'Render': 1, 'Extract': 1}
                else:
                    tmpDict[role] = {'Render': 0, 'Extract': 0}
            return tmpDict
        except:
            logger.exception('Error')

    def getRetractedSecurityStructure(self):
        """
        @summary: builds a security structure that will expose all layers
        @return: a dictionary with all the roles as keys and another dict as value
        """
        try:
            roles = self.validRoles()
            tmpDict = {}
            for role in roles:
                tmpDict[role] = {'Render': 0, 'Extract': 0}
            return tmpDict
        except:
            logger.exception('Error')

    def _getURLContent(self, url, data={}):
        """        
        """
        try:
            if data:
                if type(data) == unicode:
                    data = str(urllib.unquote(data))
                if type(data) == str:
                    f = urllib.urlopen(url, data)
                else:
                    params = urllib.urlencode(data)
                    f = urllib.urlopen(url, params)
            else:
                f = urllib.urlopen(url)
            data = f.read()
            f.close()
            return data
        except:
            import traceback
            sio = StringIO.StringIO()
            traceback.print_exc(file=sio)
            sio.seek(0)
            trace = sio.read()
            logger.exception('Error')
            return MapServerTemplates.ogcServiceException % (
                "Exception occured getURLContent request, check log for details %s"
                % trace)
예제 #22
0
     name='elementosDerivados',
     inverse_relation_label="Elementos Base",
     inverse_relation_description=
     "Elementos a partir de los cuales se ha derivado el actual.",
     description="Elementos que han sido derivados a partir del actual.",
     relationship='BPDElementosDerivados',
     inverse_relation_field_name='elementosBase',
     inverse_relation_label2="Base Elements",
     label2="Derived Elements",
     inverse_relation_description2=
     "Elements from whish this one has been derived.",
     widget=ReferenceBrowserWidget(
         label="Elementos Derivados",
         label2="Derived Elements",
         description="Elementos que han sido derivados a partir del actual.",
         description2="Elements that have been derived from this one.",
         label_msgid='gvSIGbpd_BPDElemento_rel_elementosDerivados_label',
         description_msgid=
         'gvSIGbpd_BPDElemento_rel_elementosDerivados_help',
         i18n_domain='gvSIGbpd',
     ),
     write_permission='Modify portal content',
     label="Elementos Derivados",
     description2="Elements that have been derived from this one.",
     multiValued=1,
     deststyle=
     "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
     containment="Unspecified",
     inverse_relationship='BPDElementosBase',
     owner_class_name="BPDElemento",
     dependency_supplier=True),
 RelationField(
예제 #23
0
@indexer(IGroup)
def members(obj):
    return len(obj.persons)


GroupSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((

    # -*- Your Archetypes field definitions here ... -*-
    atapi.ReferenceField(
        name='persons',
        storage=atapi.AnnotationStorage(),
        required=False,
        widget=ReferenceBrowserWidget(
            label=_(u"Persons"),
            description=_(u"The persons that belong to this group"),
            restrict_browsing_to_startup_directory=True,
        ),
        searchable=1,
        relationship='group_person',
        allowed_types=('Person', ),
        multiValued=True,
    ), ))

# Set storage on fields copied from ATContentTypeSchema, making sure
# they work well with the python bridge properties.

GroupSchema['title'].storage = atapi.AnnotationStorage()
GroupSchema['description'].storage = atapi.AnnotationStorage()

schemata.finalizeATCTSchema(GroupSchema, moveDiscussion=False)
예제 #24
0
     ),
     default_output_type='text/html',
 ),
 DateTimeField(
     name='dateOfVisit',
     widget=DateTimeField._properties['widget'](
         label='Dateofvisit',
         label_msgid='UWOshMusicRecruiting_label_dateOfVisit',
         i18n_domain='UWOshMusicRecruiting',
     ),
 ),
 ReferenceField(
     name='facultymembers',
     widget=ReferenceBrowserWidget(
         label='Facultymembers',
         label_msgid='UWOshMusicRecruiting_label_facultymembers',
         i18n_domain='UWOshMusicRecruiting',
     ),
     allowed_types=('FacultyMember',),
     multiValued=0,
     relationship='visit_facultymember',
 ),
 ReferenceField(
     name='students',
     widget=ReferenceBrowserWidget(
         label='Students',
         label_msgid='UWOshMusicRecruiting_label_students',
         i18n_domain='UWOshMusicRecruiting',
     ),
     allowed_types=('Student',),
     multiValued=0,
schema = Schema((
    RelationField(
        name='referentes',
        inverse_relation_label="Elementos Referenciados",
        inverse_relation_description=
        "Elementos de la aplicacion referidos desde este elemento.",
        description=
        "Elementos de la aplicacion que refieren al presente elemento.",
        relationship='BPDReferentes',
        label2="Refering elements",
        widget=ReferenceBrowserWidget(
            label="Elementos Referentes",
            label2="Refering elements",
            description=
            "Elementos de la aplicacion que refieren al presente elemento.",
            description2="Application elements referencing this one.",
            label_msgid=
            'gvSIGbpd_BPDArquetipoReferenciable_rel_referentes_label',
            description_msgid=
            'gvSIGbpd_BPDArquetipoReferenciable_rel_referentes_help',
            i18n_domain='gvSIGbpd',
        ),
        description2="Application elements referencing this one.",
        sourcestyle=
        "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
        inverse_relation_label2="Referenced elements",
        dependency_supplier=True,
        inverse_relation_field_name='referidos',
        inverse_relation_description2=
        "Elements in the application referenced by this element.",
        write_permission='Modify portal content',
        label="Elementos Referentes",
##/code-section module-header

schema = Schema((RelationField(
    name='referidosCualificados',
    inverse_relation_label="Referentes Cualificados",
    inverse_relation_description=
    "Referencias Cualificadas refiriendo a este elemento.",
    description="Elementos referidos desde esta Referencia Cualificada.",
    relationship='BPDReferidosCualificados',
    label2="Refered Elements",
    widget=ReferenceBrowserWidget(
        label="Elementos cualificadamente Referidos",
        label2="Refered Elements",
        description="Elementos referidos desde esta Referencia Cualificada.",
        description2="Elements refered to by this qualified Reference.",
        label_msgid=
        'gvSIGbpd_BPDReferenciaCualificada_rel_referidosCualificados_label',
        description_msgid=
        'gvSIGbpd_BPDReferenciaCualificada_rel_referidosCualificados_help',
        i18n_domain='gvSIGbpd',
    ),
    description2="Elements refered to by this qualified Reference.",
    inverse_relation_label2="Refering Qualified References",
    deststyle=
    "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
    write_permission='Modify portal content',
    inverse_relation_field_name='referentesCualificados',
    inverse_relation_description2=
    "Qualified References referencing this element.",
    label="Elementos cualificadamente Referidos",
    multiValued=1,
from Products.FacultyStaffDirectory.permissions import ASSIGN_SPECIALTIES_TO_PEOPLE

from zope.interface import implements
#from zope.i18nmessageid import MessageFactory
#_ = MessageFactory('FacultyStaffDirectory')
from Products.FacultyStaffDirectory import FSDMessageFactory as _

schema = Schema(
    (
        RelationField(
            name='people',
            widget=ReferenceBrowserWidget(
                label=_(u"FacultyStaffDirectory_label_people",
                        default=u"People"),
                i18n_domain='FacultyStaffDirectory',
                allow_browse=0,
                allow_search=1,
                show_results_without_query=1,
                base_query="_search_people_in_this_fsd",
                startup_directory_method="_get_parent_fsd_path",
            ),
            write_permission=ASSIGN_SPECIALTIES_TO_PEOPLE,
            allowed_types=('FSDPerson', ),
            multiValued=True,
            relationship=
            'SpecialtyInformation'  # weird relationship name is ArchGenXML's fault
        ),
        ImageField(
            name='overviewImage',
            schemata='Overview',
            widget=ImageWidget(
                label=_(
예제 #28
0
     owner_class_name="BPDSalida"),
 RelationField(
     name='artefactosDeSalida',
     inverse_relation_label="Salidas de Procesos de Negocio",
     inverse_relation_description=
     "Procesos de Negocio donde el Artefacto se produce como Salida, tras el final exitoso de la ejecucion.",
     description=
     "Artefactos producidos como Salida al finalizar exitosamente el Proceso de Negocio.",
     relationship='BPDArtefactosDeSalida',
     label2="Output Artefacts",
     widget=ReferenceBrowserWidget(
         label="Artefactos de Salida",
         label2="Output Artefacts",
         description=
         "Artefactos producidos como Salida al finalizar exitosamente el Proceso de Negocio.",
         description2=
         "Artefacts produced as outcomes of successfully completed Business Processes.",
         label_msgid='gvSIGbpd_BPDSalida_rel_artefactosDeSalida_label',
         description_msgid='gvSIGbpd_BPDSalida_rel_artefactosDeSalida_help',
         i18n_domain='gvSIGbpd',
     ),
     description2=
     "Artefacts produced as outcomes of successfully completed Business Processes.",
     inverse_relation_label2="Business Process Outputs",
     deststyle=
     "Navigable=Unspecified;Union=0;Derived=0;AllowDuplicates=0;Owned=0;",
     write_permission='Modify portal content',
     inverse_relation_field_name='salidasDeProcesosDeNegocio',
     inverse_relation_description2=
     "Business Processes where the Artefact is made available as Output, upon successful completion.",
     additional_columns=['codigo'],
예제 #29
0
            i18n_domain='gcommons.Journal',
        ),
        searchable=True,
    ),


    atapi.ReferenceField('readingList',
        relationship = 'reading',
        multiValued = True,
        keepReferencesOnCopy = True,
        widget = ReferenceBrowserWidget(
            allow_search = True,
            allow_browse = True,
            show_indexes = False,
            force_close_on_insert = False,
            #only_for_review_states = 'eb_draft',
            base_query={'portal_type': ('Article',),        # TODO: restrict this type to journal/conf
                        'review_state':('eb_draft',)},      
            label = _(u'label_reading_list', default=u'Reading List'),
            description = "Please select all the items that will be discussed in this meeting",
            visible = {'edit' : 'visible', 'view' : 'invisible' }
        )
    ),

))

                                                
                                                 
# Set storage on fields copied from ATFolderSchema, making sure
# they work well with the python bridge properties.
def finalizeEditorsMeetingSchema(schema):
    schema['title'].storage = atapi.AnnotationStorage()
예제 #30
0
 inverse_relation_description=
 "Datos de Pruebas definidos para este elemento de proceso en varios Casos de Pruebas.",
 description=
 "Elementos del Proceso de Negocio para los que se definen Datos de Prueba en el Caso de Prueba.",
 relationship='DatosDePrueba_ElementosProceso',
 inverse_relation_field_name='elementosDeProceso',
 inverse_relation_label2="Test Data",
 label2="Process Elements",
 inverse_relation_description2=
 "Test Data defined for this process element in various Test Cases.",
 widget=ReferenceBrowserWidget(
     label="Elementos de Proceso",
     label2="Process Elements",
     description=
     "Elementos del Proceso de Negocio para los que se definen Datos de Prueba en el Caso de Prueba.",
     description2=
     "Business Process elements for which Test Data is defined in the Test Case.",
     label_msgid='gvSIGbpd_BPDConDatosDePrueba_rel_datosDePruebas_label',
     description_msgid=
     'gvSIGbpd_BPDConDatosDePrueba_rel_datosDePruebas_help',
     i18n_domain='gvSIGbpd',
 ),
 write_permission='Modify portal content',
 label="Elementos de Proceso",
 description2=
 "Business Process elements for which Test Data is defined in the Test Case.",
 multiValued=1,
 deststyle=
 "Union=0;Derived=0;AllowDuplicates=0;Owned=0;Navigable=Unspecified;",
 containment="Unspecified",
 inverse_relationship='ElementosProceso_DatosDePrueba',
 owner_class_name="BPDConDatosDePrueba",