Beispiel #1
0
 def listFolderContentTypes(self):
     """Returns list of content types used inside
     current container.
     """
     items = []
         
     # calculate current folder's path
     cstate = getMultiAdapter((self.context, self.request),
         name='plone_context_state')
     path = '/'.join(cstate.folder().getPhysicalPath())
     
     # collect portal type list used withing current folder
     otypes = []
     catalog = getToolByName(self.context, 'portal_catalog')
     for brain in catalog(path={'query': path, 'depth': 1}):
         if brain.portal_type not in otypes:
             otypes.append(brain.portal_type)
     
     # prepare items list with type id and type title
     ttool = getToolByName(self.context, 'portal_types')
     for otype in otypes:
         item = {'id': otype, 'title': otype}
         if ttool is not None and shasattr(ttool, otype):
             item['title'] = _(safe_unicode(getattr(ttool, otype).Title()))
         items.append(item)
     
     # finally sort items and prepend 'All' filter element
     if len(items) > 0:
         items.sort(lambda x,y:cmp(x['title'], y['title']))
         items = [{'id': '', 'title': _(u'All')}] + items
     
     return tuple(items)
    def getPads(self):
        pads = []
        username, password, url = self.getUserData()
        if not (username and password and url):
            return ()

        # try to request etherpad for page with table of pads
        try:
            content = self._getPadsPage()

        except:
            logException(_(u"Error during fetching pads from %s" % url),
                context=self.context, logger=logger)
            return ()

        # try to parse html page into pads
        try:
            pads = self._parsePadsPage(content, self.trail_url(url),
                self.data.count)

        except:
            logException(_(u"Error during parsing pads page from %s" % url),
                context=self.context, logger=logger)
            return ()

        return tuple(pads)
Beispiel #3
0
    def update(self):
        super(FooterViewlet, self).update()
        self.columns = columns = {}

        context = aq_inner(self.context)
        actions_tool = getToolByName(context, 'portal_actions')

        # check if we got root category for all column links
        if not FOOTER_LINKS_CAT in actions_tool.objectIds():
            return

        # prepare expression context for evaluating TAL expressions
        ec = actions_tool._getExprContext(context)

        # go over root category and collect all sub-categories
        container = actions_tool[FOOTER_LINKS_CAT]
        cat_ids = container.objectIds()
        for cid in ('column1', 'column2', 'column3'):
            # skip not existing categories
            if cid not in cat_ids:
                continue

            cat = container[cid]
            if not IActionCategory.providedBy(cat):
                continue

            # prepare category actions
            actions = []
            for action in cat.objectValues():
                # look only for actions
                if not IAction.providedBy(action):
                    continue

                # create actioninfo object to compile and render TAL expressions
                # and check if action is available in current circumstances
                info = ActionInfo(action, ec)
                if not (info['visible'] and info['allowed'] and
                        info['available']):
                    continue

                # and finally extract all required details from action
                desc = action.getProperty('description', None) or None
                if desc is not None:
                    desc = _(safe_unicode(desc))
                actions.append({
                    'id': info['id'],
                    'title': _(safe_unicode(info['title'])),
                    'desc': _(desc),
                    'url': info['url']
                })

            # finally add category to be rendered as footer column
            columns[cid] = {
                'title': _(safe_unicode(cat.getProperty('title', ''))),
                'actions': tuple(actions)
            }

        self.columns = columns
Beispiel #4
0
    def _get_ims(self, since=None, till=None, uid=None):
        """Returns list of instant messages"""
        result = []
        purl = self.purl()
        mtool = getToolByName(self.context, 'portal_membership')
        storage = getUtility(IPubSubStorage)
        escaper = getUtility(INodeEscaper)
        convert = getToolByName(self, 'portal_transforms').convert

        # go over recent messages
        for item in storage.itemsFromNodes(['people'], start=0,
            count=DEFAULT_ITEMS_NUM):

            # TODO: handle comments
            if item.get('parent'):
                continue

            datetime = DateTime(item['updated']).toZone('GMT')

            # TODO: handle till argument
            if since and since >= datetime:
                # we've got too old entry, break from the loop
                break

            fullname = author = item['author']
            if author:
                author = escaper.unescape(author)
                member = mtool.getMemberById(author)
                if member:
                    fullname = member.getProperty('fullname', None) or author
                else:
                    fullname = author

            # strip down html code from message body
            body = safe_unicode(item['content']).encode('utf-8')
            body = safe_unicode(convert('html_to_text', body).getData())

            result.append({
                'uid': item['id'],
                'type': 'im',
                'image': {'url': mtool.getPersonalPortrait(author
                    ).absolute_url(), 'alt': _(safe_unicode(author))},
                'url': '%s/@@pubsub-feed?node=%s' % (purl, author),
                'title': _(safe_unicode(fullname)),
                'date': datetime.strftime('%b %d, %Y'),
                'time': datetime.strftime('%I:%M'),
                'datetime': datetime,
                'replies_num': 0,
                'can_reply': True,
                'body': body
            })

        return result
