Example #1
0
    def update(self):
        super(View, self).update()
        messages = IStatusMessage(self.request)
        context = aq_inner(self.context)
        self.context = context
        self.state = getMultiAdapter(
            (context, self.request), name=u'plone_context_state')
        self.wf_state = self.state.workflow_state()
        self.utility = context.utility
        # Handle vote
        form = self.request.form
        self.errors = []
        self.messages = []

        #if the poll is open and anonymous should vote but the parent folder
        #is private.. inform the user.

        # When the poll's container is the site's root, we do not need to
        # check the permissions.
        container = aq_parent(aq_inner(self.context))

        if 'open' == self.wf_state and not ISiteRoot.providedBy(container):
            roles = [
                r['name'] for r in
                self.context.rolesOfPermission('collective.polls: Vote')
                if r['selected']]

            if 'Anonymous' not in roles and self.context.allow_anonymous:
                messages.addStatusMessage(_(
                    u"Anonymous user won't be able to vote, you forgot to "
                    u"publish the parent folder, you must sent back the poll "
                    u"to private state, publish the parent folder and open "
                    u"the poll again"), type="info")

        INVALID_OPTION = _(u'Invalid option')
        if 'poll.submit' in form:
            options = form.get('options', '')
            if isinstance(options, list):
                self.errors.append(INVALID_OPTION)
            elif isinstance(options, str):
                if not options.isdigit():
                    self.errors.append(INVALID_OPTION)
                else:
                    options = int(options)
            if not self.errors:
                # Let's vote
                try:
                    self.context.setVote(options, self.request)
                    self.messages.append(_(u'Thanks for your vote'))
                    # We do this to avoid redirecting anonymous user as
                    # we just sent them the cookie
                    self._has_voted = True
                except Unauthorized:
                    self.errors.append(_(u'You are not authorized to vote'))
        # Update status messages
        for error in self.errors:
            messages.addStatusMessage(error, type="warn")
        for msg in self.messages:
            messages.addStatusMessage(msg, type="info")
Example #2
0
class IVotePortlet(IPortletDataProvider):
    """A portlet."""

    header = schema.TextLine(
        title=_(u'Header'),
        description=_(u'The header for the portlet. Leave empty for none.'),
        required=False,
    )

    poll = schema.Choice(
        title=_(u'Poll'),
        description=_(u'Which poll to show in the portlet.'),
        required=True,
        source=PossiblePolls,
    )

    show_total = schema.Bool(
        title=_(u'Show total votes'),
        description=_(u'Show the number of collected votes so far.'),
        default=True,
    )

    show_closed = schema.Bool(
        title=_(u'Show closed polls'),
        description=_(
            u'If there is no available open poll or the chosen poll is '
            u'already closed, should the porlet show the results instead.'),
        default=False,
    )

    link_poll = schema.Bool(
        title=_(u'Add a link to the poll'),
        description=u'',
        default=True,
    )
Example #3
0
 def js(self):
     add = _(u'Add')
     add_option = _(u'Add Option')
     delete_option = _(u'Delete Option')
     edit_option = _(u'Edit Option')
     return JS_TEMPLATE.format(
         id=self.id,
         add=add,
         add_task=add_option,
         delete_task=delete_option,
         edit_task=edit_option,
     )
 def js(self):
     add = _(u'Add')
     add_option = _(u'Add Option')
     delete_option = _(u'Delete Option')
     edit_option = _(u'Edit Option')
     return JS_TEMPLATE.format(
         id=self.id,
         add=add,
         add_task=add_option,
         delete_task=delete_option,
         edit_task=edit_option,
     )
Example #5
0
 def validate_options(data):
     ''' Validate options '''
     options = data.options
     descriptions = options and [o for o in options]
     if len(descriptions) < 2:
         raise InsuficientOptions(
             _(u"You need to provide at least two options for a poll."))
Example #6
0
class IPollTile(IPersistentCoverTile):
    """A tile that shows a poll."""

    uuid = TextLine(
        title=_(u'Poll uuid'),
        readonly=True,
    )
