page_models.py 65 KB

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