Exemplo n.º 1
0
 def jscode(self, datatable):
     """ return Google visualization js code
     """
     if type(datatable) is dict:
         # if dict, we convert it to googleviz compliant array
         labels = datatable.keys()
         labels.sort()
         tmp = []
         for label in labels:
             valuelist = ["'%s'" % label]
             for e in asList(datatable[label]):
                 if isinstance(e, basestring):
                     valuelist.append("'%s'" % e)
                 else:
                     valuelist.append(str(e))
             tmp.append(valuelist)
         datatable = tmp
         
     js = self.jssettings + "\n"
     js = js + "function " + self.chartid + "_getCells() {\n"
     js = js + self.chartid+".addRows(" + str(len(datatable)) + ");\n"
     i = 0
     for row in datatable:
         j = 0
         for cell in row:
             js = js + self.chartid+".setValue(" + str(i) + ", " + str(j) + ", " + cell + ");\n"
             j = j + 1
         i = i + 1
     js = js + "}"
     return js
Exemplo n.º 2
0
    def processInput(self,
                     submittedValue,
                     doc,
                     process_attachments,
                     validation_mode=False):
        """process submitted value according the field type
        """

        fieldtype = self.getFieldType()
        fieldname = self.id
        adapt = self.getSettings()

        if fieldtype == "ATTACHMENT" and process_attachments:

            if isinstance(submittedValue, FileUpload):
                submittedValue = asList(submittedValue)

            current_files = doc.getItem(fieldname)
            if not current_files:
                current_files = {}

            if submittedValue is not None:
                for fl in submittedValue:
                    (new_file, contenttype) = doc.setfile(fl)
                    if new_file is not None:
                        if adapt.type == "SINGLE":
                            for filename in current_files.keys():
                                if filename != new_file:
                                    doc.deletefile(filename)
                            current_files = {}
                        current_files[new_file] = contenttype

            v = current_files

        else:
            try:
                v = adapt.processInput(submittedValue)
            except Exception, e:
                # TODO: Log exception
                if validation_mode:
                    # when validating, submitted values are potentially bad
                    # but it must not break getHideWhens, getFormFields, etc.
                    v = submittedValue
                else:
                    raise e
Exemplo n.º 3
0
    def processInput(self, submittedValue, doc, process_attachments, validation_mode=False):
        """process submitted value according the field type
        """

        fieldtype = self.getFieldType()
        fieldname = self.id
        adapt = self.getSettings()

        if fieldtype=="ATTACHMENT" and process_attachments:

            if isinstance(submittedValue, FileUpload):
                submittedValue = asList(submittedValue)

            current_files=doc.getItem(fieldname)
            if not current_files:
                current_files = {}

            if submittedValue is not None:
                for fl in submittedValue:
                    (new_file, contenttype) = doc.setfile(fl)
                    if new_file is not None:
                        if adapt.type == "SINGLE":
                            for filename in current_files.keys():
                                if filename != new_file:
                                    doc.deletefile(filename)
                            current_files={}
                        current_files[new_file]=contenttype

            v = current_files

        else:
            try:
                v = adapt.processInput(submittedValue)
            except Exception, e:
                # TODO: Log exception
                if validation_mode:
                    # when validating, submitted values are potentially bad
                    # but it must not break getHideWhens, getFormFields, etc.
                    v = submittedValue
                else:
                    raise e
Exemplo n.º 4
0
    def jscode(self, datatable):
        """ return Google visualization js code
        """
        if type(datatable) is dict:
            # if dict, we convert it to googleviz compliant array
            labels = datatable.keys()
            labels.sort()
            tmp = []
            for label in labels:
                valuelist = ["'%s'" % label]
                for e in asList(datatable[label]):
                    if isinstance(e, basestring):
                        valuelist.append("'%s'" % e)
                    else:
                        valuelist.append(str(e))
                tmp.append(valuelist)
            datatable = tmp

        rows = []
        i = 0
        for row in datatable:
            j = 0
            for cell in row:
                rows.append(
                    js_row_template % {
                        'chartid': self.chartid,
                        'row_nr': i,
                        'col_nr': j,
                        'cell': cell
                    })
                j = j + 1
            i = i + 1

        js = js_func_template % {
            'jssettings': self.jssettings,
            'chartid': self.chartid,
            'num_rows': str(len(datatable)),
            'rows': ''.join(rows)
        }

        return js
