Exemple #1
0
def get(p):
    # load navigation
    navigation_id = p['nav'][-1]
    navigation = es.get(p['host'], 'core_nav', 'navigation', navigation_id)
    if not navigation:
        return tools.alert(
            'not valid navigation id - {}'.format(navigation_id))

    if not tools.get('site_id'): return tools.alert("site id missing")
    if not tools.get('module_id'): return tools.alert("module id missing")

    # edit role
    doc = {
        'site_id': tools.get('site_id'),
        'parent_id': tools.get('parent_id'),
        'module_id': tools.get('module_id'),
        'order_key': int(tools.get('order_key')),
        'is_displayed': tools.get('is_displayed'),
        'name': tools.get('name'),
        'display_name': tools.get('display_name'),
        'url': tools.get('url'),
        'new_window': tools.get('new_window'),
        'description': tools.get('description')
    }
    es.update(p['host'], 'core_nav', 'navigation', navigation_id, doc)
    es.flush(p['host'], 'core_nav')

    return tools.redirect(request.referrer)
Exemple #2
0
def get(p):
    host = p['c']['host']; index = p['c']['index'];

    # init workflow
    wf = tools.get("wf", 'comment_edit')
    p['workflow'] = workflow.init(wf, host, index)

    # load comment
    post_id = p['nav'][-1]
    p['post'] = es.get(host, index, 'post', post_id)
    if not p['post']:
        return tools.alert('not valid post id - {}'.format(post_id))

    # comment_id
    comment_id = tools.get("id")
    p['comment'] = next((x for x in p['post']['comment'] if x['id'] == comment_id), None)
    if not p['comment']:
        return tools.alert('not valid comment_id - {}'.format(comment_id))

    # field map
    fields = es.list(host, index, 'field')
    p['field_map'] = {}
    for field in fields:
        p['field_map'][field['name']] = field['id']

    # update comment
    p['comment']['updated'] = es.now()
    p['comment']['updated_by'] = p['login']
    p['comment']['comment'] = tools.get("comment")

    es.update(host, index, 'post', post_id, p['post'])
    es.flush(host, index)

    return tools.redirect(request.referrer)
Exemple #3
0
def get(p):
    host = p['c']['host']
    index = p['c']['index']

    # load notification
    notification_id = p['nav'][-1]
    p['notification'] = es.get(host, index, 'notification', notification_id)
    if not p['notification']:
        return tools.alert(
            'not valid notification id - {}'.format(notification_id))

    # save notification
    if request.method == "POST":
        doc = {
            'header': tools.get('header'),
            'message': tools.get('message'),
            'recipients': tools.get('recipients'),
            'condition': tools.get('condition'),
            'workflow': tools.get('workflow')
        }
        es.update(host, index, 'notification', notification_id, doc)
        es.flush(host, index)

        return tools.redirect("{}/notification/edit/{}".format(
            p['url'], notification_id))

    return render_template("post/notification/edit.html", p=p)
Exemple #4
0
def set_conf(host, index, name, value):
    config = {
        'name': name,
        'value': value
    }
    es.update(host, index, "config", name, config)
    es.flush(host, index)
Exemple #5
0
def get(p):
    host = p['c']['host']
    index = p['c']['index']

    # load comment
    post_id = p['nav'][-1]
    p['post'] = es.get(host, index, 'post', post_id)
    if not p['post']:
        return tools.alert('not valid post id - {}'.format(post_id))

    # comment_id
    comment_id = tools.get("id")
    p['comment'] = next(
        (x for x in p['post']['comment'] if x['id'] == comment_id), {})
    if not p['comment']:
        return tools.alert('not valid comment_id - {}'.format(comment_id))

    # init workflow
    wf = tools.get('wf', 'comment_delete')
    p['workflow'] = workflow.init(wf, host, index)

    # remove comment
    p['post']['comment'].remove(p['comment'])

    es.update(host, index, 'post', post_id, p['post'])
    es.flush(host, index)

    return tools.redirect(request.referrer)
Exemple #6
0
def get(p):
    # get list of roles
    query = "site_id:{}".format(p['site']['id'])
    option = "size=10000&sort=name:asc"
    p['role_list'] = es.list(p['host'], 'core_nav', 'role', query, option)

    # selected role
    role_id = p['nav'][-1]
    p['role'] = es.get(p['host'], 'core_nav', 'role', role_id)
    if not p['role']:
        p['role'] = p['role_list'][0]

    # get permission
    permission_id = "{}_{}".format(p['role']['id'], p['navigation']['id'])
    p['permission'] = es.get(p['host'], 'core_nav', 'permission', permission_id)

    if request.method == "POST":
        doc = { "operations": [x for x in tools.get('operations', []) if x] }

        if not p['permission']:
            # create permission
            es.create(p['host'], 'core_nav', 'permission', permission_id, doc)
        else:
            # edit permission
            es.update(p['host'], 'core_nav', 'permission', permission_id, doc)
        es.flush(p['host'], 'core_nav')

        return tools.redirect(request.referrer)


    return render_template("post/permission/default.html", p=p)
Exemple #7
0
def get(p):
    host = p['c']['host']
    index = p['c']['index']

    # keep pagination
    p["q"] = tools.get('q', '*')
    # pagination
    p["from"] = int(tools.get('from', 0))
    p["size"] = int(tools.get('size', p['c']['page_size']))
    # sort
    p['sort_field'] = tools.get('sort_field', p['c']['sort_field'])
    p['sort_dir'] = tools.get('sort_field', p['c']['sort_dir'])

    # load post
    post_id = p['nav'][-1]
    p['post'] = es.get(host, index, 'post', post_id)
    if not p['post']:
        return tools.alert('not valid post id - {}'.format(post_id))

    # check ACL
    valid_acl = False
    if not p['post'].get('acl_readonly') and not p['post'].get('acl_edit'):
        valid_acl = True
    if p['login'] == p['post'].get('created_by'): valid_acl = True
    if p['post'].get('acl_readonly'):
        if p['login'] in p['post'].get('acl_readonly'): valid_acl = True
        if 'EVERYONE' in p['post'].get('acl_readonly'): valid_acl = True
    if p['post'].get('acl_edit'):
        if p['login'] in p['post'].get('acl_edit'): valid_acl = True
        if 'EVERYONE' in p['post'].get('acl_edit'): valid_acl = True
    if not valid_acl:
        return tools.alert('permission not granted')

    # return json format
    if tools.get("json"):
        callback = tools.get("callback")
        if not callback:
            return json.dumps(p['post'])
        else:
            return "{}({})".format(callback, json.dumps(p['post']))

    # get comment list
    query = "post_id:{}".format(post_id)
    option = "size=100&sort=created:desc"
    p['comment_list'] = es.list(host, index, 'comment', query, option)

    # increase visit count
    if not p['post'].get("viewed"): p['post']["viewed"] = 0
    p['post']["viewed"] += 1
    es.update(host, index, 'post', post_id, p['post'])

    # field_list
    p['field_list'] = es.list(host, index, 'field', "visible:view",
                              "size=1000&sort=order_key:asc")

    return render_template("post/post/view.html", p=p)