Example #7
0
    def update(self):
        super(View, self).update()
        messages = IStatusMessage(self.request)
        context = aq_inner(self.context)
        self.context = context
        self.state = getMultiAdapter((context, self.request),
                                      name=u'plone_context_state')
        self.wf_state = self.state.workflow_state()
        self.utility = context.utility

        # Handle vote
        form = self.request.form
        self.errors = []
        self.messages = []

        INVALID_OPTION = _(u'Invalid option')
        if 'poll.submit' in form:
            options = form.get('options', '')
            if isinstance(options, list):
                self.errors.append(INVALID_OPTION)
            elif isinstance(options, str):
                if not options.isdigit():
                    self.errors.append(INVALID_OPTION)
                else:
                    options = int(options)
            if not self.errors:
                # Let's vote
                try:
                    self.context.setVote(options, self.request)
                    self.messages.append(_(u'Thanks for your vote'))
                    # We do this to avoid redirecting anonymous user as
                    # we just sent them the cookie
                    self._has_voted = True
                except Unauthorized:
                    self.errors.append(_(u'You are not authorized to vote'))
        # Update status messages
        for error in self.errors:
            messages.addStatusMessage(error, type="warn")
        for msg in self.messages:
            messages.addStatusMessage(msg, type="info")

        if 'voting.from' in form:
            url = form['voting.from']
Example #8
0
class IOption(interface.Interface):
    ''' An option in a poll '''

    option_id = schema.Int(
        title=u"Option Id",
        required=False)

    description = schema.TextLine(
        title=_(u"Description"),
        required=True)
Example #9
0
 def _handleSubmit(self, form):
     INVALID_OPTION = _(u'Invalid option')
     options = form.get('options', '')
     if isinstance(options, list):
         self.errors.append(INVALID_OPTION)
     elif isinstance(options, str):
         if not options.isdigit():
             self.errors.append(INVALID_OPTION)
         else:
             options = int(options)
     if not self.errors:
         # Let's vote
         try:
             self.context.setVote(options, self.request)
             self.messages.append(_(u'Thanks for your vote'))
             # We do this to avoid redirecting anonymous user as
             # we just sent them the cookie
             self._has_voted = True
         except Unauthorized:
             self.errors.append(_(u'You are not authorized to vote'))
Example #10
0
 def _updateForm(self, form):
     INVALID_OPTION = _(u'Invalid option')
     options = form.get('options', '')
     if isinstance(options, list):
         self.errors.append(INVALID_OPTION)
     elif isinstance(options, str):
         if not options.isdigit():
             self.errors.append(INVALID_OPTION)
         else:
             options = int(options)
     if not self.errors:
         # Let's vote
         try:
             self.context.setVote(options, self.request)
             self.messages.append(_(u'Thanks for your vote'))
             # We do this to avoid redirecting anonymous user as
             # we just sent them the cookie
             self._has_voted = True
         except Unauthorized:
             self.errors.append(_(u'You are not authorized to vote'))
Example #11
0
def PossiblePolls(context):
    catalog = getToolByName(context, 'portal_catalog')
    polls = catalog(portal_type="collective.polls.poll", review_state="open")

    values = [SimpleTerm(value="latest", title=_(u"Latest opened poll"))]
    if polls:
        for i in polls:
            values.append(SimpleTerm(value=i.UID, title=i.Title))

    vocab = SimpleVocabulary(values)

    return vocab
Example #12
0
def PossiblePolls(context):
    catalog = getToolByName(context, 'portal_catalog')
    polls = catalog(portal_type="collective.polls.poll", review_state="open")

    values = [SimpleTerm(value="latest", title=_(u"Latest opened poll"))]
    if polls:
        for i in polls:
            values.append(SimpleTerm(value=i.UID, title=i.Title))

    vocab = SimpleVocabulary(values)

    return vocab
