Ejemplo n.º 1
0
class SubscriptionConfigurationReview(SubscriptionConfigurationMixin):
    grok.context(IReviewFolder)
    grok.name('subscription-configuration')
    grok.require('zope2.View')
Ejemplo n.º 2
0
class View(grok.View):
    grok.context(IMarket)
    grok.template('market_view')

    def clearFiltersCookie(self):
        filters = self.request.form
        filters.pop('estat', None)
        filters.pop('id', None)
        filters.pop('_authenticator', None)
        return filters

    def filterResultsForDate(self, results):
        filters = self.request.form

        delete = []
        for index, item in enumerate(results, start=0):

            # Filter date
            if 'effective_date' in item and item['effective_date']:
                today = date.today()
                effective_date = datetime.strptime(item['effective_date'],
                                                   '%d/%m/%Y').date()
                diff_days = today - effective_date
                diff_days = diff_days.days
                if filters['date'] == 'w' and diff_days > 7 \
                   or filters['date'] == 'm' and diff_days > 30:
                    delete.append(index)
                    continue
            else:
                delete.append(index)
                continue

        delete.reverse()
        for item in delete:
            results.pop(item)

        return results

    def getOffers(self):
        searchMarket = self.request.cookies.get('MERCAT_TFE')
        if searchMarket and not searchMarket == "":
            if 'searchFilters' in self.request.form:
                self.request.form = ast.literal_eval(searchMarket)
            else:
                if 'search' not in self.request.form:
                    self.request.response.setCookie('MERCAT_TFE', "", path='/')

        if not isManager() and self.checkPermissionCreateOffers(
        ) or self.request.form != {} and 'form.button.confirm' not in self.request.form:
            wf_tool = getToolByName(self.context, 'portal_workflow')
            tools = getMultiAdapter((self.context, self.request),
                                    name='plone_tools')

            filters = {
                'portal_type': 'genweb.tfemarket.offer',
                'path': {
                    "query": '/'.join(self.context.getPhysicalPath())
                }
            }

            if self.checkPermissionCreateOffers(
            ) and api.user.get_current().id != "admin":
                filters.update({'show_inactive': 1})
                if 'searchOffer' not in self.request.form and 'search' not in self.request.form and 'allOffers' not in self.request.form:
                    filters.update({'Creator': api.user.get_current().id})

            if 'searchFilters' in self.request.form or 'searchOffer' in self.request.form:
                if 'offer' in self.request.form:
                    filters.update({'TFEoffer_id': self.request.form['offer']})

            if 'search' in self.request.form:
                if 'title' in self.request.form and self.request.form[
                        'title'] != 'a':
                    filters.update({'Title': self.request.form['title']})

                if 'topic' in self.request.form and self.request.form[
                        'topic'] != 'a':
                    filters.update({'TFEtopic': self.request.form['topic']})

                if 'degree' in self.request.form and self.request.form[
                        'degree'] != 'a':
                    filters.update({'TFEdegree': self.request.form['degree']})

                if 'teacher' in self.request.form and self.request.form[
                        'teacher'] != 'a':
                    filters.update(
                        {'TFEteacher_manager': self.request.form['teacher']})

                if 'departament' in self.request.form and self.request.form[
                        'departament'] != 'a':
                    filters.update(
                        {'TFEdept': self.request.form['departament']})

                if 'type' in self.request.form and self.request.form[
                        'type'] != 'a':
                    filters.update(
                        {'TFEoffer_type': self.request.form['type']})

                if 'company' in self.request.form and self.request.form[
                        'company'] != 'a':
                    filters.update(
                        {'TFEcompany': self.request.form['company']})

                if 'state' in self.request.form and self.request.form[
                        'state'] != 'a':
                    filters.update(
                        {'review_state': self.request.form['state']})

                if 'language' in self.request.form:
                    filters.update({'TFElang': self.request.form['language']})

                if 'modality' in self.request.form and len(
                        self.request.form['modality']) == 1:
                    filters.update({
                        'TFEmodality':
                        'Universitat'
                        if self.request.form['modality'] == 'u' else 'Empresa'
                    })

                if 'grant' in self.request.form:
                    filters.update(
                        {'TFEgrant': self.request.form['grant'] == 'on'})

                if 'key' in self.request.form:
                    filters.update({'TFEkeys': self.request.form['key']})

            pc = api.portal.get_tool('portal_catalog')
            values = pc.searchResults(**filters)

            values = sort(values,
                          sort=(('Date', 'cmp', 'desc'), ('Title', 'cmp',
                                                          'asc')))

            marketWorkflow = tools.workflow().getWorkflowsFor(self.context)[0]
            marketStatus = wf_tool.getStatusOf(marketWorkflow.id, self.context)
            marketState = marketWorkflow['states'][
                marketStatus['review_state']]

            results = []
            for offer in values:
                offer = offer.getObject()
                if checkPermission('zope2.View', offer):
                    workflowActions = wf_tool.listActionInfos(object=offer)
                    offerWorkflow = tools.workflow().getWorkflowsFor(offer)[0]
                    offerStatus = wf_tool.getStatusOf(offerWorkflow.id, offer)
                    offerState = offerWorkflow['states'][
                        offerStatus['review_state']]

                    if offerState.id == 'offered':
                        registry = queryUtility(IRegistry)
                        tfe_tool = registry.forInterface(ITfemarketSettings)
                        review_state = tfe_tool.review_state
                        if review_state:
                            workflowActions = [
                                x for x in workflowActions
                                if x.get('id') == 'sendtoreview'
                            ]
                        else:
                            workflowActions = [
                                x for x in workflowActions
                                if x.get('id') != 'sendtoreview'
                            ]

                    if offerState.id == 'pending' and self.currentUserIsAloneTeacher(
                    ):
                        workflowActions = []

                    if marketState.id == 'published':
                        workflowActions = [
                            x for x in workflowActions
                            if x.get('id') != 'publicaalintranet'
                        ]
                    elif marketState.id == 'intranet':
                        workflowActions = [
                            x for x in workflowActions
                            if x.get('id') != 'publicaloferta'
                        ]

                    if not offer.isExpired(
                    ) or self.checkPermissionCreateOffers():
                        results.append(
                            dict(
                                title=offer.title,
                                state=offerState.title,
                                state_id=offerState.id,
                                url=offer.absolute_url(),
                                path='/'.join(offer.getPhysicalPath()),
                                item_path='/'.join(
                                    offer.getPhysicalPath()[2:]),
                                dept=offer.dept,
                                company=offer.company,
                                effective_date=offer.effective_date.strftime(
                                    '%d/%m/%Y')
                                if offer.effective_date else None,
                                expiration_date=offer.expiration_date.strftime(
                                    '%d/%m/%Y')
                                if offer.expiration_date else None,
                                teacher_manager=offer.teacher_manager,
                                teacher_fullname=offer.teacher_fullname,
                                teacher_email=offer.teacher_email,
                                codirector=offer.codirector,
                                codirector_email=offer.codirector_email,
                                codirector_dept=offer.codirector_dept,
                                modality=offer.modality,
                                description=offer.description,
                                langs=offer.lang,
                                multiple_langs=len(offer.lang) > 1,
                                environmental_theme=offer.environmental_theme,
                                grant=offer.grant,
                                tfgm=offer.tfgm,
                                degrees=offer.degree,
                                multiple_degrees=len(offer.degree) > 1,
                                keywords=offer.keys,
                                offer_id=offer.offer_id,
                                center=offer.center,
                                workflows=workflowActions,
                                can_edit=checkPermission(
                                    'cmf.ModifyPortalContent', offer),
                                can_create_application=CPCreateApplications(
                                    self, offer),
                                if_modality_company=True
                                if offer.modality == 'Empresa' else False,
                                num_students=offer.num_students,
                                workload=offer.workload,
                                targets=offer.targets,
                                features=offer.features,
                                requirements=offer.requirements,
                                confidential=offer.confidential,
                                scope_cooperation=offer.scope_cooperation,
                                topic=offer.topic,
                                offer_type=offer.offer_type,
                                if_propietary=isTeachersOffer(offer),
                                assign_offer=self.assignOffer(
                                    offer, offerState.id),
                                is_expired=offer.isExpired()))

            if 'search' in self.request.form:
                self.request.response.setCookie('MERCAT_TFE',
                                                self.clearFiltersCookie(),
                                                path='/')

                if 'date' in self.request.form and self.request.form[
                        'date'] != 'a':
                    results = self.filterResultsForDate(results)

            return results

        else:
            return []

    def userApplications(self):
        catalog = api.portal.get_tool(name='portal_catalog')
        wf_tool = getToolByName(self.context, 'portal_workflow')
        tools = getMultiAdapter((self.context, self.request),
                                name='plone_tools')
        results = []
        values = catalog(path={
            'query': '/'.join(self.context.getPhysicalPath()),
            'depth': 3
        },
                         object_provides=IApplication.__identifier__,
                         Creator=api.user.get_current().id)

        for item in values:
            application = item.getObject()
            workflowActions = wf_tool.listActionInfos(object=application)
            workflows = tools.workflow().getWorkflowsFor(application)[0]

            results.append(
                dict(
                    UID=item.UID,
                    title=item.Title,
                    state=workflows['states'][item.review_state].title,
                    url=item.getURL(),
                    item_path='/'.join(application.getPhysicalPath()[2:]),
                    dni=application.dni,
                    name=application.title,
                    email=application.email,
                    phone=application.phone,
                    offer_id=application.offer_id,
                    offer_title=application.offer_title,
                    degree_title=application.degree_title,
                    body=application.body,
                    workflows=workflowActions,
                    can_edit=checkPermission('cmf.ModifyPortalContent',
                                             application),
                ))
        return results

    def getApplications(self, offer):
        catalog = api.portal.get_tool(name='portal_catalog')
        wf_tool = getToolByName(self.context, 'portal_workflow')
        tools = getMultiAdapter((self.context, self.request),
                                name='plone_tools')
        results = []
        values = catalog(path={
            'query': offer['path'],
            'depth': 1
        },
                         object_provides=IApplication.__identifier__)

        for item in values:
            application = item.getObject()
            workflowActions = wf_tool.listActionInfos(
                object=application) if offer['if_propietary'] else []
            workflows = tools.workflow().getWorkflowsFor(application)[0]

            results.append(
                dict(
                    UID=item.UID,
                    title=item.Title,
                    state=workflows['states'][item.review_state].title,
                    url=item.getURL(),
                    item_path='/'.join(application.getPhysicalPath()[2:]),
                    dni=application.dni,
                    name=application.title,
                    email=application.email,
                    phone=application.phone,
                    offer_id=application.offer_id,
                    offer_title=application.offer_title,
                    degree_title=application.degree_title,
                    body=application.body,
                    workflows=workflowActions,
                    can_change_workflows=True,
                    can_edit=checkPermission('cmf.ModifyPortalContent',
                                             application)
                    and not self.currentUserIsAloneTeacher(),
                    style='ignore' if item.review_state
                    in ['cancelled', 'rejected', 'renounced'] else '',
                ))
        return results

    def getLanguages(self):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)
        return tfe_tool.languages

    def getModalities(self):
        return [{
            'id': 'c',
            'lit': _(u"Company")
        }, {
            'id': 'u',
            'lit': _(u"University")
        }]

    def getDates(self):
        return [{
            'id': 'a',
            'lit': _(u"All")
        }, {
            'id': 'w',
            'lit': _(u"Last week")
        }, {
            'id': 'm',
            'lit': _(u"Last month")
        }]

    def getTypes(self):
        return [{
            'id': 'a',
            'lit': _(u"MAll")
        }, {
            'id': 'Study',
            'lit': _(u"Study")
        }, {
            'id': 'Project',
            'lit': _(u"Project")
        }, {
            'id': 'Design',
            'lit': _(u"Design")
        }, {
            'id': 'Others',
            'lit': _(u"Others")
        }]

    def getTFGM(self):
        return [{
            'id': 'a',
            'lit': _(u"MAll")
        }, {
            'id': 'TFG',
            'lit': u"TFG"
        }, {
            'id': 'TFM',
            'lit': u"TFM"
        }]

    def getDegrees(self):
        return getDegrees()

    def getDegreeLiteralFromId(self, id):
        return getDegreeLiteralFromId(id)

    def getAllOffers(self):
        return self.context.contentValues(
            {'portal_type': 'genweb.tfemarket.offer'})

    def getLiteral(self, elem):
        return elem['lit']

    def getTeachers(self):
        results = []
        for offer in self.getAllOffers():
            if checkPermission('zope2.View', offer) and offer.teacher_manager:
                teacherNotInList = True
                for teacher in results:
                    if teacher['id'] == offer.teacher_manager:
                        teacherNotInList = False
                        break
                if teacherNotInList:
                    results.append({
                        'id': offer.teacher_manager,
                        'lit': offer.teacher_fullname
                    })

        return sorted(list(results), key=self.getLiteral)

    def getDepartaments(self):
        results = []
        for offer in self.getAllOffers():
            if checkPermission('zope2.View', offer) and offer.dept:
                results.append(offer.dept)

        return sorted(list(OrderedDict.fromkeys(results)))

    def getCompanys(self):
        results = []
        for offer in self.getAllOffers():
            if checkPermission('zope2.View', offer) and offer.company:
                results.append(offer.company)

        return sorted(list(OrderedDict.fromkeys(results)))

    def getStates(self):
        results = []
        wf_tool = getToolByName(self, 'portal_workflow')
        states = wf_tool.tfemarket_offer_workflow.states._mapping
        user_roles = api.user.get_current().getRoles()
        for state in states.keys():
            permissions = states[state].permission_roles['View']
            for role in user_roles:
                if role in permissions:
                    results.append({'id': state, 'lit': states[state].title})
                    break
        return sorted(results, key=lambda x: x['lit'])

    def getKeys(self):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)
        tags = []

        keys = tfe_tool.tags
        if keys:
            tags = keys.split("\r\n")

        tags.sort()
        return tags

    def getTopics(self):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)
        topics = []

        keys = tfe_tool.topics
        if keys:
            topics = keys.split("\r\n")

        topics.sort()
        return topics

    def saveFilters(self):
        filters = self.request.form

        if 'key' in filters:
            filters['key'] = self.flattenedList(filters['key'])

        if 'language' in filters:
            filters['language'] = self.flattenedList(filters['language'])

        return filters

    def filtersString(self):
        return urllib.urlencode(self.request.form, True)

    def flattenedString(self, item):
        if isinstance(item, str):
            return unicodedata.normalize('NFKD', item.decode('utf-8')).encode(
                'ascii', errors='ignore')
        else:
            return unicodedata.normalize('NFKD', item).encode('ascii',
                                                              errors='ignore')

    def flattenedList(self, listItems):
        if isinstance(listItems, list):
            for index, item in enumerate(listItems, start=0):
                listItems[index] = self.flattenedString(listItems[index])
            return listItems
        else:
            return self.flattenedString(listItems)

    def checkPermissionCreateOffers(self):
        return CPCreateOffers(self, self.context)

    def openApplicationsTav(self):
        if self.checkPermissionCreateOffers():
            return True
        return False

    def getActualView(self):
        if 'allOffers' in self.request.form:
            return '&allOffers'
        elif 'search' in self.request.form:
            return '&search'
        else:
            return ''

    def classViewSearch(self):
        if not isManager() and self.checkPermissionCreateOffers(
        ) and self.request.form == {}:
            return {'collapse': ' hide', 'expand': ''}
        else:
            return {'collapse': '', 'expand': ' hide'}

    def assignOffer(self, offer, state):
        if checkPermission(
                'cmf.RequestReview',
                offer) and checkOfferhasConfirmedApplications(offer):
            if state == 'intranet':
                return 'assignalofertaintranet'
            elif state == 'public':
                return 'assign'
        return False

    def currentUserIsAloneTeacher(self):
        user_roles = api.user.get_current().getRoles()
        if 'TFE Teacher' in user_roles:
            if 'Manager' in user_roles or 'TFE Manager' in user_roles:
                return False
            else:
                return True
        else:
            return False

    def showErrorConfiguration(self):
        user_roles = api.user.get_current().getRoles()
        if 'Manager' in user_roles or 'TFE Manager' in user_roles:
            registry = queryUtility(IRegistry)
            bussoa_tool = registry.forInterface(IBUSSOASettings)
            if bussoa_tool.bus_url and bussoa_tool.bus_user and bussoa_tool.bus_password and bussoa_tool.bus_apikey and getTokenIdentitatDigital(
            ).status_code == 201:
                return False
            return True
        return False

    def showErrorNotConfigured(self):
        user_roles = api.user.get_current().getRoles()

        if 'Manager' in user_roles or 'TFE Manager' in user_roles or 'TFE Teacher' in user_roles:
            registry = queryUtility(IRegistry)
            tfe_tool = registry.forInterface(ITfemarketSettings)
            titulacions = tfe_tool.titulacions_table

            if titulacions:
                return False
            return True
        return False

    def showNumEstudiants(self):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)
        return tfe_tool.view_num_students
