示例#1
0
class JsonView(grok.View):
    """Generic base class for JSON views.

    This class does two things:

    1. it renders the result as JSON
    2. if a request has a body it will try to JSON-parse it and
       store the result as ``self.input``.

    """
    martian.baseclass()
    grok.layer(IAPISkinLayer)

    input = None

    def render(self):
        # Workaround for grok silliness
        pass

    def do_OPTIONS(self):
        methods = [name[3:] for name in dir(self) if name.startswith('do_')]
        self.response.setHeader('Allow', ','.join(sorted(methods)))
        return None

    def __call__(self):
        input = self.request.stdin.getvalue()
        if input:
            try:
                self.input = json.loads(input)
            except ValueError:
                self.response.setHeader('Content-Type', 'application/json')
                return json.dumps({
                    'type': 'error',
                    'message': 'Invalid JSON input'
                })

        mapply(self.update, (), self.request)
        if self.response.getStatus() in [302, 303]:
            return  # Shortcircuit on redirect, no need to render

        self.response.setHeader('Content-Type', 'application/json')
        method = self.request.get('REQUEST_METHOD', 'GET').upper()
        renderer = getattr(self, 'do_%s' % method, None)
        if renderer is None:
            log.info('Invalid HTTP method %s attempted for %s', method,
                     '/'.join(self.context.getPhysicalPath()))
            self.response.setStatus(405)
            response = {'type': 'error', 'message': 'HTTP method not allowed'}
        else:
            response = mapply(renderer, (), self.request)
        return json.dumps(response)
示例#2
0
class TemplateList(grok.View):
    """ Override of the default way of obtaining the TinyMCE template list """
    grok.context(Interface)
    grok.name('collective.tinymcetemplates.templatelist')
    grok.require('zope2.View')
    grok.layer(IGenwebLayer)

    def render(self):
        self.request.response.setHeader('Content-Type', 'text/javascript')
        registry = queryUtility(IRegistry)
        templates = []
        if registry is not None:
            templateDirectories = registry.get(
                'collective.tinymcetemplates.templateLocations', None)
            if templateDirectories:

                portal_catalog = api.portal.get_tool('portal_catalog')
                portal_path = '/'.join(api.portal.get().getPhysicalPath())
                paths = []
                for p in templateDirectories:
                    if p.startswith('/'):
                        p = p[1:]
                    paths.append('%s/%s' % (
                        portal_path,
                        p,
                    ))

                # Primer les de SCP i després les custom (templates)
                templatesSCP = portal_catalog.searchResults(
                    Language='',
                    path=paths[0],
                    object_provides=IDocument.__identifier__,
                    sort_on='getObjPositionInParent')

                # I després les custom (plantilles)
                templatesCustom = portal_catalog.searchResults(
                    Language='',
                    path=paths[1],
                    object_provides=IDocument.__identifier__,
                    sort_on='getObjPositionInParent')

                results = templatesSCP + templatesCustom

                for r in results:
                    templates.append([
                        r.Title,
                        '%s/genweb.get.dxdocument.text' % r.getURL(),
                        r.Description
                    ])

        return u'var tinyMCETemplateList = %s;' % json.dumps(templates)
示例#3
0
class newsCollectionView(grok.View):
    grok.context(IFolderish)
    grok.name('newscollection_view')
    grok.template("newscollectionview")
    grok.require('zope2.View')
    grok.layer(IGenwebTheme)

    def published_news_items(self):
        return self._data()

    @memoize
    def _data(self):

        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        state = ['published', 'intranet']
        results = catalog(portal_type=('News Item'),
                          review_state=state,
                          is_important=True,
                          sort_on="getObjPositionInParent")
        results = [a for a in results]
        results2 = catalog(portal_type=('News Item', 'Link'),
                           review_state=state,
                           is_important=False,
                           sort_on=('Date'),
                           sort_order='reverse')
        results3 = []
        #import ipdb;ipdb.set_trace()
        path_folder_news = self.all_news_link()
        for brain in results2:
            brain_url = brain.getURL()
            brain_type = brain.Type
            if brain_type == 'Link' and brain_url.startswith(
                    path_folder_news) or brain_type == 'News Item':
                results3.append(brain)
        return results + results3

    def all_news_link(self):
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request),
                                       name=u'plone_portal_state')
        self.portal = portal_state.portal()
        if self.have_news_folder:
            news = self.portal.noticies.getTranslation()
            return '%s' % news.absolute_url()
        else:
            return '%s/news_listing' % self.portal_url

    @memoize
    def have_news_folder(self):
        return 'news' in self.navigation_root_object.objectIds()
