2014-12-07 15:34:30 +01:00
|
|
|
# combo - content management system
|
|
|
|
# Copyright (C) 2014 Entr'ouvert
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
|
|
# under the terms of the GNU Affero General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Affero General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2018-02-12 15:58:27 +01:00
|
|
|
import collections
|
2017-06-24 11:10:05 +02:00
|
|
|
import copy
|
2015-08-24 14:32:06 +02:00
|
|
|
import feedparser
|
|
|
|
import hashlib
|
2015-02-18 14:15:31 +01:00
|
|
|
import json
|
2017-02-10 08:32:58 +01:00
|
|
|
import logging
|
2016-09-29 15:30:03 +02:00
|
|
|
import os
|
2018-01-18 09:11:31 +01:00
|
|
|
import re
|
2015-08-24 14:32:06 +02:00
|
|
|
import requests
|
2016-01-13 11:29:23 +01:00
|
|
|
import subprocess
|
2015-02-18 14:15:31 +01:00
|
|
|
|
2016-05-16 12:31:04 +02:00
|
|
|
from django.apps import apps
|
2014-12-13 11:25:53 +01:00
|
|
|
from django.conf import settings
|
2015-01-07 10:48:06 +01:00
|
|
|
from django.contrib.auth.models import Group
|
2015-08-24 14:32:06 +02:00
|
|
|
from django.core.cache import cache
|
2017-06-20 17:38:35 +02:00
|
|
|
from django.core.exceptions import ObjectDoesNotExist, ValidationError, PermissionDenied
|
2015-02-18 14:15:31 +01:00
|
|
|
from django.core import serializers
|
2018-04-02 12:07:34 +02:00
|
|
|
from django.db import models, transaction
|
2015-09-18 12:25:31 +02:00
|
|
|
from django.db.models.base import ModelBase
|
2018-06-02 15:08:57 +02:00
|
|
|
from django.db.models.signals import pre_save, post_save, post_delete
|
2014-12-16 15:17:15 +01:00
|
|
|
from django.db.models import Max
|
2018-07-12 21:32:59 +02:00
|
|
|
from django.dispatch import receiver
|
2014-12-13 11:25:53 +01:00
|
|
|
from django.forms import models as model_forms
|
2015-10-29 15:28:16 +01:00
|
|
|
from django import forms
|
2015-05-28 13:51:57 +02:00
|
|
|
from django import template
|
2018-07-25 14:28:05 +02:00
|
|
|
from django.utils import six
|
|
|
|
from django.utils.encoding import python_2_unicode_compatible, force_text, smart_bytes
|
2015-06-06 16:16:19 +02:00
|
|
|
from django.utils.html import strip_tags
|
2014-12-13 11:25:53 +01:00
|
|
|
from django.utils.safestring import mark_safe
|
2018-07-25 14:28:05 +02:00
|
|
|
from django.utils.six.moves.urllib import parse as urlparse
|
2016-05-16 20:28:48 +02:00
|
|
|
from django.utils.text import slugify
|
2014-12-07 15:34:30 +01:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2015-09-18 12:25:31 +02:00
|
|
|
from django.forms.widgets import MediaDefiningClass
|
2019-07-10 17:00:14 +02:00
|
|
|
from django.template import Context, engines, TemplateDoesNotExist, TemplateSyntaxError
|
2017-03-16 08:49:30 +01:00
|
|
|
from django.test.client import RequestFactory
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2019-07-01 21:19:18 +02:00
|
|
|
from .fields import RichTextField, TemplatableURLField
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2016-01-13 13:39:55 +01:00
|
|
|
from jsonfield import JSONField
|
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
from .library import register_cell_class, get_cell_classes, get_cell_class
|
|
|
|
|
2015-05-28 13:51:57 +02:00
|
|
|
from combo import utils
|
2015-08-24 14:32:06 +02:00
|
|
|
from combo.utils import NothingInCacheException
|
2015-05-28 13:51:57 +02:00
|
|
|
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2017-06-20 17:38:35 +02:00
|
|
|
class PostException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2015-01-13 10:41:46 +01:00
|
|
|
def element_is_visible(element, user=None):
|
|
|
|
if element.public:
|
2018-10-28 13:00:43 +01:00
|
|
|
if getattr(element, 'restricted_to_unlogged', None) is True:
|
2019-10-14 13:43:08 +02:00
|
|
|
return (user is None or user.is_anonymous)
|
2015-01-13 10:41:46 +01:00
|
|
|
return True
|
2019-10-14 13:43:08 +02:00
|
|
|
if user is None or user.is_anonymous:
|
2015-01-13 10:41:46 +01:00
|
|
|
return False
|
2015-10-26 21:47:06 +01:00
|
|
|
if user.is_superuser:
|
|
|
|
return True
|
2015-01-13 10:41:46 +01:00
|
|
|
page_groups = element.groups.all()
|
|
|
|
if not page_groups:
|
2018-10-28 13:00:43 +01:00
|
|
|
groups_ok = True
|
|
|
|
else:
|
|
|
|
groups_ok = len(set(page_groups).intersection(user.groups.all())) > 0
|
|
|
|
if getattr(element, 'restricted_to_unlogged', None) is True:
|
|
|
|
return not(groups_ok)
|
|
|
|
return groups_ok
|
2015-01-13 10:41:46 +01:00
|
|
|
|
|
|
|
|
2017-10-13 10:34:02 +02:00
|
|
|
class Placeholder(object):
|
2017-11-20 12:10:12 +01:00
|
|
|
def __init__(self, key, name=None, acquired=False, render=True, cell=None,
|
|
|
|
force_synchronous=False):
|
2017-10-13 10:34:02 +02:00
|
|
|
self.key = key
|
|
|
|
self.name = name
|
|
|
|
self.acquired = acquired
|
2017-10-14 22:08:21 +02:00
|
|
|
self.render = render
|
2017-11-02 17:04:51 +01:00
|
|
|
self.cell = cell
|
2017-11-20 12:10:12 +01:00
|
|
|
self.force_synchronous = force_synchronous
|
2017-11-02 17:04:51 +01:00
|
|
|
|
|
|
|
def get_name(self):
|
|
|
|
if self.cell:
|
2018-06-14 11:05:29 +02:00
|
|
|
return '%s / %s' % (self.cell.get_label(), self.name)
|
2017-11-02 17:04:51 +01:00
|
|
|
return self.name
|
2017-10-13 10:34:02 +02:00
|
|
|
|
|
|
|
|
2016-03-06 16:00:53 +01:00
|
|
|
class PageManager(models.Manager):
|
2018-04-01 15:23:01 +02:00
|
|
|
snapshots = False
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.snapshots = kwargs.pop('snapshots', False)
|
|
|
|
super(PageManager, self).__init__(*args, **kwargs)
|
|
|
|
|
2016-03-06 16:00:53 +01:00
|
|
|
def get_by_natural_key(self, path):
|
|
|
|
parts = [x for x in path.strip('/').split('/') if x] or ['index']
|
|
|
|
return self.get(slug=parts[-1])
|
|
|
|
|
2018-04-01 15:23:01 +02:00
|
|
|
def get_queryset(self):
|
|
|
|
queryset = super(PageManager, self).get_queryset()
|
|
|
|
if self.snapshots:
|
|
|
|
return queryset.filter(snapshot__isnull=False)
|
|
|
|
else:
|
|
|
|
return queryset.filter(snapshot__isnull=True)
|
|
|
|
|
2016-03-06 16:00:53 +01:00
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
@python_2_unicode_compatible
|
2014-12-07 15:34:30 +01:00
|
|
|
class Page(models.Model):
|
2016-03-06 16:00:53 +01:00
|
|
|
objects = PageManager()
|
2018-04-01 15:23:01 +02:00
|
|
|
snapshots = PageManager(snapshots=True)
|
2016-03-06 16:00:53 +01:00
|
|
|
|
2017-03-13 16:43:39 +01:00
|
|
|
title = models.CharField(_('Title'), max_length=150)
|
2015-01-17 19:15:16 +01:00
|
|
|
slug = models.SlugField(_('Slug'))
|
2018-08-08 22:18:36 +02:00
|
|
|
sub_slug = models.CharField(_('Sub Slug'), max_length=150, blank=True,
|
|
|
|
help_text=_('Regular expression to create variadic subpages. '
|
|
|
|
'Matching named groups are exposed as context variables.'
|
|
|
|
))
|
2018-04-19 10:08:51 +02:00
|
|
|
description = models.TextField(_('Description'), blank=True)
|
2015-01-17 19:15:16 +01:00
|
|
|
template_name = models.CharField(_('Template'), max_length=50)
|
2019-10-14 13:33:00 +02:00
|
|
|
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
|
2014-12-16 15:17:15 +01:00
|
|
|
order = models.PositiveIntegerField()
|
2015-01-12 09:42:57 +01:00
|
|
|
exclude_from_navigation = models.BooleanField(_('Exclude from navigation'), default=False)
|
2015-10-28 10:48:01 +01:00
|
|
|
redirect_url = models.CharField(_('Redirect URL'), max_length=200, blank=True)
|
2014-12-16 15:17:15 +01:00
|
|
|
|
2015-01-07 10:48:06 +01:00
|
|
|
public = models.BooleanField(_('Public'), default=True)
|
2015-01-17 19:15:16 +01:00
|
|
|
groups = models.ManyToManyField(Group, verbose_name=_('Groups'), blank=True)
|
2017-02-14 21:08:46 +01:00
|
|
|
last_update_timestamp = models.DateTimeField(auto_now=True)
|
2015-01-07 10:48:06 +01:00
|
|
|
|
2017-05-15 14:10:06 +02:00
|
|
|
picture = models.ImageField(_('Picture'), upload_to='page-pictures/', null=True)
|
|
|
|
|
2018-04-01 15:23:01 +02:00
|
|
|
# mark temporarily restored snapshots, it is required to save objects
|
|
|
|
# (pages and cells) for real for viewing past snapshots as many cells are
|
|
|
|
# asynchronously loaded and must refer to a real Page object.
|
|
|
|
snapshot = models.ForeignKey('PageSnapshot', on_delete=models.CASCADE, null=True,
|
|
|
|
related_name='temporary_page')
|
|
|
|
|
2018-06-02 15:08:57 +02:00
|
|
|
# keep a cached list of cell types that are used in the pages.
|
|
|
|
related_cells = JSONField(blank=True)
|
|
|
|
|
2014-12-16 15:17:15 +01:00
|
|
|
_level = None
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ['order']
|
2014-12-13 13:19:34 +01:00
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
def __str__(self):
|
2014-12-13 13:19:34 +01:00
|
|
|
return self.title
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2016-03-06 16:00:53 +01:00
|
|
|
def natural_key(self):
|
|
|
|
return (self.get_online_url().strip('/'), )
|
|
|
|
|
2019-06-25 17:41:10 +02:00
|
|
|
def picture_extension(self):
|
|
|
|
if not self.picture:
|
|
|
|
return None
|
|
|
|
return os.path.splitext(self.picture.name)[-1]
|
|
|
|
|
2014-12-16 15:17:15 +01:00
|
|
|
def save(self, *args, **kwargs):
|
2018-06-02 15:08:57 +02:00
|
|
|
if not self.id:
|
|
|
|
self.related_cells = {'cell_types': []}
|
2014-12-16 15:17:15 +01:00
|
|
|
if not self.order:
|
|
|
|
max_order = Page.objects.all().aggregate(Max('order')).get('order__max') or 0
|
|
|
|
self.order = max_order + 1
|
2016-05-16 20:28:48 +02:00
|
|
|
if not self.slug:
|
2019-11-19 08:27:46 +01:00
|
|
|
if not Page.objects.exists():
|
2016-05-16 20:28:48 +02:00
|
|
|
slug = 'index'
|
|
|
|
else:
|
|
|
|
base_slug = slugify(self.title)[:40]
|
2017-05-31 11:03:36 +02:00
|
|
|
slug = base_slug.strip('-')
|
2016-05-16 20:28:48 +02:00
|
|
|
i = 1
|
2019-11-19 08:27:46 +01:00
|
|
|
while Page.objects.filter(slug=slug, parent_id=self.parent_id).exists():
|
2016-05-16 20:28:48 +02:00
|
|
|
i += 1
|
|
|
|
slug = '%s-%s' % (base_slug, i)
|
|
|
|
self.slug = slug
|
|
|
|
if not self.template_name:
|
|
|
|
self.template_name = settings.COMBO_DEFAULT_PUBLIC_TEMPLATE
|
2014-12-16 15:17:15 +01:00
|
|
|
return super(Page, self).save(*args, **kwargs)
|
|
|
|
|
2015-05-11 09:13:45 +02:00
|
|
|
def get_parents_and_self(self):
|
|
|
|
pages = [self]
|
2014-12-13 13:30:04 +01:00
|
|
|
page = self
|
|
|
|
while page.parent_id:
|
2018-06-02 15:29:16 +02:00
|
|
|
page = page._parent if hasattr(page, '_parent') else page.parent
|
2015-05-11 09:13:45 +02:00
|
|
|
pages.append(page)
|
2016-02-20 14:47:42 +01:00
|
|
|
return list(reversed(pages))
|
2015-05-11 09:13:45 +02:00
|
|
|
|
|
|
|
def get_online_url(self):
|
|
|
|
parts = [x.slug for x in self.get_parents_and_self()]
|
2015-10-06 10:28:54 +02:00
|
|
|
if parts[0] == 'index':
|
|
|
|
parts = parts[1:]
|
|
|
|
if not parts:
|
2015-03-17 16:53:22 +01:00
|
|
|
return '/'
|
2015-10-06 10:28:54 +02:00
|
|
|
return '/' + '/'.join(parts) + '/'
|
2014-12-13 13:30:04 +01:00
|
|
|
|
2015-01-02 20:56:09 +01:00
|
|
|
def get_page_of_level(self, level):
|
|
|
|
'''Return page of given level in the page hierarchy.'''
|
|
|
|
parts = [self]
|
|
|
|
page = self
|
|
|
|
while page.parent_id:
|
2018-06-02 15:29:16 +02:00
|
|
|
page = page._parent if hasattr(page, '_parent') else page.parent
|
2015-01-02 20:56:09 +01:00
|
|
|
parts.append(page)
|
|
|
|
parts.reverse()
|
|
|
|
try:
|
|
|
|
return parts[level]
|
|
|
|
except IndexError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def get_siblings(self):
|
2018-06-02 15:29:16 +02:00
|
|
|
if hasattr(self, '_parent'):
|
|
|
|
if self._parent:
|
|
|
|
return self._parent._children
|
|
|
|
return Page.objects.filter(parent_id=self.parent_id)
|
2015-01-02 20:56:09 +01:00
|
|
|
|
2015-01-25 17:04:18 +01:00
|
|
|
def get_children(self):
|
2018-06-02 15:29:16 +02:00
|
|
|
if hasattr(self, '_children'):
|
|
|
|
return self._children
|
2015-01-25 17:04:18 +01:00
|
|
|
return Page.objects.filter(parent_id=self.id)
|
|
|
|
|
2014-12-13 16:43:29 +01:00
|
|
|
def has_children(self):
|
2018-06-02 15:29:16 +02:00
|
|
|
if hasattr(self, '_children'):
|
|
|
|
return bool(self._children)
|
2014-12-13 16:43:29 +01:00
|
|
|
return Page.objects.filter(parent_id=self.id).exists()
|
|
|
|
|
2015-06-06 11:28:46 +02:00
|
|
|
def get_template_display_name(self):
|
2018-12-30 13:39:23 +01:00
|
|
|
try:
|
|
|
|
return settings.COMBO_PUBLIC_TEMPLATES[self.template_name]['name']
|
|
|
|
except KeyError:
|
|
|
|
return _('Unknown (%s)') % self.template_name
|
2015-06-06 11:28:46 +02:00
|
|
|
|
2018-04-14 10:51:20 +02:00
|
|
|
def missing_template(self):
|
2018-12-30 13:39:23 +01:00
|
|
|
template_name = settings.COMBO_PUBLIC_TEMPLATES.get(self.template_name, {}).get('template')
|
|
|
|
if not template_name:
|
|
|
|
return True
|
2018-04-14 10:51:20 +02:00
|
|
|
try:
|
|
|
|
template.loader.select_template([template_name])
|
|
|
|
except TemplateDoesNotExist:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2017-11-09 12:50:37 +01:00
|
|
|
def get_placeholders(self, request, traverse_cells=False, template_name=None):
|
2017-10-13 10:34:02 +02:00
|
|
|
placeholders = []
|
|
|
|
|
2018-12-30 13:39:23 +01:00
|
|
|
page_template = settings.COMBO_PUBLIC_TEMPLATES.get(template_name or self.template_name, {})
|
2017-10-13 10:34:02 +02:00
|
|
|
if page_template.get('placeholders'):
|
|
|
|
# manual declaration
|
|
|
|
for key, options in page_template['placeholders'].items():
|
|
|
|
placeholders.append(Placeholder(key=key, **options))
|
|
|
|
return placeholders
|
|
|
|
|
2018-12-30 13:39:23 +01:00
|
|
|
template_names = []
|
|
|
|
if page_template.get('template'):
|
|
|
|
template_names.append(page_template['template'])
|
|
|
|
template_names.append('combo/page_template.html')
|
|
|
|
tmpl = template.loader.select_template(template_names)
|
2017-11-09 12:50:37 +01:00
|
|
|
request = RequestFactory(SERVER_NAME=request.get_host()).get(self.get_online_url())
|
2017-10-13 10:34:02 +02:00
|
|
|
request.user = None
|
2018-01-01 12:35:01 +01:00
|
|
|
context = {
|
2017-10-13 10:34:02 +02:00
|
|
|
'page': self,
|
|
|
|
'request': request,
|
2017-10-14 22:08:21 +02:00
|
|
|
'synchronous': True,
|
2017-10-13 10:34:02 +02:00
|
|
|
'placeholder_search_mode': True,
|
|
|
|
'placeholders': placeholders,
|
2017-10-14 22:08:21 +02:00
|
|
|
'traverse_cells': traverse_cells,
|
2018-01-01 12:35:01 +01:00
|
|
|
}
|
|
|
|
tmpl.render(context, request)
|
2017-10-13 10:34:02 +02:00
|
|
|
return placeholders
|
|
|
|
|
2019-10-23 17:37:10 +02:00
|
|
|
def get_next_page(self, user=None, check_visibility=True):
|
2016-09-14 14:46:56 +02:00
|
|
|
pages = Page.get_as_reordered_flat_hierarchy(Page.objects.all())
|
|
|
|
this_page = [x for x in pages if x.id == self.id][0]
|
|
|
|
pages = pages[pages.index(this_page)+1:]
|
|
|
|
for page in pages:
|
2019-10-23 17:37:10 +02:00
|
|
|
if not check_visibility or page.is_visible(user):
|
2016-09-14 14:46:56 +02:00
|
|
|
return page
|
|
|
|
return None
|
|
|
|
|
2019-10-23 17:37:10 +02:00
|
|
|
def get_previous_page(self, user=None, check_visibility=True):
|
2016-09-14 14:46:56 +02:00
|
|
|
pages = Page.get_as_reordered_flat_hierarchy(Page.objects.all())
|
|
|
|
pages.reverse()
|
|
|
|
this_page = [x for x in pages if x.id == self.id][0]
|
|
|
|
pages = pages[pages.index(this_page)+1:]
|
|
|
|
for page in pages:
|
2019-10-23 17:37:10 +02:00
|
|
|
if not check_visibility or page.is_visible(user):
|
2016-09-14 14:46:56 +02:00
|
|
|
return page
|
|
|
|
return None
|
|
|
|
|
2014-12-16 15:17:15 +01:00
|
|
|
@classmethod
|
|
|
|
def get_as_reordered_flat_hierarchy(cls, object_list):
|
|
|
|
reordered = []
|
2018-02-12 15:58:27 +01:00
|
|
|
parenting = collections.defaultdict(list)
|
|
|
|
for page in object_list:
|
|
|
|
parenting[page.parent_id].append(page)
|
2014-12-16 15:17:15 +01:00
|
|
|
def fill_list(object_sublist, level=0, parent=None):
|
|
|
|
for page in object_sublist:
|
|
|
|
if page.parent == parent:
|
|
|
|
page.level = level
|
|
|
|
reordered.append(page)
|
2018-02-12 15:58:27 +01:00
|
|
|
if page.id in parenting:
|
|
|
|
fill_list(object_sublist, level=level+1, parent=page)
|
2014-12-16 15:17:15 +01:00
|
|
|
fill_list(object_list)
|
|
|
|
return reordered
|
|
|
|
|
2018-06-02 15:29:16 +02:00
|
|
|
@staticmethod
|
|
|
|
@utils.cache_during_request
|
|
|
|
def get_with_hierarchy_attributes():
|
|
|
|
pages = Page.objects.all()
|
|
|
|
pages_by_id = {}
|
|
|
|
for page in pages:
|
|
|
|
pages_by_id[page.id] = page
|
|
|
|
page._parent = None
|
|
|
|
page._children = []
|
|
|
|
for page in pages:
|
|
|
|
page._parent = pages_by_id[page.parent_id] if page.parent_id else None
|
|
|
|
if page._parent:
|
|
|
|
page._parent._children.append(page)
|
|
|
|
for page in pages:
|
|
|
|
page._children.sort(key=lambda x: x.order)
|
|
|
|
return pages_by_id
|
|
|
|
|
2015-01-07 10:48:06 +01:00
|
|
|
def visibility(self):
|
|
|
|
if self.public:
|
|
|
|
return _('Public')
|
2019-10-22 09:19:06 +02:00
|
|
|
groups = self.groups.all()
|
|
|
|
groupnames = ', '.join([x.name for x in groups]) if groups else _('logged users')
|
|
|
|
return _('Private (%s)') % groupnames
|
2015-01-07 10:48:06 +01:00
|
|
|
|
|
|
|
def is_visible(self, user=None):
|
2015-01-13 10:41:46 +01:00
|
|
|
return element_is_visible(self, user=user)
|
|
|
|
|
2015-06-06 16:16:19 +02:00
|
|
|
def get_cells(self):
|
2018-06-02 15:08:57 +02:00
|
|
|
return CellBase.get_cells(page=self)
|
|
|
|
|
|
|
|
def build_cell_cache(self):
|
|
|
|
cells = CellBase.get_cells(page=self, skip_cell_cache=True)
|
|
|
|
cell_types = set()
|
|
|
|
for cell in cells:
|
|
|
|
cell_types.add(cell.get_cell_type_str())
|
|
|
|
if cell_types != set(self.related_cells.get('cell_types', [])):
|
|
|
|
self.related_cells['cell_types'] = list(cell_types)
|
|
|
|
self.save()
|
2015-06-06 16:16:19 +02:00
|
|
|
|
2015-02-18 14:15:31 +01:00
|
|
|
def get_serialized_page(self):
|
2017-10-12 11:18:13 +02:00
|
|
|
cells = [x for x in self.get_cells() if x.placeholder and not x.placeholder.startswith('_')]
|
2016-03-06 16:00:53 +01:00
|
|
|
serialized_page = json.loads(serializers.serialize('json', [self],
|
|
|
|
use_natural_foreign_keys=True, use_natural_primary_keys=True))[0]
|
2015-02-18 14:15:31 +01:00
|
|
|
del serialized_page['model']
|
2018-04-01 15:23:01 +02:00
|
|
|
if 'snapshot' in serialized_page:
|
|
|
|
del serialized_page['snapshot']
|
2018-06-02 15:08:57 +02:00
|
|
|
if 'related_cells' in serialized_page['fields']:
|
|
|
|
del serialized_page['fields']['related_cells']
|
2016-03-06 16:00:53 +01:00
|
|
|
serialized_page['cells'] = json.loads(serializers.serialize('json',
|
|
|
|
cells, use_natural_foreign_keys=True, use_natural_primary_keys=True))
|
2015-05-25 12:59:41 +02:00
|
|
|
for index, cell in enumerate(cells):
|
|
|
|
serialized_page['cells'][index].update(cell.export_subobjects())
|
2018-03-04 15:48:38 +01:00
|
|
|
serialized_page['fields']['groups'] = [x[0] for x in serialized_page['fields']['groups']]
|
2015-02-18 14:15:31 +01:00
|
|
|
for cell in serialized_page['cells']:
|
|
|
|
del cell['pk']
|
|
|
|
del cell['fields']['page']
|
2018-03-04 15:48:38 +01:00
|
|
|
cell['fields']['groups'] = [x[0] for x in cell['fields']['groups']]
|
2018-07-25 14:28:05 +02:00
|
|
|
for key in list(cell['fields'].keys()):
|
2017-01-03 18:18:55 +01:00
|
|
|
if key.startswith('cached_'):
|
|
|
|
del cell['fields'][key]
|
2015-02-18 14:15:31 +01:00
|
|
|
return serialized_page
|
|
|
|
|
2015-02-18 15:48:44 +01:00
|
|
|
@classmethod
|
2018-04-01 15:23:01 +02:00
|
|
|
def load_serialized_page(cls, json_page, snapshot=None):
|
2015-02-18 15:48:44 +01:00
|
|
|
json_page['model'] = 'data.page'
|
2018-07-25 14:28:05 +02:00
|
|
|
json_page['fields']['groups'] = [[x] for x in json_page['fields']['groups'] if isinstance(x, six.string_types)]
|
2018-04-01 15:23:01 +02:00
|
|
|
page, created = Page.objects.get_or_create(slug=json_page['fields']['slug'], snapshot=snapshot)
|
2015-02-18 15:48:44 +01:00
|
|
|
json_page['pk'] = page.id
|
|
|
|
page = [x for x in serializers.deserialize('json', json.dumps([json_page]))][0]
|
2018-04-01 15:23:01 +02:00
|
|
|
page.object.snapshot = snapshot
|
2015-02-18 15:48:44 +01:00
|
|
|
page.save()
|
|
|
|
for cell in json_page.get('cells'):
|
2018-07-25 14:28:05 +02:00
|
|
|
cell['fields']['groups'] = [[x] for x in cell['fields']['groups'] if isinstance(x, six.string_types)]
|
2018-04-01 15:23:01 +02:00
|
|
|
if snapshot:
|
|
|
|
cell['fields']['page'] = page.object.id
|
|
|
|
else:
|
|
|
|
cell['fields']['page'] = page.object.natural_key()
|
2015-02-18 15:48:44 +01:00
|
|
|
|
2015-05-25 12:59:41 +02:00
|
|
|
|
2015-02-18 15:48:44 +01:00
|
|
|
# if there were cells, remove them
|
|
|
|
for cell in CellBase.get_cells(page_id=page.object.id):
|
|
|
|
cell.delete()
|
2018-04-01 15:23:01 +02:00
|
|
|
return page.object # get page out of deserialization object
|
2015-02-18 15:48:44 +01:00
|
|
|
|
2016-03-06 16:00:53 +01:00
|
|
|
@classmethod
|
|
|
|
def load_serialized_cells(cls, cells):
|
2015-02-18 15:48:44 +01:00
|
|
|
# load new cells
|
2015-05-25 12:59:41 +02:00
|
|
|
for index, cell in enumerate(serializers.deserialize('json', json.dumps(cells))):
|
2015-02-18 15:48:44 +01:00
|
|
|
cell.save()
|
2018-05-14 17:17:26 +02:00
|
|
|
# will populate cached_* attributes
|
|
|
|
cell.object.save()
|
2015-05-25 12:59:41 +02:00
|
|
|
cell.object.import_subobjects(cells[index])
|
2015-02-18 15:48:44 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def load_serialized_pages(cls, json_site):
|
2016-03-06 16:00:53 +01:00
|
|
|
cells = []
|
2015-02-18 15:48:44 +01:00
|
|
|
for json_page in json_site:
|
|
|
|
cls.load_serialized_page(json_page)
|
2016-03-06 16:00:53 +01:00
|
|
|
cells.extend(json_page.get('cells'))
|
|
|
|
cls.load_serialized_cells(cells)
|
2015-02-18 15:48:44 +01:00
|
|
|
|
|
|
|
# 2nd pass to set parents
|
|
|
|
for json_page in json_site:
|
|
|
|
if json_page.get('parent_slug'):
|
|
|
|
page = Page.objects.get(slug=json_page['fields']['slug'])
|
|
|
|
page.parent = Page.objects.get(slug=json_page.get('parent_slug'))
|
|
|
|
page.save()
|
|
|
|
|
2016-10-11 10:36:33 +02:00
|
|
|
@classmethod
|
|
|
|
def export_all_for_json(cls):
|
|
|
|
ordered_pages = Page.get_as_reordered_flat_hierarchy(cls.objects.all())
|
|
|
|
return [x.get_serialized_page() for x in ordered_pages]
|
|
|
|
|
2018-12-11 20:43:08 +01:00
|
|
|
def get_redirect_url(self, context=None):
|
|
|
|
return utils.get_templated_url(self.redirect_url, context=context)
|
2017-02-03 15:12:17 +01:00
|
|
|
|
2017-02-14 21:23:58 +01:00
|
|
|
def get_last_update_time(self):
|
|
|
|
cells = CellBase.get_cells(page_id=self.id)
|
|
|
|
return max([self.last_update_timestamp] + [x.last_update_timestamp for x in cells])
|
|
|
|
|
2019-10-22 14:58:02 +02:00
|
|
|
def duplicate(self):
|
|
|
|
# clone current page
|
|
|
|
new_page = copy.deepcopy(self)
|
|
|
|
new_page.pk = None
|
|
|
|
# set title
|
|
|
|
new_page.title = _('Copy of %s') % self.title
|
2019-11-19 08:27:46 +01:00
|
|
|
# reset slug
|
|
|
|
new_page.slug = None
|
2019-10-22 14:58:02 +02:00
|
|
|
# reset snapshot
|
|
|
|
new_page.snapshot = None
|
|
|
|
# set order
|
|
|
|
new_page.order = self.order + 1
|
|
|
|
# store new page
|
|
|
|
new_page.save()
|
|
|
|
|
|
|
|
# set groups
|
|
|
|
new_page.groups.set(self.groups.all())
|
|
|
|
|
|
|
|
for cell in self.get_cells():
|
2020-01-07 15:27:44 +01:00
|
|
|
if cell.placeholder and cell.placeholder.startswith('_'):
|
|
|
|
continue
|
2019-10-22 14:58:02 +02:00
|
|
|
cell.duplicate(page_target=new_page)
|
|
|
|
|
|
|
|
return new_page
|
|
|
|
|
2015-02-18 15:48:44 +01:00
|
|
|
|
2018-04-01 15:23:01 +02:00
|
|
|
class PageSnapshot(models.Model):
|
|
|
|
page = models.ForeignKey(Page, on_delete=models.SET_NULL, null=True)
|
|
|
|
timestamp = models.DateTimeField(auto_now_add=True)
|
2019-10-14 13:33:00 +02:00
|
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
|
2018-04-01 15:23:01 +02:00
|
|
|
comment = models.TextField(blank=True, null=True)
|
|
|
|
serialization = JSONField(blank=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ('-timestamp',)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def take(cls, page, request=None, comment=None, deletion=False):
|
|
|
|
snapshot = cls(page=page, comment=comment)
|
2019-10-14 13:43:08 +02:00
|
|
|
if request and not request.user.is_anonymous:
|
2018-04-01 15:23:01 +02:00
|
|
|
snapshot.user = request.user
|
|
|
|
if not deletion:
|
|
|
|
snapshot.serialization = page.get_serialized_page()
|
|
|
|
else:
|
|
|
|
snapshot.serialization = {}
|
|
|
|
snapshot.comment = comment or _('deletion')
|
|
|
|
snapshot.save()
|
|
|
|
|
|
|
|
def get_page(self):
|
|
|
|
try:
|
|
|
|
# try reusing existing page
|
|
|
|
return Page.snapshots.get(snapshot=self)
|
|
|
|
except Page.DoesNotExist:
|
|
|
|
page = Page.load_serialized_page(self.serialization, snapshot=self)
|
|
|
|
page.load_serialized_cells(self.serialization['cells'])
|
|
|
|
return page
|
|
|
|
|
2018-04-02 12:07:34 +02:00
|
|
|
def restore(self):
|
|
|
|
with transaction.atomic():
|
|
|
|
page = Page.load_serialized_page(self.serialization)
|
|
|
|
page.load_serialized_cells(self.serialization['cells'])
|
|
|
|
return page
|
|
|
|
|
2018-04-01 15:23:01 +02:00
|
|
|
|
2018-07-12 20:45:37 +02:00
|
|
|
class Redirect(models.Model):
|
|
|
|
old_url = models.CharField(max_length=512)
|
2019-10-14 13:33:00 +02:00
|
|
|
page = models.ForeignKey(Page, on_delete=models.CASCADE)
|
2018-07-12 20:45:37 +02:00
|
|
|
creation_timestamp = models.DateTimeField(auto_now_add=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ('creation_timestamp',)
|
|
|
|
|
|
|
|
|
2015-09-18 12:25:31 +02:00
|
|
|
class CellMeta(MediaDefiningClass, ModelBase):
|
|
|
|
pass
|
|
|
|
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class CellBase(six.with_metaclass(CellMeta, models.Model)):
|
2015-09-18 12:25:31 +02:00
|
|
|
|
2019-10-14 13:33:00 +02:00
|
|
|
page = models.ForeignKey(Page, on_delete=models.CASCADE)
|
2014-12-08 10:20:23 +01:00
|
|
|
placeholder = models.CharField(max_length=20)
|
2014-12-07 15:34:30 +01:00
|
|
|
order = models.PositiveIntegerField()
|
2015-02-17 15:00:09 +01:00
|
|
|
slug = models.SlugField(_('Slug'), blank=True)
|
2016-07-13 17:47:15 +02:00
|
|
|
extra_css_class = models.CharField(_('Extra classes for CSS styling'), max_length=100, blank=True)
|
2014-12-07 15:34:30 +01:00
|
|
|
|
2015-01-13 10:41:46 +01:00
|
|
|
public = models.BooleanField(_('Public'), default=True)
|
2018-10-28 13:00:43 +01:00
|
|
|
# restricted_to_unlogged is actually an invert switch, it is used for mark
|
|
|
|
# a cell as only visibile to unlogged users but also, when groups are set,
|
|
|
|
# to mark the cell as visible to all but those groups.
|
2015-10-29 15:39:31 +01:00
|
|
|
restricted_to_unlogged = models.BooleanField(
|
|
|
|
_('Restrict to unlogged users'), default=False)
|
2015-01-17 19:15:16 +01:00
|
|
|
groups = models.ManyToManyField(Group, verbose_name=_('Groups'), blank=True)
|
2017-02-14 21:08:46 +01:00
|
|
|
last_update_timestamp = models.DateTimeField(auto_now=True)
|
2015-01-13 10:41:46 +01:00
|
|
|
|
2014-12-13 11:25:53 +01:00
|
|
|
default_form_class = None
|
2019-07-01 21:19:18 +02:00
|
|
|
manager_form_factory_kwargs = {}
|
|
|
|
manager_form_template = 'combo/cell_form.html'
|
|
|
|
|
2014-12-30 13:10:48 +01:00
|
|
|
visible = True
|
2015-05-11 09:13:45 +02:00
|
|
|
user_dependant = False
|
2015-05-28 13:51:57 +02:00
|
|
|
template_name = None
|
2014-12-13 11:25:53 +01:00
|
|
|
|
2016-05-28 19:25:19 +02:00
|
|
|
# get_badge(self, context); set to None so cell types can be skipped easily
|
|
|
|
get_badge = None
|
|
|
|
|
2018-06-25 20:23:59 +02:00
|
|
|
# get_asset_slots(self); set to None so cell types can be skipped easily
|
|
|
|
get_asset_slots = None
|
|
|
|
|
2018-02-22 14:25:56 +01:00
|
|
|
# message displayed when the cell is loaded asynchronously
|
|
|
|
loading_message = _('Loading...')
|
|
|
|
|
2018-01-09 09:58:02 +01:00
|
|
|
# modify_global_context(self, context, request=None)
|
|
|
|
# Apply changes to the template context that must visible to all cells in the page
|
|
|
|
modify_global_context = None
|
|
|
|
|
2018-12-17 23:30:49 +01:00
|
|
|
# if set, automatically refresh cell every n seconds
|
|
|
|
ajax_refresh = None
|
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
2018-07-25 14:28:05 +02:00
|
|
|
def __str__(self):
|
|
|
|
label = self.get_verbose_name()
|
2015-01-17 17:06:07 +01:00
|
|
|
additional_label = self.get_additional_label()
|
|
|
|
if label and additional_label:
|
2018-07-25 14:28:05 +02:00
|
|
|
return u'%s (%s)' % (label, re.sub(r'\r?\n', u' ', force_text(additional_label)))
|
2015-01-17 17:06:07 +01:00
|
|
|
else:
|
2018-07-25 14:28:05 +02:00
|
|
|
return force_text(label)
|
2015-01-17 17:06:07 +01:00
|
|
|
|
2014-12-08 17:06:57 +01:00
|
|
|
@classmethod
|
|
|
|
def get_verbose_name(cls):
|
|
|
|
return cls._meta.verbose_name
|
|
|
|
|
2015-01-17 17:06:07 +01:00
|
|
|
def get_additional_label(self):
|
|
|
|
return ''
|
|
|
|
|
2018-12-19 10:37:53 +01:00
|
|
|
@property
|
|
|
|
def class_name(self):
|
|
|
|
return self.__class__.__name__.lower()
|
|
|
|
|
2014-12-30 14:23:36 +01:00
|
|
|
@property
|
2016-07-13 17:47:15 +02:00
|
|
|
def css_class_names(self):
|
2018-12-19 10:37:53 +01:00
|
|
|
return self.class_name + ' ' + self.extra_css_class
|
2014-12-30 14:23:36 +01:00
|
|
|
|
2014-12-07 17:36:21 +01:00
|
|
|
@classmethod
|
2018-01-18 08:46:40 +01:00
|
|
|
def get_cell_classes(cls, class_filter=lambda x: True):
|
2014-12-24 07:34:52 +01:00
|
|
|
for klass in get_cell_classes():
|
2018-01-18 08:46:40 +01:00
|
|
|
if not class_filter(klass):
|
|
|
|
continue
|
2015-02-05 16:31:16 +01:00
|
|
|
if not klass.is_enabled():
|
|
|
|
continue
|
2014-12-30 13:10:48 +01:00
|
|
|
if klass.visible is False:
|
|
|
|
continue
|
2018-01-18 08:46:40 +01:00
|
|
|
yield klass
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_all_cell_types(cls, *args, **kwargs):
|
|
|
|
cell_types = []
|
|
|
|
for klass in cls.get_cell_classes(*args, **kwargs):
|
2016-02-07 00:25:34 +01:00
|
|
|
cell_types.extend(klass.get_cell_types())
|
|
|
|
return cell_types
|
2014-12-07 17:36:21 +01:00
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
@classmethod
|
2018-06-02 15:08:57 +02:00
|
|
|
def get_cells(cls, cell_filter=None, skip_cell_cache=False, **kwargs):
|
2014-12-24 07:34:52 +01:00
|
|
|
"""Returns the list of cells of various classes matching **kwargs"""
|
|
|
|
cells = []
|
2018-06-02 15:08:57 +02:00
|
|
|
pages = []
|
|
|
|
if 'page' in kwargs:
|
|
|
|
pages = [kwargs['page']]
|
|
|
|
elif 'page__in' in kwargs:
|
|
|
|
pages = kwargs['page__in']
|
2018-11-15 11:13:49 +01:00
|
|
|
else:
|
|
|
|
# if there are not explicit page, limit to non-snapshot pages
|
|
|
|
kwargs['page__snapshot__isnull'] = True
|
2018-06-02 15:08:57 +02:00
|
|
|
cell_classes = get_cell_classes()
|
|
|
|
if pages and not skip_cell_cache:
|
|
|
|
# if there's a request for some specific pages, limit cell types
|
|
|
|
# to those that are actually in use in those pages.
|
|
|
|
cell_types = set()
|
|
|
|
for page in pages:
|
|
|
|
if page.related_cells and 'cell_types' in page.related_cells:
|
|
|
|
cell_types |= set(page.related_cells['cell_types'])
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
cell_classes = [get_cell_class(x) for x in cell_types]
|
|
|
|
for klass in cell_classes:
|
2019-04-07 19:45:09 +02:00
|
|
|
if klass is None:
|
|
|
|
continue
|
2016-05-28 19:25:19 +02:00
|
|
|
if cell_filter and not cell_filter(klass):
|
|
|
|
continue
|
2014-12-24 07:34:52 +01:00
|
|
|
cells.extend(klass.objects.filter(**kwargs))
|
2018-07-25 14:28:05 +02:00
|
|
|
cells.sort(key=lambda x: x.order)
|
2014-12-24 07:34:52 +01:00
|
|
|
return cells
|
|
|
|
|
|
|
|
def get_reference(self):
|
|
|
|
"Returns a string that can serve as a unique reference to a cell"""
|
2016-02-07 00:25:34 +01:00
|
|
|
return str('%s-%s' % (self.get_cell_type_str(), self.id))
|
2014-12-24 07:34:52 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_cell(cls, reference, **kwargs):
|
|
|
|
"""Returns the cell matching reference, and eventual **kwargs"""
|
|
|
|
content_id, cell_id = reference.split('-')
|
2019-04-07 19:45:09 +02:00
|
|
|
klass = get_cell_class(content_id)
|
|
|
|
if klass is None:
|
2014-12-24 07:34:52 +01:00
|
|
|
raise ObjectDoesNotExist()
|
|
|
|
return klass.objects.get(id=cell_id, **kwargs)
|
|
|
|
|
2014-12-13 11:25:53 +01:00
|
|
|
@classmethod
|
2016-02-07 00:25:34 +01:00
|
|
|
def get_cell_type_str(cls):
|
|
|
|
return '%s_%s' % (cls._meta.app_label, cls._meta.model_name)
|
|
|
|
|
2016-05-16 12:31:04 +02:00
|
|
|
@classmethod
|
|
|
|
def get_cell_type_group(cls):
|
|
|
|
return apps.get_app_config(cls._meta.app_label).verbose_name
|
|
|
|
|
2016-02-07 00:25:34 +01:00
|
|
|
@classmethod
|
|
|
|
def get_cell_types(cls):
|
2014-12-13 11:25:53 +01:00
|
|
|
return [{
|
|
|
|
'name': cls.get_verbose_name(),
|
2016-02-07 00:25:34 +01:00
|
|
|
'cell_type_str': cls.get_cell_type_str(),
|
2016-05-16 12:31:04 +02:00
|
|
|
'group': cls.get_cell_type_group(),
|
2014-12-13 11:25:53 +01:00
|
|
|
'variant': 'default',
|
2016-05-16 12:31:04 +02:00
|
|
|
'order': 0,
|
2014-12-13 11:25:53 +01:00
|
|
|
}]
|
|
|
|
|
2015-02-05 16:31:16 +01:00
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
|
|
|
"""Defines if the cell type is enabled for the given site; this is used
|
|
|
|
to selectively enable cells from extension modules."""
|
|
|
|
return True
|
|
|
|
|
2014-12-13 11:25:53 +01:00
|
|
|
def set_variant(self, variant):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def get_label(self):
|
|
|
|
return self.get_verbose_name()
|
|
|
|
|
|
|
|
def get_default_form_class(self):
|
|
|
|
if self.default_form_class:
|
|
|
|
return self.default_form_class
|
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
fields = [x.name for x in self._meta.local_concrete_fields
|
2015-01-13 10:41:46 +01:00
|
|
|
if x.name not in ('id', 'page', 'placeholder', 'order',
|
2015-10-29 17:40:07 +01:00
|
|
|
'public', 'groups', 'slug',
|
2017-02-14 21:08:46 +01:00
|
|
|
'extra_css_class', 'last_update_timestamp',
|
2015-10-29 17:40:07 +01:00
|
|
|
'restricted_to_unlogged')]
|
2014-12-13 11:25:53 +01:00
|
|
|
if not fields:
|
|
|
|
return None
|
|
|
|
|
2019-07-01 21:19:18 +02:00
|
|
|
return model_forms.modelform_factory(self.__class__, fields=fields, **self.manager_form_factory_kwargs)
|
2014-12-13 11:25:53 +01:00
|
|
|
|
2015-02-17 15:00:09 +01:00
|
|
|
def get_options_form_class(self):
|
|
|
|
return model_forms.modelform_factory(self.__class__,
|
2016-07-13 17:47:15 +02:00
|
|
|
fields=['slug', 'extra_css_class'])
|
2015-02-17 15:00:09 +01:00
|
|
|
|
2015-05-21 08:49:39 +02:00
|
|
|
def get_extra_manager_context(self):
|
|
|
|
return {}
|
|
|
|
|
2015-01-13 10:41:46 +01:00
|
|
|
def is_visible(self, user=None):
|
|
|
|
return element_is_visible(self, user=user)
|
|
|
|
|
2015-02-16 17:09:04 +01:00
|
|
|
def is_relevant(self, context):
|
|
|
|
'''Return whether it's relevant to render this cell in the page
|
|
|
|
context.'''
|
|
|
|
return True
|
|
|
|
|
2015-05-11 09:13:45 +02:00
|
|
|
def is_user_dependant(self, context):
|
|
|
|
'''Return whether the cell content varies from user to user.'''
|
|
|
|
return self.user_dependant
|
|
|
|
|
2016-04-01 18:50:41 +02:00
|
|
|
def get_concerned_user(self, context):
|
2016-03-30 14:45:16 +02:00
|
|
|
'''Return user from UserSearch cell, or connected user.'''
|
|
|
|
return context.get('selected_user') or getattr(context.get('request'), 'user', None)
|
2016-04-01 18:50:41 +02:00
|
|
|
|
2016-01-13 13:29:56 +01:00
|
|
|
def get_cell_extra_context(self, context):
|
2015-05-28 13:51:57 +02:00
|
|
|
return {'cell': self}
|
|
|
|
|
|
|
|
def render(self, context):
|
2016-01-13 13:29:56 +01:00
|
|
|
context.update(self.get_cell_extra_context(context))
|
2016-09-29 15:30:03 +02:00
|
|
|
template_names = ['combo/' + self._meta.model_name + '.html']
|
|
|
|
base_template_name = self._meta.model_name + '.html'
|
|
|
|
if self.template_name:
|
|
|
|
base_template_name = os.path.basename(self.template_name)
|
|
|
|
template_names.append(self.template_name)
|
|
|
|
if self.slug:
|
|
|
|
template_names.append('combo/cells/%s/%s' % (self.slug, base_template_name))
|
|
|
|
template_names.reverse()
|
|
|
|
tmpl = template.loader.select_template(template_names)
|
2018-01-01 12:35:01 +01:00
|
|
|
return tmpl.render(context, context.get('request'))
|
2015-05-28 13:51:57 +02:00
|
|
|
|
2015-06-06 16:16:19 +02:00
|
|
|
def render_for_search(self):
|
|
|
|
if not self.is_enabled():
|
|
|
|
return ''
|
2017-03-15 23:44:03 +01:00
|
|
|
if self.user_dependant:
|
|
|
|
return ''
|
|
|
|
if not self.page.is_visible(user=None):
|
|
|
|
return ''
|
2015-06-06 16:16:19 +02:00
|
|
|
if not self.is_visible(user=None):
|
|
|
|
return ''
|
2018-11-16 17:34:51 +01:00
|
|
|
request = RequestFactory().get(self.page.get_online_url())
|
|
|
|
request.user = None # compat
|
2018-01-01 12:35:01 +01:00
|
|
|
context = {
|
2018-11-16 17:34:51 +01:00
|
|
|
'page': self.page,
|
|
|
|
'render_skeleton': False,
|
|
|
|
'request': request,
|
|
|
|
'site_base': request.build_absolute_uri('/')[:-1],
|
2018-01-01 12:35:01 +01:00
|
|
|
'synchronous': True,
|
|
|
|
'user': None, # compat
|
2018-12-08 15:24:11 +01:00
|
|
|
'absolute_uri': request.build_absolute_uri,
|
2018-01-01 12:35:01 +01:00
|
|
|
}
|
2015-06-06 16:16:19 +02:00
|
|
|
if not self.is_relevant(context):
|
|
|
|
return ''
|
2018-07-25 14:28:05 +02:00
|
|
|
from django.utils.six.moves.html_parser import HTMLParser
|
2015-06-06 16:16:19 +02:00
|
|
|
return HTMLParser().unescape(strip_tags(self.render(context)))
|
|
|
|
|
2017-12-26 16:22:29 +01:00
|
|
|
def get_external_links_data(self):
|
|
|
|
return []
|
|
|
|
|
2015-05-25 12:59:41 +02:00
|
|
|
def export_subobjects(self):
|
|
|
|
return {}
|
|
|
|
|
|
|
|
def import_subobjects(self, cell_json):
|
|
|
|
pass
|
2014-12-07 15:28:18 +01:00
|
|
|
|
2020-01-07 15:27:44 +01:00
|
|
|
def duplicate(self, page_target=None, placeholder=None):
|
2019-10-22 14:58:02 +02:00
|
|
|
# clone current cell
|
|
|
|
new_cell = copy.deepcopy(self)
|
|
|
|
new_cell.pk = None
|
|
|
|
# set page
|
|
|
|
new_cell.page = page_target or self.page
|
2020-01-07 15:27:44 +01:00
|
|
|
# set placeholder
|
|
|
|
new_cell.placeholder = placeholder or new_cell.placeholder
|
2019-10-22 14:58:02 +02:00
|
|
|
# store new cell
|
|
|
|
new_cell.save()
|
|
|
|
|
|
|
|
# set groups
|
|
|
|
new_cell.groups.set(self.groups.all())
|
|
|
|
|
|
|
|
if hasattr(self, 'duplicate_m2m'):
|
|
|
|
self.duplicate_m2m(new_cell)
|
|
|
|
|
|
|
|
return new_cell
|
|
|
|
|
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
@register_cell_class
|
2014-12-07 15:34:30 +01:00
|
|
|
class TextCell(CellBase):
|
2015-02-26 10:04:04 +01:00
|
|
|
text = RichTextField(_('Text'), blank=True, null=True)
|
2014-12-07 17:22:49 +01:00
|
|
|
|
2016-09-29 14:45:52 +02:00
|
|
|
template_name = 'combo/text-cell.html'
|
|
|
|
|
2014-12-08 17:06:57 +01:00
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Text')
|
|
|
|
|
2016-09-29 14:45:52 +02:00
|
|
|
def is_relevant(self, context):
|
|
|
|
return bool(self.text)
|
2014-12-07 21:24:27 +01:00
|
|
|
|
2015-01-14 11:50:43 +01:00
|
|
|
def get_additional_label(self):
|
|
|
|
if not self.text:
|
|
|
|
return None
|
2015-05-28 13:51:57 +02:00
|
|
|
return utils.ellipsize(self.text)
|
2015-01-14 11:50:43 +01:00
|
|
|
|
2016-05-16 12:31:04 +02:00
|
|
|
@classmethod
|
|
|
|
def get_cell_types(cls):
|
|
|
|
d = super(TextCell, cls).get_cell_types()
|
|
|
|
d[0]['order'] = -1
|
|
|
|
return d
|
|
|
|
|
2019-05-05 12:32:39 +02:00
|
|
|
def get_cell_extra_context(self, context):
|
|
|
|
extra_context = super(TextCell, self).get_cell_extra_context(context)
|
2019-05-18 09:36:45 +02:00
|
|
|
text = self.text or ''
|
2019-05-05 12:32:39 +02:00
|
|
|
render_skeleton = context.get('render_skeleton')
|
2019-05-05 13:33:04 +02:00
|
|
|
|
|
|
|
def sub_variadic_url(match):
|
|
|
|
attribute = match.group(1)
|
|
|
|
url = match.group(2)
|
2019-09-25 18:27:30 +02:00
|
|
|
try:
|
|
|
|
url = utils.get_templated_url(url, context=context)
|
|
|
|
except utils.TemplateError as e:
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
logger.warning('error in templated URL (%s): %s' % (url, e))
|
2019-05-05 13:33:04 +02:00
|
|
|
return '%s="%s"' % (attribute, url)
|
|
|
|
text = re.sub(r'(href|src)="(.*?)"', sub_variadic_url, text)
|
|
|
|
|
2019-05-05 12:32:39 +02:00
|
|
|
if render_skeleton:
|
|
|
|
request = context.get('request')
|
|
|
|
def sub_src(match):
|
|
|
|
url = request.build_absolute_uri(match.group(1))
|
|
|
|
return 'src="%s"' % url
|
2019-05-05 13:13:11 +02:00
|
|
|
def sub_href(match):
|
|
|
|
url = match.group(1)
|
|
|
|
if url.startswith('#'):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
url = request.build_absolute_uri(url)
|
|
|
|
return 'href="%s"' % url
|
2019-05-05 13:33:04 +02:00
|
|
|
text = re.sub(r'src="(.*?)"', sub_src, text)
|
|
|
|
text = re.sub(r'href="(.*?)"', sub_href, text)
|
2019-05-06 16:56:25 +02:00
|
|
|
extra_context['text'] = mark_safe(text)
|
2019-05-05 12:32:39 +02:00
|
|
|
return extra_context
|
|
|
|
|
2014-12-07 17:22:49 +01:00
|
|
|
|
2014-12-24 07:34:52 +01:00
|
|
|
@register_cell_class
|
2014-12-07 17:22:49 +01:00
|
|
|
class FortuneCell(CellBase):
|
2015-01-25 10:33:16 +01:00
|
|
|
ajax_refresh = 30
|
|
|
|
|
2014-12-08 17:06:57 +01:00
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Fortune')
|
|
|
|
|
2014-12-13 11:25:53 +01:00
|
|
|
def render(self, context):
|
2014-12-07 21:24:27 +01:00
|
|
|
return subprocess.check_output(['fortune'])
|
2014-12-13 11:25:53 +01:00
|
|
|
|
2015-03-01 14:49:35 +01:00
|
|
|
@classmethod
|
|
|
|
def is_enabled(cls):
|
2016-01-13 11:29:23 +01:00
|
|
|
try:
|
|
|
|
subprocess.check_output(['fortune'])
|
|
|
|
except OSError:
|
|
|
|
return False
|
2015-03-01 14:49:35 +01:00
|
|
|
return settings.DEBUG
|
|
|
|
|
2014-12-13 11:25:53 +01:00
|
|
|
|
2014-12-30 13:10:48 +01:00
|
|
|
@register_cell_class
|
|
|
|
class UnlockMarkerCell(CellBase):
|
2016-05-28 14:34:32 +02:00
|
|
|
# XXX: this is kept to smooth transitions, it should be removed once all
|
|
|
|
# sites # have been migrated to ParentContentCell
|
2014-12-30 13:10:48 +01:00
|
|
|
"""Marks an 'acquired' placeholder as unlocked."""
|
|
|
|
visible = False
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Unlock Marker')
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
return ''
|
|
|
|
|
2015-02-17 16:20:02 +01:00
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class MenuCell(CellBase):
|
2015-02-18 11:22:03 +01:00
|
|
|
depth = models.PositiveIntegerField(_('Depth'),
|
|
|
|
choices=[(i, i) for i in range(1, 3)], default=1, null=False)
|
2016-02-20 14:35:16 +01:00
|
|
|
initial_level = models.IntegerField(_('Initial Level'),
|
|
|
|
choices=[(-1, _('Same as page'))] +
|
|
|
|
[(i, i) for i in range(1, 3)], default=-1, null=False)
|
2019-10-14 13:33:00 +02:00
|
|
|
root_page = models.ForeignKey(Page, on_delete=models.CASCADE, related_name='root_page',
|
2016-04-04 10:17:27 +02:00
|
|
|
null=True, blank=True, verbose_name=_('Root Page'))
|
2015-02-18 11:22:03 +01:00
|
|
|
|
2016-10-29 16:35:28 +02:00
|
|
|
template_name = 'combo/menu-cell.html'
|
|
|
|
|
2015-02-17 16:20:02 +01:00
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Menu')
|
|
|
|
|
2016-05-29 23:42:18 +02:00
|
|
|
def get_default_form_class(self):
|
|
|
|
from .forms import MenuCellForm
|
|
|
|
return MenuCellForm
|
|
|
|
|
2016-10-29 16:35:28 +02:00
|
|
|
def get_cell_extra_context(self, context):
|
2015-02-17 16:20:02 +01:00
|
|
|
from combo.public.menu import render_menu
|
2016-10-29 16:35:28 +02:00
|
|
|
ctx = super(MenuCell, self).get_cell_extra_context(context)
|
|
|
|
ctx['menu'] = render_menu(context, level=self.initial_level,
|
2018-12-18 12:32:02 +01:00
|
|
|
root_page=self.root_page, depth=self.depth,
|
|
|
|
ignore_visibility=False)
|
2016-10-29 16:35:28 +02:00
|
|
|
return ctx
|
2015-05-28 13:51:57 +02:00
|
|
|
|
2015-06-06 16:16:19 +02:00
|
|
|
def render_for_search(self):
|
|
|
|
return ''
|
|
|
|
|
2015-05-28 13:51:57 +02:00
|
|
|
|
|
|
|
@register_cell_class
|
|
|
|
class LinkCell(CellBase):
|
2015-05-29 12:04:17 +02:00
|
|
|
title = models.CharField(_('Title'), max_length=150, blank=True)
|
2017-10-22 14:44:45 +02:00
|
|
|
url = models.CharField(_('URL'), max_length=200, blank=True)
|
2019-10-14 13:33:00 +02:00
|
|
|
link_page = models.ForeignKey(
|
|
|
|
'data.Page', on_delete=models.CASCADE, related_name='link_cell', blank=True,
|
|
|
|
null=True, verbose_name=_('Internal link'))
|
2015-05-29 12:04:17 +02:00
|
|
|
anchor = models.CharField(_('Anchor'), max_length=150, blank=True)
|
2015-05-28 13:51:57 +02:00
|
|
|
|
|
|
|
template_name = 'combo/link-cell.html'
|
2020-01-07 15:27:44 +01:00
|
|
|
add_as_link_label = _('add a link')
|
|
|
|
add_link_label = _('New link')
|
|
|
|
edit_link_label = _('Edit link')
|
|
|
|
add_as_link_code = 'link'
|
2015-05-28 13:51:57 +02:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Link')
|
|
|
|
|
|
|
|
def get_additional_label(self):
|
2015-05-29 17:02:30 +02:00
|
|
|
title = self.title
|
|
|
|
if not title and self.link_page:
|
|
|
|
title = self.link_page.title
|
|
|
|
if not title:
|
2015-05-28 13:51:57 +02:00
|
|
|
return None
|
2015-05-29 17:02:30 +02:00
|
|
|
return utils.ellipsize(title)
|
2015-05-29 12:04:17 +02:00
|
|
|
|
2016-01-13 13:29:56 +01:00
|
|
|
def get_cell_extra_context(self, context):
|
2017-06-14 11:14:22 +02:00
|
|
|
render_skeleton = context.get('render_skeleton')
|
|
|
|
request = context.get('request')
|
2018-11-17 11:29:58 +01:00
|
|
|
extra_context = super(LinkCell, self).get_cell_extra_context(context)
|
2015-05-29 12:04:17 +02:00
|
|
|
if self.link_page:
|
2018-11-17 11:29:58 +01:00
|
|
|
extra_context['url'] = self.link_page.get_online_url()
|
|
|
|
extra_context['title'] = self.title or self.link_page.title
|
2015-05-29 12:04:17 +02:00
|
|
|
else:
|
2018-11-17 11:29:58 +01:00
|
|
|
extra_context['url'] = utils.get_templated_url(self.url, context=context)
|
|
|
|
extra_context['title'] = self.title or self.url
|
2015-05-29 12:04:17 +02:00
|
|
|
if self.anchor:
|
2018-11-17 11:29:58 +01:00
|
|
|
extra_context['url'] += '#' + self.anchor
|
|
|
|
if render_skeleton and not urlparse.urlparse(extra_context['url']).netloc:
|
2017-06-14 11:14:22 +02:00
|
|
|
# create full URL when used in a skeleton
|
2018-11-17 11:29:58 +01:00
|
|
|
extra_context['url'] = request.build_absolute_uri(extra_context['url'])
|
|
|
|
return extra_context
|
2015-08-24 14:32:06 +02:00
|
|
|
|
2017-06-17 22:48:25 +02:00
|
|
|
def get_default_form_class(self):
|
2018-07-25 14:28:05 +02:00
|
|
|
from .forms import LinkCellForm
|
2017-06-17 22:48:25 +02:00
|
|
|
return LinkCellForm
|
|
|
|
|
2017-12-26 16:22:29 +01:00
|
|
|
def render_for_search(self):
|
|
|
|
return ''
|
|
|
|
|
|
|
|
def get_external_links_data(self):
|
|
|
|
if not self.url:
|
|
|
|
return []
|
|
|
|
link_data = self.get_cell_extra_context({})
|
|
|
|
if link_data.get('title') and link_data.get('url'):
|
|
|
|
return [link_data]
|
|
|
|
return []
|
|
|
|
|
2015-08-24 14:32:06 +02:00
|
|
|
|
2020-01-07 15:27:44 +01:00
|
|
|
@register_cell_class
|
|
|
|
class LinkListCell(CellBase):
|
|
|
|
title = models.CharField(_('Title'), max_length=150, blank=True)
|
|
|
|
|
|
|
|
template_name = 'combo/link-list-cell.html'
|
|
|
|
manager_form_template = 'combo/manager/link-list-cell-form.html'
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('List of links')
|
|
|
|
|
|
|
|
@property
|
|
|
|
def link_placeholder(self):
|
|
|
|
return '_linkslist:{}'.format(self.pk)
|
|
|
|
|
|
|
|
def get_items(self):
|
|
|
|
return CellBase.get_cells(
|
|
|
|
page=self.page,
|
|
|
|
placeholder=self.link_placeholder,
|
|
|
|
cell_filter=lambda x: hasattr(x, 'add_as_link_label'))
|
|
|
|
|
|
|
|
def get_additional_label(self):
|
|
|
|
title = self.title
|
|
|
|
if not title:
|
|
|
|
return None
|
|
|
|
return utils.ellipsize(title)
|
|
|
|
|
|
|
|
def get_cell_extra_context(self, context):
|
|
|
|
extra_context = super(LinkListCell, self).get_cell_extra_context(context)
|
|
|
|
links = []
|
|
|
|
for cell in context.get('page_cells', []):
|
|
|
|
if not hasattr(cell, 'add_as_link_label'):
|
|
|
|
continue
|
|
|
|
if not cell.placeholder == self.link_placeholder:
|
|
|
|
continue
|
|
|
|
links.append(cell.get_cell_extra_context(context))
|
|
|
|
extra_context['links'] = links
|
|
|
|
extra_context['title'] = self.title
|
|
|
|
return extra_context
|
|
|
|
|
|
|
|
def get_link_cell_classes(self):
|
|
|
|
return CellBase.get_cell_classes(lambda x: hasattr(x, 'add_as_link_label'))
|
|
|
|
|
|
|
|
def get_default_form_class(self):
|
|
|
|
from .forms import LinkListCellForm
|
|
|
|
return LinkListCellForm
|
|
|
|
|
|
|
|
def render_for_search(self):
|
|
|
|
return ''
|
|
|
|
|
|
|
|
def export_subobjects(self):
|
|
|
|
return {'links': json.loads(
|
|
|
|
serializers.serialize(
|
|
|
|
'json',
|
|
|
|
self.get_items(),
|
|
|
|
use_natural_foreign_keys=True,
|
|
|
|
use_natural_primary_keys=True)
|
|
|
|
)}
|
|
|
|
|
|
|
|
def import_subobjects(self, cell_json):
|
|
|
|
for link in cell_json['links']:
|
|
|
|
link['fields']['placeholder'] = self.link_placeholder
|
|
|
|
for link in serializers.deserialize('json', json.dumps(cell_json['links'])):
|
|
|
|
link.save()
|
|
|
|
|
|
|
|
def duplicate_m2m(self, new_cell):
|
|
|
|
# duplicate also link items
|
|
|
|
for link in self.get_items():
|
|
|
|
link.duplicate(page_target=new_cell.page, placeholder=new_cell.link_placeholder)
|
|
|
|
|
|
|
|
|
2015-08-24 14:32:06 +02:00
|
|
|
@register_cell_class
|
|
|
|
class FeedCell(CellBase):
|
2016-03-08 17:12:52 +01:00
|
|
|
title = models.CharField(_('Title'), max_length=150, blank=True)
|
2019-07-01 21:19:18 +02:00
|
|
|
url = models.CharField(_('URL'), blank=True, max_length=200)
|
2016-03-28 15:07:39 +02:00
|
|
|
limit = models.PositiveSmallIntegerField(_('Maximum number of entries'),
|
|
|
|
null=True, blank=True)
|
2015-08-24 14:32:06 +02:00
|
|
|
|
2019-07-01 21:19:18 +02:00
|
|
|
manager_form_factory_kwargs = {'field_classes': {'url': TemplatableURLField}}
|
2015-08-24 14:32:06 +02:00
|
|
|
template_name = 'combo/feed-cell.html'
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('RSS/Atom Feed')
|
|
|
|
|
2015-10-07 10:00:28 +02:00
|
|
|
def is_visible(self, user=None):
|
|
|
|
return bool(self.url) and super(FeedCell, self).is_visible(user=user)
|
|
|
|
|
2016-01-13 13:29:56 +01:00
|
|
|
def get_cell_extra_context(self, context):
|
2017-10-14 22:08:21 +02:00
|
|
|
extra_context = super(FeedCell, self).get_cell_extra_context(context)
|
|
|
|
if context.get('placeholder_search_mode'):
|
|
|
|
# don't call webservices when we're just looking for placeholders
|
|
|
|
return extra_context
|
2018-07-25 14:28:05 +02:00
|
|
|
cache_key = hashlib.md5(smart_bytes(self.url)).hexdigest()
|
2015-08-24 14:32:06 +02:00
|
|
|
feed_content = cache.get(cache_key)
|
|
|
|
if not feed_content:
|
2019-10-22 11:19:02 +02:00
|
|
|
try:
|
|
|
|
feed_response = requests.get(utils.get_templated_url(self.url))
|
|
|
|
feed_response.raise_for_status()
|
|
|
|
except (requests.exceptions.RequestException):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if feed_response.status_code == 200:
|
|
|
|
feed_content = feed_response.content
|
|
|
|
cache.set(cache_key, feed_content, 600)
|
2015-08-24 14:32:06 +02:00
|
|
|
if feed_content:
|
2017-10-14 22:08:21 +02:00
|
|
|
extra_context['feed'] = feedparser.parse(feed_content)
|
2016-03-28 15:07:39 +02:00
|
|
|
if self.limit:
|
2017-10-14 22:08:21 +02:00
|
|
|
extra_context['feed']['entries'] = extra_context['feed']['entries'][:self.limit]
|
2016-03-08 17:12:52 +01:00
|
|
|
if not self.title:
|
|
|
|
try:
|
2017-10-14 22:08:21 +02:00
|
|
|
self.title = extra_context['feed']['feed'].title
|
2017-12-26 16:27:45 +01:00
|
|
|
except (KeyError, AttributeError):
|
2016-03-08 17:12:52 +01:00
|
|
|
pass
|
2017-10-14 22:08:21 +02:00
|
|
|
return extra_context
|
2015-10-28 11:14:48 +01:00
|
|
|
|
|
|
|
def render(self, context):
|
2018-07-25 14:28:05 +02:00
|
|
|
cache_key = hashlib.md5(smart_bytes(self.url)).hexdigest()
|
2015-10-28 11:14:48 +01:00
|
|
|
feed_content = cache.get(cache_key)
|
|
|
|
if not context.get('synchronous') and feed_content is None:
|
|
|
|
raise NothingInCacheException()
|
2015-08-24 14:32:06 +02:00
|
|
|
return super(FeedCell, self).render(context)
|
2016-01-13 13:39:55 +01:00
|
|
|
|
|
|
|
|
2016-05-28 14:34:32 +02:00
|
|
|
@register_cell_class
|
|
|
|
class ParentContentCell(CellBase):
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _('Same as parent')
|
|
|
|
|
2018-01-18 08:47:42 +01:00
|
|
|
def get_parents_cells(self, hierarchy):
|
|
|
|
try:
|
2018-06-02 15:08:57 +02:00
|
|
|
pages = [Page.objects.get(slug='index', parent=None)]
|
2018-01-18 08:47:42 +01:00
|
|
|
except Page.DoesNotExist:
|
2018-06-02 15:08:57 +02:00
|
|
|
pages = []
|
|
|
|
pages.extend(hierarchy)
|
|
|
|
if not pages:
|
2016-05-28 14:34:32 +02:00
|
|
|
return []
|
2018-06-02 15:08:57 +02:00
|
|
|
if len(pages) > 1 and pages[0].id == pages[1].id:
|
2018-02-22 14:45:13 +01:00
|
|
|
# don't duplicate index cells for real children of the index page.
|
2018-06-02 15:08:57 +02:00
|
|
|
pages = pages[1:]
|
2018-01-18 08:47:42 +01:00
|
|
|
cells_by_page = {}
|
2018-06-02 15:08:57 +02:00
|
|
|
for page in pages:
|
|
|
|
cells_by_page[page.id] = []
|
|
|
|
for cell in list(CellBase.get_cells(placeholder=self.placeholder, page__in=pages)):
|
2018-01-18 08:47:42 +01:00
|
|
|
cells_by_page[cell.page_id].append(cell)
|
|
|
|
|
2018-06-02 15:08:57 +02:00
|
|
|
cells = cells_by_page[pages[-1].id]
|
|
|
|
for page in reversed(pages[:-1]):
|
2018-01-18 08:47:42 +01:00
|
|
|
for i, cell in enumerate(cells):
|
|
|
|
if isinstance(cell, ParentContentCell):
|
2018-06-02 15:08:57 +02:00
|
|
|
cells[i:i+1] = cells_by_page[page.id]
|
2018-01-18 08:47:42 +01:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
# no more ParentContentCell, stop folloing the parent page chain
|
|
|
|
break
|
2016-05-28 14:34:32 +02:00
|
|
|
return cells
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
return ''
|
2017-02-10 08:32:58 +01:00
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
|
|
|
|
class JsonCellBase(CellBase):
|
|
|
|
url = None
|
|
|
|
cache_duration = 60
|
|
|
|
template_string = None
|
2017-04-05 12:29:02 +02:00
|
|
|
varnames = None
|
2017-05-12 13:48:47 +02:00
|
|
|
force_async = False
|
2017-07-28 00:42:18 +02:00
|
|
|
log_errors = True
|
2017-12-21 01:42:05 +01:00
|
|
|
timeout = None
|
2017-06-20 17:38:35 +02:00
|
|
|
actions = {}
|
2017-06-26 10:16:37 +02:00
|
|
|
additional_data = None
|
|
|
|
# [
|
|
|
|
# {'key': ...,
|
|
|
|
# 'url': ...,
|
|
|
|
# 'cache_duration': ... (optional)
|
|
|
|
# },
|
|
|
|
# ...
|
|
|
|
# ]
|
2018-08-10 17:11:26 +02:00
|
|
|
first_data_key = 'json'
|
2017-02-10 08:32:58 +01:00
|
|
|
|
|
|
|
_json_content = None
|
|
|
|
|
|
|
|
class Meta:
|
2017-04-02 13:31:16 +02:00
|
|
|
abstract = True
|
2017-02-10 08:32:58 +01:00
|
|
|
|
|
|
|
def is_visible(self, user=None):
|
2017-04-02 13:31:16 +02:00
|
|
|
return bool(self.url) and super(JsonCellBase, self).is_visible(user=user)
|
2017-02-10 08:32:58 +01:00
|
|
|
|
2019-02-25 20:52:49 +01:00
|
|
|
def get_cell_parameters_context(self):
|
|
|
|
return {}
|
|
|
|
|
2017-06-20 17:38:35 +02:00
|
|
|
def get_cell_extra_context(self, context, invalidate_cache=False):
|
2017-04-02 13:31:16 +02:00
|
|
|
extra_context = super(JsonCellBase, self).get_cell_extra_context(context)
|
2017-10-14 22:08:21 +02:00
|
|
|
if context.get('placeholder_search_mode'):
|
|
|
|
# don't call webservices when we're just looking for placeholders
|
|
|
|
return extra_context
|
2017-04-05 12:29:02 +02:00
|
|
|
if self.varnames and context.get('request'):
|
|
|
|
for varname in self.varnames:
|
2017-08-07 15:02:01 +02:00
|
|
|
if varname in context['request'].GET:
|
2017-04-05 12:29:02 +02:00
|
|
|
context[varname] = context['request'].GET[varname]
|
2017-02-10 08:32:58 +01:00
|
|
|
self._json_content = None
|
2017-06-26 10:16:37 +02:00
|
|
|
|
2019-02-26 10:47:16 +01:00
|
|
|
extra_context.update(self.get_cell_parameters_context())
|
2019-02-25 20:52:49 +01:00
|
|
|
context.update(self.get_cell_parameters_context())
|
2018-08-10 17:11:26 +02:00
|
|
|
context['concerned_user'] = self.get_concerned_user(context)
|
|
|
|
|
|
|
|
data_urls = [{'key': self.first_data_key, 'url': self.url, 'cache_duration': self.cache_duration,
|
2017-08-07 16:35:30 +02:00
|
|
|
'log_errors': self.log_errors, 'timeout': self.timeout}]
|
2017-06-26 10:16:37 +02:00
|
|
|
data_urls.extend(self.additional_data or [])
|
|
|
|
|
|
|
|
for data_url_dict in data_urls:
|
|
|
|
extra_context[data_url_dict['key']] = None
|
|
|
|
|
|
|
|
for data_url_dict in data_urls:
|
|
|
|
data_key = data_url_dict['key']
|
2017-08-07 16:35:30 +02:00
|
|
|
log_errors = data_url_dict.get('log_errors', self.log_errors)
|
2017-02-24 12:28:21 +01:00
|
|
|
try:
|
2017-06-26 10:16:37 +02:00
|
|
|
url = utils.get_templated_url(data_url_dict['url'], context)
|
2017-10-07 18:55:17 +02:00
|
|
|
except utils.TemplateError as e:
|
2017-02-24 12:28:21 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
2017-10-07 18:55:17 +02:00
|
|
|
logger.warning('error in templated URL (%s): %s', data_url_dict['url'], e)
|
2017-06-26 10:16:37 +02:00
|
|
|
continue
|
2017-07-20 15:03:47 +02:00
|
|
|
extra_context[data_key + '_url'] = url
|
2017-10-07 18:55:17 +02:00
|
|
|
if not url:
|
|
|
|
continue
|
2017-08-07 16:35:30 +02:00
|
|
|
try:
|
|
|
|
json_response = utils.requests.get(url,
|
|
|
|
headers={'Accept': 'application/json'},
|
|
|
|
remote_service='auto',
|
|
|
|
cache_duration=data_url_dict.get('cache_duration', self.cache_duration),
|
|
|
|
without_user=True,
|
|
|
|
raise_if_not_cached=not(context.get('synchronous')),
|
|
|
|
invalidate_cache=invalidate_cache,
|
|
|
|
log_errors=log_errors,
|
|
|
|
timeout=data_url_dict.get('timeout', self.timeout),
|
2019-06-06 10:36:52 +02:00
|
|
|
django_request=context.get('request'),
|
2017-08-07 16:35:30 +02:00
|
|
|
)
|
|
|
|
except requests.RequestException as e:
|
|
|
|
extra_context[data_key + '_status'] = -1
|
2018-07-25 14:28:05 +02:00
|
|
|
extra_context[data_key + '_error'] = force_text(e)
|
2017-08-07 16:35:30 +02:00
|
|
|
extra_context[data_key + '_exception'] = e
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
if log_errors:
|
2018-07-25 14:28:05 +02:00
|
|
|
logger.warning(u'error on request %r: %s', url, force_text(e))
|
2017-08-07 16:35:30 +02:00
|
|
|
else:
|
2018-07-25 14:28:05 +02:00
|
|
|
logger.debug(u'error on request %r: %s', url, force_text(e))
|
2017-08-07 16:35:30 +02:00
|
|
|
continue
|
2017-07-20 15:03:47 +02:00
|
|
|
extra_context[data_key + '_status'] = json_response.status_code
|
|
|
|
if json_response.status_code // 100 == 2:
|
|
|
|
if json_response.status_code != 204: # 204 = No Content
|
|
|
|
try:
|
2019-08-18 13:21:51 +02:00
|
|
|
extra_context[data_key] = json_response.json()
|
2017-07-20 15:03:47 +02:00
|
|
|
except ValueError:
|
|
|
|
extra_context[data_key + '_error'] = 'invalid_json'
|
|
|
|
logger = logging.getLogger(__name__)
|
2018-03-21 10:41:33 +01:00
|
|
|
if log_errors:
|
|
|
|
logger.error('invalid json content (%s)', url)
|
|
|
|
else:
|
|
|
|
logger.debug('invalid json content (%s)', url)
|
2017-07-20 15:03:47 +02:00
|
|
|
continue
|
|
|
|
elif json_response.headers.get('content-type') == 'application/json':
|
2017-06-26 10:16:37 +02:00
|
|
|
try:
|
2019-08-18 13:21:51 +02:00
|
|
|
extra_context[data_key + '_error'] = json_response.json()
|
2017-06-26 10:16:37 +02:00
|
|
|
except ValueError:
|
2017-07-20 15:03:47 +02:00
|
|
|
extra_context[data_key + '_error'] = 'invalid_json'
|
2017-06-26 10:16:37 +02:00
|
|
|
|
|
|
|
# update context with data key so it can be used in future
|
|
|
|
# templated URLs
|
|
|
|
context[data_key] = extra_context[data_key]
|
|
|
|
|
|
|
|
# keep cache of first response as it may be used to find the
|
|
|
|
# appropriate template.
|
2018-08-10 17:11:26 +02:00
|
|
|
self._json_content = extra_context[self.first_data_key]
|
2017-06-26 10:16:37 +02:00
|
|
|
|
2017-02-25 11:23:19 +01:00
|
|
|
return extra_context
|
2017-02-10 08:32:58 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def template_name(self):
|
|
|
|
json_content = self._json_content
|
|
|
|
if json_content is None:
|
|
|
|
return 'combo/json-error-cell.html'
|
|
|
|
if json_content.get('data'):
|
|
|
|
if isinstance(json_content['data'], list):
|
|
|
|
first_element = json_content['data'][0]
|
|
|
|
if isinstance(first_element, dict):
|
|
|
|
if 'url' in first_element and 'text' in first_element:
|
|
|
|
return 'combo/json-list-cell.html'
|
|
|
|
return 'combo/json-cell.html'
|
|
|
|
|
2017-06-20 17:38:35 +02:00
|
|
|
def post(self, request):
|
|
|
|
if not 'action' in request.POST:
|
|
|
|
raise PermissionDenied()
|
|
|
|
action = request.POST['action']
|
|
|
|
if not action in self.actions:
|
|
|
|
raise PermissionDenied()
|
|
|
|
|
|
|
|
error_message = self.actions[action].get('error-message')
|
2017-08-07 16:35:30 +02:00
|
|
|
timeout = self.actions[action].get('timeout', self.timeout)
|
2018-03-04 23:01:01 +01:00
|
|
|
method = self.actions[action].get('method', 'POST')
|
2017-06-20 17:38:35 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
content = {}
|
|
|
|
for key, value in request.POST.items():
|
|
|
|
if key == 'action':
|
|
|
|
continue
|
2018-02-27 10:07:52 +01:00
|
|
|
if key.endswith('[]'): # array
|
|
|
|
content[key[:-2]] = request.POST.getlist(key)
|
|
|
|
else:
|
|
|
|
content[key] = value
|
2017-06-20 17:38:35 +02:00
|
|
|
|
2018-01-01 12:35:01 +01:00
|
|
|
context = copy.copy(content)
|
2019-02-25 20:52:49 +01:00
|
|
|
context.update(self.get_cell_parameters_context())
|
2018-01-01 12:35:01 +01:00
|
|
|
context['request'] = request
|
|
|
|
context['synchronous'] = True
|
2017-06-24 11:10:05 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
url = utils.get_templated_url(self.actions[action]['url'], context)
|
2017-10-07 18:55:17 +02:00
|
|
|
except utils.TemplateError as e:
|
|
|
|
logger.warning('error in templated URL (%s): %s', self.actions[action]['url'], e)
|
2017-06-24 11:10:05 +02:00
|
|
|
raise PostException(error_message)
|
|
|
|
|
2018-03-04 23:01:01 +01:00
|
|
|
json_response = utils.requests.request(
|
|
|
|
method,
|
|
|
|
url,
|
2017-06-20 17:38:35 +02:00
|
|
|
headers={'Accept': 'application/json'},
|
|
|
|
remote_service='auto',
|
|
|
|
json=content,
|
2019-06-06 10:36:52 +02:00
|
|
|
without_user=True,
|
|
|
|
django_request=request,
|
2020-01-18 14:19:19 +01:00
|
|
|
timeout=timeout,
|
2019-06-06 10:36:52 +02:00
|
|
|
)
|
2017-06-20 17:38:35 +02:00
|
|
|
|
|
|
|
if json_response.status_code // 100 != 2: # 2xx
|
|
|
|
logger.error('error POSTing data to URL (%s)', url)
|
|
|
|
raise PostException(error_message)
|
|
|
|
|
|
|
|
if self.cache_duration:
|
|
|
|
self.get_cell_extra_context(context, invalidate_cache=True)
|
|
|
|
|
2018-09-12 21:41:27 +02:00
|
|
|
if self.actions[action].get('response', 'cell') == 'raw':
|
|
|
|
# response: raw in the config will get the response directly sent
|
|
|
|
# to the client.
|
|
|
|
return json_response
|
|
|
|
|
|
|
|
# default behaviour, the cell will render itself.
|
|
|
|
return None
|
|
|
|
|
2017-02-10 08:32:58 +01:00
|
|
|
def render(self, context):
|
2017-05-12 13:48:47 +02:00
|
|
|
if self.force_async and not context.get('synchronous'):
|
2017-02-10 08:32:58 +01:00
|
|
|
raise NothingInCacheException()
|
|
|
|
if self.template_string:
|
2018-01-01 12:35:01 +01:00
|
|
|
tmpl = engines['django'].from_string(self.template_string)
|
2017-04-05 12:49:39 +02:00
|
|
|
context.update(self.get_cell_extra_context(context))
|
2018-01-01 12:35:01 +01:00
|
|
|
return tmpl.render(context, context.get('request'))
|
2017-04-02 13:31:16 +02:00
|
|
|
return super(JsonCellBase, self).render(context)
|
|
|
|
|
|
|
|
|
2019-07-10 17:00:14 +02:00
|
|
|
def django_template_validator(value):
|
|
|
|
try:
|
|
|
|
tmpl = engines['django'].from_string(value)
|
|
|
|
except TemplateSyntaxError as e:
|
|
|
|
raise ValidationError(_('syntax error: %s') % e)
|
|
|
|
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
@register_cell_class
|
|
|
|
class JsonCell(JsonCellBase):
|
|
|
|
title = models.CharField(_('Title'), max_length=150, blank=True)
|
2020-01-08 11:09:21 +01:00
|
|
|
url = models.CharField(_('URL'), blank=True, max_length=500)
|
2019-07-10 17:00:14 +02:00
|
|
|
template_string = models.TextField(_('Display Template'), blank=True, null=True,
|
|
|
|
validators=[django_template_validator])
|
2017-04-02 13:31:16 +02:00
|
|
|
cache_duration = models.PositiveIntegerField(
|
|
|
|
_('Cache duration'), default=60)
|
2017-05-12 13:48:47 +02:00
|
|
|
force_async = models.BooleanField(_('Force asynchronous mode'),
|
|
|
|
default=JsonCellBase.force_async)
|
2017-04-05 12:29:02 +02:00
|
|
|
varnames_str = models.CharField(_('Variable names'), max_length=200, blank=True,
|
|
|
|
help_text=_('Comma separated list of query-string variables '
|
|
|
|
'to be copied in template context'))
|
2017-12-21 01:42:05 +01:00
|
|
|
timeout = models.PositiveIntegerField(_('Request timeout'), default=0,
|
|
|
|
help_text=_('In seconds. Use 0 for default system timeout'))
|
2017-04-02 13:31:16 +02:00
|
|
|
|
2019-07-01 21:19:18 +02:00
|
|
|
manager_form_factory_kwargs = {'field_classes': {'url': TemplatableURLField}}
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
class Meta:
|
2019-07-01 15:59:15 +02:00
|
|
|
verbose_name = _('JSON Prototype')
|
2017-04-02 13:31:16 +02:00
|
|
|
|
2017-04-05 12:29:02 +02:00
|
|
|
@property
|
|
|
|
def varnames(self):
|
|
|
|
return [vn.strip() for vn in self.varnames_str.split(',') if vn.strip()]
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
|
2018-05-31 08:53:08 +02:00
|
|
|
class ConfigJsonCellManager(models.Manager):
|
|
|
|
def get_queryset(self):
|
|
|
|
queryset = super(ConfigJsonCellManager, self).get_queryset()
|
|
|
|
return queryset.filter(key__in=settings.JSON_CELL_TYPES.keys())
|
|
|
|
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
@register_cell_class
|
|
|
|
class ConfigJsonCell(JsonCellBase):
|
2018-05-31 08:53:08 +02:00
|
|
|
objects = ConfigJsonCellManager()
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
key = models.CharField(max_length=50)
|
|
|
|
parameters = JSONField(blank=True)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_cell_types(cls):
|
|
|
|
l = []
|
|
|
|
for key, definition in settings.JSON_CELL_TYPES.items():
|
|
|
|
l.append({
|
|
|
|
'name': definition['name'],
|
|
|
|
'variant': key,
|
|
|
|
'group': _('Extra'),
|
|
|
|
'cell_type_str': cls.get_cell_type_str(),
|
|
|
|
})
|
2018-07-25 14:28:05 +02:00
|
|
|
l.sort(key=lambda x: x.get('name'))
|
2017-04-02 13:31:16 +02:00
|
|
|
return l
|
|
|
|
|
|
|
|
def get_label(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key]['name']
|
|
|
|
|
|
|
|
def set_variant(self, variant):
|
|
|
|
self.key = variant
|
|
|
|
|
2018-04-10 21:59:09 +02:00
|
|
|
@property
|
|
|
|
def css_class_names(self):
|
|
|
|
return super(ConfigJsonCell, self).css_class_names + ' ' + self.key
|
|
|
|
|
2017-06-28 13:34:05 +02:00
|
|
|
@property
|
|
|
|
def ajax_refresh(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('auto_refresh', None)
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
@property
|
|
|
|
def url(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key]['url']
|
|
|
|
|
2017-04-05 16:52:06 +02:00
|
|
|
@property
|
|
|
|
def cache_duration(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('cache_duration',
|
|
|
|
JsonCellBase.cache_duration)
|
|
|
|
|
2017-04-05 12:29:02 +02:00
|
|
|
@property
|
|
|
|
def varnames(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('varnames')
|
|
|
|
|
2017-05-12 13:48:47 +02:00
|
|
|
@property
|
|
|
|
def force_async(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('force_async',
|
|
|
|
JsonCellBase.force_async)
|
|
|
|
|
2017-07-28 00:42:18 +02:00
|
|
|
@property
|
|
|
|
def log_errors(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('log_errors',
|
|
|
|
JsonCellBase.log_errors)
|
2017-08-07 16:35:30 +02:00
|
|
|
@property
|
|
|
|
def timeout(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('timeout',
|
|
|
|
JsonCellBase.timeout)
|
2017-07-28 00:42:18 +02:00
|
|
|
|
2017-06-20 17:38:35 +02:00
|
|
|
@property
|
|
|
|
def actions(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('actions',
|
|
|
|
JsonCellBase.actions)
|
|
|
|
|
2017-06-26 10:16:37 +02:00
|
|
|
@property
|
|
|
|
def additional_data(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('additional-data')
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
@property
|
|
|
|
def template_name(self):
|
|
|
|
return 'combo/json/%s.html' % self.key
|
|
|
|
|
2018-02-22 14:25:56 +01:00
|
|
|
@property
|
|
|
|
def loading_message(self):
|
|
|
|
return settings.JSON_CELL_TYPES[self.key].get('loading-message',
|
|
|
|
CellBase.loading_message)
|
|
|
|
|
2017-04-02 13:31:16 +02:00
|
|
|
def get_default_form_class(self):
|
|
|
|
formdef = settings.JSON_CELL_TYPES[self.key].get('form')
|
|
|
|
if not formdef:
|
|
|
|
return None
|
|
|
|
from .forms import ConfigJsonForm
|
|
|
|
# create a subclass of ConfigJsonForm with 'formdef' (the list of
|
|
|
|
# fields) as an attribute.
|
|
|
|
config_form_class = type(str('%sConfigClass' % self.key),
|
|
|
|
(ConfigJsonForm,), {'formdef': formdef})
|
|
|
|
return config_form_class
|
|
|
|
|
2019-02-25 20:52:49 +01:00
|
|
|
def get_cell_parameters_context(self):
|
2019-02-26 10:47:16 +01:00
|
|
|
context = copy.copy(self.parameters or {})
|
|
|
|
context['parameters'] = self.parameters
|
|
|
|
return context
|
2017-12-26 16:22:29 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ExternalLinkSearchItem(models.Model):
|
|
|
|
# Link to an external site.
|
|
|
|
#
|
|
|
|
# Those are automatically collected during by the "update_index" command,
|
|
|
|
# that calls get_external_links_data from all available cells, to be used
|
|
|
|
# by the general search engine.
|
|
|
|
title = models.CharField(_('Title'), max_length=150)
|
|
|
|
text = models.TextField(blank=True)
|
|
|
|
url = models.CharField(_('URL'), max_length=200, blank=True)
|
|
|
|
last_update_timestamp = models.DateTimeField(auto_now=True)
|
2018-07-12 21:32:59 +02:00
|
|
|
|
|
|
|
|
|
|
|
@receiver(pre_save, sender=Page)
|
|
|
|
def create_redirects(sender, instance, raw, **kwargs):
|
|
|
|
if raw or not instance.id or instance.snapshot_id:
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
old_page = Page.objects.get(id=instance.id)
|
|
|
|
except Page.DoesNotExist:
|
|
|
|
return
|
|
|
|
if old_page.slug == instance.slug and old_page.parent_id == instance.parent_id:
|
|
|
|
return
|
|
|
|
affected_pages = level_pages = [old_page]
|
|
|
|
while True:
|
|
|
|
level_pages = Page.objects.filter(parent_id__in=[x.id for x in level_pages]).select_related('parent')
|
|
|
|
if len(level_pages) == 0:
|
|
|
|
break
|
|
|
|
affected_pages.extend(level_pages)
|
|
|
|
for page in affected_pages:
|
|
|
|
Redirect(page=page, old_url=page.get_online_url()).save()
|
2018-06-02 15:08:57 +02:00
|
|
|
|
|
|
|
@receiver(post_save)
|
|
|
|
@receiver(post_delete)
|
|
|
|
def cell_maintain_page_cell_cache(sender, instance=None, **kwargs):
|
|
|
|
if not issubclass(sender, CellBase):
|
|
|
|
return
|
|
|
|
if not instance.page_id:
|
|
|
|
return
|
|
|
|
page = instance.page
|
|
|
|
page.build_cell_cache()
|