Exemple #8
0
def get(p):
    # Load Action
    action_id = p['nav'][-1]
    p['action'] = es.get(p['host'], 'core_task', 'action', action_id)
    if not p['action']:
        return tools.alert('not valid action id - {}'.format(action_id))
    # update
    es.update(p['host'], 'core_task', 'action', p['action']['id'],
              {'enabled': "No"})
    es.flush(p['host'], 'core_task')

    return tools.redirect(request.referrer)
Exemple #9
0
def get(p):
    # load public url
    public_id = p['nav'][-1]
    public = es.get(p['host'], 'core_proxy', 'public', public_id)
    if not public:
        return tools.alert('not valid public url id - {}'.format(public_id))

    # edit role
    doc = {'url': tools.get('url')}
    es.update(p['host'], 'core_proxy', 'public', public_id, doc)
    es.flush(p['host'], 'core_proxy')

    return tools.redirect(request.referrer)
Exemple #10
0
def run(p):
    AllGood = True
    # Read Query and parse parameters
    root = ET.fromstring(p["action"]["query"])
    SQL_CONNECTION = root.find("SQL_CONNECTION").text
    SQL = root.find("SQL").text.strip()
    ELASTIC_SEARCH_HOST = root.find("ELASTIC_SEARCH_HOST").text
    INDEX = root.find("INDEX").text
    DOC_TYPE = root.find("DOC_TYPE").text
    # Data Body
    SQL_RESULT = None
    # Create sql engine
    engine = create_engine(SQL_CONNECTION)
    # Get SQL connection
    with engine.connect() as conn:
        try:
            p["log"].info(SQL)
            SQL_RESULT = conn.execute(text(SQL))
            p["log"].success("SQL excuted successfully.")
        except Exception, e:
            AllGood = False
            p["log"].error("SQL execution failed", e)

        p["log"].info("start updating document ...")
        row_count = 0
        curr_id = None
        prev_id = None
        body = {}
        for r in SQL_RESULT:  # check if id exists
            if not "id" in r:
                AllGood = False
                p["log"].log(
                    "ERROR",
                    "id doesn't exist\nid: {}\n{}".format(id, str(body)))
                break

            # save current id
            curr_id = r["id"]

            # try to detect when id is changed - means new document
            if curr_id != prev_id and prev_id:
                try:
                    es.update(ELASTIC_SEARCH_HOST, INDEX, DOC_TYPE, prev_id,
                              body)
                    row_count += 1
                except Exception, e:
                    p["log"].error("id: {}\n{}".format(curr_id, str(body)), e)
                    return False

                finally:
Exemple #11
0
def get(p):
    # check if site_id is passed
    p['site_id'] = tools.get('site_id')
    if not p['site_id']: return tools.alert('site id is missing')

    if request.method == "POST":
        # save custom navigation
        p['site'] = {'navigation': tools.get('navigation')}
        es.update(p['host'], 'core_nav', 'site', p['site_id'], p['site'])
        es.flush(p['host'], 'core_nav')

    # load site
    p['site'] = es.get(p['host'], 'core_nav', 'site', p['site_id'])
    if not p['site']: return tools.alert('site id is not valid')

    return render_template("admin/customize/default.html", p=p)
Exemple #12
0
def post(p, host, index):
    # save field
    doc = {
        "is_filter": tools.get("is_filter"),
        "filter_field": tools.get("filter_field"),
        "handler": tools.get("handler"),
        "name": tools.get("name"),
        "visible": tools.get("visible"),
        "order_key": int(tools.get("order_key")),
        "list_tpl": tools.get("list_tpl"),
        "view_tpl": tools.get("view_tpl"),
        "edit_tpl": tools.get("edit_tpl")
    }

    es.update(host, index, 'field', p['field']['id'], doc)
    es.flush(host, index)
    return tools.redirect(request.referrer)
Exemple #13
0
def get(p):
    # load role
    role_id = p['nav'][-1]
    p['role'] = es.get(p['host'], 'core_nav', 'role', role_id)
    if not p['role']:
        return tools.alert('not valid role id - {}'.format(role_id))

    # edit role
    doc = {}
    if tools.get('users'): doc['users'] = tools.get('users')
    if tools.get('name'): doc['name'] = tools.get('name')
    if tools.get('description'): doc['description'] = tools.get('description')

    es.update(p['host'], 'core_nav', 'role', role_id, doc)
    es.flush(p['host'], 'core_nav')

    return tools.redirect(request.referrer)
Exemple #14
0
def post(p, host, index, workflow):
    host = p['c']['host']
    index = p['c']['index']

    doc = {
        "name": tools.get("name"),
        "description": tools.get("description"),
        "status": tools.get("status"),
        "condition": tools.get("condition"),
        "validation": tools.get('validation'),
        "postaction": tools.get('postaction'),
        "screen": tools.get('screen')
    }
    es.update(host, index, 'workflow', workflow["id"], doc)
    es.flush(host, index)

    return tools.redirect(request.referrer)
