コード例 #1
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)
コード例 #2
0
ファイル: task.py プロジェクト: unkyulee/elastic-cms
def trigger_scheduled_tasks():
    # today
    dayofmonth = datetime.today().day
    dayofweek = datetime.today().weekday()
    hour = datetime.today().hour
    minute = datetime.today().minute

    # get list of tasks that should run under this host
    query = """
        (dayofmonth:{} OR dayofmonth:None) AND
        (dayofweek:{} OR dayofweek:None) AND
        (hour:{} OR hour:None) AND
        (minute:{} OR minute:None)
    """.format(dayofmonth, dayofweek, hour, minute)
    ret = es.list(HOST, 'core_task', 'schedule', query)

    for schedule in ret:
        # check if instance exists
        query = """
            task_id:{} AND
            created:[now-1m TO now+1m]
        """.format(schedule['task_id'])
        instance = es.list(HOST, 'core_task', 'instance', query)
        if len(instance) > 0:
            continue  # task already triggered
        # create instance
        es.create(
            HOST, 'core_task', 'instance', '', {
                "task_id": schedule['task_id'],
                "status": "WAITING",
                "login": "******",
                "created": es.now()
            })
        es.flush(HOST, 'core_task')
コード例 #3
0
ファイル: TaskLog.py プロジェクト: unkyulee/elastic-cms
 def log(self, status, message):
     es.create(self.host, 'core_task', 'log', '', {
         "instance_id": self.instance['id'],
         "action": self.action['name'],
         "status": status,
         "message": message,
         "created": es.now()
     })
     es.flush(self.host, 'core_task')
コード例 #4
0
ファイル: execute.py プロジェクト: unkyulee/elastic-cms
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))

    response = es.create(
        p['host'], 'core_task', 'instance', '', {
            'task_id': task_id,
            'status': 'WAITING',
            'login': p['login'],
            'created': es.now()
        })
    es.flush(p['host'], 'core_task')

    # redirect to status
    return tools.redirect("{}/status/view/{}".format(p['url'],
                                                     response['_id']))
コード例 #5
0
        return tools.alert(str(e))

    ######################################################
    # Record History
    if p['c']['keep_history'] == "Yes":
        for k, v in p['post'].items():
            if k in ["updated", "viewed"]: continue
            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:
コード例 #6
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 %}
        """)
コード例 #7
0
ファイル: create.py プロジェクト: unkyulee/elastic-cms
        try:
            exec(p['workflow']['condition'], globals())
            ret = condition(p)
            if ret != True and ret: return ret
        except SystemExit:
            pass
        except Exception, e:
            return "{}\n{}".format(e.message, traceback.format_exc())
    ######################################################

    # create comment
    id = str(time.time()).replace(".", "")
    p['comment'] = {
        "id": id,
        "comment": tools.get("comment"),
        "created": es.now(),
        "created_by": p['login']
    }
    comments = p["post"].get("comment") \
        if p["post"].get("comment") \
        else []
    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:
コード例 #8
0
ファイル: task.py プロジェクト: unkyulee/elastic-cms
def finished(instance):
    es.update(HOST, 'core_task', 'instance', instance['id'],
              {"finished": es.now()})
    es.flush(HOST, 'core_task')
コード例 #9
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)
コード例 #10
0
    ######################################################
    # 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:
            raise
    ######################################################

    # create post
    p['post']['created'] = es.now()
    p['post']['created_by'] = p['login']
    response = es.create(host, index, 'post', p['post'].get('id'), p["post"])

    # get created id
    p["post"]["id"] = response["_id"]

    # handle attachment
    #try:
    for f in request.files:
        if request.files[f]:
            p["post"][f] = \
                upload.save(request.files[f], p['c']['allowed_exts'],
                            p["post"]["id"], p['c']['upload_dir'])
    #except Exception, e:
    #    es.delete(host, index, 'post', p['post'].get('id'))
コード例 #11
0
ファイル: install.py プロジェクト: unkyulee/elastic-cms
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 %}
        """)