Ejemplo n.º 3
0
class CreateAndDeleteViewlet(grok.Viewlet):
    grok.context(IContainer)
    grok.viewletmanager(IAboveContentTitle)
    grok.view(IViewView)
Ejemplo n.º 4
0
class ForumAddForm(silvaforms.SMIAddForm):
    """Forum Add Form
    """
    grok.context(IForum)
    grok.name("Silva Forum")
Ejemplo n.º 5
0
class CommentEditForm(silvaforms.SMIEditForm):
    """Comment Edit Form.
    """
    grok.context(IComment)

    fields = silvaforms.Fields(ICommentSchema).omit('id')
Ejemplo n.º 6
0
#-*- coding:utf-8 -*-
from zope.interface import Interface
from five import grok
from plone.app.layout.viewlets.interfaces import IAboveContentTitle, IBelowContentBody

#設定viewlet介面、pt檔目錄
'''
grok.context(Interface)
grok.templatedir('templates')


class GoogleAdAboveTitle(grok.Viewlet):

    grok.viewletmanager(IAboveContentTitle)

    def available(self):
        return True


class GoogleAdBelowContentBody(grok.Viewlet):

    grok.viewletmanager(IBelowContentBody)

    def available(self):
        return True
'''

#下列可再新增viewlet, 可用的interface可查詢 plone.app.layout
Licensed under the GPL license, see LICENCE.txt for more details.
Copyright by Affinitic sprl

