예제 #1
0
class EmailContainerView(TableContainerView):

    template = ViewPageTemplateFile('templates/email_container.pt')
    delete_template = ViewPageTemplateFile('templates/email_delete.pt')
    index_title = _('Email Queue')

    @property
    def itemsToDelete(self):
        return sorted(super(EmailContainerView, self)._listItemsForDeletion(),
                      key=lambda obj: obj.time_created)

    def mailEnabled(self):
        return mail_enabled()

    def serverStatus(self):
        result = {}
        if self.context.hostname:
            info = '%s:%s' % (self.context.hostname, self.context.port or '25')
            result['status'] = _('Enabled on ${info}', mapping={'info': info})
            result['color'] = 'green'
        else:
            result['status'] = _('Disabled')
            result['color'] = 'red'
        return result

    def __call__(self):
        if 'RETRY' in self.request:
            utility = getUtility(IEmailUtility)
            for key in self.listIdsForDeletion():
                email = removeSecurityProxy(self.context[key])
                success = utility.send(email)
                if success:
                    del self.context[key]
        return super(EmailContainerView, self).__call__()
예제 #2
0
class TextLinesSortableWidget(textlines.TextLinesWidget):
    """ Widget for adding new keywords and autocomplete with the ones in the
    system.
    """
    zope.interface.implementsOnly(ITextLinesSortableWidget)
    klass = u"textlines-sortable-widget"
    configure_template = ViewPageTemplateFile(
        'textlines_sortable_configure.pt')
    display_template = ViewPageTemplateFile('textlines_sortable_display.pt')
    input_template = ViewPageTemplateFile('textlines_sortable_input.pt')

    def render(self):
        if self.mode == interfaces.DISPLAY_MODE:
            return self.display_template(self)
        elif self.mode == interfaces.INPUT_MODE:
            return self.input_template(self)
        else:  # configure mode
            return self.configure_template(self)

    def sort_results(self):
        uuids = self.context['uuids']
        if uuids:
            return [{'obj': uuidToObject(x), 'uuid': x} for x in uuids]
        else:
            return []

    def thumbnail(self, item):
        scales = item.restrictedTraverse('@@images')
        try:
            return scales.scale('image', 'tile')
        except:
            return None
예제 #3
0
class EnhancedTextLinesWidget(textarea.TextAreaWidget):
    """Widget for adding new keywords and autocomplete with the ones in the
    system.
    """
    implementsOnly(IEnhancedTextLinesWidget)
    klass = u'keyword-widget'
    display_template = ViewPageTemplateFile('enhancedtextlines_display.pt')
    input_template = ViewPageTemplateFile('enhancedtextlines_input.pt')

    def js(self):
        add = _(u'Add')
        add_option = _(u'Add Option')
        delete_option = _(u'Delete Option')
        edit_option = _(u'Edit Option')
        return JS_TEMPLATE.format(
            id=self.id,
            add=add,
            add_task=add_option,
            delete_task=delete_option,
            edit_task=edit_option,
        )

    def render(self):
        if self.mode == DISPLAY_MODE:
            return self.display_template(self)
        else:
            return self.input_template(self)
예제 #4
0
class SchoolYearView(TableContainerView):
    """School Year view."""

    __used_for__ = ISchoolYear
    delete_template = ViewPageTemplateFile("templates/term-delete.pt")
    template = ViewPageTemplateFile("templates/schoolyear.pt")

    index_title = _("School Year")

    @property
    def sorted_terms(self):
        return sorted(self.context.values(), key=lambda t: t.last)

    @property
    def first(self):
        return self.context.first

    @property
    def last(self):
        return self.context.last

    def update(self):
        if 'CONFIRM' in self.request:
            for key in self.listIdsForDeletion():
                del self.context[key]
예제 #5
0
class DateTimeField(BaseField):
    """A field that store date-time formatted string"""
    implements(IDateTimeColumnField)

    edit_template = ViewPageTemplateFile('templates/datetime.pt')
    view_template = ViewPageTemplateFile('templates/string_view.pt')

    show_hm = True

    @classmethod
    def RealIndexIterator(csl):
        # Plone 3 compatibility
        return utils.RealIndexIterator(pos=0)

    def render_view(self, data, index=None, storage=None):
        self.data = data or ''
        if self.data:
            try:
                date = DateTime(self.data)
                ploneview = getMultiAdapter((self.context, self.request),
                                            name=u'plone')
                self.data = ploneview.toLocalizedTime(date,
                                                      long_format=self.show_hm)
            except DateTimeError:
                self.data = ''
        return self.view_template(data=self.data)