示例#4
0
class View(sectorcontainer.View):
    grok.context(sectorcontainer.ISectorContainer)
    grok.require("zope2.View")
    grok.layer(IOSHAContentSkinLayer)
    grok.template("sectorcontainer_view")
    grok.name("nuplone-view")

    def update(self):
        self.countries = summarizeCountries(aq_inner(self.context),
                                            self.request)
        library = get_library(self.context)
        self.library_info = [
            dict(title=lib['title'], url=lib['url']) for lib in library
        ]
示例#5
0
class ReservationRevocationForm(ReservationTargetForm, ReservationListView,
                                ReservationUrls):

    permission = 'seantis.reservation.ApproveReservations'

    grok.name('revoke-reservation')
    grok.require(permission)
    grok.layer(ISeantisReservationSpecific)

    destructive_buttons = ('revoke', )
    standalone_buttons = ('cancel', )

    fields = field.Fields(IRevokeReservation)
    template = ViewPageTemplateFile('templates/revoke_reservation.pt')

    label = _(u'Revoke reservation')

    show_links = False

    @property
    def hint(self):
        if not self.has_reservations:
            return _(u'No such reservation')

        return _(u'Do you really want to revoke the following reservations?')

    @property
    def has_reservations(self):
        return self.approved_reservations() and True or False

    @button.buttonAndHandler(_(u'Revoke'))
    @extract_action_data
    def revoke(self, data):

        # might happen if the user submits twice
        if not self.has_reservations:
            return

        def revoke():
            self.scheduler.revoke_reservation(token=data['token'],
                                              reason=data['reason'],
                                              id=data.get('id'),
                                              send_email=data['send_email'])
            self.flash(_(u'Reservation revoked'))

        utils.handle_action(action=revoke, success=self.redirect_to_context)

    @button.buttonAndHandler(_(u'Cancel'))
    def cancel(self, action):
        self.redirect_to_context()
示例#6
0
class OrganisationSubmittedSiteOwnerMailTemplate(MailTemplateBase):
    """ """
    grok.name('mail_organisation_submitted_siteowner')
    grok.context(IOrganisation)
    grok.layer(IOSHAHWCContentLayer)
    grok.require('cmf.ReviewPortalContent')

    def render(self):
        self.subject = 'Profile submitted'
        self.template = grok.PageTemplateFile(
            'templates/mail_organisation_submitted_siteowner.pt')
        if not self.from_addr:
            raise KeyError('email_from_address')
        return self.template.render(self)
示例#7
0
class Problemes(grok.View):
    grok.name('problemes_list')
    grok.context(IServeiTIC)
    grok.layer(IGenwebServeisticLayer)
    grok.template('problemes')

    def js_retrieve(self):
        return """
    $(document).ready(function()
    {{
        var url = '{url}';
        retrieve_problemes(url, '');
    }});
       """.format(url="retrieve_problemes")
示例#8
0
class MediapartnerRejectedMailTemplate(MailTemplateBase):
    """ """
    grok.name('mail_mediapartner_rejected')
    grok.context(IMediaPartner)
    grok.layer(IOSHAHWCContentLayer)
    grok.require('cmf.ReviewPortalContent')

    def render(self):
        self.subject = 'Profile rejected'
        self.template = grok.PageTemplateFile(
            'templates/mail_mediapartner_rejected.pt')
        if not self.from_addr:
            raise KeyError('email_from_address')
        return self.template.render(self)
示例#9
0
class removeTemplatesRobTheme(grok.View):
    grok.name('remove_templates_robtheme')
    grok.context(IPloneSiteRoot)
    grok.layer(IGenwebRobthemeLayer)
    grok.require('cmf.ManagePortal')

    def render(self):
        portal = api.portal.get()
        templates = portal.get('templates', None)
        if templates:
            for template in templates:
                if template.startswith('rob-theme-'):
                    templates.manage_delObjects([template])
        return 'Done'
示例#10
0
class VersionCommand(grok.View):
    grok.context(ISector)
    grok.require("zope2.View")
    grok.layer(NuPloneSkin)
    grok.name("version-command")

    def render(self):
        action = self.request.get("action")
        if action == "new":
            sector = aq_inner(self.context)
            self.request.response.redirect("%s/++add++euphorie.surveygroup" %
                                           sector.absolute_url())
        else:
            log.error("Invalid version command action: %r", action)
