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
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
def page_edit_save(page_id): ''' UI for saving changes to an edited blog page ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page.delete_preview() # from core.cms import save_action_list tags = save_page(page, user, page.blog) from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) tpl = template('edit/page_ajax', 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=page.id, **tags.__dict__ ), msg_float=False, **tags.__dict__) return tpl
def delete_page_preview(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page.delete_preview()
def page_media_upload_confirm(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) # get file NAMES, attributes, size, etc. first # request.form.getunicode('filename') # check each one on the SERVER side, not the client # if each file is OK, then respond appropriately and have the client send the whole file # if not, respond with a warning to be added to the notification area _g = request.forms.getunicode file_name = _g('filename') file_size = _g('filesize') # check for file types against master list # check for file length # check for name collision for n in request.files: x = request.files.get(n) file_path = _join(page.blog.path, page.blog.media_path_generated, x.filename) if _exists(file_path): pass else: pass
def page_edit_save(page_id): ''' UI for saving changes to an edited blog page ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page.delete_preview() # from core.cms import save_action_list tags = save_page(page, user, page.blog) from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) tpl = template('edit/page_ajax', 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=page.id, **tags.__dict__), msg_float=False, **tags.__dict__) return tpl
def page_media_upload(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) overwrite = [] for n in request.files: x = request.files.get(n) media_path = _join(page.blog.path, page.blog.media_path_generated) file_path = _join(media_path, x.filename) if _exists(file_path): from core.error import FileExistsError raise FileExistsError( "File '{}' already exists on the server.".format( utils.html_escape(x.filename))) else: Media.register_media(x.filename, file_path, user, page=page) if not _exists(media_path): makedirs(media_path) x.save(file_path) tags = template_tags(page=page) return template('edit/page_media_list.tpl', **tags.__dict__)
def delete_page_preview(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page.delete_preview()
def page_media_upload_confirm(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) # get file NAMES, attributes, size, etc. first # request.form.getunicode('filename') # check each one on the SERVER side, not the client # if each file is OK, then respond appropriately and have the client send the whole file # if not, respond with a warning to be added to the notification area _g = request.forms.getunicode file_name = _g('filename') file_size = _g('filesize') # check for file types against master list # check for file length # check for name collision for n in request.files: x = request.files.get(n) file_path = _join(page.blog.path, page.blog.media_path_generated, x.filename) if _exists(file_path): pass else: pass
def page_media_upload(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) overwrite = [] for n in request.files: x = request.files.get(n) media_path = _join(page.blog.path, page.blog.media_path_generated) file_path = _join(media_path, x.filename) if _exists(file_path): from core.error import FileExistsError raise FileExistsError("File '{}' already exists on the server.".format( utils.html_escape(x.filename))) else: Media.register_media(x.filename, file_path, user, page=page) if not _exists(media_path): makedirs(media_path) x.save(file_path) tags = template_tags(page=page) return template('edit/page_media_list.tpl', **tags.__dict__)
def page_edit(page_id): ''' UI for editing a page in a blog ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) status = None referer = request.headers.get('Referer') if (referer is None or page.modified_date is None or re.match(re.escape(BASE_URL + "/blog/" + str(page.blog.id)), referer) is None): referer = BASE_URL + "/blog/" + str(page.blog.id) if page.modified_date is None: status = utils.Status( type='info', message="Page <b>{}</b> created.".format(page.for_log)) page.modified_date = datetime.datetime.utcnow() page.save(user) tags = template_tags(page=page, user=user, status=status) from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) tpl = template('edit/page', menu=generate_menu('edit_page', page), parent_path=referer, # search_context=(search_context['blog'], page.blog), html_editor_settings=html_editor_settings(page.blog), sidebar=sidebar.render_sidebar( panel_set='edit_page', status_badge=status_badge, save_action_list=save_action_list, save_action=save_action, kv_ui=kv_ui_data, kv_object='Page', kv_objectid=page.id, **tags.__dict__), msg_float=False, **tags.__dict__) logger.info("Page {} opened for editing by {}.".format( page.for_log, user.for_log)) return tpl
def page_edit(page_id): ''' UI for editing a page in a blog ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) status = None referer = request.headers.get('Referer') if (referer is None or page.modified_date is None or re.match(re.escape(BASE_URL + "/blog/" + str(page.blog.id)), referer) is None): referer = BASE_URL + "/blog/" + str(page.blog.id) if page.modified_date is None: status = utils.Status(type='info', message="Page <b>{}</b> created.".format( page.for_log)) page.modified_date = datetime.datetime.utcnow() page.save(user) tags = template_tags(page=page, user=user, status=status) from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) tpl = template( 'edit/page', menu=generate_menu('edit_page', page), parent_path=referer, # search_context=(search_context['blog'], page.blog), html_editor_settings=html_editor_settings(page.blog), sidebar=sidebar.render_sidebar(panel_set='edit_page', status_badge=status_badge, save_action_list=save_action_list, save_action=save_action, kv_ui=kv_ui_data, kv_object='Page', kv_objectid=page.id, **tags.__dict__), msg_float=False, **tags.__dict__) logger.info("Page {} opened for editing by {}.".format( page.for_log, user.for_log)) return tpl
def page_media_delete(page_id, media_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id) media_reference = MediaAssociation.get(MediaAssociation.page == page, MediaAssociation.media == media) media_reference.delete_instance(recursive=True, delete_nullable=True) tags = template_tags(page=page) return template('edit/page_media_list.tpl', **tags.__dict__)
def page_preview_core(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) preview_fileinfo = page.default_fileinfo preview_file_path, preview_url = preview_fileinfo.make_preview() page_tags = fileinfo.generate_page_tags(preview_fileinfo, page.blog) file_page_text = generate_page_text(preview_fileinfo, page_tags) queue.write_file(file_page_text, page.blog.path, preview_file_path) return preview_url, page
def page_preview_core(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) preview_fileinfo = page.default_fileinfo preview_file_path, preview_url = preview_fileinfo.make_preview() page_tags = fileinfo.generate_page_tags(preview_fileinfo, page.blog) file_page_text = generate_page_text(preview_fileinfo, page_tags) queue.write_file(file_page_text, page.blog.path, preview_file_path) return preview_url, page
def page_media_add(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media_list = Media.select().where(Media.blog == page.blog) tags = template_tags(page=page, user=user) return template('modal/modal_images.tpl', media_list=media_list, title="Select media", buttons='', **tags.__dict__)
def page_revisions(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) tags = template_tags(page=page) try: tpl = template('modal/modal_revisions', title='Revisions for page #{}'.format(page.id), buttons='', **tags.__dict__) except: raise return tpl
def page_revisions(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) tags = template_tags(page=page) try: tpl = template('modal/modal_revisions', title='Revisions for page #{}'.format(page.id), buttons='', **tags.__dict__) except: raise return tpl
def page_revision_restore(page_id, revision_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page_revision = PageRevision.select().where(PageRevision.id == revision_id).get() status = utils.Status( type='success', message='Page <b>{}</b> has been restored from backup dated {}.'.format(page.for_log, page_revision.modified_date) ) tags = template_tags(page=page, user=user, status=status) page_revision.id = page.id tags.page = page_revision referer = BASE_URL + "/blog/" + str(page.blog.id) # from core.cms import save_action_list # from core.ui_kv import kv_ui from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) # TODO: save action from this doesn't trigger queue run tpl = template('edit/page', status_badge=status_badge, save_action=save_action, menu=generate_menu('edit_page', page), search_context=(search_contexts['blog'], page.blog), html_editor_settings=html_editor_settings(page.blog), 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=page.id, **tags.__dict__ ), **tags.__dict__) return tpl
def page_add_media_with_template(page_id, media_id, template_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id, page.blog) media_template = Template.get(Template.id == template_id) from core.template import tpl generated_template = tpl(media_template.body, blog=page.blog, media=media) if media not in page.media: media.associate(page) return generated_template
def page_media_add(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media_list = Media.select().where( Media.blog == page.blog) tags = template_tags(page=page, user=user) return template('modal/modal_images.tpl', media_list=media_list, title="Select media", buttons='', **tags.__dict__)
def page_media_delete(page_id, media_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id) media_reference = MediaAssociation.get( MediaAssociation.page == page, MediaAssociation.media == media) media_reference.delete_instance(recursive=True, delete_nullable=True) tags = template_tags(page=page) return template('edit/page_media_list.tpl', **tags.__dict__)
def page_revision_restore(page_id, revision_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) page_revision = PageRevision.select().where( PageRevision.id == revision_id).get() status = utils.Status( type='success', message='Page <b>{}</b> has been restored from backup dated {}.'. format(page.for_log, page_revision.modified_date)) tags = template_tags(page=page, user=user, status=status) page_revision.id = page.id tags.page = page_revision referer = BASE_URL + "/blog/" + str(page.blog.id) # from core.cms import save_action_list # from core.ui_kv import kv_ui from core.ui import kv kv_ui_data = kv.ui(page.kv_list()) # TODO: save action from this doesn't trigger queue run tpl = template('edit/page', status_badge=status_badge, save_action=save_action, menu=generate_menu('edit_page', page), search_context=(search_contexts['blog'], page.blog), html_editor_settings=html_editor_settings(page.blog), 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=page.id, **tags.__dict__), **tags.__dict__) return tpl
def page_revision_restore_save(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) tags = save_page(page, user, page.blog) from core.cms import save_action_list tpl = template('edit/page_ajax', status_badge=status_badge, save_action=save_action, save_action_list=save_action_list, sidebar='', **tags.__dict__) response.add_header('X-Redirect', BASE_URL + '/page/{}/edit'.format(str(tags.page.id))) return tpl
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"
def page_revision_restore_save(page_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) tags = save_page(page, user, page.blog) from core.cms import save_action_list tpl = template('edit/page_ajax', status_badge=status_badge, save_action=save_action, save_action_list=save_action_list, sidebar='', **tags.__dict__) response.add_header('X-Redirect', BASE_URL + '/page/{}/edit'.format(str(tags.page.id))) return tpl
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"
def page_add_media_with_template(page_id, media_id, template_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id, page.blog) media_template = Template.get( Template.id == template_id) from core.template import tpl generated_template = tpl(media_template.body, blog=page.blog, media=media) if media not in page.media: media.associate(page) return generated_template
def page_get_media_templates(page_id, media_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id, page.blog) media_templates = Template.select().where( Template.blog == page.blog, Template.template_type == template_type.media).order_by(Template.title) buttons = media_buttons.format('onclick="add_template();"', 'Apply') tpl = template('modal/modal_image_templates', media=media, templates=media_templates, buttons=buttons, title='Choose a template for {}'.format(media.for_log)) return tpl
def page_get_media_templates(page_id, media_id): user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) media = Media.load(media_id, page.blog) media_templates = Template.select().where( Template.blog == page.blog, Template.template_type == template_type.media).order_by(Template.title) buttons = media_buttons.format( 'onclick="add_template();"', 'Apply') tpl = template('modal/modal_image_templates', media=media, templates=media_templates, buttons=buttons, title='Choose a template for {}'.format( media.for_log)) return tpl
def blog_import (blog_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, True) tags = template_tags(blog=blog, user=user) import os, settings import_path = os.path.join( settings.APPLICATION_PATH, "data", "import.json") tags.status = reason if request.method == "POST": from core.models import db tpl = '' with db.atomic() as txn: import json from core.utils import string_to_date import_path = request.forms.getunicode('import_path') with open(import_path, 'r', encoding='utf8') as f: json_data = json.load(f) from core.models import page_status, MediaAssociation, Category from core.error import PageNotChanged from core.libs.peewee import InterfaceError from core.cms import media_filetypes format_str = "<b>{}</b> / (<i>{}</i>)" # TODO: go in chunks of 50 or something? # allow graceful disconnection? for n in json_data: q = [] n_id = n['id'] q.append("Checking {}".format(n_id)) changed = False found = False match = Page.kv_get('legacy_id', n_id) if match.count() > 0: if match[0].object_ref.blog == blog: found = True q.append(match[0].key + "/" + match[0].value + " / Exists: " + format_str.format(n['title'], n_id)) existing_entry = Page.load(match[0].objectid) update = existing_entry.kv_get('update').count() # raise Exception(update) q.append('{} / {}'.format(string_to_date(n['modified_date']).replace(tzinfo=None), existing_entry.modified_date )) if string_to_date(n['modified_date']).replace(tzinfo=None) <= existing_entry.modified_date and update == 0: q.append('Existing page {} not changed.'.format(existing_entry.id)) else: changed = True q.append('Updating data for existing page {}.'.format(existing_entry.id)) existing_entry.title = n['title'] existing_entry.text = n['text'] existing_entry.basename = n['basename'] existing_entry.excerpt = n['excerpt'] existing_entry.created_date = string_to_date(n['created_date']).replace(tzinfo=None) existing_entry.modified_date = string_to_date(n['modified_date']).replace(tzinfo=None) existing_entry.publication_date = string_to_date(n['publication_date']).replace(tzinfo=None) try: existing_entry.save(user, False, False, 'New revision from import') except PageNotChanged: pass except InterfaceError: raise Exception("Error saving {}. Check the JSON to make sure it's valid.".format(n_id)) for media in existing_entry.media: media.kv_del() existing_entry.clear_categories() existing_entry.clear_kvs() existing_entry.clear_tags() existing_entry.clear_media() entry = existing_entry if found is False: q.append("Creating: " + format_str.format(n['title'], n_id)) changed = True new_entry = Page( title=n['title'], text=n['text'], basename=n['basename'], excerpt=n['excerpt'], user=user, blog=blog, created_date=string_to_date(n['created_date']), publication_date=string_to_date(n['publication_date']), modified_date=string_to_date(n['modified_date']), ) new_entry.modified_date = new_entry.publication_date if n['status'] in ('Publish', 'Published', 'Live'): new_entry.status = page_status.published new_entry.save(user) entry = new_entry q.append("New ID: {}".format(entry.id)) # Everything from here on out is if changed: # Register a legacy ID for the page entry.kv_set("legacy_id", n["id"]) entry.kv_set("legacy_user", n["user_id"]) # Category assignments categories = n['categories'] if categories == []: saved_page_category = PageCategory.create( page=entry, category=blog.default_category, primary=True).save() else: primary = True for category in categories: cat_exists = False category_id = category['id'] existing_category = Category.kv_get('legacy_id', category_id) if existing_category.count() > 0: if existing_category[0].object_ref.blog == blog: cat_exists = True if cat_exists is False: q.append('Created new category {}/{}'.format( category_id, category['name'] )) new_category = Category.create( blog=blog, title=category['name'], parent_category=getattr(category, 'parent', None) ) new_category.save() new_category.kv_set('legacy_id', category_id ) else: new_category = Category.load(existing_category[0].objectid) q.append('Added to existing category {}/{}'.format( new_category.id, category['name'] )) saved_page_category = PageCategory.create( page=entry, category=new_category, primary=primary ).save() primary = False # Check to make sure a default category exists for the whole blog. # If not, assign one based on the lowest ID. # This can always be reassigned later. # Register tags tags_added, tags_existing, _ = Tag.add_or_create( n['tags'], page=entry) q.append('Tags added: {}'.format(','.join(n.tag for n in tags_added))) q.append('Tags existing: {}'.format(','.join(n.tag for n in tags_existing))) # Register KVs kvs = n['kvs'] for key in kvs: if key != "": value = kvs[key] entry.kv_set(key, value) q.append('KV: {}:{}'.format(key, value)) # Register media media = n['media'] for m in media: if 'path' not in m: continue path = os.path.split(m['path']) try: new_media = Media.get(Media.url == m['url']) except: new_media = Media( filename=path[1], path=m['path'], url=m['url'], type=media_filetypes.image, created_date=string_to_date(m['created_date']), modified_date=string_to_date(m['modified_date']), friendly_name=m['friendly_name'], user=user, blog=blog, site=blog.site ) # TODO: RBF try: new_media.save() except Exception: continue media_association = MediaAssociation( media=new_media, page=entry) media_association.save() # Save legacy ID to KV on media if 'id' in m: new_media.kv_set('legacy_id', m['id']) q.append('IMG: {}'.format(new_media.url)) # add tags for media q.append('Tags: {}'.format(m['tags'])) new_tags = Tag.add_or_create(m['tags'], media=new_media) kvs = m['kvs'] for key in kvs: value = kvs[key] new_media.kv_set(key, value) q.append('KV: {}:{}'.format(key, value)) fileinfo.build_pages_fileinfos((entry,)) fileinfo.build_archives_fileinfos((entry,)) tpl += ('<p>'.join(q)) + '<hr/>' return tpl # TODO: # Import or create categories as needed # Categories in export will need to have parent-child data # categories should have legacy identifiers where possible too # Import image files, assign those legacy KV identifiers # Modify URLs for imported images in posts # Make importing of image assets optional else: tpl = template('ui/ui_blog_import', menu=generate_menu('blog_import', blog), # search_context=(search_context['blog'], blog), import_path=import_path, **tags.__dict__) return tpl
def blog_import(blog_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, True) tags = template_tags(blog=blog, user=user) import os, settings import_path = os.path.join(settings.APPLICATION_PATH, "data", "import.json") tags.status = reason if request.method == "POST": from core.models import db tpl = '' with db.atomic() as txn: import json from core.utils import string_to_date import_path = request.forms.getunicode('import_path') with open(import_path, 'r', encoding='utf8') as f: json_data = json.load(f) from core.models import page_status, MediaAssociation, Category from core.error import PageNotChanged from core.libs.peewee import InterfaceError from core.cms import media_filetypes format_str = "<b>{}</b> / (<i>{}</i>)" # TODO: go in chunks of 50 or something? # allow graceful disconnection? for n in json_data: q = [] n_id = n['id'] q.append("Checking {}".format(n_id)) changed = False found = False match = Page.kv_get('legacy_id', n_id) if match.count() > 0: if match[0].object_ref.blog == blog: found = True q.append(match[0].key + "/" + match[0].value + " / Exists: " + format_str.format(n['title'], n_id)) existing_entry = Page.load(match[0].objectid) update = existing_entry.kv_get('update').count() # raise Exception(update) q.append('{} / {}'.format( string_to_date( n['modified_date']).replace(tzinfo=None), existing_entry.modified_date)) if string_to_date(n['modified_date']).replace( tzinfo=None ) <= existing_entry.modified_date and update == 0: q.append('Existing page {} not changed.'.format( existing_entry.id)) else: changed = True q.append( 'Updating data for existing page {}.'.format( existing_entry.id)) existing_entry.title = n['title'] existing_entry.text = n['text'] existing_entry.basename = n['basename'] existing_entry.excerpt = n['excerpt'] existing_entry.created_date = string_to_date( n['created_date']).replace(tzinfo=None) existing_entry.modified_date = string_to_date( n['modified_date']).replace(tzinfo=None) existing_entry.publication_date = string_to_date( n['publication_date']).replace(tzinfo=None) try: existing_entry.save( user, False, False, 'New revision from import') except PageNotChanged: pass except InterfaceError: raise Exception( "Error saving {}. Check the JSON to make sure it's valid." .format(n_id)) for media in existing_entry.media: media.kv_del() existing_entry.clear_categories() existing_entry.clear_kvs() existing_entry.clear_tags() existing_entry.clear_media() entry = existing_entry if found is False: q.append("Creating: " + format_str.format(n['title'], n_id)) changed = True new_entry = Page( title=n['title'], text=n['text'], basename=n['basename'], excerpt=n['excerpt'], user=user, blog=blog, created_date=string_to_date(n['created_date']), publication_date=string_to_date(n['publication_date']), modified_date=string_to_date(n['modified_date']), ) new_entry.modified_date = new_entry.publication_date if n['status'] in ('Publish', 'Published', 'Live'): new_entry.status = page_status.published new_entry.save(user) entry = new_entry q.append("New ID: {}".format(entry.id)) # Everything from here on out is if changed: # Register a legacy ID for the page entry.kv_set("legacy_id", n["id"]) entry.kv_set("legacy_user", n["user_id"]) # Category assignments categories = n['categories'] if categories == []: saved_page_category = PageCategory.create( page=entry, category=blog.default_category, primary=True).save() else: primary = True for category in categories: cat_exists = False category_id = category['id'] existing_category = Category.kv_get( 'legacy_id', category_id) if existing_category.count() > 0: if existing_category[ 0].object_ref.blog == blog: cat_exists = True if cat_exists is False: q.append('Created new category {}/{}'.format( category_id, category['name'])) new_category = Category.create( blog=blog, title=category['name'], parent_category=getattr( category, 'parent', None)) new_category.save() new_category.kv_set('legacy_id', category_id) else: new_category = Category.load( existing_category[0].objectid) q.append( 'Added to existing category {}/{}'.format( new_category.id, category['name'])) saved_page_category = PageCategory.create( page=entry, category=new_category, primary=primary).save() primary = False # Check to make sure a default category exists for the whole blog. # If not, assign one based on the lowest ID. # This can always be reassigned later. # Register tags tags_added, tags_existing, _ = Tag.add_or_create( n['tags'], page=entry) q.append('Tags added: {}'.format(','.join( n.tag for n in tags_added))) q.append('Tags existing: {}'.format(','.join( n.tag for n in tags_existing))) # Register KVs kvs = n['kvs'] for key in kvs: if key != "": value = kvs[key] entry.kv_set(key, value) q.append('KV: {}:{}'.format(key, value)) # Register media media = n['media'] for m in media: if 'path' not in m: continue path = os.path.split(m['path']) try: new_media = Media.get(Media.url == m['url']) except: new_media = Media(filename=path[1], path=m['path'], url=m['url'], type=media_filetypes.image, created_date=string_to_date( m['created_date']), modified_date=string_to_date( m['modified_date']), friendly_name=m['friendly_name'], user=user, blog=blog, site=blog.site) # TODO: RBF try: new_media.save() except Exception: continue media_association = MediaAssociation(media=new_media, page=entry) media_association.save() # Save legacy ID to KV on media if 'id' in m: new_media.kv_set('legacy_id', m['id']) q.append('IMG: {}'.format(new_media.url)) # add tags for media q.append('Tags: {}'.format(m['tags'])) new_tags = Tag.add_or_create(m['tags'], media=new_media) kvs = m['kvs'] for key in kvs: value = kvs[key] new_media.kv_set(key, value) q.append('KV: {}:{}'.format(key, value)) fileinfo.build_pages_fileinfos((entry, )) fileinfo.build_archives_fileinfos((entry, )) tpl += ('<p>'.join(q)) + '<hr/>' return tpl # TODO: # Import or create categories as needed # Categories in export will need to have parent-child data # categories should have legacy identifiers where possible too # Import image files, assign those legacy KV identifiers # Modify URLs for imported images in posts # Make importing of image assets optional else: tpl = template( 'ui/ui_blog_import', menu=generate_menu('blog_import', blog), # search_context=(search_context['blog'], blog), import_path=import_path, **tags.__dict__) return tpl
def page_delete(page_id, confirm): ''' Deletes a selected page -- no confirmation yet Returns user to list of pages in blog with a notice about the deleted file ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) blog = page.blog from core.utils import Status tags = template_tags(page=page, user=user) from core.models import page_status if page.status != page_status.unpublished: message = 'Page <b>{}</b> is not set to unpublished and cannot be deleted. Unpublish this page before deleting it.'.format( page.for_display) url = '{}/blog/{}'.format(BASE_URL, blog.id) action = 'Return to the page listing' tags.status = Status(type='danger', no_sure=True, message=message, action=action, url=url, close=False) else: if request.forms.getunicode('confirm') == user.logout_nonce: p = page.for_log from core.cms.cms import delete_page delete_page(page) message = 'Page {} successfully deleted'.format(p) url = '{}/blog/{}'.format(BASE_URL, blog.id) action = 'Return to the page listing' tags.status = Status(type='success', message=message, action=action, url=url, close=False) logger.info("Page {} deleted by user {}.".format(p, user.for_log)) else: message = ( 'You are about to delete page <b>{}</b> from blog <b>{}</b>.'. format(page.for_display, blog.for_display)) yes = { 'label': 'Yes, delete this page', 'id': 'delete', 'name': 'confirm', 'value': user.logout_nonce } no = { 'label': 'No, return to blog page listing', 'url': '{}/blog/{}'.format(BASE_URL, blog.id) } tags.status = Status(message=message, type='warning', close=False, yes=yes, no=no) return report(tags, 'blog_delete_page', page)
def template_preview_core(template_id): ''' UI for generating a preview of a given template ''' from core.models import Page, FileInfo, page_status from core.cms import fileinfo from core.cms import invalidate_cache invalidate_cache() template = Template.load(template_id) # TODO: only rebuild mappings if the dirty bit is set if template.template_type == template_type.index: fi = template.default_mapping.fileinfos test_preview_mapping(fi.count(), template) fi = fi.get() tags = template_tags(blog=template.blog, template=template, fileinfo=fi) elif template.template_type == template_type.page: try: fi = Page.load(int(request.query['use_page'])).fileinfos[0] except (KeyError, TypeError): fi = template.fileinfos test_preview_mapping(fi.count(), template) fi = fi.select().join(Page).where( FileInfo.page == Page.id, Page.blog == template.blog, Page.status == page_status.published, ).order_by(Page.publication_date.desc()).get() tags = template_tags( template=template, page=fi.page, ) elif template.template_type == template_type.include: if template.publishing_mode != publishing_mode.ssi: from core.error import PreviewException raise PreviewException( 'You can only preview server-side includes.') page = template.blog.pages.published.order_by( Page.publication_date.desc()).get() fi = page.fileinfos[0] tags = template_tags( template=template, page=page, ) elif template.template_type == template_type.archive: if 'use_page' in request.query: page_list = [Page.load(int(request.query['use_page']))] elif 'use_category' in request.query: from core.models import Category page_list = Category.load(int( request.query['use_category'])).pages.published.limit(1) elif 'use_tag' in request.query: from core.models import Tag page_list = Tag.load(int( request.query['use_tag'])).pages.published.limit(1) else: page_list = template.blog.pages.published.limit(1) fi = fileinfo.build_archives_fileinfos_by_mappings(template, pages=page_list) test_preview_mapping(len(fi), template) fi = fi[0] archive_pages = fileinfo.generate_archive_context_from_fileinfo( fi.xref.archive_xref, template.blog.pages.published, fi) tags = template_tags(blog=template.blog, archive=archive_pages, archive_context=fi, fileinfo=fi, template=template) elif template.template_type in (template_type.media, template_type.system): from core.error import PreviewException raise PreviewException( 'Template {} is of a type that cannot yet be previewed.'.format( template.for_log)) import time from core.template import tplt tc = time.clock start = tc() tpl_output = tplt(template, tags) end = tc() tpl_output = r'<!-- Produced by template {}. Total render time:{} secs -->{}'.format( template.for_log, end - start, tpl_output) preview_file_path, preview_url = fi.make_preview() from core.cms import queue queue.write_file(tpl_output, template.blog.path, preview_file_path) return ("{}?_={}".format(preview_url, template.modified_date.microsecond))
def page_delete(page_id, confirm): ''' Deletes a selected page -- no confirmation yet Returns user to list of pages in blog with a notice about the deleted file ''' user = auth.is_logged_in(request) page = Page.load(page_id) permission = auth.is_page_editor(user, page) blog = page.blog from core.utils import Status tags = template_tags( page=page, user=user) from core.models import page_status if page.status != page_status.unpublished: message = 'Page <b>{}</b> is not set to unpublished and cannot be deleted. Unpublish this page before deleting it.'.format( page.for_display) url = '{}/blog/{}'.format(BASE_URL, blog.id) action = 'Return to the page listing' tags.status = Status( type='danger', no_sure=True, message=message, action=action, url=url, close=False) else: if request.forms.getunicode('confirm') == user.logout_nonce: p = page.for_log from core.cms.cms import delete_page delete_page(page) message = 'Page {} successfully deleted'.format( p) url = '{}/blog/{}'.format(BASE_URL, blog.id) action = 'Return to the page listing' tags.status = Status( type='success', message=message, action=action, url=url, close=False) logger.info("Page {} deleted by user {}.".format( p, user.for_log)) else: message = ('You are about to delete page <b>{}</b> from blog <b>{}</b>.'.format( page.for_display, blog.for_display)) yes = { 'label':'Yes, delete this page', 'id':'delete', 'name':'confirm', 'value':user.logout_nonce} no = { 'label':'No, return to blog page listing', 'url':'{}/blog/{}'.format( BASE_URL, blog.id) } tags.status = Status( message=message, type='warning', close=False, yes=yes, no=no ) return report(tags, 'blog_delete_page', page)