示例#1
0
def statistics(context, request):

    object_counters = []
    policy_counters = []
    ous = {}
    ous_visibles = []
    settings = get_current_registry().settings
    policyname = "name_{}".format(settings['pyramid.default_locale_name'])

    is_superuser = request.user.get('is_superuser', False)
    ou_id = request.GET.get('ou_id', None)
    logger.debug("admins.py ::: statistics - ou_id = {}".format(ou_id))

    if is_superuser:
        ous_visibles = request.db.nodes.find({"type": "ou"}, {
            "_id": 1,
            "name": 1,
            "path": 1
        })
    else:
        # Get managed ous for admin
        oids = request.user.get('ou_managed', []) + request.user.get(
            'ou_readonly', [])
        ous_visibles = request.db.nodes.find(
            {"_id": {
                "$in": list(map(ObjectId, oids))
            }}, {
                "_id": 1,
                "name": 1,
                "path": 1
            })
    for ou in ous_visibles:
        path = ou['path'] + ',' + str(ou['_id'])
        ous.update({str(ou['_id']): get_complete_path(request.db, path)})

    sorted_ous = collections.OrderedDict(
        sorted(list(ous.items()), key=lambda kv: len(kv[1])))
    logger.debug(
        "admins.py ::: statistics - sorted_ous = {}".format(sorted_ous))

    # Defaults
    if not ou_id and list(sorted_ous.items()) is not None and len(
            list(sorted_ous.items())) > 0:
        ou_id = str(list(sorted_ous.items())[0][0])

    logger.debug("admins.py ::: statistics - ou_id = {}".format(ou_id))

    # Objects
    object_counters = request.db.nodes.aggregate([{
        "$match": {
            "path": get_filter_nodes_belonging_ou(ou_id)
        }
    }, {
        "$group": {
            "_id": "$type",
            "count": {
                "$sum": 1
            }
        }
    }],
                                                 cursor={})

    logger.debug("admins.py ::: statistics - object_counters = {}".format(
        object_counters))

    # Policies
    for pol in request.db.policies.find().sort("name"):
        c = request.db.nodes.count_documents({
            "$or": [{
                "path": get_filter_nodes_belonging_ou(ou_id)
            }, {
                "_id": ObjectId(ou_id)
            }],
            "policies." + str(pol['_id']): {
                '$exists': True
            }
        })
        try:
            policy_counters.append([pol[policyname], c])
        except KeyError:
            policy_counters.append([pol['name'], c])

    logger.debug("admins.py ::: statistics - policy_counters = {}".format(
        policy_counters))

    return {
        'policy_counters': policy_counters,
        'object_counters': object_counters,
        'ou_managed': sorted_ous,
        'ou_selected': ou_id,
        'is_superuser': is_superuser
    }
