Beispiel #1
0
class AnalysisRequestSchemaExtender(object):
    """Schema Extender for Sample objects
    """
    adapts(IAnalysisRequest)
    implements(IOrderableSchemaExtender, IBrowserLayerAwareExtender)
    # Modify the schema only if senaite.panic is installed
    layer = ISenaitePanicLayer

    custom_fields = [
        # Stores if a panic email has been sent
        ExtBooleanField(
            "PanicEmailAlertSent",
            default=False,
            widget=BooleanWidget(visible=False, ),
        ),
    ]

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

    def getOrder(self, schematas):
        return schematas

    def getFields(self):
        return self.custom_fields
Beispiel #2
0
class AllowQuestionsExtender(object):
    implements(ISchemaExtender)

    fields = [
        _AllowQuestionsExtensionField(
            "allowQuestions",
            default = False,
            widget = BooleanWidget(
                label=u"Allow questions",
                description=u"Allow questions on this content.",
            ),
            schemata='settings',
        ),
    ]

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

    def getFields(self):
        return self.fields
Beispiel #3
0
class BikaSetupSchemaExtender(object):
    adapts(IBikaSetup)
    implements(IOrderableSchemaExtender)

    fields = [
        ExtBooleanField('EnablePanicAlert',
                        schemata="Analyses",
                        default=False,
                        widget=BooleanWidget(
                            label=_("Enable panic levels alert"),
                            description=_(
                                "Alert labmanagers with an email when an "
                                "analysis result exceeding a panic level is "
                                "submitted"))),
        ExtBooleanField(
            'AutoShowPanicAlertEmailPopup',
            schemata="Analyses",
            default=False,
            widget=BooleanWidget(
                label=_("Show client email pop-up when panic level"),
                description=_("If enabled, shows automatically an email form "
                              "pop-up for alerting the client about a panic "
                              "level exceeded when Analysis Request view is "
                              "loaded"))),
        ExtStringField(
            'PatientConditionsHeightUnits',
            schemata="Cases",
            default=_("Feet/inches"),
            widget=StringWidget(
                label=_("Patient condition height units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtStringField(
            'PatientConditionsWeightUnits',
            schemata="Cases",
            default=_("Lbs"),
            widget=StringWidget(
                label=_("Patient condition weight units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtStringField(
            'PatientConditionsWaistUnits',
            schemata="Cases",
            default=_("Inches"),
            widget=StringWidget(
                label=_("Patient condition waist units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtBooleanField(
            'AllowResultsDistributionToPatients',
            schemata="Results Reports",
            default=False,
            widget=BooleanWidget(
                label=_("Allow results distribution to Patients"),
                description=_("If checked, results reports will also be sent "
                              "to the Patient automatically. This setting can "
                              "be overriden either on 'Patient publication "
                              "preferences' tab from Client view or on "
                              "Patient's 'Publication preferences' tab."))),
        ExtLinesField(
            'PatientPublicationPreferences',
            vocabulary_factory=
            'bika.health.obsolete.CustomPubPrefVocabularyFactory',
            schemata='Results Reports',
            widget=MultiSelectionWidget(
                label=_("Default publication preference for Patients"),
                description=_("Select the preferred channels to be used for "
                              "sending the results reports to Patients. "
                              "This setting can be overriden either on "
                              "'Patient publication preferences' tab from "
                              "Client view or on Patient's 'Publication "
                              "preferences' tab."))),
        ExtBooleanField('PatientPublicationAttachmentsPermitted',
                        default=False,
                        schemata='Results Reports',
                        widget=BooleanWidget(
                            label=_("Results attachments permitted"),
                            description=_(
                                "File attachments to results, e.g. microscope "
                                "photos, will be included in emails to "
                                "patients if this option is enabled. This "
                                "setting can be overriden either on 'Patient "
                                "publication preferences' tab from Client "
                                "view or on Patient's 'Publication "
                                "preferences' tab."))),
        ExtBooleanField(
            'EnableBikaAnalysisRequestRequestForm',
            schemata="Analyses",
            default=False,
            widget=BooleanWidget(
                label=_("Enable Bika's analysis request form."),
                description=
                _("It enables the secondary analysis request form. This request has some characteristic "
                  "features as allowing you to register more than one analysis request at the same time. "
                  "It's useful if you are supposed to register a big amount of analysis request at the same "
                  "time."))),
        ExtBooleanField('CaseDoctorIsMandatory',
                        schemata="Cases",
                        default=True,
                        widget=BooleanWidget(
                            label=_("Doctor field is mandatory in cases"),
                            description=_(
                                "Should the Doctor field be mandatory while "
                                "creating a case?"))),
        ExtBooleanField(
            'ClientPatientIDUnique',
            schemata="ID Server",
            default=False,
            widget=BooleanWidget(
                label=_("Client Patient ID must be unique"),
                description=_("If selected, Client Patient IDs will be forced "
                              "to be unique"))),
    ]

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

    def getFields(self):
        return self.fields

    def getOrder(self, schematas):
        sch = schematas['Results Reports']
        sch.remove('AllowResultsDistributionToPatients')
        sch.insert(sch.index('PatientPublicationPreferences'),
                   'AllowResultsDistributionToPatients')
        schematas['Results Reports'] = sch
        return schematas
    validators=('SortKeyValidator', ),
    widget=DecimalWidget(
        label=_("Sort Key"),
        description=_(
            "Float value from 0.0 - 1000.0 indicating the sort order. "
            "Duplicate values are ordered alphabetically."),
    ))

# Is the title of the analysis a proper Scientific Name?
ScientificName = BooleanField(
    'ScientificName',
    schemata="Description",
    default=False,
    widget=BooleanWidget(
        label=_("Scientific name"),
        description=_(
            "If enabled, the name of the analysis will be written in italics."
        ),
    ))

# The units of measurement used for representing results in reports and in
# manage_results screen.
Unit = StringField(
    'Unit',
    schemata="Description",
    widget=StringWidget(
        label=_("Unit"),
        description=_(
            "The measurement units for this analysis service' results, e.g. "
            "mg/l, ppm, dB, mV, etc."),
    ))
class FGStripeField(FGStringField):
    """ A string entry field """

    implements(IStripeField)

    security = ClassSecurityInfo()

    schema = FGStringField.schema.copy() + Schema(
        (LinesField(
            'amounts',
            required=False,
            accessor="getAmounts",
            mutator="setAmounts",
            searchable=False,
            widget=LinesWidget(
                label='Available amounts',
                description='You can also provide a description of value '
                'using the | operator. Example: 10.00|$10 small')),
         BooleanField('variable',
                      required=False,
                      default=True,
                      searchable=False,
                      widget=BooleanWidget(label='Allow variable amount')),
         StringField('variableLabel',
                     required=True,
                     default='Amount: $',
                     searchable=False,
                     widget=StringWidget(
                         label='Label used for variable amount field')),
         FixedPointField(
             'fixedPrice',
             required=False,
             default='0.00',
             searchable=False,
             widget=DecimalWidget(
                 label='Fixed amount',
                 description='If filled in, ignore previous 2 fields.')),
         StringField('stripeSecretKey',
                     require=True,
                     searchable=False,
                     view_permission=ModifyPortalContent,
                     widget=StringWidget(label='Stripe Secret Key')),
         StringField('stripePublishableKey',
                     require=True,
                     searchable=False,
                     widget=StringWidget(label='Stripe Publishable Key')),
         StringField('stripePanelLabel',
                     required=True,
                     searchable=False,
                     default='More info about this',
                     widget=StringWidget(
                         label='The label of the payment button in the '
                         'Checkout form')),
         StringField(
             'stripeLabel',
             required=True,
             searchable=False,
             default='Authorize Donation',
             widget=StringWidget(label='Specify the text to be shown on the '
                                 'default blue button')),
         StringField('stripeCurrency',
                     required=True,
                     searchable=False,
                     default='USD',
                     widget=StringWidget(label='3 letter ISO currency code')),
         LinesField(
             'stripeMetadata',
             required=False,
             default=[],
             vocabulary='getPFGFields',
             multiValued=True,
             widget=MultiSelectionWidget(
                 label='Metadata Fields',
                 description=
                 'Select the fields that should be included as metadata. '
                 'You can only include 10 fields. Extras will be striped.'))))
    schema['required'].default = True
    schema['required'].widget.visible['edit'] = 'hidden'
    schema['hidden'].widget.visible['edit'] = 'hidden'
    schema['fgDefault'].widget.visible['edit'] = 'hidden'
    schema['fgmaxlength'].widget.visible['edit'] = 'hidden'
    schema['fgsize'].widget.visible['edit'] = 'hidden'
    schema['fgStringValidator'].widget.visible['edit'] = 'hidden'

    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormStripeField'
    archetype_name = 'StripeField'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        super(FGStripeField, self).__init__(oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = StripeField('fg_stripe_field',
                                   searchable=0,
                                   required=0,
                                   write_permission=View,
                                   widget=StripeWidget(),
                                   amounts=('10.00', '25.00', '50.00',
                                            '100.00'),
                                   variable=True,
                                   variableLabel='Amount: $',
                                   fixedPrice='0.00',
                                   stripeSecretKey='',
                                   stripePublishableKey='',
                                   stripePanelLabel='More info about this',
                                   stripeLabel='Authorize Donation',
                                   stripeCurrency='USD')

    def getPFGFields(self):
        form = aq_parent(aq_inner(self))
        if form.portal_type == 'TempFolder':
            form = aq_parent(form)
        values = []
        for field in form.values():
            if (IPloneFormGenField.providedBy(field)
                    and not IStripeField.providedBy(field)):
                values.append((field.getId(), field.Title()))
        return DisplayList(values)

    security.declareProtected(ModifyPortalContent, 'getStripeSecretKey')

    def getStripeSecretKey(self):  # noqa
        return self.fgField.stripeSecretKey

    security.declareProtected(ModifyPortalContent, 'setStripeSecretKey')

    def setStripeSecretKey(self, value, **kw):  # noqa
        self.fgField.stripeSecretKey = value

    security.declareProtected(View, 'getAmounts')

    def getAmounts(self):  # noqa
        return self.fgField.amounts

    security.declareProtected(ModifyPortalContent, 'setAmounts')

    def setAmounts(self, value, **kw):  # noqa
        self.fgField.amounts = value
        self.amounts = value

    # yikes, I'm lazy
    for fieldName in [
            'variable', 'variableLabel', 'fixedPrice', 'stripePublishableKey',
            'stripePanelLabel', 'stripeLabel', 'stripeCurrency'
    ]:
        upper = fieldName[0].upper() + fieldName[1:]
        exec('''
security.declareProtected(View, 'get%(upper)s')
def get%(upper)s(self):
    return getattr(self.fgField, '%(name)s', '')

security.declareProtected(ModifyPortalContent, 'set%(upper)s')
def set%(upper)s(self, value, **kw):
    self.fgField.%(name)s = value
''' % {
            'name': fieldName,
            'upper': upper
        })

    def htmlValue(self, REQUEST):
        value = REQUEST.form.get(self.__name__, 'No Input')
        if type(value) != dict:
            return 'Invalid'
        if 'error' in value:
            return 'Error charging'
        if 'charge_data' not in value:
            return 'Card not charged for some reason'
        return 'Charged to %s for $%s' % (value['charge_data']['email'],
                                          value['original-amount'])
Beispiel #6
0
                    i18n_domain="eea")),
    StringField(
        'autocomplete_view',
        schemata="default",
        required=True,
        vocabulary_factory='eea.faceted.vocabularies.AutocompleteViews',
        widget=SelectionWidget(
            label=_(u"Autocomplete"),
            description=_(
                u'Select the source of the autocomplete suggestions'),
        )),
    BooleanField('onlyallelements',
                 schemata="default",
                 widget=BooleanWidget(
                     label=_(u'Search in all elements only'),
                     description=_(
                         u'If this checkbox is checked, hides the choice to '
                         'filter in all items or in current items only'),
                     i18n_domain="eea")),
    BooleanField('multivalued',
                 schemata="default",
                 default=True,
                 widget=BooleanWidget(
                     label=_(u'Can select several elements'), )),
))


class Widget(AbstractWidget):
    """ Widget
    """
    # Widget properties
    widget_type = 'autocomplete'
class ExtensibleMetadata(Persistence.Persistent):
    """ A DC metadata implementation for Plone Archetypes
    """

    implements(IExtensibleMetadata)

    security = ClassSecurityInfo()

    schema = type = MetadataSchema((
        BooleanField(
            'allowDiscussion',
            accessor="isDiscussable",
            mutator="allowDiscussion",
            edit_accessor="editIsDiscussable",
            default=None,
            enforceVocabulary=1,
            widget=BooleanWidget(
                label=_(u'label_allow_comments', default=u'Allow comments'),
                description=_(u'help_allow_comments',
                              default=u'If selected, users can add comments '
                              'to this item.')),
        ),
        LinesField(
            'subject',
            multiValued=1,
            accessor="Subject",
            searchable=True,
            widget=TagsWidget(
                label=_(u'label_tags', default=u'Tags'),
                description=_(u'help_tags',
                              default=u'Tags are commonly used for ad-hoc '
                              'organization of content.'),
            ),
        ),
        TextField(
            'description',
            default='',
            searchable=1,
            accessor="Description",
            default_content_type='text/plain',
            allowable_content_types=('text/plain', ),
            widget=TextAreaWidget(
                label=_(u'label_description', default=u'Description'),
                description=_(
                    u'help_description',
                    default=u'Used in item listings and search results.'),
            ),
        ),
        # Location, also known as Coverage in the DC metadata standard, but we
        # keep the term Location here for historical reasons.
        StringField(
            'location',
            # why no accessor? http://dev.plone.org/plone/ticket/6424
            searchable=True,
            widget=StringWidget(
                label=_(u'label_location', default=u'Location'),
                description=_(
                    u'help_location_dc',
                    default=
                    u'The geographical location associated with the item, if applicable.'
                ),
            ),
        ),
        LinesField(
            'contributors',
            accessor="Contributors",
            widget=AjaxSelectWidget(
                label=_(u'label_contributors', u'Contributors'),
                description=_(
                    u'help_contributors',
                    default=u"The names of people that have contributed "
                    "to this item. Each contributor should "
                    "be on a separate line."),
                vocabulary="plone.app.vocabularies.Users"),
        ),
        LinesField(
            'creators',
            accessor="Creators",
            widget=AjaxSelectWidget(
                label=_(u'label_creators', u'Creators'),
                description=_(
                    u'help_creators',
                    default=u"Persons responsible for creating the content of "
                    "this item. Please enter a list of user names, one "
                    "per line. The principal creator should come first."),
                vocabulary="plone.app.vocabularies.Users"),
        ),
        DateTimeField(
            'effectiveDate',
            mutator='setEffectiveDate',
            languageIndependent=True,
            widget=DatetimeWidget(
                label=_(u'label_effective_date', u'Publishing Date'),
                description=_(
                    u'help_effective_date',
                    default=u"The date when the item will be published. If no "
                    "date is selected the item will be published immediately."
                ),
            ),
        ),
        DateTimeField(
            'expirationDate',
            mutator='setExpirationDate',
            languageIndependent=True,
            widget=DatetimeWidget(
                label=_(u'label_expiration_date', u'Expiration Date'),
                description=_(
                    u'help_expiration_date',
                    default=
                    u"The date when the item expires. This will automatically "
                    "make the item invisible for others at the given date. "
                    "If no date is chosen, it will never expire."),
            ),
        ),
        StringField(
            'language',
            accessor="Language",
            default=config.LANGUAGE_DEFAULT,
            default_method='defaultLanguage',
            vocabulary='languages',
            widget=SelectWidget(label=_(u'label_language',
                                        default=u'Language'), ),
        ),
        TextField(
            'rights',
            accessor="Rights",
            default_method='defaultRights',
            allowable_content_types=('text/plain', ),
            widget=TextAreaWidget(
                label=_(u'label_copyrights', default=u'Rights'),
                description=_(
                    u'help_copyrights',
                    default=
                    u'Copyright statement or other rights information on this item.'
                ),
            )),
    )) + Schema((
        # XXX change this to MetadataSchema in AT 1.4
        # Currently we want to stay backward compatible without migration
        # between beta versions so creation and modification date are using the
        # standard schema which leads to AttributeStorage
        DateTimeField(
            'creation_date',
            accessor='created',
            mutator='setCreationDate',
            default_method=DateTime,
            languageIndependent=True,
            isMetadata=True,
            schemata='metadata',
            generateMode='mVc',
            widget=DatetimeWidget(
                label=_(u'label_creation_date', default=u'Creation Date'),
                description=_(u'help_creation_date',
                              default=u'Date this object was created'),
                visible={
                    'edit': 'invisible',
                    'view': 'invisible'
                }),
        ),
        DateTimeField(
            'modification_date',
            accessor='modified',
            mutator='setModificationDate',
            default_method=DateTime,
            languageIndependent=True,
            isMetadata=True,
            schemata='metadata',
            generateMode='mVc',
            widget=DatetimeWidget(
                label=_(u'label_modification_date',
                        default=u'Modification Date'),
                description=_(u'help_modification_date',
                              default=u'Date this content was modified last'),
                visible={
                    'edit': 'invisible',
                    'view': 'invisible'
                }),
        ),
    ))

    def __init__(self):
        pass

    security.declarePrivate('defaultLanguage')

    def defaultLanguage(self):
        """Retrieve the default language"""
        tool = getToolByName(self, 'portal_languages', None)
        if tool is not None:
            return tool.getDefaultLanguage()
        return config.LANGUAGE_DEFAULT

    security.declarePrivate('defaultRights')

    def defaultRights(self):
        """Retrieve the default rights"""
        mdtool = getToolByName(self, 'portal_metadata', None)
        if mdtool is None:
            return ''
        for sid, schema in mdtool.listSchemas():
            if not hasattr(schema, 'listPolicies'):
                # Broken class from CMFDefault.
                continue
            for pid, policy in schema.listPolicies(typ=self.Type()):
                if pid != 'Rights' and not policy.supply_default:
                    continue
                return policy.default_value
        return ''

    security.declareProtected(permissions.View, 'isDiscussable')

    def isDiscussable(self, encoding=None):
        log_deprecated(
            "The isDiscussable method from the ExtensibleMetadata in "
            "Products.ATContentTypes has been deprecated and will be removed "
            "in Plone 5. This method belongs to the old discussion "
            "infrastructure that already has been replaced by "
            "plone.app.discussion in Plone 4.1.")
        if not 'portal_discussion' in self.objectIds():
            return
        # Returns either True or False
        dtool = getToolByName(self, 'portal_discussion')
        return dtool.isDiscussionAllowedFor(self)

    security.declareProtected(permissions.View, 'editIsDiscussable')

    def editIsDiscussable(self, encoding=None):
        log_deprecated(
            "The editIsDiscussable method from the ExtensibleMetadata in "
            "Products.ATContentTypes has been deprecated and will be removed "
            "in Plone 5. This method belongs to the old discussion "
            "infrastructure that already has been replaced by "
            "plone.app.discussion in Plone 4.1.")
        if not 'portal_discussion' in self.objectIds():
            return
        # Returns True, False or if None the default value
        result = self.rawIsDiscussable()
        if result is not None:
            return result
        default = self.defaultIsDiscussable()
        return default

    security.declareProtected(permissions.View, 'rawIsDiscussable')

    def rawIsDiscussable(self):
        log_deprecated(
            "The rawIsDiscussable method from the ExtensibleMetadata in "
            "Products.ATContentTypes has been deprecated and will be removed "
            "in Plone 5. This method belongs to the old discussion "
            "infrastructure that already has been replaced by "
            "plone.app.discussion in Plone 4.1.")
        if not 'portal_discussion' in self.objectIds():
            return
        # Returns True, False or None where None means use the default
        result = getattr(aq_base(self), 'allow_discussion', None)
        if result is not None:
            result = bool(result)
        return result

    security.declareProtected(permissions.View, 'defaultIsDiscussable')

    def defaultIsDiscussable(self):
        log_deprecated(
            "The defaultIsDiscussable method from the ExtensibleMetadata in "
            "Products.ATContentTypes has been deprecated and will be removed "
            "in Plone 5. This method belongs to the old discussion "
            "infrastructure that already has been replaced by "
            "plone.app.discussion in Plone 4.1.")
        if not 'portal_discussion' in self.objectIds():
            return
        # Returns the default value, either True or False
        default = None
        typeInfo = self.getTypeInfo()
        if typeInfo:
            default = typeInfo.allowDiscussion()
        return default

    security.declareProtected(permissions.ModifyPortalContent,
                              'allowDiscussion')

    def allowDiscussion(self, allowDiscussion=None, **kw):
        pass

    # Vocabulary methods ######################################################

    security.declareProtected(permissions.View, 'languages')

    def languages(self):
        """Vocabulary method for the language field
        """
        util = None

        use_combined = False
        # Respect the combined language code setting from PloneLanguageTool
        lt = getToolByName(self, 'portal_languages', None)
        if lt is not None:
            use_combined = lt.use_combined_language_codes

        # Try the utility first
        if HAS_PLONE_I18N:
            util = queryUtility(IMetadataLanguageAvailability)
        # Fall back to acquiring availableLanguages
        if util is None:
            languages = getattr(self, 'availableLanguages', None)
            if callable(languages):
                languages = languages()
            # Fall back to static definition
            if languages is None:
                return DisplayList(
                    (('en', 'English'), ('fr', 'French'), ('es', 'Spanish'),
                     ('pt', 'Portuguese'), ('ru', 'Russian')))
        else:
            languages = util.getLanguageListing(combined=use_combined)
            languages.sort(key=lambda x: x[1])
            # Put language neutral at the top.
            languages.insert(0, (u'', _(u'Language neutral')))
        return DisplayList(languages)

    #  DublinCore interface query methods #####################################

    security.declareProtected(permissions.View, 'CreationDate')

    def CreationDate(self, zone=None):
        """ Dublin Core element - date resource created.
        """
        if zone is None:
            zone = _zone
        creation = self.getField('creation_date').get(self)
        # return unknown if never set properly
        return creation is None and 'Unknown' or creation.toZone(
            zone).ISO8601()

    security.declareProtected(permissions.View, 'EffectiveDate')

    def EffectiveDate(self, zone=None):
        """ Dublin Core element - date resource becomes effective.
        """
        if zone is None:
            zone = _zone
        effective = self.getField('effectiveDate').get(self)
        return effective is None and 'None' or effective.toZone(zone).ISO8601()

    def _effective_date(self):
        """Computed attribute accessor
        """
        return self.getField('effectiveDate').get(self)

    security.declareProtected(permissions.View, 'effective_date')
    effective_date = ComputedAttribute(_effective_date, 1)

    security.declareProtected(permissions.View, 'ExpirationDate')

    def ExpirationDate(self, zone=None):
        """Dublin Core element - date resource expires.
        """
        if zone is None:
            zone = _zone
        expires = self.getField('expirationDate').get(self)
        return expires is None and 'None' or expires.toZone(zone).ISO8601()

    def _expiration_date(self):
        """Computed attribute accessor
        """
        return self.getField('expirationDate').get(self)

    security.declareProtected(permissions.View, 'expiration_date')
    expiration_date = ComputedAttribute(_expiration_date, 1)

    security.declareProtected(permissions.View, 'Date')

    def Date(self, zone=None):
        """
        Dublin Core element - default date
        """
        # Return effective_date if specifically set, modification date
        # otherwise
        if zone is None:
            zone = _zone
        effective = self.getField('effectiveDate').get(self)
        if effective is None:
            effective = self.modified()
        return (effective is None and DateTime().toZone(zone)
                or effective.toZone(zone).ISO8601())

    security.declareProtected(permissions.View, 'Format')

    def Format(self):
        """cmf/backward compat
        Dublin Core element - resource format
        """
        # FIXME: get content type from marshaller
        return self.getContentType()

    security.declareProtected(permissions.ModifyPortalContent, 'setFormat')

    def setFormat(self, value):
        """cmf/backward compat: ignore setFormat"""
        self.setContentType(value)

    def Identifer(self):
        """ dublin core getId method"""
        return self.getId()

    #  DublinCore utility methods #############################################

    security.declareProtected(permissions.View, 'contentEffective')

    def contentEffective(self, date):
        """Is the date within the resource's effective range?
        """
        effective = self.getField('effectiveDate').get(self)
        expires = self.getField('expirationDate').get(self)
        pastEffective = (effective is None or effective <= date)
        beforeExpiration = (expires is None or expires >= date)
        return pastEffective and beforeExpiration

    security.declareProtected(permissions.View, 'contentExpired')

    def contentExpired(self, date=None):
        """ Is the date after resource's expiration """
        if not date:
            date = DateTime()
        expires = self.getField('expirationDate').get(self)
        if not expires:
            expires = CEILING_DATE
        return expires <= date

    #  CatalogableDublinCore methods ##########################################

    security.declareProtected(permissions.View, 'created')

    def created(self):
        """Dublin Core element - date resource created,
        returned as DateTime.
        """
        # allow for non-existent creation_date, existed always
        created = self.getField('creation_date').get(self)
        return created is None and FLOOR_DATE or created

    security.declareProtected(permissions.View, 'modified')

    def modified(self):
        """Dublin Core element - date resource last modified,
        returned as DateTime.
        """
        modified = self.getField('modification_date').get(self)
        # TODO may return None
        return modified

    security.declareProtected(permissions.View, 'effective')

    def effective(self):
        """Dublin Core element - date resource becomes effective,
        returned as DateTime.
        """
        effective = self.getField('effectiveDate').get(self)
        return effective is None and FLOOR_DATE or effective

    security.declareProtected(permissions.View, 'expires')

    def expires(self):
        """Dublin Core element - date resource expires,
        returned as DateTime.
        """
        expires = self.getField('expirationDate').get(self)
        return expires is None and CEILING_DATE or expires

    ## code below come from CMFDefault.DublinCore.DefaultDublinCoreImpl #######

    ###########################################################################
    #
    # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved
    #
    # This software is subject to the provisions of the Zope Public License,
    # Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
    # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
    # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
    # FOR A PARTICULAR PURPOSE
    #
    ###########################################################################

    #
    #  Set-modification-date-related methods.
    #  In DefaultDublinCoreImpl for lack of a better place.
    #

    security.declareProtected(permissions.ModifyPortalContent,
                              'notifyModified')

    def notifyModified(self):
        """
        Take appropriate action after the resource has been modified.
        For now, change the modification_date.
        """
        self.setModificationDate(DateTime())
        if shasattr(self, 'http__refreshEtag'):
            self.http__refreshEtag()

    security.declareProtected(permissions.ManagePortal, 'setModificationDate')

    def setModificationDate(self, modification_date=None):
        """Set the date when the resource was last modified.
        When called without an argument, sets the date to now.
        """
        if modification_date is None:
            modified = DateTime()
        else:
            modified = self._datify(modification_date)
        self.getField('modification_date').set(self, modified)

    security.declareProtected(permissions.ManagePortal, 'setCreationDate')

    def setCreationDate(self, creation_date=None):
        """Set the date when the resource was created.
        When called without an argument, sets the date to now.
        """
        if creation_date is None:
            created = DateTime()
        else:
            created = self._datify(creation_date)
        self.getField('creation_date').set(self, created)

    security.declarePrivate('_datify')

    def _datify(self, date):
        """Try to convert something into a DateTime instance or None
        """
        # stupid web
        if date == 'None':
            date = None
        if not isinstance(date, DateTime):
            if date is not None:
                date = DateTime(date)
        return date

    #
    #  DublinCore interface query methods
    #
    security.declareProtected(permissions.View, 'Publisher')

    def Publisher(self):
        """Dublin Core element - resource publisher
        """
        # XXX: fixme using 'portal_metadata'
        return 'No publisher'

    security.declareProtected(permissions.View, 'ModificationDate')

    def ModificationDate(self, zone=None):
        """ Dublin Core element - date resource last modified.
        """
        if zone is None:
            zone = _zone
        modified = self.modified()
        return (modified is None and DateTime().toZone(zone)
                or modified.toZone(zone).ISO8601())

    security.declareProtected(permissions.View, 'Type')

    def Type(self):
        """Dublin Core element - Object type"""
        if hasattr(aq_base(self), 'getTypeInfo'):
            ti = self.getTypeInfo()
            if ti is not None:
                return ti.Title()
        return self.meta_type

    security.declareProtected(permissions.View, 'Identifier')

    def Identifier(self):
        """Dublin Core element - Object ID"""
        # XXX: fixme using 'portal_metadata' (we need to prepend the
        #      right prefix to self.getPhysicalPath().
        return self.absolute_url()

    security.declareProtected(permissions.View, 'listContributors')

    def listContributors(self):
        """Dublin Core element - Contributors"""
        return self.Contributors()

    security.declareProtected(permissions.ModifyPortalContent, 'addCreator')

    def addCreator(self, creator=None):
        """ Add creator to Dublin Core creators.
        """
        if creator is None:
            mtool = getToolByName(self, 'portal_membership', None)
            if mtool is None:
                return
            creator = mtool.getAuthenticatedMember().getId()

        # call self.listCreators() to make sure self.creators exists
        curr_creators = self.listCreators()
        if creator and not creator in curr_creators:
            self.setCreators(curr_creators + (creator, ))

    security.declareProtected(permissions.View, 'listCreators')

    def listCreators(self):
        """ List Dublin Core Creator elements - resource authors.
        """
        creators = self.Schema()['creators']
        if not creators.get(self):
            # for content created with CMF versions before 1.5
            owner_tuple = self.getOwnerTuple()
            owner_id = owner_tuple and owner_tuple[1]
            if owner_id:
                creators.set(self, (owner_id, ))
            else:
                creators.set(self, ())

        return creators.get(self)

    security.declareProtected(permissions.View, 'Creator')

    def Creator(self):
        """ Dublin Core Creator element - resource author.
        """
        creators = self.listCreators()
        return creators and creators[0] or ''

    #
    #  DublinCore utility methods
    #

    # Deliberately *not* protected by a security declaration
    # See https://dev.plone.org/archetypes/ticket/712
    def content_type(self):
        """ WebDAV needs this to do the Right Thing (TM).
        """
        return self.Format()

    #
    #  CatalogableDublinCore methods
    #

    security.declareProtected(permissions.View, 'getMetadataHeaders')

    def getMetadataHeaders(self):
        """ Return RFC-822-style headers.
        """
        hdrlist = []
        hdrlist.append(('Title', self.Title()))
        hdrlist.append(('Subject', string.join(self.Subject(), ', ')))
        hdrlist.append(('Publisher', self.Publisher()))
        hdrlist.append(('Description', self.Description()))
        hdrlist.append(('Contributors', string.join(self.Contributors(),
                                                    '; ')))
        hdrlist.append(('Creators', string.join(self.Creators(), '; ')))
        hdrlist.append(('Effective_date', self.EffectiveDate()))
        hdrlist.append(('Expiration_date', self.ExpirationDate()))
        hdrlist.append(('Type', self.Type()))
        hdrlist.append(('Format', self.Format()))
        hdrlist.append(('Language', self.Language()))
        hdrlist.append(('Rights', self.Rights()))
        return hdrlist

    #
    #  Management tab methods
    #

    security.declarePrivate('_editMetadata')

    def _editMetadata(
        self,
        title=_marker,
        subject=_marker,
        description=_marker,
        contributors=_marker,
        effective_date=_marker,
        expiration_date=_marker,
        format=_marker,
        language=_marker,
        rights=_marker,
    ):
        """ Update the editable metadata for this resource.
        """
        if title is not _marker:
            self.setTitle(title)
        if subject is not _marker:
            self.setSubject(subject)
        if description is not _marker:
            self.setDescription(description)
        if contributors is not _marker:
            self.setContributors(contributors)
        if effective_date is not _marker:
            self.setEffectiveDate(effective_date)
        if expiration_date is not _marker:
            self.setExpirationDate(expiration_date)
        if format is not _marker:
            self.setFormat(format)
        if language is not _marker:
            self.setLanguage(language)
        if rights is not _marker:
            self.setRights(rights)

    security.declareProtected(permissions.ModifyPortalContent,
                              'manage_metadata')
    manage_metadata = DTMLFile('zmi_metadata', config._www)

    security.declareProtected(permissions.ModifyPortalContent,
                              'manage_editMetadata')

    def manage_editMetadata(
        self,
        title,
        subject,
        description,
        contributors,
        effective_date,
        expiration_date,
        format,
        language,
        rights,
        REQUEST,
    ):
        """ Update metadata from the ZMI.
        """
        self._editMetadata(
            title,
            subject,
            description,
            contributors,
            effective_date,
            expiration_date,
            format,
            language,
            rights,
        )
        REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_metadata' +
                                     '?manage_tabs_message=Metadata+updated.')

    security.declareProtected(permissions.ModifyPortalContent, 'editMetadata')

    def editMetadata(
        self,
        title='',
        subject=(),
        description='',
        contributors=(),
        effective_date=None,
        expiration_date=None,
        format='text/html',
        language='en-US',
        rights='',
    ):
        """
        used to be:  editMetadata = WorkflowAction(_editMetadata)
        Need to add check for webDAV locked resource for TTW methods.
        """
        self.failIfLocked()
        self._editMetadata(
            title=title,
            subject=subject,
            description=description,
            contributors=contributors,
            effective_date=effective_date,
            expiration_date=expiration_date,
            format=format,
            language=language,
            rights=rights,
        )
        self.reindexObject()
Beispiel #8
0
     )
 ),
 StringField('default',
     schemata="default",
     widget=StringWidget(
         size=25,
         label=_(u'Default value'),
         description=_(u'Default string to search for'),
         i18n_domain="eea"
     )
 ),
 BooleanField('onlyallelements',
     schemata="default",
     widget=BooleanWidget(
         label=_(u'Search in all elements only'),
         description=_(u'If this checkbox is checked, hides the choice to '
                       u'filter in all items or in current items only'),
         i18n_domain="eea"
     )
 ),
 BooleanField('wildcard',
     schemata="default",
     widget=BooleanWidget(
         label=_(u'Wildcard search'),
         description=_(u"If this checkbox is checked, the system will "
                       u"automatically do a wildcard search by appending "
                       u"a '*' to the search term so "
                       u"searching for 'budget' will also return elements "
                       u"containing 'budgetary'."),
         i18n_domain="eea"
     )
 ),