Exemple #15
0
def get(p):
    if not tools.get('name'): return tools.alert('name is missing')
    if not tools.get('id'): return tools.alert('id is missing')

    # save to configuration
    id = tools.get('id')
    es.update(
        p['host'], 'core_data', 'datasource', id, {
            'navigation_id': p['navigation']['id'],
            'type': tools.get('type'),
            'name': tools.get('name'),
            'description': tools.get('description'),
            'connection': tools.get('connection'),
            'query': tools.get('query')
        })
    es.flush(p['host'], 'core_data')

    return tools.redirect(request.referrer)
Exemple #16
0
def get(p):
    # load login module
    login_module_id = p['nav'][-1]
    login_module = es.get(p['host'], 'core_nav', 'login_module', login_module_id)
    if not login_module:
        return tools.alert('not valid login module id - {}'.format(login_module_id))

    # update new login module
    doc = {
        "type": tools.get('type'),
        "name": tools.get('name'),
        "description": tools.get('description'),
        "priority": tools.get('priority'),
        "configuration": tools.get('configuration')
    }
    es.update(p['host'], 'core_nav', 'login_module', login_module_id, doc)
    es.flush(p['host'], 'core_nav')

    return tools.redirect(request.referrer)
Exemple #17
0
def get(p):
    # load site
    site_id = p['nav'][-1]
    p['site'] = es.get(p['host'], 'core_nav', 'site', site_id)
    if not p['site']:
        return tools.alert('not valid site id - {}'.format(site_id))

    # update site
    doc = {
        'name': tools.get('name'),
        'display_name': tools.get('display_name'),
        'description': tools.get('description'),
        'is_displayed': tools.get('is_displayed'),
        'order_key': tools.get('order_key')
    }
    es.update(p['host'], 'core_nav', 'site', site_id, doc)
    es.flush(p['host'], 'core_nav')

    return tools.redirect(request.referrer)
Exemple #18
0
def get(p):
    # load rule
    rev_proxy_id = p['nav'][-1]
    rev_proxy = es.get(p['host'], 'core_proxy', 'rev_proxy', rev_proxy_id)
    if not rev_proxy:
        return tools.alert('not valid rev_proxy id - {}'.format(rev_proxy_id))


    # edit role
    doc = {
        'inc_url': tools.get('inc_url'),
        'out_url': tools.get('out_url'),
        'auth_method': tools.get('auth_method'),
        'header': tools.get('header')
    }
    es.update(p['host'], 'core_proxy', 'rev_proxy', rev_proxy_id, doc)
    es.flush(p['host'], 'core_proxy')

    return tools.redirect(request.referrer)
Exemple #19
0
def get(p):
    # load task
    task_id = p['nav'][-1]
    p['task'] = es.get(p['host'], 'core_task', 'task', task_id)
    if not p['task']:
        return tools.alert('task not found - {}'.format(task_id))

    if request.method == "POST":
        es.update(
            p['host'], 'core_task', 'task', task_id, {
                'navigation_id': p['navigation']['id'],
                'name': tools.get('name'),
                'runat':
                tools.get('runat') if tools.get('runat') else 'anywhere',
                'description': tools.get('description')
            })
        es.flush(p['host'], 'core_task')

        return tools.redirect(request.referrer)

    # load action list
    # when there are no records then the task fails to run
    option = ''
    if es.count(p['host'], 'core_task', 'action'):
        option = 'size=10000&sort=order_key:asc'

    query = 'task_id:{}'.format(p['task']['id'])
    p['action_list'] = es.list(p['host'], 'core_task', 'action', query, option)
    for action in p['action_list']:
        action['module'] = es.get(p['host'], 'core_task', 'module',
                                  action['module_id'])

    # load schedule list
    query = 'task_id:{}'.format(p['task']['id'])
    p['schedule_list'] = es.list(p['host'], 'core_task', 'schedule', query)

    # load task module List
    option = 'size=10000&sort=description:asc'
    p['task_module_list'] = es.list(p['host'], 'core_task', 'module', '*',
                                    option)

    return render_template("task/task/edit.html", p=p)
Exemple #20
0
def get(p):
    host = p['c']['host']
    index = p['c']['index']

    # load role
    role_id = p['nav'][-1]
    p['role'] = es.get(host, 'core_nav', 'role', role_id)
    if not p['role']:
        return tools.alert('not valid role id - {}'.format(role_id))

    # save role
    if request.method == "POST":
        # edit role
        doc = {}
        if tools.get('users'): doc['users'] = tools.get('users')
        if tools.get('operations'): doc['operations'] = tools.get('operations')

        es.update(p['host'], 'core_nav', 'role', role_id, doc)
        es.flush(p['host'], 'core_nav')

        return tools.redirect(request.referrer)

    return render_template("post/role/edit.html", p=p)
Exemple #21
0
def get(p):
    # Load Action
    action_id = p['nav'][-1]
    p['action'] = es.get(p['host'], 'core_task', 'action', action_id)
    if not p['action']:
        return tools.alert('not valid action id - {}'.format(action_id))

    if request.method == "POST":
        es.update(
            p['host'], 'core_task', 'action', tools.get('action_id'), {
                'task_id': tools.get('task_id'),
                'module_id': tools.get('module_id'),
                'enabled': tools.get('enabled'),
                'stop': tools.get('stop'),
                'order_key': int(tools.get('order_key')),
                'name': tools.get('name'),
                'description': tools.get('description'),
                'connection': tools.get('connection'),
                'query': tools.get('query')
            })
        es.flush(p['host'], 'core_task')

        return tools.redirect(request.referrer)

    # load module
    p['action']['module'] = es.get(p['host'], 'core_task', 'module',
                                   p['action']['module_id'])

    # load task
    p['task'] = es.get(p['host'], 'core_task', 'task', tools.get('task_id'))

    # task module list
    option = 'size=10000&sort=description:asc'
    p['task_module_list'] = es.list(p['host'], 'core_task', 'module', '*',
                                    option)

    return render_template("task/action/edit.html", p=p)