示例#11
0
class View(grok.View):
    grok.context(IHomePage)
    grok.require("zope2.View")
    grok.layer(IOSHAClientSkinLayer)
    grok.template("custom_homepage")
    grok.name("nuplone-view")

    def update(self):
        plt = api.portal.get_tool('portal_languages')
        self.language_info = plt.getAvailableLanguageInformation()
        props = api.portal.get_tool('portal_properties')
        self.json_url = props.site_properties.getProperty(
            'tools_json_url', 'https://oiraproject.eu/oira-ws/tools.json')

        self.tools = self.prepare_tools()

        return self.render()

    def get_json(self):
        tools_json = requests.get(self.json_url)
        return loads(tools_json.content)

    @property
    def cached_json(self):
        from plone.protect.auto import safeWrite
        safeWrite(self.context, self.request)
        now = datetime.now()
        short_cache = now + timedelta(minutes=5)
        long_cache = now + timedelta(minutes=15)
        if self.request.get('invalidate-cache'):
            mtool = api.portal.get_tool('portal_membership')
            if mtool.checkPermission('cmf.ModifyPortalContent', self.context):
                self.context.cache_until = now

        if not hasattr(self.context, 'json'):
            try:
                self.context.json = self.get_json()
                self.context.cache_until = long_cache
            except (ValueError, AttributeError), err:
                log.error('Failed to retrieve tools JSON from {}: {}'.format(
                    self.json_url, err))
                return []
        if now >= getattr(self.context, 'cache_until', datetime.min):
            try:
                self.context.json = self.get_json()
                self.context.cache_until = long_cache
            except (ValueError, AttributeError), err:
                log.error('Failed to update tools JSON from {}: {}'.format(
                    self.json_url, err))
                self.context.cache_until = short_cache
示例#12
0
class View(dexterity.DisplayForm):
    grok.context(IPaste)
    grok.require('zope2.View')
    grok.layer(ISGPastebinLayer)

    def updateWidgets(self):
        super(View, self).updateWidgets()
        self.widgets['code'].rows = 25

    @memoize
    def pygmented(self):
        """ Returns highlighted source code """
        lx = get_lexer_by_name(self.context.lexer)
        return highlight(self.context.code, lx, HtmlFormatter())
示例#13
0
class Identification(grok.View):
    """Survey identification start page.

    This view shows the introduction text for the identification phase. This
    includes an option to print a report with all questions.

    This view is registered for :py:class:`PathGhost` instead of
    :py:obj:`euphorie.content.survey.ISurvey` since the
    :py:class:`SurveyPublishTraverser` generates a :py:class:`PathGhost` object
    for the *identification* component of the URL.

    View name: @@index_html
    """
    grok.context(PathGhost)
    grok.require("euphorie.client.ViewSurvey")
    grok.layer(IIdentificationPhaseSkinLayer)
    grok.template("identification")
    grok.name("index_html")

    question_filter = None

    def update(self):
        if redirectOnSurveyUpdate(self.request):
            return
        self.survey = survey = aq_parent(aq_inner(self.context))
        question = FindFirstQuestion(filter=self.question_filter)
        if question is not None:
            self.next_url = QuestionURL(survey,
                                        question,
                                        phase="identification")
            self.tree = getTreeData(self.request, question)
        else:
            self.next_url = None

    @property
    def extra_text(self):
        appconfig = getUtility(IAppConfig)
        settings = appconfig.get('euphorie')
        have_extra = settings.get('extra_text_identification', False)
        if not have_extra:
            return None
        lang = getattr(self.request, 'LANGUAGE', 'en')
        # Special handling for Flemish, for which LANGUAGE is "nl-be". For
        # translating the date under plone locales, we reduce to generic "nl".
        # For the specific oira translation, we rewrite to "nl_BE"
        if "-" in lang:
            elems = lang.split("-")
            lang = "{0}_{1}".format(elems[0], elems[1].upper())
        return translate(_(u"extra_text_identification", default=u""),
                         target_language=lang)
示例#14
0
class resetCountOffers(grok.View):
    grok.name('reset_offers_counter')
    grok.context(Interface)
    grok.template('reset_offers_counter')
    grok.require('cmf.ManagePortal')
    grok.layer(IGenwebTfemarketLayer)

    def update(self):
        if 'confirm' in self.request.form:
            registry = queryUtility(IRegistry)
            tfe_tool = registry.forInterface(ITfemarketSettings)
            tfe_tool.count_offers = 0
            transaction.commit()
            self.request.response.redirect(self.context.absolute_url() + "/tfemarket-settings#fieldsetlegend-2")
示例#15
0
class OrganisationCreatedSiteOwnerMailTemplate(MailTemplateBase):
    """ """
    grok.name('mail_organisation_created_siteowner')
    grok.context(IOrganisation)
    grok.layer(IOSHAHWCContentLayer)
    grok.require('cmf.ReviewPortalContent')

    def render(self):
        self.subject = 'Application to the Healthy Workplaces campaign'
        self.template = grok.PageTemplateFile(
            'templates/mail_organisation_created_siteowner.pt')
        if not self.from_addr:
            raise KeyError('email_from_address')
        return self.template.render(self)
示例#16
0
class Edit(form.SchemaEditForm):
    grok.context(ISurvey)
    grok.require("cmf.ModifyPortalContent")
    grok.layer(NuPloneSkin)
    grok.name("edit")

    schema = ISurveyEditSchema

    def applyChanges(self, data):
        changes = super(Edit, self).applyChanges(data)
        if changes:
            # Reindex our parents title.
            catalog = getToolByName(self.context, 'portal_catalog')
            catalog.indexObject(aq_parent(aq_inner(self.context)))
        return changes