Exemplo n.º 5
0
    def jscode(self, datatable):
        """ Return Google visualization JS code
        """
        if type(datatable) is dict:
            # if dict, we convert it to googleviz compliant array
            labels = datatable.keys()
            labels.sort()
            tmp = []
            for label in labels:
                valuelist = ["'%s'" % label]
                for e in asList(datatable[label]):
                    if isinstance(e, basestring):
                        valuelist.append("'%s'" % e)
                    else:
                        valuelist.append(str(e))
                tmp.append(valuelist)
            datatable = tmp

        rows = []
        i = 0
        for row in datatable:
            j = 0
            for cell in row:
                rows.append(js_row_template % {
                        'chartid': self.chartid,
                        'row_nr': i,
                        'col_nr': j,
                        'cell': cell})
                j = j + 1
            i = i + 1

        js = js_func_template % {
                'jssettings': self.jssettings,
                'chartid': self.chartid,
                'num_rows': str(len(datatable)),
                'rows': ''.join(rows)}

        return js
Exemplo n.º 6
0
    def isCurrentUserAuthor(self, doc):
        """ Does the current user have the author role on doc?

        This is True if:
        - they have the Owner or Manager Plone roles, OR
        - if they have the PlominoDesigner, PlominoEditor or PlominoManager
          role globally, OR
        - if they have the PlominoAuthor role, AND
          - they are in the Plomino_Authors item on doc, OR
          - they have a *role* which is in the Plomino_Authors item, OR
          - they belong to a *group* which is in the Plomino_Authors item.
        """
        # the user must at least have edit permission
        if not self.checkUserPermission(EDIT_PERMISSION):
            return False

        # the user must at least be an allowed reader
        if not self.isCurrentUserReader(doc):
            return False

        # if the user is Owner of the db or Manager, no problem
        general_plone_rights = self.getCurrentMember().getRolesInContext(
            doc.getParentDatabase())
        for r in ['Owner', 'Manager']:
            if r in general_plone_rights:
                return True

        # check if the user is more powerful than a regular PlominoAuthor
        current_rights = self.getCurrentUserRights()
        for r in ['PlominoEditor', 'PlominoDesigner', 'PlominoManager']:
            if r in current_rights:
                return True

        # if he is just a PlominoAuthor, check if he is author of this very
        # document
        if 'PlominoAuthor' in current_rights:

            authors = asList(doc.getItem('Plomino_Authors') or [])
            if not authors:
                return False

            if '*' in authors:
                return True

            name = self.getCurrentMember().getUserName()
            if name in authors:
                return True

            roles = self.getCurrentUserRoles()
            for r in roles:
                if r in authors:
                    return True

            groupstool = self.portal_groups
            usergroups = [g.id for g in groupstool.getGroupsByUserId(name)]
            for u in authors:
                if u in usergroups:
                    return True

            return False

        return False