Beispiel #9
0
class BikaSetupSchemaExtender(object):
    adapts(IBikaSetup)
    implements(IOrderableSchemaExtender)

    fields = [
        ExtBooleanField('EnablePanicAlert',
                        schemata="Analyses",
                        default=False,
                        widget=BooleanWidget(
                            label=_("Enable panic levels alert"),
                            description=_(
                                "Alert labmanagers with an email when an "
                                "analysis result exceeding a panic level is "
                                "submitted"))),
        ExtBooleanField(
            'AutoShowPanicAlertEmailPopup',
            schemata="Analyses",
            default=False,
            widget=BooleanWidget(
                label=_("Show client email pop-up when panic level"),
                description=_("If enabled, shows automatically an email form "
                              "pop-up for alerting the client about a panic "
                              "level exceeded when Analysis Request view is "
                              "loaded"))),
        ExtStringField(
            'PatientConditionsHeightUnits',
            schemata="Cases",
            default=_("Feet/inches"),
            widget=StringWidget(
                label=_("Patient condition height units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtStringField(
            'PatientConditionsWeightUnits',
            schemata="Cases",
            default=_("Lbs"),
            widget=StringWidget(
                label=_("Patient condition weight units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtStringField(
            'PatientConditionsWaistUnits',
            schemata="Cases",
            default=_("Inches"),
            widget=StringWidget(
                label=_("Patient condition waist units"),
                description=_(
                    "Use '/' symbol to allow multiple-units submission"))),
        ExtBooleanField(
            'AllowResultsDistributionToPatients',
            schemata="Results Reports",
            default=False,
            widget=BooleanWidget(
                label=_("Allow results distribution to Patients"),
                description=_("If checked, results reports will also be sent "
                              "to the Patient automatically. This setting can "
                              "be overriden either on 'Patient publication "
                              "preferences' tab from Client view or on "
                              "Patient's 'Publication preferences' tab."))),
        ExtLinesField(
            'PatientPublicationPreferences',
            vocabulary=PUBLICATION_PREFS,
            schemata='Results Reports',
            widget=MultiSelectionWidget(
                label=_("Default publication preference for Patients"),
                description=_("Select the preferred channels to be used for "
                              "sending the results reports to Patients. "
                              "This setting can be overriden either on "
                              "'Patient publication preferences' tab from "
                              "Client view or on Patient's 'Publication "
                              "preferences' tab."))),
        ExtBooleanField('PatientPublicationAttachmentsPermitted',
                        default=False,
                        schemata='Results Reports',
                        widget=BooleanWidget(
                            label=_("Results attachments permitted"),
                            description=_(
                                "File attachments to results, e.g. microscope "
                                "photos, will be included in emails to "
                                "patients if this option is enabled. This "
                                "setting can be overriden either on 'Patient "
                                "publication preferences' tab from Client "
                                "view or on Patient's 'Publication "
                                "preferences' tab."))),
    ]

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

    def getFields(self):
        return self.fields

    def getOrder(self, schematas):
        sch = schematas['Results Reports']
        sch.remove('AllowResultsDistributionToPatients')
        sch.insert(sch.index('PatientPublicationPreferences'),
                   'AllowResultsDistributionToPatients')
        schematas['Results Reports'] = sch
        return schematas
from imio.dashboard.interfaces import IDashboardCollection
from imio.dashboard import ImioDashboardMessageFactory as _

################################################################################
#                                                                              #
#  DEPRECATED, THIS CONTENT WAS MOVED TO COLLECTIVE.EEAFACETED.DASHBOARD !!!   #
#                                                                              #
#  STILL EXISTS FOR MIGRATION PURPOSE !!!                                      #
#                                                                              #
################################################################################

DashboardCollectionSchema = CollectionSchema.copy() + atapi.Schema(
    (BooleanField(
        name="showNumberOfItems",
        required=False,
        widget=BooleanWidget(label=_(u'Show number of items in filter'), ),
        schemata="default",
    ), ))

# hide these fields to avoid conflict with eea.facetednavigation parameters
DashboardCollectionSchema['limit'].default = 0
DashboardCollectionSchema['b_size'].widget.visible = -1
DashboardCollectionSchema['limit'].widget.visible = -1


class DashboardCollection(Collection):
    """A Collection used in our dashboards"""
    implements(IDashboardCollection)
    meta_type = "DashboardCollection"
    schema = DashboardCollectionSchema
    security = ClassSecurityInfo()
from Products.Archetypes.Widget import BooleanWidget

from Products.ATContentTypes.content.folder import ATFolder

from Products.PloneArticle.interfaces import IPloneArticleMultiPage

from Products.PloneArticle.config import PROJECTNAME

schema = ATFolder.schema.copy() \
         + Schema((
    BooleanField(
        'viewTOCFirst',
        default=False,
        widget=BooleanWidget(
            label='View table of contents first',
            label_msgid='label_view_toc_first',
            i18n_domain='plonearticle',
            visible={'view' : 'invisible'},
        )
    ),
    BooleanField(
        'viewTOC',
        default=True,
        widget=BooleanWidget(
            label='Display table of contents in dropdown list',
            label_msgid='label_display_toc_dropdown',
            description='If you have checked properties to view TOC first, this property will not be applied.',
            description_msgid='description_display_toc_dropdown',
            i18n_domain='plonearticle',
            visible={'view' : 'invisible'},
        )
    ),
Beispiel #12
0
class BatchSchemaExtender(object):
    adapts(IBatch)
    implements(IOrderableSchemaExtender)

    fields = [
        ExtReferenceField(
            'Doctor',
            required=1,
            multiValued=0,
            allowed_types=('Doctor', ),
            referenceClass=HoldingReference,
            relationship='BatchDoctor',
            widget=ReferenceWidget(
                label=_("Doctor"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                base_query={'is_active': True},
                catalog_name='portal_catalog',
                showOn=True,
                colModel=[
                    {
                        'columnName': 'DoctorID',
                        'width': '20',
                        'label': _('Doctor ID')
                    },
                    {
                        'columnName': 'Title',
                        'width': '80',
                        'label': _('Full Name')
                    },
                ],
            ),
        ),
        ExtReferenceField(
            'Patient',
            required=1,
            multiValued=0,
            allowed_types=('Patient', ),
            referenceClass=HoldingReference,
            relationship='BatchPatient',
            widget=ReferenceWidget(
                label=_("Patient"),
                description="",
                render_own_label=False,
                visible={
                    'edit': 'visible',
                    'view': 'visible'
                },
                catalog_name='bikahealth_catalog_patient_listing',
                search_fields=('listing_searchable_text', ),
                base_query={
                    'is_active': True,
                    'sort_limit': 50,
                    'sort_on': 'getPatientID',
                    'sort_order': 'ascending'
                },
                colModel=[
                    {
                        'columnName': "getPatientID",
                        'width': '30',
                        'label': _('PID'),
                        'align': 'left'
                    },
                    {
                        'columnName': "getClientPatientID",
                        'width': '30',
                        'label': _('CPID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'Title',
                        'width': '30',
                        'label': _('Title'),
                        'align': 'left'
                    },
                ],
                showOn=True,
            ),
        ),
        ExtDateTimeField(
            'OnsetDate',
            required=1,
            widget=DateTimeWidget(label=_('Onset Date'), ),
        ),
        ExtRecordsField(
            'PatientAgeAtCaseOnsetDate',
            widget=SplittedDateWidget(
                label=_('Patient Age at Case Onset Date'), ),
        ),
        ExtBooleanField(
            'OnsetDateEstimated',
            default=False,
            widget=BooleanWidget(label=_("Onset Date Estimated"), ),
        ),
        ExtRecordsField(
            'ProvisionalDiagnosis',
            type='provisionaldiagnosis',
            subfields=('Code', 'Title', 'Description', 'Onset'),
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            #required_subfields=('Title'),
            subfield_sizes={
                'Code': 7,
                'Title': 20,
                'Description': 35,
                'Onset': 10
            },
            subfield_labels={
                'Code': _('Code'),
                'Title': _('Provisional diagnosis'),
                'Description': _('Description'),
                'Onset': _('Onset')
            },
            subfield_types={'Onset': 'datepicker_nofuture'},
            widget=RecordsWidget(
                label='Provisional diagnosis',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbytitle',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Code': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbycode',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                    'Description': {
                        'colModel': [{
                            'columnName': 'Code',
                            'width': '10',
                            'label': _('Code')
                        }, {
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Title')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _('Description')
                        }],
                        'url':
                        'getsymptomsbydesc',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtTextField(
            'AdditionalNotes',
            default_content_type='text/plain',
            allowable_content_types=('text/plain', ),
            default_output_type="text/plain",
            widget=TextAreaWidget(label=_('Additional notes'), ),
        ),
        ExtLinesField(
            'CaseStatus',
            vocabulary=getCaseStatus(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case status")),
        ),
        ExtLinesField(
            'CaseOutcome',
            vocabulary=getCaseOutcome(),
            widget=MultiSelectionWidget(format='checkbox',
                                        label=_("Case outcome")),
        ),
        ExtRecordsField(
            'Symptoms',
            type='symptoms',
            subfields=('UID', 'Title', 'Description', 'Severity'),
            widget=CaseSymptomsWidget(label='Symptoms', ),
        ),
        ExtRecordsField(
            'AetiologicAgents',
            type='aetiologicagents',
            subfields=('Title', 'Description', 'Subtype'),
            subfield_sizes={
                'Title': 15,
                'Description': 25,
                'Subtype': 10
            },
            subfield_labels={
                'Title': _('Aetiologic agent'),
                'Description': _b('Description'),
                'Subtype': _('Subtype')
            },
            # Temporary fix: https://github.com/bikalabs/bika.health/issues/89
            # required_subfields=('Title'),
            widget=RecordsWidget(
                label='Aetiologic agents',
                combogrid_options={
                    'Title': {
                        'colModel': [{
                            'columnName': 'Title',
                            'width': '30',
                            'label': _('Aetiologic agent')
                        }, {
                            'columnName': 'Description',
                            'width': '60',
                            'label': _b('Description')
                        }, {
                            'columnName': 'Subtype',
                            'width': '30',
                            'label': _('Subtype')
                        }],
                        'url':
                        'getaetiologicagents',
                        'showOn':
                        True,
                        'width':
                        "650px",
                    },
                },
            ),
        ),
        ExtIntegerField(
            'HoursFasting',
            required=0,
            widget=IntegerWidget(label=_('Hours fasting'), ),
        ),
        ExtRecordsField(
            'PatientCondition',
            widget=CasePatientConditionWidget(label='Patient condition', ),
        ),
        ExtRecordsField(
            'MenstrualStatus',
            widget=CaseMenstrualStatusWidget(label='Menstrual status', ),
        ),
        ExtRecordsField(
            'BasalBodyTemperature',
            widget=CaseBasalBodyTempWidget(label='Basal body temperature', ),
        ),
        ExtStringField(
            'ClientPatientID',
            required=0,
            widget=ReferenceWidget(
                label=_b("Client Patient ID"),
                size=20,
                visible={
                    'edit': 'invisible',
                    'view': 'visible',
                    'add': 'edit'
                },
                catalog_name='bikahealth_catalog_patient_listing',
                portal_types=('Patient', ),
                search_fields=('getClientPatientID', ),
                base_query={
                    'is_active': True,
                    'sort_limit': 50,
                    'sort_on': 'getClientPatientID',
                    'sort_order': 'ascending'
                },
                force_all=False,
                colModel=[
                    {
                        'columnName': "getPatientID",
                        'width': '30',
                        'label': _('PID'),
                        'align': 'left'
                    },
                    {
                        'columnName': "getClientPatientID",
                        'width': '30',
                        'label': _('CPID'),
                        'align': 'left'
                    },
                    {
                        'columnName': 'Title',
                        'width': '30',
                        'label': _('Fullname'),
                        'align': 'left'
                    },
                    # UID is required in colModel
                    {
                        'columnName': 'UID',
                        'hidden': True
                    },
                ],
                ui_item="getClientPatientID",
                showOn=False,
            ),
        ),
    ]

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

    def getOrder(self, schematas):
        schematas['default'] = [
            'id',
            'title',
            'description',
            'BatchID',
            'Client',
            'ClientBatchID',
            'ClientPatientID',
            'Patient',
            'Doctor',
            'BatchDate',
            'OnsetDate',
            'OnsetDateEstimated',
            'PatientAgeAtCaseOnsetDate',
            'HoursFasting',
            'PatientCondition',
            'BasalBodyTemperature',
            'MenstrualStatus',
            'Symptoms',
            'ProvisionalDiagnosis',
            'CaseStatus',
            'CaseOutcome',
            'AetiologicAgents',
            'AdditionalNotes',
            'Remarks',
            'BatchLabels',
        ]
        return schematas

    def getFields(self):
        return self.fields
Beispiel #13
0
class AnalysisRequestSchemaExtender(object):
    adapts(IAnalysisRequest)
    implements(IOrderableSchemaExtender)

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

    fields = [
        ExtProxyField("ParticipantID",
                      proxy="context.getSample()",
                      mode="rw",
                      required=1,
                      widget=StringWidget(
                          label=_("Participant ID"),
                          maxlength=22,
                          size=22,
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField("OtherParticipantReference",
                      proxy="context.getSample()",
                      mode="rw",
                      required=0,
                      widget=StringWidget(
                          label=_("Other Participant Ref"),
                          maxlength=12,
                          size=12,
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField("ParticipantInitials",
                      proxy="context.getSample()",
                      mode="rw",
                      required=1,
                      widget=StringWidget(
                          label=_("Participant Initials"),
                          maxlength=3,
                          size=2,
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField("Gender",
                      proxy="context.getSample()",
                      mode="rw",
                      required=1,
                      vocabulary=GENDERS,
                      widget=SelectionWidget(
                          format="radio",
                          label=_("Gender"),
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField("Visit",
                      proxy="context.getSample()",
                      mode="rw",
                      required=1,
                      widget=StringWidget(
                          label=_("Visit Number"),
                          maxlength=4,
                          size=4,
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField(
            "Fasting",
            proxy="context.getSample()",
            mode="rw",
            required=0,
            default=False,
            widget=BooleanWidget(
                format="radio",
                label=_("Fasting"),
                render_own_label=True,
                visible={
                    'edit': 'visible',
                    'view': 'visible',
                    'add': 'edit',
                    'header_table': 'visible'
                },
            ),
        ),
        ExtProxyField(
            'DateOfBirth',
            proxy="context.getSample()",
            mode="rw",
            required=1,
            widget=DateTimeWidget(
                label=_('Date of Birth'),
                datepicker_nofuture=1,
                show_time=False,
                render_own_label=True,
                visible={
                    'edit': 'visible',
                    'view': 'visible',
                    'add': 'edit',
                    'header_table': 'visible'
                },
            ),
        ),
        ExtProxyField("Volume",
                      proxy="context.getSample()",
                      mode="rw",
                      required=1,
                      widget=StringWidget(
                          label=_("Estimated Sample Volume"),
                          maxlength=8,
                          size=8,
                          render_own_label=True,
                          visible={
                              'edit': 'visible',
                              'view': 'visible',
                              'add': 'edit',
                              'header_table': 'visible'
                          },
                      )),
        ExtProxyField(
            "OtherInformation",
            proxy="context.getSample()",
            mode="rw",
            default_content_type="text/plain",
            allowable_content_types=("text/plain", ),
            default_output_type="text/plain",
            widget=TextAreaWidget(
                label=_("Other relevant clinical information"),
                render_own_label=True,
                visible={
                    'edit': 'visible',
                    'view': 'visible',
                    'add': 'edit',
                    'header_table': 'visible'
                },
            ),
        ),
        ExtProxyField(
            "Courier",
            proxy="context.getSample()",
            required=0,
            allowed_types='Courier',
            relationship='AnalysisRequestCourier',
            mode="rw",
            read_permission=View,
            write_permission=ModifyPortalContent,
            widget=ReferenceWidget(
                label=_("Courier"),
                description=_("The person who delivered the sample"),
                render_own_label=True,
                visible={
                    'view': 'visible',
                    'edit': 'visible',
                    'add': 'invisible',
                    'header_table': 'visible',
                    'secondary': 'disabled',
                    'sample_registered': {
                        'view': 'invisible',
                        'edit': 'invisible'
                    },
                    'to_be_sampled': {
                        'view': 'invisible',
                        'edit': 'invisible'
                    },
                    'scheduled_sampling': {
                        'view': 'invisible',
                        'edit': 'invisible'
                    },
                    'sampled': {
                        'view': 'invisible',
                        'edit': 'invisible'
                    },
                    'to_be_preserved': {
                        'view': 'invisible',
                        'edit': 'invisible'
                    },
                    'sample_ordered': {
                        'view': 'visible',
                        'edit': 'visible'
                    },
                    'sample_due': {
                        'view': 'visible',
                        'edit': 'visible'
                    },
                    'sample_prep': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'sample_received': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'attachment_due': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'to_be_verified': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'verified': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'published': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'invalid': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                    'rejected': {
                        'view': 'visible',
                        'edit': 'invisible'
                    },
                },
                catalog_name='bika_setup_catalog',
                base_query={'review_state': 'active'},
                showOn=True,
            ),
        ),

        # This Analysis Request is only for internal use?
        # This field is useful when we create Partitions (AR-like), so we don't
        # want the client to see Analysis Requests / Samples that are meant to
        # be used in the lab.
        ExtProxyField(
            "InternalUse",
            proxy="context.getSample()",
            mode="rw",
            required=0,
            default=False,
            widget=BooleanWidget(
                format="radio",
                label=_("Internal use"),
                render_own_label=True,
                visible={
                    'edit': 'visible',
                    'view': 'visible',
                    'add': 'edit',
                    'header_table': 'visible'
                },
            ),
        ),
        ExtProxyField(
            "PrimarySample",
            proxy="context.getSample()",
            required=0,
            allowed_types=('Sample'),
            relationship='SamplePrimarySample',
            mode="rw",
            read_permission=View,
            write_permission=ModifyPortalContent,
            widget=ReferenceWidget(
                label=_("Primary Sample"),
                description=_("The sample this is originated from"),
                size=20,
                render_own_label=True,
                visible={
                    'view': 'visible',
                    'edit': 'invisible',
                    'add': 'invisible',
                    'header_table': 'visible',
                    'secondary': 'disabled',
                },
                catalog_name='bika_catalog',
                base_query={'review_state': 'active'},
                showOn=False,
            ),
        ),
        ExtReferenceField(
            'PrimaryAnalysisRequest',
            allowed_types=('AnalysisRequest', ),
            relationship='AnalysisRequestPrimaryAnalysisRequest',
            referenceClass=HoldingReference,
            mode="rw",
            read_permission=View,
            write_permission=ModifyPortalContent,
            widget=ReferenceWidget(visible=False, ),
        ),
        ExtBooleanField(
            "PanicEmailAlertSent",
            default=False,
            widget=BooleanWidget(visible={
                'edit': 'invisible',
                'view': 'invisible',
                'add': 'invisible'
            }, ),
        )
    ]

    def getOrder(self, schematas):
        return schematas

    def getFields(self):
        return self.fields
         render_own_label=True,
         visible={
             'add': 'edit',
         },
     )),
 ExtBooleanField(
     "Fasting",
     mode="rw",
     required=0,
     read_permission=View,
     write_permission=ModifyPortalContent,
     default=False,
     widget=BooleanWidget(
         format="radio",
         label=_("Fasting"),
         render_own_label=True,
         visible={
             'add': 'edit',
         },
     ),
 ),
 ExtDateTimeField(
     'DateOfBirth',
     mode="rw",
     required=1,
     read_permission=View,
     write_permission=ModifyPortalContent,
     widget=DateTimeWidget(
         label=_('Date of Birth'),
         datepicker_nofuture=1,
         show_time=False,
         render_own_label=True,
Beispiel #15
0
class Slide(ATFolder):
    """The basic slide represents a part of a lecture consisting of several slides.
    The basic component of the tutor-web is the slide. A slide can contain four main components:
    maintext, and main graphic, explanation text and explanation graphic. Additionally related material relevant to a given
slide can be set, detailed material, examples handouts and alternative material.
    """
    IMAGE_FORMATS = DisplayList((
        ('none', 'No image'),
        ('image', 'png, gif or jpeg'),
        ('fig', 'Fig'),
        ('r', 'R'),
        ('gnuplot', 'gnuplot'),
    ))

    schema = ATFolderSchema.copy() + Schema((
        StringField(
            'id',
            widget=StringWidget(
                description=
                'Change ID to become more readable. Slides appear in alphabetical order based on this value.',
                modes='edit',
            ),
            required=1,
        ),
        StringField(
            'title',
            required=True,
            searchable=0,
            default='Slide',
            widget=StringWidget(
                label='Title',
                description='The main title of the slide',
            ),
        ),
        ReferenceField(
            'ExtraMaterials',
            widget=ReferenceBrowserWidget(
                label="Extra material",
                description='Extra material connected to the slide material.',
                destination=".",
                destination_types=("File", ),
                visible={'edit': 'invisible'},
            ),

            #required = 1,
            multiValued=True,
            relationship='hasExtraMaterial',
            allowed_types=("File", ),
        ),
        BooleanField(
            "UpdateSlideText",
            default=1,
            widget=BooleanWidget(
                label='Update transformable slide text data',
                description='Check this box if you want transformable text data '
                'to be updated.',
            ),
        ),
        BooleanField(
            "SlideTextChanged",
            default=0,
            widget=BooleanWidget(
                label=
                'This is a control parameter to check if text has been changed recently.',
                #label_msgid='randomize_answer_order_label',
                description='Slide is updated if text has been changed.',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'SlideText',
            searchable=0,
            default_content_type='text/latex',
            default_output_type='text/latex',
            accessor='SlideTextRaw',
            mutator='setSlideText',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'SlideTextView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'SlideImageFormat',
            vocabulary=IMAGE_FORMATS,
            default='none',
            widget=SelectionWidget(
                label='Image format',
                description=
                'Select the format of the main image. It can be a file with format png, gif or jpeg. Or the main image can be rendered from a text based image format of type R, Gnuplot or Fig.',
            ),
        ),
        TextField(
            'SlideImageText',
            allowable_content_types=(),
            default_output_type='text/plain',
            default_content_type='text/plain',
            widget=RichWidget(
                label='Image definnition',
                description=
                'Main image for slide, displayed to the right of main text of the slide. Possible formats are: fig, gnuplot and R.',
                allow_file_upload=1,
                macro='tutorwebtext_notkupu',
                #condition ='not:object/isImageFormat',
            ),
        ),
        StringField(
            'SlideImageCaption',
            widget=TextAreaWidget(
                label="Main image caption",
                description="Main image caption",
            ),
        ),
        ImageField(
            'SlideImage',
            #original_size=(600,600),
            max_size=(600, 600),
            #sizes={ 'mini' : (80,80),
            #        'normal' : (200,200),
            #         'big' : (100,100),
            #         'maxi' : (500,500),
            #        },
            widget=ImageWidget(
                label='Slide image',
                description=
                'Main image for slide, displayed to the right of main text of the slide. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                # condition ='object/isImageFormat',
            )),
        ImageField(
            'SlideImageWWW',
            max_size=(300, 300),
            widget=ImageWidget(
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                modes='view',
                visible={
                    'view': 'invisible',
                    'edit': 'invisible'
                },
            ),
        ),
        TextField(
            'Explanation',
            searchable=0,
            accessor='ExplanationRaw',
            mutator='setExplanation',
            default_content_type='text/latex',
            default_output_type='text/latex',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
                'text/html',
            ),
            widget=RichWidget(
                label='Explanation text',
                description=
                'Explantory material, displayed at the bottom of the slide',
                macro='tutorwebtext_notkupu_small',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'ExplanationView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'ExplanationImageFormat',
            vocabulary=IMAGE_FORMATS,
            default='none',
            widget=SelectionWidget(
                label='Image format',
                description=
                'Select the format of the explanation image. It can be a file with format png, gif or jpeg. Or the main image can be rendered from a text based image format of type R, Gnuplot or Fig.',
                #visible = {'edit': 'invisible'},
            ),
        ),
        TextField(
            'ExplanationImageText',
            allowable_content_types=(),
            default_output_type='text/plain',
            default_content_type='text/plain',
            widget=RichWidget(
                label='Image definition',
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of the explanation text. Possible formats are: fig, gnuplot and R',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
                #visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'ExplanationImageCaption',
            widget=TextAreaWidget(
                label="Explanation image caption",
                description="Explanation image caption",
                #visible={'edit': 'invisible'},
            ),
        ),
        ImageField(
            'ExplanationImage',
            max_size=(600, 600),
            widget=ImageWidget(
                label='Explanation image',
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                #visible={'edit':'invisible'},
            ),
        ),
        ImageField(
            'ExplanationImageWWW',
            max_size=(200, 200),
            widget=ImageWidget(
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                modes='view',
                visible={
                    'view': 'invisible',
                    'edit': 'invisible'
                },
            ),
        ),
        TextField(
            'Details',
            searchable=0,
            accessor='DetailsRaw',
            mutator='setDetails',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
            ),
            widget=RichWidget(
                description=
                'Detailed information on the topic of the slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'DetailsView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Examples',
            searchable=0,
            accessor='ExamplesRaw',
            mutator='setExamples',
            default_content_type='text/latex',
            default_output_type='text/latex',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                description=
                'Examples for slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'ExamplesView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Alternative',
            searchable=0,
            accessor='AlternativeRaw',
            mutator='setAlternative',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
                'text/html',
            ),
            widget=RichWidget(
                description=
                'Alternate educational material for slide which can be accessed from the main slide view.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'AlternativeView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Handout',
            searchable=0,
            accessor='HandoutRaw',
            mutator='setHandout',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                description=
                'Handout for slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'HandoutView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'SlideReference',
            searchable=0,
            accessor='SlideReferenceRaw',
            mutator='setSlideReference',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                label='Reference',
                description=
                'Slide references are printed as part of a pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'SlideReferenceView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
    ))

    implements(IPrintable, ISlide, IOrderedTutorWebContent)
    security = ClassSecurityInfo()
    # This prevents the Questions from showing up as a portal content type
    global_allow = False
    meta_type = 'Slide'  # zope type name
    portal_type = meta_type  # plone type name
    archetype_name = 'Slide'  # friendly type name
    changed = True

    def useExplanationFig(self):
        return EXPLANATION_FIG

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

    def RawSlideText(self):
        return self.getRawSlideText()

    def RawExplanation(self):
        return self.getRawExplanation()

    def RawDetails(self):
        return self.getRawDetails()

    def RawExamples(self):
        return self.getRawExamples()

    def RawAlternative(self):
        return self.getRawAlternative()

    def RawHandout(self):
        return self.getRawHandout()

    def SlideTextRaw(self):
        return self.getSlideTextView()

    def ExplanationRaw(self):
        return self.getExplanationView()

    def DetailsRaw(self):
        return self.getDetailsView()

    def ExamplesRaw(self):
        return self.getExamplesView()

    def AlternativeRaw(self):
        return self.getAlternativeView()

    def HandoutRaw(self):
        return self.getHandoutView()

    def SlideReferenceRaw(self):
        return self.getSlideReferenceView()

    def setSlideText(self, value, **kwargs):
        '''set main slide text'''
        f = self.getField('SlideText')
        f.set(self, value, raw=True, **kwargs)
        self.setSlideTextView(value)

    def setSlideTextView(self, value):
        """update and render appropriate slide text material"""
        if (self.UpdateSlideText):
            f = self.getField('SlideTextView')
            text = self.getRawSlideText()
            type = self.SlideText.getContentType()
            value = self.transformText(type, text, 'slidetext')
            f.set(self, value)
            self.setSlideTextChanged(1)

    def setSlideTextView2(self, value):
        f = self.getField('SlideTextView')
        f.set(self, value)

    def setSlideTextView3(self, value):
        f = self.getField('SlideTextView')
        text = self.getRawSlideText()
        type = self.SlideText.getContentType()
        val = self.transformText(type, text, 'slidetext')
        f.set(self, val)

    def setSlideTextView1(self, value):
        f = self.getField('SlideTextView')
        text = self.getRawSlideText()
        type = self.SlideText.getContentType()
        val = self.transformText(type, text, 'slidetext')
        f.set(self, val)
        f1 = self.getField('ExplanationView')
        text1 = self.getRawExplanation()
        type1 = self.Explanation.getContentType()
        value1 = self.transformText(type1, text1, 'explanation')
        f1.set(self, value1)
        f2 = self.getField('DetailsView')
        text2 = self.getRawDetails()
        type2 = self.Details.getContentType()
        value2 = self.transformText(type2, text2, 'details')
        f2.set(self, value2)
        f3 = self.getField('ExamplesView')
        text3 = self.getRawExamples()
        type3 = self.Examples.getContentType()
        value3 = self.transformText(type3, text3, 'examples')
        f3.set(self, value3)
        f4 = self.getField('HandoutView')
        text4 = self.getRawHandout()
        type4 = self.Handout.getContentType()
        value4 = self.transformText(type4, text4, 'handout')
        f4.set(self, value4)
        f5 = self.getField('AlternativeView')
        text5 = self.getRawAlternative()
        type5 = self.Alternative.getContentType()
        value5 = self.transformText(type5, text5, 'alternative')
        f5.set(self, value5)
        f6 = self.getField('SlideReferenceView')
        text6 = self.getRawSlideReference()
        type6 = self.SlideReference.getContentType()
        value6 = self.transformText(type6, text6, 'reference')
        f6.set(self, value6)
        return 'success'

    def setExplanation(self, value, **kwargs):
        '''set explanation with raw data and explanation view with transformed data.'''
        f = self.getField('Explanation')
        f.set(self, value, raw=True, **kwargs)
        self.setExplanationView(value)

    def setExplanationView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('ExplanationView')
            text = self.getRawExplanation()
            type = self.Explanation.getContentType()
            value = self.transformText(type, text, 'explanation')
            f.set(self, value)
            self.setSlideTextChanged(1)

    def setDetails(self, value, **kwargs):
        '''set details text'''
        f = self.getField('Details')
        f.set(self, value, raw=True, **kwargs)
        self.setDetailsView(value)

    def setDetailsView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('DetailsView')
            text = self.getRawDetails()
            type = self.Details.getContentType()
            value = self.transformText(type, text, 'details')
            f.set(self, value)

    def setExamples(self, value, **kwargs):
        '''set examples text'''
        f = self.getField('Examples')
        f.set(self, value, raw=True, **kwargs)
        self.setExamplesView(value)

    def setExamplesView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('ExamplesView')
            text = self.getRawExamples()
            type = self.Examples.getContentType()
            value = self.transformText(type, text, 'examples')
            f.set(self, value)

    def setAlternative(self, value, **kwargs):
        '''set alternative text'''
        f = self.getField('Alternative')
        f.set(self, value, raw=True, **kwargs)
        self.setAlternativeView(value)

    def setAlternativeView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('AlternativeView')
            text = self.getRawAlternative()
            type = self.Alternative.getContentType()
            value = self.transformText(type, text, 'alternative')
            f.set(self, value)

    def setHandout(self, value, **kwargs):
        '''set handout text'''
        f = self.getField('Handout')
        f.set(self, value, raw=True, **kwargs)
        self.setHandoutView(value)

    def setHandoutView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('HandoutView')
            text = self.getRawHandout()
            type = self.Handout.getContentType()
            value = self.transformText(type, text, 'handout')
            f.set(self, value)

    def setSlideReference(self, value, **kwargs):
        '''set slide reference'''
        f = self.getField('SlideReference')
        f.set(self, value, raw=True, **kwargs)
        self.setSlideReferenceView(value)

    def setSlideReferenceView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('SlideReferenceView')
            text = self.getRawSlideReference()
            type = self.SlideReference.getContentType()
            value = self.transformText(type, text, 'reference')
            f.set(self, value)

    def setSlideImageW(self):
        # only works for image for the moment
        value = self.getSlideImage()
        #calc heigth and width
        if (value):
            f = self.getField('SlideImageWWW')
            f.set(self, value)
        if (EXPLANATION_FIG):
            value = self.getExplanationImage()
            #calc heigth and width
            if (value):
                f = self.getField('ExplanationImageWWW')
                f.set(self, value)
        self.changed = False

    security.declarePublic('imageHasChanged')

    def imageHasChanged(self):
        return self.changed

    security.declarePublic('getSlideImageFactor')

    def getSlideImageFactor(self, maxw, maxh, fieldname):
        #ct, width, heigth = getImageInfo(self.getSlideImage())
        #value = self.getSlideImage()
        #calc heigth and width
        #f = self.getField('SlideImageWWW')
        #f.set(self, value)
        f = self.getField(fieldname)
        #w = f.getAttr(self, 'width')
        width, heigth = f.getSize(self)
        #width = 350
        #heigth = 120
        if width > maxw or \
                       heigth > maxh:
            factor = min(float(300) / float(width), float(300) / float(heigth))
        else:
            factor = 1

        return factor
        #return w
    def getImage(self):
        return 1, 1

    security.declarePrivate('initializeObject')

    def initializeObject(self):
        self.tryWorkflowAction("publish", ignoreErrors=True)
        parent = aq_parent(self)
        parent.orderObjects("id")
        parent.plone_utils.reindexOnReorder(parent)
        #self.reindexObject()
        self.changed = True
        self.renderImages()

    def editedObject(self, objtype=None):
        parent = aq_parent(self)
        parent.editedObject()
        self.renderImages()

    def renderImages(self):
        self.renderMainImage()
        if (EXPLANATION_FIG):
            self.renderExplanationImage()
        self.setSlideImageW()

    def setChanged(self, ch):
        #self.changed = ch
        lec = aq_parent(self)
        lec.setChanged(True)

    def setChanged(self, ch):
        #self.changed = ch
        lec = aq_parent(self)
        lec.setChanged(True)
        tut = aq_parent(lec)
        tut.setChanged(True)

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        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 haveChanged(self):
        self.changed = True
        self.renderImages()

    security.declareProtected(View, 'transformSlideText')

    def transformSlideText(self, val):
        type = self.SlideText.getContentType()
        data = self.transformText(type, val, 'slidetext')
        self.setSlideTextView(data)

    security.declareProtected(View, 'updateTransformableText')

    def updateTransformableText(self):
        #use loop to go through everything...
        type = self.SlideText.getContentType()
        transformtext = self.getRawSlideText()
        data = self.transformText(type, transformtext, 'slidetext')
        #self.setSlideTextView(data)
        f = self.getField('SlideTextView')
        f.set(self, data)
        #self.SlideTextView.setContentType(self, 'text/html')
        type = self.Explanation.getContentType()
        transformtext = self.getRawExplanation()
        data = self.transformText(type, transformtext, 'explanation')
        self.setExplanationView(data)
        #self.ExplanationView.setContentType(self, 'text/html')
        type = self.Details.getContentType()
        transformtext = self.getRawDetails()
        data = self.transformText(type, transformtext, 'details')
        self.setDetailsView(data)
        #self.DetailsView.setContentType(self, 'text/html')
        type = self.Examples.getContentType()
        transformtext = self.getRawExamples()
        data = self.transformText(type, transformtext, 'examples')
        self.setExamplesView(data)
        #self.ExamplesView.setContentType(self, 'text/html')
        type = self.Alternative.getContentType()
        transformtext = self.getRawAlternative()
        data = self.transformText(type, transformtext, 'alternative')
        self.setAlternativeView(data)
        #self.AlternativeView.setContentType(self, 'text/html')
        type = self.Handout.getContentType()
        transformtext = self.getRawHandout()
        data = self.transformText(type, transformtext, 'handout')
        self.setHandoutView(data)
        #self.HandoutView.setContentType(self, 'text/html')
        type = self.SlideReference.getContentType()
        transformtext = self.getRawSlideReference()
        data = self.transformText(type, transformtext, 'reference')
        self.setSlideReferenceView(data)
        #self.SlideReferenceView.setContentType(self, 'text/html')

    security.declareProtected(View, 'transformText')

    def transformText(self, type, text, origin):

        trans = getToolByName(self, 'portal_transforms')

        data = trans.convertTo('text/html', text, mimetype=type, usedby=self)
        objects = data.getSubObjects()
        #mobj = data.getMetadata()['fileName']
        #for d in mobj:
        #    mobj = 'bla'
        counter = 0
        for x in objects:
            if hasattr(self, x):
                self.manage_delObjects([x])
            if hasattr(self, origin + x):
                self.manage_delObjects([origin + x])
            self.manage_addImage(origin + x, objects[x])

            container = self[origin + x]
            counter = counter + 1
            #tempname = container.getTitle()
            #container.setTitle('bla')
            container.manage_permission(
                permissions.View,
                roles=["Anonymous", "Authenticated", "Manager"],
                acquire=False)
            container.manage_permission(
                'Delete objects',
                roles=["Anonymous", "Authenticated", "Manager"],
                acquire=False)

        transformedtext = data.getData()
        if (type == 'text/latex'):
            path = '/'.join(self.getPhysicalPath())
            transformedtext = transformedtext.replace('SRC="',
                                                      'SRC="' + path + '/')
        for x in objects:
            transformedtext = transformedtext.replace(x, origin + x)
        self.reindexObject()

        return transformedtext

    def isImageFormat(self):
        image_type = self.getSlideimageFormat()
        if (image_type == 'image'):
            return True
        else:
            return False

    def renderMainImage(self):
        # should add checkes for if it empy, try, except code as well...
        image_type = self.getSlideImageFormat()
        rendered_image = 'DELETE_IMAGE'
        text = self.getSlideImageText()
        im = self.getSlideImage()
        if (im and (image_type != 'image')):
            self.setSlideImage(rendered_image)
        if ((len(text) > 0)
                and ((image_type == 'image') or (image_type == 'none'))):
            self.setSlideImageText('')

        if (image_type == 'fig'):
            rendered_image = self.renderImage(text, 'fig2dev -L png', '')

        elif (image_type == 'gnuplot'):
            HEADER = 'set terminal png color\n'
            rendered_image = self.renderImage(text, 'gnuplot', HEADER)
        elif (image_type == 'r'):

            #HEADER = 'png(file="/dev/stdout")\r\n'
            HEADER = 'bitmap(file="/dev/stdout")\r\n'
            #rendered_image = self.renderImage(text, 'R --slave', HEADER)
            rendered_image = self.renderRQuestion(text, HEADER)

        else:
            ''' do nothing for the moement '''
        if (image_type != 'image'):
            if (rendered_image != 'FAILURE'):
                try:
                    self.setSlideImage(rendered_image)
                    return True
                except:
                    return False
            else:
                return False
        else:
            ''' Return true if image type is png, jpeg, gif - no rendering needed.'''
            return True

    def renderExplanationImage(self):
        # should add checkes for if it empy, try, except code as well...
        image_type = self.getExplanationImageFormat()
        text = self.getExplanationImageText()
        rendered_image = 'DELETE_IMAGE'
        im = self.getExplanationImage()
        if (im and (image_type != 'image')):
            self.setExplanationImage(rendered_image)
        if ((len(text) > 0)
                and ((image_type == 'image') or (image_type == 'none'))):
            self.setExplanationImageText('')

        if (image_type == 'fig'):
            rendered_image = self.renderImage(text, 'fig2dev -L png', '')
        elif (image_type == 'gnuplot'):
            HEADER = 'set terminal png color\n'
            rendered_image = self.renderImage(text, 'gnuplot', HEADER)
        elif (image_type == 'r'):
            #HEADER = 'postscript(file="/dev/stdout")\r\n'
            #HEADER = 'png(file="/dev/stdout")\r\n'
            HEADER = 'bitmap(file="/dev/stdout")\r\n'
            #rendered_image = self.renderImage(text, 'R --slave', HEADER)
            rendered_image = self.renderRQuestion(text, HEADER)

            #if (rendered_image != 'DELETE_IMAGE'):
            #    rendered_image = twutils.ps2png(rendered_image)
        else:
            ''' do nothing for the moement '''
        if (image_type != 'image'):
            if (rendered_image != 'FAILURE'):
                self.setExplanationImage(rendered_image)
                return True
            else:
                return False
        else:
            return True

    security.declarePublic("renderRQuestion")

    def renderRQuestion(self, questiontext, HEADER):
        "jaso"
        tmpout = tempfile.mkdtemp()
        png_fd, png_absname = tempfile.mkstemp(dir=tmpout, suffix='.png')
        render = False

        setdatafiles = False
        if ('read' or 'source' in questiontext):
            tmpout1 = tempfile.mkdtemp()
            setdatafiles = True
            parent = aq_parent(self)
            extradata = parent.getAllExtraFiles()
            for ext in extradata:
                extra = ext.getObject()
                filename = extra.getTitle()
                extraid = extra.getId()
                f = open(tmpout1 + '/' + extraid, 'w')
                text = str(extra.getField('file').get(extra).data)
                for ex in extradata:
                    extobj = ex.getObject()
                    extid = extobj.getId()
                    if (extid in text):
                        text = text.replace(extid, '/' + tmpout1 + '/' + extid)
                f.write(text)
                f.close()
                if (extraid in questiontext):
                    text = str(extra.getField('file').get(extra).data)
                    questiontext = questiontext.replace(
                        extraid, '/' + tmpout1 + '/' + extraid)

        try:
            stdin, stdout = os.popen2('R --slave')
            try:
                stdin.write('bitmap(file="' + png_absname + '")\r\n')
            except:
                return 'FAILURE'
            try:
                stdin.write(questiontext)
                stdin.write('\r\n')
                stdin.write('dev.off()')
                try:
                    stdin.flush()
                    try:
                        stdin.close()
                        try:
                            s = stdout.read(
                            )  #s should be of the form %s|%s|%s|%s
                            try:
                                stdout.flush()
                                render = True
                                try:
                                    stdout.close()
                                except:
                                    ''' bla bla'''
                            except:
                                ''' bla bla'''

                        except:
                            ''' bla bla'''

                    except:
                        '''bla bla'''
                except:
                    '''bla bla'''
            except:
                '''bla bla'''
        except:
            render = False

        # if exists png file then read data and set
        # else set png file as empty DELETE_IMAGE
        try:
            mainimagefile = open(png_absname, 'r')
        except:
            '''Could not open image file??'''
            return 'FAILURE'
        try:
            mainimage = mainimagefile.read()
        except:
            '''could not read from image file???'''
            return 'FAILURE'
        mainimagefile.close()
        #try:
        #    if (mainimage):
        #        self.setQuestionImage(mainimage)
        #    else:
        #        self.setQuestionImage('DELETE_IMAGE')

        #except:
        #    '''????'''

        #if (render is True):
        #    s = s.split("|")
        #else:
        #    s = questiontext.split("|")

        #remove temporary directories created by the use of tempfile
        # and close file
        os.close(png_fd)
        try:
            shutil.rmtree(tmpout, True)
            if (setdatafiles):
                shutil.rmtree(tmpout1, True)
        except OSError, (errno, strerror):
            print "tutorial pdf:(shutil.rmtree %s) OSError[%s]: %s" % \
                     (tmpout, errno, strerror)

        if (mainimage):
            return mainimage
        else:
            return 'DELETE_IMAGE'