Exemplo n.º 1
0
    def testValidateRequired(self):
        field = Bool(title=u'Bool field', description=u'',
                     readonly=False, required=True)
        field.validate(True)
        field.validate(False)

        self.assertRaises(RequiredMissing, field.validate, None)
Exemplo n.º 2
0
 def testValidate(self):
     field = Bool(title=u'Bool field', description=u'',
                  readonly=False, required=False)
     field.validate(None)
     field.validate(True)
     field.validate(False)
Exemplo n.º 3
0
class IMailer(IAction):

    """A form action adapter that will e-mail form input."""
#     default_method='getDefaultRecipientName',
    write_permission(recipient_name=EDIT_ADDRESSING_PERMISSION)
    read_permission(recipient_name=MODIFY_PORTAL_CONTENT)
    recipient_name = TextLine(
        title=_(u'label_formmailer_recipient_fullname',
                default=u"Recipient's full name"),
        description=_(u'help_formmailer_recipient_fullname',
                      default=u'The full name of the recipient of the mailed form.'),
        default=u'',
        missing_value=u'',
        required=False,
    )
#     default_method='getDefaultRecipient',
#     validators=('isEmail',),
#     TODO defaultFactory
#     TODO IContextAwareDefaultFactory
    write_permission(recipient_email=EDIT_ADDRESSING_PERMISSION)
    read_permission(recipient_email=MODIFY_PORTAL_CONTENT)
    recipient_email = TextLine(
        title=_(u'label_formmailer_recipient_email',
                default=u"Recipient's e-mail address"),
        description=_(u'help_formmailer_recipient_email',
                      default=u'The recipients e-mail address.'),
        default=u'',
        missing_value=u'',
        required=False,
    )
    fieldset(u'addressing', label=_('Addressing'), fields=[
             'to_field', 'cc_recipients', 'bcc_recipients', 'replyto_field'])
    write_permission(to_field=EDIT_ADVANCED_PERMISSION)
    read_permission(to_field=MODIFY_PORTAL_CONTENT)
    to_field = Choice(
        title=_(u'label_formmailer_to_extract',
                default=u'Extract Recipient From'),
        description=_(u'help_formmailer_to_extract', default=u''
                      u'Choose a form field from which you wish to extract '
                      u'input for the To header. If you choose anything other '
                      u'than "None", this will override the "Recipient\'s e-mail address" '
                      u'setting above. Be very cautious about allowing unguarded user '
                      u'input for this purpose.'),
        required=False,
        vocabulary=fieldsFactory,
    )
#     default_method='getDefaultCC',
    write_permission(cc_recipients=EDIT_ADDRESSING_PERMISSION)
    read_permission(cc_recipients=MODIFY_PORTAL_CONTENT)
    cc_recipients = Text(
        title=_(u'label_formmailer_cc_recipients',
                default=u'CC Recipients'),
        description=_(u'help_formmailer_cc_recipients',
                      default=u'E-mail addresses which receive a carbon copy.'),
        default=u'',
        missing_value=u'',
        required=False,
    )
#     default_method='getDefaultBCC',
    write_permission(bcc_recipients=EDIT_ADDRESSING_PERMISSION)
    read_permission(bcc_recipients=MODIFY_PORTAL_CONTENT)
    bcc_recipients = Text(
        title=_(u'label_formmailer_bcc_recipients',
                default=u'BCC Recipients'),
        description=_(u'help_formmailer_bcc_recipients',
                      default=u'E-mail addresses which receive a blind carbon copy.'),
        default=u'',
        missing_value=u'',
        required=False,
    )
    write_permission(replyto_field=EDIT_ADVANCED_PERMISSION)
    read_permission(replyto_field=MODIFY_PORTAL_CONTENT)
    replyto_field = Choice(
        title=_(u'label_formmailer_replyto_extract',
                default=u'Extract Reply-To From'),
        description=_(u'help_formmailer_replyto_extract', default=u''
                      u'Choose a form field from which you wish to extract '
                      u'input for the Reply-To header. NOTE: You should '
                      u'activate e-mail address verification for the designated '
                      u'field.'),
        required=False,
        vocabulary=fieldsFactory,
    )
    fieldset(u'message', label=PMF('Message'), fields=[
             'msg_subject', 'subject_field', 'body_pre', 'body_post',
             'body_footer', 'showAll', 'showFields', 'includeEmpties'])
    read_permission(msg_subject=MODIFY_PORTAL_CONTENT)
    msg_subject = TextLine(
        title=_(u'label_formmailer_subject', default=u'Subject'),
        description=_(u'help_formmailer_subject', default=u''
                      u'Subject line of message. This is used if you '
                      u'do not specify a subject field or if the field '
                      u'is empty.'),
        default=u'Form Submission',
        missing_value=u'',
        required=False,
    )
    write_permission(subject_field=EDIT_ADVANCED_PERMISSION)
    read_permission(subject_field=MODIFY_PORTAL_CONTENT)
    subject_field = Choice(
        title=_(u'label_formmailer_subject_extract',
                default=u'Extract Subject From'),
        description=_(u'help_formmailer_subject_extract', default=u''
                      u'Choose a form field from which you wish to extract '
                      u'input for the mail subject line.'),
        required=False,
        vocabulary=fieldsFactory,
    )
#     accessor='getBody_pre',
    read_permission(body_pre=MODIFY_PORTAL_CONTENT)
    body_pre = Text(
        title=_(u'label_formmailer_body_pre', default=u'Body (prepended)'),
        description=_(u'help_formmailer_body_pre',
                      default=u'Text prepended to fields listed in mail-body'),
        default=u'',
        missing_value=u'',
        required=False,
    )
    read_permission(body_post=MODIFY_PORTAL_CONTENT)
    body_post = Text(
        title=_(u'label_formmailer_body_post', default=u'Body (appended)'),
        description=_(u'help_formmailer_body_post',
                      default=u'Text appended to fields listed in mail-body'),
        default=u'',
        missing_value=u'',
        required=False,
    )
    read_permission(body_footer=MODIFY_PORTAL_CONTENT)
    body_footer = Text(
        title=_(u'label_formmailer_body_footer',
                default=u'Body (signature)'),
        description=_(u'help_formmailer_body_footer',
                      default=u'Text used as the footer at '
                      u'bottom, delimited from the body by a dashed line.'),
        default=u'',
        missing_value=u'',
        required=False,
    )
    read_permission(showAll=MODIFY_PORTAL_CONTENT)
    showAll = Bool(
        title=_(u'label_mailallfields_text', default=u'Include All Fields'),
        description=_(u'help_mailallfields_text', default=u''
                      u'Check this to include input for all fields '
                      u'(except label and file fields). If you check '
                      u'this, the choices in the pick box below '
                      u'will be ignored.'),
        default=True,
        required=False,
    )
    read_permission(showFields=MODIFY_PORTAL_CONTENT)
    showFields = List(
        title=_(u'label_mailfields_text', default=u'Show Responses'),
        description=_(u'help_mailfields_text',
                      default=u'Pick the fields whose inputs you\'d like to include in the e-mail.'),
        unique=True,
        required=False,
        value_type=Choice(vocabulary=fieldsFactory),
    )
    read_permission(includeEmpties=MODIFY_PORTAL_CONTENT)
    includeEmpties = Bool(
        title=_(u'label_mailEmpties_text', default=u'Include Empties'),
        description=_(u'help_mailEmpties_text', default=u''
                      u'Check this to include titles '
                      u'for fields that received no input. Uncheck '
                      u'to leave fields with no input out of the e-mail.'),
        default=True,
        required=False,
    )
    fieldset(u'template', label=PMF(
        'Template'), fields=['body_pt', 'body_type'])
#     ZPTField('body_pt',
#     default_method='getMailBodyDefault',
#     validators=('zptvalidator',),
    write_permission(body_pt=EDIT_TALES_PERMISSION)
    read_permission(body_pt=MODIFY_PORTAL_CONTENT)
    body_pt = Text(
        title=_(u'label_formmailer_body_pt', default=u'Mail-Body Template'),
        description=_(u'help_formmailer_body_pt', default=u''
                      u'This is a Zope Page Template '
                      u'used for rendering of the mail-body. You don\'t need to modify '
                      u'it, but if you know TAL (Zope\'s Template Attribute Language) '
                      u'you have the full power to customize your outgoing mails.'),
        default=MAIL_BODY_DEFAULT,
        missing_value=u'',
    )
#     default_method='getMailBodyTypeDefault',
    write_permission(body_type=EDIT_ADVANCED_PERMISSION)
    read_permission(body_type=MODIFY_PORTAL_CONTENT)
    body_type = Choice(
        title=_(u'label_formmailer_body_type', default=u'Mail Format'),
        description=_(u'help_formmailer_body_type', default=u''
                      u'Set the mime-type of the mail-body. '
                      u'Change this setting only if you know exactly what you are doing. '
                      u'Leave it blank for default behaviour.'),
        default=u'html',
        vocabulary=MIME_LIST,
    )
    fieldset(u'headers', label=_('Headers'),
             fields=['xinfo_headers', 'additional_headers'])
    widget(xinfo_headers=CheckBoxFieldWidget)
#     default_method='getDefaultXInfo',
    write_permission(xinfo_headers=EDIT_ADVANCED_PERMISSION)
    read_permission(xinfo_headers=MODIFY_PORTAL_CONTENT)
    xinfo_headers = List(
        title=_(u'label_xinfo_headers_text', default=u'HTTP Headers'),
        description=_(u'help_xinfo_headers_text', default=u''
                      u'Pick any items from the HTTP headers that '
                      u'you\'d like to insert as X- headers in the message.'),
        unique=True,
        required=False,
        default=[u'HTTP_X_FORWARDED_FOR', u'REMOTE_ADDR', u'PATH_INFO'],
        missing_value=[u'HTTP_X_FORWARDED_FOR', u'REMOTE_ADDR', u'PATH_INFO'],
        value_type=Choice(vocabulary=XINFO_HEADERS),
    )
#     default_method='getDefaultAddHdrs',
    write_permission(additional_headers=EDIT_ADVANCED_PERMISSION)
    read_permission(additional_headers=MODIFY_PORTAL_CONTENT)
    additional_headers = List(
        title=_(u'label_formmailer_additional_headers',
                default=u'Additional Headers'),
        description=_(u'help_formmailer_additional_headers',
                      default=u'Additional e-mail-header lines. Only use RFC822-compliant headers.'),
        unique=True,
        required=False,
        value_type=TextLine(
            title=_(u'extra_header',
                    default=u'${name} Header', mapping={u'name': u'HTTP'}),
        ),
    )