$Id: event.py 67630 2006-04-27 00:54:03Z jfroche $
"""
from five import grok
from zope.interface import Interface
from gites.skin.interfaces import IDerniereMinuteRootFolder
from sqlalchemy import desc
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
import random
from z3c.sqlalchemy import getSAWrapper

grok.context(Interface)
grok.templatedir('templates')


class DerniereMinuteRootFolder(grok.View):
    """
    View for the root of the derniere minute folder
    """
    grok.context(IDerniereMinuteRootFolder)
    grok.name('derniere_minute_root_folder')
    grok.require('zope2.View')

    def __init__(self, context, request, *args, **kw):
        super(DerniereMinuteRootFolder, self).__init__(context, request, *args, **kw)
        self.cat = getToolByName(self.context, 'portal_catalog')
        utool = getToolByName(context, 'portal_url')
Ejemplo n.º 8
0
class AuthorizationManager(grok.Adapter):
    grok.context(interfaces.ISilvaObject)
    grok.provides(interfaces.IAuthorizationManager)
    grok.implements(interfaces.IAuthorizationManager)

    def __init__(self, context):
        self.context = context
        self._current_user_id = getSecurityManager().getUser().getId()
        self._member = getUtility(IMemberService)
        self._group = queryUtility(IGroupService)

    def get_user_role(self, identifier=None):
        authorization = self.get_authorization(identifier=identifier)
        if authorization is None:
            return None
        return authorization.role

    def get_user_id(self, identifier=None):
        if identifier is None:
            return self._current_user_id
        return identifier

    def _get_identity(self, identifier):
        identity = self._member.get_member(identifier, location=self.context)
        if identity is None and self._group is not None:
            identity = self._group.get_group(identifier, location=self.context)
        return identity

    def get_authorization(self, identifier=None, dont_acquire=False):
        """Return authorization object for the given user. If no user
        is specified, return authorization object for the current
        authenticated user.
        """
        identifier = self.get_user_id(identifier)

        identity = self._get_identity(identifier)
        if identity is None:
            return None
        local_roles = self.context.get_local_roles_for_userid(identifier)

        acquired_roles = None
        if not dont_acquire:
            acquired_roles = []
            content = self.context
            while not interfaces.IRoot.providedBy(content):
                content = aq_parent(content)
                acquired_roles.extend(
                    content.get_local_roles_for_userid(identifier))

        return IAuthorizationFactory(identity)(self.context, self, local_roles,
                                               acquired_roles)

    def get_authorizations(self, identifiers, dont_acquire=False):
        """Return all current authorizations at this level, and
        authorization objects for given users/groups or other.
        """
        authorizations = {}
        for identifier in identifiers:
            if identifier not in authorizations:
                authorization = self.get_authorization(
                    identifier, dont_acquire=dont_acquire)
                if authorization is not None:
                    authorizations[identifier] = authorization
        return authorizations

    def get_defined_authorizations(self, dont_acquire=False):
        """Return current all authorizations at this level.
        """
        identifiers = set()
        local_roles = defaultdict(list)
        acquired_roles = defaultdict(list)

        # Collect user with roles here, tag as local_roles
        for identifier, roles in self.context.get_local_roles():
            identifiers.add(identifier)
            local_roles[identifier].extend(roles)

        if not dont_acquire:
            # Collect user with parent roles
            content = self.context
            while not interfaces.IRoot.providedBy(content):
                content = aq_parent(content)
                for identifier, roles in content.get_local_roles():
                    identifiers.add(identifier)
                    acquired_roles[identifier].extend(roles)

        auth = {}
        for identifier in identifiers:
            identity = self._get_identity(identifier)
            if identity is None:
                continue
            identity_local_roles = silva_roles(local_roles[identifier])
            identity_acquired_roles = silva_roles(acquired_roles[identifier])
            if not (identity_local_roles or identity_acquired_roles):
                # If the user doesn't have any Silva roles, we ignore it
                continue
            if dont_acquire:
                identity_acquired_roles = None

            auth[identifier] = IAuthorizationFactory(identity)(
                self.context, self, identity_local_roles,
                identity_acquired_roles)

        return auth
class View(grok.View):
    grok.context(IBoosterClub)
    grok.require("cmf.ManagePortal")
    grok.name('update-club-owner')

    def render(self):

        return self.updateClubOwner()

    def updateClubOwner(self):
        request = self.request
        context = self.context
        authenticator = getMultiAdapter((context, request),
                                        name=u"authenticator")
        if not authenticator.verify():
            raise Unauthorized

        president_id = getattr(context, 'club_president', '')

        if president_id:
            #is this a valid user?
            try:
                president_memberdata = api.user.get(userid=president_id)
            except MissingParameterError:
                api.portal.show_message(
                    message=
                    "Could not get the club president. Please contact an administrator.",
                    type='warn',
                    request=request)
                return request.response.redirect(context.absolute_url())

            current_owner = context.getOwner()
            current_owner_id = current_owner.getId()
            if president_id == current_owner_id:
                api.portal.show_message(
                    message="The club president already owns this club.",
                    type='info',
                    request=request)
                return request.response.redirect(context.absolute_url())

            portal = api.portal.get()
            plone_user = portal.acl_users.getUserById(president_id)
            context.changeOwnership(plone_user, recursive=True)
            api.user.grant_roles(user=plone_user,
                                 obj=context,
                                 roles=[
                                     'Owner',
                                 ])

            context.reindexObject()
            context.reindexObjectSecurity()

            president_fullname = president_memberdata.getProperty('fullname')

            api.portal.show_message(
                message="%s has been made the owner of this club." %
                president_fullname,
                type='info',
                request=request)

            return request.response.redirect(context.absolute_url())

        api.portal.show_message(
            message="A club president is not assigned. No change made.",
            type='warn',
            request=request)

        return request.response.redirect(context.absolute_url())
Ejemplo n.º 10
0
class setupHomePage(grok.View):
    grok.context(IPloneSiteRoot)
    grok.require('zope2.ViewManagementScreens')
    grok.name("setup-portlets")
    grok.layer(IVilaixCore)

    def render(self):
        portal = getSite()
        frontpage = portal['front-page']

        # Add portlets programatically
        from vilaix.theme.portlets.noticiaDestacada import Assignment as noticiaDestacadaAssignment
        from vilaix.theme.portlets.news import Assignment as noticiaAssignment
        from vilaix.theme.portlets.bannersportlet import Assignment as bannersVilaixAssignment
        from vilaix.theme.portlets.agendaVilaix import Assignment as agendaVilaixAssignment
        from vilaix.theme.portlets.navigationfixed import Assignment as navigationfixedAssignment
        from plone.app.event.portlets.portlet_calendar import Assignment as calendarAssignment

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager1',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments[
            'navigationfixed'] = navigationfixedAssignment(
                root='/menu-lateral')
        target_manager_assignments['bannersVilaix'] = bannersVilaixAssignment(
            content='/material-multimedia/banners/banners_esquerra')

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager2',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments[
            'noticiaDestacada'] = noticiaDestacadaAssignment()

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager3',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments['noticies'] = noticiaAssignment()

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager6',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments['bannersVilaix'] = bannersVilaixAssignment(
            content='/material-multimedia/banners/banners_dreta')

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager7',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments['agendaVilaix'] = agendaVilaixAssignment()

        target_manager = queryUtility(
            IPortletManager,
            name='genweb.portlets.HomePortletManager10',
            context=frontpage)
        target_manager_assignments = getMultiAdapter(
            (frontpage, target_manager), IPortletAssignmentMapping)
        target_manager_assignments['calendari'] = calendarAssignment(
            state='published')

        portletManager = getUtility(IPortletManager,
                                    'genweb.portlets.HomePortletManager3')
        spanstorage = getMultiAdapter((frontpage, portletManager),
                                      ISpanStorage)
        spanstorage.span = '8'

        portletManager = getUtility(IPortletManager,
                                    'genweb.portlets.HomePortletManager6')
        spanstorage = getMultiAdapter((frontpage, portletManager),
                                      ISpanStorage)
        spanstorage.span = '4'

        portletManager = getUtility(IPortletManager,
                                    'genweb.portlets.HomePortletManager7')
        spanstorage = getMultiAdapter((frontpage, portletManager),
                                      ISpanStorage)
        spanstorage.span = '8'

        portletManager = getUtility(IPortletManager,
                                    'genweb.portlets.HomePortletManager10')
        spanstorage = getMultiAdapter((frontpage, portletManager),
                                      ISpanStorage)
        spanstorage.span = '4'

        return 'Done.'
class UploadForm(form.SchemaForm):

    name = _("Import Programmes from CSV")
    schema = IUploadFormSchema
    ignoreContext = True
    grok.layer(IProductSpecific)
    grok.context(IProgrammePlanner)
    grok.name('import_programmes')
    grok.require('cmf.AddPortalContent')

    @z3c.form.button.buttonAndHandler(_("Import"), name='import')
    def import_content(self, action):
        formdata, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        f = formdata['import_file'].data.decode('utf-8')
        for l in unicode_csv_reader(StringIO(f)):
            if l[0].lower().strip() == 'title':
                continue
            if len(l) > 8:
                code = l[8]
            else:
                code = ''
            self.create(title=l[0].strip(),
                        description=l[1].strip(),
                        text=l[2].strip(),
                        startTime=l[3].strip(),
                        endTime=l[4].strip(),
                        date=parse_date(l[5]).date(),
                        event_type=l[6],
                        focus_group=l[7],
                        code=code)

    def create(self, **params):
        dest = self.context
        match = re.match(r'.*\((.*?)\)$',
                         params['title'].strip().replace('\n', ' '))
        if match:
            code = match.groups()[0].upper().strip()
        else:
            if params['code'].strip().upper():
                code = params['code'].strip().upper()
            else:
                code = None

        item = createContentInContainer(dest,
                                        'wcc.programmeplanner.programme',
                                        title=params['title'])

        item.code = code
        item.setTitle(params['title'])
        item.setDescription(params['description'])
        item.text = params['text'].replace('\n', '<br/>')
        item.startTime = params['startTime']
        item.endTime = params['endTime']
        item.date = params['date']
        item.event_type = self.parse_event_type(params['event_type'])
        item.focus_group = self.parse_focus_group(params['focus_group'])
        item.reindexObject()

    def parse_event_type(self, event_type_title):
        mapping = {
            'ecumenical conversation': 'ecumenical-conversation',
            'madang workshop': 'madang-workshop',
            'madang performance': 'madang-performance',
            'bible study': 'bible-study',
            'prayer': 'prayer',
            'plenary': 'plenary',
            'other': 'other'
        }

        if not event_type_title.lower().strip():
            return None

        val = mapping[event_type_title.lower().strip()]
        return val

    def parse_focus_group(self, focus_groups):
        mapping = {
            'inter-religious': 'inter-religious',
            'gender': 'gender',
            'indigenous people': 'indigenous-people',
            'indigenous peoples': 'indigenous-people',
            'edan': 'edan',
            'youth': 'youth'
        }
        items = [i.strip() for i in focus_groups.split(',')]

        result = []
        for i in items:
            if not i.lower().strip():
                continue
            val = mapping[i.lower().strip()]
            result.append(val)
        return result
Ejemplo n.º 12
0
class SetupView(grok.View):
    """
    """
    grok.context(Interface)
    grok.require("cmf.ManagePortal")
    grok.name("setup-inicial")
    grok.layer(IVilaixCore)

    def createOrGetObject(self, context, newid, title, type_name):
        if newid in context.contentIds():
            obj = context[newid]
        else:
            obj = createContentInContainer(context,
                                           type_name,
                                           title=title,
                                           checkConstrains=False)
            transaction.savepoint()
            if obj.id != newid:
                context.manage_renameObject(obj.id, newid)
            obj.reindexObject()
        return obj

    def newCollection(self, context, newid, title, query=None):
        collection = self.createOrGetObject(context, newid, title,
                                            u'Collection')
        if query is not None:
            collection.query = query
            collection.reindexObject()
        return collection

    def newFolder(self, context, newid, title, type_name=u'Folder'):
        return self.createOrGetObject(context, newid, title, type_name)

    def getRandomImage(self, w, h, topic=''):
        data = requests.get('http://lorempixel.com/{0}/{1}/{2}'.format(
            w, h, topic)).content
        image = NamedBlobImage(data=data,
                               filename=u'image.jpg',
                               contentType=u'image/jpeg')
        return image

    def createRandomNews(self, context, count):
        print 'creating {0} News Items'.format(count)
        for i in range(count):
            obj = createContentInContainer(context,
                                           u'News Item',
                                           title=loremipsum.get_sentence(),
                                           image=self.getRandomImage(
                                               300, 200, u'sports'))
            obj.text = RichTextValue(loremipsum.get_sentence())
            obj.destacat = False
            self.publish(obj)
            obj.reindexObject()

    def createRandomEvents(self, context, count):
        print 'creating {0} Events'.format(count)
        for i in range(count):
            obj = createContentInContainer(context,
                                           u'Event',
                                           title=loremipsum.get_sentence())
            obj.description = loremipsum.get_paragraph()
            self.publish(obj)
            obj.reindexObject()

    def createRandomBanners(self, context, count, w, h):
        print 'creating {0} Banners'.format(count)
        for i in range(count):
            obj = createContentInContainer(context,
                                           u'BannerEsports',
                                           title=loremipsum.get_sentence(),
                                           picture=self.getRandomImage(
                                               w, h, u'sports'))
            obj.description = loremipsum.get_paragraph()
            obj.url = u'http://www.upc.edu'
            self.publish(obj)
            obj.reindexObject()

    def createRandomDestacats(self, context, count, w, h, subject=[]):
        print 'creating {0} Destacats'.format(count)
        for i in range(count):
            try:
                title = loremipsum.get_sentence()
                title = re.findall('((?:\w+\s+){3})', title)[0]
            except:
                pass
            obj = createContentInContainer(context,
                                           u'Destacat',
                                           title=title,
                                           picture=self.getRandomImage(
                                               w, h, u'sports'))
            obj.text = RichTextValue(loremipsum.get_sentence())
            obj.url = u'http://www.upc.edu'
            tag0 = choice([
                'esports colectius', 'esports d'
                'adversari', 'esports individuals', 'sales d'
                'activitats', 'aules d'
                'aprenentatge'
            ])
            tag1 = choice(['futbol 11', 'futbol 7', 'futbol sala', 'basquet'])
            obj.subject = (tag0, tag1)
            self.publish(obj)
            obj.reindexObject()

    def publish(self, obj):
        workflow_tool = getToolByName(self.context, "portal_workflow")
        try:
            workflow_tool.doActionFor(obj, "publish")
        except:
            pass

    def render(self):
        """
        """
        portal = getSite()
        frontpage = portal['front-page']

        urltool = getToolByName(portal, 'portal_url')
        portal_catalog = getToolByName(portal, 'portal_catalog')
        path = urltool.getPortalPath()
        workflowTool = getToolByName(portal, "portal_workflow")
        pl = getToolByName(portal, 'portal_languages')

        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/noticies')
        if obj.actual_result_count == 0:
            noticies = self.newFolder(portal, 'noticies', 'Noticies')
            noticies.description = 'Noticies del lloc'
            noticies.exclude_from_nav = True
            self.publish(noticies)

            behavior = ISelectableConstrainTypes(noticies)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Collection', 'News Item'))
            behavior.setImmediatelyAddableTypes(('Collection', 'News Item'))

            noticies_destacades = self.newCollection(
                noticies,
                'noticies-destacades',
                u'Noticies Destacades',
                query=[{
                    u'i': u'portal_type',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': [u'News Item']
                }, {
                    u'i': u'review_state',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': u'published'
                }, {
                    u'i': u'destacat',
                    u'o': u'plone.app.querystring.operation.boolean.isTrue',
                    u'v': u'Sí'
                }])
            self.publish(noticies_destacades)

            noticies = self.newCollection(
                noticies,
                'noticies',
                u'Noticies',
                query=[{
                    u'i': u'portal_type',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': [u'News Item']
                }, {
                    u'i': u'review_state',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': u'published'
                }])
            self.publish(noticies)

        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/esdeveniments')
        if obj.actual_result_count == 0:
            esdeveniments = self.newFolder(portal, 'esdeveniments',
                                           'Esdeveniments')
            esdeveniments.description = 'Esdeveniments del lloc'
            esdeveniments.exclude_from_nav = True
            self.publish(esdeveniments)

            behavior = ISelectableConstrainTypes(esdeveniments)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Collection', 'Event'))
            behavior.setImmediatelyAddableTypes(('Collection', 'Event'))

            esdeveniments = self.newCollection(
                esdeveniments,
                'esdeveniments',
                u'Esdeveniments',
                query=[{
                    u'i': u'portal_type',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': [u'Event']
                }, {
                    u'i': u'review_state',
                    u'o': u'plone.app.querystring.operation.selection.is',
                    u'v': u'published'
                }])

            self.publish(esdeveniments)

        #Menú principal
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/menu-principal')
        if obj.actual_result_count == 0:
            menu_principal = self.newFolder(portal, 'menu-principal',
                                            u'Menú principal')
            menu_principal.language = pl.getDefaultLanguage()
            menu_principal.exclude_from_nav = True
            self.publish(menu_principal)
            alsoProvides(menu_principal, IHideFromBreadcrumbs)
            menu_principal.reindexObject()

            ajuntament = self.newFolder(menu_principal, 'ajuntament',
                                        u'Ajuntament')
            ajuntament.language = pl.getDefaultLanguage()
            self.publish(ajuntament)
            ajuntament.reindexObject()

            informacio_municipal = self.newFolder(menu_principal,
                                                  'informacio-municipal',
                                                  u'Informació Municipal')
            informacio_municipal.language = pl.getDefaultLanguage()
            self.publish(informacio_municipal)
            informacio_municipal.reindexObject()

            seu_electronica = self.newFolder(menu_principal, 'seu-electronica',
                                             u'Seu electrònica')
            seu_electronica.language = pl.getDefaultLanguage()
            self.publish(seu_electronica)
            seu_electronica.reindexObject()

            guia_de_la_ciutat = self.newFolder(menu_principal,
                                               'guia-de-la-ciutat',
                                               u'Guia de la ciutat')
            guia_de_la_ciutat.language = pl.getDefaultLanguage()
            self.publish(guia_de_la_ciutat)
            guia_de_la_ciutat.reindexObject()

            borsa_de_treball = self.newFolder(menu_principal,
                                              'borsa-de-treball',
                                              u'Borsa de treball')
            borsa_de_treball.language = pl.getDefaultLanguage()
            self.publish(borsa_de_treball)
            borsa_de_treball.reindexObject()

        #Menú Lateral
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/menu-lateral')
        if obj.actual_result_count == 0:
            menu_lateral = self.newFolder(portal, 'menu-lateral',
                                          u'Menú lateral')
            menu_lateral.language = pl.getDefaultLanguage()
            menu_lateral.exclude_from_nav = True
            self.publish(menu_lateral)
            alsoProvides(menu_lateral, IHideFromBreadcrumbs)
            menu_lateral.reindexObject()

            la_ciutat_per_temes = self.newFolder(menu_lateral,
                                                 'la-ciutat-per-temes',
                                                 u'La ciutat per temes')
            la_ciutat_per_temes.language = pl.getDefaultLanguage()
            self.publish(la_ciutat_per_temes)
            la_ciutat_per_temes.reindexObject()

            la_ciutat_per_les_persones = self.newFolder(
                menu_lateral, 'la-ciutat-per-les-persones',
                u'La ciutat i les persones')
            la_ciutat_per_les_persones.language = pl.getDefaultLanguage()
            self.publish(la_ciutat_per_les_persones)
            la_ciutat_per_les_persones.reindexObject()

            la_ciutat_en_xifres = self.newFolder(menu_lateral,
                                                 'la-ciutat-en-xifres',
                                                 u'La ciutat en xifres')
            la_ciutat_en_xifres.language = pl.getDefaultLanguage()
            self.publish(la_ciutat_en_xifres)
            la_ciutat_en_xifres.reindexObject()

            la_ciutat_per_districtes = self.newFolder(
                menu_lateral, 'la-ciutat-per-districtes',
                u'La ciutat per districtes')
            la_ciutat_per_districtes.language = pl.getDefaultLanguage()
            self.publish(la_ciutat_per_districtes)
            la_ciutat_per_districtes.reindexObject()

        #Material multimèdia
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/material-multimedia')
        if obj.actual_result_count == 0:
            material_multimedia = self.newFolder(portal, 'material-multimedia',
                                                 u'Material multimèdia')
            material_multimedia.language = pl.getDefaultLanguage()
            material_multimedia.exclude_from_nav = True
            self.publish(material_multimedia)
            material_multimedia.reindexObject()

        #Slider
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path +
                                           '/material-multimedia/sliders')
        if obj.actual_result_count == 0:
            res = portal_catalog.searchResults(id='material-multimedia')
            if res:
                material_multimedia = res[0].getObject()
            slider = self.newFolder(material_multimedia, 'sliders', u'Sliders')
            slider.language = pl.getDefaultLanguage()
            slider.exclude_from_nav = True
            self.publish(slider)
            slider.reindexObject()

            behavior = ISelectableConstrainTypes(slider)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Folder', 'Slider'))
            behavior.setImmediatelyAddableTypes(('Folder', 'Slider'))

        #Banners
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path +
                                           '/material-multimedia/banners')
        if obj.actual_result_count == 0:
            res = portal_catalog.searchResults(id='material-multimedia')
            if res:
                material_multimedia = res[0].getObject()
            banners = self.newFolder(material_multimedia, 'banners',
                                     u'Banners')
            banners.language = pl.getDefaultLanguage()
            banners.exclude_from_nav = True
            self.publish(banners)
            banners.reindexObject()

            behavior = ISelectableConstrainTypes(banners)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Banner', 'BannerContainer'))
            behavior.setImmediatelyAddableTypes(('Banner', 'BannerContainer'))

        #Carrousel
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path +
                                           '/material-multimedia/carroussel')
        if obj.actual_result_count == 0:
            res = portal_catalog.searchResults(id='material-multimedia')
            if res:
                material_multimedia = res[0].getObject()
            carroussel = self.newFolder(material_multimedia, 'carroussel',
                                        u'Carroussel')
            carroussel.language = pl.getDefaultLanguage()
            carroussel.exclude_from_nav = True
            self.publish(carroussel)
            carroussel.reindexObject()

            behavior = ISelectableConstrainTypes(carroussel)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Carrousel', 'Folder'))
            behavior.setImmediatelyAddableTypes(('Carrousel', 'Folder'))

        #Imatges Capçalera
        obj = portal_catalog.searchResults(
            portal_type='Folder',
            path=path + '/material-multimedia/imatges-capcalera')
        if obj.actual_result_count == 0:
            res = portal_catalog.searchResults(id='material-multimedia')
            if res:
                material_multimedia = res[0].getObject()
            imatges_capcalera = self.newFolder(material_multimedia,
                                               'imatges-capcalera',
                                               u'Imatges capçalera')
            imatges_capcalera.language = pl.getDefaultLanguage()
            imatges_capcalera.exclude_from_nav = True
            self.publish(imatges_capcalera)
            imatges_capcalera.reindexObject()

            behavior = ISelectableConstrainTypes(imatges_capcalera)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Folder', 'Image'))
            behavior.setImmediatelyAddableTypes(('Folder', 'Image'))

        #Banners dreta
        obj = portal_catalog.searchResults(
            portal_type='BannerContainer',
            path=path + '/material-multimedia/banners/banners_dreta')
        if obj.actual_result_count == 0:
            _createObjectByType('BannerContainer', banners, 'banners_dreta')
            banners['banners_dreta'].exclude_from_nav = True
            banners['banners_dreta'].setTitle('Banners-dreta')
            banners['banners_dreta'].reindexObject()
            workflowTool.doActionFor(banners.banners_dreta, "publish")

        #Banners esquerra
        obj = portal_catalog.searchResults(
            portal_type='BannerContainer',
            path=path + '/material-multimedia/banners/banners_esquerra')
        if obj.actual_result_count == 0:
            _createObjectByType('BannerContainer', banners, 'banners_esquerra')
            banners['banners_esquerra'].exclude_from_nav = True
            banners['banners_esquerra'].setTitle('Banners-esquerra')
            banners['banners_esquerra'].reindexObject()
            workflowTool.doActionFor(banners.banners_esquerra, "publish")

        #Documents
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/documents')
        if obj.actual_result_count == 0:
            documents = self.newFolder(portal, 'documents', u'Documents')
            documents.language = pl.getDefaultLanguage()
            documents.exclude_from_nav = True
            self.publish(documents)
            documents.reindexObject()

        #Directori equipaments
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path +
                                           '/directori-equipaments')
        if obj.actual_result_count == 0:
            directori_equipaments = self.newFolder(portal,
                                                   'directori-equipaments',
                                                   u'Directori equipaments')
            directori_equipaments.language = pl.getDefaultLanguage()
            directori_equipaments.exclude_from_nav = True
            self.publish(directori_equipaments)
            directori_equipaments.reindexObject()

            behavior = ISelectableConstrainTypes(directori_equipaments)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Folder', 'Equipament'))
            behavior.setImmediatelyAddableTypes(('Folder', 'Equipament'))

        #Tràmits
        obj = portal_catalog.searchResults(portal_type='Folder',
                                           path=path + '/tramits')
        if obj.actual_result_count == 0:
            tramits = self.newFolder(portal, 'tramits', u'Tràmits')
            tramits.language = pl.getDefaultLanguage()
            tramits.exclude_from_nav = True
            self.publish(tramits)
            tramits.reindexObject()

            behavior = ISelectableConstrainTypes(tramits)
            behavior.setConstrainTypesMode(1)
            behavior.setLocallyAllowedTypes(('Folder', 'Tramit'))
            behavior.setImmediatelyAddableTypes(('Folder', 'Tramit'))

        # # Add portlets programatically
        # from vilaix.theme.portlets.noticiaDestacada import Assignment as noticiaDestacadaAssignment
        # from vilaix.theme.portlets.news import Assignment as noticiaAssignment
        # from vilaix.theme.portlets.bannersportlet import Assignment as bannersVilaixAssignment
        # from vilaix.theme.portlets.agendaVilaix import Assignment as agendaVilaixAssignment
        # from vilaix.theme.portlets.navigationfixed import Assignment as navigationfixedAssignment
        # from plone.app.event.portlets.portlet_calendar import Assignment as calendarAssignment

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager1', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['navigationfixed'] = navigationfixedAssignment(root='/menu-lateral')
        # target_manager_assignments['bannersVilaix'] = bannersVilaixAssignment(content='/material-multimedia/banners/banners_esquerra')

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager2', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['noticiaDestacada'] = noticiaDestacadaAssignment()

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager3', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['noticies'] = noticiaAssignment()

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager6', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['bannersVilaix'] = bannersVilaixAssignment(content='/material-multimedia/banners/banners_dreta')

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager7', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['agendaVilaix'] = agendaVilaixAssignment()

        # target_manager = queryUtility(IPortletManager, name='genweb.portlets.HomePortletManager10', context=frontpage)
        # target_manager_assignments = getMultiAdapter((frontpage, target_manager), IPortletAssignmentMapping)
        # target_manager_assignments['calendari'] = calendarAssignment(state='published')

        # portletManager = getUtility(IPortletManager, 'genweb.portlets.HomePortletManager3')
        # spanstorage = getMultiAdapter((frontpage, portletManager), ISpanStorage)
        # spanstorage.span = '8'

        # portletManager = getUtility(IPortletManager, 'genweb.portlets.HomePortletManager6')
        # spanstorage = getMultiAdapter((frontpage, portletManager), ISpanStorage)
        # spanstorage.span = '4'

        # portletManager = getUtility(IPortletManager, 'genweb.portlets.HomePortletManager7')
        # spanstorage = getMultiAdapter((frontpage, portletManager), ISpanStorage)
        # spanstorage.span = '8'

        # portletManager = getUtility(IPortletManager, 'genweb.portlets.HomePortletManager10')
        # spanstorage = getMultiAdapter((frontpage, portletManager), ISpanStorage)
        # spanstorage.span = '4'

        return 'Created'
Ejemplo n.º 13
0
class PublicationAddForm(FolderAddForm):
    grok.context(IPublication)
    grok.name('Silva Publication')
Ejemplo n.º 14
0
from zope.interface import implements, Interface

from Products.CMFCore.utils import getToolByName

from five import grok

from msd.landingpage import landingpageMessageFactory as _

# Import BlocksView
from msd.landingpage.browser.blocksview import LayoutView, ILayoutView
from msd.landingpage.layout import Block

from msd.landingpage.interfaces import ILandingPage

# All layout views are available for landing page content only
grok.context(ILandingPage)

grok.templatedir("layout_templates")

# Layout views must inherit from LayoutView
class Layout1(LayoutView):
    """
    SampleLayout browser view
    """
    icon = "layout1.png"
    title = _(u"Three horizontal")
    
    # blocks are defined by Block objects
    # parameters are: direction, (width without portlets, width with one portlet column, width with two portlet columns)
    block_definitions = [ Block(Block.HORIZONTAL,
                                (24, 18, 12),
Ejemplo n.º 15
0
class PersonalCampaignPageCompactView(CampaignView):
    grok.context(IPersonalCampaignPage)
    grok.require('zope2.View')

    grok.name('compact_view')
    grok.template('compact_view')
Ejemplo n.º 16
0
class View(grok.View):
    grok.context(IMainContributing)
    grok.template('maincontributing_view')
    grok.require('zope2.View')
Ejemplo n.º 17
0
import logging
import datetime

import zope.interface
from zope.component import getMultiAdapter
from zope.app.component.hooks import getSite 

from collective.templateengines.interfaces import ITag

from five import grok

from plone.app.discussion.interfaces import IConversation

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

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

logger = logging.getLogger("mobipublic")

class FrontPageBlockTag(object):
    """ """
    zope.interface.implements(ITag)
    
    def getName(self):
        return "front_page_block"
    
    def render(self, scriptingContext, path, itemPortalType, itemPortalType2, folderPortalType, title, slotTitle, itemCount, slotCount):
        """ """
        
Ejemplo n.º 18
0
class View(dexterity.DisplayForm):
    grok.context(IRoomfolder)
    grok.require('zope2.View')

    def canRequestReview(self):
        return checkPermission('cmf.RequestReview', self.context)
Ejemplo n.º 19
0
# encoding: utf-8
# Copyright 2013–2016 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.

from Acquisition import aq_inner
from edrnsite.vanity import VANITY_UPDATE_KEY, BESPOKE_WELCOME, BESPOKE_OLD
from five import grok
from plone.app.layout.viewlets.interfaces import IPortalTop
from Products.CMFCore.interfaces import IContentish
from Products.CMFCore.utils import getToolByName


grok.context(IContentish)
grok.templatedir('templates')


class VanityReminderViewlet(grok.Viewlet):
    '''Viewlet that adds a jquery UI overlay to remind you to visit your vanity page.'''
    grok.viewletmanager(IPortalTop)
    def _getNag(self):
        context = aq_inner(self.context)
        smd = getToolByName(context, 'session_data_manager')
        session = smd.getSessionData(create=False)
        return session.get(VANITY_UPDATE_KEY, None) if session else None
    def needsToVisit(self):
        return self._getNag() == BESPOKE_WELCOME
    def needsToUpdate(self):
        return self._getNag() == BESPOKE_OLD
Ejemplo n.º 20
0
class ResourceBaseForm(GroupForm, form.Form):
    """Baseform for all forms that work with resources as their context.
    Provides helpful functions to all of them.

    """
    grok.baseclass()
    grok.context(IResourceBase)
    grok.layer(ISeantisReservationSpecific)

    ignoreContext = True
    ignore_requirements = False

    disabled_fields = []
    hidden_fields = ['id']

    context_buttons = tuple()
    destructive_buttons = tuple()
    standalone_buttons = tuple()

    css_class = 'seantis-reservation-form wizard'

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

    def updateWidgets(self):
        super(ResourceBaseForm, self).updateWidgets()

        # Hide fields found in self.hidden_fields
        for f in self.hidden_fields:
            if f in self.widgets:
                self.widgets[f].mode = interfaces.HIDDEN_MODE

        # Forces the wigets to completely ignore requirements
        if self.ignore_requirements:
            self.widgets.hasRequiredFields = False

    def disable_fields(self):
        """ Disables the fields in self.disabled_fields (by name). Be careful
        using this, as disabled fields are not submitted back from the form.

        It's the job of the individual form to deal with those unsbumitted
        values.

        See ReservationForm.inject_missing_data

        If this feature is used more extensively, it would make sense
        to provide a callback-mechanism on this baseform to abstract away
        the inject_missing_data stuff and make it more fool-proof.

        """

        # Disable fields
        for f in self.disabled_fields:
            if f in self.widgets:
                self.widgets[f].readonly = 'readonly'
                self.widgets[f].disabled = 'disabled'

        for group in self.groups:
            for f in self.disabled_fields:
                if f in group.widgets:
                    group.widgets[f].readonly = 'readonly'
                    group.widgets[f].disabled = 'disabled'

    def get_field(self, key):
        """ Returns a field either from self.fields or from any group. """

        if key in self.fields:
            return self.fields[key].field

        for group in self.groups:
            if key in group.fields:
                return group.fields[key].field

        return None

    def get_widget(self, key):
        """ Returns a widget either from self.widgets or from any group. """

        if key in self.widgets:
            return self.widgets[key]

        for group in self.groups:
            if key in group.widgets:
                return group.widgets[key]

    def defaults(self):
        return {}

    def set_widget(self, key, value):
        f = self.get_field(key)
        if not f:
            return

        w = self.get_widget(key)
        if not w:
            return

        converter = getMultiAdapter((f, w))

        # z3c forms will work with all the widgets except radio and checkboxes
        # the docs hint at differences, but I can for the
        # life of me not figure out what I should actually be doing.
        #
        # friends don't let friends use z3c.forms
        #
        # this atrocity forces the right rendering
        #
        # => TODO change to normal code
        widget_type = type(w).__name__
        if widget_type.endswith(('CheckBoxWidget', 'RadioWidget')):
            values = converter.toWidgetValue(value)
            for item in w.items:
                if item['value'] in values:
                    item['checked'] = 'checked'
                else:
                    item['checked'] = False
        else:
            w.value = converter.toWidgetValue(value)

        return True

    def apply_defaults(self):

        start, end = self.start, self.end
        if start and end:
            values = {
                'day': start.date(),
                'start_time': start.time(),
                'end_time': end.time()
            }

            for key, value in values.items():
                self.set_widget(key, value)

        other_defaults = self.defaults()
        for k, v in other_defaults.items():
            assert self.set_widget(k, v), "invalid default field %s" % k

    def adjust_date_ranges(self):
        """ Someone thought it was a good idea to have plone date widgets
        default to a daterange of ten years in the past, ten years in the
        future.

        This code undoes that on all widgets used for custom fields.

        """
        sane_range = (-100, 10)

        for group in self.groups:
            for widget in group.widgets.values():
                if hasattr(widget, 'years_range'):
                    widget.years_range = sane_range

    def redirect_to_context(self, view=None):
        """ Redirect to the url of the resource. """
        if view:
            url = '/'.join((self.context.absolute_url(), view))
        else:
            url = self.context.absolute_url()

        self.request.response.redirect(url)

    @property
    @utils.memoize
    def scheduler(self):
        """ Returns the scheduler of the resource. """
        language = utils.get_current_language(self.context, self.request)
        return self.context.scheduler(language=language)

    @property
    @from_timestamp
    def start(self):
        if 'start' in self.request:
            return self.request['start']
        elif self.updateWidgets and 'start' in self.widgets:
            widget = self.widgets['start']
            if all(widget.day, widget.month, widget.year):
                return widget.value

        return None

    @property
    @from_timestamp
    def end(self):
        if 'end' in self.request:
            return self.request['end']
        elif self.updateWidgets and 'end' in self.widgets:
            widget = self.widgets['end']
            if all(widget.day, widget.month, widget.year):
                return widget.value

        return None

    @property
    def id(self):
        if 'id' in self.request:
            value = self.request['id']
        elif self.widgets and 'id' in self.widgets:
            value = self.widgets['id'].value
        else:
            return 0

        if value in (None, u'', ''):
            return 0
        else:
            return utils.request_id_as_int(value)

    @property
    def group(self):
        if 'group' in self.request:
            group = self.request['group']
        elif self.widgets and 'group' in self.widgets:
            group = self.widgets['group'].value
        else:
            group = None

        if isinstance(group, six.string_types):
            return six.text_type(group.decode('utf-8'))
        else:
            return group and ','.join(group) or u''

    def flash(self, message, type='info'):
        utils.flash(self.context, message, type)

    def updateFields(self):
        self.form.groups = []

        if not hasattr(self, 'additionalSchemata'):
            return

        for prefix, group, schema in self.additionalSchemata:
            fields = field.Fields(schema, prefix=prefix)

            if hasattr(self, 'customize_fields'):
                self.customize_fields(fields)

            z3cutils.add(self.form, fields, group=group)

    def updateActions(self):
        super(ResourceBaseForm, self).updateActions()

        for button in self.context_buttons:
            self.actions[button].addClass("context")

        for button in self.destructive_buttons:
            self.actions[button].addClass("destructive")

        for button in self.standalone_buttons:
            self.actions[button].addClass("standalone")

    def update(self, **kwargs):
        self.updateFields()

        super(ResourceBaseForm, self).update(**kwargs)

        self.apply_defaults()
        self.disable_fields()
        self.adjust_date_ranges()
Ejemplo n.º 21
0
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName

from zope.component import getMultiAdapter, queryMultiAdapter
from zope.interface import Interface
from zope.security import checkPermission

from msd.landingpage.interfaces import ILittleBlock

from lxml import html as lxml_html
from lxml import etree
import urlparse

grok.templatedir("block_templates")

grok.context(ILittleBlock)


class BaseBlockView(grok.View):
    grok.baseclass()

    def __init__(self, *args):

        super(BaseBlockView, self).__init__(*args)
        # Set defaults for width and isLast
        self.width = 18
        self.isLast = True

    def setUnitWidth(self, width):
        """
        @param: width = 0...24
