page_models.py 67 KB

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