#     if gpg is not None:
#         formMailerAdapterSchema = formMailerAdapterSchema + Schema((
#             StringField('gpg_keyid',
#                 schemata='encryption',
#                 accessor='getGPGKeyId',
#                 mutator='setGPGKeyId',
#                 write_permission=USE_ENCRYPTION_PERMISSION,
#                 read_permission=ModifyPortalContent,
#                 widget=StringWidget(
#                     description=_(u'help_gpg_key_id', default=u"""
#                         Give your key-id, e-mail address or
#                         whatever works to match a public key from current keyring.
#                         It will be used to encrypt the message body (not attachments).
#                         Contact the site administrator if you need to
#                         install a new public key.
#                         Note that you will probably wish to change your message
#                         template to plain text if you're using encryption.
#                         TEST THIS FEATURE BEFORE GOING PUBLIC!
#                        """),
#                    label=_(u'label_gpg_key_id', default=u'Key-Id'),
#                    ),
#                ),
#            ))
    fieldset(u'overrides', label=_('Overrides'), fields=[
             'subjectOverride', 'senderOverride', 'recipientOverride', 'ccOverride', 'bccOverride'])
    write_permission(subjectOverride=EDIT_TALES_PERMISSION)
    read_permission(subjectOverride=MODIFY_PORTAL_CONTENT)
    subjectOverride = TextLine(
        title=_(u'label_subject_override_text', default=u'Subject Expression'),
        description=_(u'help_subject_override_text', default=u''
                      u'A TALES expression that will be evaluated to override any value '
                      u'otherwise entered for the e-mail subject header. '
                      u'Leave empty if unneeded. Your expression should evaluate as a string. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                      u'an error on form display.'),
        required=False,
        default=u'',
        missing_value=u'',
        constraint=isTALES,
    )
    write_permission(senderOverride=EDIT_TALES_PERMISSION)
    read_permission(senderOverride=MODIFY_PORTAL_CONTENT)
    senderOverride = TextLine(
        title=_(u'label_sender_override_text', default=u'Sender Expression'),
        description=_(u'help_sender_override_text', default=u''
                      u'A TALES expression that will be evaluated to override the "From" header. '
                      u'Leave empty if unneeded. Your expression should evaluate as a string. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                      u'an error on form display.'),
        required=False,
        default=u'',
        missing_value=u'',
        constraint=isTALES,
    )
    write_permission(recipientOverride=EDIT_TALES_PERMISSION)
    read_permission(recipientOverride=MODIFY_PORTAL_CONTENT)
    recipientOverride = TextLine(
        title=_(u'label_recipient_override_text',
                default=u'Recipient Expression'),
        description=_(u'help_recipient_override_text', default=u''
                      u'A TALES expression that will be evaluated to override any value '
                      u'otherwise entered for the recipient e-mail address. You are strongly '
                      u'cautioned against using unvalidated data from the request for this purpose. '
                      u'Leave empty if unneeded. Your expression should evaluate as a string. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                      u'an error on form display.'),
        required=False,
        default=u'',
        missing_value=u'',
        constraint=isTALES,
    )
    write_permission(ccOverride=EDIT_TALES_PERMISSION)
    read_permission(ccOverride=MODIFY_PORTAL_CONTENT)
    ccOverride = TextLine(
        title=_(u'label_cc_override_text', default=u'CC Expression'),
        description=_(u'help_cc_override_text', default=u''
                      u'A TALES expression that will be evaluated to override any value '
                      u'otherwise entered for the CC list. You are strongly '
                      u'cautioned against using unvalidated data from the request for this purpose. '
                      u'Leave empty if unneeded. Your expression should evaluate as a sequence of strings. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                      u'an error on form display.'),
        required=False,
        default=u'',
        missing_value=u'',
        constraint=isTALES,
    )
    write_permission(bccOverride=EDIT_TALES_PERMISSION)
    read_permission(bccOverride=MODIFY_PORTAL_CONTENT)
    bccOverride = TextLine(
        title=_(u'label_bcc_override_text', default=u'BCC Expression'),
        description=_(u'help_bcc_override_text', default=u''
                      u'A TALES expression that will be evaluated to override any value '
                      u'otherwise entered for the BCC list. You are strongly '
                      u'cautioned against using unvalidated data from the request for this purpose. '
                      u'Leave empty if unneeded. Your expression should evaluate as a sequence of strings. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                      u'an error on form display.'),
        required=False,
        default=u'',
        missing_value=u'',
        constraint=isTALES,
    )
Exemplo n.º 4
0
class IEasyForm(Schema):

    """Forms for Plone"""

#     fieldset(u'models', label=_('Models'),
#                   fields=['fields_model', 'actions_model'])
    omitted('fields_model', 'actions_model')
    fields_model = Text(
        title=_(u'Fields Model'),
        default=FIELDS_DEFAULT,
    )
    actions_model = Text(
        title=_(u'Actions Model'),
        default=ACTIONS_DEFAULT,
    )
    submitLabel = TextLine(
        title=_(u'label_submitlabel_text', default=u'Submit Button Label'),
        description=_(u'help_submitlabel_text', default=u''),
        default=u'Submit',
        required=False,
    )
    useCancelButton = Bool(
        title=_(u'label_showcancel_text', default=u'Show Reset Button'),
        description=_(u'help_showcancel_text', default=u''),
        default=False,
        required=False,
    )
    resetLabel = TextLine(
        title=_(u'label_reset_button', default=u'Reset Button Label'),
        description=_(u'help_reset_button', default=u''),
        default=u'Reset',
        required=False,
    )
    method = Choice(
        title=_(u'label_method', default=u'Form method'),
        description=_(u'help_method', default=u''),
        default=u'post',
        required=False,
        vocabulary=FORM_METHODS,
    )
    form_tabbing = Bool(
        title=_(u'label_form_tabbing',
                default=u'Turn fieldsets to tabs'),
        description=_(u'help_form_tabbing', default=u''),
        default=True,
        required=False,
    )
    default_fieldset_label = TextLine(
        title=_(u'label_default_fieldset_label_text',
                default=u'Custom Default Fieldset Label'),
        description=_(u'help_default_fieldset_label_text',
                      default=u'This field allows you to change default fieldset label.'),
        required=False,
        default=u'',
    )
    unload_protection = Bool(
        title=_(u'label_unload_protection',
                default=u'Unload protection'),
        description=_(u'help_unload_protection', default=u''),
        default=True,
        required=False,
    )
    CSRFProtection = Bool(
        title=_(u'label_csrf', default=u'CSRF Protection'),
        description=_(u'help_csrf', default=u'Check this to employ Cross-Site '
                      u'Request Forgery protection. Note that only HTTP Post '
                      u'actions will be allowed.'),
        default=True,
        required=False,
    )
    write_permission(forceSSL=EDIT_ADVANCED_PERMISSION)
    forceSSL = Bool(
        title=_(u'label_force_ssl', default=u'Force SSL connection'),
        description=_(u'help_force_ssl', default=u''
                      u'Check this to make the form redirect to an SSL-enabled '
                      u'version of itself (https://) if accessed via a non-SSL '
                      u'URL (http://).  In order to function properly, '
                      u'this requires a web server that has been configured to '
                      u'handle the HTTPS protocol on port 443 and forward it to Zope.'),
        default=False,
        required=False,
    )
    formPrologue = RichText(
        title=_(u'label_prologue_text', default=u'Form Prologue'),
        description=_(u'help_prologue_text',
                      default=u'This text will be displayed above the form fields.'),
        required=False,
    )
    formEpilogue = RichText(
        title=_(u'label_epilogue_text', default=u'Form Epilogue'),
        description=_(u'help_epilogue_text',
                      default=u'The text will be displayed after the form fields.'),
        required=False,
    )
    fieldset(u'overrides', label=_('Overrides'),
             fields=['thanksPageOverrideAction', 'thanksPageOverride', 'formActionOverride', 'onDisplayOverride', 'afterValidationOverride', 'headerInjection', 'submitLabelOverride'])
    write_permission(thanksPageOverrideAction=EDIT_TALES_PERMISSION)
    thanksPageOverrideAction = Choice(
        title=_(u'label_thankspageoverrideaction_text',
                default=u'Custom Success Action Type'),
        description=_(u'help_thankspageoverrideaction_text', default=u''
                      u'Use this field in place of a thanks-page designation '
                      u'to determine final action after calling '
                      u'your action adapter (if you have one). You would usually use '
                      u'this for a custom success template or script. '
                      u'Leave empty if unneeded. Otherwise, specify as you would a '
                      u'CMFFormController action type and argument, '
                      u'complete with type of action to execute '
                      u'(e.g., "redirect_to" or "traverse_to") '
                      u'and a TALES expression. For example, '
                      u'"Redirect to" and "string:thanks-page" would redirect to '
                      u'"thanks-page".'),
        default=u'redirect_to',
        required=False,
        vocabulary=customActions,
    )
    write_permission(thanksPageOverride=EDIT_TALES_PERMISSION)
    thanksPageOverride = TextLine(
        title=_(u'label_thankspageoverride_text',
                default=u'Custom Success Action'),
        description=_(u'help_thankspageoverride_text', default=u''
                      u'Use this field in place of a thanks-page designation '
                      u'to determine final action after calling '
                      u'your action adapter (if you have one). You would usually use '
                      u'this for a custom success template or script. '
                      u'Leave empty if unneeded. Otherwise, specify as you would a '
                      u'CMFFormController action type and argument, '
                      u'complete with type of action to execute '
                      u'(e.g., "redirect_to" or "traverse_to") '
                      u'and a TALES expression. For example, '
                      u'"Redirect to" and "string:thanks-page" would redirect to '
                      u'"thanks-page".'),
        default=u'',
        constraint=isTALES,
        required=False,
    )
    write_permission(formActionOverride=EDIT_TALES_PERMISSION)
    formActionOverride = TextLine(
        title=_(u'label_formactionoverride_text',
                default=u'Custom Form Action'),
        description=_(u'help_formactionoverride_text', default=u''
                      u'Use this field to override the form action attribute. '
                      u'Specify a URL to which the form will post. '
                      u'This will bypass form validation, success action '
                      u'adapter and thanks page.'),
        default=u'',
        required=False,
        constraint=isTALES,
    )
    write_permission(onDisplayOverride=EDIT_TALES_PERMISSION)
    onDisplayOverride = TextLine(
        title=_(u'label_OnDisplayOverride_text', default=u'Form Setup Script'),
        description=_(u'help_OnDisplayOverride_text', default=u''
                      u'A TALES expression that will be called when the form is '
                      u'displayed. '
                      u'Leave empty if unneeded. '
                      u'The most common use of this field is to call a python script '
                      u'that sets defaults for multiple fields by pre-populating '
                      u'request.form. '
                      u'Any value returned by the expression is ignored. '
                      u'PLEASE NOTE: errors in the evaluation of this expression '
                      u'will cause an error on form display.'),
        constraint=isTALES,
        required=False,
        default=u'',
    )
    write_permission(afterValidationOverride=EDIT_TALES_PERMISSION)
    afterValidationOverride = TextLine(
        title=_(u'label_AfterValidationOverride_text',
                default=u'After Validation Script'),
        description=_(u'help_AfterValidationOverride_text', default=u''
                      u'A TALES expression that will be called after the form is'
                      u'successfully validated, but before calling an action adapter'
                      u'(if any) or displaying a thanks page.'
                      u'Form input will be in the request.form dictionary.'
                      u'Leave empty if unneeded.'
                      u'The most common use of this field is to call a python script'
                      u'to clean up form input or to script an alternative action.'
                      u'Any value returned by the expression is ignored.'
                      u'PLEASE NOTE: errors in the evaluation of this expression will'
                      u'cause an error on form display.'),
        constraint=isTALES,
        required=False,
        default=u'',
    )
    write_permission(headerInjection=EDIT_TALES_PERMISSION)
    headerInjection = TextLine(
        title=_(u'label_headerInjection_text', default=u'Header Injection'),
        description=_(u'help_headerInjection_text', default=u''
                      u'This override field allows you to insert content into the xhtml '
                      u'head. The typical use is to add custom CSS or JavaScript. '
                      u'Specify a TALES expression returning a string. The string will '
                      u'be inserted with no interpretation. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will '
                      u'cause an error on form display.'),
        constraint=isTALES,
        required=False,
        default=u'',
    )
    write_permission(submitLabelOverride=EDIT_TALES_PERMISSION)
    submitLabelOverride = TextLine(
        title=_(u'label_submitlabeloverride_text',
                default=u'Custom Submit Button Label'),
        description=_(u'help_submitlabeloverride_text', default=u''
                      u'This override field allows you to change submit button label. '
                      u'The typical use is to set label with request parameters. '
                      u'Specify a TALES expression returning a string. '
                      u'PLEASE NOTE: errors in the evaluation of this expression will '
                      u'cause an error on form display.'),
        constraint=isTALES,
        required=False,
        default=u'',
    )
    fieldset(u'thankyou', label=_('Thanks Page'),
             fields=['thankstitle', 'thanksdescription', 'showAll', 'showFields', 'includeEmpties', 'thanksPrologue', 'thanksEpilogue'])
    thankstitle = TextLine(
        title=_(u'label_thankstitle', default=u'Thanks title'),
        default=u'Thank You',
        required=True
    )
    thanksdescription = Text(
        title=_(u'label_thanksdescription', default=u'Thanks summary'),
        description=_(
            u'help_thanksdescription',
            default=u'Used in thanks page.'
        ),
        default=u'Thanks for your input.',
        required=False,
        missing_value=u'',
    )
#     TODO
#     obj.setTitle(_(u'pfg_thankyou_title', u'Thank You'))
#     obj.setDescription(_(u'pfg_thankyou_description', u'Thanks for your input.'))
    showAll = Bool(
        title=_(u'label_showallfields_text', default=u'Show All Fields'),
        description=_(u'help_showallfields_text', default=u''
                      u'Check this to display input for all fields '
                      u'(except label and file fields). If you check '
                      u'this, the choices in the pick box below '
                      u'will be ignored.'),
        default=True,
        required=False,
    )
    showFields = List(
        title=_(u'label_showfields_text', default=u'Show Responses'),
        description=_(u'help_showfields_text',
                      default=u'Pick the fields whose inputs you\'d like to display on the success page.'),
        unique=True,
        required=False,
        value_type=Choice(vocabulary=fieldsFactory),
    )
    includeEmpties = Bool(
        title=_(u'label_includeEmpties_text', default=u'Include Empties'),
        description=_(u'help_includeEmpties_text', default=u''
                      u'Check this to display field titles '
                      u'for fields that received no input. Uncheck '
                      u'to leave fields with no input off the list.'),
        default=True,
        required=False,
    )
    thanksPrologue = RichText(
        title=_(u'label_thanksprologue_text', default=u'Thanks Prologue'),
        description=_(u'help_thanksprologue_text',
                      default=u'This text will be displayed above the selected field inputs.'),
        required=False,
    )
    thanksEpilogue = RichText(
        title=_(u'label_thanksepilogue_text', default=u'Thanks Epilogue'),
        description=_(u'help_thanksepilogue_text',
                      default=u'The text will be displayed after the field inputs.'),
        required=False,
    )
Exemplo n.º 5
0
class ILanguage(Interface):
    """A Language."""
    export_as_webservice_entry()

    id = Attribute("This Language ID.")

    code = exported(TextLine(title=u'The ISO 639 code', required=True))

    englishname = exported(TextLine(title=u'The English name', required=True),
                           exported_as='english_name')

    nativename = TextLine(
        title=u'Native name',
        description=u'The name of this language in the language itself.',
        required=False)

    pluralforms = exported(Int(
        title=u'Number of plural forms',
        description=u'The number of plural forms this language has.',
        required=False),
                           exported_as='plural_forms')

    guessed_pluralforms = Int(
        title=u"Number of plural forms, or a reasonable guess",
        required=False,
        readonly=True)

    pluralexpression = exported(TextLine(
        title=u'Plural form expression',
        description=(u'The expression that relates a number of items'
                     u' to the appropriate plural form.'),
        required=False),
                                exported_as='plural_expression')

    translators = doNotSnapshot(
        Field(title=u'List of Person/Team that translate into this language.',
              required=True))

    translators_count = exported(
        Int(title=u"Total number of translators for this language.",
            readonly=True))

    translation_teams = Field(
        title=u'List of Teams that translate into this language.',
        required=True)

    countries = Set(
        title=u'Spoken in',
        description=u'List of countries this language is spoken in.',
        required=True,
        value_type=Choice(vocabulary="CountryName"))

    def addCountry(country):
        """Add a country to a list of countries this language is spoken in.

        Provided by SQLObject.
        """

    def removeCountry(country):
        """Remove country from list of countries this language is spoken in.

        Provided by SQLObject.
        """

    visible = exported(
        Bool(title=u'Visible',
             description=(u'Whether this language is visible by default.'),
             required=True))

    direction = exported(Choice(
        title=u'Text direction',
        description=u'The direction of text in this language.',
        required=True,
        vocabulary=TextDirection),
                         exported_as='text_direction')

    displayname = TextLine(title=u'The displayname of the language',
                           required=True,
                           readonly=True)

    alt_suggestion_language = Attribute(
        "A language which can reasonably "
        "be expected to have good suggestions for translations in this "
        "language.")

    dashedcode = TextLine(
        title=(u'The language code in a form suitable for use in HTML and'
               u' XML files.'),
        required=True,
        readonly=True)

    abbreviated_text_dir = TextLine(
        title=(u'The abbreviated form of the text direction, suitable'
               u' for use in HTML files.'),
        required=True,
        readonly=True)

    @invariant
    def validatePluralData(form_language):
        pair = (form_language.pluralforms, form_language.pluralexpression)
        if None in pair and pair != (None, None):
            raise Invalid(
                'The number of plural forms and the plural form expression '
                'must be set together, or not at all.')
Exemplo n.º 6
0
class IIkDeleteConfirm(Interface):
    """ Confirm the delete """
    confirmed = Bool(
        title = _(u"Confirm"),
        description = _(u"please confirm"),
        default = False)
Exemplo n.º 7
0
class IPOTemplate(IRosettaStats):
    """A translation template."""

    export_as_webservice_entry(singular_name='translation_template',
                               plural_name='translation_templates')

    id = exported(
        Int(title=u"The translation template id.",
            required=True,
            readonly=True))

    name = exported(
        TextLine(title=_("Template name"),
                 description=_(
                     "The name of this PO template, for example "
                     "'evolution-2.2'. Each translation template has a "
                     "unique name in its package. It's important to get this "
                     "correct, because Launchpad will recommend alternative "
                     "translations based on the name."),
                 constraint=valid_name,
                 required=True))

    translation_domain = exported(
        TextLine(
            title=_("Translation domain"),
            description=_(
                "The translation domain for a translation template. "
                "Used with PO file format when generating MO files for inclusion "
                "in language pack or MO tarball exports."),
            required=True))

    description = exported(
        Text(
            title=_("Description"),
            description=_(
                "Please provide a brief description of the content "
                "of this translation template, for example, telling translators "
                "if this template contains strings for end-users or other "
                "developers."),
            required=False))

    header = Text(
        title=_('Header'),
        description=_("The standard template header in its native format."),
        required=True)

    iscurrent = exported(Bool(
        title=_("Template is active"),
        description=_(
            "If unchecked, people can no longer change the template's "
            "translations."),
        required=True,
        default=True),
                         exported_as='active')

    owner = exported(
        PersonChoice(
            title=_("Owner"),
            required=True,
            description=_(
                "The owner of the template in Launchpad can edit the template "
                "and change it's status, and can also upload new versions "
                "of the template when a new release is made or when the "
                "translation strings have been changed during development."),
            vocabulary="ValidOwner"))

    productseries = Choice(title=_("Series"),
                           required=False,
                           vocabulary="ProductSeries")

    distroseries = Choice(title=_("Series"),
                          required=False,
                          vocabulary="DistroSeries")

    sourcepackagename = Choice(
        title=_("Source Package Name"),
        description=_("The source package that uses this template."),
        required=False,
        vocabulary="SourcePackageName")

    sourcepackagenameID = Int(
        title=_("Source Package Name ID"),
        description=_("The ID of the source package that uses this template."),
        required=False,
        readonly=True)

    sourcepackage = Reference(
        ISourcePackage,
        title=u"Source package this template is for, if any.",
        required=False,
        readonly=True)

    from_sourcepackagename = Choice(
        title=_("From Source Package Name"),
        description=_(
            "The source package this template comes from (set it only if it's"
            " different from the previous 'Source Package Name'."),
        required=False,
        vocabulary="SourcePackageName")

    sourcepackageversion = TextLine(title=_("Source Package Version"),
                                    required=False)

    binarypackagename = Choice(
        title=_("Binary Package"),
        description=_("The package in which this template's translations are "
                      "installed."),
        required=False,
        vocabulary="BinaryPackageName")

    languagepack = exported(Bool(
        title=_("Include translations for this template in language packs?"),
        description=_(
            "Check this box if this template is part of a language pack so "
            "its translations should be exported that way."),
        required=True,
        default=False),
                            exported_as='exported_in_languagepacks')

    path = exported(
        TextLine(title=_(
            "Path of the template in the source tree, including filename."),
                 required=True))

    source_file = Object(title=_('Source file for this translation template'),
                         readonly=True,
                         schema=ILibraryFileAlias)

    source_file_format = exported(Choice(
        title=_("File format for the source file"),
        required=False,
        vocabulary=TranslationFileFormat),
                                  exported_as='format')

    priority = exported(
        Int(title=_('Priority'),
            required=True,
            default=0,
            description=_(
                'A number that describes how important this template is. Often '
                'there are multiple templates, and you can use this as a way '
                'of indicating which are more important and should be '
                'translated first. Pick any number - higher priority '
                'templates will generally be listed first.')))

    datecreated = Datetime(
        title=_('When this translation template was created.'),
        required=True,
        readonly=True)

    translationgroups = Attribute(
        _('''
            The `ITranslationGroup` objects that handle translations for this
            template.
            There can be several because they can be inherited from project to
            product, for example.
            '''))

    translationpermission = Choice(title=_('Translation permission'),
                                   required=True,
                                   readonly=True,
                                   description=_('''
            The permission system which is used for this translation template.
            This is inherited from the product, project and/or distro in which
            the translation template is found.
            '''),
                                   vocabulary='TranslationPermission')

    pofiles = exported(
        CollectionField(
            title=_("All translation files that exist for this template."),
            # Really IPOFile, see _schema_circular_imports.py.
            value_type=Reference(schema=Interface)),
        exported_as='translation_files')

    relatives_by_source = Attribute(
        _('''All `IPOTemplate` objects that have the same source.
            For example those that came from the same productseries or the
            same source package.
            '''))

    displayname = TextLine(title=_('The translation template brief name.'),
                           required=True,
                           readonly=True)

    title = TextLine(title=_('The translation template title.'),
                     required=True,
                     readonly=True)

    product = Object(
        title=_('The `IProduct` to which this translation template belongs.'),
        required=False,
        readonly=True,
        # Really IProduct, see _schema_circular_imports.py.
        schema=Interface)

    distribution = Object(title=_(
        'The `IDistribution` to which this translation template '
        'belongs.'),
                          readonly=True,
                          schema=IDistribution)

    messagecount = exported(Int(
        title=_('The number of translation messages for this template.'),
        required=True,
        readonly=True),
                            exported_as='message_count')

    language_count = exported(
        Int(title=_('The number of languages for which we have translations.'),
            required=True,
            readonly=True))

    translationtarget = Attribute(
        _('''
            The direct object in which this template is attached.
            This will either be an `ISourcePackage` or an `IProductSeries`.
            '''))

    date_last_updated = exported(
        Datetime(title=_('Date for last update'), required=True))

    uses_english_msgids = Bool(title=_("Uses English strings as msgids"),
                               readonly=True,
                               description=_("""
            Some formats, such as Mozilla's XPI, use symbolic msgids where
            gettext uses the original English strings to identify messages.
            """))

    translation_side = Int(title=_("Translation side"),
                           required=True,
                           readonly=True)

    def __iter__():
        """Return an iterator over current `IPOTMsgSet` in this template."""

    def clearPOFileCache():
        """Clear `POFile`-related cached data.

        As you work with a `POTemplate`, some data about its `POFile`s
        gets cached.  But if you're iterating over the template's
        translations one `POFile` at a time, you can drop any cached
        data about a `POFile` as soon as you're done with it.  Use this
        method to do that.
        """

    def setActive(active):
        """Toggle the iscurrent flag.

        Takes care of updating the suggestive potempalte cache when the
        template is disabled.
        """

    def getHeader():
        """Return an `ITranslationHeaderData` representing its header."""

    def getPOTMsgSetByMsgIDText(singular_text,
                                plural_text=None,
                                only_current=False,
                                context=None):
        """Return `IPOTMsgSet` indexed by `singular_text` from this template.

        If the key is a string or a unicode object, returns the
        `IPOTMsgSet` in this template that has a primary message ID
        with the given text.

        If `only_current` is True, then get only current message sets.

        If `context` is not None, look for a message set with that context
        value.

        If `plural_text` is not None, also filter by that plural text.

        If no `IPOTMsgSet` is found, return None.
        """

    def getPOTMsgSetBySequence(sequence):
        """Return the `IPOTMsgSet` with the given sequence or None.

        :arg sequence: The sequence number when the `IPOTMsgSet` appears.

        The sequence number must be > 0.
        """

    def getPOTMsgSets(current=True, prefetch=True):
        """Return an iterator over `IPOTMsgSet` objects in this template.

        :param current: Whether to limit the search to current
            POTMsgSets.
        :param prefetch: Whether to prefetch the `POMsgID`s attached to
            the POTMsgSets.  This is for optimization only.
        :return: All current POTMsgSets for the template if `current` is
            True, or all POTMsgSets for the template otherwise.
        """

    def getTranslationCredits():
        """Return an iterator over translation credits.

        Return all `IPOTMsgSet` objects in this template that are translation
        credits.
        """

    def getPOTMsgSetsCount(current=True):
        """Return the number of POTMsgSet objects related to this object.

        The current argument is used to select only current POTMsgSets or all
        of them.
        """

    def __getitem__(key):
        """Same as getPOTMsgSetByMsgIDText(), with only_current=True
        """

    def sharingKey():
        """A key for determining the sharing precedence of a template.

        Active templates have precedence over inactive ones.
        Development foci have precendence over non-development foci.
        Product development foci have precedence over Package development
        foci.
        """

    def getPOTMsgSetByID(id):
        """Return the POTMsgSet object related to this POTemplate with the id.

        If there is no POTMsgSet with that id and for that POTemplate, return
        None.
        """

    def languages():
        """This Return the set of languages for which we have POFiles for
        this POTemplate.
        """

    def getPOFileByPath(path):
        """Get the PO file of the given path.

        Return None if there is no such `IPOFile`.
        """

    def getPOFileByLang(language_code):
        """Get the PO file of the given language.

        Return None if there is no such POFile.
        """

    def getOtherSidePOTemplate():
        """Get the POTemplate with the same name on the other side of a
        packaging link.
        """

    def hasPluralMessage():
        """Test whether this template has any message sets which are plural
        message sets."""

    def export():
        """Return a serialized version as a string using its native format."""

    def exportWithTranslations():
        """Return an ExportedTranslationFile using its native format.

        It include all translations available.
        """

    def expireAllMessages():
        """Mark all of our message sets as not current (sequence=0)"""

    def newPOFile(language_code, create_sharing=True):
        """Return a new `IPOFile` for the given language.

        Raise LanguageNotFound if the language does not exist in the
        database.

        We should not have already an `IPOFile` for the given language_code.

        :param language_code: The code of the language for which to create
            the IPOFile.
        :param requester: The requester person. If given and will have edit
            permissions on the IPOFile, it becomes the owner. Otherwise
            rosetta_experts own the file.
        :param create_sharing: Whether the IPOFile should be created in all
            sharing templates, too. Should only be set to False to avoid
            loops when creating a new IPOTemplate.
        """

    def getDummyPOFile(language, requester=None, check_for_existing=True):
        """Return a DummyPOFile if there isn't already a persistent `IPOFile`

        Raise `LanguageNotFound` if the language does not exist in the
        database.

        This method is designed to be used by read only actions. This way you
        only create a POFile when you actually need to store data.

        We should not have already a POFile for the given language:
        if check_for_existing is set to False, no check will be done for this.
        """

    def createPOTMsgSetFromMsgIDs(msgid_singular,
                                  msgid_plural=None,
                                  context=None,
                                  sequence=0):
        """Creates a new template message in the database.

        :param msgid_singular: A reference to a singular msgid.
        :param msgid_plural: A reference to a plural msgid.  Can be None
            if the message is not a plural message.
        :param context: A context for the template message differentiating
            it from other template messages with exactly the same `msgid`.
        :param sequence: The sequence number of this POTMsgSet within this
            POTemplate. If 0, it is considered obsolete.
        :return: The newly created message set.
        """

    def createMessageSetFromText(singular_text,
                                 plural_text,
                                 context=None,
                                 sequence=0):
        """Creates a new template message in the database using strings.

        Similar to createMessageSetFromMessageID, but takes text objects
        (unicode or string) along with textual context, rather than a
        message IDs.

        :param singular_text: The string for the singular msgid.
        :param msgid_plural: The string for the plural msgid.  Must be None
            if the message is not a plural message.
        :param context: A context for the template message differentiating
            it from other template messages with exactly the same `msgid`.
        :param sequence: The sequence number of this POTMsgSet within this
            POTemplate. If 0, it is considered obsolete.
        :return: The newly created message set.
        """

    def getOrCreateSharedPOTMsgSet(singular_text,
                                   plural_text,
                                   context=None,
                                   initial_file_references=None,
                                   initial_source_comment=None):
        """Finds an existing shared POTMsgSet to use or creates a new one.

        :param singular_text: string containing singular form.
        :param plural_text: string containing plural form.
        :param context: context to differentiate between two messages with
        same singular_text and plural_text.
        :param initial_file_references: Initializer for file_references if
            a new POTMsgSet needs to be created.  Will not be set on an
            existing POTMsgSet.
        :param initial_source_comment: Initializer for source_comment if
            a new POTMsgSet needs to be created.  Will not be set on an
            existing POTMsgSet.
        :return: existing or new shared POTMsgSet with a sequence of 0
        in this POTemplate.
        """

    def importFromQueue(entry_to_import, logger=None, txn=None):
        """Import given queue entry.

        :param entry_to_import: `TranslationImportQueueEntry` specifying an
            approved import for this `POTemplate`
        :param logger: optional logger to report problems to.
        :param txn: optional transaction manager for intermediate
            commits.  Used to prevent long-running transactions that can
            lead to deadlocks.

        :return: a tuple of the subject line and body for a notification email
            to be sent to the uploader.
        """

    def getTranslationRows():
        """Return the `IVPOTexport` objects for this template."""

    def awardKarma(person, action_name):
        """Award karma for a translation action on this template."""

    def getTranslationPolicy():
        """Return the applicable `ITranslationPolicy` object.
Exemplo n.º 8
0
class IGSSearchResults(Interface):
    """The generic search results"""

    s = TextLine(title="Search Text",
                 description="Text that is searched for",
                 required=False,
                 default="")

    gs = TextLine(title="Group Identifier",
                  description="Unique Identifier for a group",
                  required=False)

    g = List(
        title="Group IDs",
        description="The groups to search in; defaults to all visible groups",
        required=False,
        default=[],
        value_type=gs,
        unique=True,
    )

    ais = TextLine(title='Author ID',
                   description='Unique Identifier of an author',
                   required=False)

    a = List(
        title="Author IDs",
        description="The author to search with; defaults to any",
        required=False,
        default=[],
        value_type=ais,
        unique=True,
    )

    l = Int(
        title="Limit",
        description="Number of items to show in the results",
        required=False,
        min=1,
        default=20,
    )

    i = Int(
        title="Start Index",
        description="The index of the first item show in the results",
        required=False,
        min=0,
        default=0,
    )

    t = Bool(title="View Topics",
             description="Whether the topic-results should be viewed",
             required=False,
             default=True)

    p = Bool(title="View Posts",
             description="Whether the post-results should be viewed",
             required=False,
             default=False)

    f = Bool(title="View Files",
             description="Whether the file-results should be viewed",
             required=False,
             default=True)

    r = Bool(title="View Profiles",
             description="Whether the profile-results should be viewed",
             required=False,
             default=True)

    mg = Bool(title="Member groups only",
              description="Limit the search to groups in which the user is a "
              "member only",
              required=False,
              default=False)

    ms = ASCIILine(
        title="MIME Type",
        description="MIME Type of the returned file (file search only).",
        required=False)
    m = List(
        title='MIME Types',
        description="The file types to search for (file search only).",
        required=False,
        default=[],
        value_type=ms,
        unique=True,
    )

    st = Bool(title="Show Thumbnails",
              description="Whether the thumbnails for images should be shown",
              required=False,
              default=None)
Exemplo n.º 9
0
class IVPOExport(Interface):
    """Shorthand of translation messages for efficient exports."""

    pofile = Object(
        title=u"Translation file",
        required=True, readonly=True, schema=IPOFile)

    diverged = Text(
        title=u"Message divergence.",
        description=u"A POTemplate this is a divergence for, or None.",
        required=False, readonly=True)

    potmsgset = Object(
        title=u"See `IPOTMsgSet`.",
        required=True, readonly=True, schema=IPOTMsgSet)

    sequence = Int(
        title=u"Message sequence number",
        description=u"As in IPOTMsgSet.",
        required=True, readonly=True)

    comment = Text(
        title=u"Comment for translated message",
        description=u"Same as IPOTMsgSet.commenttext.",
        required=False, readonly=True)

    source_comment = Text(
        title=u"Comment for original message",
        description=u"Same as IPOTMsgSet.sourcecomment.",
        required=False, readonly=True)

    file_references = Text(
        title=u"Message's source location",
        description=u"Same as IPOTMsgSet.filereferences.",
        required=False, readonly=True)

    flags_comment = Text(
        title=u"Message flags",
        description=u"Same as IPOTMsgSet.flagscomment.",
        required=False, readonly=True)

    context = Text(
        title=u"Message context",
        description=u"As in IPOTMsgSet.", readonly=True, required=False)

    msgid_singular = Text(
        title=u"Message identifier (singular)",
        description=u"See IPOMsgID.pomsgid.",
        required=True, readonly=True)

    msgid_plural = Text(
        title=u"Message identifier (plural)",
        description=u"See IPOMsgID.pomsgid.",
        required=False, readonly=True)

    is_current_ubuntu = Bool(
        title=_("Whether this message is currently used in Launchpad"),
        description=u"As in ITranslationMessage.",
        readonly=True, required=True)

    is_current_upstream = Bool(
        title=_("Whether this message was imported"),
        description=u"As in ITranslationMessage.",
        readonly=True, required=True)

    assert TranslationConstants.MAX_PLURAL_FORMS == 6, (
        "Change this code to support %d plural forms."
        % TranslationConstants.MAX_PLURAL_FORMS)

    translation0 = Text(
        title=u"Translation in plural form 0",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)

    translation1 = Text(
        title=u"Translation in plural form 1",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)

    translation2 = Text(
        title=u"Translation in plural form 2",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)

    translation3 = Text(
        title=u"Translation in plural form 3",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)

    translation4 = Text(
        title=u"Translation in plural form 4",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)

    translation5 = Text(
        title=u"Translation in plural form 5",
        description=u"As in ITranslationMessage.",
        readonly=True, required=False)
class ICKEditorBaseSchema(Interface):
    """
    CKEditor Base fieldset schema
    """

    forcePasteAsPlainText = Bool(
        title=_(u"Force paste as plain text"),
        description=_(u"Choose if you want to remove format on copy/paste, "
                      "and paste only text and CR/LF"),
        default=False,
        required=False)

    toolbar = Choice(
        title=_(u"Toolbar"),
        description=_(u"Choose the editor toolbar, "
                      "edit the next field if you choose a Custom toolbar'."),
        required=True,
        default='Plone',
        vocabulary="collective.ckeditor.vocabularies.toolbar")

    toolbar_Custom = Text(title=_(u"Customized Toolbar"),
                          description=_(
                              u"Build your own CKEditor Toolbar. "
                              "Take care with the javascript syntax. "
                              "If you want to add new plugins, "
                              "add new buttons here if needed."),
                          required=False)

    menuStyles = Text(title=_(u"Menu styles"),
                      description=_(
                          u"Build your own CKEditor menu styles Combo box. "
                          "Take care with the javascript syntax. "
                          "If you want to use css classes or ids, "
                          "the attributes must exist in your css."),
                      required=True)

    bodyId = TextLine(title=_(u"Area Body Id"),
                      description=_(u"Enter the css id applied to the "
                                    "body tag of the editor area"),
                      default=u'content',
                      required=False)

    plugins = List(title=_(u"Plugins"),
                   description=_(u"Plugin format is 'id;relative path'."),
                   value_type=TextLine(),
                   required=False)

    bodyClass = TextLine(title=_(u"Area Body Class"),
                         description=_(
                             u"Enter the css class name applied to the "
                             "body tag of the editor area"),
                         required=False)

    customTemplates = List(title=_(u"Custom templates"),
                           description=_(
                               u"URLs of Javascript "
                               "files that register custom templates"),
                           value_type=TextLine(),
                           required=False)

    templatesReplaceContent = Bool(
        title=_(u"Templates will replace the current contents "
                "of the visual editor window"),
        description=_(u"Choose if you want templates to replace "
                      "the contents when inserted"),
        default=False,
        required=False)
class ICKEditorBrowserSchema(Interface):
    """
    CKEditor Browser fieldset schema
    """
    allow_link_byuid = Bool(
        title=_(u"Allow link objects by UID"),
        description=_(u"Check if you want url with Unique ID "
                      "(no more 404 errors when moving objects). "
                      "Notice that portal_transforms in standard "
                      "configuration transforms uid links in absolute urls "
                      "in view displays."),
        default=True,
        required=False)

    allow_relative_links = Bool(
        title=_(u"Allow relative urls transformation"),
        description=_(u"Check if you want relative urls after saving forms. "
                      "Useful when link by uid is not checked."),
        default=False,
        required=False)

    allow_server_browsing = Bool(title=_(u"Allow browsing for links"),
                                 description=_(
                                     u"Check to allow server browsing"
                                     "used for medias linking."),
                                 default=True,
                                 required=False)

    allow_file_upload = Bool(
        title=_(u"Allow file upload"),
        description=_(u"Check to allow files upload in link dialog boxes)."),
        default=False,
        required=False)

    allow_image_upload = Bool(
        title=_(u"Allow image upload"),
        description=_(u"Check to allow upload for images."),
        default=False,
        required=False)

    allow_flash_upload = Bool(
        title=_(u"Allow flash upload"),
        description=_(u"Check to allow upload for flash content."),
        default=False,
        required=False)

    allow_folder_creation = Bool(
        title=_(u"Allow folder creation"),
        description=_(u"Check to allow folder creation in browser."),
        default=False,
        required=False)

    file_portal_type = Choice(
        title=_(u"File portal type"),
        description=_(u"Choose the portal type used for file upload."),
        required=True,
        default='File',
        vocabulary="collective.ckeditor.vocabularies.FileTypeUpload")

    file_portal_type_custom = List(
        title=_(u"Custom File portal type for upload"),
        description=_(u"Add list of pairs CONTAINER_TYPE|FILE_TYPE. "
                      "The file portal type choosen for upload will depend "
                      "on contextual container portal type. "
                      "* means any portal type."
                      "Take care, no control is done over this field value."),
        required=False,
        value_type=TextLine(),
        default=[
            '*|File',
            'Folder|File',
        ])

    browse_images_portal_types = Tuple(
        title=_(u"Portal Types for images linking"),
        description=_(u"Choose the types used "
                      "for images selection in browser."),
        required=True,
        missing_value=tuple(),
        default=(
            'Image',
            'News Item',
        ),
        value_type=Choice(
            vocabulary="collective.ckeditor.vocabularies.ImageTypes"))

    image_portal_type = Choice(
        title=_(u"Image portal type"),
        description=_(u"Choose the portal type used for image upload."),
        required=True,
        default='auto',
        vocabulary="collective.ckeditor.vocabularies.ImageTypeUpload")

    image_portal_type_custom = List(
        title=_(u"Custom Image portal type for upload"),
        description=_(u"Add list of pairs CONTAINER_TYPE|IMAGE_TYPE. "
                      "The image portal type choosen for upload will depend "
                      "on contextual container portal type. "
                      "* means any portal type."
                      "Take care, no control is done over this field value."),
        required=False,
        value_type=TextLine(),
        default=[
            '*|Image',
            'Folder|Image',
        ])

    browse_flashs_portal_types = Tuple(
        title=_(u"Portal Types for flash contents linking"),
        description=_(u"Choose the types used "
                      "for flash contents selection in browser."),
        required=True,
        missing_value=tuple(),
        default=('File', ),
        value_type=Choice(
            vocabulary="collective.ckeditor.vocabularies.FileTypes"))

    flash_portal_type = Choice(
        title=_(u"Flash portal type"),
        description=_(u"Choose the portal type used for flash content upload"),
        required=True,
        default='File',
        vocabulary="collective.ckeditor.vocabularies.FileTypeUpload")

    flash_portal_type_custom = List(
        title=_(u"Custom Flash portal type for upload"),
        description=_(u"Add list of pairs CONTAINER_TYPE|FLASH_TYPE. "
                      "The flash portal type choosen for upload will depend "
                      "on contextual container portal type. "
                      "* means any portal type. "
                      "Take care, no control is done over this field value."),
        required=False,
        value_type=TextLine(),
        default=[
            '*|File',
            'Folder|File',
        ])

    folder_portal_type = Choice(
        title=_(u"Folder portal type"),
        description=_(u"Choose the portal type used for folder creation"),
        required=True,
        default='Folder',
        vocabulary="collective.ckeditor.vocabularies.FolderTypes")

    folder_portal_type_custom = List(
        title=_(u"Custom portal type for folder creation"),
        description=_(u"Add list of pairs CONTAINER_TYPE|FOLDER_TYPE. "
                      "The folder portal type choosen for folders creation "
                      "will depend on contextual container portal type. "
                      "* means any portal type. "
                      "Take care, no control is done over this field value."),
        required=False,
        value_type=TextLine(),
        default=[
            '*|Folder',
            'Large Plone Folder|Large Plone Folder',
        ])
Exemplo n.º 12
0
class IObjectManager(IZopeObject, ICopyContainer, INavigation, IManageable,
                     IAcquirer, IPersistent, ITraversable, IPossibleSite,
                     IContainer):
    """Generic object manager

    This interface provides core behavior for collections of heterogeneous
    objects."""

    meta_types = Tuple(
        title=u"Meta types",
        description=u"Sub-object types that are specific to this object",
    )

    isAnObjectManager = Bool(title=u"Is an object manager", )

    manage_main = Attribute(""" """)
    manage_index_main = Attribute(""" """)
    manage_addProduct = Attribute(""" """)
    manage_importExportForm = Attribute(""" """)

    def all_meta_types(interfaces=None):
        """
        """

    def _subobject_permissions():
        """
        """

    def filtered_meta_types(user=None):
        """Return a list of the types for which the user has adequate
        permission to add that type of object.
        """

    def _setOb(id, object):
        """
        """

    def _delOb(id):
        """
        """

    def _getOb(id, default=None):
        """
        """

    def _setObject(id, object, roles=None, user=None, set_owner=1):
        """
        """

    def _delObject(id, dp=1):
        """
        """

    def hasObject(id):
        """Indicate whether the folder has an item by ID.
        """

    def objectIds(spec=None):
        """List the IDs of the subobjects of the current object.

        If 'spec' is specified, returns only objects whose meta_types match
        'spec'.
        """

    def objectValues(spec=None):
        """List the subobjects of the current object.

        If 'spec' is specified, returns only objects whose meta_types match
        'spec'.
        """

    def objectItems(spec=None):
        """List (ID, subobject) tuples for subobjects of the current object.

        If 'spec' is specified, returns only objects whose meta_types match
        'spec'.
        """

    def objectMap():
        """Return a tuple of mappings containing subobject meta-data.
        """

    def superValues(t):
        """Return all of the objects of a given type located in this object
        and containing objects.
        """

    def manage_delObjects(ids=[], REQUEST=None):
        """Delete a subordinate object

        The objects specified in 'ids' get deleted.
        """

    def tpValues():
        """Return a list of subobjects, used by tree tag.
        """

    def manage_exportObject(id='', download=None, RESPONSE=None, REQUEST=None):
        """Exports an object to a file and returns that file."""

    def manage_importObject(file, REQUEST=None, set_owner=1):
        """Import an object from a file"""

    def _importObjectFromFile(filepath, verify=1, set_owner=1):
        """
Exemplo n.º 13
0
class ISolrSchema(Interface):

    active = Bool(
        title=_('label_active', default=u'Active'),
        description=_(
            'help_active',
            default=u'Check this to enable the Solr integration, i.e. '
            u'indexing and searching using the below settings.'),
        default=False,
    )

    host = TextLine(
        title=_('label_host', default=u'Host'),
        description=_(
            'help_host',
            default=u'The host name of the Solr instance to be used.'))

    port = Int(title=_('label_port', default=u'Port'),
               description=_(
                   'help_port',
                   default=u'The port of the Solr instance to be used.'))

    base = TextLine(
        title=_('label_base', default=u'Base'),
        description=_(
            'help_base',
            default=u'The base prefix of the Solr instance to be used.'))

    async = Bool(
        title=_('label_async', default=u'Asynchronous indexing'),
        default=False,
        description=_(
            'help_async',
            default=u'Check to enable asynchronous indexing operations, '
            u'which will improve Zope response times in return for '
            u'not having the Solr index updated immediately.'))

    auto_commit = Bool(
        title=_('label_auto_commit', default=u'Automatic commit'),
        default=True,
        description=_(
            'help_auto_commit',
            default=u'If enabled each index operation will cause a commit '
            u'to be sent to Solr, which causes it to update its '
            u'index. If you disable this, you need to configure '
            u'commit policies on the Solr server side.'))

    commit_within = Int(
        title=_('label_commit_within', default=u'Commit within'),
        default=0,
        description=_(
            'help_commit_within',
            default=u'Maximum number of milliseconds after which adds '
            u'should be processed by Solr. Defaults to 0, meaning '
            u'immediate commits. Enabling this feature implicitly '
            u'disables automatic commit and you should configure '
            u'commit policies on the Solr server side. Otherwise '
            u'large numbers of deletes without adds will not be '
            u'processed. This feature requires a Solr 1.4 server.'))

    index_timeout = Float(
        title=_('label_index_timeout', default=u'Index timeout'),
        description=_(
            'help_index_timeout',
            default=u'Number of seconds after which an index request will '
            u'time out. Set to "0" to disable timeouts.'))

    search_timeout = Float(
        title=_('label_search_timeout', default=u'Search timeout'),
        description=_(
            'help_search_timeout',
            default=u'Number of seconds after which a search request will '
            u'time out. Set to "0" to disable timeouts.'))

    max_results = Int(
        title=_('label_max_results', default=u'Maximum search results'),
        description=_(
            'help_max_results',
            default=u'Specify the maximum number of matches to be returned '
            u'when searching. Set to "10000000" or some other '
            u'ridiculously large value that is higher than the '
            u'possible number of rows that are expected.'),
        default=1000000,
    )

    required = List(
        title=_('label_required', default=u'Required query parameters'),
        description=_(
            'help_required',
            default=u'Specify required query parameters, one per line. '
            u'Searches will only get dispatched to Solr if any '
            u'of the listed parameters is present in the query. '
            u'Leave empty to dispatch all searches.'),
        value_type=TextLine(),
        default=[],
        missing_value=[],
        required=False)

    search_pattern = Text(
        title=_('label_search_pattern',
                default=u'Pattern for simple search queries'),
        description=_(
            'help_search_pattern',
            default=u'Specify a query pattern used for simple queries '
            u'consisting only of words and numbers, i.e. not '
            u'using any of Solr\'s advanced query expressions. '
            u'{value} and {base_value} are available in the '
            u'pattern and will be replaced by the search word '
            u'and the search word stripped of wildcard symbols.'))

    facets = List(
        title=_('label_facets', default=u'Default search facets'),
        description=_(
            'help_facets',
            default=u'Specify catalog indexes that should be queried for '
            u'facet information, one per line.'),
        value_type=TextLine(),
        default=[],
        required=False)

    filter_queries = List(
        title=_('label_filter_queries', default=u'Filter query parameters'),
        description=_(
            'help_filter_queries',
            default=u'Specify query parameters for which filter queries '
            u'should be used, one per line.  You can use several '
            u'indices in one filter query separated by space. '
            u'Typical examples are '
            u'"effective expires allowedRolesAndUsers" or '
            u'"review_state portal_type".'),
        value_type=TextLine(),
        default=[],
        required=False)

    slow_query_threshold = Int(
        title=_('label_slow_query_threshold', default=u'Slow query threshold'),
        description=_(
            'help_slow_query_threshold',
            default=u'Specify a threshold (in milliseconds) after which '
            u'queries are considered to be slow causing them to '
            u'be logged. Set to "0" to prevent any logging.'),
        default=0,
    )

    effective_steps = Int(
        title=_('label_effective_steps', default=u'Effective date steps'),
        default=1,
        description=_('help_effective_steps',
                      default=u'Specify the effective date steps in seconds. '
                      u'Using 900 seconds (15 minutes) means the effective '
                      u'date sent to Solr changes every 15 minutes.'))

    exclude_user = Bool(
        title=_('label_exclude_user',
                default=u'Exclude user from allowedRolesAndUsers'),
        description=_(
            'help_exclude_user',
            default=u'Specify whether the user:userid should be excluded '
            u'from allowedRolesAndUsers to improve cacheability '
            u'on the expense of finding content with local roles'
            u'given to specific users.'),
        default=False)

    highlight_fields = List(
        title=_('label_highlight_fields', u'Highlighting fields'),
        description=_(
            'help_highlight_fields',
            default=(u'Fields that should be used for highlighting. '
                     u'Snippets of text will be generated from the contents '
                     u'of these fields, with the search keywords that '
                     u'matched highlighted inside the text.')),
        value_type=TextLine(),
        default=[],
        required=False)

    highlight_formatter_pre = TextLine(
        title=_('label_highlight_formatter_pre',
                default=u'Highlight formatter: pre'),
        description=_(
            'help_highlight_formatter_pre',
            default=u'The text to insert before the highlighted keyword.'),
        default=u'[',
        required=False)

    highlight_formatter_post = TextLine(
        title=_('label_highlight_formatter_post',
                default=u'Highlight formatter: post'),
        description=_(
            'help_highlight_formatter_post',
            default=u'The text to insert after the highlighted keyword.'),
        default=u']',
        required=False)

    highlight_fragsize = Int(
        title=_('label_highlight_fragsize',
                default=u'Highlight Fragment Size'),
        description=_(
            'help_highlight_fragsize',
            default=(u'The size, in characters, of the snippets (aka '
                     u'fragments) created by the highlighter.')),
        default=100,
    )

    field_list = List(
        title=_('label_field_list', default=u'Default fields to be returned'),
        description=_(
            'help_field_list',
            default=(u'Specify metadata fields that should be returned for '
                     u'items in the result set, one per line. Defaults to '
                     u'all available plus ranking score.')),
        value_type=TextLine(),
        default=[],
        required=False)

    levenshtein_distance = Float(
        title=_('label_levenshtein_distance', default=u'Levenshtein distance'),
        description=_(
            'help_levenshtein_distance',
            default=u'The Levenshtein distance is a string metric for '
            u'measuring the difference between two strings. It allows'
            u'you to perform fuzzy searches by specifying a value '
            u'between 0 and 1.'),
        required=False,
        default=0.0,
    )

    atomic_updates = Bool(
        title=_('label_atomic_updates', default=u'Enable atomic updates'),
        description=_(
            'help_atomic_updates',
            default=u'Atomic updates allows you to update only specific '
            u'indexes, like "reindexObject(idxs=["portal_type"])".'
            u'Unfortunately atomic updates are not compatible with '
            u'index time boosting. If you enable atomic updates, '
            u'index time boosting no longer works.'),
        default=True,
        required=False,
    )

    boost_script = Text(
        title=_('label_boost_script',
                default=u'Python script for custom index boosting'),
        required=False,
        default=u'',
        missing_value=u'',
        description=_(
            'help_boost_script',
            default=u'This script is meant to be customized according to '
            u'site-specific search requirements, e.g. boosting '
            u'certain content types like "news items", ranking older '
            u'content lower, consider special important content items,'
            u' content rating etc.'
            u' the indexing data that will be sent to Solr is passed '
            u'in as the `data` parameter, the indexable object is '
            u'available via the `context` binding. The return value '
            u'should be a dictionary consisting of field names and '
            u'their respecitive boost values.  use an empty string '
            u'as the key to set a boost value for the entire '
            u'document/content item.'))
Exemplo n.º 14
0
class IMultiLanguageOptionsSchema(Interface):
    """ Interface for language options - control panel fieldset
    """

    use_content_negotiation = Bool(
        title=_(u"heading_language_of_the_content",
                default=u"Use the language of the content item."),
        description=_(u"description_language_of_the_content",
                      default=u"Use the language of the content item."),
        required=False,
    )

    use_path_negotiation = Bool(
        title=_(
            u"heading_language_codes_in_URL",
            default=u"Use language codes in URL path for manual override."),
        description=_(
            u"description_language_codes_in_URL",
            default=u"Use language codes in URL path for manual override."),
        required=False,
    )

    use_cookie_negotiation = Bool(
        title=_(u"heading_cookie_manual_override",
                default=(u"Use cookie for manual override. (Required for "
                         u"the language selector viewlet to be rendered.)")),
        description=_(
            u"description_cookie_manual_override",
            default=(u"Use cookie for manual override. (Required for the "
                     u"language selector viewlet to be rendered.)")),
        required=False,
    )

    authenticated_users_only = Bool(
        title=_(u"heading_auth_cookie_manual_override",
                default=u"Authenticated users only."),
        description=_(
            u"description_auth_ookie_manual_override",
            default=(u"Authenticated users only. Use cookie for manual "
                     u"override. (Required for the language selector viewlet "
                     u"to be rendered.)")),
        required=False,
    )

    set_cookie_everywhere = Bool(
        title=_(u"heading_set_language_cookie_always",
                default=(u"Set the language cookie always, i.e. also when the "
                         u"'set_language' request parameter is absent.")),
        description=_(
            u"description_set_language_cookie_always",
            default=(u"Set the language cookie always, i.e. also when the "
                     u"'set_language' request parameter is absent.")),
        required=False,
    )

    use_subdomain_negotiation = Bool(
        title=_(u"heading_use_subdomain",
                default=u"Use subdomain (e.g.: de.plone.org)."),
        description=_(u"description_use_subdomain",
                      default=u"Use subdomain (e.g.: de.plone.org)."),
        required=False,
    )

    use_cctld_negotiation = Bool(
        title=_(u"heading_top_level_domain",
                default=u"Use top-level domain (e.g.: www.plone.de)."),
        description=_(u"description_top_level_domain",
                      default=u"Use top-level domain (e.g.: www.plone.de)."),
        required=False,
    )

    use_request_negotiation = Bool(
        title=_(u"heading_browser_language_request_negotiation",
                default=u"Use browser language request negotiation."),
        description=_(u"description_browser_language_request_negotiation",
                      default=u"Use browser language request negotiation."),
        required=False,
    )
Exemplo n.º 15
0
class IDesignPloneSettings(Interface):
    tipologie_notizia = SourceText(
        title=_("tipologie_notizia_label", default="Tipologie Notizia"),
        description=_(
            "tipologie_notizia_help",
            default="Inserisci i valori utilizzabili per le tipologie di una"
            " Notizia. Se il sito è multilingua, puoi inserire valori diversi"
            " a seconda delle lingue del sito.",
        ),
        required=True,
        default=json.dumps({"it": ["Avviso", "Comunicato stampa", "Novità"]}),
    )

    tipologie_unita_organizzativa = SourceText(
        title=_(
            "tipologie_unita_organizzativa_label",
            default="Tipologie Unità Organizzativa",
        ),
        description=_(
            "tipologie_unita_organizzativa_help",
            default="Inserisci i valori utilizzabili per le tipologie di un' "
            "Unità Organizzativa. Se il sito è multilingua, puoi inserire "
            "valori diversi a seconda delle lingue del sito.",
        ),
        required=True,
        default=json.dumps({"it": ["Politica", "Amministrativa", "Altro"]}),
    )

    tipologie_documento = SourceText(
        title=_("tipologie_documento_label", default="Tipologie Documento"),
        description=_(
            "tipologie_documento_help",
            default="Inserisci i valori utilizzabili per le tipologie di un "
            "Documento. Se il sito è multilingua, puoi inserire "
            "valori diversi a seconda delle lingue del sito.",
        ),
        required=True,
        default=json.dumps(
            {
                "it": [
                    "Accordi tra enti",
                    "Atti normativi",
                    "Dataset",
                    "Documenti (tecnici) di supporto",
                    "Documenti albo pretorio",
                    "Documenti attività politica",
                    "Documenti funzionamento interno",
                    "Istanze",
                    "Modulistica",
                ]
            }
        ),
    )

    tipologie_persona = SourceText(
        title=_("tipologie_persona_label", default="Tipologie Persona"),
        description=_(
            "tipologie_persona_help",
            default="Inserisci i valori utilizzabili per le tipologie di "
            "una Persona. Se il sito è multilingua, puoi inserire "
            "valori diversi a seconda delle lingue del sito.",
        ),
        required=True,
        default=json.dumps({"it": ["Amministrativa", "Politica", "Altro tipo"]}),
    )

    ruoli_persona = SourceText(
        title=_("ruoli_persona_label", default="Ruoli Persona"),
        description=_(
            "ruoli_persona_help",
            default="Inserisci i valori utilizzabili per il ruolo di "
            "una Persona. Se il sito è multilingua, puoi inserire "
            "valori diversi a seconda delle lingue del sito.",
        ),
        required=True,
        default=json.dumps(
            {
                "it": [
                    "Assessore",
                    "Sindaco",
                    "Consigliere",
                    "Referente ufficio",
                    "Responsabile",
                    "Presidente",
                ]
            }
        ),
    )

    lead_image_dimension = List(
        title=_(
            "lead_image_dimension_label",
            default="Dimensioni lead image",
        ),
        description=_(
            "lead_image_dimension_help",
            default="Se un content-type deve avere una dimensione della "
            "leadimage particolare, indicarle qui. "
            "Inserire le dimensioni nella forma di esempio "
            "PortalType|900x900",
        ),
        required=True,
        default=[
            "News Item|1920x600",
            "Servizio|1920x600",
            "UnitaOrganizzativa|1920x600",
            "Persona|180x100",
        ],
        value_type=TextLine(),
    )

    search_sections = SourceText(
        title=_("search_sections_label", default="Sezioni ricerca"),
        description=_(
            "search_sections_help",
            default="Inserire una lista di sezioni per la ricerca.",
        ),
        default="",
        required=False,
    )

    show_modified_default = Bool(
        title=_("show_modified_default_label", default="Mostra la data di modifica"),
        description=_(
            "show_modified_default_help",
            default="Questo è il valore di default per decidere se mostrare "
            "o meno la data di modifica nei contenuti che hanno la behavior "
            "abilitata. E' poi possibile sovrascrivere il default nei singoli "
            'contenuti (nel tab "Impostazioni").',
        ),
        default=True,
        required=False,
    )
class IBinaryPackageRelease(Interface):
    id = Int(title=_('ID'), required=True)
    binarypackagename = Int(required=True)
    binarypackagenameID = Int(required=True)
    version = TextLine(required=True, constraint=valid_debian_version)
    summary = Text(required=True)
    description = Text(required=True)
    build = Int(required=True)
    binpackageformat = Int(required=True)
    component = Int(required=True)
    section = Int(required=True)
    priority = Int(required=False)
    shlibdeps = TextLine(required=False)
    depends = TextLine(required=False)
    recommends = TextLine(required=False)
    suggests = TextLine(required=False)
    conflicts = TextLine(required=False)
    replaces = TextLine(required=False)
    provides = TextLine(required=False)
    pre_depends = TextLine(required=False)
    enhances = TextLine(required=False)
    breaks = TextLine(required=False)
    essential = Bool(required=False)
    installedsize = Int(required=False)
    architecturespecific = Bool(required=True)
    datecreated = Datetime(required=True, readonly=True)
    debug_package = Object(
        title=_("Debug package"),
        schema=Interface,
        required=False,
        description=_("The corresponding package containing debug symbols "
                      "for this binary."))
    user_defined_fields = List(
        title=_("Sequence of user-defined fields as key-value pairs."))

    homepage = TextLine(
        title=_("Homepage"),
        description=_(
            "Upstream project homepage as set in the package. This URL is not "
            "sanitized."),
        required=False)

    files = Attribute("Related list of IBinaryPackageFile entries")

    title = TextLine(required=True, readonly=True)
    name = Attribute("Binary Package Name")
    sourcepackagename = Attribute(
        "The name of the source package from where this binary was built.")

    # Properties.
    distributionsourcepackagerelease = Attribute(
        "The sourcepackage release in this distribution from which this "
        "binary was built.")

    is_new = Bool(title=_("New Binary."),
                  description=_(
                      "True if there binary version was never published for "
                      "the architeture it was built for. False otherwise."))

    # This is a dictionary for fast retrieval over the webservice.
    properties = Dict(title=_("The properties of this binary."))

    def addFile(file):
        """Create a BinaryPackageFile record referencing this build
        and attach the provided library file alias (file).
        """

    def override(component=None, section=None, priority=None):
        """Uniform method to override binarypackagerelease attribute.
Exemplo n.º 17
0
class IQuickUploadControlPanel(Interface):
    """
    fields for quick upload control panel
    """
    use_flashupload = Bool(
        title=_(u"title_use_flashupload", default=u"Use Flash Upload"),
        description=_(
            u"description_use_flashupload",
            default=u"By default, the upload script is a javascript only "
            u"tool. Check this option to replace it with a Flash "
            u"Upload based script. For modern browsers the javascript "
            u"tool is more powerful. Flash Upload is just more user "
            u"friendly under other browsers (MSIE 7, MSIE 8), but has "
            u"many problems : don't work in https, don't work behind "
            u"HTTP Authentication ..."),
        default=False,
        required=False)

    use_flash_as_fallback = Bool(
        title=_(u"title_use_flash_fallback",
                default=u"Use flash as fallback for IE"),
        description=_(
            u"description_use_flash_fallback",
            default=u"Check if you want to use flash uload as fallback for IE"
        ),
        default=False,
        required=False)

    auto_upload = Bool(
        title=_(u"title_auto_upload", default=u"Automatic upload on select"),
        description=_(
            u"description_auto_upload",
            default=u"Check if you want to start the files upload on select, "
            u"without submit the form. Note that you cannot choose "
            u"file titles or descriptions with this option set to "
            u"True."),
        default=False,
        required=False)

    show_upload_action = Bool(
        title=_('title_show_upload_action', default=u'Show "Upload" action'),
        description=_(
            'description_show_upload_action',
            default=u'Check if '
            'you want to have an "Upload" link in your edit bar. Clicking it '
            'will open a panel for uploading below the title of the current '
            'item. This panel is an alternative to the "Upload" portlet and '
            'does not offer any further configuration, such as filtering by '
            'content type. The panel will only be shown where the "Upload" '
            'portlet is not present.'),
        default=False,
        required=False,
    )

    fill_titles = Bool(
        title=_(u"title_fill_titles", default=u"Fill title before upload"),
        description=_(u"description_fill_titles",
                      default=u"If checked, you can fill the files titles "
                      u"before upload. Uncheck if you don't need titles."),
        default=True,
        required=False)

    fill_descriptions = Bool(
        title=_(u"title_fill_descriptions",
                default=u"Fill description before upload"),
        description=_(
            u"description_fill_descriptions",
            default=u"If checked, you can fill the files descriptions "
            u"before upload. Uncheck if you don't need descriptions."),
        default=False,
        required=False)

    size_limit = Int(
        title=_(u"title_size_limit", default=u"Size limit"),
        description=_(u"description_size_limit",
                      default=u"Size limit for each file in KB, 0 = no limit"),
        default=0,
        required=True)

    sim_upload_limit = Int(
        title=_(u"title_sim_upload_limit",
                default=u"Simultaneous uploads limit"),
        description=_(
            u"description_sim_upload_limit",
            default=u"Number of simultaneous files uploaded, over this number "
            u"uploads are placed in a queue, 0 = no limit"),
        default=2,
        required=True)

    object_override = Bool(
        title=_(u"title_object_override", default=u"Override by upload file"),
        description=_(u"description_object_override",
                      default=u"If the folder already has same file name, "
                      u"Checked: Override, Non-Checked: raise upload error."),
        default=True,
        required=False)
Exemplo n.º 18
0
class IAdmUtilLinuxHa(Interface):
    """
    major component for registration and event distribution 
    """
    linuxHaServerActive = Bool(
        title = _("HA-Cluster active"),
        description = _("HA-Cluster connector active"),
        default = False,
        required = False)

    linuxHaServerIp = HostIpValid(
        min_length = 1,
        max_length = 30,
        title = _("HA-Cluster IP"),
        description = _("Active IP address of the ha cluster"),
        default = u"0.0.0.0",
        required = False)
    
    linuxHaServerPort = Int(
        min = 1,
        max = 65535,
        title = _("HA-Cluster Port"),
        description = _("Port of of the ha cluster"),
        default = 5560,
        required = False)
    
    linuxHaUsername = TextLine(
        title = _("HA-Cluster Username"),
        description = _("Name of user with admin rights on ha cluster"),
        default = u"username",
        required = False)

    linuxHaPassword = Password(
        title = _("HA-Cluster Password"),
        description = _("Password of user with admin rights on ha cluster"),
        default = u"password",
        required = False)

    connState = Attribute("Connection State")

    def keys(self):
        '''See interface `IReadContainer`'''

    def __iter__(self):
        '''See interface `IReadContainer`'''

    def __getitem__(self, key):
        '''See interface `IReadContainer`'''

    def get(self, key, default=None):
        '''See interface `IReadContainer`'''

    def values(self):
        '''See interface `IReadContainer`'''

    def __len__(self):
        '''See interface `IReadContainer`'''

    def items(self):
        '''See interface `IReadContainer`'''

    def __contains__(self, key):
        '''See interface `IReadContainer`'''

    def connect2HaCluster(self):
        ''' '''
    def getNodes(self):
        """ list of all cluster nodes objects
Exemplo n.º 19
0
class IPOTemplateSubset(Interface):
    """A subset of POTemplate."""

    sourcepackagename = Object(
        title=_('The `ISourcePackageName` associated with this subset.'),
        schema=ISourcePackageName)

    distroseries = Object(
        title=_('The `IDistroSeries` associated with this subset.'),
        # Really IDistroSeries, see _schema_circular_imports.py.
        schema=Interface)

    productseries = Object(
        title=_('The `IProductSeries` associated with this subset.'),
        # Really IProductSeries, see _schema_circular_imports.py.
        schema=Interface)

    iscurrent = Bool(
        title=_("Filter for iscurrent flag."),
        description=_(
            "The filter for the iscurrent flag that this subset should "
            "apply. The filter is disabled if it is None"),
        required=False)

    title = TextLine(title=_('The translation file title.'),
                     required=True,
                     readonly=True)

    def __iter__():
        """Return an iterator over all POTemplate for this subset."""

    def __len__():
        """Return the number of `IPOTemplate` objects in this subset."""

    def __getitem__(name):
        """Get a POTemplate by its name."""

    def isNameUnique(name):
        """Is the IPOTemplate name unique to the series (and package).

        The subset may only include active `IPOTemplate` objects
        (iscurrent=True), but the full set that constrains creating new
        templates includes inactive templates too. Use this method to
        verify that an `IPOTemplate` can be created before calling new().
        """

    def new(name, translation_domain, path, owner, copy_pofiles=True):
        """Create a new template for the context of this Subset.

        The name must be unique to the full subset of active and inactive
        templates in a series (and package). See `isNameUnique`.
        """

    def getPOTemplateByName(name):
        """Return the `IPOTemplate` with the given name or None.

        The `IPOTemplate` is restricted to this concrete `IPOTemplateSubset`.
        """

    def getPOTemplatesByTranslationDomain(translation_domain):
        """Return the `IPOTemplate`s with the given translation_domain.

        The search is restricted to this concrete `IPOTemplateSubset`.

        :return: An ORM result set containing the templates in the given
            `IPOTemplateSubset` with the given translation_domain.
        """

    def getPOTemplateByPath(path):
        """Return the `IPOTemplate` from this subset that has the given path.

        Return None if there is no such `IPOTemplate`.
        """

    def getAllOrderByDateLastUpdated():
        """Return an iterator over all POTemplate for this subset.

        The iterator will give entries sorted by modification.
        """

    def getClosestPOTemplate(path):
        """Return a `IPOTemplate` with a path closer to given path, or None.

        If there is no `IPOTemplate` with a common path with the given,
        argument or if there are more than one `IPOTemplate` with the same
        common path, and both are the closer ones, returns None.
        """

    def findUniquePathlessMatch(filename):
        """Find the one `POTemplate` with given filename, if there is one.
class ITranslationMessage(Interface):
    """A translation message in a translation file."""

    id = Int(title=_("The ID for this translation message"),
             readonly=True,
             required=True)

    browser_pofile = Object(
        title=_("The translation file from where this translation comes"),
        readonly=False,
        required=False,
        schema=IPOFile)

    sequence = Int(
        title=_("Sequence of a message in the PO file browser_pofile."),
        readonly=True,
        required=False)

    potemplate = Object(title=_("The template this translation is in"),
                        readonly=False,
                        required=False,
                        schema=IPOTemplate)

    language = Choice(title=_('Language of this translation message.'),
                      vocabulary='Language',
                      required=False)

    potmsgset = Object(
        title=_("The template message that this translation is for"),
        readonly=False,
        required=True,
        schema=IPOTMsgSet)

    date_created = Datetime(title=_("The date we saw this translation first"),
                            readonly=True,
                            required=True)

    submitter = Object(title=_("The submitter of this translation"),
                       readonly=True,
                       required=True,
                       schema=IPerson)

    date_reviewed = Datetime(
        title=_("The date when this message was reviewed for last time"),
        readonly=False,
        required=False)

    reviewer = Object(
        title=_("The person who reviewed and accepted this translation"),
        readonly=False,
        required=False,
        schema=IPerson)

    # Message references for up to TranslationConstants.MAX_PLURAL_FORMS
    # plural forms.
    msgstr0 = Object(title=_("Translation for plural form 0 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    msgstr1 = Object(title=_("Translation for plural form 1 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    msgstr2 = Object(title=_("Translation for plural form 2 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    msgstr3 = Object(title=_("Translation for plural form 3 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    msgstr4 = Object(title=_("Translation for plural form 4 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    msgstr5 = Object(title=_("Translation for plural form 5 (if any)"),
                     required=False,
                     schema=IPOTranslation)

    all_msgstrs = List(title=_("All msgstr attributes"),
                       description=_("""
            All translations [msgstr0, msgstr1, ...] for this message,
            including any empty ones.
            """),
                       readonly=True,
                       required=True)

    translations = List(title=_("Translations for this message"),
                        description=_("""
            All translations for this message, its number will depend on the
            number of plural forms available for its language.
            """),
                        readonly=True,
                        required=True)

    comment = Text(
        title=_("Text of translator comment from the translation file"),
        readonly=False,
        required=False)

    origin = Choice(title=_("Where the submission originally came from"),
                    values=RosettaTranslationOrigin,
                    readonly=True,
                    required=True)

    validation_status = Choice(
        title=_("The status of the validation of the translation"),
        values=TranslationValidationStatus,
        readonly=False,
        required=True)

    is_current_ubuntu = Bool(
        title=_("Whether this translation is being used in Ubuntu"),
        readonly=False,
        default=False,
        required=True)

    is_complete = Bool(
        title=_("Whether the translation has all needed plural forms or not"),
        readonly=True,
        required=True)

    is_current_upstream = Bool(title=_(
        "Whether this translation is being used in latest imported file"),
                               readonly=False,
                               default=False,
                               required=True)

    was_obsolete_in_last_import = Bool(
        title=_("Whether this translation was obsolete in last imported file"),
        readonly=False,
        default=False,
        required=True)

    is_empty = Bool(title=_("Whether this message has any translation"),
                    readonly=True,
                    required=True)

    plural_forms = Int(
        title=_("Number of plural form translations in this translation."),
        readonly=True,
        required=True)

    is_diverged = Bool(title=_("Is this message diverged?"),
                       readonly=True,
                       required=True)

    def setPOFile(pofile):
        """Set a POFile for use in views."""

    def getOnePOFile():
        """Get any POFile containing this translation."""

    def ensureBrowserPOFile():
        """Assign the result of getOnePOFile to browser_pofile.

        If browser_pofile is already set, it is left unchanged.
        """

    def getSharedEquivalent():
        """Find shared message that otherwise exactly matches this one."""

    def shareIfPossible():
        """Make this message shared, if possible.

        If there is already a similar message that is shared, this
        message's information is merged into that of the existing one,
        and self is deleted.
        """

    def isHidden(pofile):
        """Whether this is an unused, hidden suggestion in `pofile`.

        A suggestion is hidden if it's older than the current translation.
        """

    # Used in a script to remove upstream translations.
    def destroySelf():
        """Remove this object.

        It must not be referenced by any other object.
        """

    def clone(potmsgset):
        """Create a copy of this message associated with a different MsgSet.

        potemplate of the clone is always None.  Aside from this, all values
        should be the same.
        """

    def approve(pofile,
                reviewer,
                share_with_other_side=False,
                lock_timestamp=None):
        """Approve this suggestion, making it a current translation."""

    def approveAsDiverged(pofile, reviewer, lock_timestamp=None):
        """Approve this suggestion, as a diverged translation."""

    def acceptFromImport(pofile,
                         share_with_other_side=False,
                         lock_timestamp=None):
        """Accept a suggestion coming from a translation import."""

    def acceptFromUpstreamImportOnPackage(pofile, lock_timestamp=None):
        """Accept a suggestion coming from a translation import.

        This method allows to mark a translation as being current in
        upstream even though there is no upstream template.
        """

    # XXX CarlosPerelloMarin 20071022: We should move this into browser code.
    def makeHTMLID(description):
        """Unique identifier for self, suitable for use in HTML element ids.

        Constructs an identifier for use in HTML.  This identifier matches the
        format parsed by `BaseTranslationView`.

        :param description: a keyword to be embedded in the id string, e.g.
            "suggestion" or "translation."  Must be suitable for use in an
            HTML element id.
        """

    def markReviewed(reviewer, timestamp=None):
        """Mark this message as reviewed.
Exemplo n.º 21
0
class IHasTranslationTemplates(Interface):
    """An entity that has translation templates attached.

    Examples include `ISourcePackage`, `IDistroSeries`, and `IProductSeries`.
    """

    has_translation_templates = Bool(
        title=_("Does this object have any translation templates?"),
        readonly=True)

    has_current_translation_templates = Bool(
        title=_("Does this object have current translation templates?"),
        readonly=True)

    has_obsolete_translation_templates = Bool(
        title=_("Does this object have obsolete translation templates?"),
        readonly=True)

    has_sharing_translation_templates = Bool(
        title=_("Does this object have sharing translation templates?"),
        readonly=True)

    has_translation_files = Bool(
        title=_("Does this object have translation files?"),
        readonly=True)

    def getTemplatesCollection():
        """Return templates as a `TranslationTemplatesCollection`.

        The collection selects all `POTemplate`s attached to the
        translation target that implements this interface.
        """

    def getSharingPartner():
        """Return the object on the other side of the packaging link.

        Return the object that is sharing translations with this one on the
        other side of a packaging link. It must also implement this interface.
        """

    def getCurrentTemplatesCollection():
        """Return `TranslationTemplatesCollection` of current templates.

        A translation template is considered active when
        `IPOTemplate`.iscurrent flag is set to True.
        """

    def getCurrentTranslationTemplates(just_ids=False):
        """Return an iterator over all active translation templates.

        :param just_ids: If True, return only the `POTemplate.id` rather
            than the full `POTemplate`.  Used to save time on retrieving
            and deserializing the objects from the database.

        A translation template is considered active when
        `IPOTemplate`.iscurrent is set to True.
        """

    def getCurrentTranslationFiles(just_ids=False):
        """Return an iterator over all active translation files.

        A translation file is active if it's attached to an
        active translation template.
        """

    @export_read_operation()
    @operation_returns_collection_of(Interface)
    @operation_for_version('beta')
    def getTranslationTemplates():
        """Return an iterator over all its translation templates.

        The returned templates are either obsolete or current.

        :return: A sequence of `IPOTemplate`.
        """

    def getTranslationTemplateByName(name):
        """Return the template with the given name or None."""

    def getTranslationTemplateFormats():
        """A list of native formats for all current translation templates.
        """

    def getTemplatesAndLanguageCounts():
        """List tuples of `POTemplate` and its language count.
Exemplo n.º 22
0
class IDAVResource(IWriteLock):
    """Provide basic WebDAV support for non-collection objects."""

    __dav_resource__ = Bool(title=u"Is DAV resource")

    __http_methods__ = Tuple(title=u"HTTP methods",
                             description=u"Sequence of valid HTTP methods")

    def dav__init(request, response):
        """Init expected HTTP 1.1 / WebDAV headers which are not
        currently set by the base response object automagically.

        Also, we sniff for a ZServer response object, because we don't
        want to write duplicate headers (since ZS writes Date
        and Connection itself).
        """

    def dav__validate(object, methodname, REQUEST):
        """
        """

    def dav__simpleifhandler(request,
                             response,
                             method='PUT',
                             col=0,
                             url=None,
                             refresh=0):
        """
        """

    def HEAD(REQUEST, RESPONSE):
        """Retrieve resource information without a response body."""

    def PUT(REQUEST, RESPONSE):
        """Replace the GET response entity of an existing resource.
        Because this is often object-dependent, objects which handle
        PUT should override the default PUT implementation with an
        object-specific implementation. By default, PUT requests
        fail with a 405 (Method Not Allowed)."""

    def OPTIONS(REQUEST, RESPONSE):
        """Retrieve communication options."""

    def TRACE(REQUEST, RESPONSE):
        """Return the HTTP message received back to the client as the
        entity-body of a 200 (OK) response. This will often usually
        be intercepted by the web server in use. If not, the TRACE
        request will fail with a 405 (Method Not Allowed), since it
        is not often possible to reproduce the HTTP request verbatim
        from within the Zope environment."""

    def DELETE(REQUEST, RESPONSE):
        """Delete a resource. For non-collection resources, DELETE may
        return either 200 or 204 (No Content) to indicate success."""

    def PROPFIND(REQUEST, RESPONSE):
        """Retrieve properties defined on the resource."""

    def PROPPATCH(REQUEST, RESPONSE):
        """Set and/or remove properties defined on the resource."""

    def MKCOL(REQUEST, RESPONSE):
        """Create a new collection resource. If called on an existing
        resource, MKCOL must fail with 405 (Method Not Allowed)."""

    def COPY(REQUEST, RESPONSE):
        """Create a duplicate of the source resource whose state
        and behavior match that of the source resource as closely
        as possible. Though we may later try to make a copy appear
        seamless across namespaces (e.g. from Zope to Apache), COPY
        is currently only supported within the Zope namespace."""

    def MOVE(REQUEST, RESPONSE):
        """Move a resource to a new location. Though we may later try to
        make a move appear seamless across namespaces (e.g. from Zope
        to Apache), MOVE is currently only supported within the Zope
        namespace."""

    def LOCK(REQUEST, RESPONSE):
        """Lock a resource"""

    def UNLOCK(REQUEST, RESPONSE):
        """Remove an existing lock on a resource."""

    def manage_DAVget():
        """Gets the document source"""

    def listDAVObjects():
        """
Exemplo n.º 23
0
class ISpecificationWorkItem(Interface):
    """SpecificationWorkItem's public attributes and methods."""

    id = Int(title=_("Database ID"), required=True, readonly=True)

    title = Title(title=_('Title'),
                  required=True,
                  readonly=False,
                  description=_("Work item title."))

    assignee = PublicPersonChoice(
        title=_('Assignee'),
        required=False,
        readonly=False,
        description=_(
            "The person responsible for implementing the work item."),
        vocabulary='ValidPersonOrTeam')

    date_created = Datetime(title=_('Date Created'),
                            required=True,
                            readonly=True)

    milestone = Choice(
        title=_('Milestone'),
        required=False,
        readonly=False,
        vocabulary='Milestone',
        description=_(
            "The milestone to which this work item is targetted. If this "
            "is not set, then the target is the specification's "
            "milestone."))

    status = Choice(title=_("Work Item Status"),
                    required=True,
                    readonly=False,
                    default=SpecificationWorkItemStatus.TODO,
                    vocabulary=SpecificationWorkItemStatus,
                    description=_(
                        "The state of progress being made on the actual "
                        "implementation of this work item."))

    specification = Choice(
        title=_('The specification that the work item is linked to.'),
        required=True,
        readonly=True,
        vocabulary='Specification')

    deleted = Bool(title=_('Is this work item deleted?'),
                   required=True,
                   readonly=False,
                   default=False,
                   description=_("Marks the work item as deleted."))

    sequence = Int(
        title=_("Work Item Sequence."),
        required=True,
        description=_(
            "The sequence in which the work items are to be displayed in the "
            "UI."))

    is_complete = Bool(
        readonly=True,
        description=_(
            "True or False depending on whether or not there is more "
            "work required on this work item."))
class IDistributionMirror(Interface):
    """A mirror of a given distribution."""
    export_as_webservice_entry()

    id = Int(title=_('The unique id'), required=True, readonly=True)
    owner = exported(
        PublicPersonChoice(
            title=_('Owner'),
            readonly=False,
            vocabulary='ValidOwner',
            required=True,
            description=_(
                "The person who is set as the current administrator of this"
                "mirror.")))
    distribution = exported(
        Reference(
            Interface,
            # Really IDistribution, circular import fixed in
            # _schema_circular_imports.
            title=_("Distribution"),
            required=True,
            readonly=True,
            description=_("The distribution that is mirrored")))
    name = exported(
        DistributionMirrorNameField(
            title=_('Name'),
            required=True,
            readonly=False,
            description=_('A short and unique name for this mirror.'),
            constraint=name_validator))
    displayname = exported(
        TextLine(title=_('Organisation'),
                 required=False,
                 readonly=False,
                 description=_(
                     'The name of the organization hosting this mirror.')))
    description = exported(
        TextLine(title=_('Description'), required=False, readonly=False))
    http_base_url = exported(
        DistroMirrorHTTPURIField(
            title=_('HTTP URL'),
            required=False,
            readonly=False,
            allowed_schemes=['http'],
            allow_userinfo=False,
            allow_query=False,
            allow_fragment=False,
            trailing_slash=True,
            description=_('e.g.: http://archive.ubuntu.com/ubuntu/')))
    ftp_base_url = exported(
        DistroMirrorFTPURIField(
            title=_('FTP URL'),
            required=False,
            readonly=False,
            allowed_schemes=['ftp'],
            allow_userinfo=False,
            allow_query=False,
            allow_fragment=False,
            trailing_slash=True,
            description=_('e.g.: ftp://archive.ubuntu.com/ubuntu/')))
    rsync_base_url = exported(
        DistroMirrorRsyncURIField(
            title=_('Rsync URL'),
            required=False,
            readonly=False,
            allowed_schemes=['rsync'],
            allow_userinfo=False,
            allow_query=False,
            allow_fragment=False,
            trailing_slash=True,
            description=_('e.g.: rsync://archive.ubuntu.com/ubuntu/')))
    enabled = exported(
        Bool(title=_('This mirror was probed successfully.'),
             required=False,
             readonly=True,
             default=False))
    speed = exported(
        Choice(title=_('Link Speed'),
               required=True,
               readonly=False,
               vocabulary=MirrorSpeed))
    country = exported(
        ReferenceChoice(
            title=_('Location'),
            description=_("The country in which this mirror is based."),
            required=True,
            readonly=False,
            vocabulary='CountryName',
            schema=ICountry))
    content = exported(
        Choice(title=_('Content'),
               required=True,
               readonly=False,
               description=_(
                   'Choose "CD Image" if this mirror contains CD images of '
                   'this distribution. Choose "Archive" if this is a '
                   'mirror of packages for this distribution.'),
               vocabulary=MirrorContent))
    status = exported(
        Choice(
            title=_('Status'),
            required=True,
            readonly=False,
            vocabulary=MirrorStatus,
            description=_("The current status of a mirror's registration.")))

    title = Attribute('The title of this mirror')
    cdimage_series = Attribute('All MirrorCDImageDistroSeries of this mirror')
    source_series = Attribute('All MirrorDistroSeriesSources of this mirror')
    arch_series = Attribute('All MirrorDistroArchSeries of this mirror')
    last_probe_record = Attribute(
        'The last MirrorProbeRecord for this mirror.')
    all_probe_records = Attribute('All MirrorProbeRecords for this mirror.')
    has_ftp_or_rsync_base_url = Bool(
        title=_('Does this mirror have a FTP or Rsync base URL?'))
    arch_mirror_freshness = Attribute(
        'The freshness of this mirror\'s archive mirrors')
    source_mirror_freshness = Attribute(
        'The freshness of this mirror\'s source mirrors')
    base_url = Attribute('The HTTP or FTP base URL of this mirror')
    date_created = exported(
        Datetime(
            title=_('Date Created'),
            required=True,
            readonly=True,
            description=_("The date on which this mirror was registered.")))
    country_dns_mirror = exported(
        Bool(title=_('Country DNS Mirror'),
             description=_('Whether this is a country mirror in DNS.'),
             required=False,
             readonly=True,
             default=False))

    reviewer = exported(
        PublicPersonChoice(
            title=_('Reviewer'),
            required=False,
            readonly=True,
            vocabulary='ValidPersonOrTeam',
            description=_("The person who last reviewed this mirror.")))
    date_reviewed = exported(
        Datetime(
            title=_('Date reviewed'),
            required=False,
            readonly=True,
            description=_(
                "The date on which this mirror was last reviewed by a mirror "
                "admin.")))

    official_candidate = exported(
        Bool(title=_('Apply to be an official mirror of this distribution'),
             required=False,
             readonly=False,
             default=True))
    whiteboard = exported(
        Whiteboard(title=_('Whiteboard'),
                   required=False,
                   readonly=False,
                   description=_(
                       "Notes on the current status of the mirror (only "
                       "visible to admins and the mirror's registrant).")))

    @export_read_operation()
    def canTransitionToCountryMirror():
        """Verify if a mirror can be set as a country mirror or return
        False."""

    @mutator_for(country_dns_mirror)
    @operation_parameters(country_dns_mirror=copy_field(country_dns_mirror))
    @export_write_operation()
    def transitionToCountryMirror(country_dns_mirror):
        """Method run on changing country_dns_mirror."""

    @invariant
    def mirrorMustHaveHTTPOrFTPURL(mirror):
        if not (mirror.http_base_url or mirror.ftp_base_url):
            raise Invalid('A mirror must have at least an HTTP or FTP URL.')

    def getSummarizedMirroredSourceSeries():
        """Return a summarized list of this distribution_mirror's
        MirrorDistroSeriesSource objects.

        Summarized, in this case, means that it ignores pocket and components
        and returns the MirrorDistroSeriesSource with the worst freshness for
        each distroseries of this distribution mirror.
        """

    def getSummarizedMirroredArchSeries():
        """Return a summarized list of this distribution_mirror's
        MirrorDistroArchSeries objects.

        Summarized, in this case, means that it ignores pocket and components
        and returns the MirrorDistroArchSeries with the worst freshness for
        each distro_arch_series of this distribution mirror.
        """

    @export_read_operation()
    def getOverallFreshness():
        """Return this mirror's overall freshness.

        For ARCHIVE mirrors, the overall freshness is the worst freshness of
        all of this mirror's content objects (MirrorDistroArchSeries,
        MirrorDistroSeriesSource or MirrorCDImageDistroSeriess).

        For RELEASE mirrors, the overall freshness is either UPTODATE, if the
        mirror contains all ISO images that it should or UNKNOWN if it doesn't
        contain one or more ISO images.
        """

    @export_read_operation()
    def isOfficial():
        """Return True if this is an official mirror."""

    def shouldDisable(expected_file_count=None):
        """Should this mirror be marked disabled?

        If this is a RELEASE mirror then expected_file_count must not be None,
        and it should be disabled if the number of cdimage_series it
        contains is smaller than the given expected_file_count.

        If this is an ARCHIVE mirror, then it should be disabled only if it
        has no content at all.

        We could use len(get_expected_cdimage_paths()) to obtain the
        expected_file_count, but that's not a good idea because that method
        gets the expected paths from releases.ubuntu.com, which is something
        we don't have control over.
        """

    def disable(notify_owner, log):
        """Disable this mirror and notify the distro's mirror admins by email.

        :param notify_owner: If True, an identical notification is sent to the
        mirror owner.

        :param log: The log of requests/responses from the last time this
        mirror was probed.  This is only necessary because we want to include
        a snippet of the log in the email notification but the content can
        only be read back from the librarian after we commit the transaction
        (and we really don't want to do it here).

        This method can't be called before a probe record has been created
        because we'll link to the latest probe record in the email we send to
        notify the owner.

        The notification(s) are actually sent only if this mirror was
        previously enabled or if it was probed only once.
        """

    def newProbeRecord(log_file):
        """Create and return a new MirrorProbeRecord for this mirror."""

    def deleteMirrorDistroArchSeries(distro_arch_series, pocket, component):
        """Delete the MirrorDistroArchSeries with the given arch series and
        pocket, in case it exists.
        """

    def ensureMirrorDistroArchSeries(distro_arch_series, pocket, component):
        """Check if we have a MirrorDistroArchSeries with the given arch
        series and pocket, creating one if not.

        Return that MirrorDistroArchSeries.
        """

    def ensureMirrorDistroSeriesSource(distroseries, pocket, component):
        """Check if we have a MirrorDistroSeriesSource with the given distro
        series, creating one if not.

        Return that MirrorDistroSeriesSource.
        """

    def deleteMirrorDistroSeriesSource(distroseries, pocket, component):
        """Delete the MirrorDistroSeriesSource with the given distro series,
        in case it exists.
        """

    def ensureMirrorCDImageSeries(arch_series, flavour):
        """Check if we have a MirrorCDImageDistroSeries with the given
        arch series and flavour, creating one if not.

        Return that MirrorCDImageDistroSeries.
        """

    def deleteMirrorCDImageSeries(arch_series, flavour):
        """Delete the MirrorCDImageDistroSeries with the given arch
        series and flavour, in case it exists.
        """

    def deleteAllMirrorCDImageSeries():
        """Delete all MirrorCDImageDistroSeriess of this mirror."""

    def getExpectedPackagesPaths():
        """Get all paths where we can find Packages.gz files on this mirror.

        Return a list containing, for each path, the DistroArchSeries,
        the PackagePublishingPocket and the Component to which that given
        Packages.gz file refer to and the path to the file itself.
        """

    def getExpectedSourcesPaths():
        """Get all paths where we can find Sources.gz files on this mirror.
Exemplo n.º 25
0
class IQuestion(IHasOwner):
    """A single question, often a support request."""

    export_as_webservice_entry(as_of='beta')

    id = exported(Int(title=_('Question Number'),
                      required=True,
                      readonly=True,
                      description=_("The tracking number for this question.")),
                  as_of="devel")
    title = exported(TextLine(
        title=_('Summary'),
        required=True,
        description=_("A one-line summary of the issue or problem.")),
                     as_of="devel")
    description = exported(Text(
        title=_('Description'),
        required=True,
        description=_(
            "Include as much detail as possible: what "
            u"you\N{right single quotation mark}re trying to achieve, what steps "
            "you take, what happens, and what you think should happen instead."
        )),
                           as_of="devel")
    status = exported(Choice(title=_('Status'),
                             vocabulary=QuestionStatus,
                             default=QuestionStatus.OPEN,
                             readonly=True),
                      as_of="devel")
    priority = Choice(title=_('Priority'),
                      vocabulary=QuestionPriority,
                      default=QuestionPriority.NORMAL)
    # XXX flacoste 2006-10-28: It should be more precise to define a new
    # vocabulary that excludes the English variants.
    language = exported(ReferenceChoice(
        title=_('Language'),
        vocabulary='Language',
        schema=ILanguage,
        description=_('The language in which this question is written.')),
                        as_of="devel")
    owner = exported(PublicPersonChoice(title=_('Owner'),
                                        required=True,
                                        readonly=True,
                                        vocabulary='ValidPersonOrTeam'),
                     as_of="devel")
    assignee = exported(PublicPersonChoice(
        title=_('Assignee'),
        required=False,
        description=_("The person responsible for helping to resolve the "
                      "question."),
        vocabulary='ValidPersonOrTeam'),
                        as_of="devel")
    answerer = exported(PublicPersonChoice(
        title=_('Answered By'),
        required=False,
        description=_("The person who last provided a response intended to "
                      "resolve the question."),
        vocabulary='ValidPersonOrTeam'),
                        as_of="devel",
                        readonly=True)
    answer = exported(Reference(
        title=_('Answer'),
        required=False,
        description=_(
            "The IQuestionMessage that contains the answer "
            "confirmed by the owner as providing a solution to their "
            "problem."),
        schema=IQuestionMessage),
                      readonly=True,
                      as_of="devel")
    datecreated = exported(Datetime(title=_('Date Created'),
                                    required=True,
                                    readonly=True),
                           exported_as='date_created',
                           readonly=True,
                           as_of="devel")
    datedue = exported(Datetime(
        title=_('Date Due'),
        required=False,
        default=None,
        description=_(
            "The date by which we should have resolved this question.")),
                       exported_as='date_due',
                       readonly=True,
                       as_of="devel")
    datelastquery = exported(Datetime(
        title=_("Date Last Queried"),
        required=True,
        description=_("The date on which we last heard from the "
                      "customer (owner).")),
                             exported_as='date_last_query',
                             readonly=True,
                             as_of="devel")
    datelastresponse = exported(Datetime(
        title=_("Date last Responded"),
        required=False,
        description=_(
            "The date on which we last communicated "
            "with the customer. The combination of datelastquery and "
            "datelastresponse tells us in whose court the ball is.")),
                                exported_as='date_last_response',
                                readonly=True,
                                as_of="devel")
    date_solved = exported(Datetime(
        title=_("Date Answered"),
        required=False,
        description=_(
            "The date on which the question owner confirmed that the "
            "question is Solved.")),
                           exported_as='date_solved',
                           readonly=True,
                           as_of="devel")
    product = Choice(title=_('Upstream Project'),
                     required=False,
                     vocabulary='Product',
                     description=_(
                         'Select the upstream project with which you need '
                         'support.'))
    distribution = Choice(title=_('Distribution'),
                          required=False,
                          vocabulary='Distribution',
                          description=_(
                              'Select '
                              'the distribution for which you need support.'))
    sourcepackagename = Choice(
        title=_('Source Package'),
        required=False,
        vocabulary='SourcePackageName',
        description=_(
            'The source package '
            'in the distribution which contains the software with which you '
            'are experiencing difficulties.'))
    whiteboard = Text(
        title=_('Status Whiteboard'),
        required=False,
        description=_('Up-to-date notes on the status of the question.'))
    # other attributes
    target = exported(Reference(
        title=_('This question is about'),
        required=True,
        schema=IQuestionTarget,
        description=_('The distribution, source package, or project the '
                      'question pertains to.')),
                      as_of="devel")
    faq = Object(title=_('Linked FAQ'),
                 description=_(
                     'The FAQ document containing the long answer to this '
                     'question.'),
                 readonly=True,
                 required=False,
                 schema=IFAQ)

    # joins
    subscriptions = Attribute('The set of subscriptions to this question.')
    reopenings = Attribute("Records of times when this question was reopened.")
    messages = exported(CollectionField(
        title=_("Messages"),
        description=_(
            "The list of messages that were exchanged as part of this "
            "question , sorted from first to last."),
        value_type=Reference(schema=IQuestionMessage),
        required=True,
        default=[],
        readonly=True),
                        as_of='devel')

    # Workflow methods
    def setStatus(user, new_status, comment, datecreated=None):
        """Change the status of this question.

        Set the question's status to new_status and add an IQuestionMessage
        with action SETSTATUS.

        Only the question target owner or admin can change the status using
        this method.

        An InvalidQuestiontateError is raised when this method is called
        with new_status equals to the current question status.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: The IPerson making the change.
        :new_status: The new QuestionStatus
        :comment: A string or IMessage containing an explanation for the
                  change.
        :datecreated: Date for the message. Defaults to the current time.
        """

    can_request_info = Attribute(
        'Whether the question is in a state where a user can request more '
        'information from the question owner.')

    def requestInfo(user, question, datecreated=None):
        """Request more information from the question owner.

        Add an IQuestionMessage with action REQUESTINFO containing the
        question. The question's status is changed to NEEDSINFO, and the
        datelastresponse attribute is updated to the message creation date.

        The user requesting more information cannot be the question's owner.
        This workflow method should only be called when the question status is
        OPEN or NEEDSINFO. An InvalidQuestionStateError is raised otherwise.

        It can also be called when the question is in the ANSWERED state, but
        in that case, the status will stay unchanged.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: IPerson requesting for the information.
        :question: A string or IMessage containing the question.
        :datecreated: Date for the answer. Defaults to the current time.
        """

    can_give_info = Attribute(
        'Whether the question is in a state where the question owner can '
        'give more information on the question.')

    def giveInfo(reply, datecreated=None):
        """Reply to the information request.

        Add an IQuestionMessage with action GIVEINFO. The question status is
        changed to OPEN, the datelastquery attribute is updated to the
        message creation time.

        This method should only be called on behalf of the question owner when
        the question is in the OPEN or NEEDSINFO state. An
        InvalidQuestionStateError is raised otherwise.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :reply: A string or IMessage containing the new information.
        :datecreated: Date for the message. Defaults to the current time.
        """

    can_give_answer = Attribute(
        'Whether the question is in a state a user can provide an answer on '
        'the question.')

    def giveAnswer(user, answer, datecreated=None):
        """Give an answer to this question.

        If the user is not the question's owner, add an IQuestionMessage with
        action ANSWER containing an answer for the question. This changes the
        question's status to ANSWERED and updates the datelastresponse
        attribute to the message's creation date.

        When the question owner answers the question, add an IQuestionMessage
        with action CONFIRM. The question status is changed to SOLVED, the
        answerer attribute is updated to contain the question owner, the
        answer attribute will be updated to point at the new message, the
        datelastresponse and date_solved attributes are updated to the
        message creation date.

        This workflow method should only be called when the question status is
        one of OPEN, ANSWERED or NEEDSINFO. An InvalidQuestionStateError is
        raised otherwise.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: IPerson giving the answer.
        :answer: A string or IMessage containing the answer.
        :datecreated: Date for the message. Defaults to the current time.
        """

    def linkFAQ(user, faq, comment, datecreated=None):
        """Link a FAQ as an answer to this question.

        Exactly like giveAnswer() but also link the IFAQ faq object to this
        question.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :param user: IPerson linking the faq.
        :param faq: The IFAQ containing the answer.
        :param comment: A string or IMessage explaining how the FAQ is
            relevant.
        :param datecreated: Date for the message. Defaults to the current
            time.
        """

    can_confirm_answer = Attribute(
        'Whether the question is in a state for the question owner to '
        'confirm that an answer solved their problem.')

    def confirmAnswer(comment, answer=None, datecreated=None):
        """Confirm that a solution to the question was found.

        Add an IQuestionMessage with action CONFIRM. The question status is
        changed to SOLVED. If the answer parameter is not None, it is recorded
        in the answer attribute and the answerer attribute is set to that
        message's owner. The datelastresponse and date_solved attributes are
        updated to the message creation date.

        This workflow method should only be called on behalf of the question
        owner, when the question status is ANSWERED, or when the status is
        OPEN or NEEDSINFO but an answer was already provided. An
        InvalidQuestionStateError is raised otherwise.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

       :comment: A string or IMessage containing a comment.
        :answer: The IQuestionMessage that contain the answer to the question.
                 It must be one of the IQuestionMessage of this question.
        :datecreated: Date for the message. Defaults to the current time.
        """

    def canReject(user):
        """Test if a user can reject the question.

        Return true only if user is an answer contact for the question target,
        the question target owner or part of the administration team.
        """

    @operation_parameters(
        comment=Text(title=_("An explanation of the rejection")))
    @call_with(user=REQUEST_USER)
    @export_factory_operation(IQuestionMessage, [])
    @operation_for_version("devel")
    def reject(user, comment, datecreated=None):
        """Mark this question as INVALID.

        Add an IQuestionMessage with action REJECT. The question status is
        changed to INVALID. The created message is set as the question answer
        and its owner as the question answerer. The datelastresponse and
        date_solved are updated to the message creation.

        Only answer contacts for the question target, the target owner or a
        member of the admin team can reject a request. All questions can be
        rejected.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: The user rejecting the request.
        :comment: A string or IMessage containing an explanation of the
                  rejection.
        :datecreated: Date for the message. Defaults to the current time.
        """

    def expireQuestion(user, comment, datecreated=None):
        """Mark a question as EXPIRED.

        Add an IQuestionMessage with action EXPIRE. This changes the question
        status to EXPIRED and update the datelastresponse attribute to the new
        message creation date.

        This workflow method should only be called when the question status is
        one of OPEN or NEEDSINFO. An InvalidQuestionStateError is raised
        otherwise.

        Return the created IQuestionMessage.

        (Note this method is named expireQuestion and not expire because of
        conflicts with SQLObject.)

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: IPerson expiring the request.
        :comment: A string or IMessage containing an explanation for the
                  expiration.
        :datecreated: Date for the message. Defaults to the current time.
        """

    can_reopen = Attribute(
        'Whether the question state is a state where the question owner '
        'could reopen it.')

    def reopen(comment, datecreated=None):
        """Reopen a question that was ANSWERED, EXPIRED or SOLVED.

        Add an IQuestionMessage with action REOPEN. This changes the question
        status to OPEN and update the datelastquery attribute to the new
        message creation date. When the question was in the SOLVED state, this
        method should reset the date_solved, answerer and answer attributes.

        This workflow method should only be called on behalf of the question
        owner, when the question status is in one of ANSWERED, EXPIRED or
        SOLVED. An InvalidQuestionStateError is raised otherwise.

        Return the created IQuestionMessage.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :comment: A string or IMessage containing more information about the
                  request.
        :datecreated: Date for the message. Defaults to the current time.
        """

    def addComment(user, comment, datecreated=None):
        """Add a comment on the question.

        Create an IQuestionMessage with action COMMENT. It leaves the question
        status unchanged.

        This method should fire an IObjectCreatedEvent for the created
        IQuestionMessage and an IObjectModifiedEvent for the question.

        :user: The IPerson making the comment.
        :comment: A string or IMessage containing the comment.
        :datecreated: Date for the message. Defaults to the current time.
        """

    # subscription-related methods

    @operation_parameters(person=Reference(IPerson,
                                           title=_('Person'),
                                           required=True))
    @call_with(subscribed_by=REQUEST_USER)
    @export_write_operation()
    @operation_for_version("devel")
    def subscribe(person, subscribed_by=None):
        """Subscribe `person` to the question.

        :param person: the subscriber.
        :param subscribed_by: the person who created the subscription.
        :return: an `IQuestionSubscription`.
        """

    def isSubscribed(person):
        """Return a boolean indicating whether the person is subscribed."""

    @operation_parameters(person=Reference(IPerson,
                                           title=_('Person'),
                                           required=False))
    @call_with(unsubscribed_by=REQUEST_USER)
    @export_write_operation()
    @operation_for_version("devel")
    def unsubscribe(person, unsubscribed_by):
        """Unsubscribe `person` from the question.

        :param person: the subscriber.
        :param unsubscribed_by: the person who removed the subscription.
        """

    def getDirectSubscribers():
        """Return the persons who are subscribed to this question.

        :return: A list of persons sorted by displayname.
        """

    def getDirectSubscribersWithDetails():
        """Get direct subscribers and their subscriptions for the question.

        :returns: A ResultSet of tuples (Person, QuestionSubscription)
            representing a subscriber and their question subscription.
        """

    def getIndirectSubscribers():
        """Return the persons who are implicitly subscribed to this question.

        :return: A list of persons sorted by displayname.
        """

    def getRecipients():
        """Return the set of person to notify about changes in this question.

        That is the union of getDirectSubscribers() and
        getIndirectSubscribers().

        :return: An `INotificationRecipientSet` containing the persons to
            notify along the rationale for doing so.
        """

    direct_recipients = Attribute(
        "Return An `INotificationRecipientSet` containing the persons to "
        "notify along the rationale for doing so.")

    indirect_recipients = Attribute(
        "Return the INotificationRecipientSet of answer contacts for the "
        "question's target as well as the question's assignee.")

    @operation_parameters(comment_number=Int(
        title=_('The number of the comment in the list of messages.'),
        required=True),
                          visible=Bool(title=_('Show this comment?'),
                                       required=True))
    @call_with(user=REQUEST_USER)
    @export_write_operation()
    @operation_for_version('devel')
    def setCommentVisibility(user, comment_number, visible):
        """Set the visible attribute on a question message.
Exemplo n.º 26
0
class IDistroSeriesPublic(ISeriesMixin, IHasAppointedDriver, IHasOwner,
                          IBugTarget, ISpecificationGoal, IHasMilestones,
                          IHasOfficialBugTags, IHasBuildRecords,
                          IHasTranslationImports, IHasTranslationTemplates,
                          IServiceUsage, IHasExpirableBugs):
    """Public IDistroSeries properties."""

    id = Attribute("The distroseries's unique number.")
    name = exported(
        DistroSeriesNameField(title=_("Name"),
                              required=True,
                              description=_("The name of this series."),
                              constraint=name_validator))
    display_name = exported(TextLine(title=_("Display name"),
                                     required=True,
                                     description=_("The series displayname.")),
                            exported_as="displayname")
    displayname = Attribute("Display name (deprecated)")
    fullseriesname = exported(
        TextLine(title=_("Series full name"),
                 required=False,
                 description=_("The series full name, e.g. Ubuntu Warty")))
    title = exported(
        Title(title=_("Title"),
              required=True,
              description=_(
                  "The title of this series. It should be distinctive "
                  "and designed to look good at the top of a page.")))
    description = exported(
        Description(title=_("Description"),
                    required=True,
                    description=_(
                        "A detailed description of this series, with "
                        "information on the architectures covered, the "
                        "availability of security updates and any other "
                        "relevant information.")))
    version = exported(
        DistroSeriesVersionField(
            title=_("Version"),
            required=True,
            description=_("The version string for this series.")))
    distribution = exported(
        Reference(
            Interface,  # Really IDistribution, see circular import fix below.
            title=_("Distribution"),
            required=True,
            description=_("The distribution for which this is a series.")))
    distributionID = Attribute('The distribution ID.')
    named_version = Attribute('The combined display name and version.')
    parent = Attribute('The structural parent of this series - the distro')
    components = Attribute("The series components.")
    # IComponent is not exported on the api.
    component_names = exported(
        List(value_type=TextLine(),
             title=_(u'The series component names'),
             readonly=True))
    upload_components = Attribute("The series components that can be "
                                  "uploaded to.")
    suite_names = exported(
        List(value_type=TextLine(),
             title=_(u'The series pocket names'),
             readonly=True))
    sections = Attribute("The series sections.")
    status = exported(
        Choice(title=_("Status"), required=True, vocabulary=SeriesStatus))
    datereleased = exported(Datetime(title=_("Date released")))
    previous_series = exported(
        ReferenceChoice(
            title=_("Parent series"),
            description=_("The series from which this one was branched."),
            required=True,
            schema=Interface,  # Really IDistroSeries
            vocabulary='DistroSeries'),
        ("devel", dict(exported_as="previous_series")),
        ("1.0", dict(exported_as="parent_series")),
        ("beta", dict(exported_as="parent_series")),
        readonly=True)
    registrant = exported(
        PublicPersonChoice(title=_("Registrant"),
                           vocabulary='ValidPersonOrTeam'))
    owner = exported(
        Reference(
            IPerson,
            title=_("Owning team of the derived series"),
            readonly=True,
            description=_(
                "This attribute mirrors the owner of the distribution.")))
    date_created = exported(
        Datetime(title=_("The date this series was registered.")))
    driver = exported(
        ReferenceChoice(
            title=_("Driver"),
            description=_(
                "The person or team responsible for decisions about features "
                "and bugs that will be targeted to this series of the "
                "distribution."),
            required=False,
            vocabulary='ValidPersonOrTeam',
            schema=IPerson))
    changeslist = exported(
        TextLine(title=_("Email changes to"),
                 required=True,
                 description=_("The mailing list or other email address that "
                               "Launchpad should notify about new uploads."),
                 constraint=email_validator))
    sourcecount = Attribute("Source Packages Counter")
    defer_translation_imports = Bool(
        title=_("Defer translation imports"),
        description=_("Suspends any translation imports for this series"),
        default=True,
        required=True,
    )
    binarycount = Attribute("Binary Packages Counter")

    architecturecount = Attribute("The number of architectures in this "
                                  "series.")
    nominatedarchindep = exported(
        Reference(
            Interface,  # IDistroArchSeries.
            title=_("DistroArchSeries designed to build "
                    "architecture-independent packages whithin this "
                    "distroseries context."),
            default=None,
            required=False))
    messagecount = Attribute("The total number of translatable items in "
                             "this series.")
    distroserieslanguages = Attribute("The set of dr-languages in this "
                                      "series.")

    hide_all_translations = Bool(
        title=u'Hide translations for this release',
        required=True,
        description=(
            u"You may hide all translation for this distribution series so"
            " that only Launchpad administrators will be able to see them."
            " For example, you should hide these translations while they are"
            " being imported from a previous series so that translators"
            " will not be confused by imports that are in progress."),
        default=True)

    language_pack_base = Choice(title=_('Language pack base'),
                                required=False,
                                description=_('''
            Language pack with the export of all translations
            available for this distribution series when it was generated. The
            subsequent update exports will be generated based on this one.
            '''),
                                vocabulary='FilteredFullLanguagePack')

    language_pack_delta = Choice(title=_('Language pack update'),
                                 required=False,
                                 description=_('''
            Language pack with the export of all translation updates
            available for this distribution series since the language pack
            base was generated.
            '''),
                                 vocabulary='FilteredDeltaLanguagePack')

    language_pack_proposed = Choice(title=_('Proposed language pack update'),
                                    required=False,
                                    description=_('''
            Base or update language pack export that is being tested and
            proposed to be used as the new language pack base or
            language pack update for this distribution series.
            '''),
                                    vocabulary='FilteredLanguagePack')

    language_pack_full_export_requested = exported(
        Bool(title=_('Request a full language pack export'),
             required=True,
             description=_('''
            Whether next language pack generation will be a full export. This
            information is useful when update packs are too big and want to
            merge all those changes in the base pack.
            ''')))

    last_full_language_pack_exported = Object(
        title=_('Latest exported language pack with all translation files.'),
        required=False,
        readonly=True,
        schema=ILanguagePack)

    last_delta_language_pack_exported = Object(title=_(
        'Lastest exported language pack with updated translation files.'),
                                               required=False,
                                               readonly=True,
                                               schema=ILanguagePack)

    # related joins
    packagings = Attribute("All of the Packaging entries for this "
                           "distroseries.")
    specifications = Attribute("The specifications targeted to this "
                               "series.")

    language_packs = Attribute(
        "All language packs associated with this distribution series.")

    backports_not_automatic = Bool(
        title=_("Don't upgrade to backports automatically"),
        required=True,
        description=_("""
            Set NotAutomatic: yes and ButAutomaticUpgrades: yes in Release
            files generated for the backports pocket. This tells apt to
            automatically upgrade within backports, but not into it.
            """))

    include_long_descriptions = exported(
        Bool(title=_("Include long descriptions in Packages rather than in "
                     "Translation-en"),
             default=True,
             required=True,
             description=_("""
                If True, write long descriptions to the per-architecture
                Packages files; if False, write them to a Translation-en
                file common across architectures instead. Using a common
                file reduces the bandwidth footprint of enabling multiarch
                on clients, which requires downloading Packages files for
                multiple architectures.""")))

    index_compressors = exported(
        List(value_type=Choice(vocabulary=IndexCompressionType),
             title=_("Compression types to use for published index files"),
             required=True,
             description=_("""
            A list of compression types to use for published index files
            (Packages, Sources, etc.).""")))

    publish_by_hash = exported(
        Bool(title=_("Publish by-hash directories"),
             required=True,
             description=_("""
            Publish archive index files in by-hash directories so that apt
            can retrieve them based on their hash, avoiding race conditions
            between InRelease and other files during mirror updates.""")))

    advertise_by_hash = exported(
        Bool(title=_("Advertise by-hash directories"),
             required=True,
             description=_("""
            Advertise by-hash directories with a flag in the Release file so
            that apt uses them by default.  Only effective if
            publish_by_hash is also set.""")))

    strict_supported_component_dependencies = exported(Bool(
        title=_("Strict dependencies of supported components"),
        required=True,
        description=_("""
            If True, packages in supported components (main and restricted)
            may not build-depend on packages in unsupported components.  Do
            not rely on the name of this attribute, even for reading; it is
            currently subject to change.""")),
                                                       as_of="devel")

    inherit_overrides_from_parents = Bool(
        title=_("Inherit overrides from parents"),
        readonly=False,
        required=True)

    main_archive = exported(
        Reference(
            Interface,  # Really IArchive, see below for circular import fix.
            title=_('Distribution Main Archive')))

    supported = exported(
        Bool(title=_("Supported"),
             description=_(
                 "Whether or not this series is currently supported.")))

    def isUnstable():
        """Whether or not a distroseries is unstable.

        The distribution is "unstable" until it is released; after that
        point, all development on the Release pocket is stopped and
        development moves on to the other pockets.
        """

    def getLatestUploads():
        """Return the latest five source uploads for this DistroSeries.

        It returns a list containing up to five elements as
        IDistributionSourcePackageRelease instances
        """

    # DistroArchSeries lookup properties/methods.
    architectures = Attribute("All architectures in this series.")

    enabled_architectures = exported(
        doNotSnapshot(
            CollectionField(
                title=_("Enabled architectures"),
                description=_("All architectures in this series with the "
                              "'enabled' flag set."),
                value_type=Reference(schema=Interface),  # IDistroArchSeries
                readonly=True)),
        exported_as="architectures")

    virtualized_architectures = Attribute(
        "All architectures in this series where PPA is supported.")

    buildable_architectures = Attribute(
        "All architectures in this series with available chroot tarball.")

    def __getitem__(archtag):
        """Return the distroarchseries for this distroseries with the
        given architecturetag.
        """

    def __str__():
        """Return the name of the distroseries."""

    def getDistroArchSeriesByProcessor(processor):
        """Return the distroarchseries for this distroseries with the
        given architecturetag from a `IProcessor`.

        :param processor: An `IProcessor`
        :return: An `IDistroArchSeries` or None when none was found.
        """

    @operation_parameters(archtag=TextLine(title=_("The architecture tag"),
                                           required=True))
    @operation_returns_entry(Interface)
    @export_read_operation()
    def getDistroArchSeries(archtag):
        """Return the distroarchseries for this distroseries with the
        given architecturetag.
        """

    # End of DistroArchSeries lookup methods.

    def updateStatistics(ztm):
        """Update all the Rosetta stats for this distro series."""

    def updatePackageCount():
        """Update the binary and source package counts for this distro
        series."""

    @operation_parameters(name=TextLine(
        title=_("The name of the source package"), required=True))
    @operation_returns_entry(ISourcePackage)
    @export_read_operation()
    def getSourcePackage(name):
        """Return a source package in this distro series by name.

        The name given may be a string or an ISourcePackageName-providing
        object. The source package may not be published in the distro series.
        """

    def getTranslatableSourcePackages():
        """Return a list of Source packages in this distribution series
        that can be translated.
        """

    def getPrioritizedUnlinkedSourcePackages():
        """Return a list of package summaries that need packaging links.

        A summary is a dict of package (`ISourcePackage`), total_bugs,
        and total_messages (translatable messages).
        """

    def getPrioritizedPackagings():
        """Return a list of packagings that need more upstream information."""

    def getMostRecentlyLinkedPackagings():
        """Return a list of packagings that are the most recently linked.

        At most five packages are returned of those most recently linked to an
        upstream.
        """

    @operation_parameters(
        created_since_date=Datetime(
            title=_("Created Since Timestamp"),
            description=_(
                "Return items that are more recent than this timestamp."),
            required=False),
        status=Choice(
            vocabulary=PackageUploadStatus,
            title=_("Package Upload Status"),
            description=_("Return only items that have this status."),
            required=False),
        archive=Reference(
            # Really IArchive, patched in _schema_circular_imports.py
            schema=Interface,
            title=_("Archive"),
            description=_("Return only items for this archive."),
            required=False),
        pocket=Choice(
            vocabulary=PackagePublishingPocket,
            title=_("Pocket"),
            description=_("Return only items targeted to this pocket"),
            required=False),
        custom_type=Choice(vocabulary=PackageUploadCustomFormat,
                           title=_("Custom Type"),
                           description=_(
                               "Return only items with custom files of this "
                               "type."),
                           required=False),
        name=TextLine(title=_("Package or file name"), required=False),
        version=TextLine(title=_("Package version"), required=False),
        exact_match=Bool(title=_("Exact match"),
                         description=_(
                             "Whether to filter name and version by exact "
                             "matching."),
                         required=False),
    )
    # Really IPackageUpload, patched in _schema_circular_imports.py
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPackageUploads(status=None,
                          created_since_date=None,
                          archive=None,
                          pocket=None,
                          custom_type=None,
                          name=None,
                          version=None,
                          exact_match=False):
        """Get package upload records for this distribution series.

        :param status: Filter results by this `PackageUploadStatus`, or list
            of statuses.
        :param created_since_date: If specified, only returns items uploaded
            since the timestamp supplied.
        :param archive: Filter results for this `IArchive`.
        :param pocket: Filter results by this `PackagePublishingPocket` or a
            list of `PackagePublishingPocket`.
        :param custom_type: Filter results by this
            `PackageUploadCustomFormat`.
        :param name: Filter results by this file name or package name.
        :param version: Filter results by this version number string.
        :param exact_match: If True, look for exact string matches on the
            `name` and `version` filters.  If False, look for a substring
            match so that e.g. a package "kspreadsheetplusplus" would match
            the search string "spreadsheet".  Defaults to False.
        :return: A result set containing `IPackageUpload`.
        """

    def getUnlinkedTranslatableSourcePackages():
        """Return a list of source packages that can be translated in
        this distribution series but which lack Packaging links.
        """

    def getBinaryPackage(name):
        """Return a DistroSeriesBinaryPackage for this name.

        The name given may be an IBinaryPackageName or a string.  The
        binary package may not be published in the distro series.
        """

    def getCurrentSourceReleases(source_package_names):
        """Get the current release of a list of source packages.

        :param source_package_names: a list of `ISourcePackageName`
            instances.

        :return: a dict where the key is a `ISourcePackage`
            and the value is a `IDistributionSourcePackageRelease`.
        """

    def getPublishedSources(sourcepackage_or_name,
                            pocket=None,
                            version=None,
                            include_pending=False,
                            archive=None):
        """Return the SourcePackagePublishingHistory(s)

        Deprecated.  Use IArchive.getPublishedSources instead.

        Given a ISourcePackageName or name.

        If pocket is not specified, we look in all pockets.

        If version is not specified, return packages with any version.

        If 'include_pending' is True, we return also the pending publication
        records, those packages that will get published in the next publisher
        run (it's only useful when we need to know if a given package is
        known during a publisher run, mostly in pre-upload checks)

        If 'archive' is not specified consider publication in the
        main_archive, otherwise respect the given value.
        """

    def getAllPublishedSources():
        """Return all currently published sources for the distroseries.

        Return publications in the main archives only.
        """

    def getAllUncondemnedSources():
        """Return all uncondemned sources for the distroseries.

        An uncondemned publication is one without scheduleddeletiondate set.

        Return publications in the main archives only.
        """

    def getAllPublishedBinaries():
        """Return all currently published binaries for the distroseries.

        Return publications in the main archives only.
        """

    def getAllUncondemnedBinaries():
        """Return all uncondemned binaries for the distroseries.

        An uncondemned publication is one without scheduleddeletiondate set.

        Return publications in the main archives only.
        """

    def getDistroSeriesLanguage(language):
        """Return the DistroSeriesLanguage for this distroseries and the
        given language, or None if there's no DistroSeriesLanguage for this
        distribution and the given language.
        """

    def getDistroSeriesLanguageOrDummy(language):
        """Return the DistroSeriesLanguage for this distroseries and the
        given language, or a DummyDistroSeriesLanguage.
        """

    def createUploadedSourcePackageRelease(sourcepackagename,
                                           version,
                                           maintainer,
                                           builddepends,
                                           builddependsindep,
                                           architecturehintlist,
                                           component,
                                           creator,
                                           urgency,
                                           changelog,
                                           changelog_entry,
                                           dsc,
                                           dscsigningkey,
                                           section,
                                           dsc_maintainer_rfc822,
                                           dsc_standards_version,
                                           dsc_format,
                                           dsc_binaries,
                                           archive,
                                           copyright,
                                           build_conflicts,
                                           build_conflicts_indep,
                                           dateuploaded=None,
                                           source_package_recipe_build=None,
                                           user_defined_fields=None,
                                           homepage=None,
                                           buildinfo=None):
        """Create an uploads `SourcePackageRelease`.

        Set this distroseries set to be the uploadeddistroseries.

        All arguments are mandatory, they are extracted/built when
        processing and uploaded source package:

         :param dateuploaded: timestamp, if not provided will be UTC_NOW
         :param sourcepackagename: `ISourcePackageName`
         :param version: string, a debian valid version
         :param maintainer: IPerson designed as package maintainer
         :param creator: IPerson, package uploader
         :param component: IComponent
         :param section: ISection
         :param urgency: dbschema.SourcePackageUrgency
         :param dscsigningkey: IGPGKey used to sign the DSC file
         :param dsc: string, original content of the dsc file
         :param copyright: string, the original debian/copyright content
         :param changelog: LFA ID of the debian/changelog file in librarian
         :param changelog_entry: string, changelog extracted from the
                                 changesfile
         :param architecturehintlist: string, DSC architectures
         :param builddepends: string, DSC build dependencies
         :param builddependsindep: string, DSC architecture independent build
                                   dependencies.
         :param build_conflicts: string, DSC Build-Conflicts content
         :param build_conflicts_indep: string, DSC Build-Conflicts-Indep
                                       content
         :param dsc_maintainer_rfc822: string, DSC maintainer field
         :param dsc_standards_version: string, DSC standards version field
         :param dsc_format: string, DSC format version field
         :param dsc_binaries:  string, DSC binaries field
         :param archive: IArchive to where the upload was targeted
         :param dateuploaded: optional datetime, if omitted assumed nowUTC
         :param source_package_recipe_build: optional SourcePackageRecipeBuild
         :param user_defined_fields: optional sequence of key-value pairs with
                                     user defined fields.
         :param homepage: optional string with (unchecked) upstream homepage
                          URL
         :param buildinfo: optional LFA with build information file
         :return: the just creates `SourcePackageRelease`
        """

    def getComponentByName(name):
        """Get the named component.

        Raise NotFoundError if the component is not in the permitted component
        list for this distroseries.
        """

    def getSectionByName(name):
        """Get the named section.

        Raise NotFoundError if the section is not in the permitted section
        list for this distroseries.
        """

    def addSection(section):
        """SQLObject provided method to fill a related join key section."""

    def getBinaryPackagePublishing(archtag, pocket, component, archive):
        """Get BinaryPackagePublishings in a DistroSeries.

        Can optionally restrict the results by architecturetag, pocket and/or
        component.

        If archive is passed, restricted the results to the given archive,
        if it is suppressed the results will be restricted to the
        distribution 'main_archive'.
        """

    def getSourcePackagePublishing(pocket, component, archive):
        """Return a selectResult of ISourcePackagePublishingHistory.

        According status and pocket.
        If archive is passed, restricted the results to the given archive,
        if it is suppressed the results will be restricted to the
        distribution 'main_archive'.
        """

    def searchPackages(text):
        """Search through the packge cache for this distroseries and return
        DistroSeriesBinaryPackage objects that match the given text.
        """

    def createQueueEntry(pocket,
                         archive,
                         changesfilename=None,
                         changesfilecontent=None,
                         changes_file_alias=None,
                         signingkey=None,
                         package_copy_job=None):
        """Create a queue item attached to this distroseries.

        Create a new `PackageUpload` to the given pocket and archive.

        The default state is NEW.  Any further state changes go through
        the Queue state-machine.

        :param pocket: The `PackagePublishingPocket` to upload to.
        :param archive: The `Archive` to upload to.  Must be for the same
            `Distribution` as this series.
        :param changesfilename: Name for the upload's .changes file.  You may
            specify a changes file by passing both `changesfilename` and
            `changesfilecontent`, or by passing `changes_file_alias`.
        :param changesfilecontent: Text for the changes file.  It will be
            signed and stored in the Librarian.  Must be passed together with
            `changesfilename`; alternatively, you may provide a
            `changes_file_alias` to replace both of these.
        :param changes_file_alias: A `LibraryFileAlias` containing the
            .changes file.  Security warning: unless the file has already
            been checked, this may open us up to replay attacks as per bugs
            159304 and 451396.  Use `changes_file_alias` only if you know
            this can't happen.
        :param signingkey: `IGPGKey` used to sign the changes file, or None if
            it is unsigned.
        :return: A new `PackageUpload`.
        """

    def newArch(architecturetag, processor, official, owner, enabled=True):
        """Create a new port or DistroArchSeries for this DistroSeries."""

    def getPOFileContributorsByLanguage(language):
        """People who translated strings to the given language.

        The people that translated only IPOTemplate objects that are not
        current will not appear in the returned list.
        """

    def getSuite(pocket):
        """Return the suite for this distro series and the given pocket.

        :param pocket: A `DBItem` of `PackagePublishingPocket`.
        :return: A string.
        """

    def isSourcePackageFormatPermitted(format):
        """Check if the specified source format is allowed in this series.

        :param format: The SourcePackageFormat to check.
        """

    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getDerivedSeries():
        """Get all `DistroSeries` derived from this one."""

    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getParentSeries():
        """Get all parent `DistroSeries`."""

    @operation_parameters(
        parent_series=Reference(
            schema=Interface,  # IDistroSeries
            title=_("The parent series to consider."),
            required=False),
        difference_type=Choice(
            vocabulary=DistroSeriesDifferenceType,
            title=_("Only return differences of this type."),
            required=False),
        source_package_name_filter=TextLine(title=_(
            "Only return differences for packages matching this "
            "name."),
                                            required=False),
        status=Choice(vocabulary=DistroSeriesDifferenceStatus,
                      title=_("Only return differences of this status."),
                      required=False),
        child_version_higher=Bool(title=_(
            "Only return differences for which the child's version "
            "is higher than the parent's."),
                                  required=False),
    )
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    @operation_for_version('devel')
    def getDifferencesTo(parent_series, difference_type,
                         source_package_name_filter, status,
                         child_version_higher):
        """Return the differences between this series and the specified
        parent_series (or all the parent series if parent_series is None).

        :param parent_series: The parent series for which the differences
            should be returned. All parents are considered if this is None.
        :param difference_type: The type of the differences to return.
        :param source_package_name_filter: A package name to use as a filter
            for the differences.
        :param status: The status of the differences to return.
        :param child_version_higher: Only return differences for which the
            child's version is higher than the parent's version.
        """

    def isDerivedSeries():
        """Is this series a derived series?

        A derived series has one or more parent series.
        """

    def isInitializing():
        """Is this series initializing?"""

    def isInitialized():
        """Has this series been initialized?"""

    def getInitializationJob():
        """Get the last `IInitializeDistroSeriesJob` for this series.

        :return: `None` if no job is found or an `IInitializeDistroSeriesJob`.
        """

    @operation_parameters(
        since=Datetime(
            title=_("Minimum creation timestamp"),
            description=_("Ignore comments that are older than this."),
            required=False),
        source_package_name=TextLine(
            title=_("Name of source package"),
            description=_("Only return comments for this source package."),
            required=False))
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    @operation_for_version('devel')
    def getDifferenceComments(since=None, source_package_name=None):
        """Get `IDistroSeriesDifferenceComment` items.
Exemplo n.º 27
0
class IFieldExtender(Schema):
    field_widget = Choice(
        title=_(u'label_field_widget',
                default=u'Field Widget'),
        description=_(u'help_field_widget', default=u''),
        required=False,
        source=widgetsFactory,
    )
    fieldset(u'overrides', label=_('Overrides'),
             fields=['TDefault', 'TEnabled', 'TValidator', 'serverSide'])
    write_permission(TDefault=EDIT_TALES_PERMISSION)
    TDefault = TextLine(
        title=_(u'label_tdefault_text', default=u'Default Expression'),
        description=(_(u'help_tdefault_text', default=u''
                       u'A TALES expression that will be evaluated when the form is displayed '
                       u'to get the field default value. '
                       u'Leave empty if unneeded. Your expression should evaluate as a string. '
                       u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                       u'an error on form display.')),
        default=u'',
        constraint=isTALES,
        required=False,
    )
    write_permission(TEnabled=EDIT_TALES_PERMISSION)
    TEnabled = TextLine(
        title=_(u'label_tenabled_text', default=u'Enabling Expression'),
        description=(_(u'help_tenabled_text', default=u''
                       u'A TALES expression that will be evaluated when the form is displayed '
                       u'to determine whether or not the field is enabled. '
                       u'Your expression should evaluate as True if '
                       u'the field should be included in the form, False if it should be omitted. '
                       u'Leave this expression field empty if unneeded: the field will be included. '
                       u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                       u'an error on form display.')),
        default=u'',
        constraint=isTALES,
        required=False,
    )
    write_permission(TValidator=EDIT_TALES_PERMISSION)
    TValidator = TextLine(
        title=_(u'label_tvalidator_text', default=u'Custom Validator'),
        description=(_(u'help_tvalidator_text', default=u''
                       u'A TALES expression that will be evaluated when the form is validated. '
                       u'Validate against \'value\', which will contain the field input. '
                       u'Return False if valid; if not valid return a string error message. '
                       u'E.G., "python: test(value==\'eggs\', False, \'input must be eggs\')" will '
                       u'require "eggs" for input. '
                       u'PLEASE NOTE: errors in the evaluation of this expression will cause '
                       u'an error on form display.')),
        default=u'',
        constraint=isTALES,
        required=False,
    )
    write_permission(serverSide=EDIT_TALES_PERMISSION)
    serverSide = Bool(
        title=_(u'label_server_side_text', default=u'Server-Side Variable'),
        description=_(u'description_server_side_text', default=u''
                      u'Mark this field as a value to be injected into the '
                      u'request form for use by action adapters and is not '
                      u'modifiable by or exposed to the client.'),
        default=False,
        required=False,
    )
    validators = List(
        title=_('Validators'),
        description=_(
            u'help_userfield_validators',
            default=u'Select the validators to use on this field'),
        unique=True,
        required=False,
        value_type=Choice(
            vocabulary='collective.easyform.validators'),
    )
Exemplo n.º 28
0
class IFoo(Interface):
    bar = Bool(title=u'Bar')
Exemplo n.º 29
0
class INotificationSettings(IAttributeAnnotatable):
    """Mailer notification settings interface"""

    enable_notifications = Bool(
        title=_("Enable notifications?"),
        description=_("If 'no', mail notifications will be disabled"),
        required=True,
        default=False)

    mailer = Choice(
        title=_("Mailer utility"),
        description=_("Mail delivery utility used to send notifications"),
        required=False,
        vocabulary=MAILERS_VOCABULARY_NAME)

    @invariant
    def check_mailer(self):
        """Check mailer to enable notifications"""
        if self.enable_notifications and not self.mailer:
            raise Invalid(
                _("Notifications can't be enabled without mailer utility"))

    def get_mailer(self):
        """Return mailer utility"""

    service_name = TextLine(
        title=_("Service name"),
        description=_("Name of service as defined in registration mail "
                      "subject"),
        required=True)

    service_owner = TextLine(
        title=_("Service owner"),
        description=_("Name of the entity providing this service, which "
                      "will be visible in notifications messages"),
        required=True)

    sender_name = TextLine(
        title=_("Sender name"),
        description=_("Visible name of registration mail sender"),
        required=True)

    sender_email = TextLine(
        title=_("Sender email"),
        description=_("Email address of registration mail sender"),
        required=True)

    subject_prefix = TextLine(
        title=_("Subject prefix"),
        description=_("This prefix will be inserted into subject prefix of "
                      "each notification message"),
        required=False)

    confirmation_template = I18nHTMLField(
        title=_("Confirmation template"),
        description=
        _("This template will be used instead of default template to send "
          "notification when a user is registered by a system administrator; you can "
          "use some user properties into the message body, like: {login}, {email}, "
          "{firstname}, {lastname}, {title} or {company_name}; message activation "
          "link and footer are added automatically"),
        required=False)

    registration_template = I18nHTMLField(
        title=_("Registration template"),
        description=
        _("This template will be used instead of default template to send "
          "notificaiton when a user is auto-registered; you can use some user "
          "properties into the message body, like: {login}, {email}, {firstname}, "
          "{lastname}, {title} or {company_name}; message activation link and footer "
          "are added automatically"),
        required=False)

    signature = Text(title=_("Email signature"),
                     description=_("Text displayed in email footer"),
                     required=False)
Exemplo n.º 30
0
class IPhysicalMedia(Interface):
    """A PhysicalMedia object."""

    capacity = PhysicalQuantity(
        title=_(u'Capacity'),
        description=_(
            u"The number of bytes that can be read from or written to a Media."
        ),
        required=False)

    cleanerMedia = Bool(
        title=_(u'Cleaner media'),
        description=
        _(u"Indicating that the PhysicalMedia is used for cleaning purposes and not data storage."
          ),
        required=False)

    dualSided = Bool(
        title=_(u'Dual sided'),
        description=
        _(u"Indicating that the Media has two recording sides (TRUE) or only a single side (FALSE)."
          ),
        required=False)

    maxMounts = Int(
        title=_(u'Max mounts'),
        description=
        _(u"For removable Media, the maximum number of times that the Media can be mounted before it should be retired. For cleaner Media, this is the maximum number of Drive cleans that can be performed. For nonremovable Media, such as hard disks, this property is not applicable and should be set to 0."
          ),
        required=False)

    mediaSize = Float(title=_(u'Media size'),
                      description=_(u"Size of the Media in inches."),
                      required=False)

    mediaType = Choice(
        title=_(u'Media Type'),
        description=_(u"Specifies the type of the PhysicalMedia."),
        required=False,
        vocabulary="PhysicalMediaMediaTypes")

    timeOfLastMount = Datetime(
        title=_(u'Time of last mount'),
        description=
        _(u"For removable or cleaner Media, the date and time that the Media was last mounted. For nonremovable Media, such as hard disks, this property has no meaning and is not applicable."
          ),
        required=False)

    writeProtectOn = Bool(
        title=_(u'Write protect on'),
        description=
        _(u"Specifying whether the Media is currently write protected by some kind of physical mechanism, such as a protect tab on a floppy diskette."
          ),
        required=False)

    labelFormat = Choice(
        title=_(u'Label Format'),
        description=_(
            u"The formats of each of the labels on a PhysicalMedia."),
        required=False,
        vocabulary="PhysicalMediaLabelFormats")

    device = Choice(title=_(u'Device'),
                    vocabulary='AllDevices',
                    required=False)

    @invariant
    def ensureCapacityUnit(physicalMedia):
        if physicalMedia.capacity is not None:
            physicalInput = convertQuantity(physicalMedia.capacity)
            if not physicalInput.isBitUnit():
                raise Invalid(
                    "No capacity specification: '%s'." % \
                    (physicalMedia.capacity))

    def trigger_online():
        """
Exemplo n.º 31
0
class IBugTracker(Interface):
    """A remote bug system.

    Launchpadlib example: What bug tracker is used for a distro source
    package?

    ::

        product = source_package.upstream_product
        if product:
            tracker = product.bug_tracker
            if not tracker:
                project = product.project_group
                if project:
                    tracker = project.bug_tracker
        if tracker:
            print "%s at %s" %(tracker.bug_tracker_type, tracker.base_url)

    """
    export_as_webservice_entry()

    id = Int(title=_('ID'))
    bugtrackertype = exported(
        Choice(title=_('Bug Tracker Type'),
               vocabulary=BugTrackerType,
               default=BugTrackerType.BUGZILLA),
        exported_as='bug_tracker_type')
    name = exported(
        BugTrackerNameField(
            title=_('Name'),
            constraint=name_validator,
            description=_('A URL-friendly name for the bug tracker, '
                          'such as "mozilla-bugs".')))
    title = exported(
        TextLine(
            title=_('Title'),
            description=_('A descriptive label for this tracker to show '
                          'in listings.')))
    summary = exported(
        Text(
            title=_('Summary'),
            description=_(
                'A brief introduction or overview of this bug '
                'tracker instance.'),
            required=False))
    baseurl = exported(
        BugTrackerURL(
            title=_('Location'),
            allowed_schemes=LOCATION_SCHEMES_ALLOWED,
            description=_(
                'The top-level URL for the bug tracker, or an upstream email '
                'address. This must be accurate so that Launchpad can link '
                'to external bug reports.')),
        exported_as='base_url')
    aliases = exported(
        List(
            title=_('Location aliases'),
            description=_(
                'A list of URLs or email addresses that all lead to the '
                'same bug tracker, or commonly seen typos, separated by '
                'whitespace.'),
            value_type=BugTrackerURL(
                allowed_schemes=LOCATION_SCHEMES_ALLOWED),
            required=False),
        exported_as='base_url_aliases')
    owner = exported(
        Reference(title=_('Owner'), schema=Interface),
        exported_as='registrant')
    contactdetails = exported(
        Text(
            title=_('Contact details'),
            description=_(
                'The contact details for the external bug tracker (so that, '
                'for example, its administrators can be contacted about a '
                'security breach).'),
            required=False),
        exported_as='contact_details')
    watches = doNotSnapshot(
        exported(
            CollectionField(
                title=_('The remote watches on this bug tracker.'),
                value_type=Reference(schema=IObject))))
    has_lp_plugin = exported(
        Bool(
            title=_('This bug tracker has a Launchpad plugin installed.'),
            required=False, default=False))
    products = Attribute('The products that use this bug tracker.')
    latestwatches = Attribute('The last 10 watches created.')
    imported_bug_messages = Attribute(
        'Bug messages that have been imported from this bug tracker.')
    multi_product = Attribute(
        "This bug tracker tracks multiple remote products.")
    active = exported(
        Bool(
            title=_('Updates for this bug tracker are enabled'),
            required=True, default=True))

    watches_ready_to_check = Attribute(
        "The set of bug watches that are scheduled to be checked.")
    watches_with_unpushed_comments = Attribute(
        "The set of bug watches that have unpushed comments.")
    watches_needing_update = Attribute(
        "The set of bug watches that need updating.")

    def getBugFilingAndSearchLinks(remote_product, summary=None,
                                   description=None, remote_component=None):
        """Return the bug filing and search links for the tracker.

        :param remote_product: The name of the product on which the bug
            is to be filed or searched for.
        :param summary: The string with which to pre-filly the summary
            field of the upstream bug tracker's search and bug filing forms.
        :param description: The string with which to pre-filly the description
            field of the upstream bug tracker's bug filing form.
        :param remote_component: The name of the component on which the bug
            is to be filed or search for.
        :return: A dict of the absolute URL of the bug filing form and
            the search form for `remote_product` on the remote tracker,
            in the form {'bug_filing_url': foo, 'search_url': bar}. If
            either or both of the URLs is unavailable for the current
            BugTrackerType the relevant values in the dict will be set
            to None. If the bug tracker requires a `remote_product` but
            None is passed, None will be returned for both values in the
            dict.
        """

    def getBugsWatching(remotebug):
        """Get the bugs watching the given remote bug in this bug tracker."""

    def getLinkedPersonByName(name):
        """Return the `IBugTrackerPerson` for a given name on a bugtracker.

        :param name: The name of the person on the bugtracker in
            `bugtracker`.
        :return: an `IBugTrackerPerson`.
        """

    def linkPersonToSelf(name, person):
        """Link a Person to the BugTracker using a given name.

        :param name: The name used for person on bugtracker.
        :param person: The `IPerson` to link to bugtracker.
        :raise BugTrackerPersonAlreadyExists: If `name` has already been
            used to link a person to `bugtracker`.
        :return: An `IBugTrackerPerson`.
        """

    def ensurePersonForSelf(
        display_name, email, rationale, creation_comment):
        """Return the correct `IPerson` for a given name on a bugtracker.

        :param bugtracker: The `IBugTracker` for which we should have a
            given Person.
        :param display_name: The name of the Person on `bugtracker`.
        :param email: The Person's email address if available. If `email`
            is supplied a Person will be created or retrieved using that
            email address and no `IBugTrackerPerson` records will be created.
        :param rationale: The `PersonCreationRationale` used to create a
            new `IPerson` for this `name` and `bugtracker`, if necessary.
        :param creation_comment: The creation comment for the `IPerson`
            if one is created.
         """

    def destroySelf():
        """Delete this bug tracker."""

    def resetWatches(new_next_check=None):
        """Reset the next_check times of this BugTracker's `BugWatch`es.

        :param new_next_check: If specified, contains the datetime to
            which to set the BugWatches' next_check times.  If not
            specified, the watches' next_check times will be set to a
            point between now and 24 hours hence.
        """

    @operation_parameters(
        component_group_name=TextLine(
            title=u"The name of the remote component group", required=True))
    @operation_returns_entry(Interface)
    @export_write_operation()
    def addRemoteComponentGroup(component_group_name):
        """Adds a new component group to the bug tracker"""

    @export_read_operation()
    @operation_returns_collection_of(Interface)
    def getAllRemoteComponentGroups():
        """Return collection of all component groups for this bug tracker"""

    @operation_parameters(
        component_group_name=TextLine(
            title=u"The name of the remote component group",
            required=True))
    @operation_returns_entry(Interface)
    @export_read_operation()
    def getRemoteComponentGroup(component_group_name):
        """Retrieve a given component group registered with the bug tracker.

        :param component_group_name: Name of the component group to retrieve.
        """

    @operation_parameters(
        distribution=TextLine(
            title=u"The distribution for the source package",
            required=True),
        sourcepackagename=TextLine(
            title=u"The source package name",
            required=True))
    @operation_returns_entry(Interface)
    @export_read_operation()
    @operation_for_version('devel')
    def getRemoteComponentForDistroSourcePackageName(
        distribution, sourcepackagename):
        """Returns the component linked to this source package, if any.

        If no components have been linked, returns value of None.
        """

    def getRelatedPillars(user=None):
        """Returns the `IProduct`s and `IProjectGroup`s that use this tracker.
Exemplo n.º 32
0
class ITestOptions(zope.interface.Interface):
    text_id = Text()
    int_id = Int()
    bool_id = Bool()
    float_id = Float()