forked from NCIOCPL/cdr-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdrcgi.py
More file actions
4290 lines (3576 loc) · 149 KB
/
cdrcgi.py
File metadata and controls
4290 lines (3576 loc) · 149 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Common routines for creating CDR web forms.
This module has the following sections:
Imports of modules on which this one depends
Tools for creating CGI forms and reports
FieldStorage
Replacement for deprecated cgi.FieldStorage class
Controller
Base class for top-level controller of CGI scripts
FormFieldFactory
Provides convenient class methods for creating HTML form fields
HTMLPage
Creates a CDR web page for forms and reports using a common
customizable layout; uses the USWDS framework
Reporter
Creates CDR reports which can be sent to the web browser or
to Excel
BasicWebPage
Framework for creating reports which need more space than can
be provided by the USWDS-based classes
Excel
Wrapper for building Excel workbooks using OpenPyXl
AdvancedSearch
Search forms for each of the CDR document types
"""
# Packages from the standard library.
from collections import OrderedDict, UserDict
from datetime import date, datetime
from email.utils import parseaddr as parse_email_address
from functools import cached_property
from json import load as load_json_file, loads as load_json_string
from os import environ
from pathlib import Path
from re import compile as re_compile, search as re_search, sub as re_sub
from string import hexdigits
from sys import argv as sys_argv, exit as sys_exit
from sys import stdin as sys_stdin, stdout as sys_stdout
from types import SimpleNamespace
from urllib import parse as urllib_parse
# Third-party libraries/packages.
from lxml import html as lxml_html
from lxml.html import builder as html_builder, HtmlElement
from multipart import MultipartError, MultipartParser, parse_options_header
from openpyxl import styles as excel_styles, Workbook as ExcelWorkbook
# Project modules.
from cdr import Board, getControlGroup, getDoctype, Logging, TMP, URDATE
from cdrapi import db
from cdrapi.docs import Doc
from cdrapi.settings import Tier
from cdrapi.users import Session
class FieldStorage:
"""Replacement for deprecated cgi.FieldStorage class."""
ENCODED = "application/x-www-form-urlencoded", "application/x-url-encoded"
def __init__(self, logger=None):
"""Parse the field values we get from the browser via the web server.
Optional keyword argument:
logger - pass this in to perform debug logging for the values
"""
# Get some values from the environment.
self.logger = logger
if logger:
logger.debug("Constructing FieldStorage object")
method = environ.get("REQUEST_METHOD", "GET").upper()
content_type = environ.get("CONTENT_TYPE", self.ENCODED[0])
content_type, options = parse_options_header(content_type)
charset = options.get("charset", "utf-8")
self.__fields = {}
query_string = environ.get("QUERY_STRING")
qs_opts = dict(encoding=charset, keep_blank_values=True)
# Capture values passed as parameters appended to the URL.
if query_string:
if logger:
logger.debug("query_string: %s", query_string)
for key, value in urllib_parse.parse_qsl(query_string, **qs_opts):
if logger:
logger.debug("adding %s from query_string", key)
self.__add(self.SimpleValue(key, value))
# Read values POSTed by the client.
if method not in ("GET", "HEAD"):
content_length = int(environ.get("CONTENT_LENGTH", "-1"))
if logger:
logger.debug("content_length: %s", content_length)
logger.debug("content_type: %s", content_type)
if content_type == "multipart/form-data":
boundary = options.get("boundary")
if logger:
logger.debug("boundary: %s", boundary)
if not boundary:
message = "No boundary for multipart/form-data"
raise MultipartError(message)
args = sys_stdin.buffer, boundary, content_length
kwargs = dict(charset=charset)
for part in MultipartParser(*args, **kwargs):
if logger:
logger.debug("adding %s from multipart", part.name)
self.__add(self.StreamedValue(part))
elif content_type in self.ENCODED and content_length > 0:
data = sys_stdin.buffer.read(content_length).decode(charset)
if logger:
logger.debug("parsing %s", data)
for key, value in urllib_parse.parse_qsl(data, **qs_opts):
self.__add(self.SimpleValue(key, value))
def __add(self, item):
if item.name not in self.__fields:
self.__fields[item.name] = []
self.__fields[item.name].append(item)
def getfirst(self, key, default=None):
"""Return the first value received."""
items = self.__fields.get(key, [])
return items[0].value if items else default
def getlist(self, key):
"""Return list of received values."""
return [item.value for item in self.__fields.get(key, [])]
def getvalue(self, key, default=None):
"""Return single value, list of values, or None."""
items = self.__fields.get(key, [])
if not items:
return default
if len(items) == 1:
return items[0].value
return [item.value for item in items]
def keys(self):
"""Dictionary-style keys() method."""
return self.__fields.keys()
def __bool__(self):
"""True if we found any fields else false."""
return bool(self.__fields)
def __contains__(self, key):
"""Dictionary-style __contains__() method."""
return key in self.__fields
def __getitem__(self, key):
"""Dictionary-style indexing, returning the value objects."""
if key not in self.__fields:
raise KeyError(key)
items = self.__fields[key]
return items[0] if len(items) == 1 else items
def __iter__(self):
return iter(self.keys())
def __len__(self):
"""Dictionary-style len(x) support."""
return len(self.keys())
def __str__(self):
"""Improve debugging/logging output."""
fields = []
for name, values in self.__fields.items():
if len(values) < 1:
fields.append(f"{name}=''")
elif len(values) == 1:
fields.append(f"{name}={values[0]!r}")
else:
fields.append(f"{name}={values!r}")
fields = ", ".join(fields)
return f"[{fields}]"
def __repr__(self) -> str:
"""Pass through the serialized string."""
return str(self)
class SimpleValue:
"""Basic name+value pairings."""
def __init__(self, name, value):
"""Store the name and value and create stubs for the rest."""
self.name = name
self.value = value
self.filename = self.file = None
def __str__(self):
"""Show the value for debugging/logging."""
return self.value
def __repr__(self) -> str:
"""Improve debugging/logging output."""
return repr(self.value)
class StreamedValue():
"""Items which might be a posted file or other streamed value."""
def __init__(self, part):
"""Store the object extracted by the Multipart parser."""
self.__part = part
def __str__(self):
"""Show the value for debugging/logging."""
return f"file {self.filename}"
def __repr__(self):
"""Show the value for debugging/logging."""
return f"file {self.filename}"
@cached_property
def name(self):
"""The string for the name of the value."""
return self.__part.name
@cached_property
def value(self):
"""String (or bytes if from a file) for the value."""
return self.__part.raw if self.filename else self.__part.value
@cached_property
def filename(self):
"""String for the name (not the whole path) for a posted file."""
return self.__part.filename
@cached_property
def file(self):
"""File handle from which the binary file content can be read."""
return self.__part.file
class Controller:
"""Base class for top-level controller for a CGI script.
Includes methods for displaying a form (typically for a report)
and for rendering the requested report.
This will gradually replace the older `Control` class, which
is built around the use of `Page` objects, which created
HTML pages using direct string manipulation instead of real
HTML parser objects.
Typically, a web script will create a derived class using this
class as its base. It is possible to override the constructor,
but this is not necessary. If you do, be sure to invoke the
base class constructor from the overriding implementation.
The `run()` method is the top-level processing starting point.
That method calls the `show_report()` method if the Submit
button was clicked, or `show_form()` if no button was clicked.
The derived class implements `populate_form()` to add the
fields it needs for its job, and overrides the `build_tables()`
method to provide the report's data.
"""
DATETIMELEN = len("YYYY-MM-DD HH:MM:SS")
TAMPERING = "CGI parameter tampering detected"
USERNAME = "UserName"
PASSWORD = "Password"
PORT = "Port"
SESSION = "Session"
REQUEST = "Request"
DOCID = "DocId"
BASE = "/cgi-bin/cdr"
TIER = Tier()
WEBSERVER = environ.get("SERVER_NAME") or TIER.hosts.get("APPC")
DAY_ONE = URDATE
PAGE_TITLE = "CDR Administration"
TITLE = PAGE_TITLE
SUBTITLE = None
SUBMIT = "Submit"
LOG_OUT = "Log Out"
FORMATS = "html", "excel"
LOGNAME = "reports"
LOGLEVEL = "INFO"
METHOD = "post"
AUDIENCES = "Health Professional", "Patient"
LANGUAGES = "English", "Spanish"
INCLUDE_ANY_LANGUAGE_CHECKBOX = INCLUDE_ANY_AUDIENCE_CHECKBOX = False
SUMMARY_SELECTION_METHODS = "id", "title", "board"
EMAIL_PATTERN = re_compile(r"[^@]+@[^@\.]+\.[^@]+$")
KEEP_COMPLETE_TITLES = False
SAME_WINDOW = "document.getElementById('primary-form').target = '_self';"
NONBREAKING_HYPHEN = "\u2011"
def __init__(self, **opts):
"""Set up a skeletal controller."""
self.__started = datetime.now()
self.__opts = opts
self.logger.info("started %s", self.subtitle or "controller")
# ----------------------------------------------------------------
# Top-level processing routines.
# ----------------------------------------------------------------
def run(self):
"""Override in derived class if there are custom actions."""
try:
return self.show_report() if self.request else self.show_form()
except Exception as e:
self.logger.exception("Controller.run() failure")
self.bail(e)
def show_form(self):
"""Populate an HTML page with a form and fields and send it."""
self.populate_form(self.form_page)
for label in self.buttons:
button = self.form_page.button(label)
if self.same_window and label in self.same_window:
button.set("onclick", self.SAME_WINDOW)
self.form_page.form.append(button)
for alert in self.alerts:
message = alert["message"]
del alert["message"]
self.form_page.add_alert(message, **alert)
self.form_page.send()
def show_report(self):
"""Override this method if you need to make some tweaks.
A typical case would be:
def show_report(self):
self.report.body.set("id", "activity-report")
self.report.send(self.format)
Another situation in which you would override this method
would be if you have a non-tabular report to be sent.
"""
if self.format == "html":
if self.use_basic_web_page:
report = BasicWebPage()
report.wrapper.append(report.B.H1(self.subtitle))
tables = self.build_tables() or []
if not isinstance(tables, (list, tuple)):
tables = [tables]
for table in tables:
report.wrapper.append(table.node)
report.wrapper.append(self.footer)
return report.send()
if self.report_css:
self.report.page.add_css(self.report_css)
elapsed = self.report.page.html.get_element_by_id("elapsed", None)
if elapsed is not None:
elapsed.text = str(self.elapsed)
for alert in self.alerts:
message = alert["message"]
del alert["message"]
self.report.page.add_alert(message, **alert)
if self.wide_css:
sibling = self.report.page.form.getparent()
for table in self.report.page.form.findall("table"):
sibling.addnext(table)
sibling = table
self.report.page.add_css(self.wide_css)
self.report.send(self.format)
def populate_form(self, page):
"""Stub, to be overridden by real controllers."""
def build_tables(self):
"""Stub, to be overridden by real controllers."""
return []
# ----------------------------------------------------------------
# General-purpose utility methods.
# ----------------------------------------------------------------
def load_group(self, group):
"""Fetch the active members of a named user group.
Pass:
group - name of group to fetch
Return:
dictionary-like object of user names indexed by user ID
"""
query = db.Query("usr u", "u.id", "u.fullname", "u.name")
query.join("grp_usr j", "j.usr = u.id")
query.join("grp g", "g.id = j.grp")
query.where("u.expired IS NULL")
query.where(query.Condition("g.name", group))
rows = query.execute(self.cursor).fetchall()
class Group:
def __init__(self, rows):
self.map = {}
for row in rows:
self.map[row.id] = row.fullname or row.name
items = self.map.items()
values = [(val[1].lower(), val[0], val[1]) for val in items]
self.items = [vals[1:] for vals in sorted(values)]
def __getvalue__(self, key):
return self.map.get(key)
return Group(rows)
def load_valid_values(self, table_name):
"""Factor out logic for collecting a valid values set.
This works because our tables for valid values have the
same structure.
Pass:
table_name - name of the database table for the values
Return:
a populated `Values` object
"""
query = self.Query(table_name, "value_id", "value_name")
rows = query.order("value_pos").execute(self.cursor).fetchall()
class Values:
def __init__(self, rows):
self.map = {}
self.values = []
for value_id, value_name in rows:
self.map[value_id] = value_name
self.values.append((value_id, value_name))
return Values(rows)
def log_elapsed(self):
"""Record how long this took."""
self.logger.info(f"elapsed: {self.elapsed.total_seconds():f}")
def make_url(self, script, **params):
"""Create a URL.
Pass:
script - string for base of url (can be relative or absolute)
params - dictionary of named parameters for the URL
Return:
value appropriate for the href attribute of a link
"""
if self.SESSION not in params:
params[self.SESSION] = self.session.name
params = urllib_parse.urlencode(params, doseq=True)
return f"{script}?{params}"
def redirect(self, where, session=None, **params):
"""Send the user to another page.
Pass:
where - base URL, up to but not including parameters
session - session string or object to override this session (opt)
params - dictionary of other named parameters
"""
session = session or self.session
self.navigate_to(where, session, **params)
# ----------------------------------------------------------------
# Routines specific to Summary reports.
# ----------------------------------------------------------------
def add_audience_fieldset(self, page):
"""Add radio buttons for PDQ audience.
Pass:
page - object on which we place the fields
"""
fieldset = page.fieldset("Audience")
fieldset.set("class", "by-board-block usa-fieldset")
fieldset.set("id", "audience-block")
default = self.default_audience
if self.INCLUDE_ANY_AUDIENCE_CHECKBOX:
checked = False if default else True
opts = dict(label="Any", value="", checked=checked)
fieldset.append(page.radio_button("audience", **opts))
elif not default:
default = self.AUDIENCES[0]
for value in self.AUDIENCES:
checked = True if value == default else False
opts = dict(value=value, checked=checked)
fieldset.append(page.radio_button("audience", **opts))
page.form.append(fieldset)
def add_board_fieldset(self, page):
"""Add checkboxes for the PDQ Editorial Boards.
Pass:
page - object on which we place the fields
"""
fieldset = page.fieldset("Board")
fieldset.set("class", "by-board-block usa-fieldset")
fieldset.set("id", "board-set")
boards = ["all"]
if hasattr(self, "board") and isinstance(self.board, (list, tuple)):
boards = self.board
checked = "all" in boards or not boards
opts = dict(label="All Boards", value="all", checked=checked)
opts["onclick"] = "check_board('all');"
fieldset.append(page.checkbox("board", **opts))
for value, label in self.get_boards().items():
opts = dict(value=value, label=label, classes="ind")
opts["onclick"] = f"check_board({value});"
if value in boards:
opts["checked"] = True
fieldset.append(page.checkbox("board", **opts))
page.form.append(fieldset)
def add_language_fieldset(self, page):
"""Add radio buttons for summary language.
Pass:
page - object on which we place the fields
"""
fieldset = page.fieldset("Language")
fieldset.set("class", "by-board-block usa-fieldset")
fieldset.set("id", "language-block")
current = self.language if hasattr(self, "language") else None
if self.INCLUDE_ANY_LANGUAGE_CHECKBOX:
checked = not current
opts = dict(label="Any", value="", checked=checked)
fieldset.append(page.radio_button("language", **opts))
elif not current:
current = self.LANGUAGES[0]
for value in self.LANGUAGES:
checked = value == current
opts = dict(value=value, checked=checked)
fieldset.append(page.radio_button("language", **opts))
page.form.append(fieldset)
def add_summary_selection_fields(self, page, **kwopts):
"""
Display the fields used to specify which summaries should be
selected for a report, using one of several methods:
* by summary document ID
* by summary title
* by summary board
There are two branches taken by this method. If the user has
elected to select a summary by summary title, and the summary
title fragment matches more than one summary, then a follow-up
page is presented on which the user selects one of the summaries
and re-submits the report request. Otherwise, the user is shown
options for choosing a selection method, which in turn displays
the fields appropriate to that method dynamically. We also add
JavaScript functions to handle the dynamic control of field display.
Pass:
page - Page object on which to show the fields
titles - an optional array of SummaryTitle objects
audience - if False, omit Audience buttons (default is True)
language - if False, omit Language buttons (default is True)
id-label - optional string for the CDR ID field (defaults
to "CDR ID" but can be overridden, for example,
to say "CDR ID(s)" if multiple IDs are accepted)
id-tip - optional string for the CDR ID field for popup
help (e.g., "separate multiple IDs by spaces")
Return:
nothing (the form object is populated as a side effect)
"""
# --------------------------------------------------------------
# Show the second stage in a cascading sequence of the form if we
# have invoked this method directly from build_tables(). Widen
# the form to accomodate the length of the title substrings
# we're showing.
# --------------------------------------------------------------
titles = kwopts.get("titles")
if titles:
page.form.append(page.hidden_field("selection_method", "id"))
fieldset = page.fieldset("Choose Summary")
page.add_css("fieldset { width: 600px; }")
for t in titles:
opts = dict(label=t.display, value=t.id, tooltip=t.tooltip)
fieldset.append(page.radio_button("cdr-id", **opts))
page.form.append(fieldset)
else:
# Fields for the original form.
fieldset = page.fieldset("Selection Method")
methods = "PDQ Board", "CDR ID", "Summary Title"
for method in methods:
value = method.split()[-1].lower()
checked = value == self.selection_method
opts = dict(label=f"By {method}", value=value, checked=checked)
opts["onclick"] = f"check_selection_method('{value}');"
fieldset.append(page.radio_button("selection_method", **opts))
page.form.append(fieldset)
self.add_board_fieldset(page)
if kwopts.get("audience", True):
self.add_audience_fieldset(page)
if kwopts.get("language", True):
self.add_language_fieldset(page)
fieldset = page.fieldset("Summary Document ID")
fieldset.set("class", "by-id-block usa-fieldset")
label = kwopts.get("id-label", "CDR ID")
opts = dict(label=label, tooltip=kwopts.get("id-tip"))
if hasattr(self, "cdr_id"):
if isinstance(self.cdr_id, (int, str)):
opts["value"] = self.cdr_id
fieldset.append(page.text_field("cdr-id", **opts))
page.form.append(fieldset)
fieldset = page.fieldset("Summary Title")
fieldset.set("class", "by-title-block usa-fieldset")
opts = dict(tooltip="Use wildcard (%) as appropriate.")
if hasattr(self, "fragment") and self.fragment:
opts["value"] = self.fragment
fieldset.append(page.text_field("title", **opts))
page.form.append(fieldset)
page.add_script(self.summary_selection_js)
def get_boards(self):
"""Construct a dictionary of PDQ board names indexed by CDR ID."""
boards = Board.get_boards().values()
OD = OrderedDict
return OD([(board.id, board.short_name) for board in boards])
# ----------------------------------------------------------------
# Static and class methods.
# ----------------------------------------------------------------
@staticmethod
def add_date_range_to_caption(caption, start, end):
"""Format caption with date range (we do this a lot).
Pass:
caption - base string for the start of the caption
start - optional beginning of the date range
end - optional finish of the date range
Return:
possibly altered string for the table caption
"""
if start:
if end:
return f"{caption} Between {start} and {end}"
return f"{caption} Since {start}"
elif end:
return f"{caption} Through {end}"
return caption
@classmethod
def bail(cls, message=TAMPERING, /, **opts):
"""Send an error page to the browser.
Optional positional argument:
message - string describing the problem
by default this is a vague intended to convey as little
information to a hacker as possible
Optional keyword arguments:
extra - sequence of extra lines to append
logfile - name of logfile to write to
"""
class ErrorPage(HTMLPage):
def __init__(self, message, extra):
HTMLPage.__init__(self, "CDR Error")
self.message = message
self.extra = extra
if extra and not isinstance(extra, (list, tuple)):
self.extra = [extra]
@cached_property
def main(self):
alert_body = self.B.DIV(
self.B.H3(
str(self.message),
self.B.CLASS("usa-alert__heading")
)
)
if self.extra:
if len(self.extra) == 1:
p = self.B.P(str(self.extra[0]))
p.set("class", "usa-alert__text")
alert_body.append(p)
else:
extra = self.B.UL()
for arg in self.extra:
extra.append(self.B.LI(str(arg)))
alert_body.append(extra)
alert_body.set("class", "usa-alert__body")
return self.B.E(
"main",
self.B.DIV(
self.B.E(
"section",
self.B.DIV(
alert_body,
self.B.CLASS("usa-alert usa-alert--error")
)
),
self.B.CLASS("grid-container")
),
self.B.CLASS("usa-section")
)
try:
page = ErrorPage(message, opts.get("extra"))
except Exception:
page = ErrorPage(cls.TAMPERING, {})
logfile = opts.get("logfile")
if logfile:
if logfile.lower().endswith(".log"):
logfile = logfile[:-4]
logger = Logging.get_logger(logfile)
logger.error("cdrcgi bailout: %s", message)
page.send()
@classmethod
def navigate_to(cls, where, session, **params):
"""Send the user to another page.
This is the non-instance version.
Pass:
where - base URL, up to but not including parameters (required)
session - session string or object (required)
params - dictionary of other named parameters
"""
where = where.split("?")[0]
params[__class__.SESSION] = session
params = urllib_parse.urlencode(params)
print(f"Location:https://{cls.WEBSERVER}{cls.BASE}/{where}?{params}\n")
sys_exit(0)
@staticmethod
def parse_date(iso_date):
"""Convert a date string to a `datetime.date` object.
Changed requirements: might not be an ISO date any more, because
for some strange reasone, the USWDS project uses a non-standard
format.
Pass:
iso_date - optional string for the date
Return:
None if the string is None or empty, otherwise a date object
"""
if iso_date is None or not iso_date.strip():
return None
if "/" in iso_date:
month, day, year = iso_date.strip().split("/")
else:
year, month, day = iso_date.strip().split("-")
return date(int(year), int(month), int(day))
@classmethod
def parse_email_address(cls, address):
"""Pull out an email address from a string.
Performs a very simple validation, may improve it later, but full
RFC requires an incredible thousand-character regular expression.
Pass:
address - string which might have a display portion
(e.g., "Joe Blow <joe@example.com>")
Return:
address portion of the string if validation passes
None if no valid address is found
"""
_, address = parse_email_address(address)
if address and cls.EMAIL_PATTERN.match(address):
if ".." not in address:
return address
return None
@staticmethod
def send_page(page, text_type="html", mime_type=None):
"""Send a string back to the web server using UTF-8 encoding.
Required position argument:
page - Unicode string for the page or DOM object
Optional keyword arguments:
text_type - typically "html" but sometimes "xml"
mime_type - for other types; for example, "application/json"
"""
if not isinstance(page, str):
opts = dict(HTMLPage.STRING_OPTS, encoding="unicode")
page = lxml_html.tostring(page, **opts)
mime_type = mime_type or f"text/{text_type}"
headers = "\n".join([
f"Content-type: {mime_type};charset=utf-8",
"X-Content-Type-Options: nosniff",
])
string = f"{headers}\n\n{page}"
sys_stdout.buffer.write(string.encode("utf-8"))
sys_exit(0)
@staticmethod
def toggle_display(function_name, show_value, class_name):
"""Create JavaScript function to show or hide elements.
Pass:
function_name - name of the JavaScript function to create
show_value - controlling element's value causing show
class_name - class of which the controlled blocks are members
Return:
source code for JavaScript function
"""
return f"""\
function {function_name}(value) {{
const display = value === "{show_value}" ? "block" : "none";
const elements = document.querySelectorAll(".{class_name}");
elements.forEach(element => element.style.display = display);
}}
"""
# ----------------------------------------------------------------
# Instance properties.
# ----------------------------------------------------------------
@cached_property
def alerts(self):
"""Override to add alerts which should be shown on the page."""
return []
@cached_property
def buttons(self):
"""Sequence of names for request buttons to be provided."""
buttons = self.__opts.get("buttons")
if buttons is None:
if self.SUBMIT:
return [self.SUBMIT]
return []
return buttons
@cached_property
def conn(self):
"""Database connection for this controller."""
return db.connect()
@cached_property
def cursor(self):
"""Database cursor for this controller."""
return self.conn.cursor()
@property
def default_audience(self):
"""Let a subclass override the default for the audience picklist."""
return None
@cached_property
def doc_titles(self):
"""Cached lookup of CDR document titles by ID.
By default, only the portion of the title column's value before
the first semicolon is used. If "Inactive;" is at the front of
the title string the second segment of the title is used instead
(if it exists) and " (inactive)" is appended. To preserve the
entire contents of the title column's values, set the class-level
property `KEEP_COMPLETE_TITLES` to `True` in the derived class.
"""
class DocTitles(UserDict):
def __init__(self, control):
self.__control = control
UserDict.__init__(self)
def __getitem__(self, key):
if key not in self.data:
query = self.__control.Query("document", "title")
query.where(query.Condition("id", key))
row = query.execute(self.__control.cursor).fetchone()
title = row.title.strip() if row else ""
if not self.__control.KEEP_COMPLETE_TITLES:
pieces = [p.strip() for p in row.title.split(";")]
title = pieces[0]
if title.lower() == "inactive" and len(pieces) > 1:
title = f"{pieces[1]} (inactive)"
self.data[key] = title or None
return self.data[key]
return DocTitles(self)
@property
def elapsed(self):
"""How long have we been running? Don't cache."""
return datetime.now() - self.started
@cached_property
def fields(self):
"""CGI fields for the web form."""
return FieldStorage()
@cached_property
def footer(self):
"""Override to alter or suppress the default report footer."""
user = self.session.User(self.session, id=self.session.user_id)
name = user.fullname or user.name
today = date.today()
generated = f"Report generated {today} by {name}"
elapsed = HTMLPage.B.SPAN(str(self.elapsed), id="elapsed")
args = generated, HTMLPage.B.BR(), "Elapsed: ", elapsed
footer = HTMLPage.B.P(*args)
footer.set("class", "report-footer")
return footer
@cached_property
def format(self):
"""Either "html" (the default) or "excel"."""
format = self.fields.getvalue("format")
if not format:
format = self.__opts.get("format") or self.FORMATS[0]
if format not in self.FORMATS:
self.bail("invalid report format")
return format
@cached_property
def form_page(self):
"""Create a form page."""
opts = {
"control": self,
"action": self.script,
"buttons": [HTMLPage.button(b) for b in self.buttons],
"subtitle": self.subtitle,
"session": self.session,
"method": self.method,
"suppress_sidenav": self.suppress_sidenav,
}
return self.HTMLPage(self.title, **opts)
@cached_property
def HTMLPage(self):
"""Allow overriding of page class."""
return HTMLPage
@cached_property
def logged_out(self):
"""True if the user has just logged out."""
return True if self.fields.getvalue("logged_out") else False
@cached_property
def logger(self):
"""Object for recording what we do."""
logger = self.__opts.get("logger")
if logger is not None:
return logger
opts = dict(level=self.loglevel)
return Logging.get_logger(self.LOGNAME, **opts)
@cached_property
def loglevel(self):
"""Override this to provide runtime control of logging."""
return self.LOGLEVEL
@cached_property
def method(self):
"""Allow override of form method."""
return self.fields.getvalue("method") or self.METHOD
@cached_property
def no_results(self):
"""Message to display if no result tables are returned."""
return "No report results found."
@cached_property
def Query(self):
"""Convenience reference to database query class object."""
return db.Query
@cached_property
def report(self):
"""Create the `Reporter` object for this job."""
tables = self.build_tables()
if self.format == "excel":
return Reporter(self.title, tables)