Beispiel #5
0
    def _get_zmails(self, since=None, till=None, uid=None):
        """Returns list of recent zimbra emails."""
        purl = self.purl()

        # get zimbra settings
        mtool = getToolByName(self.context, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        username = member.getProperty('zimbra_username', '')
        password = member.getProperty('zimbra_password', '')
        if not (username and password):
            return []

        # make zimbra soap query to get list of recent emails
        try:
            zimbra = getUtility(IZimbraUtil).get_client(username=username,
                password=password)
            mails = zimbra.get_emails(folder='inbox', limit=DEFAULT_ITEMS_NUM,
                types='message')
        except Exception:
            logException(_(u"Error during fetching zimbra mails"),
                context=self.context, logger=logger)
            return []

        zurl = getZimbraUrl(self.context)
        result = []
        for mail in mails:
            # TODO: handle till argument
            datetime = DateTime(int(mail['date']) / 1000).toZone('GMT')
            if since and since >= datetime:
                # we've got too old entry, break from the loop
                break

            result.append({
                'uid': mail['id'],
                'type': 'zm',
                'image': {
                    'url': '%s/add_content_area/metabox_icon_email.png' %
                    purl, 'alt': _(u"MAIL")},
                'url': '%s/zimbra/h/search?st=conversation&id=%s' \
                    '&action=view&cid=%s' % (zurl, mail['id'],
                    mail['cid']),
                'title': _(u"MAIL"),
                'date': datetime.strftime('%b %d, %Y'),
                'time': datetime.strftime('%I:%M'),
                'datetime': datetime,
                'replies_num': 0,
                'can_reply': True,
                'body': mail['subject']
            })

        return result
Beispiel #6
0
    def get_email(self, eid):
        """Returns conversation emails by given id.

        It also marks conversation as read.
        """
        if not eid:
            return {'error': _(u"Conversation id is not valid.")}

        result = self.client.get_email(eid)
        thread = []
        for item in result:
            from_ = [su(e._getAttr('p')) for e in item.e
                        if e._getAttr('t') == 'f']
            from_ = from_[0] if len(from_) else ''
            to = u', '.join([su(e._getAttr('d')) for e in item.e
                        if e._getAttr('t') == 't'])

            thread.append({
                'from': from_,
                'to': to,
                'body': findMsgBody(item),
                'id': item._getAttr('_orig_id'),
                'date': item._getAttr('d'),
            })

        return {'conversation': '<br />'.join([t['from'] + ': ' + t['body']
            for t in thread])}
Beispiel #7
0
    def _get_recent(self, since=None, till=None, uid=None):
        """Returns list of Recently updated content and comments on the site"""
        result = []
        purl = self.purl()

        # check if we got since and till arguments, if so - add it to catalog
        # query to get only recent or older items
        extra_query = None
        limit = DEFAULT_ITEMS_NUM
        if since is not None:
            limit = None
            extra_query = Ge('modified', since) & (~ Eq('modified', since))
        elif till:
            extra_query = Le('modified', till) & (~ Eq('modified', till))

        # get friendly content types
        portal_state = getMultiAdapter((self.context, self.request),
            name=u'plone_portal_state')
        ftypes = list(portal_state.friendly_types())
        ftypes.remove('News Item')

        for brain in self._cp_items(ftypes, sort_on='modified',
            extra_query=extra_query, limit=limit):
            datetime = brain.modified.toZone('GMT')
            time = datetime.strftime('%I:%M')
            date = datetime.strftime('%b %d, %Y')

            result.append({
                'uid': brain.UID,
                'type': 'recent',
                'image': {
                    'url': '%s/add_content_area/' \
                        'metabox_icon_serviceportal.png' % purl,
                    'alt': _(u"RECENT")},
                'url': brain.getURL(),
                'title': _(u"RECENT"),
                'date': date,
                'time': time,
                'datetime': datetime,
                'replies_num': 0,
                'can_reply': True,
                'body': _(safe_unicode(brain.Title))
            })
        return result
Beispiel #8
0
 def handleSave(self, action):
     data, errors = self.extractData()
     if errors:
         self.status = self.formErrorsMessage
         return
     self.applyChanges(data)
     IStatusMessage(self.request).addStatusMessage(_(u"Changes saved."),
                                                   "info")
     self.request.response.redirect("%s/%s" % (self.context.absolute_url(),
                                               self.control_panel_view))
Beispiel #9
0
    def __call__(self, action, portlethash):
        """Main method that accepts action to perform.

        Args:
          @action - one of allowed actions, like emails, create, send, etc...
          @portlethash - portlet hash so we get portlet assignement data from it

        This method accepts only post requests.
        It returns json.
        It authenticates before any further actions.
        """
        # get settings
        data = self._data(portlethash)

        # check if method is POST
        request = self.request
        if request.method != 'POST':
            return self._error(_(u"Request method is not allowed."))

        # check if action is valid
        if action not in ('emails', 'email'):
            return self._error(_(u"Requested action is not allowed."))

        # Gets the zimbra client
        zimbraUtil = getUtility(IZimbraUtil)
        self.client = zimbraUtil.get_client(data['url'], data['username'],
                data['password'])

        mails = []
        if action == 'emails':
            mails = self.get_emails(request.get('folder') or None,
                int(request.get('offset') or '0'),
                int(request.get('limit') or '100'),
                request.get('recip') or '1',
                request.get('sortBy') or 'dateDesc'
            )
        elif action == 'email':
            mails = self.get_email(request.get('eid') or None)

        return simplejson.dumps(mails)
Beispiel #10
0
    def update(self):
        catalog = getToolByName(self.context, 'portal_catalog')
        elems = []
        for brain in catalog(path={'depth': 20,
            'query': '/'.join(self.context.getPhysicalPath())},
            sort_on='avg_ratings',
            sort_order='reverse'):

            # skip item if nobody voted yet
            if brain.positive_ratings == 0 and brain.total_down_ratings == 0:
                continue

            elems.append({
                'title': _(safe_unicode(brain.Title)),
                'desc': _(safe_unicode(brain.Description)),
                'url': brain.getURL(),
                'type': normalizeString(brain.portal_type, encoding='utf-8'),
                'rating': {'total': brain.avg_ratings,
                           'liked': brain.positive_ratings,
                           'disliked': brain.total_down_ratings}})

        self.elems = tuple(elems)
Beispiel #11
0
    def _get_news(self, since=None, till=None, uid=None):
        """Returns list of Cloud Portal News"""
        result = []
        purl = self.purl()

        # check if we got since and till arguments, if so - add it to catalog
        # query to get only recent or older items
        extra_query = None
        limit = DEFAULT_ITEMS_NUM
        if since is not None:
            limit = None
            extra_query = Ge('created', since) & (~ Eq('created', since))
        elif till:
            extra_query = Le('created', till) & (~ Eq('created', till))

        for brain in self._cp_items(('News Item',), sort_on='created',
            extra_query=extra_query, limit=limit):
            datetime = brain.created.toZone('GMT')
            time = datetime.strftime('%I:%M')
            date = datetime.strftime('%b %d, %Y')

            result.append({
                'uid': brain.UID,
                'type': 'news',
                'image': {
                    'url': '%s/add_content_area/metabox_icon_news-item.png' %
                    purl, 'alt': _(u"NEWS")},
                'url': brain.getURL(),
                'title': _(u"NEWS"),
                'date': date,
                'time': time,
                'datetime': datetime,
                'replies_num': 0,
                'can_reply': True,
                'body': _(safe_unicode(brain.Title))
            })
        return result
Beispiel #12
0
 def __init__(self, header=_(u"World Clock"), tz_1='Europe/Berlin',
     skin_1='vnc', radius_1=35, no_seconds_1=False, tz_2='Europe/Berlin',
     skin_2='vnc', radius_2=35, no_seconds_2=False, tz_3='Europe/Berlin',
     skin_3='vnc', radius_3=35, no_seconds_3=False):
     self.header = header
     self.tz_1 = tz_1
     self.skin_1 = skin_1
     self.radius_1 = radius_1
     self.no_seconds_1 = no_seconds_1
     self.tz_2 = tz_2
     self.skin_2 = skin_2
     self.radius_2 = radius_2
     self.no_seconds_2 = no_seconds_2
     self.tz_3 = tz_3
     self.skin_3 = skin_3
     self.radius_3 = radius_3
     self.no_seconds_3 = no_seconds_3
Beispiel #13
0
    def update(self):
        self.tickets = ()

        if IPloneSiteRoot in providedBy(self.context):
            return

        tickets = []
        # check if settings are configured
        # check user redmine credentials and redmine url/field id
        registry = getUtility(IRegistry)
        url = registry.get('vnccollab.theme.redmine.url')
        field_id = registry.get('vnccollab.theme.redmine.plone_uid_field_id')
        username, password = self.getAuthCredentials()
        if username and password and url and field_id:
            Issue = type("Issue", (ActiveResource,), {'_site': url, '_user':
                username, '_password': password})
            # do actual calls to redmine
            try:
                # fetch opened issues belonging to authenticated user
                uuid = self.context.UID()
                data = Issue.find(**{'cf_%d' % field_id: uuid,
                    'status_id': 'o', 'sort': 'updated_on:desc'})
            except Exception:
                logException(_(u"Error during fetching redmine tickets %s" %
                    url), context=self.context, logger=logger)
                return

            for item in data:
                info = item.to_dict()

                # skip invalid entries
                if not info.get('id') or not info.get('subject'):
                    continue

                tickets.append({
                    'id': info['id'],
                    'title': safe_unicode(info['subject']),
                    'body': safe_unicode(info.get('description', '')),
                    'url': '%s/issues/%s' % (url, info['id'])
                })

        self.tickets = tuple(tickets)
Beispiel #14
0
 def uploadFile(self, file):
     """Form post handler to create file.
     
     If created successfully then redirect to it's Edit form,
     otherwise to it's Add form with validation errors.
     
     Parameter:
       @file - data to upload
     File title is taken from file as filename.
     """
     # check it's post request
     if self.request.method != 'POST' or not file or not file.filename:
         raise Exception(u'Invalid request.')
     
     context = aq_inner(self.context)
     id = make_uuid('temp-id')
     # make sure our id is unique
     id = context.invokeFactory(id=id, type_name='File')
     obj = getattr(context, id)
     obj.update(title=file.filename, file=file)
     obj._renameAfterCreation()
     if obj.checkCreationFlag():
         obj.unmarkCreationFlag()
     obj._renameAfterCreation()
     obj.reindexObject()
     notify(ObjectInitializedEvent(obj))
     
     # if file is not there then it haven't got over validation process,
     # notify user about this issue
     if not obj.get_size():
         IStatusMessage(self.request).addStatusMessage(_(u"Attached file is "
             "invalid, please, try to upload another one."), type="error")
     
     # if posted by javascript then no redirect
     if self.request.form.get('ajax_call'):
         return '%s/edit' % obj.absolute_url()
     else:
         return self.request.response.redirect('%s/edit' %
             obj.absolute_url())
    def __call__(self, context):
        # get authenticated user
        mtool = getToolByName(context, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        if not member:
            return SimpleVocabulary([])

        username, password = member.getProperty('redmine_username', ''), \
            safe_unicode(member.getProperty('redmine_password',
            '')).encode('utf-8')
        registry = getUtility(IRegistry)
        url = registry.get('vnccollab.theme.redmine.url')
        field_id = registry.get(
            'vnccollab.theme.redmine.plone_uid_field_id')
        if not (username and password and url and field_id):
            return SimpleVocabulary([])

        try:
            data = getRedmineEnumerators(url, username, password)
        except Exception, e:
            logException(_(u"Error during fetching redmine enumerators"),
                context=context, logger=logger)
            return SimpleVocabulary([])
Beispiel #16
0
 def recordPortletState(self, hash, action, value):
     """Sets portlet state on site annotations"""
     # check if we got anthenticated user
     user = getSecurityManager().getUser()
     if not user or getattr(user, 'name', '') == 'Anonymous User':
         return _(u"No authenticated user found.")
     
     annotations = IAnnotations(self.context)
     users = annotations.get(PORTLETS_STATES_ANNO_KEY, None)
     if users is None:
         users = annotations[PORTLETS_STATES_ANNO_KEY] = OOBTree()
     
     userid = getattr(user, '_id', user.getId())
     portlets = users.get(userid, None)
     if portlets is None:
         portlets = users[userid] = PersistentDict()
     
     portlet = portlets.get(hash, None)
     if portlet is None:
         portlet = portlets[hash] = PersistentDict()
     
     portlet[action] = value
     
     return 'Done.'
Beispiel #17
0
    def get_user_data(self, userid=''):
        """Returns user name, url and image.

        If not given userid, return data of authenticated user.
        """
        mtool = getToolByName(self.context, 'portal_membership')
        purl = self.purl()

        if userid:
            member = mtool.getMemberById(userid)
        else:
            member = mtool.getAuthenticatedMember()

        name = userid
        if member:
            userid = member.getId()
            name = member.getProperty('fullname') or userid

        escaper = getUtility(INodeEscaper)
        return {'name': _(safe_unicode(name)),
                'url': '%s/author/%s' % (purl, userid),
                'image': mtool.getPersonalPortrait(userid).absolute_url(),
                'id': userid,
                'safe_id': escaper.escape(userid)}
Beispiel #18
0
 def title(self):
     """Return portlet header"""
     return _(self.header) or _(u"Users Box")
    def _tickets(self, url, username, password):
        """Requests redmine for list of opened issues for current user"""
        # create ActiveResource classes to fetch data from Redmine over REST API
        attrs = {'_site': url, '_user': username, '_password': password}
        if self.data.request_timeout:
            attrs['_timeout'] = self.data.request_timeout

        Issue = type("Issue", (ActiveResource,), attrs.copy())
        User = type("User", (ActiveResource,), attrs.copy())

        # do actual calls to redmine
        try:
            # fetch opened issues belonging to authenticated user
            data = Issue.find(assigned_to_id=User.find('current').id,
                              status_id='o',
                              sort='updated_on:desc')
        except:
            logException(_(u"Error during fetching redmine tickets %s" % url),
                         context=self.context, logger=logger)
            return ()

        plone_view = getMultiAdapter((self.context, self.request),
                                     name=u'plone')

        # process retrieved data
        tickets = []
        limit = self.data.count
        counter = 0
        for item in data:
            # we've got enough tickets
            if counter >= limit:
                break

            info = item.to_dict()

            # skip invalid entries
            if not info.get('id') or not info.get('subject'):
                continue

            # prepare date
            date = info.get('updated_on', '')
            if date:
                date = plone_view.toLocalizedTime(date, long_format=1)

            # prepare ticket body
            body = safe_unicode(info.get('description', ''))
            if body:
                # convert textile to html and do not cut down ticket
                # description anymore
                try:
                    body = textile.textile(body)
                except:
                    pass
                # crop length to 160 characters
                # body = plone_view.cropText(body, 160, ellipsis=u'...')

            tickets.append({
                'id': info['id'],
                'title': safe_unicode(info['subject']),
                'body': body,
                'date': date,
                'url': '%s/issues/%s' % (url, info['id'])
            })

            counter += 1

        return tuple(tickets)
Beispiel #20
0
 def handleCancel(self, action):
     IStatusMessage(self.request).addStatusMessage(_(u"Edit cancelled."),
                                                   "info")
     self.request.response.redirect("%s/%s" % (self.context.absolute_url(),
                                               self.control_panel_view))
Beispiel #21
0
    def handleCreate(self, action):
        """Create zimbra task using SOAP API."""
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        url = util.getZimbraUrl(self.context)
        username, password = util.getZimbraCredentials(self.context)
        if not username or not password or not url:
            if not username or not password:
                msg = _(u"Please, set correct zimbra username and password in "
                "your profile form in order to create a zimbra task.")
            else:
                msg = _(u"Please, set Zimbra URL in Control "
                    " Panel (Configuration Registry).")
            # issue form level error
            self.status = msg
            error = getMultiAdapter((Invalid(u''), self.request, None,
                None, self, self.context), IErrorViewSnippet)
            error.update()
            self.widgets.errors += (error,)
            return

        created = False
        try:
            zimbraUtil = getUtility(IZimbraUtil)
            client = zimbraUtil.get_client(url, username, password)
            email = util.getZimbraEmail(self.context)
            url = self.context.absolute_url()
            description = self.context.Description()
            content = u'%s\n\n%s' % (url, description)

            data['author'] = email
            data['subject'] = data['subject_']
            data['priority'] = data['priority_']
            data['content'] = content
            task = client.create_task(data)
            util.addZimbraAnnotatedTasks(self.context, task)
            created = True

        except Exception:
            plone_utils = getToolByName(self.context, 'plone_utils')
            exception = plone_utils.exceptionString()
            self.status = _(u"Unable create issue: ${exception}",
                mapping={u'exception': exception})
            error = getMultiAdapter((Invalid(u''), self.request, None,
                None, self, self.context), IErrorViewSnippet)
            error.update()
            self.widgets.errors += (error,)
            return

        else:
            if not created:
                self.status = _(u"Task wasn't created, please, check your "
                    "settings or contact site administrator if you are sure "
                    "your settings are set properly.")
                error = getMultiAdapter((Invalid(u''), self.request, None,
                    None, self, self.context), IErrorViewSnippet)
                error.update()
                self.widgets.errors += (error,)
                return

        self.status = self.successMessage
        IStatusMessage(self.request).addStatusMessage(self.successMessage,
            type='info')
        came_from = self.request.get('HTTP_REFERER') or self.context.absolute_url()
        return self.request.response.redirect(came_from)
Beispiel #22
0
 def validateBothDates(data):
     if not data.startDate and not data.endDate:
         return
     if not data.startDate or not data.endDate:
         raise BothDatesError(_("You must set both start and end date or none."))
Beispiel #23
0
 def get_item_types(self):
     """Returns list of stream item types"""
     return (
         {'id': 'all',
          'title': _(u"All"),
          'desc': _(u"Show All Items")},
         {'id': 'im',
          'title': _(u"Instant Messages"),
          'desc': _(u"Show Only IM messages")},
         {'id': 'zm',
          'title': _(u"Mail"),
          'desc': _(u"Show Only Zimra Emails")},
         {'id': 'news',
          'title': _(u"News"),
          'desc': _(u"Show Only Cloud Portal News")},
         {'id': 'tickets',
          'title': _(u"Tickets"),
          'desc': _(u"Show Only Redmine Tickets")},
         {'id': 'recent',
          'title': _(u"Recent"),
          'desc': _(u"Show Only Recent Cloud Portal Updates")},
     )
Beispiel #24
0
    def handleCreate(self, action):
        """Create redmine ticket using REST API."""
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # check user redmine credentials and redmine url/field id
        registry = getUtility(IRegistry)
        url = registry.get('vnccollab.theme.redmine.url')
        field_id = registry.get('vnccollab.theme.redmine.plone_uid_field_id')
        username, password = self.getAuthCredentials()
        if not username or not password or not url or not field_id:
            if not username or not password:
                msg = _(u"Please, set correct redmine username and password in "
                "your profile form in order to create redmine issue.")
            else:
                msg = _(u"Please, set Redmine URL and ID settings in Control "
                    " Panel (Configuration Registry).")

            # issue form level error
            self.status = msg
            error = getMultiAdapter((Invalid(u''), self.request, None,
                None, self, self.context), IErrorViewSnippet)
            error.update()
            self.widgets.errors += (error,)
            return

        # finally trying to post new issue
        Issue = type("Issue", (ActiveResource,), {'_site': url, '_user':
            username, '_password': password})
        try:
            start_date = data.get('start_date') or ''
            if start_date:
                start_date = start_date.strftime('%Y-%m-%d')
            due_date = data.get('due_date') or ''
            if due_date:
                due_date = due_date.strftime('%Y-%m-%d')

            issue = Issue({
                'project_id': data['project'],
                'subject': data['subject'].encode('utf-8'),
                'tracker_id': data['tracker'],
                'description': (data.get('description') or u'').encode('utf-8'),
                'priority_id': data['priority'],
                'assigned_to_id': data.get('asignee') or '',
                'start_date': start_date,
                'due_date': due_date,
                'estimated_hours': data.get('estimated_time') or '',
                'custom_fields': [{'value': self.context.UID(),
                    'id': '%d' % field_id}]
            })
            created = issue.save()
        except Exception, e:
            # issue form level error
            logException(_(u"Error during creating redmine issue at %s" %
                self.context.absolute_url()), context=self.context,
                logger=logger)
            plone_utils = getToolByName(self.context, 'plone_utils')
            exception = plone_utils.exceptionString()
            self.status = _(u"Unable create issue: ${exception}",
                mapping={u'exception' : exception})
            error = getMultiAdapter((Invalid(u''), self.request, None,
                None, self, self.context), IErrorViewSnippet)
            error.update()
            self.widgets.errors += (error,)
            return
Beispiel #25
0
                self.context.absolute_url()), context=self.context,
                logger=logger)
            plone_utils = getToolByName(self.context, 'plone_utils')
            exception = plone_utils.exceptionString()
            self.status = _(u"Unable create issue: ${exception}",
                mapping={u'exception' : exception})
            error = getMultiAdapter((Invalid(u''), self.request, None,
                None, self, self.context), IErrorViewSnippet)
            error.update()
            self.widgets.errors += (error,)
            return
        else:
            # check if issue was created successfully
            if not created:
                self.status = _(u"Issue wasn't created, please, check your "
                    "settings or contact site administrator if you are sure "
                    "your settings are set properly.")
                error = getMultiAdapter((Invalid(u''), self.request, None,
                    None, self, self.context), IErrorViewSnippet)
                error.update()
                self.widgets.errors += (error,)
                return

        # add status message
        self.status = self.successMessage
        IStatusMessage(self.request).addStatusMessage(self.successMessage,
            type='info')

        # redirect to success page to gather number of emailed pages
        came_from = self.request.get('HTTP_REFERER') or self.context.absolute_url()
        return self.request.response.redirect(came_from)
 def Title(self):
     print type(self.data.name), self.data.name, _(self.data.name)
     return _(self.data.name)