Ejemplo n.º 22
0
class ProfileRegistrationForm(form.SchemaForm, FridgeForm):
    grok.name('registration')
    grok.require('zope2.View')
    grok.context(IRegistrator)

    schema = IRegistration

    ignoreContext = True
    id = "ProfileRegistrationForm"
    label = _(u"profile_registration_form_title")
    description = _(u"profile_registration_form_description")

    def __init__(self, context, request):
        super(ProfileRegistrationForm, self).__init__(context, request)

        portal_state = getMultiAdapter((context, request),
                                       name=u'plone_portal_state')
        self.schema['accept_terms'].description = \
            _(u"accept_link_form_help",
            mapping={'link': '%s/agb' % portal_state.portal_url()})

    def _redirect(self, target=''):
        if not target:
            portal_state = getMultiAdapter((self.context, self.request),
                                           name=u'plone_portal_state')
            target = portal_state.portal_url()
        self.request.response.redirect(target)

    @button.buttonAndHandler(_(u"save_profile_form_button"), name='submit')
    def handle_apply(self, action):
        data, errors = self.extractData()

        if errors:
            return

        fridgemanager = IFridgeManager(self.context)
        user_data = fridgemanager.get_entry_payload(data['fridge_rand'])

        if user_data is not None:
            # Testing uniqueness of username
            portal = getSite()
            pas_tool = getToolByName(portal, 'acl_users')
            members = pas_tool.getUserById(data['username'])
            if members is not None:
                raise forminterfaces.WidgetActionExecutionError(
                    'username',
                    interface.Invalid(_(u"username_invalid_error")))

            # Add member: We store username, password and email-address in the
            # default Plone member profile. All other member properties
            # (description, location, home_page, newsletter, etc.) are stored in
            # the Dexterity-based memberfolder.
            roles = []
            domains = []

            mtool = getToolByName(portal, 'portal_membership')
            password = data['password']
            if isinstance(password, unicode):
                password = password.encode('utf-8')
            mtool.addMember(data['username'], password, roles, domains)
            mtool.createMemberarea(data['username'])
            membersfolder = mtool.getMembersFolder()

            memberfolder = membersfolder[data['username']]
            memberfolder.title = data['fullname']
            memberfolder.description = data['description']
            memberfolder.location = data['location']
            memberfolder.home_page = data['home_page']
            memberfolder.portrait = data['portrait']
            memberfolder.newsletter = data['newsletter']

            memberfolder.email = user_data['email']

            notify(ObjectModifiedEvent(memberfolder))
            memberfolder.reindexObject()

            # Remove the fridge entry
            fridgemanager.delete_entry(data['fridge_rand'])

            # Log the new member in
            pas_tool.session._setupSession(data['username'].encode("utf-8"),
                                           self.request.RESPONSE)

            IStatusMessage(self.request).add(_(
                u'profile_registration_success_notification',
                default="Registration success"),
                                             type='info')
        else:
            IStatusMessage(self.request).add(
                _(u'profile_registration_expired_or_invalid_notification'),
                type='error')

        return self._redirect()

    @button.buttonAndHandler(_(u'cancel_form_button'), name='cancel')
    def handle_cancel(self, action):
        IStatusMessage(self.request).add(
            _(u'profile_registration_cancel_notification'), type='info')
        return self._redirect()

    def updateFields(self):
        super(ProfileRegistrationForm, self).updateFields()
        self.fields['newsletter'].widgetFactory = \
            SingleCheckBoxFieldWidget
        self.fields['accept_terms'].widgetFactory = \
            SingleCheckBoxFieldWidget

    def updateWidgets(self):
        super(ProfileRegistrationForm, self).updateWidgets()
        self.widgets['home_page'].addClass("url")
