Source

c5t / c5t / core / lib / helpers.py

# -*- coding: utf-8 -*-

"""WebHelpers used in c5t."""

from webhelpers import date, feedgenerator, html, number, misc, text
from HTMLParser import HTMLParser
from c5t.core.model.content import Page

import os, re
from tg import config, request, flash
from tg.util import odict
import pkg_resources

def find_templates_in_package(package):
    start_dir = pkg_resources.resource_filename(package, '')
    r = []
    for (path, dirs, files) in os.walk(start_dir):
        #if this directory is not a module, the template may not be used
        if not '__init__.py' in files:
            continue
        dotted_path = package+path[len(start_dir):].replace('/', '.')
        for f in files:
            if f.endswith('.mak'):
                r.append('.'.join((dotted_path, f[:-4])))
                continue
            if f.endswith('.mako'):
                r.append('.'.join((dotted_path, f[:-5])))
    return sorted(r)

def make_template_list():
    r = odict()
    package = config['pylons.package']
    if package != 'c5t.core':
        r[package] = find_templates_in_package(package)
    r['c5t'] = find_templates_in_package('c5t.core')
    return r

def make_parent_list():
    (page_ids,page_names) = get_pages_id_name('')
    page_count = len(page_ids)
    return (page_names,page_ids,page_count)

def is_admin(page):
    identity = getattr(request, 'identity', None)
    if not identity:
        return False
    user = identity.get('user', None)
    if user and user.role == 'admin':
        return True
    return False

def can_edit(page):
    identity = getattr(request, 'identity', None)
    if not identity:
        return False
    user = identity.get('user', None)
    if user and user.role in ['editor', 'writer', 'admin']:
        return True
    return False

def can_add(page):
    identity = getattr(request, 'identity', None)
    if not identity:
        return False
    user = identity.get('user', None)
    if user and user.role in ['writer', 'admin']:
        return True
    return False

def can_delete(page):
    return can_add(page)

def get_pages_id_name(current_page_id=None):
    page_ids = []
    page_names =[]
    parent_pages = {}
    allpages = [page for page in Page.query.find()]
    allpages = sorted(allpages, key=lambda page: (page.parent_id, page.title))
    for a_page in allpages:
        if a_page.parent_id and a_page.parent_id != current_page_id:
            parent_pages[a_page.parent_id] = 1
    for a_page in allpages:
        if a_page.parent_id == None:
            page_ids.append(a_page._id)
            page_names.append(a_page.title)
            if a_page._id in parent_pages:
                (page_ids, page_names) = get_child_pages(allpages,page_ids,page_names,parent_pages,a_page._id,'-')
    #remove current page from array
    if current_page_id:
        try:
            pindex = page_ids.index(current_page_id) 
            page_ids.pop(pindex)
            page_names.pop(pindex)
        except ValueError, e:
            pass
    return (page_ids,page_names)

def get_all_tags():
    all_tags_list = [] 
    all_tags = "["  
    # better way to pull as tags? how to use distinct?
    # all_tags = Page.query.find(distinct='tags').distinct(�tags�)
    tags_query = Page.query.find()
    for item in tags_query:
        for tag in item.tags:
           if tag not in all_tags and tag != '[]':
               all_tags_list.append(str(tag))
               all_tags+="'"+str(tag)+"',"
    all_tags+="]"
    return all_tags
        
def get_child_pages(allpages,page_ids,page_names,parent_pages,previous_page_id,indent):
    for a_page in allpages:
        if a_page.parent_id == previous_page_id:
          page_ids.append(a_page._id)
          page_names.append(indent+a_page.title)    
          if a_page._id in parent_pages:
              (page_ids, page_names) = get_child_pages(allpages,page_ids,page_names,parent_pages,a_page._id,indent+'-')
    return (page_ids, page_names)

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    if html is None:
        return "No Content"
    try:
        s.feed(html)
    except Exception, e:
        flash('An error exists in the page being stripped, nothing done: "%s"' % str(e))
        return html
    return s.get_data()