def queue_index_actions(blog): ''' Pushes to the publishing queue all the index pages for a given blog that are marked for Immediate publishing. ''' try: templates = Template.select().where( Template.blog == blog, Template.template_type == template_type.index, Template.publishing_mode == publishing_mode.immediate) if templates.count() == 0: raise Template.DoesNotExist except Template.DoesNotExist: raise Template.DoesNotExist( "No index templates exist for blog {}.".format(blog.for_log)) else: mappings = TemplateMapping.select().where( TemplateMapping.template << templates) fileinfos = FileInfo.select().where( FileInfo.template_mapping << mappings) for f in fileinfos: push_to_queue(job_type=job_type.index, priority=1, blog=blog, site=blog.site, data_integer=f.id)
def handle(self, *args, **options): try: sheet = Spreadsheet.objects.get(name=options["sheet"]) except Spreadsheet.DoesNotExist: self.stderr.write( f"Sheet {options['sheet']} does not exist in the torquedata database." ) return json_file = options["json_file"] template_file = options["template_file"] template_type = options["template_type"] if not json_file.exists(): self.stderr.write(f'Path "{json_file}" does not exist.') if not json_file.is_file(): self.stderr.write(f'Path "{json_file}" is not a file.') if not template_file.exists(): self.stderr.write(f'Path "{template_file}" does not exist.') if not template_file.is_file(): self.stderr.write(f'Path "{template_file}" is not a file.') template = Template( sheet=sheet, type=template_type, template_file=File(open(template_file, "r")), name=options["name"], ) template.save() toc = TableOfContents(sheet=sheet, name=options["name"], json_file=json_file, template=template) toc.save()
def parseTemplates(self): files = [ f for f in listdir(GLABELS_TEMPLATES) if isfile(join(GLABELS_TEMPLATES, f))] for f in files: with open(join(GLABELS_TEMPLATES, f), 'r') as xmlfile: data = xmlfile.read() dom = parseString(data) for template in dom.getElementsByTagName('Template'): if not template.getElementsByTagName('Label-rectangle'): # round labels, etc. continue t = self.parseTemplate(template) t = Template.get_or_insert('-'.join((t['brand'], t['part'])), **t) for alias in self.parseAlias(template): t.aliases.append(Alias.get_or_insert('-'.join((alias['brand'], alias['part'])), **alias).key) for layout in self.parseLayout(template): #TOFIX t.layout = Layout(**layout).put() t.put()
def queue_index_actions(blog, include_manual=False): ''' Pushes to the publishing queue all the index pages for a given blog that are marked for Immediate publishing. :param blog: The blog object whose index templates will be pushed to the queue. :param include_manual: If set to True, all templates, including those set to the Manual publishing mode, will be pushed to the queue. Default is False, since those templates are not pushed in most publishing actions. ''' templates = blog.index_templates.select().where( Template.publishing_mode != publishing_mode.do_not_publish) if include_manual is False: templates = templates.select().where( Template.publishing_mode == publishing_mode.immediate) if templates.count() == 0: raise Template.DoesNotExist( "No valid index templates exist for blog {}.".format(blog.for_log)) mappings = TemplateMapping.select().where( TemplateMapping.template << templates) fileinfos = FileInfo.select().where(FileInfo.template_mapping << mappings) for f in fileinfos: Queue.push(job_type=job_type.index, priority=1, blog=blog, site=blog.site, data_integer=f.id)
def html_editor_settings(blog): 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 html_editor_settings
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__)
def delete(template): t0 = FileInfo.delete().where( FileInfo.template_mapping << template.mappings) t0.execute() t1 = TemplateMapping.delete().where( TemplateMapping.id << template.mappings) t1.execute() t2 = Template.delete().where(Template.id == template.id) t2.execute()
def export_theme_for_blog(blog_id): from core.models import Template, TemplateMapping, KeyValue theme_to_export = Template.select().where( Template.blog == blog_id) 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 = TemplateMapping.select().where( TemplateMapping.template == n) theme["data"][n.id]["mapping"] = {} for m in mappings_to_export: theme["data"][n.id]["mapping"][m.id] = json_dump(m) 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 with open(settings.APPLICATION_PATH + settings._sep + "install" + settings._sep + "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
def html_editor_settings(blog): 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 html_editor_settings
def new_template(blog_id, tpl_type): with db.atomic() as txn: user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_designer(user, blog) auth.check_template_lock(blog) mappings_index = template_mapping_index.get(tpl_type, None) if mappings_index is None: raise Exception('Mapping type not found') template = Template( blog=blog, theme=blog.theme, template_type=tpl_type, publishing_mode=publishing_mode.do_not_publish, body='', ) template.save(user) template.title = 'Untitled Template #{}'.format(template.id) template.save(user) if tpl_type != template_type.media: new_template_mapping = TemplateMapping( template=template, is_default=True, path_string="'" + utils.create_basename(template.title, blog) + "'") new_template_mapping.save() from core.cms import fileinfo fileinfo.build_mapping_xrefs((new_template_mapping, )) from settings import BASE_URL redirect(BASE_URL + '/template/{}/edit'.format(template.id))
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)
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__)
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 theme_apply_to_blog(theme, blog): ''' Applies a given theme to a given blog. Removes and regenerates fileinfos for the pages on the blog. ''' from core import cms cms.purge_fileinfos(blog.fileinfos) mappings_to_remove = TemplateMapping.delete().where( TemplateMapping.template << blog.templates) mappings_to_remove.execute() theme_to_remove = Template.delete().where(Template.blog == blog) theme_to_remove.execute() theme_install_to_blog(theme, blog)
def queue_archive_template_fast(template_id, action, pass_id=0): from core.models import Template, Queue template = Template.load(template_id) blog = template.blog from core import cms from core.libs.bottle import HTTPResponse r = HTTPResponse() fileinfos = FileInfo.select().where(FileInfo.template_mapping << template.mappings).paginate(pass_id, 50) # TODO: if action is fast and no fileinfos present, redirect to full rebuild? if fileinfos.count() > 0: r.body = "Adding {}".format(pass_id * 50) for f in fileinfos: Queue.push(job_type=cms.queue.job_type.archive, blog=blog, site=blog.site, data_integer=f.id) pass_id += 1 r.add_header('Refresh', "0;{}/template/{}/{}/fast/{}".format( BASE_PATH, template_id, action, pass_id)) else: r.body = "Queue insertion finished." if action == 'publish': redir = 'publish' else: redir = 'queue' r.add_header('Refresh', "0;{}/blog/{}/{}".format( BASE_PATH, blog.id, redir)) return r
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 queue_archive_template_all(template_id, action, pass_id=0): from core.models import Template, Queue template = Template.load(template_id) blog = template.blog from core.cms import fileinfo, queue from core.libs.bottle import HTTPResponse r = HTTPResponse() pages = blog.pages.published.paginate(pass_id, 50) if pages.count() > 0: r.body = "Adding {}".format(pass_id * 50) for f in fileinfo.build_archives_fileinfos_by_mappings(template, pages): Queue.push(job_type=queue.job_type.archive, blog=blog, site=blog.site, data_integer=f.id) pass_id += 1 r.add_header('Refresh', "0;{}/template/{}/{}/all/{}".format( BASE_PATH, template_id, action, pass_id)) else: r.body = "Queue insertion finished." if action == 'publish': redir = 'publish' else: redir = 'queue' r.add_header('Refresh', "0;{}/blog/{}/{}".format( BASE_PATH, blog.id, redir)) return r
def queue_archive_template_fast(template_id, action, pass_id=0): from core.models import Template, Queue template = Template.load(template_id) blog = template.blog from core import cms from core.libs.bottle import HTTPResponse r = HTTPResponse() fileinfos = FileInfo.select().where( FileInfo.template_mapping << template.mappings).paginate(pass_id, 50) # TODO: if action is fast and no fileinfos present, redirect to full rebuild? if fileinfos.count() > 0: r.body = "Adding {}".format(pass_id * 50) for f in fileinfos: Queue.push(job_type=cms.queue.job_type.archive, blog=blog, site=blog.site, data_integer=f.id) pass_id += 1 r.add_header( 'Refresh', "0;{}/template/{}/{}/fast/{}".format(BASE_PATH, template_id, action, pass_id)) else: r.body = "Queue insertion finished." if action == 'publish': redir = 'publish' else: redir = 'queue' r.add_header('Refresh', "0;{}/blog/{}/{}".format(BASE_PATH, blog.id, redir)) return r
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_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
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)
def queue_archive_template_all(template_id, action, pass_id=0): from core.models import Template, Queue template = Template.load(template_id) blog = template.blog from core.cms import fileinfo, queue from core.libs.bottle import HTTPResponse r = HTTPResponse() pages = blog.pages.published.paginate(pass_id, 50) if pages.count() > 0: r.body = "Adding {}".format(pass_id * 50) for f in fileinfo.build_archives_fileinfos_by_mappings( template, pages): Queue.push(job_type=queue.job_type.archive, blog=blog, site=blog.site, data_integer=f.id) pass_id += 1 r.add_header( 'Refresh', "0;{}/template/{}/{}/all/{}".format(BASE_PATH, template_id, action, pass_id)) else: r.body = "Queue insertion finished." if action == 'publish': redir = 'publish' else: redir = 'queue' r.add_header('Refresh', "0;{}/blog/{}/{}".format(BASE_PATH, blog.id, redir)) return r
def _combine(self, registry: Registry, language: str, first: Message, second: Message) -> Message: log.debug("Combining two templates:") log.debug("\t{}".format([c.value for c in first.template.components])) log.debug("\t{}".format([c.value for c in second.template.components])) shared_prefix = self._get_combinable_prefix(first, second) log.debug(f"Shared prefix is {[e.value for e in shared_prefix]}") combined = [c for c in first.template.components] # TODO At the moment everything is considered either positive or negative, which is sometimes weird. # Add neutral sentences. conjunctions = registry.get("conjunctions").get(language, None) if not conjunctions: conjunctions = (defaultdict(lambda x: "NO-CONJUNCTION-DICT"), ) if first.polarity != first.polarity: combined.append( Literal( conjunctions.get("inverse_combiner", "MISSING-INVERSE-CONJUCTION"))) else: combined.append( Literal( conjunctions.get("default_combiner", "MISSING-DEFAULT-CONJUCTION"))) combined.extend(second.template.components[len(shared_prefix):]) log.debug("Combined thing is {}".format([c.value for c in combined])) new_message = Message( facts=first.facts + [fact for fact in second.facts if fact not in first.facts], importance_coefficient=first.importance_coefficient, ) new_message.template = Template(combined) new_message.prevent_aggregation = True return new_message
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_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__)
def blog_save_theme(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) tags = template_tags(blog=blog, user=user) from core.utils import Status, create_basename_core if request.method == 'POST': theme = Theme( title=request.forms.getunicode('theme_title'), description=request.forms.getunicode('theme_description'), json='') export = blog.export_theme(theme.title, theme.description, user) from settings import THEME_FILE_PATH # , _sep import os directory_name = create_basename_core(theme.title) dirs = [x[0] for x in os.walk(THEME_FILE_PATH)] dir_name_ext = 0 dir_name_full = directory_name while 1: if dir_name_full in dirs: dir_name_ext += 1 dir_name_full = directory_name + "-" + str(dir_name_ext) continue else: break dir_name_final = os.path.join(THEME_FILE_PATH, dir_name_full) os.makedirs(dir_name_final) theme.json = dir_name_full theme.save() Template.update(theme=theme).where(Template.blog == blog).execute() TemplateRevision.update(theme=theme).where(TemplateRevision.blog == blog).execute() blog.theme = theme blog.theme_modified = False blog.save() for n in export: with open(os.path.join(dir_name_final, n), "w", encoding='utf-8') as output_file: output_file.write(export[n]) save_tpl = 'listing/report' status = Status( type='success', close=False, message=''' Theme <b>{}</b> was successfully saved from blog <b>{}</b>. '''.format('', blog.for_display, ''), action='Return to theme list', url='{}/blog/{}/themes'.format( BASE_URL, blog.id) ) else: save_tpl = 'edit/theme_save' status = None tags.status = status if reason is None else reason import datetime # TODO: eventually this will be migrated to the report function # but it's a little complex for that now due to the funtion logic return template(save_tpl, menu=generate_menu('blog_save_theme', blog), # search_context=(search_context['blog'], blog), theme_title=blog.theme.title + " (Revised {})".format(datetime.datetime.now()), theme_description=blog.theme.description, msg_float=False, ** tags.__dict__)
def blog_templates(blog_id): ''' List all templates in a given blog ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_designer(user, blog) reason = auth.check_template_lock(blog, True) tags = template_tags(blog_id=blog.id, user=user) tags.status = reason from core.libs.peewee import JOIN_LEFT_OUTER template_list = Template.select(Template, TemplateMapping).join( TemplateMapping, JOIN_LEFT_OUTER).where( (Template.blog == blog)).order_by(Template.title) index_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.index) page_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.page) archive_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.archive) template_includes = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.include) media_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.media) code_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.code) system_templates = template_list.select( Template, TemplateMapping).where(Template.template_type == template_type.system) from core.models import archive_defaults tags.list_items = ( { 'title': 'Index Templates', 'type': template_type.index, 'data': index_templates, 'defaults': archive_defaults[template_type.index] }, { 'title': 'Page Templates', 'type': template_type.page, 'data': page_templates, 'defaults': archive_defaults[template_type.page] }, { 'title': 'Archive Templates', 'type': template_type.archive, 'data': archive_templates, 'defaults': archive_defaults[template_type.archive] }, { 'title': 'Includes', 'type': template_type.include, 'data': template_includes }, { 'title': 'Media Templates', 'type': template_type.media, 'data': media_templates }, { 'title': 'Code', 'type': template_type.code, 'data': code_templates }, { 'title': 'System Templates', 'type': template_type.system, 'data': system_templates }, ) return template('ui/ui_blog_templates', icons=icons, section_title="Templates", publishing_mode=publishing_mode, search_context=(search_contexts['blog_templates'], blog), menu=generate_menu('blog_manage_templates', blog), templates_with_defaults=('Index', 'Page', 'Archive'), **tags.__dict__)
def theme_install_to_blog(installed_theme, blog): json_obj = json.loads(installed_theme.json) templates = json_obj["data"] kvs = json_obj["kv"] for t in templates: template = templates[t]["template"] table_obj = Template() for name in table_obj._meta.fields: if name not in ("id"): setattr(table_obj, name, template[name]) table_obj.theme = installed_theme table_obj.blog = blog table_obj.save() mappings = templates[t]["mapping"] for mapping in mappings: mapping_obj = TemplateMapping() for name in mapping_obj._meta.fields: if name not in ("id"): setattr(mapping_obj, name, mappings[mapping][name]) mapping_obj.template = table_obj mapping_obj.save() kv_index = {} kx = System() for kv in kvs: kv_current = kvs[kv] new_kv = kx.add_kv(**kv_current) kv_index[kv_current['id']] = new_kv.id for kv in kv_index: kv_current = kv new_kv_value = kv_index[kv] kv_to_change = KeyValue.get(KeyValue.id == new_kv_value) parent = kv_to_change.__dict__['_data']['parent'] if parent is None: continue kv_to_change.parent = kv_index[parent] kv_to_change.save() from core import cms # TODO: use purge_blog instead # for n in blog.pages(): cms.build_pages_fileinfos(blog.pages()) # for n in blog.index_templates: cms.build_indexes_fileinfos(blog.index_templates)
def blog_save_theme(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) tags = template_tags(blog=blog, user=user) from core.utils import Status, create_basename_core if request.method == 'POST': theme = Theme( title=request.forms.getunicode('theme_title'), description=request.forms.getunicode('theme_description'), json='') export = blog.export_theme(theme.title, theme.description, user) from settings import THEME_FILE_PATH # , _sep import os directory_name = create_basename_core(theme.title) dirs = [x[0] for x in os.walk(THEME_FILE_PATH)] dir_name_ext = 0 dir_name_full = directory_name while 1: if dir_name_full in dirs: dir_name_ext += 1 dir_name_full = directory_name + "-" + str(dir_name_ext) continue else: break dir_name_final = os.path.join(THEME_FILE_PATH, dir_name_full) os.makedirs(dir_name_final) theme.json = dir_name_full theme.save() Template.update(theme=theme).where(Template.blog == blog).execute() TemplateRevision.update(theme=theme).where( TemplateRevision.blog == blog).execute() blog.theme = theme blog.theme_modified = False blog.save() for n in export: with open(os.path.join(dir_name_final, n), "w", encoding='utf-8') as output_file: output_file.write(export[n]) save_tpl = 'listing/report' status = Status(type='success', close=False, message=''' Theme <b>{}</b> was successfully saved from blog <b>{}</b>. '''.format('', blog.for_display, ''), action='Return to theme list', url='{}/blog/{}/themes'.format(BASE_URL, blog.id)) else: save_tpl = 'edit/theme_save' status = None tags.status = status if reason is None else reason import datetime # TODO: eventually this will be migrated to the report function # but it's a little complex for that now due to the funtion logic return template( save_tpl, menu=generate_menu('blog_save_theme', blog), # search_context=(search_context['blog'], blog), theme_title=blog.theme.title + " (Revised {})".format(datetime.datetime.now()), theme_description=blog.theme.description, msg_float=False, **tags.__dict__)
def _include(self, env, _name=None, **kwargs): from core.models import Template template_to_import = Template.get(Template.title == _name) tpl = MetalTemplate(template_to_import.body) self.includes.append(_name) return tpl.execute(env['_stdout'], env)
def blog_templates(blog_id): ''' List all templates in a given blog ''' user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_designer(user, blog) reason = auth.check_template_lock(blog, True) tags = template_tags(blog_id=blog.id, user=user) tags.status = reason from core.libs.peewee import JOIN_LEFT_OUTER template_list = Template.select(Template, TemplateMapping).join( TemplateMapping, JOIN_LEFT_OUTER).where( (Template.blog == blog) ).order_by(Template.title) index_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.index) page_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.page) archive_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.archive) template_includes = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.include) media_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.media) code_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.code) system_templates = template_list.select(Template, TemplateMapping).where( Template.template_type == template_type.system) from core.models import archive_defaults tags.list_items = ( {'title':'Index Templates', 'type': template_type.index, 'data':index_templates, 'defaults': archive_defaults[template_type.index]}, {'title':'Page Templates', 'type': template_type.page, 'data':page_templates, 'defaults':archive_defaults[template_type.page]}, {'title':'Archive Templates', 'type': template_type.archive, 'data':archive_templates, 'defaults': archive_defaults[template_type.archive]}, {'title':'Includes', 'type': template_type.include, 'data':template_includes}, {'title':'Media Templates', 'type': template_type.media, 'data':media_templates}, {'title':'Code', 'type': template_type.code, 'data':code_templates}, {'title':'System Templates', 'type': template_type.system, 'data':system_templates}, ) return template('ui/ui_blog_templates', icons=icons, section_title="Templates", publishing_mode=publishing_mode, search_context=(search_contexts['blog_templates'], blog), menu=generate_menu('blog_manage_templates', blog), templates_with_defaults=('Index', 'Page', 'Archive'), ** tags.__dict__)
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 template_edit_save(template_id): ''' UI for saving a blog template ''' user = auth.is_logged_in(request) tpl = Template.load(template_id) blog = Blog.load(tpl.blog) permission = auth.is_blog_designer(user, blog) auth.check_template_lock(blog) from core.utils import Status from core.error import TemplateSaveException, PageNotChanged status = None save_mode = int(request.forms.getunicode('save', default="0")) if save_mode in (1, 2, 3): try: message = template_save(request, user, tpl, blog) except TemplateSaveException as e: status = Status(type='danger', no_sure=True, message="Error saving template <b>{}</b>:".format( tpl.for_display), message_list=(e, )) except PageNotChanged as e: status = Status(type='success', message="Template <b>{}</b> was unchanged.".format( tpl.for_display)) except Exception as e: raise e status = Status( type='warning', no_sure=True, message="Problem saving template <b>{}</b>: <br>".format( tpl.for_display), message_list=(e, )) else: tpl.delete_preview() status = Status( type='success', message="Template <b>{}</b> saved successfully. {}".format( tpl.for_display, message) # TODO: move messages into message lister ) tags = template_tags(template_id=template_id, user=user) tags.mappings = template_mapping_index[tpl.template_type] tags.status = status from core.models import (template_type as template_types) return template('edit/template_ajax', sidebar=sidebar.render_sidebar( panel_set='edit_template', publishing_mode=publishing_mode, types=template_types, **tags.__dict__), **tags.__dict__)
def template_refresh(template_id): ''' UI for reloading a template from the original version stored in the template's theme (assuming such an original template exists) ''' 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: import os, json template_path = (os.path.join(tpl.theme.path, tpl.template_ref)) with open(template_path, 'r') as f: tp_json = json.loads(f.read()) # TODO: We will eventually merge in all the other refresh functions # and convert this to a generic function called from # mgmt.theme_apply_to_blog as well with open(template_path[:-5] + '.tpl', 'r') as b: tpl.body = b.read() tpl.save(user) 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)) else: status = Status(type='warning', close=False, message=''' You are attempting to refresh template <b>{}</b> for blog <b>{}</b> from its underlying theme <b>{}</b>.</p> <p>This will <b>overwrite</b> the current version of the template and replace it with the original version from the theme. '''.format(tpl.for_display, blog.for_display, tpl.theme.for_display), no={ 'url': '{}/template/{}/edit'.format( settings.BASE_URL, tpl.id), 'label': 'No, I don\'t want to replace this template' }, yes={ 'id': 'delete', 'name': 'confirm', 'label': 'Yes, I want to replace this template', 'value': user.logout_nonce }) tags.status = status return report(tags, 'blog_delete_template', tpl)