Exemple #22
0
def create_acl(host, index):
    # add acl_readonly field configuration
    doc = {
        "id": 'acl_readonly',
        "name": 'acl_readonly',
        "is_filter": '0',
        "filter_field": '',
        "handler": '',
        "visible": [],
        "order_key": 900,
        "list_tpl": '',
        "view_tpl": '',
        "edit_tpl": """
{% import "widget/select_multi.html" as select_multi %}
{{select_multi.render("acl_readonly", "acl_readonly", item.acl_readonly, ajax="/people?json=1")}}
        """
    }
    es.update(host, index, 'field', doc['id'], doc)
    es.flush(host, index)


    # add acl_edit field configuration
    doc = {
        "id": 'acl_edit',
        "name": 'acl_edit',
        "is_filter": '0',
        "filter_field": '',
        "handler": '',
        "visible": [],
        "order_key": 900,
        "list_tpl": '',
        "view_tpl": '',
        "edit_tpl": """
{% import "widget/select_multi.html" as select_multi %}
{{select_multi.render("acl_edit", "acl_edit", item.acl_edit, ajax="/people?json=1")}}
        """
    }
    es.update(host, index, 'field', doc['id'], doc)
    es.flush(host, index)


    # add workflow
    doc = {
      "status": "",
      "postaction": "",
      "name": "security",
      "screen": [
        "acl_readonly",
        "acl_edit"
      ],
      "validation": "",
      "condition": """
# p - context of current request
def condition(p):
    # author can edit
    if p['post'].get('created_by') == p['login']:
        return True

    # editors can edit
    if p['login'] in p['post'].get('acl_edit'):
        return True

    # if allowed to everyone then
    if 'EVERYONE' in p['post'].get('acl_edit'):
        return True

    return tools.alert('permission not granted')
    # this message will be displayed in the web browser when condition not met
    # return tools.alert('edit allowed to author only')

      """,
      "description": "Set Security"
    }

    es.update(host, index, 'workflow', 'setsecurity', doc)
    es.flush(host, index)
