Example #1
0
def blog_publish_progress(blog_id, original_queue_length):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    queue_count = 0

    control_jobs = Queue.control_jobs(blog)

    if control_jobs.count() > 0:
        # queue_count = queue.process_queue(blog)
        # queue_count = transaction(queue.process_queue)(blog)
        queue_count = q_p(blog)
        time.sleep(RETRY_INTERVAL * 5)
    else:
        queue_count = 0

    percentage_complete = int((1 - (int(queue_count) / int(original_queue_length))) * 100)
    import settings
    return template('queue/queue_run_include',
            queue_count=queue_count,
            blog=blog,
            break_path='{}/blog/{}/publish/break'.format(BASE_URL, blog.id),
            settings=settings,
            percentage_complete=percentage_complete)
Example #2
0
def blog_publish_process(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    control_jobs = Queue.control_jobs(blog)

    if control_jobs.count() > 0:
        queue_count = q_p(blog)
        # queue_count = transaction(queue.process_queue)(blog)
        time.sleep(RETRY_INTERVAL * 5)
    else:
        jobs = Queue.jobs(blog)
        if jobs.count() > 0:
            queue_count = jobs.count()
            Queue.start(blog, queue_count)
            queue_count = q_p(blog)
            # queue_count = transaction(queue.process_queue)(blog)
            time.sleep(RETRY_INTERVAL * 5)
        else:
            queue_count = 0

    import settings
    return template('queue/queue_counter_include',
            blog=blog,
            settings=settings,
            queue_count=queue_count)
Example #3
0
def blog_delete_preview(blog_id, preview_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    f = lambda:None
    f.blog = blog

    if preview_id == 'all':
        previews_to_delete = blog.fileinfos.where(FileInfo.preview_path.is_null(False))
        message = 'All previews for blog {} deleted.'.format(blog.for_display)
        f.msg = 'Delete all'
    else:
        previews_to_delete = blog.fileinfos.where(FileInfo.id == preview_id)
        message = 'Preview for fileinfo {} deleted.'.format(preview_id)
        f.msg = 'Delete preview {}'.format(preview_id)

    for n in previews_to_delete:
        if n.page is not None:
            n.page.delete_preview()
        else:
            n.template_mapping.template.delete_preview()

    tags = template_tags(blog_id=blog.id, user=user)

    from core.utils import Status

    tags.status = Status(
        type='success',
        message=message,
        close=False,
        )

    return report(tags, 'blog_delete_preview', f)
Example #4
0
def media_edit(blog_id, media_id, status=None):
    '''
    UI for editing a given media entry
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    is_member = auth.is_blog_member(user, blog)
    media = Media.load(media_id, blog)
    permission = auth.is_media_owner(user, media)

    from core.ui import kv
    kv_ui_data = kv.ui(media.kv_list())

    tags = template_tags(blog=blog,
         media=media,
         status=status,
         user=user,
        )
    tags.sidebar = sidebar.render_sidebar(
            panel_set='edit_media',
            status_badge=status_badge,
            kv_object='Media',
            kv_objectid=media.id,
            kv_ui=kv_ui_data)

    return media_edit_output(tags)
Example #5
0
def tag_make_for_page(blog_id=None, page_id=None):

    user = auth.is_logged_in(request)

    if page_id is None:
        # page = Page()
        blog = Blog.load(blog_id)
        page = None
        permission = auth.is_blog_editor(user, blog)
        assoc = {'blog':blog}
    else:
        page = Page.load(page_id)
        blog = None
        permission = auth.is_page_editor(user, page)
        assoc = {'page':page}

    tag_name = request.forms.getunicode('tag')

    if len(tag_name) < 1:
        return None

    # Note that this is a single tag only!

    tag = Tag.add_or_create(
        [tag_name, ],
        **assoc
        )

    if len(tag[0]) > 0:
        tpl = template(tag[0][0].new_tag_for_display)
    else:
        tpl = template(tag[1][0].for_display)

    return tpl
Example #6
0
def blog_publish(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    queue_length = Queue.job_counts(blog=blog)

    if queue_length > 0:
        start_message = template('queue/queue_run_include',
            queue=Queue.jobs(blog),
            percentage_complete=0,
            blog=blog,
            break_path='{}/blog/{}/publish/break'.format(BASE_URL, blog.id)
            )
        Queue.start(blog, queue_length)
    else:
        start_message = "Queue empty."

    tags = template_tags(blog_id=blog.id,
            user=user)

    #
    return template('queue/queue_run_ui',
        start=queue_length,
        start_message=start_message,
        action_url="../../blog/{}/publish/progress/{}".format(blog.id,
                                                              queue_length),
        title='Publishing queue progress',
        # search_context=(search_context['blog_queue'], blog),
        menu=generate_menu('blog_queue', blog),
        **tags.__dict__)
Example #7
0
def blog_user(user_id, blog_id):
    # Obtains user edit in blog context.
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)
    user_to_edit = User.find(user_id)

    return edit_user(user_to_edit, editing_user=user, context=blog_context, blog=blog)
Example #8
0
def media_edit_save(blog_id, media_id):
    '''
    Save changes to a media entry.
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    is_member = auth.is_blog_member(user, blog)
    media = Media.load(media_id)
    permission = auth.is_media_owner(user, media)

    friendly_name = request.forms.getunicode('media_friendly_name')

    changes = False

    if friendly_name != media.friendly_name:
        changes = True
        media.friendly_name = friendly_name

    import datetime

    if changes is True:
        media.modified_date = datetime.datetime.utcnow()
        media.save()

        status = utils.Status(
            type='success',
            message='Changes to media <b>{}</b> saved successfully.'.format(
                media.for_display)
            )
    else:

        status = utils.Status(
            type='warning',
            no_sure=True,
            message='No discernible changes submitted for media <b>{}</b>.'.format(
                media.id, media.for_display)
            )

    logger.info("Media {} edited by user {}.".format(
        media.for_log,
        user.for_log))

    from core.ui import kv
    kv_ui_data = kv.ui(media.kv_list())

    tags = template_tags(blog=blog,
         media=media,
         status=status,
         user=user)

    tags.sidebar = sidebar.render_sidebar(
        panel_set='edit_media',
        status_badge=status_badge,
        kv_object='Media',
        kv_objectid=media.id,
        kv_ui=kv_ui_data)

    return media_edit_output(tags)
Example #9
0
def blog_new_page(blog_id):
    '''
    Displays UI for newly created (unsaved) page
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    tags = template_tags(blog=blog, user=user)

    tags.page = Page()

    referer = request.headers.get('Referer')
    if referer is None:
        referer = BASE_URL + "/blog/" + str(blog.id)

    blog_new_page = tags.page

    for n in new_page_submission_fields:
        blog_new_page.__setattr__(n, "")
        if n in request.query:
            blog_new_page.__setattr__(n, request.query.getunicode(n))

    import datetime

    blog_new_page.blog = blog
    blog_new_page.user = user
    blog_new_page.publication_date = datetime.datetime.utcnow()
    blog_new_page.basename = ''

    from core.cms import save_action_list

    from core.ui import kv
    kv_ui_data = kv.ui(blog_new_page.kv_list())

    try:
        html_editor_settings = Template.get(
            Template.blog == blog, Template.title == 'HTML Editor Init',
            Template.template_type == template_type.system).body
    except Template.DoesNotExist:
        from core.static import html_editor_settings

    return template(
        'edit/page',
        menu=generate_menu('create_page', blog),
        parent_path=referer,
        # search_context=(search_context['blog'], blog),
        html_editor_settings=html_editor_settings,
        sidebar=sidebar.render_sidebar(panel_set='edit_page',
                                       status_badge=status_badge,
                                       save_action=save_action,
                                       save_action_list=save_action_list,
                                       kv_ui=kv_ui_data,
                                       kv_object='Page',
                                       kv_objectid=None,
                                       **tags.__dict__),
        **tags.__dict__)
Example #10
0
def blog_queue_clear(blog_id):
    '''
    Clear all pending jobs out of the queue
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    Queue.clear(blog)
Example #11
0
def blog_queue_clear(blog_id):
    '''
    Clear all pending jobs out of the queue
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    Queue.clear(blog)
Example #12
0
    def blog_static(filepath):
        '''
        Returns static routes for the currently staged blog.
        The blog ID is appended to the URL as a '_' parameter (e.g., ?_=1 for blog ID 1)
        The future of this function is currently being debated.
        '''

        try:
            blog_id = int(request.query['_'])
        except KeyError:
            return system_site_index()
            # raise

        blog = Blog.load(blog_id)

        root_path = blog.path

        filesystem_filepath = urllib.parse.quote(filepath)

        # TODO: replace this with results from /preview path,
        # or another function that finds by abs path in db.

        if os.path.isfile(root_path + "/" + filesystem_filepath) is False:
            filepath += ("index.html")

        if os.path.isfile(root_path + "/" + filesystem_filepath) is False:

            abort(
                404, 'File {} not found'.format(root_path + "/" +
                                                filesystem_filepath))

        k = static_file(filesystem_filepath, root=root_path)

        if (k.headers['Content-Type'][:5] == "text/"
                or k.headers['Content-Type'] == "application/javascript"):

            k.add_header('Cache-Control',
                         'max-age=7200, public, must-revalidate')

        if (k._headers['Content-Type'][0][:5] == "text/" and not k.body == ""):

            x = k.body.read()
            k.body.close()

            y = x.decode('utf8')
            z = re.compile(r' href=["\']' + (blog.url) + '([^"\']*)["\']')
            z2 = re.compile(r' href=["\'](/[^"\']*)["\']')
            y = re.sub(
                z, r" href='" + BASE_URL_PROTOCOL + DEFAULT_LOCAL_ADDRESS +
                DEFAULT_LOCAL_PORT + "\\1?_={}'".format(blog_id), y)
            y = re.sub(z2, r" href='\1?_={}'".format(blog_id), y)
            y = y.encode('utf8')

            k.headers['Content-Length'] = len(y)
            k.body = y

        return (k)
Example #13
0
def export_theme_for_blog(blog_id, theme_name, theme_description):

    from core.models import KeyValue, Blog

    blog = Blog.load(blog_id)
    theme_to_export = blog.templates()

    theme = {}
    theme["title"] = theme_to_export[0].theme.title
    theme["description"] = theme_to_export[0].theme.description
    theme["data"] = {}

    for n in theme_to_export:
        theme["data"][n.id] = {}
        theme["data"][n.id]["template"] = json_dump(n)

        mappings_to_export = n.mappings

        theme["data"][n.id]["mapping"] = {}

        for m in mappings_to_export:
            theme["data"][n.id]["mapping"][m.id] = json_dump(m)

    # We may not use the rest of this because of the way
    # KVs are being scaled back

    theme["kv"] = {}

    kv_list = []

    top_kvs = KeyValue.select().where(
        KeyValue.object == 'Theme',
        KeyValue.objectid == theme_to_export[0].theme.id,
        KeyValue.is_schema == True)

    for n in top_kvs:
        kv_list.append(n)

    while len(kv_list) > 0:
        theme["kv"][kv_list[0].id] = json_dump(kv_list[0])
        next_kvs = KeyValue.select().where(
            KeyValue.parent == kv_list[0],
            KeyValue.is_schema == True)
        for f in next_kvs:
            kv_list.append(f)
        del kv_list[0]

    import settings, os
    with open(os.path.join(settings.APPLICATION_PATH , "install" ,
        "templates.json"), "w", encoding='utf-8') as output_file:
        output_file.write(json.dumps(theme,
            indent=1,
            sort_keys=True,
            allow_nan=True))

    return theme
Example #14
0
def export_theme_for_blog(blog_id, theme_name, theme_description):

    from core.models import KeyValue, Blog

    blog = Blog.load(blog_id)
    theme_to_export = blog.templates()

    theme = {}
    theme["title"] = theme_to_export[0].theme.title
    theme["description"] = theme_to_export[0].theme.description
    theme["data"] = {}

    for n in theme_to_export:
        theme["data"][n.id] = {}
        theme["data"][n.id]["template"] = json_dump(n)

        mappings_to_export = n.mappings

        theme["data"][n.id]["mapping"] = {}

        for m in mappings_to_export:
            theme["data"][n.id]["mapping"][m.id] = json_dump(m)

    # We may not use the rest of this because of the way
    # KVs are being scaled back

    theme["kv"] = {}

    kv_list = []

    top_kvs = KeyValue.select().where(
        KeyValue.object == 'Theme',
        KeyValue.objectid == theme_to_export[0].theme.id,
        KeyValue.is_schema == True)

    for n in top_kvs:
        kv_list.append(n)

    while len(kv_list) > 0:
        theme["kv"][kv_list[0].id] = json_dump(kv_list[0])
        next_kvs = KeyValue.select().where(KeyValue.parent == kv_list[0],
                                           KeyValue.is_schema == True)
        for f in next_kvs:
            kv_list.append(f)
        del kv_list[0]

    import settings, os
    with open(os.path.join(settings.APPLICATION_PATH, "install",
                           "templates.json"),
              "w",
              encoding='utf-8') as output_file:
        output_file.write(
            json.dumps(theme, indent=1, sort_keys=True, allow_nan=True))

    return theme
Example #15
0
    def blog_static(filepath):
        '''
        Returns static routes for the currently staged blog.
        The blog ID is appended to the URL as a '_' parameter (e.g., ?_=1 for blog ID 1)
        The future of this function is currently being debated.
        '''

        try:
            blog_id = int(request.query['_'])
        except KeyError:
            return system_site_index()
            # raise

        blog = Blog.load(blog_id)

        root_path = blog.path

        filesystem_filepath = urllib.parse.quote(filepath)

        # TODO: replace this with results from /preview path,
        # or another function that finds by abs path in db.

        if os.path.isfile(root_path + "/" + filesystem_filepath) is False:
            filepath += ("index.html")

        if os.path.isfile(root_path + "/" + filesystem_filepath) is False:

            abort(404, 'File {} not found'.format(root_path + "/" + filesystem_filepath))

        k = static_file(filesystem_filepath, root=root_path)

        if (k.headers['Content-Type'][:5] == "text/" or
                k.headers['Content-Type'] == "application/javascript"):

            k.add_header(
                'Cache-Control', 'max-age=7200, public, must-revalidate')

        if (k._headers['Content-Type'][0][:5] == "text/" and not k.body == ""):

            x = k.body.read()
            k.body.close()

            y = x.decode('utf8')
            z = re.compile(r' href=["\']' + (blog.url) + '([^"\']*)["\']')
            z2 = re.compile(r' href=["\'](/[^"\']*)["\']')
            y = re.sub(z, r" href='" + BASE_URL_PROTOCOL + DEFAULT_LOCAL_ADDRESS +
                       DEFAULT_LOCAL_PORT + "\\1?_={}'".format(blog_id), y)
            y = re.sub(z2, r" href='\1?_={}'".format(blog_id), y)
            y = y.encode('utf8')

            k.headers['Content-Length'] = len(y)
            k.body = y

        return (k)
Example #16
0
def blog_user(user_id, blog_id):
    # Obtains user edit in blog context.
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)
    user_to_edit = User.find(user_id)

    return edit_user(user_to_edit,
                     editing_user=user,
                     context=blog_context,
                     blog=blog)
Example #17
0
def blog_list_users(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    return listing(request, blog, blog.users,
                   'blog_users', 'blog_list_users',
                   user=user,
                   tags_data={'blog':blog}
                   )
Example #18
0
def new_category(blog_id):

    from core.models import db
    with db.atomic() as txn:

        user = auth.is_logged_in(request)
        blog = Blog.load(blog_id)
        permission = auth.is_blog_editor(user, blog)

        category_list = [n for n in blog.categories]

        category = Category(id=0,
            title='',
            blog=blog)

        top_level_category = Category(
            id=None,
            title='[Top-level category]',
            parent=None
            )

        category_list.insert(0, top_level_category)

        tags = template_tags(
            blog=blog,
            user=user)

    if request.method == "POST":
        with db.atomic() as txn:
            category_title = request.forms.getunicode('category_title')
            try:
                parent_category = int(request.forms.getunicode('category_parent'))
            except ValueError:
                parent_category = None

            with db.atomic() as txn:

                category = Category(blog=blog,
                    title=category_title,
                    parent_category=parent_category
                    )
                category.save()

        redirect('{}/blog/{}/category/{}'.format(
            BASE_URL, blog.id, category.id))

    tpl = template('edit/category',
        category=category,
        category_list=category_list,
        menu=generate_menu('blog_new_category', category),
        search_context=(search_contexts['sites'], None),
        **tags.__dict__)

    return tpl
Example #19
0
def blog_apply_theme(blog_id, theme_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)
    reason = auth.check_template_lock(blog)

    theme = Theme.load(theme_id)

    tags = template_tags(blog=blog,
            user=user)

    from core.utils import Status

    if request.forms.getunicode('confirm') == user.logout_nonce:

        from core.models import db
        with db.atomic() as txn:
            blog.apply_theme(theme, user)

        status = Status(
            type='success',
            close=False,
            message='''
Theme <b>{}</b> was successfully applied to blog <b>{}</b>.</p>
It is recommended that you <a href="{}">republish this blog.</a>
'''.format(theme.for_display, blog.for_display, '{}/blog/{}/republish'.format(
                BASE_URL, blog.id))
            )

    else:

        status = Status(
            type='warning',
            close=False,
            message='''
You are about to apply theme <b>{}</b> to blog <b>{}</b>.</p>
<p>This will OVERWRITE AND REMOVE ALL EXISTING TEMPLATES on this blog!</p>
'''.format(theme.for_display, blog.for_display),
            url='{}/blog/{}/themes'.format(
                BASE_URL, blog.id),
            yes={'id':'delete',
                'name':'confirm',
                'label':'Yes, I want to apply this theme',
                'value':user.logout_nonce},
            no={'label':'No, don\'t apply this theme',
                'url':'{}/blog/{}/themes'.format(
                BASE_URL, blog.id)}
            )

    tags.status = status if reason is None else reason

    return report(tags, 'blog_apply_theme', [blog, theme])
Example #20
0
def blog_settings(blog_id, nav_setting):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    auth.check_settings_lock(blog)

    tags = template_tags(blog_id=blog.id, user=user)

    tags.nav_default = nav_setting

    return blog_settings_output(tags)
Example #21
0
def blog_list_users(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    return listing(request,
                   blog,
                   blog.users,
                   'blog_users',
                   'blog_list_users',
                   user=user,
                   tags_data={'blog': blog})
Example #22
0
def media_edit_save(blog_id, media_id):
    '''
    Save changes to a media entry.
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    is_member = auth.is_blog_member(user, blog)
    media = Media.load(media_id)
    permission = auth.is_media_owner(user, media)

    friendly_name = request.forms.getunicode('media_friendly_name')

    changes = False

    if friendly_name != media.friendly_name:
        changes = True
        media.friendly_name = friendly_name

    import datetime

    if changes is True:
        media.modified_date = datetime.datetime.utcnow()
        media.save()

        status = utils.Status(
            type='success',
            message='Changes to media <b>{}</b> saved successfully.'.format(
                media.for_display))
    else:

        status = utils.Status(
            type='warning',
            no_sure=True,
            message='No discernible changes submitted for media <b>{}</b>.'.
            format(media.id, media.for_display))

    logger.info("Media {} edited by user {}.".format(media.for_log,
                                                     user.for_log))

    from core.ui import kv
    kv_ui_data = kv.ui(media.kv_list())

    tags = template_tags(blog=blog, media=media, status=status, user=user)

    tags.sidebar = sidebar.render_sidebar(panel_set='edit_media',
                                          status_badge=status_badge,
                                          kv_object='Media',
                                          kv_objectid=media.id,
                                          kv_ui=kv_ui_data)

    return media_edit_output(tags)
Example #23
0
def blog_previews_list(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    previews = blog.fileinfos.where(FileInfo.preview_path.is_null(False))

    return listing(request, blog, previews,
               'blog_previews', 'blog_previews',
               user=user,
               msg_float=False,
               tags_data={'blog':blog}
               )
Example #24
0
def blog_settings(blog_id, nav_setting):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    auth.check_settings_lock(blog)

    tags = template_tags(blog_id=blog.id,
        user=user)

    tags.nav_default = nav_setting

    return blog_settings_output(tags)
Example #25
0
def tag_list_pages(blog_id, tag_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)
    tag = Tag.load(tag_id)

    return listing(request, tag, tag.pages.order_by(Page.publication_date.desc()),
                   'blog', 'blog_pages_for_tag',
                   user=user,
                   search_ui='blog_pages_with_tag',
                   search_context=tag_in_blog_search_results,
                   tags_data={'blog':blog}
                   )
Example #26
0
def media_pages(blog_id, media_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    is_member = auth.is_blog_member(user, blog)
    media = Media.load(media_id, blog)

    return listing(request, media,
                   media.pages.order_by(Page.publication_date.desc()),
                   'blog', 'blog_media_pages',
                   user=user,
                   search_ui='blog_media_pages',
                   search_context=media_search_results,
                   tags_data={'blog':blog}
                   )
Example #27
0
def blog(blog_id, errormsg=None):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    return listing(request, blog, blog.pages,
                   'blog', 'blog_menu',
                   user=user,
                   errormsg=errormsg,
                   search_ui='blog',
                   search_context=blog_search_results,
                   tags_data={'blog':blog}
                   )
Example #28
0
def tag_get(blog_id, tag_name):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    tag_name = url_unescape(tag_name)

    tag_list = Tag.select().where(Tag.tag.contains(tag_name), Tag.blog == blog)

    import json
    tag_list_json = json.dumps([{'tag': t.tag, 'id': t.id} for t in tag_list])

    return tag_list_json
Example #29
0
def blog_apply_theme(blog_id, theme_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)
    reason = auth.check_template_lock(blog)

    theme = Theme.load(theme_id)

    tags = template_tags(blog=blog, user=user)

    from core.utils import Status

    if request.forms.getunicode('confirm') == user.logout_nonce:

        from core.models import db
        with db.atomic() as txn:
            blog.apply_theme(theme, user)

        status = Status(type='success',
                        close=False,
                        message='''
Theme <b>{}</b> was successfully applied to blog <b>{}</b>.</p>
It is recommended that you <a href="{}">republish this blog.</a>
'''.format(theme.for_display, blog.for_display,
           '{}/blog/{}/republish'.format(BASE_URL, blog.id)))

    else:

        status = Status(type='warning',
                        close=False,
                        message='''
You are about to apply theme <b>{}</b> to blog <b>{}</b>.</p>
<p>This will OVERWRITE AND REMOVE ALL EXISTING TEMPLATES on this blog!</p>
'''.format(theme.for_display, blog.for_display),
                        url='{}/blog/{}/themes'.format(BASE_URL, blog.id),
                        yes={
                            'id': 'delete',
                            'name': 'confirm',
                            'label': 'Yes, I want to apply this theme',
                            'value': user.logout_nonce
                        },
                        no={
                            'label': 'No, don\'t apply this theme',
                            'url':
                            '{}/blog/{}/themes'.format(BASE_URL, blog.id)
                        })

    tags.status = status if reason is None else reason

    return report(tags, 'blog_apply_theme', [blog, theme])
Example #30
0
def template_set_default(template_id):
    '''
    UI for setting a given template as the default for an archive type
    '''

    user = auth.is_logged_in(request)
    tpl = Template.load(template_id)
    blog = Blog.load(tpl.blog.id)
    permission = auth.is_blog_designer(user, blog)

    auth.check_template_lock(blog)

    tags = template_tags(template=tpl, user=user)

    from core.utils import Status
    import settings

    if request.forms.getunicode('confirm') == user.logout_nonce:

        # check for form submission
        # setting should be done by way of class object
        # theme? blog? template?
        # blog.set_default_archive_template(template,{archive_type.index...})

        status = Status(
            type='success',
            close=False,
            message=
            'Template <b>{}</b> was successfully refreshed from theme <b>{}</b>.'
            .format(tpl.for_display, tpl.theme.for_display),
            action='Return to template',
            url='{}/template/{}/edit'.format(settings.BASE_URL, tpl.id))
        tags.status = status
    else:
        pass

    from core.models import archive_defaults

    return template('edit/template-set-default',
                    icons=icons,
                    search_context=(search_contexts['blog'], tags.blog),
                    menu=generate_menu('blog_edit_template', tags.template),
                    sidebar=sidebar.render_sidebar(
                        panel_set='edit_template',
                        publishing_mode=publishing_mode,
                        types=template_type,
                        **tags.__dict__),
                    archive_defaults=archive_defaults,
                    **tags.__dict__)
Example #31
0
def template_delete(template_id):
    '''
    UI for deleting a template
    '''
    user = auth.is_logged_in(request)
    tpl = Template.load(template_id)
    blog = Blog.load(tpl.blog)
    permission = auth.is_blog_designer(user, blog)

    from core.utils import Status
    import settings

    tags = template_tags(template_id=tpl.id, user=user)

    if request.forms.getunicode('confirm') == user.logout_nonce:

        # _template.delete(tpl)
        tpl.delete_instance()

        status = Status(type='success',
                        close=False,
                        message='Template {} was successfully deleted.'.format(
                            tpl.for_log),
                        action='Return to template list',
                        url='{}/blog/{}/templates'.format(
                            settings.BASE_URL, blog.id))

    else:

        status = Status(
            type='warning',
            close=False,
            message=
            'You are attempting to delete template <b>{}</b> from blog <b>{}</b>.'
            .format(tpl.for_display, blog.for_display),
            no={
                'url': '{}/template/{}/edit'.format(settings.BASE_URL, tpl.id),
                'label': 'No, I don\'t want to delete this template'
            },
            yes={
                'id': 'delete',
                'name': 'confirm',
                'label': 'Yes, I want to delete this template',
                'value': user.logout_nonce
            })

    tags.status = status

    return report(tags, 'blog_delete_template', tpl)
Example #32
0
def media_pages(blog_id, media_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    is_member = auth.is_blog_member(user, blog)
    media = Media.load(media_id, blog)

    return listing(request,
                   media,
                   media.pages.order_by(Page.publication_date.desc()),
                   'blog',
                   'blog_media_pages',
                   user=user,
                   search_ui='blog_media_pages',
                   search_context=media_search_results,
                   tags_data={'blog': blog})
Example #33
0
def new_category(blog_id):

    from core.models import db
    with db.atomic() as txn:

        user = auth.is_logged_in(request)
        blog = Blog.load(blog_id)
        permission = auth.is_blog_editor(user, blog)

        category_list = [n for n in blog.categories]

        category = Category(id=0, title='', blog=blog)

        top_level_category = Category(id=None,
                                      title='[Top-level category]',
                                      parent=None)

        category_list.insert(0, top_level_category)

        tags = template_tags(blog=blog, user=user)

    if request.method == "POST":
        with db.atomic() as txn:
            category_title = request.forms.getunicode('category_title')
            try:
                parent_category = int(
                    request.forms.getunicode('category_parent'))
            except ValueError:
                parent_category = None

            with db.atomic() as txn:

                category = Category(blog=blog,
                                    title=category_title,
                                    parent_category=parent_category)
                category.save()

        redirect('{}/blog/{}/category/{}'.format(BASE_URL, blog.id,
                                                 category.id))

    tpl = template('edit/category',
                   category=category,
                   category_list=category_list,
                   menu=generate_menu('blog_new_category', category),
                   search_context=(search_contexts['sites'], None),
                   **tags.__dict__)

    return tpl
Example #34
0
def blog_queue(blog_id, status=None):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    tags = template_tags(blog_id=blog.id, user=user, status=status)

    return listing(request,
                   blog,
                   tags.queue,
                   'queue',
                   'blog_menu',
                   user=user,
                   tags_data={'blog': blog},
                   errormsg=tags.status)
Example #35
0
def blog_queue(blog_id, status=None):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    tags = template_tags(blog_id=blog.id,
            user=user,
            status=status)

    return listing(request, blog, tags.queue,
                   'queue', 'blog_menu',
                   user=user,
                   tags_data={'blog':blog},
                   errormsg=tags.status
                   )
Example #36
0
def media_list(blog_id):
    '''
    UI for listing media for a given blog
    '''

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    return listing(request, blog, blog.media.order_by(Media.id.desc()),
                   'media', 'blog_manage_media',
                   user=user,
                   search_ui='blog_media',
                   search_context=media_search_results,
                   tags_data={'blog':blog}
                   )
Example #37
0
def tags_list(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_author(user, blog)

    errormsg = auth.check_tag_editing_lock(blog, True)

    return listing(request, blog, blog.tags,
                   'tags', 'blog_manage_tags',
                   user=user,
                   search_ui='blog_tags',
                   search_context=tag_search_results,
                   errormsg=errormsg,
                   tags_data={'blog':blog}
                   )
Example #38
0
def tag_list_pages(blog_id, tag_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)
    tag = Tag.load(tag_id)

    return listing(request,
                   tag,
                   tag.pages.order_by(Page.publication_date.desc()),
                   'blog',
                   'blog_pages_for_tag',
                   user=user,
                   search_ui='blog_pages_with_tag',
                   search_context=tag_in_blog_search_results,
                   tags_data={'blog': blog})
Example #39
0
def blog(blog_id, errormsg=None):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    return listing(request,
                   blog,
                   blog.pages,
                   'blog',
                   'blog_menu',
                   user=user,
                   errormsg=errormsg,
                   search_ui='blog',
                   search_context=blog_search_results,
                   tags_data={'blog': blog})
Example #40
0
def blog_previews_list(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)

    previews = blog.fileinfos.where(FileInfo.preview_path.is_null(False))

    return listing(request,
                   blog,
                   previews,
                   'blog_previews',
                   'blog_previews',
                   user=user,
                   msg_float=False,
                   tags_data={'blog': blog})
Example #41
0
def blog_republish_batch(blog_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    pages_to_queue = request.forms.getall('check')
    pages_that_can_be_queued = blog.pages.published.select().where(
        Page.id << pages_to_queue)
    page_count = pages_that_can_be_queued.count()
    response.add_header('X-Page-Count', page_count)
    if page_count > 0:
        queue.queue_page_actions(pages_that_can_be_queued)
        msg = '<b>OK:</b> {} pages queued for publication.'.format(page_count)
    else:
        msg = '<b>NOTE:</b> No pages queued for publication.'

    return msg
Example #42
0
def blog_purge(blog_id):
    '''
    UI for purging/republishing an entire blog
    Eventually to be reworked
    '''

    user = auth.is_logged_in(request)

    blog = Blog.load(blog_id)

    permission = auth.is_blog_publisher(user, blog)

    tags = template_tags(blog=blog, user=user)

    tags.report = cms.purge_blog(blog)

    return report(tags, 'blog_purge', blog)
Example #43
0
def blog_republish_batch(blog_id):
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    pages_to_queue = request.forms.getall('check')
    pages_that_can_be_queued = blog.pages.published.select().where(
        Page.id << pages_to_queue)
    page_count = pages_that_can_be_queued.count()
    response.add_header('X-Page-Count', page_count)
    if page_count > 0:
        queue.queue_page_actions(pages_that_can_be_queued)
        msg = '<b>OK:</b> {} pages queued for publication.'.format(page_count)
    else:
        msg = '<b>NOTE:</b> No pages queued for publication.'

    return msg
Example #44
0
def blog_purge(blog_id):
    '''
    UI for purging/republishing an entire blog
    Eventually to be reworked
    '''

    user = auth.is_logged_in(request)

    blog = Blog.load(blog_id)

    permission = auth.is_blog_publisher(user, blog)

    tags = template_tags(blog=blog, user=user)

    tags.report = cms.purge_blog(blog)

    return report(tags, 'blog_purge', blog)
Example #45
0
def tag_get(blog_id, tag_name):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    tag_name = url_unescape(tag_name)

    tag_list = Tag.select().where(
        Tag.tag.contains(tag_name),
        Tag.blog == blog)

    import json
    tag_list_json = json.dumps([{'tag':t.tag,
                                'id':t.id} for t in tag_list])

    return tag_list_json
Example #46
0
def blog_new_page_save(blog_id):
    '''
    UI for saving a newly created page.
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    tags = cms.save_page(None, user, blog)

    # TODO: move to model instance?
    logger.info("Page {} created by user {}.".format(
        tags.page.for_log,
        user.for_log))

    response.add_header('X-Redirect', BASE_URL + '/page/{}/edit'.format(str(tags.page.id)))

    return response
Example #47
0
def blog_queue_run(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_publisher(user, blog)

    import subprocess, sys
    taskpath = "{}/scripts/tasks.py".format(APPLICATION_PATH)
    pid = subprocess.Popen([sys.executable, taskpath, '--nowait']).pid
    msg = "<a href='../queue'>Queue</a> runner {} started with pid {}. ".format(
        taskpath, pid)

    from core.utils import Status
    status = Status(type='success', no_sure=True, message=msg)

    tags = template_tags(blog_id=blog.id, user=user, status=status)

    return report(tags, 'blog_menu', blog)
Example #48
0
def media_list(blog_id):
    '''
    UI for listing media for a given blog
    '''

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    return listing(request,
                   blog,
                   blog.media.order_by(Media.id.desc()),
                   'media',
                   'blog_manage_media',
                   user=user,
                   search_ui='blog_media',
                   search_context=media_search_results,
                   tags_data={'blog': blog})
Example #49
0
def blog_categories(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_editor(user, blog)
    errormsg = auth.check_category_editing_lock(blog, True)

    action = (
        ('Create new category',
        '{}/blog/{}/newcategory'.format(BASE_URL, blog.id)),
        )

    return listing(request, blog, blog.categories.select(),
                   'categories', 'blog_manage_categories',
                   user=user,
                   errormsg=errormsg,
                   tags_data={'blog':blog}
                   )
Example #50
0
def blog_new_page_save(blog_id):
    '''
    UI for saving a newly created page.
    '''
    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    tags = cms.save_page(None, user, blog)

    # TODO: move to model instance?
    logger.info("Page {} created by user {}.".format(tags.page.for_log,
                                                     user.for_log))

    response.add_header('X-Redirect',
                        BASE_URL + '/page/{}/edit'.format(str(tags.page.id)))

    return response
Example #51
0
def blog_categories(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_editor(user, blog)
    errormsg = auth.check_category_editing_lock(blog, True)

    action = (('Create new category',
               '{}/blog/{}/newcategory'.format(BASE_URL, blog.id)), )

    return listing(request,
                   blog,
                   blog.categories.select(),
                   'categories',
                   'blog_manage_categories',
                   user=user,
                   errormsg=errormsg,
                   tags_data={'blog': blog})
Example #52
0
def blog_pages_in_category(blog_id, category_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_editor(user, blog)
    errormsg = auth.check_category_editing_lock(blog, True)

    from core.models import Category
    category = Category.load(category_id, blog_id=blog.id)

    return listing(request, category, category.pages,
                   'blog', 'blog_pages_in_category',
                   user=user,
                   errormsg=errormsg,
                   search_ui='blog_pages_in_category',
                   search_context=blog_pages_in_category_search_results,
                   tags_data={'blog':blog}
                   )
Example #53
0
def tags_list(blog_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_author(user, blog)

    errormsg = auth.check_tag_editing_lock(blog, True)

    return listing(request,
                   blog,
                   blog.tags,
                   'tags',
                   'blog_manage_tags',
                   user=user,
                   search_ui='blog_tags',
                   search_context=tag_search_results,
                   errormsg=errormsg,
                   tags_data={'blog': blog})
Example #54
0
def blog_pages_in_category(blog_id, category_id):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_editor(user, blog)
    errormsg = auth.check_category_editing_lock(blog, True)

    from core.models import Category
    category = Category.load(category_id, blog_id=blog.id)

    return listing(request,
                   category,
                   category.pages,
                   'blog',
                   'blog_pages_in_category',
                   user=user,
                   errormsg=errormsg,
                   search_ui='blog_pages_in_category',
                   search_context=blog_pages_in_category_search_results,
                   tags_data={'blog': blog})
Example #55
0
def reparent_page(page_id, blog_id):
    with db.atomic():
        page = Page.load(page_id)
        blog = Blog.load(blog_id)
        page.blog = blog.id
        page.text += "\n"  # stupid hack, we should have a force-save option
        # also, have .save options kw, not args

        # Reparent any existing media
        # Delete any existing categories
        # Migrate/re-add any existing tags
        # Remove and regenerate basename, permalink, etc.
        # Create new fileinfo

        from core.error import PageNotChanged
        try:
            page.save(page.user)
        except PageNotChanged:
            pass
    return "OK"
Example #56
0
def blog_create_user(blog_id):
    '''
    Creates a user and gives it certain permissions within the context of a given blog
    '''

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_admin(user, blog)
    tags = template_tags(blog_id=blog.id, user=user)

    edit_user = Struct()
    edit_user.name = ""
    edit_user.email = ""

    return template(
        'edit/user_settings',
        section_title="Create new blog user",
        # search_context=(search_context['sites'], None),
        edit_user=edit_user,
        **tags.__dict__)
Example #57
0
def reparent_page(page_id, blog_id):
    with db.atomic():
        page = Page.load(page_id)
        blog = Blog.load(blog_id)
        page.blog = blog.id
        page.text += "\n"  # stupid hack, we should have a force-save option
        # also, have .save options kw, not args

        # Reparent any existing media
        # Delete any existing categories
        # Migrate/re-add any existing tags
        # Remove and regenerate basename, permalink, etc.
        # Create new fileinfo

        from core.error import PageNotChanged
        try:
            page.save(page.user)
        except PageNotChanged:
            pass
    return "OK"
Example #58
0
def blog_editor_css(blog_id):
    '''
    Route for a copy of the blog's editor CSS;
    this allows it to be cached browser-side
    '''
    blog = Blog.load(blog_id)

    from core.models import Template, template_type
    try:
        editor_css_template = Template.get(
            Template.blog == blog, Template.title == 'HTML Editor CSS',
            Template.template_type == template_type.system)
    except:
        from core import static
        template = static.editor_css
    else:
        template = editor_css_template.body

    response.content_type = "text/css"
    response.add_header('Cache-Control', 'max-age=7200')
    return template
Example #59
0
def tags_get(blog_id, limit, page_limit):

    user = auth.is_logged_in(request)
    blog = Blog.load(blog_id)
    permission = auth.is_blog_member(user, blog)

    from core.models import TagAssociation

    blog_pages = blog.pages.published.select(Page.id).order_by(Page.publication_date.desc()).limit(page_limit)
    tag_assc = TagAssociation.select(TagAssociation.tag).where(TagAssociation.page << blog_pages)
    tag_list = Tag.select(Tag.tag, Tag.id).where(Tag.id << tag_assc)

    # tag_list = Blog.load(blog_id).tags_all.order_by(Tag.id.desc())

    if limit:
        tag_list = tag_list.limit(limit)

    import json
    tag_list_json = json.dumps([{'tag':t.tag,
                                'id':t.id} for t in tag_list])
    return tag_list_json
Example #60
0
def template_edit(template_id):
    '''
    UI for editing a blog template
    '''

    user = auth.is_logged_in(request)
    edit_template = Template.load(template_id)
    blog = Blog.load(edit_template.blog.id)
    permission = auth.is_blog_designer(user, blog)

    auth.check_template_lock(blog)

    utils.disable_protection()

    tags = template_tags(template_id=template_id, user=user)

    # find out if the template object returns a list of all the mappings, or just the first one
    # it's edit_template.mappings

    tags.mappings = template_mapping_index[edit_template.template_type]

    return template_edit_output(tags)