示例#2
0
def report_printers(context, request, file_ext):
    '''
    Generate a report with all the printers and its related computers.

    
    Args:
        ou_id (string) : ID of the OU.

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''    

    # Check current user permissions
    ou_id = check_visibility_of_ou(request)
    if ou_id is None:
        raise HTTPBadRequest()

    # Get printers policy
    policy = request.db.policies.find_one({'slug': 'printer_can_view'})
    property_name = 'policies.' + str(policy['_id']) + '.object_related_list'
    
    # Get all printers
    query = request.db.nodes.find(
        {'type': 'printer', 'path': get_filter_nodes_belonging_ou(ou_id)})

    task = ChefTask()

    rows = []
    if file_ext == 'pdf':
        for item in query:
            row = []
            # No path in PDF because it's too long
            row.append('--')
            row.append(item['name']);
            row.append(treatment_string_to_pdf(item, 'manufacturer', 15))
            row.append(treatment_string_to_pdf(item, 'model', 15))
            row.append(treatment_string_to_pdf(item, 'serial', 15))
            row.append(treatment_string_to_pdf(item, 'registry', 15))

            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find(
                {property_name: str(item['_id'])})
            related_computers = []
            related_objects = []
            for node in nodes_query:
                related_computers = task.get_related_computers(
                    node, related_computers, related_objects)
            
            # Remove duplicated computers
            computer_paths = []
            computers = []
            for computer in related_computers:
                full_path = computer['path'] + '.' + computer['name']
                if not full_path in computer_paths:
                    computer_paths.append(full_path)
                    computers.append(computer)
            
            if len(computers) == 0:
                row.append('--')
                rows.append(row)
            else:
                for computer in computers:
                    computer_row = list(row)
                    computer_row.append(treatment_string_to_pdf(
                        computer, 'name', 15))
                    # No path in PDF because it's too long
                    rows.append(computer_row)

            
    else:
        for item in query:
            row = []
            item['complete_path'] = get_complete_path(request.db, item['path'])
            row.append(treatment_string_to_csv(item, 'complete_path'))
            row.append(treatment_string_to_csv(item, 'name') \
                if file_ext == 'csv' else get_html_node_link(item))
            row.append(treatment_string_to_csv(item, 'manufacturer'))
            row.append(treatment_string_to_csv(item, 'model'))
            row.append(treatment_string_to_csv(item, 'serial'))
            row.append(treatment_string_to_csv(item, 'registry'))

            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find(
                {property_name: str(item['_id'])})
            related_computers = []
            related_objects = []
            for node in nodes_query:
                related_computers = task.get_related_computers(
                    node, related_computers, related_objects)

            # Remove duplicated computers
            computer_paths = []
            computers = []
            for computer in related_computers:
                full_path = computer['path'] + '.' + computer['name']
                if not full_path in computer_paths:
                    computer_paths.append(full_path)
                    computers.append(computer)

                
            if len(computers) == 0:
                row.append('--')
                rows.append(row)
            else:
                for computer in computers:
                    computer_row = list(row)
                    computer_row.append(treatment_string_to_csv(
                        computer, 'name') \
                            if file_ext == 'csv' \
                            else get_html_node_link(computer))
                    computer['complete_path'] = get_complete_path(
                        request.db, item['path'])
                    rows.append(computer_row)
        
    
    header = (_(u'Path').encode('utf-8'),
              _(u'Name').encode('utf-8'),
              _(u'Manufacturer').encode('utf-8'),
              _(u'Model').encode('utf-8'),
              _(u'Serial number').encode('utf-8'),
              _(u'Registry number').encode('utf-8'),
              _(u'Computer').encode('utf-8'))
    
    # Column widths in percentage
    if file_ext == 'pdf':
        widths = (0, 25, 15, 15, 15, 15, 15)
    else:
        widths = (0, 20, 10, 10, 10, 10, 20)
    title =  _(u'Printers and related computers report')
    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
        
    # Sort rows
    rows = sorted(rows, key = lambda i: (i[0].lower(), i[1].lower(),
                                         i[6].lower()))   
        
    return {'headers': header,
            'rows': rows,
            'default_order': [[ 0, 'asc' ], [ 1, 'asc' ], [ 6, 'asc' ]],
            'widths': widths,
            'report_title': title,
            'page': _(u'Page').encode('utf-8'),
            'of': _(u'of').encode('utf-8'),
            'report_type': file_ext,
            'now': now}
示例#3
0
def report_storages(context, request, file_ext):
    '''
    Generate a report with all the storages and its related users.

    
    Args:
        ou_id (string) : ID of the OU.

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''

    # Check current user permissions
    ou_id = check_visibility_of_ou(request)
    if ou_id is None:
        raise HTTPBadRequest()

    # Get storages policy
    policy = request.db.policies.find_one({'slug': 'storage_can_view'})
    property_name = 'policies.' + str(policy['_id']) + '.object_related_list'

    # Get all storages
    query = request.db.nodes.find({
        'type': 'storage',
        'path': get_filter_nodes_belonging_ou(ou_id)
    })

    rows = []
    if file_ext == 'pdf':
        for item in query:
            row = []
            # No path in PDF because it's too long
            row.append('--')
            row.append(item['name'])
            row.append(item['uri'])
            row.append(item['_id'])

            # Get all nodes related with this storage
            nodes_query = request.db.nodes.find(
                {property_name: str(item['_id'])})
            # Targets: ou, group or user
            users = []
            for node in nodes_query:
                if node['type'] == 'ou':
                    users = list(
                        request.db.nodes.find({
                            'path':
                            get_filter_nodes_belonging_ou(node['_id']),
                            'type':
                            'user'
                        }))
                elif node['type'] == 'group':
                    users = list(
                        request.db.nodes.find({
                            '_id': node['members'],
                            'type': 'user'
                        }))
                elif node['type'] == 'user':
                    users = [node]

            if len(users) == 0:
                row.append('--')
                row.append('--')
                rows.append(row)
            else:
                for user in users:
                    user_row = list(row)
                    user_row.append(user['name'])
                    # No path in PDF because it's too long
                    user_row.append('--')
                    rows.append(user_row)

    else:
        for item in query:
            row = []
            item['complete_path'] = get_complete_path(request.db, item['path'])
            row.append(treatment_string_to_csv(item, 'complete_path'))
            if file_ext == 'csv':
                row.append(treatment_string_to_csv(item, 'name'))
            else:  # html links
                row.append(get_html_node_link(item))
            row.append(treatment_string_to_csv(item, 'uri'))
            row.append(item['_id'])

            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find(
                {property_name: str(item['_id'])})
            # Targets: ou, group or user
            users = []
            for node in nodes_query:
                if node['type'] == 'ou':
                    users = list(
                        request.db.nodes.find({
                            'path':
                            get_filter_nodes_belonging_ou(node['_id']),
                            'type':
                            'user'
                        }))
                elif node['type'] == 'group':
                    users = list(
                        request.db.nodes.find({
                            '_id': node['members'],
                            'type': 'user'
                        }))
                elif node['type'] == 'user':
                    users = [node]

            if len(users) == 0:
                row.append('--')
                rows.append(row)
            else:
                for user in users:
                    user_row = list(row)
                    if file_ext == 'csv':
                        user_row.append(treatment_string_to_csv(user, 'name'))
                    else:  # html links
                        user_row.append(get_html_node_link(user))
                    user['complete_path'] = get_complete_path(
                        request.db, item['path'])
                    rows.append(user_row)

    header = (_(u'Path'), _(u'Name'), _(u'Uri'), _(u'Id'), _(u'User'))

    # Column widths in percentage
    widths = (0, 20, 45, 15, 20, 0)
    title = _(u'Storages and related users report')
    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")

    # Sort rows
    rows = sorted(rows,
                  key=lambda i: (i[0].lower(), i[1].lower(), i[4].lower()))

    return {
        'headers': header,
        'rows': rows,
        'default_order': [[0, 'asc'], [1, 'asc'], [4, 'asc']],
        'widths': widths,
        'report_title': title,
        'page': _(u'Page'),
        'of': _(u'of'),
        'report_type': file_ext,
        'now': now
    }