示例#17
0
class AdminEdit(dexterity.EditForm):
    grok.context(sector.ISector)
    grok.require("cmf.ManagePortal")
    grok.layer(IOSHAContentSkinLayer)
    grok.name("admin-edit")
    grok.template('sector_admin_edit')

    def extractData(self):
        self.fields = self.fields.omit("login", "password")
        if "login" in self.widgets:
            del self.widgets["login"]

        if "password" in self.widgets:
            del self.widgets["password"]
        return super(AdminEdit, self).extractData()
示例#18
0
class BaseJobSearchAutocomplete(grok.View):
    grok.baseclass()
    grok.name('jobtitle_autocomplete')
    grok.layer(IProductSpecific)

    def render(self):
        cluster = self.request.get('industry_cluster', '')
        query = self.request.get('q', '')
        results = []

        for job in self.context.portal_catalog(
                industry_cluster=cluster, portal_type='dkiscm.jobmatrix.job'):
            if job.Title.lower().startswith(query):
                results.append('|'.join((job.Title, job.Title)))
        return '\n'.join(results)
示例#19
0
class OSHASurveyView(survey.View):
    grok.layer(IOSHAContentSkinLayer)
    grok.template("survey_view")

    def modules_and_profile_questions(self):
        return [self._morph(child) for child in self.context.values()]

    def _morph(self, child):
        state = getMultiAdapter((child, self.request),
                                name="plone_context_state")

        return dict(id=child.id,
                    title=child.title,
                    url=state.view_url(),
                    is_profile_question=IProfileQuestion.providedBy(child))
示例#20
0
class AddForm(dexterity.AddForm):
    """ View name: euphorie.profilequestion
    """
    grok.context(IProfileQuestion)
    grok.name('euphorie.profilequestion')
    grok.require('euphorie.content.AddNewRIEContent')
    grok.layer(NuPloneSkin)
    form.wrap(True)

    schema = IProfileQuestion
    template = ViewPageTemplateFile('templates/profilequestion_add.pt')

    @property
    def label(self):
        return _(u"Add Profile question")
示例#21
0
class TimeframeAddForm(dexterity.AddForm):

    permission = 'cmf.AddPortalContent'

    grok.context(ITimeframe)
    grok.layer(ISeantisReservationSpecific)
    grok.require(permission)

    grok.name('seantis.reservation.timeframe')

    @button.buttonAndHandler(_('Save'), name='save')
    def handleAdd(self, action):
        data, errors = self.extractData()
        validate_timeframe(self.context, self.request, data)
        dexterity.AddForm.handleAdd(self, action)
示例#22
0
class JSON_View(browser.JSON_View):
    grok.context(Interface)
    grok.name('api')
    grok.require('cmf.AddPortalContent')
    grok.layer(IUploadBrowserLayer)

    json_var = {'name': 'File-Name.jpg',
                'title': '',
                'description': '',
                'rights': '',
                'size': 999999,
                'url': '\/\/nohost.org',
                'thumbnail_url': '//nohost.org',
                'delete_url': '//nohost.org',
                'delete_type': 'DELETE',
                }

    def getContextInfo(self, context=None):
        if context is None:
            context = self.context
        context = aq_inner(context)

        info = ''
        context_name = context.Title()
        context_url = context.absolute_url()
        context_type = context.Type()
        del_url = context_url

        info = {'name': context_name,
                'title': context_name,
                'description': context.Description(),
                'rights': context.Rights(),
                'url': context_url,
                'delete_url': del_url,
                'delete_type': 'DELETE',
                }
        if hasattr(context, 'size'):
            info['size'] = context.size()
        else:
            if context_type == 'File':
                info['size'] = context.file.getSize()
            elif context_type == 'Image':
                info['size'] = context.image.getSize()
        if context_type == 'Image':
            scales = context.restrictedTraverse('@@images')
            thumb = scales.scale(fieldname='image', scale='thumb')
            info['thumbnail_url'] = thumb.url
        return info