Ejemplo n.º 23
0
class TopicAddForm(silvaforms.SMIAddForm):
    """Topic Add Form
    """
    grok.context(ITopic)
    grok.name('Silva Forum Topic')
Ejemplo n.º 24
0
class AddMeetingDossierView(WizzardWrappedAddForm):
    grok.context(IRepositoryFolder)
    grok.name('add-meeting-dossier')

    typename = 'opengever.meeting.meetingdossier'

    def _create_form_class(self, parent_form_class, steptitle):
        class WrappedForm(BaseWizardStepForm, parent_form_class):
            step_name = 'add-meeting-dossier'
            step_title = steptitle
            steps = ADD_MEETING_STEPS
            label = _(u'Add Dossier for Meeting')

            passed_data = ['committee-oguid']

            @buttonAndHandler(pd_mf(u'Save'), name='save')
            def handleAdd(self, action):
                # create the dossier
                data, errors = self.extractData()
                if errors:
                    self.status = self.formErrorsMessage
                    return

                committee_oguid = get_committee_oguid()
                dossier = self.create_meeting_dossier(data)
                meeting = self.create_meeting(dossier, committee_oguid)

                api.portal.show_message(
                    _(u"The meeting and its dossier were created successfully"),
                    request=self.request,
                    type="info")

                committee = committee_oguid.resolve_object()
                return self.request.RESPONSE.redirect(
                    '{}#meetings'.format(committee.absolute_url()))

            @buttonAndHandler(pd_mf(u'Cancel'), name='cancel')
            def handleCancel(self, action):
                committee_oguid = get_committee_oguid()

                dm = getUtility(IWizardDataStorage)
                dm.drop_data(get_dm_key(committee_oguid))

                committee = committee_oguid.resolve_object()
                return self.request.RESPONSE.redirect(committee.absolute_url())

            def create_meeting_dossier(self, data):
                obj = self.createAndAdd(data)
                if obj is not None:
                    # mark only as finished if we get the new object
                    self._finishedAdd = True
                return obj

            def create_meeting(self, dossier, committee_oguid):
                dm = getUtility(IWizardDataStorage)
                data = dm.get_data(get_dm_key())
                data['dossier_oguid'] = Oguid.for_object(dossier)
                meeting = Meeting(**data)
                meeting.initialize_participants()
                session = create_session()
                session.add(meeting)
                session.flush()  # required to create an autoincremented id

                dm.drop_data(get_dm_key())
                return meeting

        return WrappedForm

    def __call__(self):
        title_key = 'form.widgets.IOpenGeverBase.title'

        if title_key not in self.request.form:
            dm = getUtility(IWizardDataStorage)
            data = dm.get_data(get_dm_key())

            start_date = api.portal.get_localized_time(datetime=data['start'])
            default_title = _(u'Meeting on ${date}',
                              mapping={'date': start_date})
            self.request.set(title_key, default_title)

        return super(AddMeetingDossierView, self).__call__()
Ejemplo n.º 25
0
class GlobalTaskListingTab(grok.View, OpengeverTab, ListingView):
    """A tabbed view mixing which brings support for listing tasks from
    the SQL (globally over all clients).

    There is support for searching, batching and ordering.
    """

    implements(IGlobalTaskTableSourceConfig)

    grok.context(IJournalizable)
    grok.require('zope2.View')

    template = ViewPageTemplateFile("generic_task.pt")

    sort_on = 'modified'
    sort_reverse = False
    #lazy must be false otherwise there will be no correct batching
    lazy = False

    # the model attributes is used for a dynamic textfiltering functionality
    model = Task
    enabled_actions = []
    major_actions = []

    select_all_template = ViewPageTemplateFile('select_all_globaltasks.pt')
    selection = ViewPageTemplateFile("selection_tasks.pt")

    open_states = [
        'task-state-open',
        'task-state-in-progress',
        'task-state-resolved',
        'task-state-rejected',
        'forwarding-state-open',
        'forwarding-state-refused',
    ]

    state_filter_name = 'task_state_filter'

    columns = (
        ('', task_id_checkbox_helper),
        {
            'column': 'review_state',
            'column_title': _(u'column_review_state', default=u'Review state'),
            'transform': workflow_state
        },
        {
            'column': 'title',
            'column_title': _(u'column_title', default=u'Title'),
            'transform': indexed_task_link_helper
        },
        {
            'column': 'task_type',
            'column_title': _(u'column_task_type', default=u'Task type'),
            'transform': task_type_helper
        },
        {
            'column': 'deadline',
            'column_title': _(u'column_deadline', default=u'Deadline'),
            'transform': overdue_date_helper
        },
        {
            'column':
            'completed',
            'column_title':
            _(u'column_date_of_completion', default=u'Date of completion'),
            'transform':
            readable_date_set_invisibles
        },
        {
            'column': 'responsible',
            'column_title': _(u'label_responsible_task',
                              default=u'Responsible'),
            'transform': readable_ogds_author
        },
        {
            'column': 'issuer',
            'column_title': _(u'label_issuer', default=u'Issuer'),
            'transform': readable_ogds_author
        },
        {
            'column': 'created',
            'column_title': _(u'column_issued_at', default=u'Issued at'),
            'transform': helper.readable_date
        },
        {
            'column': 'containing_dossier',
            'column_title': _('containing_dossier', 'Dossier'),
        },
        {
            'column': 'client_id',
            'column_title': _('column_client', default=u'Client'),
            'transform': client_title_helper,
            'condition': display_client_title_condition
        },
        {
            'column':
            'sequence_number',
            'column_title':
            _(u'column_sequence_number', default=u'Sequence number')
        },
    )

    __call__ = ListingView.__call__
    update = ListingView.update
    render = __call__
