<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from aybu.core.utils.modifiers import urlify
from aybu.core.models import Language
from aybu.core.models import InternalLink, Node, Menu, Page, Section
from aybu.core.models import ExternalLink
from aybu.core.models import Setting
from collections import deque
from collections import namedtuple
from recaptcha.client.captcha import displayhtml
from sqlalchemy.orm.exc import NoResultFound
from webhelpers.html.builder import literal
import logging
import collections

log = logging.getLogger(__name__)


CSS = namedtuple('CSS', ['href', 'media'])
JS = namedtuple('JS', ['href'])

class NodeNotFound(object):
    """ A class mocking a translation when no translations
        are found for a given url (i.e. in 404)
    """
    def __init__(self, request):
        self.meta_description = ''
        self.parent = request.db_session.query(Menu).first()
        self.banners = []
        self.lang = request.language
        self.translations = [self]
        self.title = 'Pagina Non Trovata'
        self.head_content = ''
        self.id = -1
        self.node = self
        self.children = []


class TemplateHelper(object):

    def __init__(self, request):
        self._request = request
        self._settings = SettingProxy(self._request.db_session)
        self._menus = MenuProxy(self._request.db_session)
        self._languages = Language.get_by_enabled(self._request.db_session,
                                                      True)
        if hasattr(self._request, "context"):
            self._translation = self._request.context
            node = getattr(self._translation, 'node', None)
            if not node is None:
                self._node = NodeProxy(node)
                self._language = getattr(self._request.context, 'lang', None)
            else:
                self._node = self._language = None
        else:
            self._translation = NodeNotFound(request)
            self._node = NodeProxy(self._translation)
            self._language = request.language

    def static_url(self, resource_url):
        return str('/static%s' % resource_url)

    def url(self, url, *args, **kwargs):
        import inspect
        log.debug("Called %s.url with params: '%s', '%s', '%s'",
                    __name__, url, args, kwargs)
        try:
            frame = inspect.stack()[1]
            log.debug("Called from: %s'", frame)
            return url

        except Exception as e:
            log.error('url helper does not work! %s', e)

        finally:
            del frame

    @property
    def literal(self):
        return literal

    @property
    def settings(self):
        return self._settings

    @property
    def rendering_type(self):
        return 'dynamic'

    @property
    def user(self):
        return None

    @property
    def node(self):
        if self._node is None:
            raise ValueError('Node is None')

        return self._node

    @property
    def languages(self):
        return self._languages

    @property
    def lang(self):
        if self._language is None:
            raise ValueError('Language is None')

        return self._language

    @property
    def menus(self):
        return self._menus

    @property
    def translation(self):
        return self._translation

    def urlify(self, name):
        return urlify(name)

    def captcha(self, error=None):

        #public_key = '<KEY>'

        html = displayhtml('<KEY>', error)

        return literal(html)



class SettingProxy(object):

    def __init__(self, session):
        self.session = session
        self._settings = {}

    def __getattr__(self, attr_name):

        try:
            return self._settings[attr_name].value
        except KeyError:
            try:
                self._settings[attr_name] = Setting.get(self.session, attr_name)<commit_msg>Permit to set rendering type in template helper<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from aybu.core.utils.modifiers import urlify
from aybu.core.models import Language
from aybu.core.models import InternalLink, Node, Menu, Page, Section
from aybu.core.models import ExternalLink
from aybu.core.models import Setting
from collections import deque
from collections import namedtuple
from recaptcha.client.captcha import displayhtml
from sqlalchemy.orm.exc import NoResultFound
from webhelpers.html.builder import literal
import logging


log = logging.getLogger(__name__)
CSS = namedtuple('CSS', ['href', 'media'])
JS = namedtuple('JS', ['href'])

class NodeNotFound(object):
    """ A class mocking a translation when no translations
        are found for a given url (i.e. in 404)
    """
    def __init__(self, request):
        self.meta_description = ''
        self.parent = request.db_session.query(Menu).first()
        self.banners = []
        self.lang = request.language
        self.translations = [self]
        self.title = 'Pagina Non Trovata'
        self.head_content = ''
        self.id = -1
        self.node = self
        self.children = []


class TemplateHelper(object):

    def __init__(self, request):
        self._request = request
        self._settings = SettingProxy(self._request.db_session)
        self._menus = MenuProxy(self._request.db_session)
        self._languages = Language.get_by_enabled(self._request.db_session,
                                                      True)

        self._rendering_type = 'dynamic'

        if hasattr(self._request, "context"):
            self._translation = self._request.context
            node = getattr(self._translation, 'node', None)
            if not node is None:
                self._node = NodeProxy(node)
                self._language = getattr(self._request.context, 'lang', None)
            else:
                self._node = self._language = None
        else:
            self._translation = NodeNotFound(request)
            self._node = NodeProxy(self._translation)
            self._language = request.language

    def static_url(self, resource_url):
        return str('/static%s' % resource_url)

    def url(self, url, *args, **kwargs):
        import inspect
        log.debug("Called %s.url with params: '%s', '%s', '%s'",
                    __name__, url, args, kwargs)
        try:
            frame = inspect.stack()[1]
            log.debug("Called from: %s'", frame)
            return url

        except Exception as e:
            log.error('url helper does not work! %s', e)

        finally:
            del frame

    @property
    def literal(self):
        return literal

    @property
    def settings(self):
        return self._settings

    @property
    def rendering_type(self):
        return self._rendering_type

    @rendering_type.setter
    def rendering_type(self, value):
        if value not in ('static', 'dynamic'):
            raise ValueError('Invalid rendering_type %s' % value)
        self._rendering_type = value

    @property
    def user(self):
        return None

    @property
    def node(self):
        if self._node is None:
            raise ValueError('Node is None')

        return self._node

    @property
    def languages(self):
        return self._languages

    @property
    def lang(self):
        if self._language is None:
            raise ValueError('Language is None')

        return self._language

    @property
    def menus(self):
        return self._menus

    @property
    def translation(self):
        return self._translation

    def urlify(self, name):
        return urlify(name)

    def captcha(self, error=None):
        #public_key = '<KEY>'
        html = displayhtml('6LeNHcYSAAAAAKHbUX4bGAE-DE_0fR_J0nynW1OR', error)
        return literal(html)


class SettingProxy(object):

    def __init__(self, session):
        self.session = session
        self._settings = {}

    def __getattr__(self, attr_name):

        try:
            return self._settings[attr_name].value
        except KeyError:
            try:
                self._settings[attr_name] = Setting.get(self.session, attr_name)
{'fraction_non_alphanumeric': 0.09395973154362416, 'fraction_numerical': 0.0035722017752760336, 'mean_word_length': 2.3535390199637023, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2942635', 'n_tokens_mistral': 2546, 'n_tokens_neox': 2455, 'n_words': 765}