示例#4
0
def report_permission(context, request, file_ext):
    '''
    Generate a report with all the admin permissions.
    
    Args:

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''

    items = []
    total_ous = []
    vmark_html = "<div class='centered'><img alt=\"OK\" " + \
        "src='/static/images/checkmark.jpg'/></div>"
    xmark_html = "<div class='centered'><img alt=\"NOK\" " + \
        "src='/static/images/xmark.jpg'/></div>"

    # Get all admins
    admins = request.db.adminusers.find()

    for admin in admins:
        ou_readonly = admin.get('ou_readonly', [])
        ou_availables = admin.get('ou_availables', [])
        ou_remote = admin.get('ou_remote', [])
        ou_managed = admin.get('ou_managed', [])
        admin_ous = set(ou_readonly + ou_availables + ou_remote + ou_managed)
        total_ous += admin_ous

        for ou in admin_ous:
            item = {}
            item['_id'] = str(admin['_id'])
            item['username'] = admin['username']
            item['OU'] = ou
            item['email'] = admin['email']
            item['name'] = admin['first_name'] + " " + admin['last_name']

            if file_ext == 'csv':
                item['readonly'] = _('Yes') if ou in ou_readonly else _('No')
                item['link'] = _('Yes') if ou in ou_availables else _('No')
                item['remote'] = _('Yes') if ou in ou_remote else _('No')
                item['managed'] = _('Yes') if ou in ou_managed else _('No')
            else:
                item['readonly'] = vmark_html if ou in ou_readonly else \
                    xmark_html
                item[
                    'link'] = vmark_html if ou in ou_availables else xmark_html
                item['remote'] = vmark_html if ou in ou_remote else xmark_html
                item[
                    'managed'] = vmark_html if ou in ou_managed else xmark_html
            items.append(item)

    logger.debug("report_permission: items = {}".format(items))

    # Get all OU names
    ids = [ObjectId(x) for x in total_ous]
    result = request.db.nodes.find({'_id': {
        '$in': ids
    }}, {
        '_id': 1,
        'path': 1
    })
    ou_paths = {}

    for r in result:
        path = r['path'] + ',' + str(r['_id'])
        ou_paths.update({str(r['_id']): get_complete_path(request.db, path)})

    logger.debug("report_permission: ou_paths = {}".format(ou_paths))

    rows = []

    for item in items:
        row = []
        item['OU'] = ou_paths.get(item['OU'], item['OU'])

        if file_ext == 'pdf':
            row.append(item['username'] + "<br/>" + item['email'])
            row.append(item['OU'])
            row.append(treatment_string_to_pdf(item, 'readonly', 80))
            row.append(treatment_string_to_pdf(item, 'link', 80))
            row.append(treatment_string_to_pdf(item, 'remote', 80))
            row.append(treatment_string_to_pdf(item, 'managed', 80))
        else:
            row.append(treatment_string_to_csv(item, 'username'))
            row.append(treatment_string_to_csv(item, 'email'))
            row.append(treatment_string_to_csv(item, 'name'))
            row.append(treatment_string_to_csv(item, 'OU'))
            row.append(treatment_string_to_csv(item, 'readonly'))
            row.append(treatment_string_to_csv(item, 'link'))
            row.append(treatment_string_to_csv(item, 'remote'))
            row.append(treatment_string_to_csv(item, 'managed'))

        rows.append(row)

    if file_ext == 'pdf':
        header = (_(u'Username and Email'), _(u'Organizational Unit'),
                  _(u'Read Only'), _(u'Link'), _(u'Remote'), _(u'Manage'))
    else:
        header = (_(u'Username'), _(u'Email'), _(u'Name'),
                  _(u'Organizational Unit'), _(u'Read Only'), _(u'Link'),
                  _(u'Remote'), _(u'Manage'))

    # Column widths in percentage
    if file_ext == 'pdf':
        widths = (36, 36, 7, 7, 7, 7)
    else:
        widths = (20, 20, 20, 20, 20, 10, 10, 10, 10)

    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")

    title = _(u'Permissions report')

    # Sort rows
    # TODO: Use MongoDB Collations to do a "ignore_case" sorting
    # (MongoDB 2.6 does not support "ignore case" sorting)
    rows = sorted(rows, key=lambda i: (i[0].lower()))

    return {
        'headers': header,
        'rows': rows,
        'default_order': [[0, 'asc']],
        'widths': widths,
        'report_title': title,
        'page': _(u'Page'),
        'of': _(u'of'),
        'report_type': file_ext,
        'now': now
    }
示例#5
0
def report_storages(context, request, file_ext):
    '''
    Generate a report with all the storages and its related users.

    
    Args:
        ou_id (string) : ID of the OU.

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''    

    # Check current user permissions
    ou_id = check_visibility_of_ou(request)
    if ou_id is None:
        raise HTTPBadRequest()
 
    # Get storages policy
    policy = request.db.policies.find_one({'slug': 'storage_can_view'})
    property_name = 'policies.' + str(policy['_id']) + '.object_related_list'
    
    # Get all storages
    query = request.db.nodes.find(
        {'type': 'storage','path': get_filter_nodes_belonging_ou(ou_id)})

    rows = []
    if file_ext == 'pdf':
        for item in query:
            row = []
            # No path in PDF because it's too long
            row.append('--')
            row.append(item['name'])
            row.append(item['uri'])
            row.append(item['_id'])
            
            # Get all nodes related with this storage
            nodes_query = request.db.nodes.find({property_name: str(item['_id'])})
            # Targets: ou, group or user
            users = []
            for node in nodes_query:
                if node['type'] == 'ou':
                    users = list(request.db.nodes.find(
                                    {'path': get_filter_nodes_belonging_ou(node['_id']),
                                    'type': 'user'}))
                elif node['type'] == 'group':
                    users = list(request.db.nodes.find(
                                    {'_id': node['members'], 
                                    'type': 'user'}))
                elif node['type'] == 'user':
                    users = [node]
                
            if len(users) == 0:
                row.append('--')
                row.append('--')                
                rows.append(row)
            else:
                for user in users:
                    user_row = list(row)
                    user_row.append(user['name'])
                    # No path in PDF because it's too long
                    user_row.append('--')
                    rows.append(user_row)

            
    else:
        for item in query:
            row = []
            item['complete_path'] = get_complete_path(request.db, item['path'])
            row.append(treatment_string_to_csv(item, 'complete_path'))
            if file_ext == 'csv':
                row.append(treatment_string_to_csv(item, 'name'))
            else: # html links
                row.append(get_html_node_link(item))
            row.append(treatment_string_to_csv(item, 'uri'))
            row.append(item['_id'])
            
            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find({property_name: str(item['_id'])})
            # Targets: ou, group or user
            users = []
            for node in nodes_query:
                if node['type'] == 'ou':
                    users = list(request.db.nodes.find(
                                    {'path': get_filter_nodes_belonging_ou(node['_id']),
                                    'type': 'user'}))
                elif node['type'] == 'group':
                    users = list(request.db.nodes.find(
                                    {'_id': node['members'], 
                                    'type': 'user'}))
                elif node['type'] == 'user':
                    users = [node]
                
            if len(users) == 0:
                row.append('--')
                rows.append(row)
            else:
                for user in users:
                    user_row = list(row)
                    if file_ext == 'csv':
                        user_row.append(treatment_string_to_csv(user, 'name'))
                    else: # html links
                        user_row.append(get_html_node_link(user))
                    user['complete_path'] = get_complete_path(request.db, item['path'])
                    rows.append(user_row)
        
    
    header = (_(u'Path').encode('utf-8'),
              _(u'Name').encode('utf-8'),
              _(u'Uri').encode('utf-8'),
              _(u'Id').encode('utf-8'),
              _(u'User').encode('utf-8'))
    
    # Column widths in percentage
    widths = (0, 20, 45, 15, 20, 0)
    title =  _(u'Storages and related users report')
    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
        
    return {'headers': header,
            'rows': rows,
            'widths': widths,
            'report_title': title,
            'page': _(u'Page').encode('utf-8'),
            'of': _(u'of').encode('utf-8'),
            'report_type': file_ext,
            'now': now}