Exemple #23
0
def install(host, base_dir):
    # check if people already exists
    if not es.index_exists(host, "people"):
        # create core_proxy
        schema = tools.read_file("web/templates/install/schema/post.json",
                                 base_dir)
        es.create_index(host, "people", schema)
        es.flush(host, "people")

        # general configuration
        h = host
        n = 4

        # set global config
        tools.set_conf(h, n, 'host', 'http://localhost:9200')
        tools.set_conf(h, n, 'index', 'people')

        # set local config
        config.set_conf(h, 'people', 'name', 'People')
        config.set_conf(h, 'people', 'description',
                        'Members of the organization')
        config.set_conf(h, 'people', 'upload_dir', '')
        config.set_conf(h, 'people', 'allowed_exts', "jpg, jpeg, gif, png")
        config.set_conf(h, 'people', 'page_size', 10)
        config.set_conf(h, 'people', 'query', '*')
        config.set_conf(h, 'people', 'sort_field', 'created')
        config.set_conf(h, 'people', 'sort_dir', 'desc')

        # create fields
        es.create_mapping(
            host, 'people', 'post', {
                "email": {
                    "type": "string"
                },
                "office": {
                    "type": "string"
                },
                "phone": {
                    "type": "string"
                },
                "photo": {
                    "type": "string"
                },
                "password": {
                    "type": "string"
                },
                "new_password": {
                    "type": "string"
                }
            })
        es.flush(host, 'people')

        # add type field configuration
        doc = {
            "id": 'type',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'type',
            "visible": ['view'],
            "order_key": 5,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add id field configuration
        doc = {
            "id": 'id',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'id',
            "visible": ['create', 'view'],
            "order_key": 10,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add password field configuration
        doc = {
            "id":
            'password',
            "is_filter":
            '0',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'password',
            "visible": ['create'],
            "order_key":
            11,
            "list_tpl":
            '',
            "view_tpl":
            '',
            "edit_tpl":
            """
<input type=password class="form-control" name="password">
            """
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add new_password field configuration
        doc = {
            "id":
            'new_password',
            "is_filter":
            '0',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'new_password',
            "visible":
            '',
            "order_key":
            12,
            "list_tpl":
            '',
            "view_tpl":
            '',
            "edit_tpl":
            """
<input type=password class="form-control" name="new_password">
            """
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add title field configuration
        doc = {
            "id": 'title',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'full name',
            "visible": ['create', 'view', 'edit'],
            "order_key": 20,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add office field configuration
        doc = {
            "id": 'office',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'office',
            "visible": ['create', 'view', 'edit'],
            "order_key": 100,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add photo field configuration
        doc = {
            "id": 'photo',
            "is_filter": '0',
            "filter_field": '',
            "handler": 'file',
            "name": 'photo',
            "visible": ['create', 'view', 'edit'],
            "order_key": 100,
            "list_tpl": '',
            "view_tpl": """
{% if item.photo %}
<a href="{{p.url}}/file/view/{{item.photo}}">
  <img src="{{p.url}}/file/view/{{item.photo}}" width=200>
</a>
{% endif %}
            """,
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add email field configuration
        doc = {
            "id": 'email',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'email',
            "visible": ['create', 'view', 'edit'],
            "order_key": 100,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add phone field configuration
        doc = {
            "id": 'phone',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'phone',
            "visible": ['create', 'view', 'edit'],
            "order_key": 100,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # add description field configuration
        doc = {
            "id":
            'description',
            "is_filter":
            '0',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'description',
            "visible": ['create', 'edit', 'view'],
            "order_key":
            200,
            "list_tpl":
            '',
            "view_tpl":
            '',
            "edit_tpl":
            """
<textarea id="description" name="description" class="form-control" rows=5>{{item.description}}</textarea>
            """
        }
        es.update(host, 'people', 'field', doc['id'], doc)
        es.flush(host, 'people')

        # create workflow
        doc = {
            "name": 'create',
            "description": '',
            "status": '',
            "condition": '',
            "validation": """
import hashlib

def validation(p):
    if p['post'].get('password'):
        p['post']['password'] = hashlib.sha512(p['post'].get('password')).hexdigest()


            """,
            "postaction": '',
            "screen": ''
        }
        es.create(host, 'people', 'workflow', '', doc)

        doc = {
            "name": 'password',
            "description": '',
            "status": '',
            "condition": '',
            "validation": """
import hashlib

def validation(p):
    # check if the password matches the orginal
    password = hashlib.sha512(p['post'].get('password')).hexdigest()
    if p['original'].get('password'):
        orig_password = hashlib.sha512(p['original'].get('password')).hexdigest()
    else:
        orig_password = ''

    # update to new password
    if password == orig_password:
        p['post']['password'] = hashlib.sha512(p['post'].get('new_password')).hexdigest()

    else:
        # if the password doesn't match then alert
        raise Exception('password does not match')

            """,
            "postaction": '',
            "screen": ['password', 'new_password']
        }
        es.create(host, 'people', 'workflow', '', doc)

        # add default people
        doc = {
            "id": 'EVERYONE',
            "title": 'EVERYONE',
            "description":
            'system account representing all authenticated users',
            "created": es.now(),
            "updated": es.now()
        }
        es.update(host, 'people', 'post', doc['id'], doc)
        es.flush(host, 'people')

        # set permission
        permission_id = 'Admins_4'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit', 'post/delete',
                'config/', 'list_item/', 'layout/', 'field/default',
                'field/edit', 'mapping/default', 'mapping/edit',
                'backup/default', 'backup/download', 'backup/restore',
                'role/default', 'role/edit', 'permission/default',
                'permission/edit', 'workflow/default', 'workflow/create',
                'workflow/edit', 'workflow/delete'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)

        permission_id = 'Users_4'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)

        # side layout
        config.set_conf(
            h, 'people', 'side', """
<button type="button" class="btn btn-danger btn-block"
    onclick="location='{{p.url}}/post/edit/{{p.post.id}}?wf=password'">Change Password</button>
<br>
        """)

        # people item renderer
        config.set_conf(
            h, 'people', 'search_item_template', """
{% extends "post/search/base.html" %}

{% macro default(post) %}
<table class="table">
  <tr>
    <th class="bg-success" colspan="2">
      <span>
        <a href="{{ p.url }}/post/view/{{ post.id }}">
          <b>{{post.highlight.title|first|safe}}</b>
        </a>
      </span>
    </th>
  </tr>

  <tbody>


    <tr>
      <td>
        <!-- photo -->
        {% if post.photo %}
        <a href="{{p.url}}/post/view/{{post.id}}">
          <img src="{{p.url}}/file/view/{{post.photo}}" height=120>
        </a>
        {% endif %}
      </td>
      <td>

        {% if post.email %}
        <div class="col-lg-6 col-md-6">
          <label class="col-lg-4 col-md-4 control-label">email</label>
          <div class="col-lg-8 col-md-8">{{post.email}}</div>
        </div>
        {% endif %}

        {% if post.phone %}
        <div class="col-lg-6 col-md-6">
          <label class="col-lg-4 col-md-4 control-label">phone</label>
          <div class="col-lg-8 col-md-8">{{post.phone}}</div>
          </div>
        </div>
        {% endif %}


        {% if post.office %}
        <div class="col-lg-6 col-md-6">
          <label class="col-lg-4 col-md-4 control-label">office</label>
          <div class="col-lg-8 col-md-8">{{post.office}}</div>
          </div>
        </div>
        {% endif %}

      </td>
    </tr>


  </tbody>
</table>

<br>
{% endmacro %}

{% block search_result %}

{% include "post/search/part/summary.html" %}
{% include "post/search/part/didyoumean.html" %}

{% for post in p.post_list %}
  {{ default(post) }}
{% endfor %}

{% include "post/search/part/pagination.html" %}

{# display create icon when post/create is allowed #}
{% if 'post/create' in p.allowed_operation %}
<div class="col-lg-12 text-right">
  <a href="{{p.url}}/post/create" title="new">
    <button type="button" class="btn btn-xs btn-danger">
      <span class="glyphicon glyphicon-plus"></span> New
    </button>
  </a>
</div>
{% endif %}


{% endblock %}
        """)
Exemple #24
0
    comments.append(p['comment'])

    ######################################################
    # validate
    if p['workflow'] and p['workflow'].get('validation'):
        try:
            exec(p['workflow']['validation'], globals())
            ret = validation(p)
            if ret != True and ret: return ret
        except SystemExit:
            pass
        except Exception, e:
            return "{}\n{}".format(e.message, traceback.format_exc())
    ######################################################

    es.update(host, index, 'post', p["post"]['id'], p['post'])
    es.update(host, index, 'post', p["post"]['id'], {"comment": comments})
    es.flush(host, index)

    ######################################################
    # Post action
    if p['workflow'] and p['workflow'].get('postaction'):
        try:
            exec(p['workflow']['postaction'], globals())
            postaction(p)
        except SystemExit:
            pass
        except Exception, e:
            return "{}\n{}".format(e.message, traceback.format_exc())
    ######################################################
Exemple #25
0
def install(host, base_dir):
    index = 'schedule'
    h = host
    n = 5
    # check if people already exists
    if not es.index_exists(host, index):
        # create core_proxy
        schema = tools.read_file("web/templates/install/schema/post.json",
                                 base_dir)
        es.create_index(host, index, schema)
        es.flush(host, index)

        # global configuration
        tools.set_conf(h, n, 'host', 'http://localhost:9200')
        tools.set_conf(h, n, 'index', index)

        # local configuration
        config.set_conf(h, 'schedule', 'name', 'Schedule')
        config.set_conf(h, 'schedule', 'description',
                        'News and event of the organization')
        config.set_conf(h, 'schedule', 'upload_dir', '')
        config.set_conf(h, 'schedule', 'allowed_exts', "jpg, jpeg, gif, png")
        config.set_conf(h, 'schedule', 'page_size', 1000)
        config.set_conf(h, 'schedule', 'query', '*')
        config.set_conf(h, 'schedule', 'sort_field', 'start')
        config.set_conf(h, 'schedule', 'sort_dir', 'desc')

        # create fields
        es.create_mapping(
            host, index, 'post', {
                "attendee": {
                    "type": "string"
                },
                "organizer": {
                    "type": "string"
                },
                "finish": {
                    "type": "date"
                },
                "start": {
                    "type": "date"
                }
            })
        es.flush(host, index)

        # add organizer field configuration
        doc = {
            "id":
            'organizer',
            "is_filter":
            '1',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'organizer',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key":
            15,
            "list_tpl":
            '{{ item.organizer | first }}',
            "view_tpl":
            """
{% for organizer_id in item.organizer|getlist %}
    {% set organizer = organizer_id|get('http://localhost:9200', 'people', 'post') %}
    {% if organizer %}
        <div class="row">
            <div class="col-sm-11">
                <a href="/schedule?organizer={{organizer.id}}">
                    {{ organizer.title }}
                </a>
            </div>
            <div class="col-sm-1">
                <a href="/people/post/view/{{organizer.id}}">
                  <i class="fa fa-external-link" aria-hidden="true"></i>
                </a>
            </div>
        </div>
    {% endif %}
{% endfor %}
            """,
            "edit_tpl":
            """
<select id="organizer" style="width:100%"></select>
<ul id="organizer_list" class="list-group"></ul>

<script>
$(document).ready(function() {
  $("#organizer").select2({
    placeholder: "search for people",
    ajax: {
      url: '/people?json=1',
      dataType: 'jsonp',
      data: function (params) { return { q: params.term ? params.term + "*" : "*" } },
      processResults: function (data, page) {
        ResultList = { "results" : [] , "more":false }
        data.hits.hits.forEach(function(entry) {
          ResultList.results.push({
            "id": entry._id,
            "text": entry._source.title
          })
        });
        return ResultList;
      }
    }
  });

  $("#organizer").on('select2:select', function (evt) {
    // Do something
    id = evt.params.data.id;
    text = evt.params.data.text;

    add_organizer( id, text );
  });

  $( "#organizer_list" ).sortable();
  $( "#organizer_list" ).disableSelection();

});


</script>

<script id="organizer_item" type="text/html">
<li class="list-group-item" id="$id">
    <div class="container-fluid" >
        <div class="row">
            <div class="col-md-1">
                <a href="javascript:remove_organizer('$id')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a>
            </div>
            <div class="col-md-11">
                $organizer
            </div>
        </div>
    </div>
    <input type="checkbox" checked=1 style="display: none" name="organizer" value="$id">
</li>
</script>

<script>
String.prototype.replaceAll = function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }
    return this.split(search).join(replace);
}

function add_organizer(id, organizer, affiliation) {
    var organizer_tpl = $("#organizer_item").html()
    organizer_tpl = organizer_tpl.replaceAll("$id", id)
    organizer_tpl = organizer_tpl.replaceAll("$organizer", organizer)

    var organizer_list = document.getElementById('organizer_list');
    organizer_list.insertAdjacentHTML('beforeend', organizer_tpl);
}

function remove_organizer(id) {
    $("#"+id).remove()
}

// add organizers
{% for a in item.organizer|getlist %}
    {% set organizer = a|get('http://localhost:9200', 'people', 'post') %}
    {% if organizer %}
        add_organizer( "{{ organizer.id }}", "{{ organizer.title }}" );
    {% endif %}
{% endfor %}

</script>
            """
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add start field configuration
        doc = {
            "id":
            'start',
            "is_filter":
            '0',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'start',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key":
            50,
            "list_tpl":
            '{{item.start|dt}}',
            "view_tpl":
            '{{item.start|dt}}',
            "edit_tpl":
            """
<input type="text" id="start" name="start" value="{{item.start}}">
<script>
$(function() {
    $("#start").datepicker({
      dateFormat: "yy-mm-dd"
    });
});
</script>
            """
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add finish field configuration
        doc = {
            "id":
            'finish',
            "is_filter":
            '0',
            "filter_field":
            '',
            "handler":
            '',
            "name":
            'finish',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key":
            55,
            "list_tpl":
            '{{item.finish|dt}}',
            "view_tpl":
            '{{item.finish|dt}}',
            "edit_tpl":
            """
<input type="text" id="finish" name="finish" value="{{item.finish}}">
<script>
$(function() {
    $("#finish").datepicker({
      dateFormat: "yy-mm-dd"
    });
});
</script>
"""
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add attendee field configuration
        doc = {
            "id":
            'attendee',
            "is_filter":
            '1',
            "filter_field":
            '',
            "handler":
            'multiple',
            "name":
            'attendee',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key":
            100,
            "list_tpl":
            '{{ item.attendee | first }}',
            "view_tpl":
            """
{% for attendee_id in item.attendee|getlist %}
    {% set attendee = attendee_id|get('http://localhost:9200', 'people', 'post') %}
    {% if attendee %}
        <div class="row">
            <div class="col-sm-11">
                <a href="/schedule?attendee={{attendee.id}}">
                    {{ attendee.title }}
                </a>
            </div>
            <div class="col-sm-1">
                <a href="/people/post/view/{{attendee.id}}">
                  <i class="fa fa-external-link" aria-hidden="true"></i>
                </a>
            </div>
        </div>
    {% endif %}
{% endfor %}
            """,
            "edit_tpl":
            """
<select id="attendee" style="width:100%"></select>
<ul id="attendee_list" class="list-group"></ul>

<script>
$(document).ready(function() {
  $("#attendee").select2({
    placeholder: "search for people",
    ajax: {
      url: '/people?json=1',
      dataType: 'jsonp',
      data: function (params) { return { q: params.term ? params.term + "*" : "*" } },
      processResults: function (data, page) {
        ResultList = { "results" : [] , "more":false }
        data.hits.hits.forEach(function(entry) {
          ResultList.results.push({
            "id": entry._id,
            "text": entry._source.title
          })
        });
        return ResultList;
      }
    }
  });

  $("#attendee").on('select2:select', function (evt) {
    // Do something
    id = evt.params.data.id;
    text = evt.params.data.text;

    add_attendee( id, text );
  });

  $( "#attendee_list" ).sortable();
  $( "#attendee_list" ).disableSelection();

});


</script>

<script id="attendee_item" type="text/html">
<li class="list-group-item" id="$id">
    <div class="container-fluid" >
        <div class="row">
            <div class="col-md-1">
                <a href="javascript:remove_attendee('$id')"><i class="fa fa-minus-circle" aria-hidden="true"></i></a>
            </div>
            <div class="col-md-11">
                $attendee
            </div>
        </div>
    </div>
    <input type="checkbox" checked=1 style="display: none" name="attendee" value="$id">
</li>
</script>

<script>
String.prototype.replaceAll = function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }
    return this.split(search).join(replace);
}

function add_attendee(id, attendee, affiliation) {
    var attendee_tpl = $("#attendee_item").html()
    attendee_tpl = attendee_tpl.replaceAll("$id", id)
    attendee_tpl = attendee_tpl.replaceAll("$attendee", attendee)

    var attendee_list = document.getElementById('attendee_list');
    attendee_list.insertAdjacentHTML('beforeend', attendee_tpl);
}

function remove_attendee(id) {
    $("#"+id).remove()
}

// add attendees
{% for a in item.attendee|getlist %}
    {% set attendee = a|get('http://localhost:9200', 'people', 'post') %}
    {% if attendee %}
        add_attendee( "{{ attendee.id }}", "{{ attendee.title }}" );
    {% endif %}
{% endfor %}

</script>
            """
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add title field configuration
        doc = {
            "id": 'title',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'title',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key": 10,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add description field configuration
        doc = {
            "id": 'description',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "name": 'description',
            "visible": ['view'],
            "order_key": 1000,
            "list_tpl": '',
            "view_tpl": '<pre><code>{{item.description}}</code></pre>',
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # set permission
        permission_id = 'Admins_5'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit', 'post/delete',
                'config/', 'list_item/', 'layout/', 'field/default',
                'field/edit', 'mapping/default', 'mapping/edit',
                'backup/default', 'backup/download', 'backup/restore',
                'role/default', 'role/edit', 'permission/default',
                'permission/edit', 'workflow/default', 'workflow/create',
                'workflow/edit', 'workflow/delete'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)

        permission_id = 'Users_5'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)

        # add test event
        doc = {
            "id": 'test',
            "title": "You have installed Elastic-CMS today !",
            "organizer": "EVERYONE",
            "attendee": "EVERYONE",
            "start": es.now(),
            "finish": es.now(),
            "description":
            'Thanks for installing the system. This is a sample event',
            "created": es.now(),
            "updated": es.now()
        }
        es.update(host, index, 'post', doc['id'], doc)
        es.flush(host, index)

        # people item renderer
        config.set_conf(
            h, 'schedule', 'search_item_template', """
{% extends "post/search/base.html" %}

{% block search_result %}
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.7.2/fullcalendar.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.7.2/fullcalendar.min.js"></script>

<div class="col-lg-12">
  <div id='calendar'></div>
</div>

<script>
$(document).ready(function() {

    // page is now ready, initialize the calendar...
    $('#calendar').fullCalendar({
      eventLimit: true, // allow "more" link when too many events
      events: [
        {% for post in p.post_list %}
        {
            id:'{{post.id}}',
            title: '{{post.title}}',
            tooltip: '{{post.title}}',
            start: '{{post.start}}'
        }
          {% if not loop.last %}, {% endif %}
        {% endfor %}
      ],
      eventClick: function(calEvent, jsEvent, view) {
        location = '{{p.url}}/post/view/' + calEvent.id
      },
      eventRender: function(event, element) {
        element.attr('title', event.tooltip);
      }
    })

});
</script>


{# display create icon when post/create is allowed #}
{% if 'post/create' in p.allowed_operation %}
<div class="col-lg-12 text-right">
  <br>
  <a href="{{p.url}}/post/create" title="new">
    <button type="button" class="btn btn-xs btn-danger">
      <span class="glyphicon glyphicon-plus"></span> New Schedule
    </button>
  </a>
</div>
{% endif %}

{% endblock %}
        """)
Exemple #26
0
def status(instance, status):
    es.update(HOST, 'core_task', 'instance', instance['id'],
              {"status": status})
    es.flush(HOST, 'core_task')
Exemple #27
0
def finished(instance):
    es.update(HOST, 'core_task', 'instance', instance['id'],
              {"finished": es.now()})
    es.flush(HOST, 'core_task')
Exemple #28
0
def install_data(host, base_dir):
    # delete module, operation
    try:
        es.delete_query(host, "core_nav", "module",
                        {"query": {
                            "match_all": {}
                        }})
        es.delete_query(host, "core_nav", "operation",
                        {"query": {
                            "match_all": {}
                        }})
    except:
        pass

    # bulk insert data
    bulk_install = tools.read_file(
        "web/templates/install/schema/core_nav_bulk.json", base_dir)
    es.bulk(host, bulk_install)

    # task module definition
    os.chdir("{}/web/templates/install/task_module".format(base_dir))
    for file in glob.glob("*.xml"):
        id = file.split("_")[0]
        definition = readfile(file)
        es.update(host, "core_task", "module", id, {"definition": definition})

    # install root site
    if not es.get(host, "core_nav", "site", 0):
        es.create(host, "core_nav", "site", 0, {
            "name": "",
            "display_name": "Root",
            "description": "Root site"
        })

    # install default navigation - dashboard
    if not es.get(host, "core_nav", "navigation", 0):
        es.create(
            host, "core_nav", "navigation", 0, {
                "name": "",
                "display_name": "Home",
                "site_id": 0,
                "module_id": "4",
                "is_displayed": "1",
                "order_key": 0
            })

    # install default navigation - install
    if not es.get(host, "core_nav", "navigation", 1):
        es.create(
            host, "core_nav", "navigation", 1, {
                "name": "install",
                "display_name": "install",
                "site_id": 0,
                "module_id": "1",
                "is_displayed": "0"
            })

    # install default navigation - auth
    if not es.get(host, "core_nav", "navigation", 2):
        es.create(
            host, "core_nav", "navigation", 2, {
                "name": "auth",
                "display_name": "Authentication",
                "site_id": 0,
                "module_id": "2",
                "is_displayed": "0"
            })

    # install default navigation - admin
    if not es.get(host, "core_nav", "navigation", 3):
        es.create(
            host, "core_nav", "navigation", 3, {
                "name": "admin",
                "display_name": "admin",
                "site_id": 0,
                "module_id": "3",
                "is_displayed": "0"
            })

    # install default navigation - people
    if not es.get(host, "core_nav", "navigation", 4):
        es.create(
            host, "core_nav", "navigation", 4, {
                "name": "people",
                "display_name": "People",
                "site_id": 0,
                "module_id": "7",
                "is_displayed": "1",
                "order_key": 4
            })

    # install default navigation - schedule
    if not es.get(host, "core_nav", "navigation", 5):
        es.create(
            host, "core_nav", "navigation", 5, {
                "name": "schedule",
                "display_name": "Schedule",
                "site_id": 0,
                "module_id": "7",
                "is_displayed": "1",
                "order_key": 5
            })

    # install default navigation - document management
    if not es.get(host, "core_nav", "navigation", 6):
        es.create(
            host, "core_nav", "navigation", 6, {
                "name": "doc",
                "display_name": "Document",
                "site_id": 0,
                "module_id": "7",
                "is_displayed": "1",
                "order_key": 6
            })
Exemple #29
0
            if p['original'].get(k) != p['post'].get(k):
                # write history
                doc = {
                    "id": p["post"]["id"],
                    "field": k,
                    "previous": unicode(p['original'].get(k)),
                    "current": unicode(p['post'].get(k)),
                    "login": p['login'],
                    "created": es.now()
                }
                es.create(host, index, 'log', '', doc)

    # update post
    p['post']['updated'] = es.now()
    p['post']['updated_by'] = p['login']
    es.update(host, index, 'post', p["post"]["id"], p["post"])
    es.flush(host, index)


    ######################################################
    # Post action
    p['post'] = es.get(host, index, 'post', p["post"]["id"])
    if p['workflow'] and p['workflow'].get('postaction'):
        try:
            exec (p['workflow']['postaction'], globals())
            ret = postaction(p)
            if ret != True and ret: return ret
        except SystemExit: pass
        except Exception, e:
            raise
    ######################################################
Exemple #30
0
def install(host, base_dir):
    index = 'doc'
    h = host
    n = 6
    # check if people already exists
    if not es.index_exists(host, index):
        # create core_proxy
        schema = tools.read_file(
            "web/templates/install/schema/post.json", base_dir)
        es.create_index(host, index, schema)
        es.flush(host, index)

        # global configuration
        tools.set_conf(h, n, 'host', 'http://localhost:9200')
        tools.set_conf(h, n, 'index', index)

        # local configuration
        config.set_conf(h, 'doc', 'name', 'Document')
        config.set_conf(h, 'doc', 'description', 'Document Management')
        config.set_conf(h, 'doc', 'upload_dir', '')
        config.set_conf(h, 'doc', 'allowed_exts', "jpg, jpeg, gif, png, doc, docx, pdf, ppt, pptx, txt, xls, xlsx, rtf, odp, mp4, avi, ogg")
        config.set_conf(h, 'doc', 'page_size', 30)
        config.set_conf(h, 'doc', 'query', '*')
        config.set_conf(h, 'doc', 'sort_field', 'created')
        config.set_conf(h, 'doc', 'sort_dir', 'desc')

        # create fields
        es.create_mapping(host, index, 'post', {
            "filepath": { "type": "string" }
        })
        es.flush(host, index)

        # add title field configuration
        doc = {
            "id": 'title',
            "name": 'title',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "visible": ['create', 'view', 'edit', 'list'],
            "order_key": 100,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add description field configuration
        doc = {
            "id": 'description',
            "name": 'description',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "visible": ['create', 'view', 'edit'],
            "order_key": 101,
            "list_tpl": '',
            "view_tpl": '<pre><code>{{ item.description }}</code></pre>',
            "edit_tpl": """
<textarea id="description" name="description" class="form-control" rows=5>{{item.description}}</textarea>
            """
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add filepath field configuration
        doc = {
            "id": 'filepath',
            "name": 'filepath',
            "is_filter": '0',
            "filter_field": '',
            "handler": 'file',
            "visible": ['create', 'view', 'edit'],
            "order_key": 105,
            "list_tpl": '',
            "view_tpl": """
<a href="{{p.url}}/file/view/{{item.filepath}}?id={{item.id}}" class="btn btn-danger btn-xs">download</a>
<a href="{{p.url}}/file/view/{{item.filepath}}?id={{item.id}}" target=_blank>
{{item.filepath|filename(item.id)}}
</a>
            """,
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)


        # add created_by field configuration
        doc = {
            "id": 'created_by',
            "name": 'created_by',
            "is_filter": '1',
            "filter_field": '',
            "handler": '',
            "visible": ['list'],
            "order_key": 102,
            "list_tpl": '',
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)

        # add created_by field configuration
        doc = {
            "id": 'created',
            "name": 'created',
            "is_filter": '0',
            "filter_field": '',
            "handler": '',
            "visible": ['list'],
            "order_key": 103,
            "list_tpl": """{{item.created|dt}}""",
            "view_tpl": '',
            "edit_tpl": ''
        }
        es.update(host, index, 'field', doc['id'], doc)
        es.flush(host, index)



        # create acl
        create_acl(host, index)


        # set permission
        permission_id = 'Admins_6'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit', 'post/delete',
                'config/', 'list_item/', 'layout/', 'field/default', 'field/edit',
                'mapping/default', 'mapping/edit', 'backup/default', 'backup/download',
                'backup/restore', 'role/default', 'role/edit', 'permission/default',
                'permission/edit', 'workflow/default', 'workflow/create', 'workflow/edit',
                'workflow/delete'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)


        permission_id = 'Users_6'
        doc = {
            "operations": [
                'saerch/', 'post/view', 'filter/', 'file/', 'history/list',
                'history/view', 'post/create', 'post/edit'
            ]
        }
        es.create(host, 'core_nav', 'permission', permission_id, doc)


        # add test document
        doc = {
            "id": 'test_doc',
            "title": "You have installed Elastic-CMS today !",
            "description": "This is sample document",
            "created": es.now(),
            "created_by": "EVERYONE",
            "acl_readonly": "EVERYONE",
            "acl_edit": "EVERYONE"
        }
        es.update(host, index, 'post', doc['id'], doc)
        es.flush(host, index)