示例#23
0
class dynamicCSS(grok.View):
    grok.name('dynamic.css')
    grok.context(Interface)
    grok.layer(IGenwebTheme)

    def update(self):
        self.especific1 = genweb_config().especific1
        self.especific2 = genweb_config().especific2

    def render(self):
        self.request.response.setHeader('Content-Type', 'text/css')
        self.request.response.addHeader(
            'Cache-Control', 'must-revalidate, max-age=0, no-cache, no-store')
        if self.especific1 and self.especific2:
            return self.compile_scss(especific1=self.especific1,
                                     especific2=self.especific2)
        else:
            return ""

    #@ram.cache(_render_cachekey)
    def compile_scss(self, **kwargs):
        genwebthemeegg = pkg_resources.get_distribution('genweb.alternatheme')

        scssfile = open('{}/genweb/alternatheme/scss/_dynamic.scss'.format(
            genwebthemeegg.location))

        settings = dict(especific1=self.especific1, especific2=self.especific2)

        variables_scss = """

        $genwebPrimary: {especific1};
        $genwebTitles: {especific2};

        """.format(**settings)

        scss.config.LOAD_PATHS = [
            '{}/genweb/alternatheme/bootstrap/scss/compass_twitter_bootstrap'.
            format(genwebthemeegg.location)
        ]

        css = Scss(scss_opts={
            'compress': False,
            'debug_info': False,
        })

        dynamic_scss = ''.join([variables_scss, scssfile.read()])

        return css.compile(dynamic_scss)
示例#24
0
class tfemarketUtilsDeleteOffer(grok.View):
    grok.context(Interface)
    grok.name('tfemarket-utils-delete-offer')
    grok.template('tfemarket_utils_delete_offer')
    grok.require('genweb.tfemarket.utils')
    grok.layer(IGenwebTfemarketLayer)

    def getTFEs(self):
        return getUrlAllTFE(self)

    def getOffers(self):
        pc = api.portal.get_tool('portal_catalog')
        filters = {'portal_type': 'genweb.tfemarket.offer',
                   'review_state': ('intranet', 'offered', 'public', 'pending'),
                   'sort_on': 'sortable_title',
                   'sort_order': 'ascending'}

        if 'TFE Teacher' in api.user.get_current().getRoles() and api.user.get_current().id != "admin":
            filters.update({'Creator': api.user.get_current().id})

        offers = pc.searchResults(**filters)
        res = {'ok': [], 'ko': []}
        for offer in offers:
            data = {'UID': offer.UID,
                    'Title': offer.Title,
                    'offer_id': offer.getObject().offer_id}

            if isManager() or not checkOfferhasApplications(offer.getObject()):
                res['ok'].append(data)
            else:
                res['ko'].append(data)
        return res

    def update(self):
        if 'submit' in self.request.form:
            pc = api.portal.get_tool('portal_catalog')
            offer = pc.searchResults({'portal_type': 'genweb.tfemarket.offer',
                                      'UID': self.request.form['offer']})
            if len(offer) > 0:
                offer = offer[0]
                parent = offer.getObject().aq_parent
                try:
                    parent.manage_delObjects([offer.id])
                    IStatusMessage(self.request).addStatusMessage(_(u"The offer has been removed."), 'info')
                except:
                    IStatusMessage(self.request).addStatusMessage(_(u"The offer could not be removed."), 'error')
            else:
                IStatusMessage(self.request).addStatusMessage(_(u"The offer could not be removed."), 'error')
示例#25
0
class View(BaseView):
    """ Override so that we can use out own template (only needed for one
        translation).
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        XXX: If the view is bound to IOSHAContentSkinLayer instead of NuPloneSkin,
        then it will NOT be used.
        Only by giving it the SAME layer as the view it is supposed to override
        can we make sure this view is actually used. I have no idea why this
        works for all other content types but not for solution.
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        """
    grok.context(ISolution)
    grok.require("zope2.View")
    grok.layer(NuPloneSkin)
    grok.name("nuplone-view")
    grok.template("solution_view")