示例#6
0
def statistics(context, request):

    object_counters = []
    policy_counters = []
    ous = {}
    ous_visibles = []
    settings = get_current_registry().settings
    policyname = "name_{}".format(settings['pyramid.default_locale_name'])

    is_superuser = request.user.get('is_superuser', False)
    ou_id = request.GET.get('ou_id', None)
    logger.debug("admins.py ::: statistics - ou_id = {}".format(ou_id))

    if is_superuser:
        ous_visibles = request.db.nodes.find(
            {"type": "ou"},
            {"_id": 1, "name": 1, "path": 1}
        )
    else:
        # Get managed ous for admin
        oids = request.user.get('ou_managed', []) + request.user.get('ou_readonly', [])
        ous_visibles = request.db.nodes.find(
            {"_id": { "$in": map(ObjectId, oids) }},
            {"_id": 1, "name": 1, "path": 1}
        )
    for ou in ous_visibles:
        path = ou['path'] + ',' + str(ou['_id'])
        ous.update({str(ou['_id']): get_complete_path(request.db, path)})

    sorted_ous = collections.OrderedDict(sorted(ous.items(), key=lambda kv: len(kv[1])))
    logger.debug("admins.py ::: statistics - sorted_ous = {}".format(sorted_ous))

    # Defaults
    if not ou_id:
        ou_id = str(sorted_ous.items()[0][0])

    logger.debug("admins.py ::: statistics - ou_id = {}".format(ou_id))

    # Objects
    object_counters = request.db.nodes.aggregate([
        {"$match" : { "path": get_filter_nodes_belonging_ou(ou_id)}},
        {"$group" : { "_id" : "$type", "count": {"$sum":1}}}
    ], cursor={})

    logger.debug("admins.py ::: statistics - object_counters = {}".format(object_counters))

    # Policies
    for pol in request.db.policies.find().sort("name"):
        c = request.db.nodes.find({
            "$or": [{"path": get_filter_nodes_belonging_ou(ou_id)}, {"_id":ObjectId(ou_id)}],
            "policies." + str(pol['_id']): {'$exists': True}
        }).count()
        try:
            policy_counters.append([pol[policyname],c])
        except KeyError:
            policy_counters.append([pol['name'],c])

    logger.debug("admins.py ::: statistics - policy_counters = {}".format(policy_counters))

    return {
       'policy_counters': policy_counters,
       'object_counters': object_counters,
       'ou_managed': sorted_ous,
       'ou_selected': ou_id,
       'is_superuser': is_superuser
    }