예제 #6
0
class RichField(BaseField):
    implements(IRichColumnField)

    edit_template = ViewPageTemplateFile('templates/rich.pt')
    view_template = ViewPageTemplateFile('templates/rich_view.pt')
    # we cache because we have portal_transforms but we can cache for a long time
    cache_time = 60 * 60 * 12  # 12 hours

    def __init__(self, context, request):
        BaseField.__init__(self, context, request)
        self.rows = 5
        self.widget = RichWidget(description='',
                                 label=_('Html'),
                                 filter_buttons=(
                                     'tablecontrols',
                                     'code',
                                     'fullscreen',
                                     'attribs',
                                 ),
                                 rows=25,
                                 allow_file_upload=False)

    def renderText(self, text):
        context = self.context
        transformer = getToolByName(context, 'portal_transforms')
        data = transformer.convertTo('text/x-html-safe',
                                     text,
                                     context=context,
                                     mimetype='text/html')
        return data.getData()
예제 #7
0
class SelectField(BaseField):
    implements(ISelectColumnField)

    edit_template = ViewPageTemplateFile('templates/select.pt')
    view_template = ViewPageTemplateFile('templates/string_view.pt')

    def vocabulary(self):
        """Vocabulary can be a static list of values, or a vocabulary:TAL espression"""
        raw_vocabulary = self.configuration.get('vocabulary')
        values = raw_vocabulary.rstrip().decode('utf-8').splitlines()
        talEngine = Expressions.getEngine()
        portal_state = getMultiAdapter((self.context, self.request),
                                       name=u'plone_portal_state')
        evals = {
            'portal': portal_state.portal(),
            'context': self.context,
            'request': self.request,
        }

        results = []
        for value in values:
            if value and value.startswith('vocabulary:'):
                tales = value[11:]
                try:
                    compiledExpr = talEngine.compile(tales)
                    result = compiledExpr(talEngine.getContext(evals))
                    results.extend(result)
                except CompilerError, e:
                    logger.error("Error compiling %s: %s" % (tales, e))
                    continue
                except Exception, e:
                    logger.error("Error evaluating %s: %s" % (tales, e))
                    continue
            else:
class ContentSearch(grok.View):
    """
    returns the html with the list of results and icons
    """
    grok.context(Interface)
    grok.name('content-search')
    grok.require('zope2.View')

    list_template = ViewPageTemplateFile(
        'contentchooser_templates/search_list.pt')
    tree_template = ViewPageTemplateFile(
        'contentchooser_templates/tree_template.pt')

    def update(self):
        self.query = self.request.get('q', None)
        self.tab = self.request.get('tab', None)
        b_size = int(self.request.get('b_size', 10))
        page = int(self.request.get('page', 0))
        strategy = SitemapNavtreeStrategy(self.context)

        uids = None
        result = self.search(self.query, uids=uids, page=page, b_size=b_size)
        self.has_next = result.next is not None
        self.nextpage = result.pagenumber
        result = [strategy.decoratorFactory({'item': node}) for node in result]
        self.level = 1
        self.children = result

    def render(self):
        return self.list_template(children=self.children, level=1)

    def search(self, query=None, page=0, b_size=10, uids=None):
        catalog = api.portal.get_tool('portal_catalog')
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ICoverSettings)
        searchable_types = settings.searchable_content_types

        # temporary we'll only list published elements
        catalog_query = {'sort_on': 'effective', 'sort_order': 'descending'}
        catalog_query['portal_type'] = searchable_types

        if query:
            catalog_query = {
                'SearchableText': u'{0}*'.format(safe_unicode(query))
            }

        # XXX: not implemented, this is needed?
        # if uids:
        #     catalog_query['UID'] = uids

        results = catalog(**catalog_query)
        results = Batch(results, size=b_size, start=(page * b_size), orphan=0)

        return results

    def getTermByBrain(self, brain, real_value=True):
        portal_tool = api.portal.get_tool('portal_url')
        self.portal_path = portal_tool.getPortalPath()
        value = brain.getPath()[len(self.portal_path):]
        return SimpleTerm(value, token=brain.getPath(), title=brain.Title)