示例#26
0
class RSS(grok.View):
    """ A storyline specific RSS view """
    grok.context(IStoryline)
    grok.layer(IGiesingLayer)
    grok.template('storyline_rss')

    def update(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        self.object_list = catalog(
            path='/'.join(self.context.getPhysicalPath()),
            portal_type='collective.giesing.snippet',
            sort_on='modified',
            sort_order='reverse',
            b_start=0,
            b_size=10,
        )
示例#27
0
class SolutionEdit(form.SchemaEditForm):
    """ Override to allow us to set form title and button labels """
    grok.context(ISolution)
    grok.require("cmf.ModifyPortalContent")
    grok.layer(IOSHAContentSkinLayer)
    grok.name("edit")

    def updateFields(self):
        super(SolutionEdit, self).updateFields()
        self.buttons['save'].title = _(u'button_save_changes',
                                       default=u"Save changes")
        self.buttons['cancel'].title = _(u'button_cancel', default=u"Cancel")

    @property
    def label(self):
        return _(u"Edit Solution", default=u"Edit Measure")
示例#28
0
文件: risk.py 项目: EU-OSHA/osha.oira
class Add(risk.Add, OSHAFormMixin):
    """ Override to allow us to dynamically set field descriptions
    """
    grok.context(risk.IRisk)
    grok.layer(IOSHAContentSkinLayer)

    def updateFields(self):
        super(Add, self).updateFields()
        self.setDynamicDescriptions()
        self.buttons['save'].title = _(
            u'button_save_changes', default=u"Save changes")
        self.buttons['cancel'].title = _(u'button_cancel', default=u"Cancel")

    @property
    def label(self):
        return _(u"Add Risk")
示例#29
0
文件: risk.py 项目: EU-OSHA/osha.oira
class Edit(risk.Edit, OSHAFormMixin):
    """ Override to allow us to dynamically set field descriptions
    """
    grok.context(risk.IRisk)
    grok.layer(IOSHAContentSkinLayer)

    def __init__(self, context, request):
        risk.Edit.__init__(self, context, request)
        self.evaluation_algorithm = context.evaluation_algorithm()

    def updateFields(self):
        super(Edit, self).updateFields()
        self.setDynamicDescriptions()
        self.buttons['save'].title = _(
            u'button_save_changes', default=u"Save changes")
        self.buttons['cancel'].title = _(u'button_cancel', default=u"Cancel")
示例#30
0
class BannersViewlet(grok.Viewlet):
    """ Viewlet que exibira os banners
    """

    grok.viewletmanager(IPortalFooter)
    grok.layer(IObservatorioTemaLayer)

    @memoize
    def get_banners(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        banners = catalog(object_provides = IBanner.__identifier__, review_state='published')
        return banners

    def available(self):
        if self.get_banners():
            return True
示例#31
0
from silva.core.layout.porto import porto
from silva.core.layout.porto.interfaces import IPorto
from silva.core.views import views as silvaviews


class INewTheme(IPorto):
    """Layer for the theme.
    """

class INewThemeSkin(INewTheme, ISilvaSkin):
    """Skin for the new theme.
    """
    grok.skin("New theme")


grok.layer(INewTheme)


class Layout(porto.Layout):
    """Skins should have a Layout class
    """


class AwesomeView(silvaviews.Page):
    """A view
    """
    grok.name('awesome.html')

    def render(self):
        return u"Hello awesome!"
示例#32
0
# Copyright (c) 2002-2013 Infrae. All rights reserved.
# See also LICENSE.txt

from five import grok
from zope.component import getUtility, getAdapter
from zope.cachedescriptors.property import Lazy
from zope.traversing.browser import absoluteURL

from silva.core.interfaces import IContainer
from silva.core.layout.interfaces import IMetadata
from silva.core.layout.porto.interfaces import IPorto
from silva.core.services.interfaces import IContentFilteringService
from silva.core.views import views as silvaviews
from silva.core.views.interfaces import IVirtualSite

grok.layer(IPorto)


# Main design

class MainLayout(silvaviews.Layout):
    """ This is the main layout it is the first entry point of the page.

    DO NOT USE IT DIRECTLY !!

    Use Layout/Body content provider for your themes
    which permits you to customize the body of the page.
    To include your javascript and css in the head html tag
    use silva.resourceinclude
    """
    grok.template('mainlayout')
示例#33
0
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2013 Infrae. All rights reserved.
# See also LICENSE.txt

from five import grok
from zope.publisher.interfaces import INotFound
from zope.security.interfaces import IUnauthorized

from silva.core.layout.interfaces import ICustomizableLayer
from silva.core.views import views as silvaviews
from silva.core.views.httpheaders import ErrorHeaders

grok.layer(ICustomizableLayer)


# 404 page

class NotFoundPage(silvaviews.Page):
    grok.context(INotFound)
    grok.name('error.html')


class NotFoundHeaders(ErrorHeaders):
    grok.adapts(ICustomizableLayer, INotFound)

    def other_headers(self, headers):
        super(NotFoundHeaders, self).other_headers(headers)
        self.response.setStatus(404)


# Unauthorized page
示例#34
0
from Acquisition import aq_parent
from Products.ATContentTypes.interfaces.document import IATDocument
from Products.ATContentTypes.interfaces.interfaces import IATContentType
from Products.CMFCore.utils import getToolByName

from deaf.contents.buyable_content import IBuyableContent
from deaf.contents.browser.utils import get_lead_image
from collective.contentleadimage.interfaces import ILeadImageable
from five import grok
from plone.theme.interfaces import IDefaultPloneLayer
from plone.app.layout.nextprevious.interfaces import INextPreviousProvider
from zope.i18nmessageid import MessageFactory

_ = MessageFactory('deaf.contents')

grok.layer(IDefaultPloneLayer)


class DocumentView(grok.View):
    grok.context(IATDocument)
    grok.name('document_view')

    RELATED_LABELS = {
        'Event': _(u'Events'),
        'News Item': _(u'News Items'),
        'Link': _(u'V2 Archives'),
        'Document': _(u'Program Items'),
        'Person': _(u'Artists/Speakers'),
        'GeoLocation': _(u'Locations')}

    def update(self):
from gomobiletheme.basic.viewlets import getView
from gomobile.mobile.interfaces import IMobileImageProcessor

from gomobiletheme.mobipublic import MessageFactory as _

# Layer for which against all our viewlets are registered
from interfaces import IThemeLayer

# Viewlets are on all content by default.
grok.context(Interface)

# Use templates directory to search for templates.
grok.templatedir('templates')

# Viewlets are active only when gomobiletheme.basic theme layer is activated
grok.layer(IThemeLayer)

# All viewlets are registered against this dummy viewlet manager
grok.viewletmanager(base.MainViewletManager)

class Head(base.Head):

    def favicon_url(self):
        """ Get url for favicon
        """
        portal_state = getView(self.context, self.request, "plone_portal_state")
        self.portal_url = portal_state.portal_url()
        return self.portal_url + "/favicon.ico"

class Logo(base.Logo):
    """ Render site logo with link back to the site root.
import datetime
from five import grok
from zope.interface import Interface
from zope.component import getUtility

from plone.app.layout.viewlets.interfaces import IPortalFooter

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName

from upfront.pagetracker import MessageFactory as _
from upfront.pagetracker.interfaces import IUpfrontPageTrackerLayer
from upfront.pagetracker.interfaces import IPageTracker

grok.context(Interface)
grok.layer(IUpfrontPageTrackerLayer)

class PageTrackingViewlet(grok.Viewlet):
    """ A viewlet which will log the request details on each page """

    grok.viewletmanager(IPortalFooter)

    def update(self):
        """ Log data from current request with page tracker
        """

        mt = getToolByName(self.context, 'portal_membership')
        user = mt.getAuthenticatedMember()        
        now = datetime.datetime.now()
        datetime_str = now.strftime('%d/%m/%Y %H:%M:%S')
示例#37
0
"""

    For more information see

    * http://collective-docs.readthedocs.org/en/latest/views/viewlets.html

"""

# Zope imports
from zope.interface import Interface
from zope.component import getMultiAdapter
from five import grok

# Plone imports
from plone.app.layout.viewlets.interfaces import IPortalFooter

# Local imports
from interfaces import IAddonSpecific

grok.templatedir("templates")
grok.layer(IAddonSpecific)

# By default, set context to zope.interface.Interface
# which matches all the content items.
# You can register viewlets to be content item type specific
# by overriding grok.context() on class body level
grok.context(Interface)

from silva.app.document.interfaces import IDocumentDetails
from silva.core import contentlayout
from silva.core.interfaces import IPublication, IRoot, IFeedEntryProvider
from silva.core.interfaces import ISilvaObject, IGhost, IContainer
from silva.core.layout.interfaces import ICustomizableTag
from silva.core.layout.porto import porto, errors
from silva.core.services.interfaces import IMetadataService, ICatalogService
from silva.core.views import views as silvaviews

from silva.app.redirectlink.interfaces import IPermanentRedirectLink

from .interfaces import ISilvaCmsOrg, ISilvaSilvaOrgWithNavigation

grok.templatedir('templates_silvacmsorg')
grok.layer(ISilvaCmsOrg)


class MainLayout(porto.MainLayout):
    grok.template('htmlheadbody')


class INoNavigationLayout(ICustomizableTag):
    """Remove the navigation from the layout
    """


class Layout(porto.Layout):

    @Lazy
    def publication_title(self):
示例#39
0
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2013 Infrae. All rights reserved.
# See also LICENSE.txt

from five import grok
from zope.interface import providedBy
from zope.publisher.interfaces import INotFound
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.security.interfaces import IForbidden

from AccessControl import ClassSecurityInfo
from App.class_init import InitializeClass
import Acquisition
import zExceptions

grok.layer(IBrowserRequest)

HTML_TEMPLATE = u"""
<html>
  <head>
    <title>%s</title>
  </head>
  <body>
     <h1>An error happened</h1>
     <p><b>%s</b></p>
  </body>
</html>
"""

class DefaultError(Acquisition.Implicit):
    """Wrapper for errors. The are the context, with all acquisition
示例#40
0
from zope.component import getUtility
from zope.component.hooks import getSite
from plone.directives import dexterity
from Products.CMFCore.utils import getToolByName

from tarmii.theme import MessageFactory as _
from tarmii.theme.interfaces import ITARMIIThemeLayer
from tarmii.theme.content.teacherresource import ITeacherResource
from upfront.assessment.content.assessment import IAssessment
from upfront.classlist.content.classlist import IClassList
from upfront.classlist.content.learner import ILearner
from upfront.pagetracker.interfaces import IPageTracker
from upfront.pagetracker.browser.viewlets import PageTrackingViewlet

grok.templatedir('templates')
grok.layer(ITARMIIThemeLayer)

class TeacherResourceAddForm(dexterity.AddForm):
    grok.name('tarmii.theme.content.teacherresource')
    grok.layer(ITARMIIThemeLayer)

    def nextURL(self):
        # both save and cancel buttons redirect to the same place
        site = getSite()
        return '%s/resources' % (site.absolute_url())


class TeacherResourceEditForm(dexterity.EditForm):
    grok.name('edit')
    grok.context(ITeacherResource)
示例#41
0
from five import grok
from zope.interface import Interface
from Products.CMFCore.utils import getToolByName

from emas.theme.interfaces import IEmasThemeLayer


grok.templatedir('templates')
grok.layer(IEmasThemeLayer)


class MXitStats(grok.View):
    """
        Custom view for mxit signup stats 
    """

    grok.context(Interface)
    grok.require('zope2.View')
    
    def stats_per_group(self):
        group_stats = {}
        gt = getToolByName(self.context, 'portal_groups')
        for groupname in ["PastMathsExamPapers", "PastScienceExamPapers"]:
            group = gt.getGroupById(groupname)
            count = len(group.getMemberIds())
            group_stats[groupname] = count

        return group_stats
示例#42
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collective.deform import base_views
from example.conference.presenter import IPresenter
from five import grok
from zope.interface import Interface

from deform_demo.layer import IDeformDemo

grok.layer(IDeformDemo)


class Edit(base_views.BaseEditForm):
    grok.context(IPresenter)


class View(base_views.BaseView):
    grok.context(IPresenter)


class AddPresenter(base_views.BaseAddView):
    grok.context(Interface)
    portal_type = 'example.conference.presenter'

示例#43
0
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 Infrae. All rights reserved.
# See also LICENSE.txt

from five import grok

from silva.core.views import views as silvaviews

from .interfaces import ISilvaUITheme
from zope.interface import Interface
from zope.publisher.interfaces.browser import IBrowserRequest


grok.layer(Interface)


class DefaultLayout(silvaviews.Layout):
    """ Layout for smi objects that needs one (e.g. exceptions)
    """
    grok.context(Interface)


示例#44
0
from five import grok

from Products.CMFCore.interfaces import ISiteRoot
from Products.CMFCore.utils import getToolByName
from Products.statusmessages.interfaces import IStatusMessage

from zope.lifecycleevent import ObjectRemovedEvent
from zope.event import notify

from ..interfaces import INotice, INoticesStorage, INoticeFactory, \
    INoticesLayer
from ..catalog import ResultSet



grok.layer(INoticesLayer)


class AddNotice(form.SchemaAddForm):

    grok.context(INoticesStorage)
    grok.require('cmf.ManagePortal')
    grok.name('add')

    schema = INotice

    label = u"Add Notice"

    def create(self, data):
        return INoticeFactory(self.context)(**data)
示例#45
0
from five import grok

# from zope.component.hooks import getSite

from plone.directives import dexterity
from z3c.form import form, button

# from Acquisition import aq_inner

from collective.topictree import MessageFactory as _
from collective.topictree.topictree import ITopicTree

from collective.topictree.interfaces import ITopicTreeLayer

grok.templatedir("templates")
grok.layer(ITopicTreeLayer)


class TopicTreeEditForm(dexterity.EditForm):
    grok.name("edit")
    grok.context(ITopicTree)
    grok.template("edittopictree")

    formname = "edit-topictree-form"
    kssformname = "kssattr-formname-@@edit"
示例#46
0
# See also LICENSE.txt

from five import grok
from silva.core.interfaces import IVersionedContent, IVersion
from silva.core.layout.interfaces import ISilvaLayer
from silva.core.views import views as silvaviews
from silva.core.views.interfaces import IView
from silva.translations import translate as _
from grokcore.layout.interfaces import ILayout
from zope.component import queryMultiAdapter, getMultiAdapter
from zope.interface import Interface
from zope.i18n import translate

from zExceptions import NotFound

grok.layer(ISilvaLayer)


class FallbackLayout(silvaviews.Layout):
    """ Layout for objects that do not provide ISilvaObject
    """

    grok.context(Interface)

    def render(self):
        return (
            """
            <html>
                <head><!-- no layout --></head>
                <body>%s</body>
            </html>
示例#47
0
"""

	Plone views overrides.

	For more information see

	* http://collective-docs.readthedocs.org/en/latest/views/browserviews.html

"""

# Zope imports
from zope.interface import Interface
from five import grok
from Products.CMFCore.interfaces import ISiteRoot

# Local imports
from scanned_docs_frontend.interfaces import IAddonSpecific, IThemeSpecific

#grok.templatedir("templates")
grok.layer(IThemeSpecific)
# Copyright (c) 2013 Infrae. All rights reserved.
# See also LICENSE.txt
from five import grok
from silvatheme.silvacmsorg.subskins.interfaces import ISilvaCmsOrgResponsive

grok.layer(ISilvaCmsOrgResponsive)