Ejemplo n.º 26
0
class Overview(DisplayForm, OpengeverTab):
    grok.context(ITask)
    grok.name('tabbedview_view-overview')
    grok.template('overview')

    def get_type(self, item):
        """differ the object typ and return the type as string
        """
        if not item:
            return None
        elif isinstance(item, dict):
            return 'dict'
        elif isinstance(item, Task) or ITask.providedBy(item):
            return 'task'
        else:
            return 'obj'

    def boxes(self):
        """ Return the boxes in the overview splittet in two columns
        """
        items = [
            [
                dict(id='main_attributes',
                     label=_(u'label_main_attributes',
                             default="Main Atrributes"),
                     content=self.get_main_attributes()),
                dict(id='documents',
                     label=_(u'label_documents', default="Documents"),
                     content=self.documents()),
            ],
            [
                dict(id='containing_task',
                     label=_(u'label_containing_task',
                             default="Containing tasks"),
                     content=self.get_containing_task()),
                dict(id='sub_task',
                     label=_(u'label_sub_task', default="Sub tasks"),
                     content=self.get_sub_tasks()),
                dict(id='predecessor_task',
                     label=_(u'label_predecessor_task',
                             default="Predecessor task"),
                     content=self.get_predecessor_task()),
                dict(id='successor_tasks',
                     label=_(u'label_successor_task',
                             default="Successor task"),
                     content=self.get_successor_tasks()),
            ],
        ]
        return items

    def documents(self):
        """ Return containing documents and related documents
        """
        def _get_documents():
            """ Return documents in this task and subtasks
            """
            documents = getToolByName(self.context, 'portal_catalog')(
                portal_type=[
                    'opengever.document.document',
                    'ftw.mail.mail',
                ],
                path=dict(depth=2,
                          query='/'.join(self.context.getPhysicalPath())),
            )
            return [document.getObject() for document in documents]

        def _get_related_documents():
            """ Return related documents in this task
            """
            # Related documents
            related_documents = []
            for item in self.context.relatedItems:
                obj = item.to_object
                if obj.portal_type in [
                        'opengever.document.document', 'ftw.mail.mail'
                ]:
                    obj._v__is_relation = True
                    related_documents.append(obj)
            return related_documents

        # merge and sort the two different lists
        document_list = _get_documents() + _get_related_documents()
        document_list.sort(lambda a, b: cmp(b.modified(), a.modified()))

        return document_list

    def get_main_attributes(self):
        """ return a list of widgets,
        which should be displayed in the attributes box
        """
        def _get_state():
            state = getToolByName(self.context, 'portal_workflow').getInfoFor(
                self.context, 'review_state')

            return "<span class=wf-%s>%s</span>" % (
                state,
                translate(state, domain='plone', context=self.request),
            )

        def _get_parent_dossier_title():
            finder = queryAdapter(self.context, name='parent-dossier-finder')
            if not finder:
                return

            dossier = finder.find_dossier()
            if not dossier:
                return None

            return dossier.Title()

        def _get_issuer():
            info = getUtility(IContactInformation)
            task = ITask(self.context)

            if info.is_one_client_setup():
                return info.render_link(task.issuer)

            client_id = get_client_id()
            predecessors = self.get_predecessor_task()

            if predecessors and \
                predecessors[0].task_type != 'forwarding_task_type':
                client_id = predecessors[0].client_id

            client = client_title_helper(task, client_id)

            return client + ' / ' + info.render_link(task.issuer)

        def _get_task_widget_value(attr):
            field = ITask.get(attr)
            field = Field(field, interface=field.interface, prefix='')
            return get_field_widget(self.context, field).render()

        items = [
            {
                'label': _('label_task_title'),
                'value': _get_task_widget_value('title'),
            },
            {
                'label': _('label_parent_dossier_title'),
                'value': _get_parent_dossier_title(),
            },
            {
                'label': _(u"label_text", default=u"Text"),
                'value': _get_task_widget_value('text'),
            },
            {
                'label': _(u'label_task_type', default=u'Task Type'),
                'value': _get_task_widget_value('task_type'),
            },
            {
                'label': _('label_workflow_state'),
                'value': _get_state(),
            },
            {
                'label': _(u"label_deadline", default=u"Deadline"),
                'value': _get_task_widget_value('deadline'),
            },
            {
                'label': _(u"label_issuer", default=u"Issuer"),
                'css_class': "issuer",
                'value': _get_issuer(),
            },
            {
                'label': _(u"label_responsible", default=u"Responsible"),
                'value': self.get_task_info(self.context),
            },
            {
                'label':
                _(u"label_date_of_completion", default=u"Date of completion"),
                'value':
                _get_task_widget_value('date_of_completion'),
            },
        ]

        return items

    def get_css_class(self, item):
        """Return the sprite-css-class for the given object.
        """
        css = get_css_class(item)
        return '%s %s' % ("rollover-breadcrumb", css)

    def get_sub_tasks(self):
        """ Return the subtasks
        """
        tasks = self.context.getFolderContents(
            full_objects=True,
            contentFilter={'portal_type': 'opengever.task.task'},
        )
        return tasks

    def get_containing_task(self):
        """ Get the parent-tasks if we have one
        """
        parent = aq_parent(aq_inner(self.context))
        if ITask.providedBy(parent):
            return [parent]
        return []

    def get_predecessor_task(self):
        """ Get the original task
        """
        controller = ISuccessorTaskController(self.context)
        task = controller.get_predecessor()
        # box rendering need a list
        if not task:
            return []
        return [task]

    def get_successor_tasks(self):
        """ Get the task from which this task was copied
        """
        controller = ISuccessorTaskController(self.context)
        return controller.get_successors()

    def get_task_info(self, item):
        """ return some task attributes for objects:
            Responsible client ID /  responsible
        """
        if not ITask.providedBy(item):
            return ''

        info = getUtility(IContactInformation)

        if not item.responsible_client or len(info.get_clients()) <= 1:
            # No responsible client is set yet or we have a single client
            # setup.
            return info.describe(item.responsible)

        # Client
        client = client_title_helper(item, item.responsible_client)

        taskinfo = "%s / %s" % (
            client,
            info.render_link(item.responsible),
        )

        return taskinfo.encode('utf-8')

    def render_task(self, item):
        """ Render the taskobject
        """
        if isinstance(item, Task):
            # Its a task stored in sql
            return self._sqlalchemy_task_link(item)

        elif ITask.providedBy(item):
            # Its a normal task object
            return self._object_task_link(item)

        else:
            return None

    def _object_task_link(self, item):
        """ Renders a task object with a link to the effective task
        We have two different types of a task. task-object from the sql-db is
        handled in the _sqlalchemy_task_link-method.
        """
        breadcrumb_titles = "[%s] > %s" % (client_title_helper(
            item, item.responsible_client).encode('utf-8'), ' > '.join(
                _breadcrumbs_from_item(item)))

        info_html = self.get_task_info(item)
        task_html = \
            '<a href="%s" title="%s"><span class="%s">%s</span></a>' % (
                item.absolute_url(),
                breadcrumb_titles,
                self.get_css_class(item),
                item.Title(),
            )
        inner_html = '%s <span class="discreet">(%s)</span>' % (task_html,
                                                                info_html)

        return self._task_state_wrapper(item, inner_html)

    def _sqlalchemy_task_link(self, item):
        """Renders a indexed task item (globalindex sqlalchemy object) either
        with a link to the effective task (if the user has access) or just with
        the title.
        We have two different types of a task. task-object providing the
        ITask-interface is handled in the _object_task_link.
        """

        css_class = self.get_css_class(item)

        # get the client which the task cames from
        info = queryUtility(IContactInformation)
        if info:
            client = info.get_client_by_id(item.client_id)
        if not info or not client:
            return '<span class="%s">%s</span>' % (css_class, item.title)

        # has the user access to the target task?
        has_access = False
        mtool = getToolByName(self.context, 'portal_membership')
        member = mtool.getAuthenticatedMember()

        if member:
            principals = set(member.getGroups() + [member.getId()])
            allowed_principals = set(item.principals)
            has_access = len(principals & allowed_principals) > 0

        # If the target is on a different client we need to make a popup
        if item.client_id != get_client_id():
            link_target = ' target="_blank"'
            url = '%s/%s' % (client.public_url, item.physical_path)
        else:
            link_target = ''
            url = client.public_url + '/' + item.physical_path

        # create breadcrumbs including the (possibly remote) client title
        breadcrumb_titles = "[%s] > %s" % (client.title, item.breadcrumb_title)

        # Client and user info
        info_html = ' <span class="discreet">(%s / %s)</span>' % (
            client_title_helper(item, item.assigned_client),
            info.render_link(item.responsible),
        )

        # Link to the task object
        task_html = '<span class="%s">%s</span>' % \
                        (css_class, item.title)

        # Render the full link if we have acccess
        if has_access:
            inner_html = '<a href="%s"%s title="%s">%s</a> %s' % (
                url, link_target, breadcrumb_titles, task_html, info_html)
        else:
            inner_html = '%s %s' % (task_html, info_html)

        # Add the task-state css and return it
        return self._task_state_wrapper(item, inner_html)

    def _task_state_wrapper(self, item, text):
        """ Wrap a span-tag around the text with the status-css class
        """
        if isinstance(item, Task):
            # Its a sql-task-object
            state = item.review_state
        elif ITask.providedBy(item):
            # Its a task-object
            state = getToolByName(self.context, 'portal_workflow').getInfoFor(
                item, 'review_state')
        else:
            return ''
        return '<span class="wf-%s">%s</span>' % (state, text)
Ejemplo n.º 27
0
class DirectoryCatalog(grok.Adapter):

    grok.context(IDirectoryBase)
    grok.provides(IDirectoryCatalog)

    def __init__(self, context):
        self.directory = context
        self.catalog = getToolByName(context, 'portal_catalog')
        self.path = '/'.join(context.getPhysicalPath())

    def query(self, **kwargs):
        """Runs a query on the catalog with default parameters set.
        Not part of the official IDirectoryCatalog interface as this is
        highly storage_backend dependent. """
        results = self.catalog(
            path={
                'query': self.path,
                'depth': 1
            },
            object_provides=IDirectoryItemLike.__identifier__,
            **kwargs)
        return results

    def sortkey(self):
        """Returns the default sortkey."""
        uca_sortkey = utils.unicode_collate_sortkey()
        return lambda b: uca_sortkey(b.Title.decode('utf-8'))

    def items(self):
        return sorted(self.query(), key=self.sortkey())

    def filter(self, term):
        results = self.query(categories={
            'query': term.values(),
            'operator': 'and'
        })
        filter_key = partial(is_exact_match, term=term)

        return sorted(filter(filter_key, results), key=self.sortkey())

    def search(self, text):

        # remove the fuzzy-search first
        text = text.replace('*', '')

        # wrap the text in quotes so the query parser ignores the content
        # (the user should not be able to get his text inspected by the
        # query parser, because it's a hidden feature at best and a security
        # problem at worst)
        #
        # add a wildcard at the end for fuzzyness
        text = '"{}*"'.format(text)

        return sorted(self.query(SearchableText=text), key=self.sortkey())

    def possible_values(self, items=None, categories=None):
        """Returns a dictionary with the keys being the categories of the
        directory, filled with a list of all possible values for each category.
        If an item contains a list of values (as opposed to a single string)
        those values flattened. In other words, there is no hierarchy in the
        resulting list.

        """
        items = items or self.query()
        categories = categories or self.directory.all_categories()

        values = dict([(c, list()) for c in categories])
        for item in items:
            for key, label, value in item.categories:
                if not key in categories:
                    continue

                if not value:
                    continue

                if isinstance(value, basestring):
                    values[key].append(value)
                else:
                    map(values[key].append, utils.flatten(value))

        return values

    def grouped_possible_values(self, items=None, categories=None):
        """Same as possible_values, but with the categories of the dictionary
        being unique and each value being wrapped in a tuple with the first
        element as the actual value and the second element as the count
        non-unique values.

        It's really the grouped result of possible_values.

        """

        possible = self.possible_values(items, categories)
        grouped = dict([(k, dict()) for k in possible.keys()])

        for category, items in possible.items():
            groups = groupby(sorted(items))
            for group, values in groups:
                grouped[category][group] = len(list(values))

        return grouped

    def grouped_possible_values_counted(self, items=None, categories=None):
        """Returns a dictionary of categories with a list of possible values
        including counts in brackets.

        """
        possible = self.grouped_possible_values(items, categories)
        result = dict((k, []) for k in possible.keys())

        for category, values in possible.items():
            counted = []
            for text, count in values.items():
                counted.append(utils.add_count(text, count))

            result[category] = sorted(counted,
                                      key=utils.unicode_collate_sortkey())

        return result
Ejemplo n.º 28
0
class BoaPraticaView(form.SchemaForm):
    grok.context(IBoaPratica)
    grok.require('zope2.View')
    grok.name('boapratica-view')

    schema = ICommentPraticaView
    ignoreContext = True

    def update(self):
        self.request.set('disable_border', 1)
        return super(BoaPraticaView, self).update()

    @button.buttonAndHandler(u'Comentar')
    def handleApply(self, action):
        data, errors = self.extractData()

        if errors:
            self.status = self.formErrorsMessage
            return

        messages = IStatusMessage(self.request)
        messages.add(u"Obrigado. Seu comentário foi enviado para aprovação.",
                     type=u"info")

        nome = data['nome']
        email = data['email']
        comentario = data['comentario']

        title = '{0} - {1}'.format(nome, email)

        normalizer = getUtility(IIDNormalizer)
        objid = self.generateIdForContext(self.context,
                                          normalizer.normalize(title))

        pt = api.portal.get_tool('portal_types')
        type_info = pt.getTypeInfo('Comentario')
        content = type_info._constructInstance(self.context,
                                               objid,
                                               title=title)
        content.setNome(nome)
        content.setEmail(email)
        content.setCreated(datetime.datetime.now())
        content.setComentario(comentario)

        return self.request.response.redirect(self.context.absolute_url())

    def generateIdForContext(self, ctx, id, count=0):
        """
            Método que gera um id para um objeto dentro do contexto,
            caso o id já exista no contexto ele adiciona numero na frente

            @param ctx: Contexto para qual será gerado o Id
            @param id: O id do objeto
            @param count: Contador que vai a frente do id de entrada

            @return: valor de um id que não existe no contexto
        """

        if getattr(ctx, id, False):
            if count > 0:
                id = id[:(len(str(count)) + 1) * -1]
            count += 1
            id = '%s-%s' % (id, count)
            return self.generateIdForContext(ctx, id, count)
        else:
            return id

    def get_ip(self, request):
        """
        Extract the client IP address from the HTTP request in proxy compatible way.

        @return: IP address as a string or None if not available
        """
        if "HTTP_X_FORWARDED_FOR" in request.environ:
            # Virtual host
            ip = request.environ["HTTP_X_FORWARDED_FOR"]
        elif "HTTP_HOST" in request.environ:
            # Non-virtualhost
            ip = request.environ["REMOTE_ADDR"]
        else:
            # Unit test code?
            ip = None

        return ip

    def getAccessObject(self):
        uid = self.context.UID()
        content_type = self.context.meta_type
        contador = ContadorManager(uid=uid, content_type=content_type)
        return contador.setAcesso()

    def getFilesRelated(self):
        """ Metodo retorna os arquivos bibliotecas relacionados a boa pratica """
        rc = api.portal.get_tool('reference_catalog')
        results = rc.searchResults(relationship='uid_pratica',
                                   targetUID=self.context.UID())
        uids_arquivos = []
        for ref in results:
            ref_obj = ref.getObject()
            uids_arquivos.append(ref_obj.sourceUID)
        catalog = api.portal.get_tool(name='portal_catalog')
        files = catalog.searchResults(portal_type='ArquivoBiblioteca',
                                      UID=uids_arquivos)

        data = []
        for file in files:
            data_file = file.getObject()
            full_ctype = data_file.getContentType()
            ctype = 'NONE'
            for type in FILE_CONTENT_TYPES:
                if full_ctype in FILE_CONTENT_TYPES[type]:
                    ctype = type
                    break

            data.append({
                'title': data_file.Title(),
                'UID': data_file.UID,
                'ctype': ctype,
                'status': file.review_state,
                'url': data_file.absolute_url(),
                'created': data_file.created().strftime('%d/%m/%Y'),
                'size': sizeof_fmt(data_file.size())
            })

        return data

    def getCategoria(self):
        categoria = self.context.getCategoria()
        if categoria:
            factory = getUtility(
                IVocabularyFactory,
                'mpdg.govbr.observatorio.CategoriasBoaPratica')
            vocab = factory(self)
            try:
                term = vocab.getTerm(categoria)
                return term.title
            except LookupError:
                return None