Beispiel #27
0
 def update(self):
     self.users = self._getUsers()
     self.header = _(self.data.header)
Beispiel #28
0
    def _get_rtickets(self, since=None, till=None, uid=None):
        """Returns list of Redmine tickets belonging to currently logged in
        user.

        If since or till are passed, then return tickets that suit given date
        range.
        """
        result = []
        purl = self.purl()

        # get redmine credentials
        mtool = getToolByName(self.context, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        username, password = member.getProperty('redmine_username', ''), \
            member.getProperty('redmine_password', '')
        if not (username and password):
            return []
        else:
            password = safe_unicode(password).encode('utf-8')

        # get redmine url
        url = getUtility(IRegistry).get('vnccollab.theme.redmine.url')
        if not url:
            return []

        # create ActiveResource classes to fetch data from Redmine over REST API
        attrs = {'_site': url, '_user': username, '_password': password}

        Issue = type("Issue", (ActiveResource,), attrs.copy())
        User = type("User", (ActiveResource,), attrs.copy())

        # do actual calls to redmine
        try:
            # fetch opened issues belonging to authenticated user
            data = Issue.find(assigned_to_id=User.find('current').id,
             status_id='o', sort='updated_on:desc')
        except Exception:
            logException(_(u"Error during fetching redmine tickets %s" % url),
                context=self.context, logger=logger)
            return []

        # cut down number of tickets in case we don't have date range arguments
        if not since:
            data = data[:DEFAULT_ITEMS_NUM]

        for item in data:
            info = item.to_dict()

            # skip invalid entries
            if not info.get('id') or not info.get('subject'):
                continue

            # prepare date
            datetime = DateTime(info.get('updated_on', '')).toZone('GMT')
            # TODO: handle till argument
            if since and since >= datetime:
                # we've got too old entry, break from the loop
                break

            result.append({
                'uid': info['id'],
                'type': 'tickets',
                'image': {
                    'url': '%s/add_content_area/metabox_icon_task.png' % purl,
                    'alt': _(u"ISSUE")},
                'url': '%s/issues/%s' % (url, info['id']),
                'title': _(u"ISSUE"),
                'date': datetime.strftime('%b %d, %Y'),
                'time': datetime.strftime('%I:%M'),
                'datetime': datetime,
                'replies_num': 0,
                'can_reply': True,
                'body': _(safe_unicode(info['subject']))
            })

        return result
    def upload_settings(self):
        context = aq_inner(self.context)
        request = self.request
        try:
            session = request.get('SESSION', {})
            mediaupload = session.get('mediaupload',
                    request.get('mediaupload', ''))
            typeupload = session.get('typeupload',
                    request.get('typeupload', ''))
        except SessionDataManagerErr:
            logger.debug('Error occurred getting session data. Falling back to '
                    'request.')
            mediaupload = request.get('mediaupload', '')
            typeupload = request.get('typeupload', '')
        portal_url = getToolByName(context, 'portal_url')()

        settings = dict(
            portal_url             = portal_url,
            typeupload             = '',
            context_url            = context.absolute_url(),
            physical_path          = "/".join(context.getPhysicalPath()),
            ul_id                  = self.uploader_id,
            ul_fill_titles         = self.qup_prefs.fill_titles and 'true' or 'false',
            ul_fill_descriptions   = self.qup_prefs.fill_descriptions and 'true' or 'false',
            ul_auto_upload         = self.qup_prefs.auto_upload and 'true' or 'false',
            ul_size_limit          = self.qup_prefs.size_limit and str(self.qup_prefs.size_limit*1024) or '',
            ul_xhr_size_limit      = self.qup_prefs.size_limit and str(self.qup_prefs.size_limit*1024) or '0',
            ul_sim_upload_limit    = str(self.qup_prefs.sim_upload_limit),
            ul_button_text         = self._translate(_(u'Browse')),
            ul_draganddrop_text    = self._translate(_(u'Drag and drop files to upload')),
            ul_msg_all_sucess      = self._translate(_(u'All files uploaded with success.')),
            ul_msg_some_sucess     = self._translate(_(u' files uploaded with success, ')),
            ul_msg_some_errors     = self._translate(_(u" uploads return an error.")),
            ul_msg_failed          = self._translate(_(u"Failed")),
            ul_error_try_again_wo  = self._translate(_(u"please select files again without it.")),
            ul_error_try_again     = self._translate(_(u"please try again.")),
            ul_error_empty_file    = self._translate(_(u"Selected elements contain an empty file or a folder:")),
            ul_error_empty_extension = self._translate(_(u"This file has no extension:")),
            ul_error_file_large    = self._translate(_(u"This file is too large:")),
            ul_error_maxsize_is    = self._translate(_(u"maximum file size is:")),
            ul_error_bad_ext       = self._translate(_(u"This file has invalid extension:")),
            ul_error_onlyallowed   = self._translate(_(u"Only allowed:")),
            ul_error_no_permission = self._translate(_(u"You don't have permission to add this content in this place.")),
            ul_error_disallowed_type = self._translate(_(u"This type of element is not allowed in this folder.",)),
            ul_error_already_exists = self._translate(_(u"This file already exists with the same name on server:")),
            ul_error_zodb_conflict = self._translate(_(u"A data base conflict error happened when uploading this file:")),
            ul_error_server        = self._translate(_(u"Server error, please contact support and/or try again.")),
            ul_browse_files        = self._translate(_('Browse files')),
        )

        settings['typeupload'] = typeupload
        if typeupload :
            imageTypes = _listTypesForInterface(context, IImageContent)
            if typeupload in imageTypes :
                ul_content_types_infos = self.ul_content_types_infos('image')
            else :
                ul_content_types_infos = self.ul_content_types_infos(mediaupload)
        else :
            ul_content_types_infos = self.ul_content_types_infos(mediaupload)

        settings['ul_file_extensions'] = ul_content_types_infos[0]
        settings['ul_file_extensions_list'] = str(ul_content_types_infos[1])
        settings['ul_file_description'] = ul_content_types_infos[2]

        return settings
Beispiel #30
0
 def __init__(self, header=u"Users", do_not_recurse=False, count=30):
     self.header = _(header)
     self.do_not_recurse = do_not_recurse
     self.count = count