Exemplo n.º 7
0
    def isCurrentUserAuthor(self, doc):
        """ Does the current user have the author role on doc?

        This is True if:
        - they have the Owner or Manager Plone roles, OR
        - if they have the PlominoDesigner, PlominoEditor or PlominoManager
          role globally, OR
        - if they have the PlominoAuthor role, AND
          - they are in the Plomino_Authors item on doc, OR
          - they have a *role* which is in the Plomino_Authors item, OR
          - they belong to a *group* which is in the Plomino_Authors item.
        """
        # the user must at least have edit permission
        if not self.checkUserPermission(EDIT_PERMISSION):
            return False

        # the user must at least be an allowed reader
        if not self.isCurrentUserReader(doc):
            return False

        # if the user is Owner of the db or Manager, no problem
        general_plone_rights = self.getCurrentMember().getRolesInContext(doc.getParentDatabase())
        for r in ['Owner', 'Manager']:
            if r in general_plone_rights:
                return True

        # check if the user is more powerful than a regular PlominoAuthor
        current_rights = self.getCurrentUserRights()
        for r in ['PlominoEditor', 'PlominoDesigner', 'PlominoManager']:
            if r in current_rights:
                return True

        # if he is just a PlominoAuthor, check if he is author of this very
        # document
        if 'PlominoAuthor' in current_rights:

            authors = asList(doc.getItem('Plomino_Authors') or [])
            if not authors:
                return False

            if '*' in authors:
                return True

            name = self.getCurrentMember().getUserName()
            if name in authors:
                return True

            roles = self.getCurrentUserRoles()
            for r in roles:
                if r in authors:
                    return True

            groupstool = self.portal_groups
            usergroups = [g.id for g in groupstool.getGroupsByUserId(name)]
            for u in authors:
                if u in usergroups:
                    return True

            return False

        return False
Exemplo n.º 8
0
def search_json(self, REQUEST=None):
    """ Returns a JSON representation of view filtered data
    """
    data = []
    categorized = self.getCategorized()
    start = 1
    search = None
    sort_index = None
    reverse = 1

    if REQUEST:
        start = int(REQUEST.get('iDisplayStart', 1))

        limit = REQUEST.get('iDisplayLength')
        limit = (limit and int(limit))
        # In case limit == -1 we want it to be None
        if limit < 1:
            limit = None

        search = REQUEST.get('sSearch', '').lower()
        if search:
            search = " ".join([term+'*' for term in search.split(' ')])
        sort_column = REQUEST.get('iSortCol_0')
        if sort_column:
            sort_index = self.getIndexKey(self.getColumns()[int(sort_column)-1].id)
        reverse = REQUEST.get('sSortDir_0') or 'asc'
        if reverse=='desc':
            reverse = 0
        if reverse=='asc':
            reverse = 1

    query_request = json.loads(REQUEST['query'])
    # Some fields might express a date
    # We try to convert those strings to datetime
    #indexes = self.aq_parent.aq_base.plomino_index.Indexes
    indexes = self.getParentDatabase().getIndex().Indexes
    for key, value in query_request.iteritems():
        if key in indexes:
            index = indexes[key]
            # This is lame: we should check if it quacks, not
            # if it's a duck!
            # XXX Use a more robust method to tell apart
            # date indexes from non-dates

            # I'd use a solution like this one: http://getpython3.com/diveintopython3/examples/customserializer.py
            if isinstance(index, DateIndex):
                # convert value(s) to date(s)
                if isinstance(value, basestring):
                    query_request[key] = parse_date(value)
                else:
                    if isinstance(value['query'], basestring):
                        value['query'] = parse_date(value['query'])
                    else:
                        query_request[key]['query'] = [parse_date(v) for v in value['query']]

    results, total = self.search_documents(start=1,
                                   limit=None,
                                   getObject=False,
                                   fulltext_query=search,
                                   sortindex=sort_index,
                                   reverse=reverse,
                                   query_request=query_request)

    if limit:
        if HAS_PLONE43:
            results = Batch(items=results, size=limit, start=int(start/limit)+1)*limit
        else:
            results = Batch(items=results, pagesize=limit, pagenumber=int(start/limit)+1)
    display_total = len(results)

    columnids = [col.id for col in self.getColumns() if not getattr(col, 'HiddenColumn', False)]
    for b in results:
        row = [b.getPath().split('/')[-1]]
        for colid in columnids:
            v = getattr(b, self.getIndexKey(colid), '')
            if isinstance(v, list):
                v = [asUnicode(e).encode('utf-8').replace('\r', '') for e in v]
            else:
                v = asUnicode(v).encode('utf-8').replace('\r', '')
            row.append(v or '&nbsp;')
        if categorized:
            for cat in asList(row[1]):
                entry = [c for c in row]
                entry[1] = cat
                data.append(entry)
        else:
            data.append(row)
    return json.dumps({ 'iTotalRecords': total, 'iTotalDisplayRecords': display_total, 'aaData': data })