예제 #9
0
class SelectPreviewWidget(select.SelectWidget):
    """ Widget for adding new keywords and autocomplete with the ones in the
    system.
    """
    zope.interface.implementsOnly(ISelectPreviewWidget)
    klass = u'keyword-widget'
    display_template = ViewPageTemplateFile('selectpreview_display.pt')
    input_template = ViewPageTemplateFile('selectpreview_input.pt')

    # JavaScript template
    js_template = """\
    (function($) {
        $().ready(function() {
        var layouts = %(layouts)s;
        $.fn.layoutpreview('#%(id)s', layouts);
        });
    })(jQuery);
    """

    def js(self):
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ICoverSettings)
        layouts = settings.layouts

        simple_layouts = {}
        for layout in layouts:
            simplyfied = []
            lay = json.loads(layouts[layout])

            self.simplify_layout(lay, simplyfied)
            simple_layouts[layout] = simplyfied

        return self.js_template % dict(id=self.id, layouts=json.dumps(simple_layouts))

    def render(self):
        if self.mode == interfaces.DISPLAY_MODE:
            return self.display_template(self)
        else:
            return self.input_template(self)

    def simplify_layout(self, layout, simple_layout=[]):
        for element in layout:
            item = {}
            if element['type'] == 'row':
                item['type'] = 'row'

            if element['type'] == 'group':
                item['type'] = 'group'
                item['size'] = element['data']['column-size']

            if element['type'] == 'tile':
                item['type'] = 'tile'
                item['tile-type'] = element['tile-type']

            if 'children' in element:
                item['children'] = []
                simple_layout.append(item)
                self.simplify_layout(element['children'], item['children'])
            else:
                simple_layout.append(item)
