# Path: smartsnippets_inherit/models.py
# class InheritPageContent(CMSPlugin):
#     # from which page
#     from_page = models.ForeignKey(Page)
#     # from which section
#     from_placeholder = models.CharField(max_length=255, db_index=True)
# 
#     class Meta:
#         db_table = 'cmsplugin_inheritpagecontent'
# 
#     def get_placeholder(self):
#         try:
#             return self.from_page.placeholders.get(slot=self.from_placeholder)
#         except Placeholder.DoesNotExist:
#             return None
# 
# class OverwriteVariable(models.Model):
#     # which variable I overwrite
#     variable = models.ForeignKey(Variable)
#     # overwrite with this value
#     value = models.TextField()
#     # where I exist
#     plugin = models.ForeignKey(
#         InheritPageContent, related_name='overwrite_variables')
# 
#     def to_variable(self):
#         """
#         Utility to transform this to a plugin variable object. This is used
#             for rendering as a plugin variable with the overwritten value.
#         """
#         variable = self.variable
#         variable.value = self.value
#         return variable
# 
# Path: smartsnippets/models.py
# class SmartSnippetPointer(CMSPlugin):
#     snippet = models.ForeignKey(SmartSnippet, verbose_name='Custom Component')
#     cache_key_format = 'smartsnippet-pointer-{primary_key}'
# 
#     class Meta:
#         db_table = 'cmsplugin_smartsnippetpointer'
# 
#     def get_cache_key(self):
#         return self.cache_key_format.format(primary_key=self.pk)
# 
#     def _do_restore_sekizai_context(self, context, changes):
#         """Sekizai tags involve magic with the context object.
#         When need to restore the sekizai content to the context"""
#         cache_key = sekizai_cache_key()
#         sekizai_container = context.get(cache_key)
#         for key, values in changes.items():
#             sekizai_namespace = sekizai_container[key]
#             for value in values:
#                 sekizai_namespace.append(value)
# 
#     def fetch_cached(self, context):
#         cache_key = self.get_cache_key()
#         user = context['request'].user
#         if not user.is_staff and caching_enabled and cache.has_key(cache_key):
#             cached_value = cache.get(cache_key)
#             rendered_content = cached_value.get('content')
#             sekizai = cached_value.get('sekizai')
#             self._do_restore_sekizai_context(context, sekizai)
#             return rendered_content
# 
#     def set_and_get_cache(self, user, sekizai_diff, content):
#         if not user.is_staff and caching_enabled:
#             value = {'content': content, 'sekizai': sekizai_diff}
#             key = self.get_cache_key()
#             cache.set(key, value, snippet_caching_time)
#         return content
# 
#     def render_pointer(self, context, handle_errors=True):
#         vars_qs = self.variables.select_related('snippet_variable').all()
# 
#         def var_for_context(var):
#             default, overwrite = var.formatted_value, None
#             if allow_inheritance:
#                 overwrite = context.get(
#                     inherit_variable_pattern.format(identifier=var.pk))
#             name = var.snippet_variable.name
#             value = overwrite if overwrite is not None else default
#             return (name, value)
# 
#         variables = dict(var_for_context(var) for var in vars_qs)
#         context.update(variables)
#         sekizai_differ = sekizai_context_watcher(context)
#         try:
#             content = self.snippet.render(context)
#         except VariableDoesNotExist as exc:
#             logger.exception("Cannot render plugin %s!", self)
#             if handle_errors:
#                 content = render_to_string("smartsnippets/unrenderable_smartsnippet.html",
#                                            {'plugin_name': str(self)})
#             else:
#                 raise UnrenderableSmarSnippet(exc)
#         sekizai_diff = sekizai_differ.get_changes()
#         user = context.get('request').user
#         return self.set_and_get_cache(user, sekizai_diff, content)
# 
#     def render(self, context, handle_errors=True):
#         return self.fetch_cached(context) or self.render_pointer(context, handle_errors)
# 
#     def copy_relations(self, old_instance):
#         for variable in old_instance.variables.all():
#             variable.pk = None
#             variable.snippet = self
#             variable.save()
# 
#     def __unicode__(self):
#         return unicode(self.snippet)


from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse, HttpResponseBadRequest, QueryDict
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied
from django.template import RequestContext
from smartsnippets_inherit.models import InheritPageContent, OverwriteVariable
from smartsnippets.models import SmartSnippetPointer
from cms.utils.permissions import has_plugin_permission
    plugin = get_object_or_404(InheritPageContent, id=plugin_id)

    if not has_plugin_permission(request.user, plugin.plugin_type, "change"):
        raise PermissionDenied

    snippet_plugin_id = None
    if request.method == 'DELETE':
       snippet_plugin_id =  QueryDict(request.body).get('snippet_plugin')

    snippet_plugin_id = (snippet_plugin_id or
                         request.REQUEST.get('snippet_plugin'))
    if snippet_plugin_id is None:
        return HttpResponseBadRequest('Snippet plugin missing')

    snippet_plugin = get_object_or_404(
        SmartSnippetPointer, id=snippet_plugin_id
    )
    variables = snippet_plugin.variables.filter(
        snippet_variable__snippet=snippet_plugin.snippet
    )
    overwrite_variables = None

    if request.method == 'POST':
        variables = variables.select_related('snippet_variable')
        overwrite_variables = []
        for var in variables:
            new_value = request.POST.get("_%s_" % var.snippet_variable.name)
            if new_value is None:
                continue
            try:

# Path: smartsnippets_inherit/models.py
# class InheritPageContent(CMSPlugin):
#     # from which page
#     from_page = models.ForeignKey(Page)
#     # from which section
#     from_placeholder = models.CharField(max_length=255, db_index=True)
# 
#     class Meta:
#         db_table = 'cmsplugin_inheritpagecontent'
# 
#     def get_placeholder(self):
#         try:
#             return self.from_page.placeholders.get(slot=self.from_placeholder)
#         except Placeholder.DoesNotExist:
#             return None
# 
# class OverwriteVariable(models.Model):
#     # which variable I overwrite
#     variable = models.ForeignKey(Variable)
#     # overwrite with this value
#     value = models.TextField()
#     # where I exist
#     plugin = models.ForeignKey(
#         InheritPageContent, related_name='overwrite_variables')
# 
#     def to_variable(self):
#         """
#         Utility to transform this to a plugin variable object. This is used
#             for rendering as a plugin variable with the overwritten value.
#         """
#         variable = self.variable
#         variable.value = self.value
#         return variable
# 
# Path: smartsnippets/models.py
# class SmartSnippetPointer(CMSPlugin):
#     snippet = models.ForeignKey(SmartSnippet, verbose_name='Custom Component')
#     cache_key_format = 'smartsnippet-pointer-{primary_key}'
# 
#     class Meta:
#         db_table = 'cmsplugin_smartsnippetpointer'
# 
#     def get_cache_key(self):
#         return self.cache_key_format.format(primary_key=self.pk)
# 
#     def _do_restore_sekizai_context(self, context, changes):
#         """Sekizai tags involve magic with the context object.
#         When need to restore the sekizai content to the context"""
#         cache_key = sekizai_cache_key()
#         sekizai_container = context.get(cache_key)
#         for key, values in changes.items():
#             sekizai_namespace = sekizai_container[key]
#             for value in values:
#                 sekizai_namespace.append(value)
# 
#     def fetch_cached(self, context):
#         cache_key = self.get_cache_key()
#         user = context['request'].user
#         if not user.is_staff and caching_enabled and cache.has_key(cache_key):
#             cached_value = cache.get(cache_key)
#             rendered_content = cached_value.get('content')
#             sekizai = cached_value.get('sekizai')
#             self._do_restore_sekizai_context(context, sekizai)
#             return rendered_content
# 
#     def set_and_get_cache(self, user, sekizai_diff, content):
#         if not user.is_staff and caching_enabled:
#             value = {'content': content, 'sekizai': sekizai_diff}
#             key = self.get_cache_key()
#             cache.set(key, value, snippet_caching_time)
#         return content
# 
#     def render_pointer(self, context, handle_errors=True):
#         vars_qs = self.variables.select_related('snippet_variable').all()
# 
#         def var_for_context(var):
#             default, overwrite = var.formatted_value, None
#             if allow_inheritance:
#                 overwrite = context.get(
#                     inherit_variable_pattern.format(identifier=var.pk))
#             name = var.snippet_variable.name
#             value = overwrite if overwrite is not None else default
#             return (name, value)
# 
#         variables = dict(var_for_context(var) for var in vars_qs)
#         context.update(variables)
#         sekizai_differ = sekizai_context_watcher(context)
#         try:
#             content = self.snippet.render(context)
#         except VariableDoesNotExist as exc:
#             logger.exception("Cannot render plugin %s!", self)
#             if handle_errors:
#                 content = render_to_string("smartsnippets/unrenderable_smartsnippet.html",
#                                            {'plugin_name': str(self)})
#             else:
#                 raise UnrenderableSmarSnippet(exc)
#         sekizai_diff = sekizai_differ.get_changes()
#         user = context.get('request').user
#         return self.set_and_get_cache(user, sekizai_diff, content)
# 
#     def render(self, context, handle_errors=True):
#         return self.fetch_cached(context) or self.render_pointer(context, handle_errors)
# 
#     def copy_relations(self, old_instance):
#         for variable in old_instance.variables.all():
#             variable.pk = None
#             variable.snippet = self
#             variable.save()
# 
#     def __unicode__(self):
#         return unicode(self.snippet)


# Path: smartsnippets_inherit/views.py
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse, HttpResponseBadRequest, QueryDict
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied
from django.template import RequestContext
from smartsnippets_inherit.models import InheritPageContent, OverwriteVariable
from smartsnippets.models import SmartSnippetPointer
from cms.utils.permissions import has_plugin_permission

    plugin = get_object_or_404(InheritPageContent, id=plugin_id)

    if not has_plugin_permission(request.user, plugin.plugin_type, "change"):
        raise PermissionDenied

    snippet_plugin_id = None
    if request.method == 'DELETE':
       snippet_plugin_id =  QueryDict(request.body).get('snippet_plugin')

    snippet_plugin_id = (snippet_plugin_id or
                         request.REQUEST.get('snippet_plugin'))
    if snippet_plugin_id is None:
        return HttpResponseBadRequest('Snippet plugin missing')

    snippet_plugin = get_object_or_404(
        SmartSnippetPointer, id=snippet_plugin_id
    )
    variables = snippet_plugin.variables.filter(
        snippet_variable__snippet=snippet_plugin.snippet
    )
    overwrite_variables = None

    if request.method == 'POST':
        variables = variables.select_related('snippet_variable')
        overwrite_variables = []
        for var in variables:
            new_value = request.POST.get("_%s_" % var.snippet_variable.name)
            if new_value is None:
                continue
            try:

                existing_var = OverwriteVariable.objects.get(