#   Verificar se o usuario tem permissão de Modificar o conteúdo do portal

    def user_has_permission(self):
        if api.user.is_anonymous():
            return False

        pm = api.portal.get_tool('portal_membership')
        username = pm.getAuthenticatedMember().getUserName()
        permissions = api.user.get_permissions(username)

        # permissions = getSecurityManager().checkPermission(permissions.ModifyPortalContent, username)
        if permissions.get('Modify portal content'):
            # if permissions:
            return True
        return False

    # Verificar se o usuario e dono ou tem permissao do conteúdo do portal

    def is_owner(self):
        """returns True if current user is owner of context's object"""
        user = api.user.get_current()
        owner = self.context.getOwner()
        if user.id == owner.getId():
            return True
        return False

    def getSitesRelacionados(self):
        sites_relacionados = self.context.getSitesrelacionados()
        results = []

        for site in sites_relacionados:
            url = site['url']

            if url:
                if url.find('http') == -1:
                    url = 'http://' + url

            results.append({'description': site['description'], 'url': url})

        return results

    def getComentarios(self):
        catalog_comment = api.portal.get_tool('portal_catalog')
        path = '/'.join(self.context.getPhysicalPath())
        busca = catalog_comment.searchResults(portal_type='Comentario',
                                              review_state='published',
                                              path=path)

        results = []
        for item in busca:
            obj = item.getObject()
            created = obj.getCreated()
            results.append({
                'name': obj.getNome(),
                'email': obj.getEmail(),
                'created': created.strftime('%d/%m/%y, %H:%M'),
                'text': obj.getComentario(),
            })

        return results

    def canManageComments(self):
        return checkPermission('cmf.RequestReview', self.context)

    def getDataReplies(self):
        """
            Método retorna um dicionario com os dados dos comentários do conteúdo do contexto

            @return: Retorna o dicionario com os dados - qtd_replies - Quandidade de respostas no conteúdo
                                                         qtd_pending - Quantidade de respostas pendenetes
                                                         data - Lista de comentarios aprovados
        """
        approved = self.getComentarios()
        qtd_replies = len(approved)

        return {
            'qtd_replies': qtd_replies,
            'qtd_pending': len(self.getPendingComments()),
            'data': approved
        }

    def getPendingComments(self):
        catalog = api.portal.get_tool('portal_catalog')
        path = '/'.join(self.context.getPhysicalPath())
        brains = catalog.searchResults(portal_type='Comentario',
                                       review_state='pending',
                                       path=path)
        return brains
Ejemplo n.º 29
0
class Tmpls(viewlets.Tmpls):
    grok.context(Interface)
    grok.name(u'collective.upload.tmpls')
    grok.require('cmf.AddPortalContent')
    grok.template('tmpls')
    grok.viewletmanager(IHtmlHead)
Ejemplo n.º 30
0
class ChangeOwner(grok.View):
    """
    Temp page for testing the LDAP integration.

    http://localhost:8080/Plone/@@changeowner
    """

    # use grok.context(Interface) to associate view with the site root
    grok.context(ISiteRoot)
    grok.require('cmf.ManagePortal')

    need_oldowners_message = _(
        u"You have to select one or more from the old owners.")
    need_newowner_message = _(u"You have to select a new owner.")
    objects_updated_message = _(u"Objects updated")

    @property
    def catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def membership(self):
        return getToolByName(self.context, 'portal_membership')

    def exclude_members_folder(self):
        """Do we have to exclude the members folder ? """
        return self.request.form.get('exclude_members_folder', True)

    def dry_run(self):
        """Do we have to do a dry run ? """
        return self.request.form.get('dry_run', True)

    def delete_old_creators(self):
        """Do we have to delete old owners from the creators list ? """
        return self.request.form.get('delete_old_creators', False)

    def delete_old_owners(self):
        """Do we have to delete old owners from the owners role list ? """
        return self.request.form.get('delete_old_owners', False)

    def path_filter(self):
        """Do we have an old path?"""
        return self.request.form.get('path', '')

    def list_authors(self):
        """Returns a list of members that have created objects
        """
        authors = []
        oldowners = self.request.form.get('oldowners', [])

        for creator in self.catalog.uniqueValuesFor('Creator'):
            if not creator:
                continue

            info = self.membership.getMemberInfo(creator)
            if info and info['fullname']:
                d = dict(id=creator,
                         name="%s (%s)" % (info['fullname'], creator))
            else:
                d = dict(id=creator, name=creator)

            if creator in oldowners:
                d['selected'] = 1
            else:
                d['selected'] = 0
            authors.append(d)

        authors.sort(
            lambda a, b: cmp(str(a['name']).lower(),
                             str(b['name']).lower()))
        return authors

    ##
    def update(self):

        old_owners = self.request.form.get('oldowners', [])
        new_owner = self.request.form.get('newowner', '')
        path = self.request.form.get('path', '')
        dryrun = self.request.form.get('dry_run', '')
        ret = ''

        self.status = []
        if 'submit' in self.request.form:

            if isinstance(old_owners, str):
                old_owners = [old_owners]

            if not new_owner:
                self.status.append(self.need_newowner_message)

            if not old_owners:
                self.status.append(self.need_oldowners_message)

            #if self.status:
            #    return self.template()

            #clean up
            old_owners = [c for c in old_owners if c != new_owner]

            members_folder = self.membership.getMembersFolder()
            members_folder_path = None
            if members_folder:
                members_folder_path = '/'.join(
                    self.membership.getMembersFolder().getPhysicalPath())
            query = {'Creator': old_owners}
            if path:
                query['path'] = self.context.portal_url.getPortalObject(
                ).getId() + path

            count = 0
            for brain in self.catalog(**query):
                if self.exclude_members_folder() and members_folder_path and \
                   brain.getPath().startswith(members_folder_path):
                    #we dont want to change ownership for the members folder
                    #and its contents
                    continue

                if not dryrun:
                    obj = brain.getObject()
                    self._change_ownership(obj, new_owner, old_owners)
                    self._change_sharing(obj, new_owner, old_owners)
                    if base_hasattr(obj, 'reindexObject'):
                        obj.reindexObject()
                else:
                    ret += "%s " % brain.getPath()

                count += 1

            self.status.append(self.objects_updated_message + " (%s)" % count)
            if ret:
                self.status.append(ret)

        #return self.template()

    def _change_sharing(self, obj, new_owner, old_owners):
        """Change object ownership
        """
        # get_local_roles() return sequence like ( ("userid1", ("rolename1", "rolename2")), ("userid2", ("rolename1") )
        roles = obj.get_local_roles()
        for user, local_roles in roles:
            if user in old_owners:
                obj.manage_setLocalRoles(new_owner, list(local_roles))

    def _change_ownership(self, obj, new_owner, old_owners):
        """Change object ownership
        """

        #1. Change object ownership
        # changing the way it retrieve user (member)
        #acl_users = getattr(self.context, 'acl_users')
        #user = acl_users.getUserById(new_owner)
        mt = getToolByName(self.context, 'portal_membership')
        user = mt.getMemberById(new_owner)
        utils = self.context.plone_utils

        if user is None:
            user = self.membership.getMemberById(new_owner)
            if user is None:
                raise KeyError, 'Only retrievable users in this site can be made owners.'

        utils.changeOwnership(obj, user)

        #obj.changeOwnership(user)

        #2. Remove old authors if we was asked to and add the new_owner
        #   as primary author
        try:
            creators = list(obj.Creators())
        except:
            print "Not possible to reach Creators on this obj : %s" % obj
            #import pdb; pdb.set_trace()
            creators = list(obj.creators)
        if self.delete_old_creators():
            creators = [c for c in creators if c not in old_owners]

        if new_owner in creators:
            # Don't add same creator twice, but move to front
            del creators[creators.index(new_owner)]

        obj.setCreators([new_owner] + creators)

        #3. Remove the "owner role" from the old owners if we was asked to
        #   and add the new_owner as owner
        if self.delete_old_owners():
            #remove old owners
            owners = [
                o for o in obj.users_with_local_role('Owner')
                if o in old_owners
            ]
            for owner in owners:
                roles = list(obj.get_local_roles_for_userid(owner))
                roles.remove('Owner')
                if roles:
                    obj.manage_setLocalRoles(owner, roles)
                else:
                    obj.manage_delLocalRoles([owner])

        roles = list(obj.get_local_roles_for_userid(new_owner))
        if 'Owner' not in roles:
            roles.append('Owner')
            obj.manage_setLocalRoles(new_owner, roles)
Ejemplo n.º 31
0
class SaveSubscriptions(SaveSubscriptionsReview):
    grok.context(IObservation)
Ejemplo n.º 32
0
class DossierDeactivateView(grok.View):
    """ Recursively deactivate the dossier and his subdossiers.
    If some subdossiers are already resolved we return a status err msg.
    If some subdossiers are already deactivated we ignore them."""

    grok.context(IDossierMarker)
    grok.name('transition-deactivate')
    grok.require('zope2.View')

    def render(self):
        if not self.check_preconditions():
            return self.redirect()

        # recursively deactivate all dossiers
        for subdossier in self.context.get_subdossiers():
            state = api.content.get_state(obj=subdossier.getObject())
            if state != 'dossier-state-inactive':
                api.content.transition(
                    obj=subdossier.getObject(),
                    transition=u'dossier-transition-deactivate')

        # deactivate main dossier
        self.set_end_date(self.context)
        api.content.transition(obj=self.context,
                               transition='dossier-transition-deactivate')

        api.portal.show_message(_("The Dossier has been deactivated"),
                                self.request,
                                type='info')

        return self.redirect()

    def set_end_date(self, dossier):
        if not IDossier(dossier).end:
            IDossier(dossier).end = date.today()

    def redirect(self):
        return self.request.RESPONSE.redirect(self.context.absolute_url())

    def check_preconditions(self):
        satisfied = True

        if not self.context.is_all_checked_in():
            api.portal.show_message(_(
                u"The Dossier can't be deactivated, not all contained"
                "documents are checked in."),
                                    self.request,
                                    type='error')
            satisfied = False

        if self.context.has_active_proposals():
            api.portal.show_message(_(
                u"The Dossier can't be deactivated, it contains active "
                "proposals."),
                                    self.request,
                                    type='error')
            satisfied = False

        # check for resolved subdossiers
        for subdossier in self.context.get_subdossiers():
            state = api.content.get_state(obj=subdossier.getObject())
            if state == 'dossier-state-resolved':
                msg = _(
                    u"The Dossier can't be deactivated, the subdossier "
                    "${dossier} is already resolved",
                    mapping=dict(dossier=subdossier.Title.decode('utf-8')))
                api.portal.show_message(msg, self.request, type='error')

                satisfied = False

        if self.context.has_active_tasks():
            satisfied = False
            api.portal.show_message(_(
                u"The Dossier can't be deactivated, not all contained "
                "tasks are in a closed state."),
                                    self.request,
                                    type='error')

        return satisfied
Ejemplo n.º 33
0
class PromoteCampaignView(ShareView):
    grok.context(IPersonalCampaignPage)
    grok.require('collective.salesforce.fundraising.PromotePersonalCampaign')

    grok.name('promote')
    grok.template('promote')