def report_permission(context, request, file_ext):
    '''
    Generate a report with all the admin permissions.
    
    Args:

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''    

    items = []
    total_ous = []
    vmark_html = "<div class='centered'><img alt=\"OK\" src='/static/images/checkmark.jpg'/></div>"
    xmark_html = "<div class='centered'><img alt=\"NOK\" src='/static/images/xmark.jpg'/></div>"

    # Get all admins
    admins = request.db.adminusers.find()

    for admin in admins:
        ou_readonly = admin.get('ou_readonly', [])
        ou_availables = admin.get('ou_availables', [])
        ou_remote = admin.get('ou_remote', [])
        ou_managed = admin.get('ou_managed', [])
        admin_ous = set(ou_readonly + ou_availables + ou_remote + ou_managed)
        total_ous += admin_ous

        for ou in admin_ous:
            item = {}
            item['_id'] = str(admin['_id'])
            item['username'] = admin['username']
            item['OU'] = ou
            item['email'] = admin['email']
            item['name'] = admin['first_name']+" "+admin['last_name']

            if file_ext == 'csv':
                item['readonly'] = _('Yes') if ou in ou_readonly else _('No')
                item['link'] = _('Yes') if ou in ou_availables else _('No')
                item['remote'] = _('Yes') if ou in ou_remote else _('No')
                item['managed'] = _('Yes') if ou in ou_managed else _('No')
            else:
                item['readonly'] = vmark_html if ou in ou_readonly else xmark_html
                item['link'] = vmark_html if ou in ou_availables else xmark_html
                item['remote'] =  vmark_html if ou in ou_remote else xmark_html
                item['managed'] = vmark_html if ou in ou_managed else xmark_html
            items.append(item)

    logger.debug("report_permission: items = {}".format(items))
            
    # Get all OU names
    ids = map(lambda x: ObjectId(x), total_ous)
    result = request.db.nodes.find({'_id': {'$in': ids}},{'_id':1, 'path':1})
    ou_paths = {}

    for r in result:
        path = r['path']+','+str(r['_id'])
        ou_paths.update({str(r['_id']): get_complete_path(request.db, path)})

    logger.debug("report_permission: ou_paths = {}".format(ou_paths))

    rows = []

    for item in items:    
        row = []
        item['OU'] = ou_paths.get(item['OU'], item['OU'])

        if file_ext == 'pdf':
            row.append(item['username']+"<br/>"+item['email'])
            row.append(item['OU'])
            row.append(treatment_string_to_pdf(item, 'readonly', 80))
            row.append(treatment_string_to_pdf(item, 'link', 80))
            row.append(treatment_string_to_pdf(item, 'remote', 80))
            row.append(treatment_string_to_pdf(item, 'managed', 80))
        else:
            row.append(treatment_string_to_csv(item, 'username'))
            row.append(treatment_string_to_csv(item, 'email'))
            row.append(treatment_string_to_csv(item, 'name'))
            row.append(treatment_string_to_csv(item, 'OU'))
            row.append(treatment_string_to_csv(item, 'readonly'))
            row.append(treatment_string_to_csv(item, 'link'))
            row.append(treatment_string_to_csv(item, 'remote'))
            row.append(treatment_string_to_csv(item, 'managed'))

        rows.append(row)
                
    if file_ext == 'pdf':
        header = (_(u'Username and Email').encode('utf-8'),
                  _(u'Organizational Unit').encode('utf-8'),
                  _(u'Read Only').encode('utf-8'),
                  _(u'Link').encode('utf-8'),
                  _(u'Remote').encode('utf-8'),
                  _(u'Manage').encode('utf-8'))
    else:
        header = (_(u'Username').encode('utf-8'),
                  _(u'Email').encode('utf-8'),
                  _(u'Name').encode('utf-8'),
                  _(u'Organizational Unit').encode('utf-8'),
                  _(u'Read Only').encode('utf-8'),
                  _(u'Link').encode('utf-8'),
                  _(u'Remote').encode('utf-8'),
                  _(u'Manage').encode('utf-8'))

    # Column widths in percentage
    if file_ext == 'pdf':
        widths = (36, 36, 7, 7, 7, 7)
    else:
        widths = (20, 20, 20, 20, 20, 10, 10, 10, 10)

    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")

    title = _(u'Permissions report')
        
    return {'headers': header,
            'rows': rows,
            'widths': widths,
            'report_title': title,
            'page': _(u'Page').encode('utf-8'),
            'of': _(u'of').encode('utf-8'),
            'report_type': file_ext,
            'now': now}
示例#8
0
def report_printers(context, request, file_ext):
    '''
    Generate a report with all the printers and its related computers.

    
    Args:
        ou_id (string) : ID of the OU.

    Returns:
        headers (list) : The headers of the table to export
        rows (list)    : Rows with the report data
        widths (list)  : The witdhs of the columns of the table to export
        page           : Translation of the word "page" to the current language
        of             : Translation of the word "of" to the current language
        report_type    : Type of report (html, csv or pdf)
    '''    

    # Check current user permissions
    ou_id = check_visibility_of_ou(request)
    if ou_id is None:
        raise HTTPBadRequest()

    # Get printers policy
    policy = request.db.policies.find_one({'slug': 'printer_can_view'})
    property_name = 'policies.' + str(policy['_id']) + '.object_related_list'
    
    # Get all printers
    query = request.db.nodes.find(
        {'type': 'printer', 'path': get_filter_nodes_belonging_ou(ou_id)})

    task = ChefTask()

    rows = []
    if file_ext == 'pdf':
        for item in query:
            row = []
            # No path in PDF because it's too long
            row.append('--')
            row.append(item['name']);
            row.append(treatment_string_to_pdf(item, 'manufacturer', 15))
            row.append(treatment_string_to_pdf(item, 'model', 15))
            row.append(treatment_string_to_pdf(item, 'serial', 15))
            row.append(treatment_string_to_pdf(item, 'registry', 15))

            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find({property_name: str(item['_id'])})
            related_computers = []
            related_objects = []
            for node in nodes_query:
                related_computers = task.get_related_computers(node, related_computers, related_objects)
            
            # Remove duplicated computers
            computer_paths = []
            computers = []
            for computer in related_computers:
                full_path = computer['path'] + '.' + computer['name']
                if not full_path in computer_paths:
                    computer_paths.append(full_path)
                    computers.append(computer)
            
            if len(computers) == 0:
                row.append('--')
                rows.append(row)
            else:
                for computer in computers:
                    computer_row = list(row)
                    computer_row.append(treatment_string_to_pdf(computer, 'name', 15))
                    # No path in PDF because it's too long
                    rows.append(computer_row)

            
    else:
        for item in query:
            row = []
            item['complete_path'] = get_complete_path(request.db, item['path'])
            row.append(treatment_string_to_csv(item, 'complete_path'))
            row.append(treatment_string_to_csv(item, 'name') if file_ext == 'csv' else get_html_node_link(item))
            row.append(treatment_string_to_csv(item, 'manufacturer'))
            row.append(treatment_string_to_csv(item, 'model'))
            row.append(treatment_string_to_csv(item, 'serial'))
            row.append(treatment_string_to_csv(item, 'registry'))

            # Get all nodes related with this printer
            nodes_query = request.db.nodes.find({property_name: str(item['_id'])})
            related_computers = []
            related_objects = []
            for node in nodes_query:
                related_computers = task.get_related_computers(node, related_computers, related_objects)

            # Remove duplicated computers
            computer_paths = []
            computers = []
            for computer in related_computers:
                full_path = computer['path'] + '.' + computer['name']
                if not full_path in computer_paths:
                    computer_paths.append(full_path)
                    computers.append(computer)

                
            if len(computers) == 0:
                row.append('--')
                rows.append(row)
            else:
                for computer in computers:
                    computer_row = list(row)
                    computer_row.append(treatment_string_to_csv(computer, 'name') if file_ext == 'csv' else get_html_node_link(computer))
                    computer['complete_path'] = get_complete_path(request.db, item['path'])
                    rows.append(computer_row)
        
    
    header = (_(u'Path').encode('utf-8'),
              _(u'Name').encode('utf-8'),
              _(u'Manufacturer').encode('utf-8'),
              _(u'Model').encode('utf-8'),
              _(u'Serial number').encode('utf-8'),
              _(u'Registry number').encode('utf-8'),
              _(u'Computer').encode('utf-8'))
    
    # Column widths in percentage
    if file_ext == 'pdf':
        widths = (0, 25, 15, 15, 15, 15, 15)
    else:
        widths = (0, 20, 10, 10, 10, 10, 20)
    title =  _(u'Printers and related computers report')
    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
        
    return {'headers': header,
            'rows': rows,
            'widths': widths,
            'report_title': title,
            'page': _(u'Page').encode('utf-8'),
            'of': _(u'of').encode('utf-8'),
            'report_type': file_ext,
            'now': now}