page_models.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. """
  2. Base and abstract pages used in CodeRed CMS.
  3. """
  4. import json
  5. import logging
  6. import os
  7. import warnings
  8. from datetime import date, datetime
  9. from typing import Dict, List, Optional, TYPE_CHECKING, Union
  10. import geocoder
  11. from django import forms
  12. from django.conf import settings
  13. from django.contrib import messages
  14. from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile
  15. from django.core.files.storage import FileSystemStorage
  16. from django.core.mail import EmailMessage
  17. from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
  18. from django.core.serializers.json import DjangoJSONEncoder
  19. from django.core.validators import MaxValueValidator, MinValueValidator
  20. from django.db import models
  21. from django.db.models.signals import post_delete, post_save
  22. from django.dispatch import receiver
  23. from django.http import JsonResponse, HttpResponseRedirect
  24. from django.shortcuts import render, redirect
  25. from django.template import Context, Template
  26. from django.template.loader import render_to_string
  27. from django.utils import timezone
  28. from django.utils.html import strip_tags
  29. from django.utils.safestring import mark_safe
  30. from django.utils.translation import gettext_lazy as _
  31. from eventtools.models import BaseEvent, BaseOccurrence
  32. from icalendar import Event as ICalEvent
  33. from modelcluster.fields import ParentalKey, ParentalManyToManyField
  34. from modelcluster.tags import ClusterTaggableManager
  35. from pathlib import Path
  36. from taggit.models import TaggedItemBase
  37. from wagtail.admin.edit_handlers import (
  38. FieldPanel,
  39. FieldRowPanel,
  40. InlinePanel,
  41. MultiFieldPanel,
  42. ObjectList,
  43. PageChooserPanel,
  44. StreamFieldPanel,
  45. TabbedInterface
  46. )
  47. from wagtail.core import hooks
  48. from wagtail.core.fields import StreamField
  49. from wagtail.core.models import Orderable, PageBase, Page, Site
  50. from wagtail.core.utils import resolve_model_string
  51. from wagtail.contrib.forms.edit_handlers import FormSubmissionsPanel
  52. from wagtail.contrib.forms.forms import WagtailAdminFormPageForm
  53. from wagtail.images import get_image_model_string
  54. from wagtail.images.edit_handlers import ImageChooserPanel
  55. from wagtail.contrib.forms.models import FormSubmission
  56. from wagtail.search import index
  57. from wagtail.utils.decorators import cached_classmethod
  58. from wagtailcache.cache import WagtailCacheMixin
  59. from wagtailseo.models import SeoMixin, TwitterCard
  60. from wagtailseo.utils import get_struct_data_images, StructDataEncoder
  61. from coderedcms import utils
  62. from coderedcms.blocks import (
  63. CONTENT_STREAMBLOCKS,
  64. LAYOUT_STREAMBLOCKS,
  65. STREAMFORM_BLOCKS,
  66. ContentWallBlock,
  67. )
  68. from coderedcms.fields import ColorField
  69. from coderedcms.forms import CoderedFormBuilder, CoderedSubmissionsListView
  70. from coderedcms.models.snippet_models import ClassifierTerm
  71. from coderedcms.models.wagtailsettings_models import (
  72. GeneralSettings,
  73. GoogleApiSettings,
  74. LayoutSettings,
  75. )
  76. from coderedcms.wagtail_flexible_forms.blocks import FormFieldBlock, FormStepBlock
  77. from coderedcms.wagtail_flexible_forms.models import (
  78. Step,
  79. Steps,
  80. StreamFormMixin,
  81. StreamFormJSONEncoder,
  82. SessionFormSubmission,
  83. SubmissionRevision,
  84. )
  85. from coderedcms.settings import cr_settings
  86. from coderedcms.widgets import ClassifierSelectWidget
  87. if TYPE_CHECKING:
  88. from wagtail.images.models import AbstractImage
  89. logger = logging.getLogger('coderedcms')
  90. CODERED_PAGE_MODELS = []
  91. def get_page_models():
  92. return CODERED_PAGE_MODELS
  93. class CoderedPageMeta(PageBase):
  94. def __init__(cls, name, bases, dct):
  95. super().__init__(name, bases, dct)
  96. if 'search_db_include' not in dct:
  97. cls.search_db_include = False
  98. if 'search_db_boost' not in dct:
  99. cls.search_db_boost = 0
  100. if 'search_filterable' not in dct:
  101. cls.search_filterable = False
  102. if 'search_name' not in dct:
  103. cls.search_name = cls._meta.verbose_name
  104. if 'search_name_plural' not in dct:
  105. cls.search_name_plural = cls._meta.verbose_name_plural
  106. if 'search_template' not in dct:
  107. cls.search_template = 'coderedcms/pages/search_result.html'
  108. if not cls._meta.abstract:
  109. CODERED_PAGE_MODELS.append(cls)
  110. class CoderedTag(TaggedItemBase):
  111. class Meta:
  112. verbose_name = _('CodeRed Tag')
  113. content_object = ParentalKey('coderedcms.CoderedPage', related_name='tagged_items')
  114. class CoderedPage(WagtailCacheMixin, SeoMixin, Page, metaclass=CoderedPageMeta):
  115. """
  116. General use page with caching, templating, and SEO functionality.
  117. All pages should inherit from this.
  118. """
  119. class Meta:
  120. verbose_name = _('CodeRed Page')
  121. # Do not allow this page type to be created in wagtail admin
  122. is_creatable = False
  123. # Templates
  124. # The page will render the following templates under certain conditions:
  125. #
  126. # template = ''
  127. # ajax_template = ''
  128. # search_template = ''
  129. ###############
  130. # Content fields
  131. ###############
  132. cover_image = models.ForeignKey(
  133. get_image_model_string(),
  134. null=True,
  135. blank=True,
  136. on_delete=models.SET_NULL,
  137. related_name='+',
  138. verbose_name=_('Cover image'),
  139. )
  140. ###############
  141. # Index fields
  142. ###############
  143. # Subclasses can override this to enabled index features by default.
  144. index_show_subpages_default = False
  145. # Subclasses can override this to query on a specific
  146. # page model, rather than the default wagtail Page.
  147. index_query_pagemodel = 'coderedcms.CoderedPage'
  148. # Subclasses can override these fields to enable custom
  149. # ordering based on specific subpage fields.
  150. index_order_by_default = ''
  151. index_order_by_choices = (
  152. ('', _('Default Ordering')),
  153. ('-first_published_at', _('Date first published, newest to oldest')),
  154. ('first_published_at', _('Date first published, oldest to newest')),
  155. ('-last_published_at', _('Date updated, newest to oldest')),
  156. ('last_published_at', _('Date updated, oldest to newest')),
  157. ('title', _('Title, alphabetical')),
  158. ('-title', _('Title, reverse alphabetical')),
  159. )
  160. index_show_subpages = models.BooleanField(
  161. default=index_show_subpages_default,
  162. verbose_name=_('Show list of child pages')
  163. )
  164. index_order_by_classifier = models.ForeignKey(
  165. 'coderedcms.Classifier',
  166. blank=True,
  167. null=True,
  168. on_delete=models.SET_NULL,
  169. related_name="+",
  170. verbose_name=_('Order child pages by classifier'),
  171. help_text=_(
  172. 'Child pages will first be sorted following the order of this '
  173. 'classifier’s terms (from Snippets > Classifiers).'
  174. )
  175. )
  176. index_order_by = models.CharField(
  177. max_length=255,
  178. choices=index_order_by_choices,
  179. default=index_order_by_default,
  180. blank=True,
  181. verbose_name=_('Order child pages by'),
  182. help_text=_('Child pages will then be sorted by this attribute.')
  183. )
  184. index_num_per_page = models.PositiveIntegerField(
  185. default=10,
  186. verbose_name=_('Number per page'),
  187. )
  188. index_classifiers = ParentalManyToManyField(
  189. 'coderedcms.Classifier',
  190. blank=True,
  191. verbose_name=_('Filter child pages by'),
  192. help_text=_('Enable filtering child pages by these classifiers.'),
  193. )
  194. ###############
  195. # Layout fields
  196. ###############
  197. custom_template = models.CharField(
  198. blank=True,
  199. max_length=255,
  200. choices=None,
  201. verbose_name=_('Template')
  202. )
  203. ###############
  204. # SEO overrides
  205. ###############
  206. seo_image_sources = [
  207. "og_image",
  208. "cover_image",
  209. ]
  210. ###############
  211. # Classify
  212. ###############
  213. classifier_terms = ParentalManyToManyField(
  214. 'coderedcms.ClassifierTerm',
  215. blank=True,
  216. verbose_name=_('Classifiers'),
  217. help_text=_('Categorize and group pages together with classifiers. Used to organize and filter pages across the site.'), # noqa
  218. )
  219. tags = ClusterTaggableManager(
  220. through=CoderedTag,
  221. blank=True,
  222. verbose_name=_('Tags'),
  223. help_text=_('Used to organize pages across the site.'),
  224. )
  225. ###############
  226. # Settings
  227. ###############
  228. content_walls = StreamField(
  229. [
  230. ('content_wall', ContentWallBlock())
  231. ],
  232. blank=True,
  233. verbose_name=_('Content Walls')
  234. )
  235. ###############
  236. # Search
  237. ###############
  238. search_fields = [
  239. index.SearchField('title', partial_match=True, boost=3),
  240. index.SearchField('seo_title', partial_match=True, boost=3),
  241. index.SearchField('search_description', boost=2),
  242. index.FilterField('title'),
  243. index.FilterField('id'),
  244. index.FilterField('live'),
  245. index.FilterField('owner'),
  246. index.FilterField('content_type'),
  247. index.FilterField('path'),
  248. index.FilterField('depth'),
  249. index.FilterField('locked'),
  250. index.FilterField('first_published_at'),
  251. index.FilterField('last_published_at'),
  252. index.FilterField('latest_revision_created_at'),
  253. index.FilterField('index_show_subpages'),
  254. index.FilterField('index_order_by'),
  255. index.FilterField('custom_template'),
  256. index.FilterField('classifier_terms'),
  257. ]
  258. ###############
  259. # Panels
  260. ###############
  261. content_panels = Page.content_panels + [
  262. ImageChooserPanel('cover_image'),
  263. ]
  264. body_content_panels = []
  265. bottom_content_panels = []
  266. classify_panels = [
  267. FieldPanel('classifier_terms', widget=ClassifierSelectWidget()),
  268. FieldPanel('tags'),
  269. ]
  270. layout_panels = [
  271. MultiFieldPanel(
  272. [
  273. FieldPanel('custom_template')
  274. ],
  275. heading=_('Visual Design')
  276. ),
  277. MultiFieldPanel(
  278. [
  279. FieldPanel('index_show_subpages'),
  280. FieldPanel('index_num_per_page'),
  281. FieldPanel('index_order_by_classifier'),
  282. FieldPanel('index_order_by'),
  283. FieldPanel('index_classifiers', widget=forms.CheckboxSelectMultiple()),
  284. ],
  285. heading=_('Show Child Pages')
  286. )
  287. ]
  288. promote_panels = SeoMixin.seo_meta_panels + SeoMixin.seo_struct_panels
  289. settings_panels = Page.settings_panels + [
  290. StreamFieldPanel('content_walls'),
  291. ]
  292. integration_panels = []
  293. def __init__(self, *args, **kwargs):
  294. """
  295. Inject custom choices and defaults into the form fields
  296. to enable customization by subclasses.
  297. """
  298. super().__init__(*args, **kwargs)
  299. klassname = self.__class__.__name__.lower()
  300. template_choices = cr_settings['FRONTEND_TEMPLATES_PAGES'].get('*', ()) + \
  301. cr_settings['FRONTEND_TEMPLATES_PAGES'].get(klassname, ())
  302. self._meta.get_field('index_order_by').choices = self.index_order_by_choices
  303. self._meta.get_field('custom_template').choices = template_choices
  304. if not self.id:
  305. self.index_order_by = self.index_order_by_default
  306. self.index_show_subpages = self.index_show_subpages_default
  307. @cached_classmethod
  308. def get_edit_handler(cls):
  309. """
  310. Override to "lazy load" the panels overridden by subclasses.
  311. """
  312. panels = [
  313. ObjectList(
  314. cls.content_panels + cls.body_content_panels + cls.bottom_content_panels,
  315. heading=_('Content')
  316. ),
  317. ObjectList(cls.classify_panels, heading=_('Classify')),
  318. ObjectList(cls.layout_panels, heading=_('Layout')),
  319. ObjectList(cls.promote_panels, heading=_('SEO'), classname="seo"),
  320. ObjectList(cls.settings_panels, heading=_('Settings'), classname="settings"),
  321. ]
  322. if cls.integration_panels:
  323. panels.append(ObjectList(
  324. cls.integration_panels,
  325. heading='Integrations',
  326. classname='integrations'
  327. ))
  328. return TabbedInterface(panels).bind_to(model=cls)
  329. @property
  330. def seo_logo(self) -> "Optional[AbstractImage]":
  331. """
  332. Override method in SeoMixin.
  333. Gets the primary logo of the organization.
  334. """
  335. logo = super().seo_logo
  336. if logo:
  337. return logo
  338. else:
  339. layout_settings = LayoutSettings.for_site(self.get_site())
  340. if layout_settings.logo:
  341. return layout_settings.logo
  342. return None
  343. @property
  344. def seo_image(self) -> "Optional[AbstractImage]":
  345. """
  346. Override method in SeoMixin.
  347. Fallback to logo if opengraph image is not specified.
  348. """
  349. img = super().seo_image
  350. if img is None:
  351. return self.seo_logo
  352. return img
  353. @property
  354. def seo_twitter_card_content(self) -> str:
  355. """
  356. Override of method in SeoMixin.
  357. Show a large twitter card if the page has an image set.
  358. """
  359. if self.seo_image:
  360. return TwitterCard.LARGE.value
  361. return self.seo_twitter_card.value
  362. def get_template(self, request, *args, **kwargs):
  363. """
  364. Override parent to serve different templates based on querystring.
  365. """
  366. if self.custom_template:
  367. return self.custom_template
  368. return super().get_template(request, args, kwargs)
  369. def get_index_children(self):
  370. """
  371. Returns query of subpages as defined by `index_` variables.
  372. """
  373. if self.index_query_pagemodel:
  374. querymodel = resolve_model_string(self.index_query_pagemodel, self._meta.app_label)
  375. query = querymodel.objects.child_of(self).live()
  376. else:
  377. query = self.get_children().live()
  378. # Determine query sorting order.
  379. order = []
  380. # To sort by term order of a specific classifier, annotate the child
  381. # pages with the `sort_order` of its ClassifierTerms.
  382. if self.index_order_by_classifier:
  383. terms = ClassifierTerm.objects.filter(
  384. classifier=self.index_order_by_classifier,
  385. # Reverse ManyToMany of `coderedpage.classifier_terms`.
  386. coderedpage=models.OuterRef("pk"),
  387. )
  388. query = query.annotate(
  389. term_sort_order=models.Subquery(terms.values("sort_order"))
  390. )
  391. order.append("term_sort_order")
  392. # Second, order by the specified model attribute.
  393. if self.index_order_by:
  394. order.append(self.index_order_by)
  395. # Order the query.
  396. if order:
  397. query = query.order_by(*order)
  398. return query
  399. def get_content_walls(self, check_child_setting=True):
  400. current_content_walls = []
  401. if check_child_setting:
  402. for wall in self.content_walls:
  403. if wall.value['show_content_wall_on_children']:
  404. current_content_walls.append(wall.value)
  405. else:
  406. current_content_walls = self.content_walls
  407. try:
  408. return list(current_content_walls) + self.get_parent().specific.get_content_walls()
  409. except AttributeError:
  410. return list(current_content_walls)
  411. def get_context(self, request, *args, **kwargs):
  412. """
  413. Add child pages and paginated child pages to context.
  414. """
  415. context = super().get_context(request)
  416. if self.index_show_subpages:
  417. # Get child pages
  418. all_children = self.get_index_children()
  419. # Filter by classifier terms if applicable
  420. if len(request.GET) > 0 and self.index_classifiers.exists():
  421. # Look up comma separated ClassifierTerm slugs i.e. `/?c=term1-slug,term2-slug`
  422. terms = []
  423. get_c = request.GET.get('c', None)
  424. if get_c:
  425. terms = get_c.split(',')
  426. # Else look up individual querystrings i.e. `/?classifier-slug=term1-slug`
  427. else:
  428. for classifier in self.index_classifiers.all().only('slug'):
  429. get_term = request.GET.get(classifier.slug, None)
  430. if get_term:
  431. terms.append(get_term)
  432. if len(terms) > 0:
  433. selected_terms = ClassifierTerm.objects.filter(slug__in=terms)
  434. context['selected_terms'] = selected_terms
  435. if len(selected_terms) > 0:
  436. try:
  437. for term in selected_terms:
  438. all_children = all_children.filter(classifier_terms=term)
  439. except AttributeError:
  440. logger.warning(
  441. "Tried to filter by ClassifierTerm, but <%s.%s ('%s')>.get_index_children() did not return a queryset or is not a queryset of CoderedPage models.", # noqa
  442. self._meta.app_label,
  443. self.__class__.__name__,
  444. self.title
  445. )
  446. paginator = Paginator(all_children, self.index_num_per_page)
  447. pagenum = request.GET.get('p', 1)
  448. try:
  449. paged_children = paginator.page(pagenum)
  450. except (PageNotAnInteger, EmptyPage, InvalidPage) as e: # noqa
  451. paged_children = paginator.page(1)
  452. context['index_paginated'] = paged_children
  453. context['index_children'] = all_children
  454. context['content_walls'] = self.get_content_walls(check_child_setting=False)
  455. return context
  456. ###############################################################################
  457. # Abstract pages providing pre-built common website functionality, suitable for subclassing.
  458. # These are abstract so subclasses can override fields if desired.
  459. ###############################################################################
  460. class CoderedWebPage(CoderedPage):
  461. """
  462. Provides a body and body-related functionality.
  463. This is abstract so that subclasses can override the body StreamField.
  464. """
  465. class Meta:
  466. verbose_name = _('CodeRed Web Page')
  467. abstract = True
  468. template = 'coderedcms/pages/web_page.html'
  469. # Child pages should override based on what blocks they want in the body.
  470. # Default is LAYOUT_STREAMBLOCKS which is the fullest editor experience.
  471. body = StreamField(LAYOUT_STREAMBLOCKS, null=True, blank=True)
  472. # Search fields
  473. search_fields = (
  474. CoderedPage.search_fields +
  475. [index.SearchField('body')]
  476. )
  477. # Panels
  478. body_content_panels = [
  479. StreamFieldPanel('body'),
  480. ]
  481. @property
  482. def body_preview(self):
  483. """
  484. A shortened version of the body without HTML tags.
  485. """
  486. # add spaces between tags for legibility
  487. body = str(self.body).replace('>', '> ')
  488. # strip tags
  489. body = strip_tags(body)
  490. # truncate and add ellipses
  491. preview = body[:200] + "..." if len(body) > 200 else body
  492. return mark_safe(preview)
  493. @property
  494. def page_ptr(self):
  495. """
  496. Overwrite of `page_ptr` to make it compatible with wagtailimportexport.
  497. """
  498. return self.base_page_ptr
  499. @page_ptr.setter
  500. def page_ptr(self, value):
  501. self.base_page_ptr = value
  502. class CoderedArticlePage(CoderedWebPage):
  503. """
  504. Article, suitable for news or blog content.
  505. """
  506. class Meta:
  507. verbose_name = _('CodeRed Article')
  508. abstract = True
  509. template = 'coderedcms/pages/article_page.html'
  510. # Override body to provide simpler content
  511. body = StreamField(CONTENT_STREAMBLOCKS, null=True, blank=True)
  512. caption = models.CharField(
  513. max_length=255,
  514. blank=True,
  515. verbose_name=_('Caption'),
  516. )
  517. author = models.ForeignKey(
  518. settings.AUTH_USER_MODEL,
  519. null=True,
  520. blank=True,
  521. editable=True,
  522. on_delete=models.SET_NULL,
  523. verbose_name=_('Author'),
  524. )
  525. author_display = models.CharField(
  526. max_length=255,
  527. blank=True,
  528. verbose_name=_('Display author as'),
  529. help_text=_('Override how the author’s name displays on this article.'),
  530. )
  531. date_display = models.DateField(
  532. null=True,
  533. blank=True,
  534. verbose_name=_('Display publish date'),
  535. )
  536. def get_author_name(self):
  537. warnings.warn(
  538. ("CoderedArticlePage.get_author_name has been replaced with "
  539. "CoderedArticlePage.seo_author"),
  540. DeprecationWarning,
  541. )
  542. return self.seo_author
  543. @property
  544. def seo_author(self) -> str:
  545. """
  546. Override of method in SeoMixin.
  547. Gets author name using a fallback.
  548. """
  549. if self.author_display:
  550. return self.author_display
  551. if self.author:
  552. return self.author.get_full_name()
  553. if self.owner:
  554. return self.owner.get_full_name()
  555. return ""
  556. def get_pub_date(self):
  557. warnings.warn(
  558. ("CoderedArticlePage.get_pub_date has been replaced with "
  559. "CoderedArticlePage.seo_published_at"),
  560. DeprecationWarning,
  561. )
  562. return self.seo_published_at
  563. @property
  564. def seo_published_at(self) -> datetime:
  565. """
  566. Override of method in SeoMixin.
  567. Gets published date.
  568. """
  569. if self.date_display:
  570. return self.date_display
  571. return self.first_published_at
  572. def get_description(self):
  573. warnings.warn(
  574. ("CoderedArticlePage.get_description has been replaced with "
  575. "CoderedArticlePage.seo_description"),
  576. DeprecationWarning,
  577. )
  578. return self.seo_description
  579. @property
  580. def seo_description(self) -> str:
  581. """
  582. Override of method in SeoMixin.
  583. Gets the description using a fallback.
  584. """
  585. if self.search_description:
  586. return self.search_description
  587. if self.caption:
  588. return self.caption
  589. if self.body_preview:
  590. return self.body_preview
  591. return ""
  592. search_fields = (
  593. CoderedWebPage.search_fields +
  594. [
  595. index.SearchField('caption', boost=2),
  596. index.FilterField('author'),
  597. index.FilterField('author_display'),
  598. index.FilterField('date_display'),
  599. ]
  600. )
  601. content_panels = CoderedWebPage.content_panels + [
  602. FieldPanel('caption'),
  603. MultiFieldPanel(
  604. [
  605. FieldPanel('author'),
  606. FieldPanel('author_display'),
  607. FieldPanel('date_display'),
  608. ],
  609. _('Publication Info')
  610. )
  611. ]
  612. class CoderedArticleIndexPage(CoderedWebPage):
  613. """
  614. Shows a list of article sub-pages.
  615. """
  616. class Meta:
  617. verbose_name = _('CodeRed Article Index Page')
  618. abstract = True
  619. template = 'coderedcms/pages/article_index_page.html'
  620. index_show_subpages_default = True
  621. index_order_by_default = '-date_display'
  622. index_order_by_choices = (('-date_display', 'Display publish date, newest first'),) + \
  623. CoderedWebPage.index_order_by_choices
  624. show_images = models.BooleanField(
  625. default=True,
  626. verbose_name=_('Show images'),
  627. )
  628. show_captions = models.BooleanField(
  629. default=True,
  630. )
  631. show_meta = models.BooleanField(
  632. default=True,
  633. verbose_name=_('Show author and date info'),
  634. )
  635. show_preview_text = models.BooleanField(
  636. default=True,
  637. verbose_name=_('Show preview text'),
  638. )
  639. layout_panels = CoderedWebPage.layout_panels + [
  640. MultiFieldPanel(
  641. [
  642. FieldPanel('show_images'),
  643. FieldPanel('show_captions'),
  644. FieldPanel('show_meta'),
  645. FieldPanel('show_preview_text'),
  646. ],
  647. heading=_('Child page display')
  648. ),
  649. ]
  650. class CoderedEventPage(CoderedWebPage, BaseEvent):
  651. class Meta:
  652. verbose_name = _('CodeRed Event')
  653. abstract = True
  654. calendar_color = ColorField(
  655. blank=True,
  656. help_text=_('The color that the event will use when displayed on a calendar.'),
  657. )
  658. address = models.TextField(
  659. blank=True,
  660. verbose_name=_("Address")
  661. )
  662. content_panels = CoderedWebPage.content_panels + [
  663. MultiFieldPanel(
  664. [
  665. FieldPanel('calendar_color'),
  666. FieldPanel('address'),
  667. ],
  668. heading=_('Event information')
  669. ),
  670. InlinePanel(
  671. 'occurrences',
  672. min_num=1,
  673. heading=_("Dates and times"),
  674. ),
  675. ]
  676. @property
  677. def upcoming_occurrences(self):
  678. """
  679. Returns the next x occurrences for this event.
  680. By default, it returns 10.
  681. """
  682. return self.query_occurrences(num_of_instances_to_return=10)
  683. @property
  684. def most_recent_occurrence(self):
  685. """
  686. Gets the next upcoming, or last occurrence if the event has no more occurrences.
  687. """
  688. try:
  689. noc = self.next_occurrence()
  690. if noc:
  691. return noc
  692. aoc = []
  693. for occurrence in self.occurrences.all():
  694. aoc += [instance for instance in occurrence.all_occurrences()]
  695. if len(aoc) > 0:
  696. return aoc[-1] # last one in the list
  697. except AttributeError:
  698. # Triggers when a preview is initiated on an
  699. # EventPage because it uses a FakeQuerySet object.
  700. # Here we manually compute the next_occurrence
  701. occurrences = [e.next_occurrence() for e in self.occurrences.all()]
  702. if occurrences:
  703. return sorted(occurrences, key=lambda tup: tup[0])[0]
  704. @property
  705. def seo_struct_event_dict(self) -> dict:
  706. next_occ = self.most_recent_occurrence
  707. sd_dict = {
  708. "@context": "https://schema.org/",
  709. "@type": "Event",
  710. "name": self.title,
  711. "description": self.seo_description,
  712. "startDate": next_occ.start,
  713. "endDate": next_occ.end,
  714. "mainEntityOfPage": {
  715. "@type": "WebPage",
  716. "@id": self.get_full_url,
  717. },
  718. }
  719. if self.seo_image:
  720. sd_dict.update({"image": get_struct_data_images(self.seo_image)})
  721. if self.address:
  722. sd_dict.update({
  723. "location": {
  724. "@type": "Place",
  725. "name": self.title,
  726. "address": {
  727. "@type": "PostalAddress",
  728. "streetAddress": self.address,
  729. },
  730. },
  731. })
  732. return sd_dict
  733. @property
  734. def seo_struct_event_json(self) -> str:
  735. return json.dumps(self.seo_struct_event_dict, cls=StructDataEncoder)
  736. def query_occurrences(self, num_of_instances_to_return=None, **kwargs):
  737. """
  738. Returns a list of all upcoming event instances for the specified query.
  739. For more information on what you can query with, visit
  740. https://github.com/gregplaysguitar/django-eventtools
  741. """
  742. event_instances = []
  743. occurrence_kwargs = {
  744. 'from_date': kwargs.get('from_date', timezone.now().date())
  745. }
  746. if 'limit' in kwargs:
  747. if kwargs['limit'] is not None:
  748. # Limit the number of event instances that will be
  749. # generated per occurrence rule to 10, if not otherwise specified.
  750. occurrence_kwargs['limit'] = kwargs.get('limit', 10)
  751. # For each occurrence rule in all of the occurrence rules for this event.
  752. for occurrence in self.occurrences.all():
  753. # Add the qualifying generated event instances to the list.
  754. event_instances += [
  755. instance for instance in occurrence.all_occurrences(**occurrence_kwargs)]
  756. # Sort all the events by the date that they start
  757. event_instances.sort(key=lambda d: d[0])
  758. # Return the event instances, possibly spliced if num_instances_to_return is set.
  759. return event_instances[:num_of_instances_to_return] if num_of_instances_to_return else event_instances # noqa
  760. def convert_to_ical_format(self, dt_start=None, dt_end=None, occurrence=None):
  761. ical_event = ICalEvent()
  762. ical_event.add('summary', self.title)
  763. if self.address:
  764. ical_event.add('location', self.address)
  765. if dt_start:
  766. ical_event.add('dtstart', dt_start)
  767. if dt_end:
  768. ical_event.add('dtend', dt_end)
  769. if occurrence:
  770. freq = occurrence.repeat.split(":")[1] if occurrence.repeat else None
  771. repeat_until = occurrence.repeat_until.strftime(
  772. "%Y%m%dT000000Z") if occurrence.repeat_until else None
  773. ical_event.add('dtstart', occurrence.start)
  774. if occurrence.end:
  775. ical_event.add('dtend', occurrence.end)
  776. if freq:
  777. ical_event.add('RRULE', freq, encode=False)
  778. if repeat_until:
  779. ical_event.add('until', repeat_until)
  780. return ical_event
  781. def create_single_ical(self, dt_start, dt_end=None):
  782. return self.convert_to_ical_format(dt_start=dt_start, dt_end=dt_end)
  783. def create_recurring_ical(self):
  784. events = []
  785. for occurrence in self.occurrences.all():
  786. events.append(self.convert_to_ical_format(occurrence=occurrence))
  787. return events
  788. class CoderedEventIndexPage(CoderedWebPage):
  789. """
  790. Shows a list of event sub-pages.
  791. """
  792. class Meta:
  793. verbose_name = _('CodeRed Event Index Page')
  794. abstract = True
  795. class CalendarViews(models.TextChoices):
  796. NONE = '', _('No calendar')
  797. MONTH = 'month', _('Month')
  798. AGENDA_WEEK = 'agendaWeek', _('Week')
  799. AGENDA_DAY = 'agendaDay', _('Day')
  800. LIST_MONTH = 'listMonth', _('List of events')
  801. class EventStyles(models.TextChoices):
  802. DEFAULT = '', _('Default')
  803. BLOCK = 'block', _('Solid rectangles')
  804. DOT = 'list-item', _('Dots with labels')
  805. template = 'coderedcms/pages/event_index_page.html'
  806. index_show_subpages_default = True
  807. index_order_by_default = 'next_occurrence'
  808. index_order_by_choices = (
  809. ('next_occurrence', 'Display next occurrence, soonest first'),
  810. ) + CoderedWebPage.index_order_by_choices
  811. default_calendar_view = models.CharField(
  812. blank=True,
  813. choices=CalendarViews.choices,
  814. default=CalendarViews.MONTH,
  815. max_length=255,
  816. verbose_name=_('Calendar Style'),
  817. help_text=_('The default look of the calendar on this page.')
  818. )
  819. event_style = models.CharField(
  820. blank=True,
  821. choices=EventStyles.choices,
  822. default=EventStyles.DEFAULT,
  823. max_length=255,
  824. verbose_name=_('Event Style'),
  825. help_text=_('How events look on the calendar.')
  826. )
  827. layout_panels = CoderedWebPage.layout_panels + [
  828. MultiFieldPanel(
  829. [
  830. FieldPanel('default_calendar_view'),
  831. FieldPanel('event_style'),
  832. ],
  833. heading=_('Calendar Style'),
  834. )
  835. ]
  836. @property
  837. def fullcalendar_view(self) -> str:
  838. """
  839. Translate calendar views to fullcalendar.js identifiers.
  840. """
  841. return {
  842. self.CalendarViews.NONE: '',
  843. self.CalendarViews.MONTH: 'dayGridMonth',
  844. self.CalendarViews.AGENDA_WEEK: 'timeGridWeek',
  845. self.CalendarViews.AGENDA_DAY: 'timeGridDay',
  846. self.CalendarViews.LIST_MONTH: 'listMonth',
  847. }[self.default_calendar_view]
  848. @property
  849. def fullcalendar_event_display(self) -> str:
  850. """
  851. Translate event display styles to fullcalendar.js identifiers.
  852. """
  853. return {
  854. self.EventStyles.DEFAULT: 'auto',
  855. self.EventStyles.BLOCK: 'block',
  856. self.EventStyles.DOT: 'list-item',
  857. }[self.event_style]
  858. def get_index_children(self):
  859. if self.index_query_pagemodel and self.index_order_by == 'next_occurrence':
  860. querymodel = resolve_model_string(self.index_query_pagemodel, self._meta.app_label)
  861. qs = querymodel.objects.child_of(self).live()
  862. # filter out events that don't have a next_occurrence
  863. upcoming = []
  864. for event in qs.all():
  865. if event.next_occurrence():
  866. upcoming.append(event)
  867. # Sort the events by next_occurrence start date.
  868. return sorted(upcoming, key=lambda e: e.next_occurrence()[0])
  869. return super().get_index_children()
  870. def get_calendar_events(
  871. self,
  872. start: Union[datetime, date],
  873. end: Union[datetime, date]
  874. ) -> List[Dict[str, str]]:
  875. """
  876. Returns a list of event occurrences as dictionaries with times
  877. converted to Django TIME_ZONE settings.
  878. """
  879. # start with all child events, regardless of get_index_children rules.
  880. querymodel = resolve_model_string(self.index_query_pagemodel, self._meta.app_label)
  881. qs = querymodel.objects.child_of(self).live()
  882. event_instances = []
  883. for event in qs:
  884. occurrences = event.query_occurrences(limit=None, from_date=start, to_date=end)
  885. for occurrence in occurrences:
  886. local_start = timezone.localtime(value=occurrence[0])
  887. local_end = None
  888. if occurrence[1]:
  889. local_end = timezone.localtime(value=occurrence[1])
  890. event_data = {
  891. 'title': event.title,
  892. 'start': local_start.strftime('%Y-%m-%dT%H:%M:%S%z'),
  893. 'end': local_end.strftime('%Y-%m-%dT%H:%M:%S%z') if local_end else "",
  894. 'description': "",
  895. }
  896. if event.url:
  897. event_data['url'] = event.url
  898. if event.calendar_color:
  899. event_data['color'] = event.calendar_color
  900. event_instances.append(event_data)
  901. return event_instances
  902. class CoderedEventOccurrence(Orderable, BaseOccurrence):
  903. class Meta:
  904. verbose_name = _('CodeRed Event Occurrence')
  905. abstract = True
  906. class CoderedFormMixin(models.Model):
  907. class Meta:
  908. abstract = True
  909. submissions_list_view_class = CoderedSubmissionsListView
  910. encoder = DjangoJSONEncoder
  911. # Custom codered fields
  912. to_address = models.CharField(
  913. max_length=255,
  914. blank=True,
  915. verbose_name=_('Email form submissions to'),
  916. help_text=_('Optional - email form submissions to this address. Separate multiple addresses by comma.'), # noqa
  917. )
  918. reply_address = models.CharField(
  919. max_length=255,
  920. blank=True,
  921. verbose_name=_('Reply-to address'),
  922. help_text=_('Optional - to reply to the submitter, specify the email field here. For example, if a form field above is labeled "Your Email", enter: {{ your_email }}'), # noqa
  923. )
  924. subject = models.CharField(
  925. max_length=255,
  926. blank=True,
  927. verbose_name=_('Subject'),
  928. )
  929. save_to_database = models.BooleanField(
  930. default=True,
  931. verbose_name=_('Save form submissions'),
  932. help_text=_('Submissions are saved to database and can be exported at any time.')
  933. )
  934. thank_you_page = models.ForeignKey(
  935. 'wagtailcore.Page',
  936. null=True,
  937. blank=True,
  938. on_delete=models.SET_NULL,
  939. related_name='+',
  940. verbose_name=_('Thank you page'),
  941. help_text=_('The page users are redirected to after submitting the form.'),
  942. )
  943. button_text = models.CharField(
  944. max_length=255,
  945. default=_('Submit'),
  946. verbose_name=_('Button text'),
  947. )
  948. button_style = models.CharField(
  949. blank=True,
  950. choices=cr_settings['FRONTEND_BTN_STYLE_CHOICES'],
  951. default=cr_settings["FRONTEND_BTN_STYLE_DEFAULT"],
  952. max_length=255,
  953. verbose_name=_('Button style'),
  954. )
  955. button_size = models.CharField(
  956. blank=True,
  957. choices=cr_settings['FRONTEND_BTN_SIZE_CHOICES'],
  958. default=cr_settings["FRONTEND_BTN_SIZE_DEFAULT"],
  959. max_length=255,
  960. verbose_name=_('Button Size'),
  961. )
  962. button_css_class = models.CharField(
  963. max_length=255,
  964. blank=True,
  965. verbose_name=_('Button CSS class'),
  966. help_text=_('Custom CSS class applied to the submit button.'),
  967. )
  968. form_css_class = models.CharField(
  969. max_length=255,
  970. blank=True,
  971. verbose_name=_('Form CSS Class'),
  972. help_text=_('Custom CSS class applied to <form> element.'),
  973. )
  974. form_id = models.CharField(
  975. max_length=255,
  976. blank=True,
  977. verbose_name=_('Form ID'),
  978. help_text=_('Custom ID applied to <form> element.'),
  979. )
  980. form_golive_at = models.DateTimeField(
  981. blank=True,
  982. null=True,
  983. verbose_name=_('Form go live date/time'),
  984. help_text=_('Date and time when the FORM goes live on the page.'),
  985. )
  986. form_expire_at = models.DateTimeField(
  987. blank=True,
  988. null=True,
  989. verbose_name=_('Form expiry date/time'),
  990. help_text=_('Date and time when the FORM will no longer be available on the page.'),
  991. )
  992. spam_protection = models.BooleanField(
  993. default=True,
  994. verbose_name=_('Spam Protection'),
  995. help_text=_('When enabled, the CMS will filter out spam form submissions for this page.')
  996. )
  997. body_content_panels = [
  998. MultiFieldPanel(
  999. [
  1000. PageChooserPanel('thank_you_page'),
  1001. FieldPanel('button_text'),
  1002. FieldPanel('button_style'),
  1003. FieldPanel('button_size'),
  1004. FieldPanel('button_css_class'),
  1005. FieldPanel('form_css_class'),
  1006. FieldPanel('form_id'),
  1007. ],
  1008. _('Form Settings')
  1009. ),
  1010. MultiFieldPanel(
  1011. [
  1012. FieldPanel('save_to_database'),
  1013. FieldPanel('to_address'),
  1014. FieldPanel('reply_address'),
  1015. FieldPanel('subject'),
  1016. ],
  1017. _('Form Submissions')
  1018. ),
  1019. ]
  1020. settings_panels = [
  1021. MultiFieldPanel(
  1022. [
  1023. FieldRowPanel(
  1024. [
  1025. FieldPanel('form_golive_at'),
  1026. FieldPanel('form_expire_at'),
  1027. ],
  1028. classname='label-above',
  1029. ),
  1030. ],
  1031. _('Form Scheduled Publishing'),
  1032. ),
  1033. FieldPanel('spam_protection')
  1034. ]
  1035. @property
  1036. def form_live(self):
  1037. """
  1038. A boolean on whether or not the <form> element should be shown on the page.
  1039. """
  1040. return (self.form_golive_at is None or self.form_golive_at <= timezone.now()) and \
  1041. (self.form_expire_at is None or self.form_expire_at >= timezone.now())
  1042. def get_landing_page_template(self, request, *args, **kwargs):
  1043. return self.landing_page_template
  1044. def process_data(self, form, request):
  1045. processed_data = {}
  1046. # Handle file uploads
  1047. for key, val in form.cleaned_data.items():
  1048. if type(val) == InMemoryUploadedFile or type(val) == TemporaryUploadedFile:
  1049. # Save the file and get its URL
  1050. # Custom code to ensure that anonymous users get a session key.
  1051. if not request.session.session_key:
  1052. request.session.create()
  1053. directory = request.session.session_key
  1054. storage = self.get_storage()
  1055. Path(storage.path(directory)).mkdir(parents=True,
  1056. exist_ok=True)
  1057. path = storage.get_available_name(
  1058. str(Path(directory) / val.name))
  1059. with storage.open(path, 'wb+') as destination:
  1060. for chunk in val.chunks():
  1061. destination.write(chunk)
  1062. processed_data[key] = "{0}{1}".format(cr_settings['PROTECTED_MEDIA_URL'], path)
  1063. else:
  1064. processed_data[key] = val
  1065. return processed_data
  1066. def get_storage(self):
  1067. return FileSystemStorage(
  1068. location=cr_settings['PROTECTED_MEDIA_ROOT'],
  1069. base_url=cr_settings['PROTECTED_MEDIA_URL']
  1070. )
  1071. def process_form_submission(self, request, form, form_submission, processed_data):
  1072. # Save to database
  1073. if self.save_to_database:
  1074. form_submission.save()
  1075. # Send the mails
  1076. if self.to_address:
  1077. self.send_summary_mail(request, form, processed_data)
  1078. if self.confirmation_emails:
  1079. # Convert form data into a context.
  1080. context = Context(self.data_to_dict(processed_data, request))
  1081. # Render emails as if they are django templates.
  1082. for email in self.confirmation_emails.all():
  1083. # Build email message parameters.
  1084. message_args = {}
  1085. # From
  1086. if email.from_address:
  1087. template_from_email = Template(email.from_address)
  1088. message_args['from_email'] = template_from_email.render(context)
  1089. else:
  1090. genemail = GeneralSettings.for_request(request).from_email_address
  1091. if genemail:
  1092. message_args['from_email'] = genemail
  1093. # Reply-to
  1094. if email.reply_address:
  1095. template_reply_to = Template(email.reply_address)
  1096. message_args['reply_to'] = template_reply_to.render(context).split(',')
  1097. # CC
  1098. if email.cc_address:
  1099. template_cc = Template(email.cc_address)
  1100. message_args['cc'] = template_cc.render(context).split(',')
  1101. # BCC
  1102. if email.bcc_address:
  1103. template_bcc = Template(email.bcc_address)
  1104. message_args['bcc'] = template_bcc.render(context).split(',')
  1105. # Subject
  1106. if email.subject:
  1107. template_subject = Template(email.subject)
  1108. message_args['subject'] = template_subject.render(context)
  1109. else:
  1110. message_args['subject'] = self.title
  1111. # Body
  1112. template_body = Template(email.body)
  1113. message_args['body'] = template_body.render(context)
  1114. # To
  1115. template_to = Template(email.to_address)
  1116. message_args['to'] = template_to.render(context).split(',')
  1117. # Send email
  1118. self.send_mail(request, message_args, 'html')
  1119. for fn in hooks.get_hooks('form_page_submit'):
  1120. fn(instance=self, form_submission=form_submission)
  1121. def send_summary_mail(self, request, form, processed_data):
  1122. """
  1123. Sends a form submission summary email.
  1124. """
  1125. addresses = [x.strip() for x in self.to_address.split(',')]
  1126. content = []
  1127. for field in self.get_form_fields():
  1128. key = field.clean_name
  1129. label = field.label
  1130. value = processed_data.get(key)
  1131. content.append('{0}: {1}'.format(label, value))
  1132. content = '\n-------------------- \n'.join(content)
  1133. # Build email message parameters
  1134. message_args = {
  1135. 'body': content,
  1136. 'to': addresses,
  1137. }
  1138. if self.subject:
  1139. message_args['subject'] = self.subject
  1140. else:
  1141. message_args['subject'] = self.title
  1142. genemail = GeneralSettings.for_request(request).from_email_address
  1143. if genemail:
  1144. message_args['from_email'] = genemail
  1145. if self.reply_address:
  1146. # Render reply-to field using form submission as context.
  1147. context = Context(self.data_to_dict(processed_data, request))
  1148. template_reply_to = Template(self.reply_address)
  1149. message_args['reply_to'] = template_reply_to.render(context).split(',')
  1150. # Send email
  1151. self.send_mail(request, message_args)
  1152. def send_mail(
  1153. self,
  1154. resuest,
  1155. message_args: dict,
  1156. content_subtype: Optional[str] = None
  1157. ):
  1158. """
  1159. Utility to send email messages from form submissions.
  1160. You can override this method to have the form send mail in a different
  1161. way or using a different backend as needed.
  1162. """
  1163. message = EmailMessage(**message_args)
  1164. if content_subtype:
  1165. message.content_subtype = content_subtype
  1166. message.send()
  1167. def render_landing_page(self, request, form_submission=None):
  1168. """
  1169. Renders the landing page.
  1170. You can override this method to return a different HttpResponse as
  1171. landing page. E.g. you could return a redirect to a separate page.
  1172. """
  1173. if self.thank_you_page:
  1174. return redirect(self.thank_you_page.url)
  1175. context = self.get_context(request)
  1176. context['form_submission'] = form_submission
  1177. response = render(
  1178. request,
  1179. self.get_landing_page_template(request),
  1180. context
  1181. )
  1182. return response
  1183. def data_to_dict(self, processed_data, request):
  1184. """
  1185. Converts processed form data into a dictionary suitable
  1186. for rendering in a context.
  1187. """
  1188. dictionary = {}
  1189. for key, value in processed_data.items():
  1190. new_key = key.replace('-', '_')
  1191. if isinstance(value, list):
  1192. dictionary[new_key] = ', '.join(value)
  1193. else:
  1194. dictionary[new_key] = utils.attempt_protected_media_value_conversion(request, value)
  1195. return dictionary
  1196. preview_modes = [
  1197. ('form', _('Form')),
  1198. ('landing', _('Thank you page')),
  1199. ]
  1200. def serve_preview(self, request, mode):
  1201. if mode == 'landing':
  1202. request.is_preview = True
  1203. return self.render_landing_page(request)
  1204. return super().serve_preview(request, mode)
  1205. def serve_submissions_list_view(self, request, *args, **kwargs):
  1206. """
  1207. Returns list submissions view for admin.
  1208. `list_submissions_view_class` can be set to provide custom view class.
  1209. Your class must be inherited from SubmissionsListView.
  1210. """
  1211. view = self.submissions_list_view_class.as_view()
  1212. return view(request, form_page=self, *args, **kwargs)
  1213. def get_form(self, request, *args, **kwargs):
  1214. form_class = self.get_form_class()
  1215. form_params = self.get_form_parameters()
  1216. form_params.update(kwargs)
  1217. if request.method == 'POST':
  1218. return form_class(request.POST, request.FILES, *args, **form_params)
  1219. return form_class(*args, **form_params)
  1220. def contains_spam(self, request):
  1221. """
  1222. Checks to see if the spam honeypot was filled out.
  1223. """
  1224. if request.POST.get("cr-decoy-comments", None):
  1225. return True
  1226. return False
  1227. def process_spam_request(self, form, request):
  1228. """
  1229. Called when spam is found in the request.
  1230. """
  1231. messages.error(request, self.get_spam_message())
  1232. logger.info("Detected spam submission on page: {0}\n{1}".format(self.title, vars(request)))
  1233. return self.process_form_get(form, request)
  1234. def get_spam_message(self):
  1235. return _("There was an error while processing your submission. Please try again.")
  1236. def process_form_post(self, form, request):
  1237. if form.is_valid():
  1238. processed_data = self.process_data(form, request)
  1239. form_submission = self.get_submission_class()(
  1240. form_data=json.dumps(processed_data, cls=self.encoder),
  1241. page=self,
  1242. )
  1243. self.process_form_submission(
  1244. request=request,
  1245. form=form,
  1246. form_submission=form_submission,
  1247. processed_data=processed_data)
  1248. return self.render_landing_page(request, form_submission)
  1249. return self.process_form_get(form, request)
  1250. def process_form_get(self, form, request):
  1251. context = self.get_context(request)
  1252. context['form'] = form
  1253. response = render(
  1254. request,
  1255. self.get_template(request),
  1256. context
  1257. )
  1258. return response
  1259. def serve(self, request, *args, **kwargs):
  1260. form = self.get_form(request, page=self, user=request.user)
  1261. if request.method == 'POST':
  1262. if self.spam_protection and self.contains_spam(request):
  1263. return self.process_spam_request(form, request)
  1264. return self.process_form_post(form, request)
  1265. return self.process_form_get(form, request)
  1266. class CoderedFormPage(CoderedFormMixin, CoderedWebPage):
  1267. """
  1268. This is basically a clone of wagtail.contrib.forms.models.AbstractForm
  1269. with changes in functionality and extending CoderedWebPage vs wagtailcore.Page.
  1270. """
  1271. class Meta:
  1272. verbose_name = _('CodeRed Form Page')
  1273. abstract = True
  1274. template = 'coderedcms/pages/form_page.html'
  1275. landing_page_template = 'coderedcms/pages/form_page_landing.html'
  1276. base_form_class = WagtailAdminFormPageForm
  1277. form_builder = CoderedFormBuilder
  1278. body_content_panels = [
  1279. InlinePanel('form_fields', label="Form fields"),
  1280. ] + \
  1281. CoderedWebPage.body_content_panels + \
  1282. CoderedFormMixin.body_content_panels + [
  1283. FormSubmissionsPanel(),
  1284. InlinePanel('confirmation_emails', label=_('Confirmation Emails'))
  1285. ]
  1286. settings_panels = CoderedPage.settings_panels + CoderedFormMixin.settings_panels
  1287. def __init__(self, *args, **kwargs):
  1288. super().__init__(*args, **kwargs)
  1289. if not hasattr(self, 'landing_page_template'):
  1290. name, ext = os.path.splitext(self.template)
  1291. self.landing_page_template = name + '_landing' + ext
  1292. def get_form_fields(self):
  1293. """
  1294. Form page expects `form_fields` to be declared.
  1295. If you want to change backwards relation name,
  1296. you need to override this method.
  1297. """
  1298. return self.form_fields.all()
  1299. def get_data_fields(self):
  1300. """
  1301. Returns a list of tuples with (field_name, field_label).
  1302. """
  1303. data_fields = [
  1304. ('submit_time', _('Submission date')),
  1305. ]
  1306. data_fields += [
  1307. (field.clean_name, field.label)
  1308. for field in self.get_form_fields()
  1309. ]
  1310. return data_fields
  1311. def get_form_class(self):
  1312. fb = self.form_builder(self.get_form_fields())
  1313. return fb.get_form_class()
  1314. def get_form_parameters(self):
  1315. return {}
  1316. def get_submission_class(self):
  1317. """
  1318. Returns submission class.
  1319. You can override this method to provide custom submission class.
  1320. Your class must be inherited from AbstractFormSubmission.
  1321. """
  1322. return FormSubmission
  1323. class CoderedSubmissionRevision(SubmissionRevision, models.Model):
  1324. pass
  1325. class CoderedSessionFormSubmission(SessionFormSubmission):
  1326. INCOMPLETE = 'incomplete'
  1327. COMPLETE = 'complete'
  1328. REVIEWED = 'reviewed'
  1329. APPROVED = 'approved'
  1330. REJECTED = 'rejected'
  1331. STATUSES = (
  1332. (INCOMPLETE, _('Not submitted')),
  1333. (COMPLETE, _('Complete')),
  1334. (REVIEWED, _('Under consideration')),
  1335. (APPROVED, _('Approved')),
  1336. (REJECTED, _('Rejected')),
  1337. )
  1338. status = models.CharField(max_length=10, choices=STATUSES, default=INCOMPLETE)
  1339. def create_normal_submission(self, delete_self=True):
  1340. submission_data = self.get_data()
  1341. if 'user' in submission_data:
  1342. submission_data['user'] = str(submission_data['user'])
  1343. submission = FormSubmission.objects.create(
  1344. form_data=json.dumps(submission_data, cls=StreamFormJSONEncoder),
  1345. page=self.page
  1346. )
  1347. if delete_self:
  1348. CoderedSubmissionRevision.objects.filter(submission_id=self.id).delete()
  1349. self.delete()
  1350. return submission
  1351. def render_email(self, value):
  1352. return value
  1353. def render_link(self, value):
  1354. return "{0}{1}".format(cr_settings['PROTECTED_MEDIA_URL'], value)
  1355. def render_image(self, value):
  1356. return "{0}{1}".format(cr_settings['PROTECTED_MEDIA_URL'], value)
  1357. def render_file(self, value):
  1358. return "{0}{1}".format(cr_settings['PROTECTED_MEDIA_URL'], value)
  1359. @receiver(post_save)
  1360. def create_submission_changed_revision(sender, **kwargs):
  1361. if not issubclass(sender, SessionFormSubmission):
  1362. return
  1363. submission = kwargs['instance']
  1364. created = kwargs['created']
  1365. CoderedSubmissionRevision.create_from_submission(
  1366. submission, (CoderedSubmissionRevision.CREATED if created else CoderedSubmissionRevision.CHANGED)) # noqa
  1367. @receiver(post_delete)
  1368. def create_submission_deleted_revision(sender, **kwargs):
  1369. if not issubclass(sender, CoderedSessionFormSubmission):
  1370. return
  1371. submission = kwargs['instance']
  1372. CoderedSubmissionRevision.create_from_submission(submission, SubmissionRevision.DELETED) # noqa
  1373. class CoderedStep(Step):
  1374. def get_markups_and_bound_fields(self, form):
  1375. for struct_child in self.form_fields:
  1376. block = struct_child.block
  1377. if isinstance(block, FormFieldBlock):
  1378. struct_value = struct_child.value
  1379. field_name = block.get_slug(struct_value)
  1380. yield form[field_name], 'field', struct_child
  1381. else:
  1382. yield mark_safe(struct_child), 'markup'
  1383. class CoderedSteps(Steps):
  1384. def __init__(self, page, request=None):
  1385. self.page = page
  1386. # TODO: Make it possible to change the `form_fields` attribute.
  1387. self.form_fields = page.form_fields
  1388. self.request = request
  1389. has_steps = any(isinstance(struct_child.block, FormStepBlock)
  1390. for struct_child in self.form_fields)
  1391. if has_steps:
  1392. steps = [CoderedStep(self, i, form_field)
  1393. for i, form_field in enumerate(self.form_fields)]
  1394. else:
  1395. steps = [CoderedStep(self, 0, self.form_fields)]
  1396. super(Steps, self).__init__(steps)
  1397. class CoderedStreamFormMixin(StreamFormMixin):
  1398. class Meta:
  1399. abstract = True
  1400. def get_steps(self, request=None):
  1401. if not hasattr(self, 'steps'):
  1402. steps = CoderedSteps(self, request=request)
  1403. if request is None:
  1404. return steps
  1405. self.steps = steps
  1406. return self.steps
  1407. @staticmethod
  1408. def get_submission_class():
  1409. return FormSubmission
  1410. @staticmethod
  1411. def get_session_submission_class():
  1412. return CoderedSessionFormSubmission
  1413. def get_submission(self, request):
  1414. Submission = self.get_session_submission_class()
  1415. if request.user.is_authenticated:
  1416. user_submission = Submission.objects.filter(
  1417. user=request.user, page=self).order_by('-pk').first()
  1418. if user_submission is None:
  1419. return Submission(user=request.user, page=self, form_data='[]')
  1420. return user_submission
  1421. # Custom code to ensure that anonymous users get a session key.
  1422. if not request.session.session_key:
  1423. request.session.create()
  1424. user_submission = Submission.objects.filter(
  1425. session_key=request.session.session_key, page=self
  1426. ).order_by('-pk').first()
  1427. if user_submission is None:
  1428. return Submission(session_key=request.session.session_key,
  1429. page=self, form_data='[]')
  1430. return user_submission
  1431. class CoderedStreamFormPage(CoderedFormMixin, CoderedStreamFormMixin, CoderedWebPage):
  1432. class Meta:
  1433. verbose_name = _('CodeRed Advanced Form Page')
  1434. abstract = True
  1435. template = 'coderedcms/pages/stream_form_page.html'
  1436. landing_page_template = 'coderedcms/pages/form_page_landing.html'
  1437. form_fields = StreamField(STREAMFORM_BLOCKS)
  1438. encoder = StreamFormJSONEncoder
  1439. body_content_panels = [
  1440. StreamFieldPanel('form_fields')
  1441. ] + \
  1442. CoderedFormMixin.body_content_panels + [
  1443. InlinePanel('confirmation_emails', label=_('Confirmation Emails'))
  1444. ]
  1445. def process_form_post(self, form, request):
  1446. if form.is_valid():
  1447. is_complete = self.steps.update_data()
  1448. if is_complete:
  1449. submission = self.get_submission(request)
  1450. self.process_form_submission(
  1451. request=request,
  1452. form=form,
  1453. form_submission=submission,
  1454. processed_data=submission.get_data()
  1455. )
  1456. normal_submission = submission.create_normal_submission()
  1457. return self.render_landing_page(request, normal_submission)
  1458. return HttpResponseRedirect(self.url)
  1459. return self.process_form_get(form, request)
  1460. def process_form_get(self, form, request):
  1461. return CoderedWebPage.serve(self, request)
  1462. def get_form(self, request, *args, **kwargs):
  1463. return self.get_context(request)['form']
  1464. def get_storage(self):
  1465. return FileSystemStorage(
  1466. location=cr_settings['PROTECTED_MEDIA_ROOT'],
  1467. base_url=cr_settings['PROTECTED_MEDIA_URL']
  1468. )
  1469. class CoderedLocationPage(CoderedWebPage):
  1470. """
  1471. Location, suitable for store locations or help centers.
  1472. """
  1473. class Meta:
  1474. verbose_name = _('CodeRed Location')
  1475. abstract = True
  1476. template = 'coderedcms/pages/location_page.html'
  1477. # Override body to provide simpler content
  1478. body = StreamField(CONTENT_STREAMBLOCKS, null=True, blank=True)
  1479. address = models.TextField(
  1480. blank=True,
  1481. verbose_name=_("Address")
  1482. )
  1483. latitude = models.FloatField(
  1484. blank=True,
  1485. null=True,
  1486. verbose_name=_("Latitude")
  1487. )
  1488. longitude = models.FloatField(
  1489. blank=True,
  1490. null=True,
  1491. verbose_name=_("Longitude")
  1492. )
  1493. auto_update_latlng = models.BooleanField(
  1494. default=True,
  1495. verbose_name=_("Auto Update Latitude and Longitude"),
  1496. help_text=_("If checked, automatically update the latitude and longitude when the address is updated.") # noqa
  1497. )
  1498. map_title = models.CharField(
  1499. blank=True,
  1500. max_length=255,
  1501. verbose_name=_("Map Title"),
  1502. help_text=_("If this is filled out, this is the title that will be used on the map.")
  1503. )
  1504. map_description = models.CharField(
  1505. blank=True,
  1506. max_length=255,
  1507. verbose_name=_("Map Description"),
  1508. help_text=_("If this is filled out, this is the description that will be used on the map.")
  1509. )
  1510. website = models.TextField(
  1511. blank=True,
  1512. verbose_name=_("Website")
  1513. )
  1514. phone_number = models.CharField(
  1515. blank=True,
  1516. max_length=255,
  1517. verbose_name=_("Phone Number")
  1518. )
  1519. content_panels = CoderedWebPage.content_panels + [
  1520. FieldPanel('address'),
  1521. FieldPanel('website'),
  1522. FieldPanel('phone_number'),
  1523. ]
  1524. layout_panels = CoderedWebPage.layout_panels + [
  1525. MultiFieldPanel(
  1526. [
  1527. FieldPanel('map_title'),
  1528. FieldPanel('map_description'),
  1529. ],
  1530. heading=_('Map Layout')
  1531. ),
  1532. ]
  1533. settings_panels = CoderedWebPage.settings_panels + [
  1534. MultiFieldPanel(
  1535. [
  1536. FieldPanel('auto_update_latlng'),
  1537. FieldPanel('latitude'),
  1538. FieldPanel('longitude'),
  1539. ],
  1540. heading=_("Location Settings")
  1541. ),
  1542. ]
  1543. @property
  1544. def geojson_name(self):
  1545. return self.map_title or self.title
  1546. @property
  1547. def geojson_description(self):
  1548. return self.map_description
  1549. @property
  1550. def render_pin_description(self):
  1551. return render_to_string(
  1552. 'coderedcms/includes/map_pin_description.html',
  1553. {
  1554. 'page': self
  1555. }
  1556. )
  1557. @property
  1558. def render_list_description(self):
  1559. return render_to_string(
  1560. 'coderedcms/includes/map_list_description.html',
  1561. {
  1562. 'page': self
  1563. }
  1564. )
  1565. def to_geojson(self):
  1566. return {
  1567. "type": "Feature",
  1568. "geometry": {
  1569. "type": "Point",
  1570. "coordinates": [self.longitude, self.latitude]
  1571. },
  1572. "properties": {
  1573. "list_description": self.render_list_description,
  1574. "pin_description": self.render_pin_description
  1575. }
  1576. }
  1577. def save(self, *args, **kwargs):
  1578. if self.auto_update_latlng and GoogleApiSettings.for_site(
  1579. Site.objects.get(is_default_site=True)
  1580. ).google_maps_api_key:
  1581. try:
  1582. g = geocoder.google(self.address, key=GoogleApiSettings.for_site(
  1583. Site.objects.get(is_default_site=True)
  1584. ).google_maps_api_key)
  1585. self.latitude = g.latlng[0]
  1586. self.longitude = g.latlng[1]
  1587. except TypeError:
  1588. # Raised if google denied the request
  1589. pass
  1590. return super(CoderedLocationPage, self).save(*args, **kwargs)
  1591. def get_context(self, request, *args, **kwargs):
  1592. context = super().get_context(request)
  1593. context['google_api_key'] = GoogleApiSettings.for_site(
  1594. Site.objects.get(is_default_site=True)
  1595. ).google_maps_api_key
  1596. return context
  1597. class CoderedLocationIndexPage(CoderedWebPage):
  1598. """
  1599. Shows a map view of the children CoderedLocationPage.
  1600. """
  1601. class Meta:
  1602. verbose_name = _('CodeRed Location Index Page')
  1603. abstract = True
  1604. template = 'coderedcms/pages/location_index_page.html'
  1605. index_show_subpages_default = True
  1606. center_latitude = models.FloatField(
  1607. null=True,
  1608. blank=True,
  1609. help_text=_('The default latitude you want the map set to.'),
  1610. default=0
  1611. )
  1612. center_longitude = models.FloatField(
  1613. null=True,
  1614. blank=True,
  1615. help_text=_('The default longitude you want the map set to.'),
  1616. default=0
  1617. )
  1618. zoom = models.IntegerField(
  1619. default=8,
  1620. validators=[
  1621. MaxValueValidator(20),
  1622. MinValueValidator(1),
  1623. ],
  1624. help_text=_("Requires API key to use zoom. 1: World, 5: Landmass/continent, 10: City, 15: Streets, 20: Buildings") # noqa
  1625. )
  1626. layout_panels = CoderedWebPage.layout_panels + [
  1627. MultiFieldPanel(
  1628. [
  1629. FieldPanel('center_latitude'),
  1630. FieldPanel('center_longitude'),
  1631. FieldPanel('zoom'),
  1632. ],
  1633. heading=_('Map Display')
  1634. ),
  1635. ]
  1636. def geojson_data(self, viewport=None):
  1637. """
  1638. function that will return all locations under this index as geoJSON compliant data.
  1639. It is filtered by a latitude/longitude viewport if given.
  1640. viewport is a string in the format of :
  1641. 'southwest.latitude,southwest.longitude|northeast.latitude,northeast.longitude'
  1642. An example viewport that covers Cleveland, OH would look like this:
  1643. '41.354912150983964,-81.95331736661791|41.663427748126935,-81.45206614591478'
  1644. """
  1645. qs = self.get_index_children().live()
  1646. if viewport:
  1647. southwest, northeast = viewport.split('|')
  1648. southwest = [float(x) for x in southwest.split(',')]
  1649. northeast = [float(x) for x in northeast.split(',')]
  1650. qs = qs.filter(
  1651. latitude__gte=southwest[0],
  1652. latitude__lte=northeast[0],
  1653. longitude__gte=southwest[1],
  1654. longitude__lte=northeast[1]
  1655. )
  1656. return {
  1657. "type": "FeatureCollection",
  1658. "features": [
  1659. location.to_geojson() for location in qs
  1660. ]
  1661. }
  1662. def serve(self, request, *args, **kwargs):
  1663. data_format = request.GET.get('data-format', None)
  1664. if data_format == 'geojson':
  1665. return self.serve_geojson(request, *args, **kwargs)
  1666. return super().serve(request, *args, **kwargs)
  1667. def serve_geojson(self, request, *args, **kwargs):
  1668. viewport = request.GET.get('viewport', None)
  1669. return JsonResponse(self.geojson_data(viewport=viewport))
  1670. def get_context(self, request, *args, **kwargs):
  1671. context = super().get_context(request)
  1672. context['google_api_key'] = GoogleApiSettings.for_site(
  1673. Site.objects.get(is_default_site=True)
  1674. ).google_maps_api_key
  1675. return context