class Contactable(grok.Adapter):
    """Base adapter class for objects that have the IContactDetails behavior fields"""
    grok.provides(IContactable)
    grok.context(IContactContent)
    grok.baseclass()

    @property
    def person(self):
        return None

    @property
    def position(self):
        return None

    @property
    def organizations(self):
        return []

    def _get_contactables(self):
        """
        Build a list of objects which have the IContactDetails behavior
        for each contact information (email, phone, ...)
        we use the one of the first object in this list which have this information
        """
        contactables = []
        related_items = [self.context, self.person, self.position] + list(
            reversed(self.organizations))
        for related_item in related_items:
            if related_item is not None \
              and IContactDetails.providedBy(related_item) \
              and related_item not in contactables:
                contactables.append(related_item)

        return contactables

    def _get_address(self, contactables):
        for obj in contactables:
            obj = aq_base(obj)
            if obj.use_parent_address is True:
                continue
            else:
                address = get_address(obj)
                if address:
                    return address

        return {}

    def get_contact_details(self):
        contact_details = {}
        contact_details_fields = [
            'email', 'phone', 'cell_phone', 'fax', 'website', 'im_handle'
        ]
        contactables = self._get_contactables()
        for field in contact_details_fields:
            # search the object that carries the field
            for obj in contactables:
                obj = aq_base(obj)
                value = getattr(obj, field, '') or ''
                if value:
                    contact_details[field] = value
                    break
            else:
                contact_details[field] = ''

        contact_details['address'] = self._get_address(contactables)
        return contact_details

    def get_parent_address(self):
        contactables = self._get_contactables()
        url = self.context.REQUEST.URL
        # we don't want self.context address if the object is already created
        if '/++add++' not in url and '/@@add' not in url:
            contactables.remove(self.context)

        address = self._get_address(contactables)
        if not address:
            # Very important to return unicode here, RichTextWidget needs it.
            return u''

        template_path = os.path.join(TEMPLATES_DIR, 'address.pt')
        template = ViewPageTemplateFile(template_path)
        self.request = getRequest()
        return template(self, address)
Ejemplo n.º 35
0
    description = schema.Text(
        title=_(u'label_detailed_question', default=u'Detailed Question'),
        description=_(u'desc_detailed_question', default=u'More details on the question, if not evident from the title.'),
        required=False,
    )

    answer = RichText(
        title=_(u'label_answer', default=u'Answer'),
        description=_(u"desc_answer", default=u"Meaningful sentences that explains the answer."),
        allowed_mime_types=('text/html', 'text/plain',),
        default_mime_type='text/html',
        output_mime_type='text/x-html-safe',
        required=True,
    )
    
class FaqEntryDx(Item):
    """FaqEntryDx class
    """

    implements(IFaqEntryDx)

grok.context(IFaqEntryDx)
grok.templatedir('browser/templates')

class View(grok.View):
    """IFaqEntryDx View
    """
    
    grok.require('zope2.View')
    grok.name('view')
    grok.template('faq-entry')
Ejemplo n.º 36
0
class importOfertes(grok.View):
    """ Import Titulacions from csv file """
    grok.name('import_ofertes')
    grok.context(Interface)
    grok.template('import_ofertes')
    grok.require('cmf.ManagePortal')
    grok.layer(IGenwebTfemarketLayer)

    def update(self):
        if self.request.environ['REQUEST_METHOD'] == 'POST':
            marketUID = self.request.form['market']
            fitxer = self.request.form['offersfile']
            filename = fitxer.filename
            hasHeaders = 'csv_headers' in self.request.form

            if filename != '' and filename.endswith('.csv'):
                msgError = self.createOffers(hasHeaders, fitxer, marketUID)
                if msgError != []:
                    IStatusMessage(self.request).addStatusMessage(
                        '\n'.join(msgError), type='error')
                else:
                    self.request.response.redirect(
                        self.context.absolute_url() +
                        "/tfemarket-settings#fieldsetlegend-2")
            else:
                message = (u"Falta afegir el fitxer csv.")
                IStatusMessage(self.request).addStatusMessage(message,
                                                              type='alert')

    def createOffers(self, hasHeaders, fitxer, marketUID):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)

        catalog = api.portal.get_tool(name='portal_catalog')
        market = catalog(UID=marketUID)[0].getObject()

        msgError = []
        csv_file = csv.reader(fitxer, delimiter=',', quotechar='"')

        if hasHeaders:
            csv_file.next()  # Ignore header for csv

        for count, row in enumerate(csv_file):
            # Importa ofertas
            notValidDegrees = self.checkNotValidDegrees(
                row[5].decode("utf-8").split(","))
            if len(notValidDegrees) == 0:
                teacher = getExactUserData(row[7].decode("utf-8"))
                if teacher:
                    data = {
                        'title':
                        row[0].decode("utf-8"),
                        'description':
                        row[1].decode("utf-8"),
                        'topic':
                        row[2].decode("utf-8"),
                        'offer_type':
                        row[3].decode("utf-8"),
                        'tfgm':
                        row[4].decode("utf-8").split(","),
                        'degree':
                        row[5].decode("utf-8").split(","),
                        'keys':
                        row[6].decode("utf-8").split(","),
                        'teacher_manager':
                        teacher['id'],
                        'teacher_fullname':
                        teacher['sn1'] + ' ' + teacher['sn2'] + ', ' +
                        teacher['givenName'] if 'sn2' in teacher else
                        teacher['sn1'] + ', ' + teacher['givenName'],
                        'teacher_email':
                        teacher['mail'],
                        'dept':
                        teacher['unitCode'] + "-" + teacher['unit'],
                        'num_students':
                        int(row[10].decode("utf-8")),
                        'workload':
                        row[11].decode("utf-8"),
                        'targets':
                        row[12].decode("utf-8"),
                        'features':
                        row[13].decode("utf-8"),
                        'requirements':
                        row[14].decode("utf-8"),
                        'lang':
                        row[15].decode("utf-8").split(","),
                        'modality':
                        row[16].decode("utf-8"),
                        'company':
                        row[17].decode("utf-8"),
                        'grant':
                        bool(row[18].decode("utf-8") == "True"),
                        'confidential':
                        bool(row[19].decode("utf-8") == "True"),
                        'environmental_theme':
                        bool(row[20].decode("utf-8") == "True"),
                        'scope_cooperation':
                        bool(row[21].decode("utf-8") == "True"),
                    }

                    type_codirector = row[8].decode("utf-8")
                    data.update({'type_codirector': type_codirector})
                    if type_codirector == 'UPC':
                        codirector = getExactUserData(row[9].decode("utf-8"))
                        if codirector:
                            data.update({
                                'codirector_id':
                                codirector['id'],
                                'codirector':
                                codirector['sn1'] + ' ' + codirector['sn2'] +
                                ', ' + codirector['givenName']
                                if 'sn2' in codirector else codirector['sn1'] +
                                ', ' + codirector['givenName'],
                                'codirector_email':
                                codirector['mail'],
                                'codirector_dept':
                                codirector['unitCode'] + "-" +
                                codirector['unit']
                            })
                        else:
                            msg = row[0].decode(
                                "utf-8") + " - Codirector (" + row[9].decode(
                                    "utf-8") + ") not exist."
                            print str(count + 1) + ": Error - " + msg
                            msgError.append(str(count + 1) + ": " + msg)
                            continue
                    else:
                        data.update({'codirector': row[9].decode("utf-8")})

                    offer = createContentInContainer(market,
                                                     "genweb.tfemarket.offer",
                                                     **data)
                    offer.setEffectiveDate(
                        dt_start_of_day(datetime.datetime.today() +
                                        datetime.timedelta(1)))
                    offer.setExpirationDate(
                        dt_end_of_day(datetime.datetime.today() +
                                      datetime.timedelta(365)))
                    offer.reindexObject()

                    # Importa topics y tags
                    strTopics = row[2].decode("utf-8") + ","
                    topics = list(dict.fromkeys(strTopics.split(",")[:-1]))
                    actualTopics = tfe_tool.topics.split('\r\n')
                    newTopics = "\r\n".join([
                        topic for topic in topics if topic not in actualTopics
                    ])
                    if newTopics:
                        tfe_tool.topics += "\r\n" + newTopics

                    strTags = row[6].decode("utf-8") + ","
                    tags = list(dict.fromkeys(strTags.split(",")[:-1]))
                    actualTags = tfe_tool.tags.split('\r\n')
                    newTags = "\r\n".join(
                        [tag for tag in tags if tag not in actualTags])
                    if newTags:
                        tfe_tool.tags += "\r\n" + newTags

                    transaction.commit()

                    print str(count + 1) + ": Done - " + row[0].decode("utf-8")
                else:
                    msg = row[0].decode("utf-8") + " - Teacher (" + row[
                        7].decode("utf-8") + ") not exist."
                    print str(count + 1) + ": Error - " + msg
                    msgError.append(str(count + 1) + ": " + msg)
            else:
                msg = row[0].decode("utf-8") + " - Degree (" + " - ".join(
                    notValidDegrees) + ") not valid."
                print str(count + 1) + ": Error - " + msg
                msgError.append(str(count + 1) + ": " + msg)

        return msgError

    def getMarkets(self):
        markets = []
        catalog = api.portal.get_tool(name='portal_catalog')
        values = catalog(path={'query': '/'},
                         object_provides=IMarket.__identifier__)
        for market in values:
            markets.append({'value': market.UID, 'title': market.Title})

        return markets

    def checkNotValidDegrees(self, degrees):
        registry = queryUtility(IRegistry)
        tfe_tool = registry.forInterface(ITfemarketSettings)
        allDegrees = [x['codi_mec'] for x in tfe_tool.titulacions_table]
        notValid = [x for x in degrees if x not in allDegrees]
        return notValid
                for collection, storageTypes in collectionTypes.iteritems():
                    for storage, organs in storageTypes.iteritems():
                        for organ, pptIDs in organs.iteritems():
                            totalSpecimens = sum(pptIDs.values())
                            totalPpts = len(pptIDs)
                            cases, controls = totalPpts, 0 # FIXME: but how? No idea how to compute # cases or # controls from ERNE data
                            records.append(ERNESpecimenSummary(
                                storage, totalSpecimens,cases,controls,organ,withCancer,available,email,protocolID,collection
                            ))
            return records
        except urllib2.HTTPError, ex:
            _logger.info('Ignoring failed attempt to get specimens from %s via %s: %r', erneID, erneWS, ex)
        try:
            con.close()
        except (IOError, AttributeError):
            pass
        return records

    grok.provides(IJsonGenerator)
    grok.context(ISpecimenSummarizerGenerator)
    def generateJson(self):
        context = aq_inner(self.context)
        erneWS = context.queryDataSource
        specimenCount = {}
        if erneWS:
            for siteID, erneID in SITES.items():
                specimenCount = self.getSpecimens(erneID, erneWS)

        # C'est tout.
        return jsonlib.write(specimenCount)
Ejemplo n.º 38
0
class Todo(grok.View):
    """A BrowserView to display the Todo listing on a Folder."""

    grok.context(IATFolder)  # type of object on which this View is available
    grok.require('zope2.View')  # what permission is needed for access
Ejemplo n.º 39
0
    import PIL.Image
except ImportError:
    # no PIL, no scaled versions!
    HAS_PIL = False
    PIL_ALGO = None
else:
    HAS_PIL = True
    PIL_ALGO = PIL.Image.ANTIALIAS

_marker = []

video_mimetypes = ['video/mp4', 'video/x-flv']
image_mimetypes = ['image/jpeg', 'image/gif', 'image/png']

# GLOBAL CONTEXT INTERFACES IS IATNewsItem
grok.context(IATNewsItem)


# INTERFACES
class INewsMediaLayer(IDefaultBrowserLayer):
    """ Default Layer for News Media Items """


class IMediaManager(Interface):
    """ Marker interface for news-item media. """


class IMediaContainer(Interface):
    """ Marker interface for a news-item media container. """

Ejemplo n.º 40
0
from five import grok
from Products.CMFCore.utils import getToolByName

from gites.db.interfaces import IHebergement


grok.templatedir('templates')
grok.context(IHebergement)


class HebergementViewletManager(grok.ViewletManager):
    grok.name('gites.hebergement')


class ButtonsViewlet(grok.Viewlet):
    grok.order(10)

    def backButtonAvailable(self):
        """
        Show back button only if we were already on gites website
        """
        referer = self.request.get('HTTP_REFERER')
        if not referer:
            return False
        portalUrl = getToolByName(self.context, 'portal_url')()
        if referer and referer.startswith(portalUrl):
            return True
        return False


grok.viewletmanager(HebergementViewletManager)
Ejemplo n.º 41
0
# -*- coding: utf-8 -*-
from five import grok
from zope import interface

from gites.core.browser.search import BasicForm


grok.templatedir('templates')
grok.context(interface.Interface)


class RechercherViewletManager(grok.ViewletManager):
    grok.name('gites.rechercher')


class RechercherViewlet(grok.Viewlet):
    grok.order(10)

    def update(self):

        self.form = BasicForm(self.context, self.request)
        self.form.update()

        # Defines the placeholder for some field
        widgets_placeholder = ('fromDate', 'toDate', 'nearTo')
        for widget in self.form.widgets:
            if widget in widgets_placeholder:
                label = self.form.widgets[widget].label
                self.form.widgets[widget].placeholder = label

from five import grok

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

from collective.dms.basecontent.dmsdocument import IDmsDocument
from collective.dms.basecontent import _
from collective.dms.basecontent.browser.listing import VersionsTable, DmsAppendixTable
from collective.dms.basecontent.browser.table import TableViewlet

from zope.interface import Interface


grok.templatedir("templates")
grok.context(IDmsDocument)


class DmsAboveContentViewletManager(grok.ViewletManager):
    grok.name("dms.abovecontent")


class DmsBelowContentViewletManager(grok.ViewletManager):
    grok.name("dms.belowcontent")


class BaseViewlet(TableViewlet):
    grok.baseclass()
    grok.viewletmanager(DmsBelowContentViewletManager)
    __table__ = VersionsTable

    def contentFilter(self):
        return {"portal_type": self.portal_type}