예제 #10
0
class FileField(BaseField):
    implements(IFileColumnField)

    portal_type = TYPE_TO_CREATE

    edit_template = ViewPageTemplateFile('templates/file.pt')
    view_template = ViewPageTemplateFile('templates/file_view.pt')
    cache_time = 60 * 60 # 2 hours

    def _get_obj_info(self, uuid):
        # for fields that need to refer to other contents
        info = super(FileField, self)._get_obj_info(uuid)
        if 'url' in info:
            url = info['url'].rstrip('/')
            if HAS_DEXTERITY and IDexterityContent.providedBy(info['object']):
                download_url = url + '/download'
            else:
                download_url = url + '/at_download/file'
            info['download_url'] = download_url

        return info

    def render_view(self, data, index=None, storage=None):
        self.data = data or ''
        if data:
            obj_info = self._get_obj_info(data)
            if obj_info:
                return self.view_template(**obj_info)
        return ''

    def can_add_file(self):
        member = getMultiAdapter((self.context, self.request), name=u'plone_portal_state').member()
        return member.has_permission(permissions[self.portal_type], self.attachment_storage)

    @property
    @memoize
    def attachment_storage(self):
        try:
            attachment_storage = self.context.getAttachmentStorage() or aq_parent(aq_inner(self.context))
            # just check permissions
            self.context.restrictedTraverse('/'.join(attachment_storage.getPhysicalPath()))
            return attachment_storage
        except Unauthorized:
            return None

    def attachments(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        files_in_storage = catalog(portal_type=self.portal_type,
                                   path={'query': '/'.join(self.attachment_storage.getPhysicalPath()),
                                         'depth': 1,
                                         },
                                   sort_on = 'getObjPositionInParent')
        if self.data:
            # we must handle the special case where the storage has been changed and
            # when editing we haven't the old file still there
            old = catalog(UID=self.data)
            if old and old[0].getPath() not in [a.getPath() for a in files_in_storage]:
                return old + files_in_storage
        return files_in_storage
예제 #11
0
class ListingView(ftw.tabbedview.browser.listing.ListingView):
    """ XXX OpenGever specific override of the ftw.tabbedview ListingView in
    order to fix batching by overriding the page template.
    """
    implements(IGeverTableSourceConfig)

    batching = ViewPageTemplateFile("batching.pt")
    template = ViewPageTemplateFile("generic.pt")
예제 #12
0
class Select2TagsInputWidget(textarea.TextAreaWidget):
    """Widget for select site tags"""
    zope.interface.implementsOnly(ITagsSelectWidget)
    klass = u'tags-token-input-widget'
    display_template = ViewPageTemplateFile('select2_user_display.pt')
    input_template = ViewPageTemplateFile('select2_user_input.pt')

    # JavaScript template
    js_template = u"""\
    (function($) {
        $().ready(function() {
            $('#'+'%(id)s').select2({
                tags: [],
                tokenSeparators: [","],
                minimumInputLength: 1,
                ajax: {
                    url: portal_url + '/getVocabulary?name=plone.app.vocabularies.Keywords&field=subjects',
                    data: function (term, page) {
                        return {
                            query: term,
                            page: page, // page number
                        };
                    },
                    results: function (data, page) {
                        console.log(data);
                        return data;
                    },
                },
                initSelection: function(element, callback) {
                    var data = [];
                    $(element.val().split(",")).each(function () {
                        data.push({id: this, text: this});
                    });
                    callback(data);
                },
                // Allow manually entered text in drop down.
                createSearchChoice:function(term, data) {
                    if ( $(data).filter( function() {
                            return this.text.localeCompare(term)===0;
                        }).length===0) {
                        return {id:term, text:term};
                    }
                }
            });
        });
    })(jQuery);
    """

    def js(self):
        return self.js_template % dict(id=self.id)

    def render(self):
        if self.mode == interfaces.DISPLAY_MODE:
            return self.display_template(self)
        else:
            return self.input_template(self)
예제 #13
0
class FlourishSpecialDayView(flourish.page.Page, SpecialDayView):
    select_template = ViewPageTemplateFile('templates/f_specialday_select.pt')
    form_template = ViewPageTemplateFile('templates/f_specialday_change.pt')
    flourish_template = InheritTemplate(flourish.page.Page.template)

    field_error_message = _('Please correct the marked fields below.')

    def update(self):
        SpecialDayView.update(self)
        self.content_template = self.template
        self.template = self.flourish_template
예제 #14
0
class BaseCatalogListingTab(GeverTabMixin, CatalogListingView):
    """Base view for catalog listing tabs."""

    selection = ViewPageTemplateFile("selection_with_filters.pt")
    template = ViewPageTemplateFile("generic_with_filters.pt")

    columns = ()

    search_index = 'SearchableText'
    sort_on = 'modified'
    sort_order = 'reverse'
예제 #15
0
class FileField(BaseField):
    implements(IFileColumnField)

    edit_template = ViewPageTemplateFile('templates/file.pt')
    view_template = ViewPageTemplateFile('templates/file_view.pt')
    cache_time = 60 * 60  # 2 hours

    def render_view(self, data, index=None, storage=None):
        self.data = data or ''
        if data:
            obj_info = self._get_obj_info(data)
            if obj_info:
                return self.view_template(**obj_info)
        return ''

    def can_add_file(self):
        member = getMultiAdapter((self.context, self.request),
                                 name=u'plone_portal_state').member()
        return member.has_permission(permissions[TYPE_TO_CREATE],
                                     self.attachment_storage)

    @property
    @memoize
    def attachment_storage(self):
        try:
            attachment_storage = self.context.getAttachmentStorage(
            ) or aq_parent(aq_inner(self.context))
            # just check permissions
            self.context.restrictedTraverse('/'.join(
                attachment_storage.getPhysicalPath()))
            return attachment_storage
        except Unauthorized:
            return None

    def attachments(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        files_in_storage = catalog(
            portal_type='File',
            path={
                'query': '/'.join(self.attachment_storage.getPhysicalPath()),
                'depth': 1,
            },
            sort_on='getObjPositionInParent')
        if self.data:
            # we must handle the special case where the storage has been changed and
            # when editing we haven't the old file still there
            old = catalog(UID=self.data)
            if old and old[0].getPath() not in [
                    a.getPath() for a in files_in_storage
            ]:
                return old + files_in_storage
        return files_in_storage
예제 #16
0
class ContentSearch(BrowserView):
    """Returns the html with the list of results and icons."""

    list_template = ViewPageTemplateFile('templates/search_list.pt')
    tree_template = ViewPageTemplateFile('templates/tree_template.pt')

    def setup(self):
        self.query = self.request.get('q', None)
        self.tab = self.request.get('tab', None)
        page = int(self.request.get('page', 1))
        strategy = SitemapNavtreeStrategy(self.context)

        uuids = None
        result = self.search(self.query, uuids=uuids, page=page)
        self.has_next = result.next is not None
        self.nextpage = result.pagenumber + 1
        children = [
            strategy.decoratorFactory({'item': node}) for node in result
        ]
        self.level = 1
        self.children = children

    def search(self, query=None, page=1, b_size=ITEMS_BY_REQUEST, uuids=None):
        # XXX uuids parameter not used anywhere
        catalog = api.portal.get_tool('portal_catalog')
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ICoverSettings)
        searchable_types = settings.searchable_content_types

        # temporary we'll only list published elements
        catalog_query = {'sort_on': 'effective', 'sort_order': 'descending'}
        catalog_query['portal_type'] = searchable_types
        if query:
            catalog_query['Title'] = u'{0}*'.format(safe_unicode(query))
        results = catalog(**catalog_query)
        self.total_results = len(results)
        start = (page - 1) * b_size
        results = Batch(results, size=b_size, start=start, orphan=0)
        return results

    def getTermByBrain(self, brain, real_value=True):
        portal_tool = api.portal.get_tool('portal_url')
        self.portal_path = portal_tool.getPortalPath()
        value = brain.getPath()[len(self.portal_path):]
        return SimpleTerm(value, token=brain.getPath(), title=brain.Title)

    def render(self):
        return self.list_template()

    def __call__(self):
        self.setup()
        return self.render()
예제 #17
0
class KeywordsTokenInputWidget(textarea.TextAreaWidget):
    """Widget for adding new keywords and autocomplete with the ones in the
    system."""
    zope.interface.implementsOnly(ITokenInputWidget)
    klass = u'token-input-widget'
    display_template = ViewPageTemplateFile('token_input_display.pt')
    input_template = ViewPageTemplateFile('token_input_input.pt')

    # JavaScript template
    js_template = u"""\
    (function($) {
        $().ready(function() {
            var newValues = [%(newtags)s];
            var oldValues = [%(oldtags)s];
            $('#%(id)s').data('klass','%(klass)s');
            keywordTokenInputActivate('%(id)s', newValues, oldValues);
        });
    })(jQuery);
    """

    def js(self):
        values = self.context.portal_catalog.uniqueValuesFor('Subject')
        old_values = self.context.Subject()
        tags = u''
        old_tags = u''
        index = 0
        for index, value in enumerate(values):
            if isinstance(value, str):
                value = value.decode('utf-8')
            tags += u'{id: "%s", name: "%s"}' % (value.replace(
                u"'", u"\\'"), value.replace(u"'", u"\\'"))  # noqa
            if index < len(values) - 1:
                tags += ', '

        # prepopulate
        for index, value in enumerate(old_values):
            if isinstance(value, str):
                value = value.decode('utf-8')
            old_tags += u'{id: "%s", name: "%s"}' % (value.replace(
                u"'", u"\\'"), value.replace(u"'", u"\\'"))  # noqa
            if index < len(old_values) - 1:
                old_tags += ', '
        result = self.js_template % dict(
            id=self.id, klass=self.klass, newtags=tags, oldtags=old_tags)
        return result

    def render(self):
        if self.mode == interfaces.DISPLAY_MODE:
            return self.display_template(self)
        else:
            return self.input_template(self)
예제 #18
0
class LinkField(BaseField):
    implements(ILinkColumnField)

    edit_template = ViewPageTemplateFile('templates/link.pt')
    view_template = ViewPageTemplateFile('templates/link_view.pt')
    cache_time = 60 * 60  # 2 hours

    def __init__(self, context, request):
        BaseField.__init__(self, context, request)
        self.PLONE3 = PLONE3

    def portal_url(self):
        portal_state = getMultiAdapter((self.context, self.request),
                                       name=u'plone_portal_state')
        return portal_state.portal_url()

    def getStartupDirectory(self):
        """Startup directory in pure atreferencebrowser widget style"""
        storage = self.context.getAttachmentStorage() or self.context
        return storage.absolute_url()

    def render_view(self, data, index=None, storage=None):
        self.data = data or ''
        if self.data:
            if is_url(self.data):
                custom_prefs = self._getCustomPreferences()
                return self.view_template(external_url=self.data,
                                          **custom_prefs)
            # probably an uid
            uuid = self.data
            obj_info = self._get_obj_info(uuid)
            return self.view_template(**obj_info)
        return self.view_template(data=self.data)

    def render_edit(self, data):
        data = data or ''
        self.data = data.decode('utf-8')
        if not is_url(self.data):
            return self.edit_template(data=self.data)
        return self.edit_template(external_url=self.data)

    def getReferencedDocument(self):
        uuid = self.data
        if uuid:
            rcatalog = getToolByName(self.context, 'reference_catalog')
            obj = rcatalog.lookupObject(uuid)
            return obj and {
                'title': obj.Title().decode('utf-8'),
                'uuid': obj.UID()
            } or None
예제 #19
0
class Select2MAXUserInputWidget(textarea.TextAreaWidget):
    """Widget for select site users"""
    zope.interface.implementsOnly(IAjaxSelectWidget)
    klass = u'user-token-input-widget'
    display_template = ViewPageTemplateFile(
        'templates/select2_maxuser_display.pt')
    input_template = ViewPageTemplateFile('templates/select2_maxuser_input.pt')

    # JavaScript template
    js_template = u"""\
    (function($) {
        $().ready(function() {
            $('#'+'%(id)s').select2({
                tags: [],
                tokenSeparators: [","],
                minimumInputLength: 3,
                ajax: {
                    url: portal_url + '/max.ajaxusersearch',
                    quietMillis: 700,
                    data: function (term, page) {
                        return {
                            q: term,
                            page: page, // page number
                        };
                    },
                    results: function (data, page) {
                        return data;
                    },
                },
                initSelection: function(element, callback) {
                    var id=$(element).val();
                    $.ajax(portal_url + '/genweb.fromusername2displayname', {
                        data: {
                            q: id,
                        },
                    }).done(function(data) { callback(data); });
                },
            });
        });
    })(jQuery);
    """

    def js(self):
        return self.js_template % dict(id=self.id)

    def render(self):
        if self.mode == interfaces.DISPLAY_MODE:
            return self.display_template(self)
        else:
            return self.input_template(self)
예제 #20
0
    def testInitWithType(self):
        t = ViewPageTemplateFile('test.pt', content_type="text/plain")
        t._cook_check()
        self.assertEquals(t.content_type, "text/plain")

        t = ViewPageTemplateFile('testxml.pt', content_type="text/plain")
        t._cook_check()
        self.assertEquals(t.content_type, "text/xml")
예제 #21
0
    def testInitWithoutType(self):
        t = ViewPageTemplateFile('test.pt')
        t._cook_check()
        self.assertEqual(t.content_type, "text/html")

        t = ViewPageTemplateFile('testxml.pt')
        t._cook_check()
        self.assertEqual(t.content_type, "text/xml")
예제 #22
0
class ScheduleDeleteView(BrowserView):
    template = ViewPageTemplateFile('templates/confirm_schedule_delete.pt')

    @property
    def schedule(self):
        name = self.request.get('schedule')
        if name is None or name not in self.context:
            return None
        return self.context[name]

    def nextURL(self):
        return absoluteURL(self.context, self.request)

    def __call__(self):
        schedule = self.schedule
        if schedule is not None:
            if 'CONFIRM' in self.request:
                del self.context[schedule.__name__]
                self.request.response.redirect(self.nextURL())
            elif 'CANCEL' in self.request:
                self.request.response.redirect(self.nextURL())
            else:
                return self.template()
        else:
            self.request.response.redirect(self.nextURL())
예제 #23
0
class ScheduleContainerView(BrowserView):
    template = ViewPageTemplateFile('templates/schedule_container_view.pt')

    @property
    def owner(self):
        return IHaveSchedule(self.context)

    @property
    def term(self):
        return ITerm(self.owner, None)

    @property
    def school_year(self):
        term = self.term
        if term is None:
            return None
        return ISchoolYear(term, None)

    def schedules(self):
        for name, schedule in list(self.context.items()):
            if schedule.timetable.__parent__ is not None:
                yield schedule
            else:
                # Remove stray schedule (LP: #1280528)
                del self.context[name]

    def timetables(self):
        snippets = filter(None, [
            queryMultiAdapter((schedule, self.request), name='schedule_table')
            for schedule in self.schedules()
        ])
        return snippets

    def __call__(self):
        return self.template()
예제 #24
0
class RequestReportDownloadDialog(DialogForm, z3c.form.form.EditForm):

    template = ViewPageTemplateFile('templates/f_request_report_download.pt')

    dialog_submit_actions = ('download',)
    dialog_close_actions = ('cancel',)
    label = None

    @button.buttonAndHandler(_("Download"), name='download')
    def handleDownload(self, action):
        self.request.response.redirect(self.nextURL())
        # We never have errors, so just close the dialog.
        self.ajax_settings['dialog'] = 'close'

    @button.buttonAndHandler(_("Cancel"))
    def handle_cancel_action(self, action):
        pass

    def updateActions(self):
        super(RequestReportDownloadDialog, self).updateActions()
        self.actions['download'].addClass('button-ok')
        self.actions['cancel'].addClass('button-cancel')

    def nextURL(self):
        raise NotImplementedError("nextURL must redirect to a 'downloadable' view")

    @property
    def file_type(self):
        if 'file_type' in self.request:
            return unquote_plus(self.request['file_type'])

    @property
    def description(self):
        if 'description' in self.request:
            return unquote_plus(self.request['description'])
예제 #25
0
class Members(MemberListingTab):

    selection = ViewPageTemplateFile("templates/no_selection.pt")
    sort_on = 'lastname'

    enabled_actions = []
    major_actions = []
예제 #26
0
class ReportReferenceView(BrowserView):

    template = ViewPageTemplateFile('templates/report_reference.pt')

    def __call__(self):
        return self.template()

    def rows(self):
        collator = ICollator(self.request.locale)
        utility = getReportRegistrationUtility()
        app = self.context

        rows = []
        for group_key, group_reports in utility.reports_by_group.items():
            reference_url = reportLinksURL(app, self.request, name=group_key)
            for report in group_reports:
                row = {
                    'url': reference_url,
                    'group': report['group'],
                    'title': report['title'],
                    'description': report['description'],
                }
                rows.append([
                    collator.key(report['group']),
                    collator.key(report['title']), row
                ])

        return [row for group, title, row in sorted(rows)]
예제 #27
0
class TileList(BrowserView):

    """Helper browser view to create a list of tiles."""

    index = ViewPageTemplateFile('templates/tilelist.pt')

    def setup(self):
        self.context = aq_inner(self.context)
        vocab_name = 'collective.cover.AvailableTiles'
        available_tiles = queryUtility(IVocabularyFactory, vocab_name)
        # the view is expecting a dictionary of "tile types"
        self.tiles = [{'tile_type': name.value}
                      for name in available_tiles(self.context)]

    def get_tile_metadata(self, tile_name):
        tile_type = getUtility(ITileType, tile_name)
        tile = self.context.restrictedTraverse(str(tile_name))
        title = tile.short_name
        if not title:
            title = tile_type.title
        tile_metadata = {
            'icon': tile_type.icon,
            'description': tile_type.description,
            'title': title,
            'is_configurable': tile.is_configurable and 1 or 0
        }

        return tile_metadata

    def __call__(self):
        self.setup()
        return self.index()
예제 #28
0
class TypesListing(crud.CrudForm):
    """ The combined content type edit + add forms.
    """
    @lazy_property
    def description(self):
        if self.get_items():
            return _(u'The following custom content types are available for '
                     u'your site.')
        else:
            return _('help_addcontenttype_button', default=HELP)

    template = ViewPageTemplateFile('types_listing.pt')
    view_schema = field.Fields(ITypeSettings).select('title', 'description')
    view_schema += field.Fields(ITypeStats)
    addform_factory = crud.NullForm
    editform_factory = TypeEditForm

    def get_items(self):
        """Look up all Dexterity FTIs via the component registry.

        (These utilities are created via an IObjectCreated handler for the
        DexterityFTI class, configured in plone.dexterity.)
        """
        ftis = getAllUtilitiesRegisteredFor(IDexterityFTI)
        return [(fti.__name__, fti) for fti in ftis]

    def remove(self, (id, item)):
        """ Remove a content type.
        """
        ttool = getToolByName(self.context, 'portal_types')
        ttool.manage_delObjects([id])
예제 #29
0
class SchoolYearContainerView(TableContainerView, SchoolYearContainerBaseView):
    """SchoolYear container view."""

    __used_for__ = ISchoolYearContainer
    template = ViewPageTemplateFile("templates/schoolyear_container.pt")

    index_title = _("School Years")
    error = None

    @property
    def first(self):
        year = self.context.getActiveSchoolYear()
        if year is not None:
            return year.first

    @property
    def last(self):
        year = self.context.getActiveSchoolYear()
        if year is not None:
            return year.last

    def setUpTableFormatter(self, formatter):
        columns_before = []
        if self.canModify():
            columns_before = [
                table.DependableCheckboxColumn(prefix="delete",
                                               name='delete_checkbox',
                                               title=u'')
            ]
        columns_after = [
            table.DateColumn(title=_("Starts"), getter=lambda x, y: x.first),
            table.DateColumn(title=_("Ends"), getter=lambda x, y: x.last)
        ]
        formatter.setUp(formatters=[table.url_cell_formatter],
                        columns_before=columns_before,
                        columns_after=columns_after)

    def __call__(self):
        if 'DELETE' in self.request:
            if not self.deletingActiveSchoolYear():
                return self.delete_template()
            elif not self.canDeleteSchoolYears():
                self.error = _(
                    "You can not delete the active school year."
                    " Unless you are deleting all the school years.")
            else:
                return self.delete_template()

        self.setUpTableFormatter(self.table)
        return self.template()

    def nextURL(self):
        return absoluteURL(self.context, self.request)

    def update(self):
        if 'ACTIVATE_NEXT_SCHOOLYEAR' in self.request:
            for key in self.listIdsForDeletion():
                if key in self.context:
                    self.context.activateNextSchoolYear(key)
                    self.request.response.redirect(self.nextURL())
예제 #30
0
class NotificationSettingsForm(BrowserView):
    """Person notification settings form.

    Frontend functionality implemented in setting.js.
    """

    template = ViewPageTemplateFile('templates/settings.pt')

    def __call__(self):
        return self.template()

    def render_form_template(self):
        return prepare_handlebars_template(
            TEMPLATES_DIR.joinpath('settings-form.html'),
            translations=[
                _('label_activity', default=u'Activity'),
                _('label_badge', default=u'Badge'),
                _('label_mail', default=u'Mail'),
                _('label_daily_digest', default=u'Daily Digest'),
                _('btn_save', default=u'Save'),
                _('btn_cancel', default=u'Cancel'),
                _('btn_reset', default=u'Reset')
            ])

    def list_url(self):
        return '{}/notification-settings/list'.format(
            api.portal.get().absolute_url())

    def save_url(self):
        return '{}/notification-settings/save'.format(
            api.portal.get().absolute_url())

    def reset_url(self):
        return '{}/notification-settings/reset'.format(
            api.portal.get().absolute_url())
예제 #31
0
    def __call__(self):
        response = self.request.response
        title = self.context.Title()
        ftitle = "/tmp/%s_CV.pdf" % (title)
        filename = ftitle

        attachment = 'attachment; filename=%s' % (ftitle)
        f = file(filename, "wb")
        pdf_template = ViewPageTemplateFile('templates/pdf-view.pt')(self)

        response.setHeader('Content-Type', 'application/pdf')
        response.setHeader('Content-Disposition', attachment);
        pdf = pisa.CreatePDF(pdf_template.encode("UTF-8"), response)
        f.flush()
        f.close()

        if not pdf.err:
            return response
        else:
            # Something is wrong 
            # Fledge this out later
            pass
    def testInitWithoutType(self):
        t = ViewPageTemplateFile('test.pt')
        t._cook_check()
        self.assertEqual(t.content_type, "text/html")

        t = ViewPageTemplateFile('testxml.pt')
        t._cook_check()
        self.assertEqual(t.content_type, "text/xml")
예제 #33
0
 def __call__(self):
     self.request.response.setHeader("content-type", "application/pdf")
     rml_doc = ViewPageTemplateFile("print_survey.pt")(self)
     return parseString(rml_doc.encode("utf-8")).read()
예제 #34
0
 def __init__(self, *args, **kw):
     kw['_prefix'] = self.get_path_from_prefix(kw.get('prefix'))
     kw['content_type'] = 'text/html'
     File.__init__(self, *args, **kw)
 def __call__(self):
     self.request.response.setHeader('content-type', 'application/pdf')
     rml_doc = ViewPageTemplateFile('print_survey.pt')(self)
     return parseString(rml_doc.encode('utf-8')).read()
예제 #36
0
class TestViewZPT(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(TestViewZPT, self).setUp()
        self.t = ViewPageTemplateFile('test.pt')
        self.context = C1()

    def testNamespaceContextAvailable(self):
        context = self.context
        request = None

        namespace = self.t.pt_getContext(InstanceWithContext(context), request)
        self.failUnless(namespace['context'] is context)
        self.failUnless('views' in namespace)

    def testNamespaceHereNotAvailable(self):
        request = None
        self.assertRaises(AttributeError, self.t.pt_getContext,
                          InstanceWithoutContext(), request)

    def testViewMapper(self):
        the_view = "This is the view"
        the_view_name = "some view name"
        def ViewMaker(*args, **kw):
            return the_view

        from zope.publisher.interfaces import IRequest

        gsm = getGlobalSiteManager()
        gsm.registerAdapter(
            ViewMaker, (I1, IRequest), Interface, the_view_name, event=False)

        class MyRequest(object):
            implements(IRequest)

        request = MyRequest()

        namespace = self.t.pt_getContext(InstanceWithContext(self.context),
                                         request)
        views = namespace['views']
        self.failUnless(the_view is views[the_view_name])

    def test_debug_flags(self):
        from zope.publisher.browser import TestRequest
        self.request = TestRequest()
        self.request.debug.sourceAnnotations = False
        self.assert_('test.pt' not in self.t(self))
        self.request.debug.sourceAnnotations = True
        self.assert_('test.pt' in self.t(self))

        t = ViewPageTemplateFile('testsimpleviewclass.pt')
        self.request.debug.showTAL = False
        self.assert_('metal:' not in t(self))
        self.request.debug.showTAL = True
        self.assert_('metal:' in t(self))

    def test_render_sets_content_type_unless_set(self):
        from zope.publisher.browser import TestRequest
        t = ViewPageTemplateFile('test.pt')

        self.request = TestRequest()
        response = self.request.response
        self.assert_(not response.getHeader('Content-Type'))
        t(self)
        self.assertEquals(response.getHeader('Content-Type'), 'text/html')

        self.request = TestRequest()
        response = self.request.response
        response.setHeader('Content-Type', 'application/x-test-junk')
        t(self)
        self.assertEquals(response.getHeader('Content-Type'),
                          'application/x-test-junk')
예제 #37
0
 def setUp(self):
     super(TestViewZPT, self).setUp()
     self.t = ViewPageTemplateFile('test.pt')
     self.context = C1()