Example #13
0
class IVotePortlet(IPortletDataProvider):
    """A portlet
    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    header = schema.TextLine(
        title=_(u'Header'),
        description=_(u"The header for the portlet. Leave empty for none."),
        required=False,
    )

    poll = schema.Choice(
        title=_(u'Poll'),
        description=_(u"Which poll to show in the portlet."),
        required=True,
        source=PossiblePolls,
    )

    show_closed = schema.Bool(
        title=_(u'Show closed polls'),
        description=_(
            u"If there is no available open poll or the chosen poll is "
            u"already closed, should the porlet show the results instead."),
        default=False,
    )
Example #14
0
def PossiblePolls(context):
    portal_state = api.content.get_view(name='plone_portal_state',
                                        context=context,
                                        request=context.REQUEST)
    utility = queryUtility(IPolls, name='collective.polls')
    navigation_root = portal_state.navigation_root()
    polls = utility.recent_polls(context=navigation_root,
                                 show_all=False,
                                 limit=999999)

    values = [SimpleTerm(value='latest', title=_(u'Latest opened poll'))]
    values.extend(
        SimpleTerm(value=i.UID, title=i.Title.decode('utf-8')) for i in polls)

    return SimpleVocabulary(values)
Example #15
0
class IPoll(form.Schema):
    """ A Poll in a Plone site
    """

    allow_anonymous = schema.Bool(
        title=_(u"Allow anonymous"),
        description=_(u"Allow not logged in users to vote."),
        default=True,
        )

    #multivalue = schema.Bool(
        #title = _(u"Multivalue"),
        #description = _(u"Voters can choose several answers at the same "
                         #"time."),
        #)

    show_results = schema.Bool(
        title=_(u"Show partial results"),
        description=_(u"Show partial results after a voter has already "
                       "voted."),
        default=True,
        )

    results_graph = schema.Choice(
        title=_(u'Graph'),
        description=_(u"Format to show the results."),
        default='bar',
        required=True,
        source=graph_options)

    options = schema.List(
        title=_(u"Available options"),
        value_type=DictRow(title=_(u'Option'),
                           schema=IOption),
        default=[],
        required=True)

    @invariant
    def validate_options(data):
        ''' Validate options '''
        options = data.options
        descriptions = options and [o['description'].strip() for o in options]
        if len(descriptions) < 2:
            raise InsuficientOptions(
                    _(u"You need to provide at least two options for a poll."))
Example #16
0
class IPoll(form.Schema):
    """ A Poll in a Plone site
    """

    allow_anonymous = schema.Bool(
        title=_(u"Allow anonymous"),
        description=_(
            u"Allow not logged in users to vote. The parent folder of this "
            u"poll should be published before opeining the poll for this "
            u"field to take effect"),
        default=True,
    )

    #multivalue = schema.Bool(
        #title = _(u"Multivalue"),
        #description = _(u"Voters can choose several answers at the same "
                         #"time."),
    #)

    show_results = schema.Bool(
        title=_(u"Show partial results"),
        description=_(u"Show partial results after a voter has already voted."),
        default=True,
    )

    results_graph = schema.Choice(
        title=_(u'Graph'),
        description=_(u"Format to show the results."),
        default='bar',
        required=True,
        source=graph_options,
    )

    form.widget(options=EnhancedTextLinesFieldWidget)
    options = schema.List(
        title=_(u"Available options"),
        value_type=schema.TextLine(),
        default=[],
        required=True,
    )

    @invariant
    def validate_options(data):
        ''' Validate options '''
        options = data.options
        descriptions = options and [o for o in options]
        if len(descriptions) < 2:
            raise InsuficientOptions(
                _(u"You need to provide at least two options for a poll."))
Example #17
0
def PossiblePolls(context):
    portal_state = api.content.get_view(
        name='plone_portal_state',
        context=context,
        request=context.REQUEST
    )
    utility = queryUtility(IPolls, name='collective.polls')
    navigation_root = portal_state.navigation_root()
    polls = utility.recent_polls(context=navigation_root, show_all=False, limit=999999)

    values = [SimpleTerm(value='latest', title=_(u'Latest opened poll'))]
    values.extend(
        SimpleTerm(value=i.UID, title=i.Title.decode('utf-8'))
        for i in polls
    )

    return SimpleVocabulary(values)
Example #18
0
    def update(self):
        super(View, self).update()
        context = aq_inner(self.context)
        self.context = context
        self.state = getMultiAdapter(
            (context, self.request), name=u'plone_context_state')
        self.wf_state = self.state.workflow_state()
        # Handle vote
        form = self.request.form
        self.errors = []
        self.messages = []

        # if the poll is open and anonymous should vote but the parent folder
        # is private.. inform the user.

        # When the poll's container is the site's root, we do not need to
        # check the permissions.
        container = aq_parent(aq_inner(self.context))

        if 'open' == self.wf_state and not ISiteRoot.providedBy(container):
            roles = [
                r['name'] for r in
                self.context.rolesOfPermission('collective.polls: Vote')
                if r['selected']]

            if 'Anonymous' not in roles and self.context.allow_anonymous:
                msg = _(
                    u"Anonymous user won't be able to vote, you forgot to "
                    u'publish the parent folder, you must sent back the poll '
                    u'to private state, publish the parent folder and open '
                    u'the poll again'
                )
                api.portal.show_message(msg, self.request, type='warn')

        if 'poll.submit' in form:
            self._updateForm(form)
        # Update status messages
        for error in self.errors:
            api.portal.show_message(error, self.request, type='warn')
        for msg in self.messages:
            api.portal.show_message(msg, self.request, type='info')
Example #19
0
    def update(self):
        super(View, self).update()
        context = aq_inner(self.context)
        self.context = context
        self.state = getMultiAdapter((context, self.request),
                                     name=u'plone_context_state')
        self.wf_state = self.state.workflow_state()
        # Handle vote
        form = self.request.form
        self.errors = []
        self.messages = []

        # if the poll is open and anonymous should vote but the parent folder
        # is private.. inform the user.

        # When the poll's container is the site's root, we do not need to
        # check the permissions.
        container = aq_parent(aq_inner(self.context))

        if 'open' == self.wf_state and not ISiteRoot.providedBy(container):
            roles = [
                r['name'] for r in self.context.rolesOfPermission(
                    'collective.polls: Vote') if r['selected']
            ]

            if 'Anonymous' not in roles and self.context.allow_anonymous:
                msg = _(
                    u"Anonymous user won't be able to vote, you forgot to "
                    u'publish the parent folder, you must sent back the poll '
                    u'to private state, publish the parent folder and open '
                    u'the poll again')
                api.portal.show_message(msg, self.request, type='warn')

        if 'poll.submit' in form:
            self._updateForm(form)
        # Update status messages
        for error in self.errors:
            api.portal.show_message(error, self.request, type='warn')
        for msg in self.messages:
            api.portal.show_message(msg, self.request, type='info')
Example #20
0
 def title(self):
     """This property is used to give the title of the portlet in the
     "manage portlets" screen.
     """
     return _(u"Voting portlet")
Example #21
0
 def title(self):
     """Return the title of the portlet in the 'manage portlets' screen."""
     return _(u'Voting portlet')
Example #22
0
class InsuficientOptions(Invalid):
    __doc__ = _(u"Not enought options provided")
Example #23
0
 def title(self):
     """Return the title of the portlet in the 'manage portlets' screen."""
     return _(u'Voting portlet')
Example #24
0
from Products.statusmessages.interfaces import IStatusMessage
from Products.CMFCore.interfaces import ISiteRoot

from collective.polls.config import COOKIE_KEY
from collective.polls.config import MEMBERS_ANNO_KEY
from collective.polls.config import VOTE_ANNO_KEY

from collective.polls.config import PERMISSION_VOTE

from collective.polls.polls import IPolls

from collective.polls import MessageFactory as _


graph_options = SimpleVocabulary(
    [SimpleTerm(value=u'bar', title=_(u'Bar Chart')),
     SimpleTerm(value=u'pie', title=_(u'Pie Chart')),
     SimpleTerm(value=u'numbers', title=_(u'Numbers Only'))])


class InsuficientOptions(Invalid):
    __doc__ = _(u"Not enought options provided")


class IPoll(form.Schema):
    """ A Poll in a Plone site
    """

    allow_anonymous = schema.Bool(
        title=_(u"Allow anonymous"),
        description=_(
Example #25
0
 def title(self):
     """This property is used to give the title of the portlet in the
     "manage portlets" screen.
     """
     return _(u"Voting portlet")
Example #26
0
    def render(self):
        response = self.request.response
        response.setHeader('content-type', 'text/javascript;;charset=utf-8')

        label_legendothers = _(u"label_legendothers", default=u"Others")
        return "legendothers_translation = '%s';" % label_legendothers